sqlite3.c 5.3 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676416774167841679416804168141682416834168441685416864168741688416894169041691416924169341694416954169641697416984169941700417014170241703417044170541706417074170841709417104171141712417134171441715417164171741718417194172041721417224172341724417254172641727417284172941730417314173241733417344173541736417374173841739417404174141742417434174441745417464174741748417494175041751417524175341754417554175641757417584175941760417614176241763417644176541766417674176841769417704177141772417734177441775417764177741778417794178041781417824178341784417854178641787417884178941790417914179241793417944179541796417974179841799418004180141802418034180441805418064180741808418094181041811418124181341814418154181641817418184181941820418214182241823418244182541826418274182841829418304183141832418334183441835418364183741838418394184041841418424184341844418454184641847418484184941850418514185241853418544185541856418574185841859418604186141862418634186441865418664186741868418694187041871418724187341874418754187641877418784187941880418814188241883418844188541886418874188841889418904189141892418934189441895418964189741898418994190041901419024190341904419054190641907419084190941910419114191241913419144191541916419174191841919419204192141922419234192441925419264192741928419294193041931419324193341934419354193641937419384193941940419414194241943419444194541946419474194841949419504195141952419534195441955419564195741958419594196041961419624196341964419654196641967419684196941970419714197241973419744197541976419774197841979419804198141982419834198441985419864198741988419894199041991419924199341994419954199641997419984199942000420014200242003420044200542006420074200842009420104201142012420134201442015420164201742018420194202042021420224202342024420254202642027420284202942030420314203242033420344203542036420374203842039420404204142042420434204442045420464204742048420494205042051420524205342054420554205642057420584205942060420614206242063420644206542066420674206842069420704207142072420734207442075420764207742078420794208042081420824208342084420854208642087420884208942090420914209242093420944209542096420974209842099421004210142102421034210442105421064210742108421094211042111421124211342114421154211642117421184211942120421214212242123421244212542126421274212842129421304213142132421334213442135421364213742138421394214042141421424214342144421454214642147421484214942150421514215242153421544215542156421574215842159421604216142162421634216442165421664216742168421694217042171421724217342174421754217642177421784217942180421814218242183421844218542186421874218842189421904219142192421934219442195421964219742198421994220042201422024220342204422054220642207422084220942210422114221242213422144221542216422174221842219422204222142222422234222442225422264222742228422294223042231422324223342234422354223642237422384223942240422414224242243422444224542246422474224842249422504225142252422534225442255422564225742258422594226042261422624226342264422654226642267422684226942270422714227242273422744227542276422774227842279422804228142282422834228442285422864228742288422894229042291422924229342294422954229642297422984229942300423014230242303423044230542306423074230842309423104231142312423134231442315423164231742318423194232042321423224232342324423254232642327423284232942330423314233242333423344233542336423374233842339423404234142342423434234442345423464234742348423494235042351423524235342354423554235642357423584235942360423614236242363423644236542366423674236842369423704237142372423734237442375423764237742378423794238042381423824238342384423854238642387423884238942390423914239242393423944239542396423974239842399424004240142402424034240442405424064240742408424094241042411424124241342414424154241642417424184241942420424214242242423424244242542426424274242842429424304243142432424334243442435424364243742438424394244042441424424244342444424454244642447424484244942450424514245242453424544245542456424574245842459424604246142462424634246442465424664246742468424694247042471424724247342474424754247642477424784247942480424814248242483424844248542486424874248842489424904249142492424934249442495424964249742498424994250042501425024250342504425054250642507425084250942510425114251242513425144251542516425174251842519425204252142522425234252442525425264252742528425294253042531425324253342534425354253642537425384253942540425414254242543425444254542546425474254842549425504255142552425534255442555425564255742558425594256042561425624256342564425654256642567425684256942570425714257242573425744257542576425774257842579425804258142582425834258442585425864258742588425894259042591425924259342594425954259642597425984259942600426014260242603426044260542606426074260842609426104261142612426134261442615426164261742618426194262042621426224262342624426254262642627426284262942630426314263242633426344263542636426374263842639426404264142642426434264442645426464264742648426494265042651426524265342654426554265642657426584265942660426614266242663426644266542666426674266842669426704267142672426734267442675426764267742678426794268042681426824268342684426854268642687426884268942690426914269242693426944269542696426974269842699427004270142702427034270442705427064270742708427094271042711427124271342714427154271642717427184271942720427214272242723427244272542726427274272842729427304273142732427334273442735427364273742738427394274042741427424274342744427454274642747427484274942750427514275242753427544275542756427574275842759427604276142762427634276442765427664276742768427694277042771427724277342774427754277642777427784277942780427814278242783427844278542786427874278842789427904279142792427934279442795427964279742798427994280042801428024280342804428054280642807428084280942810428114281242813428144281542816428174281842819428204282142822428234282442825428264282742828428294283042831428324283342834428354283642837428384283942840428414284242843428444284542846428474284842849428504285142852428534285442855428564285742858428594286042861428624286342864428654286642867428684286942870428714287242873428744287542876428774287842879428804288142882428834288442885428864288742888428894289042891428924289342894428954289642897428984289942900429014290242903429044290542906429074290842909429104291142912429134291442915429164291742918429194292042921429224292342924429254292642927429284292942930429314293242933429344293542936429374293842939429404294142942429434294442945429464294742948429494295042951429524295342954429554295642957429584295942960429614296242963429644296542966429674296842969429704297142972429734297442975429764297742978429794298042981429824298342984429854298642987429884298942990429914299242993429944299542996429974299842999430004300143002430034300443005430064300743008430094301043011430124301343014430154301643017430184301943020430214302243023430244302543026430274302843029430304303143032430334303443035430364303743038430394304043041430424304343044430454304643047430484304943050430514305243053430544305543056430574305843059430604306143062430634306443065430664306743068430694307043071430724307343074430754307643077430784307943080430814308243083430844308543086430874308843089430904309143092430934309443095430964309743098430994310043101431024310343104431054310643107431084310943110431114311243113431144311543116431174311843119431204312143122431234312443125431264312743128431294313043131431324313343134431354313643137431384313943140431414314243143431444314543146431474314843149431504315143152431534315443155431564315743158431594316043161431624316343164431654316643167431684316943170431714317243173431744317543176431774317843179431804318143182431834318443185431864318743188431894319043191431924319343194431954319643197431984319943200432014320243203432044320543206432074320843209432104321143212432134321443215432164321743218432194322043221432224322343224432254322643227432284322943230432314323243233432344323543236432374323843239432404324143242432434324443245432464324743248432494325043251432524325343254432554325643257432584325943260432614326243263432644326543266432674326843269432704327143272432734327443275432764327743278432794328043281432824328343284432854328643287432884328943290432914329243293432944329543296432974329843299433004330143302433034330443305433064330743308433094331043311433124331343314433154331643317433184331943320433214332243323433244332543326433274332843329433304333143332433334333443335433364333743338433394334043341433424334343344433454334643347433484334943350433514335243353433544335543356433574335843359433604336143362433634336443365433664336743368433694337043371433724337343374433754337643377433784337943380433814338243383433844338543386433874338843389433904339143392433934339443395433964339743398433994340043401434024340343404434054340643407434084340943410434114341243413434144341543416434174341843419434204342143422434234342443425434264342743428434294343043431434324343343434434354343643437434384343943440434414344243443434444344543446434474344843449434504345143452434534345443455434564345743458434594346043461434624346343464434654346643467434684346943470434714347243473434744347543476434774347843479434804348143482434834348443485434864348743488434894349043491434924349343494434954349643497434984349943500435014350243503435044350543506435074350843509435104351143512435134351443515435164351743518435194352043521435224352343524435254352643527435284352943530435314353243533435344353543536435374353843539435404354143542435434354443545435464354743548435494355043551435524355343554435554355643557435584355943560435614356243563435644356543566435674356843569435704357143572435734357443575435764357743578435794358043581435824358343584435854358643587435884358943590435914359243593435944359543596435974359843599436004360143602436034360443605436064360743608436094361043611436124361343614436154361643617436184361943620436214362243623436244362543626436274362843629436304363143632436334363443635436364363743638436394364043641436424364343644436454364643647436484364943650436514365243653436544365543656436574365843659436604366143662436634366443665436664366743668436694367043671436724367343674436754367643677436784367943680436814368243683436844368543686436874368843689436904369143692436934369443695436964369743698436994370043701437024370343704437054370643707437084370943710437114371243713437144371543716437174371843719437204372143722437234372443725437264372743728437294373043731437324373343734437354373643737437384373943740437414374243743437444374543746437474374843749437504375143752437534375443755437564375743758437594376043761437624376343764437654376643767437684376943770437714377243773437744377543776437774377843779437804378143782437834378443785437864378743788437894379043791437924379343794437954379643797437984379943800438014380243803438044380543806438074380843809438104381143812438134381443815438164381743818438194382043821438224382343824438254382643827438284382943830438314383243833438344383543836438374383843839438404384143842438434384443845438464384743848438494385043851438524385343854438554385643857438584385943860438614386243863438644386543866438674386843869438704387143872438734387443875438764387743878438794388043881438824388343884438854388643887438884388943890438914389243893438944389543896438974389843899439004390143902439034390443905439064390743908439094391043911439124391343914439154391643917439184391943920439214392243923439244392543926439274392843929439304393143932439334393443935439364393743938439394394043941439424394343944439454394643947439484394943950439514395243953439544395543956439574395843959439604396143962439634396443965439664396743968439694397043971439724397343974439754397643977439784397943980439814398243983439844398543986439874398843989439904399143992439934399443995439964399743998439994400044001440024400344004440054400644007440084400944010440114401244013440144401544016440174401844019440204402144022440234402444025440264402744028440294403044031440324403344034440354403644037440384403944040440414404244043440444404544046440474404844049440504405144052440534405444055440564405744058440594406044061440624406344064440654406644067440684406944070440714407244073440744407544076440774407844079440804408144082440834408444085440864408744088440894409044091440924409344094440954409644097440984409944100441014410244103441044410544106441074410844109441104411144112441134411444115441164411744118441194412044121441224412344124441254412644127441284412944130441314413244133441344413544136441374413844139441404414144142441434414444145441464414744148441494415044151441524415344154441554415644157441584415944160441614416244163441644416544166441674416844169441704417144172441734417444175441764417744178441794418044181441824418344184441854418644187441884418944190441914419244193441944419544196441974419844199442004420144202442034420444205442064420744208442094421044211442124421344214442154421644217442184421944220442214422244223442244422544226442274422844229442304423144232442334423444235442364423744238442394424044241442424424344244442454424644247442484424944250442514425244253442544425544256442574425844259442604426144262442634426444265442664426744268442694427044271442724427344274442754427644277442784427944280442814428244283442844428544286442874428844289442904429144292442934429444295442964429744298442994430044301443024430344304443054430644307443084430944310443114431244313443144431544316443174431844319443204432144322443234432444325443264432744328443294433044331443324433344334443354433644337443384433944340443414434244343443444434544346443474434844349443504435144352443534435444355443564435744358443594436044361443624436344364443654436644367443684436944370443714437244373443744437544376443774437844379443804438144382443834438444385443864438744388443894439044391443924439344394443954439644397443984439944400444014440244403444044440544406444074440844409444104441144412444134441444415444164441744418444194442044421444224442344424444254442644427444284442944430444314443244433444344443544436444374443844439444404444144442444434444444445444464444744448444494445044451444524445344454444554445644457444584445944460444614446244463444644446544466444674446844469444704447144472444734447444475444764447744478444794448044481444824448344484444854448644487444884448944490444914449244493444944449544496444974449844499445004450144502445034450444505445064450744508445094451044511445124451344514445154451644517445184451944520445214452244523445244452544526445274452844529445304453144532445334453444535445364453744538445394454044541445424454344544445454454644547445484454944550445514455244553445544455544556445574455844559445604456144562445634456444565445664456744568445694457044571445724457344574445754457644577445784457944580445814458244583445844458544586445874458844589445904459144592445934459444595445964459744598445994460044601446024460344604446054460644607446084460944610446114461244613446144461544616446174461844619446204462144622446234462444625446264462744628446294463044631446324463344634446354463644637446384463944640446414464244643446444464544646446474464844649446504465144652446534465444655446564465744658446594466044661446624466344664446654466644667446684466944670446714467244673446744467544676446774467844679446804468144682446834468444685446864468744688446894469044691446924469344694446954469644697446984469944700447014470244703447044470544706447074470844709447104471144712447134471444715447164471744718447194472044721447224472344724447254472644727447284472944730447314473244733447344473544736447374473844739447404474144742447434474444745447464474744748447494475044751447524475344754447554475644757447584475944760447614476244763447644476544766447674476844769447704477144772447734477444775447764477744778447794478044781447824478344784447854478644787447884478944790447914479244793447944479544796447974479844799448004480144802448034480444805448064480744808448094481044811448124481344814448154481644817448184481944820448214482244823448244482544826448274482844829448304483144832448334483444835448364483744838448394484044841448424484344844448454484644847448484484944850448514485244853448544485544856448574485844859448604486144862448634486444865448664486744868448694487044871448724487344874448754487644877448784487944880448814488244883448844488544886448874488844889448904489144892448934489444895448964489744898448994490044901449024490344904449054490644907449084490944910449114491244913449144491544916449174491844919449204492144922449234492444925449264492744928449294493044931449324493344934449354493644937449384493944940449414494244943449444494544946449474494844949449504495144952449534495444955449564495744958449594496044961449624496344964449654496644967449684496944970449714497244973449744497544976449774497844979449804498144982449834498444985449864498744988449894499044991449924499344994449954499644997449984499945000450014500245003450044500545006450074500845009450104501145012450134501445015450164501745018450194502045021450224502345024450254502645027450284502945030450314503245033450344503545036450374503845039450404504145042450434504445045450464504745048450494505045051450524505345054450554505645057450584505945060450614506245063450644506545066450674506845069450704507145072450734507445075450764507745078450794508045081450824508345084450854508645087450884508945090450914509245093450944509545096450974509845099451004510145102451034510445105451064510745108451094511045111451124511345114451154511645117451184511945120451214512245123451244512545126451274512845129451304513145132451334513445135451364513745138451394514045141451424514345144451454514645147451484514945150451514515245153451544515545156451574515845159451604516145162451634516445165451664516745168451694517045171451724517345174451754517645177451784517945180451814518245183451844518545186451874518845189451904519145192451934519445195451964519745198451994520045201452024520345204452054520645207452084520945210452114521245213452144521545216452174521845219452204522145222452234522445225452264522745228452294523045231452324523345234452354523645237452384523945240452414524245243452444524545246452474524845249452504525145252452534525445255452564525745258452594526045261452624526345264452654526645267452684526945270452714527245273452744527545276452774527845279452804528145282452834528445285452864528745288452894529045291452924529345294452954529645297452984529945300453014530245303453044530545306453074530845309453104531145312453134531445315453164531745318453194532045321453224532345324453254532645327453284532945330453314533245333453344533545336453374533845339453404534145342453434534445345453464534745348453494535045351453524535345354453554535645357453584535945360453614536245363453644536545366453674536845369453704537145372453734537445375453764537745378453794538045381453824538345384453854538645387453884538945390453914539245393453944539545396453974539845399454004540145402454034540445405454064540745408454094541045411454124541345414454154541645417454184541945420454214542245423454244542545426454274542845429454304543145432454334543445435454364543745438454394544045441454424544345444454454544645447454484544945450454514545245453454544545545456454574545845459454604546145462454634546445465454664546745468454694547045471454724547345474454754547645477454784547945480454814548245483454844548545486454874548845489454904549145492454934549445495454964549745498454994550045501455024550345504455054550645507455084550945510455114551245513455144551545516455174551845519455204552145522455234552445525455264552745528455294553045531455324553345534455354553645537455384553945540455414554245543455444554545546455474554845549455504555145552455534555445555455564555745558455594556045561455624556345564455654556645567455684556945570455714557245573455744557545576455774557845579455804558145582455834558445585455864558745588455894559045591455924559345594455954559645597455984559945600456014560245603456044560545606456074560845609456104561145612456134561445615456164561745618456194562045621456224562345624456254562645627456284562945630456314563245633456344563545636456374563845639456404564145642456434564445645456464564745648456494565045651456524565345654456554565645657456584565945660456614566245663456644566545666456674566845669456704567145672456734567445675456764567745678456794568045681456824568345684456854568645687456884568945690456914569245693456944569545696456974569845699457004570145702457034570445705457064570745708457094571045711457124571345714457154571645717457184571945720457214572245723457244572545726457274572845729457304573145732457334573445735457364573745738457394574045741457424574345744457454574645747457484574945750457514575245753457544575545756457574575845759457604576145762457634576445765457664576745768457694577045771457724577345774457754577645777457784577945780457814578245783457844578545786457874578845789457904579145792457934579445795457964579745798457994580045801458024580345804458054580645807458084580945810458114581245813458144581545816458174581845819458204582145822458234582445825458264582745828458294583045831458324583345834458354583645837458384583945840458414584245843458444584545846458474584845849458504585145852458534585445855458564585745858458594586045861458624586345864458654586645867458684586945870458714587245873458744587545876458774587845879458804588145882458834588445885458864588745888458894589045891458924589345894458954589645897458984589945900459014590245903459044590545906459074590845909459104591145912459134591445915459164591745918459194592045921459224592345924459254592645927459284592945930459314593245933459344593545936459374593845939459404594145942459434594445945459464594745948459494595045951459524595345954459554595645957459584595945960459614596245963459644596545966459674596845969459704597145972459734597445975459764597745978459794598045981459824598345984459854598645987459884598945990459914599245993459944599545996459974599845999460004600146002460034600446005460064600746008460094601046011460124601346014460154601646017460184601946020460214602246023460244602546026460274602846029460304603146032460334603446035460364603746038460394604046041460424604346044460454604646047460484604946050460514605246053460544605546056460574605846059460604606146062460634606446065460664606746068460694607046071460724607346074460754607646077460784607946080460814608246083460844608546086460874608846089460904609146092460934609446095460964609746098460994610046101461024610346104461054610646107461084610946110461114611246113461144611546116461174611846119461204612146122461234612446125461264612746128461294613046131461324613346134461354613646137461384613946140461414614246143461444614546146461474614846149461504615146152461534615446155461564615746158461594616046161461624616346164461654616646167461684616946170461714617246173461744617546176461774617846179461804618146182461834618446185461864618746188461894619046191461924619346194461954619646197461984619946200462014620246203462044620546206462074620846209462104621146212462134621446215462164621746218462194622046221462224622346224462254622646227462284622946230462314623246233462344623546236462374623846239462404624146242462434624446245462464624746248462494625046251462524625346254462554625646257462584625946260462614626246263462644626546266462674626846269462704627146272462734627446275462764627746278462794628046281462824628346284462854628646287462884628946290462914629246293462944629546296462974629846299463004630146302463034630446305463064630746308463094631046311463124631346314463154631646317463184631946320463214632246323463244632546326463274632846329463304633146332463334633446335463364633746338463394634046341463424634346344463454634646347463484634946350463514635246353463544635546356463574635846359463604636146362463634636446365463664636746368463694637046371463724637346374463754637646377463784637946380463814638246383463844638546386463874638846389463904639146392463934639446395463964639746398463994640046401464024640346404464054640646407464084640946410464114641246413464144641546416464174641846419464204642146422464234642446425464264642746428464294643046431464324643346434464354643646437464384643946440464414644246443464444644546446464474644846449464504645146452464534645446455464564645746458464594646046461464624646346464464654646646467464684646946470464714647246473464744647546476464774647846479464804648146482464834648446485464864648746488464894649046491464924649346494464954649646497464984649946500465014650246503465044650546506465074650846509465104651146512465134651446515465164651746518465194652046521465224652346524465254652646527465284652946530465314653246533465344653546536465374653846539465404654146542465434654446545465464654746548465494655046551465524655346554465554655646557465584655946560465614656246563465644656546566465674656846569465704657146572465734657446575465764657746578465794658046581465824658346584465854658646587465884658946590465914659246593465944659546596465974659846599466004660146602466034660446605466064660746608466094661046611466124661346614466154661646617466184661946620466214662246623466244662546626466274662846629466304663146632466334663446635466364663746638466394664046641466424664346644466454664646647466484664946650466514665246653466544665546656466574665846659466604666146662466634666446665466664666746668466694667046671466724667346674466754667646677466784667946680466814668246683466844668546686466874668846689466904669146692466934669446695466964669746698466994670046701467024670346704467054670646707467084670946710467114671246713467144671546716467174671846719467204672146722467234672446725467264672746728467294673046731467324673346734467354673646737467384673946740467414674246743467444674546746467474674846749467504675146752467534675446755467564675746758467594676046761467624676346764467654676646767467684676946770467714677246773467744677546776467774677846779467804678146782467834678446785467864678746788467894679046791467924679346794467954679646797467984679946800468014680246803468044680546806468074680846809468104681146812468134681446815468164681746818468194682046821468224682346824468254682646827468284682946830468314683246833468344683546836468374683846839468404684146842468434684446845468464684746848468494685046851468524685346854468554685646857468584685946860468614686246863468644686546866468674686846869468704687146872468734687446875468764687746878468794688046881468824688346884468854688646887468884688946890468914689246893468944689546896468974689846899469004690146902469034690446905469064690746908469094691046911469124691346914469154691646917469184691946920469214692246923469244692546926469274692846929469304693146932469334693446935469364693746938469394694046941469424694346944469454694646947469484694946950469514695246953469544695546956469574695846959469604696146962469634696446965469664696746968469694697046971469724697346974469754697646977469784697946980469814698246983469844698546986469874698846989469904699146992469934699446995469964699746998469994700047001470024700347004470054700647007470084700947010470114701247013470144701547016470174701847019470204702147022470234702447025470264702747028470294703047031470324703347034470354703647037470384703947040470414704247043470444704547046470474704847049470504705147052470534705447055470564705747058470594706047061470624706347064470654706647067470684706947070470714707247073470744707547076470774707847079470804708147082470834708447085470864708747088470894709047091470924709347094470954709647097470984709947100471014710247103471044710547106471074710847109471104711147112471134711447115471164711747118471194712047121471224712347124471254712647127471284712947130471314713247133471344713547136471374713847139471404714147142471434714447145471464714747148471494715047151471524715347154471554715647157471584715947160471614716247163471644716547166471674716847169471704717147172471734717447175471764717747178471794718047181471824718347184471854718647187471884718947190471914719247193471944719547196471974719847199472004720147202472034720447205472064720747208472094721047211472124721347214472154721647217472184721947220472214722247223472244722547226472274722847229472304723147232472334723447235472364723747238472394724047241472424724347244472454724647247472484724947250472514725247253472544725547256472574725847259472604726147262472634726447265472664726747268472694727047271472724727347274472754727647277472784727947280472814728247283472844728547286472874728847289472904729147292472934729447295472964729747298472994730047301473024730347304473054730647307473084730947310473114731247313473144731547316473174731847319473204732147322473234732447325473264732747328473294733047331473324733347334473354733647337473384733947340473414734247343473444734547346473474734847349473504735147352473534735447355473564735747358473594736047361473624736347364473654736647367473684736947370473714737247373473744737547376473774737847379473804738147382473834738447385473864738747388473894739047391473924739347394473954739647397473984739947400474014740247403474044740547406474074740847409474104741147412474134741447415474164741747418474194742047421474224742347424474254742647427474284742947430474314743247433474344743547436474374743847439474404744147442474434744447445474464744747448474494745047451474524745347454474554745647457474584745947460474614746247463474644746547466474674746847469474704747147472474734747447475474764747747478474794748047481474824748347484474854748647487474884748947490474914749247493474944749547496474974749847499475004750147502475034750447505475064750747508475094751047511475124751347514475154751647517475184751947520475214752247523475244752547526475274752847529475304753147532475334753447535475364753747538475394754047541475424754347544475454754647547475484754947550475514755247553475544755547556475574755847559475604756147562475634756447565475664756747568475694757047571475724757347574475754757647577475784757947580475814758247583475844758547586475874758847589475904759147592475934759447595475964759747598475994760047601476024760347604476054760647607476084760947610476114761247613476144761547616476174761847619476204762147622476234762447625476264762747628476294763047631476324763347634476354763647637476384763947640476414764247643476444764547646476474764847649476504765147652476534765447655476564765747658476594766047661476624766347664476654766647667476684766947670476714767247673476744767547676476774767847679476804768147682476834768447685476864768747688476894769047691476924769347694476954769647697476984769947700477014770247703477044770547706477074770847709477104771147712477134771447715477164771747718477194772047721477224772347724477254772647727477284772947730477314773247733477344773547736477374773847739477404774147742477434774447745477464774747748477494775047751477524775347754477554775647757477584775947760477614776247763477644776547766477674776847769477704777147772477734777447775477764777747778477794778047781477824778347784477854778647787477884778947790477914779247793477944779547796477974779847799478004780147802478034780447805478064780747808478094781047811478124781347814478154781647817478184781947820478214782247823478244782547826478274782847829478304783147832478334783447835478364783747838478394784047841478424784347844478454784647847478484784947850478514785247853478544785547856478574785847859478604786147862478634786447865478664786747868478694787047871478724787347874478754787647877478784787947880478814788247883478844788547886478874788847889478904789147892478934789447895478964789747898478994790047901479024790347904479054790647907479084790947910479114791247913479144791547916479174791847919479204792147922479234792447925479264792747928479294793047931479324793347934479354793647937479384793947940479414794247943479444794547946479474794847949479504795147952479534795447955479564795747958479594796047961479624796347964479654796647967479684796947970479714797247973479744797547976479774797847979479804798147982479834798447985479864798747988479894799047991479924799347994479954799647997479984799948000480014800248003480044800548006480074800848009480104801148012480134801448015480164801748018480194802048021480224802348024480254802648027480284802948030480314803248033480344803548036480374803848039480404804148042480434804448045480464804748048480494805048051480524805348054480554805648057480584805948060480614806248063480644806548066480674806848069480704807148072480734807448075480764807748078480794808048081480824808348084480854808648087480884808948090480914809248093480944809548096480974809848099481004810148102481034810448105481064810748108481094811048111481124811348114481154811648117481184811948120481214812248123481244812548126481274812848129481304813148132481334813448135481364813748138481394814048141481424814348144481454814648147481484814948150481514815248153481544815548156481574815848159481604816148162481634816448165481664816748168481694817048171481724817348174481754817648177481784817948180481814818248183481844818548186481874818848189481904819148192481934819448195481964819748198481994820048201482024820348204482054820648207482084820948210482114821248213482144821548216482174821848219482204822148222482234822448225482264822748228482294823048231482324823348234482354823648237482384823948240482414824248243482444824548246482474824848249482504825148252482534825448255482564825748258482594826048261482624826348264482654826648267482684826948270482714827248273482744827548276482774827848279482804828148282482834828448285482864828748288482894829048291482924829348294482954829648297482984829948300483014830248303483044830548306483074830848309483104831148312483134831448315483164831748318483194832048321483224832348324483254832648327483284832948330483314833248333483344833548336483374833848339483404834148342483434834448345483464834748348483494835048351483524835348354483554835648357483584835948360483614836248363483644836548366483674836848369483704837148372483734837448375483764837748378483794838048381483824838348384483854838648387483884838948390483914839248393483944839548396483974839848399484004840148402484034840448405484064840748408484094841048411484124841348414484154841648417484184841948420484214842248423484244842548426484274842848429484304843148432484334843448435484364843748438484394844048441484424844348444484454844648447484484844948450484514845248453484544845548456484574845848459484604846148462484634846448465484664846748468484694847048471484724847348474484754847648477484784847948480484814848248483484844848548486484874848848489484904849148492484934849448495484964849748498484994850048501485024850348504485054850648507485084850948510485114851248513485144851548516485174851848519485204852148522485234852448525485264852748528485294853048531485324853348534485354853648537485384853948540485414854248543485444854548546485474854848549485504855148552485534855448555485564855748558485594856048561485624856348564485654856648567485684856948570485714857248573485744857548576485774857848579485804858148582485834858448585485864858748588485894859048591485924859348594485954859648597485984859948600486014860248603486044860548606486074860848609486104861148612486134861448615486164861748618486194862048621486224862348624486254862648627486284862948630486314863248633486344863548636486374863848639486404864148642486434864448645486464864748648486494865048651486524865348654486554865648657486584865948660486614866248663486644866548666486674866848669486704867148672486734867448675486764867748678486794868048681486824868348684486854868648687486884868948690486914869248693486944869548696486974869848699487004870148702487034870448705487064870748708487094871048711487124871348714487154871648717487184871948720487214872248723487244872548726487274872848729487304873148732487334873448735487364873748738487394874048741487424874348744487454874648747487484874948750487514875248753487544875548756487574875848759487604876148762487634876448765487664876748768487694877048771487724877348774487754877648777487784877948780487814878248783487844878548786487874878848789487904879148792487934879448795487964879748798487994880048801488024880348804488054880648807488084880948810488114881248813488144881548816488174881848819488204882148822488234882448825488264882748828488294883048831488324883348834488354883648837488384883948840488414884248843488444884548846488474884848849488504885148852488534885448855488564885748858488594886048861488624886348864488654886648867488684886948870488714887248873488744887548876488774887848879488804888148882488834888448885488864888748888488894889048891488924889348894488954889648897488984889948900489014890248903489044890548906489074890848909489104891148912489134891448915489164891748918489194892048921489224892348924489254892648927489284892948930489314893248933489344893548936489374893848939489404894148942489434894448945489464894748948489494895048951489524895348954489554895648957489584895948960489614896248963489644896548966489674896848969489704897148972489734897448975489764897748978489794898048981489824898348984489854898648987489884898948990489914899248993489944899548996489974899848999490004900149002490034900449005490064900749008490094901049011490124901349014490154901649017490184901949020490214902249023490244902549026490274902849029490304903149032490334903449035490364903749038490394904049041490424904349044490454904649047490484904949050490514905249053490544905549056490574905849059490604906149062490634906449065490664906749068490694907049071490724907349074490754907649077490784907949080490814908249083490844908549086490874908849089490904909149092490934909449095490964909749098490994910049101491024910349104491054910649107491084910949110491114911249113491144911549116491174911849119491204912149122491234912449125491264912749128491294913049131491324913349134491354913649137491384913949140491414914249143491444914549146491474914849149491504915149152491534915449155491564915749158491594916049161491624916349164491654916649167491684916949170491714917249173491744917549176491774917849179491804918149182491834918449185491864918749188491894919049191491924919349194491954919649197491984919949200492014920249203492044920549206492074920849209492104921149212492134921449215492164921749218492194922049221492224922349224492254922649227492284922949230492314923249233492344923549236492374923849239492404924149242492434924449245492464924749248492494925049251492524925349254492554925649257492584925949260492614926249263492644926549266492674926849269492704927149272492734927449275492764927749278492794928049281492824928349284492854928649287492884928949290492914929249293492944929549296492974929849299493004930149302493034930449305493064930749308493094931049311493124931349314493154931649317493184931949320493214932249323493244932549326493274932849329493304933149332493334933449335493364933749338493394934049341493424934349344493454934649347493484934949350493514935249353493544935549356493574935849359493604936149362493634936449365493664936749368493694937049371493724937349374493754937649377493784937949380493814938249383493844938549386493874938849389493904939149392493934939449395493964939749398493994940049401494024940349404494054940649407494084940949410494114941249413494144941549416494174941849419494204942149422494234942449425494264942749428494294943049431494324943349434494354943649437494384943949440494414944249443494444944549446494474944849449494504945149452494534945449455494564945749458494594946049461494624946349464494654946649467494684946949470494714947249473494744947549476494774947849479494804948149482494834948449485494864948749488494894949049491494924949349494494954949649497494984949949500495014950249503495044950549506495074950849509495104951149512495134951449515495164951749518495194952049521495224952349524495254952649527495284952949530495314953249533495344953549536495374953849539495404954149542495434954449545495464954749548495494955049551495524955349554495554955649557495584955949560495614956249563495644956549566495674956849569495704957149572495734957449575495764957749578495794958049581495824958349584495854958649587495884958949590495914959249593495944959549596495974959849599496004960149602496034960449605496064960749608496094961049611496124961349614496154961649617496184961949620496214962249623496244962549626496274962849629496304963149632496334963449635496364963749638496394964049641496424964349644496454964649647496484964949650496514965249653496544965549656496574965849659496604966149662496634966449665496664966749668496694967049671496724967349674496754967649677496784967949680496814968249683496844968549686496874968849689496904969149692496934969449695496964969749698496994970049701497024970349704497054970649707497084970949710497114971249713497144971549716497174971849719497204972149722497234972449725497264972749728497294973049731497324973349734497354973649737497384973949740497414974249743497444974549746497474974849749497504975149752497534975449755497564975749758497594976049761497624976349764497654976649767497684976949770497714977249773497744977549776497774977849779497804978149782497834978449785497864978749788497894979049791497924979349794497954979649797497984979949800498014980249803498044980549806498074980849809498104981149812498134981449815498164981749818498194982049821498224982349824498254982649827498284982949830498314983249833498344983549836498374983849839498404984149842498434984449845498464984749848498494985049851498524985349854498554985649857498584985949860498614986249863498644986549866498674986849869498704987149872498734987449875498764987749878498794988049881498824988349884498854988649887498884988949890498914989249893498944989549896498974989849899499004990149902499034990449905499064990749908499094991049911499124991349914499154991649917499184991949920499214992249923499244992549926499274992849929499304993149932499334993449935499364993749938499394994049941499424994349944499454994649947499484994949950499514995249953499544995549956499574995849959499604996149962499634996449965499664996749968499694997049971499724997349974499754997649977499784997949980499814998249983499844998549986499874998849989499904999149992499934999449995499964999749998499995000050001500025000350004500055000650007500085000950010500115001250013500145001550016500175001850019500205002150022500235002450025500265002750028500295003050031500325003350034500355003650037500385003950040500415004250043500445004550046500475004850049500505005150052500535005450055500565005750058500595006050061500625006350064500655006650067500685006950070500715007250073500745007550076500775007850079500805008150082500835008450085500865008750088500895009050091500925009350094500955009650097500985009950100501015010250103501045010550106501075010850109501105011150112501135011450115501165011750118501195012050121501225012350124501255012650127501285012950130501315013250133501345013550136501375013850139501405014150142501435014450145501465014750148501495015050151501525015350154501555015650157501585015950160501615016250163501645016550166501675016850169501705017150172501735017450175501765017750178501795018050181501825018350184501855018650187501885018950190501915019250193501945019550196501975019850199502005020150202502035020450205502065020750208502095021050211502125021350214502155021650217502185021950220502215022250223502245022550226502275022850229502305023150232502335023450235502365023750238502395024050241502425024350244502455024650247502485024950250502515025250253502545025550256502575025850259502605026150262502635026450265502665026750268502695027050271502725027350274502755027650277502785027950280502815028250283502845028550286502875028850289502905029150292502935029450295502965029750298502995030050301503025030350304503055030650307503085030950310503115031250313503145031550316503175031850319503205032150322503235032450325503265032750328503295033050331503325033350334503355033650337503385033950340503415034250343503445034550346503475034850349503505035150352503535035450355503565035750358503595036050361503625036350364503655036650367503685036950370503715037250373503745037550376503775037850379503805038150382503835038450385503865038750388503895039050391503925039350394503955039650397503985039950400504015040250403504045040550406504075040850409504105041150412504135041450415504165041750418504195042050421504225042350424504255042650427504285042950430504315043250433504345043550436504375043850439504405044150442504435044450445504465044750448504495045050451504525045350454504555045650457504585045950460504615046250463504645046550466504675046850469504705047150472504735047450475504765047750478504795048050481504825048350484504855048650487504885048950490504915049250493504945049550496504975049850499505005050150502505035050450505505065050750508505095051050511505125051350514505155051650517505185051950520505215052250523505245052550526505275052850529505305053150532505335053450535505365053750538505395054050541505425054350544505455054650547505485054950550505515055250553505545055550556505575055850559505605056150562505635056450565505665056750568505695057050571505725057350574505755057650577505785057950580505815058250583505845058550586505875058850589505905059150592505935059450595505965059750598505995060050601506025060350604506055060650607506085060950610506115061250613506145061550616506175061850619506205062150622506235062450625506265062750628506295063050631506325063350634506355063650637506385063950640506415064250643506445064550646506475064850649506505065150652506535065450655506565065750658506595066050661506625066350664506655066650667506685066950670506715067250673506745067550676506775067850679506805068150682506835068450685506865068750688506895069050691506925069350694506955069650697506985069950700507015070250703507045070550706507075070850709507105071150712507135071450715507165071750718507195072050721507225072350724507255072650727507285072950730507315073250733507345073550736507375073850739507405074150742507435074450745507465074750748507495075050751507525075350754507555075650757507585075950760507615076250763507645076550766507675076850769507705077150772507735077450775507765077750778507795078050781507825078350784507855078650787507885078950790507915079250793507945079550796507975079850799508005080150802508035080450805508065080750808508095081050811508125081350814508155081650817508185081950820508215082250823508245082550826508275082850829508305083150832508335083450835508365083750838508395084050841508425084350844508455084650847508485084950850508515085250853508545085550856508575085850859508605086150862508635086450865508665086750868508695087050871508725087350874508755087650877508785087950880508815088250883508845088550886508875088850889508905089150892508935089450895508965089750898508995090050901509025090350904509055090650907509085090950910509115091250913509145091550916509175091850919509205092150922509235092450925509265092750928509295093050931509325093350934509355093650937509385093950940509415094250943509445094550946509475094850949509505095150952509535095450955509565095750958509595096050961509625096350964509655096650967509685096950970509715097250973509745097550976509775097850979509805098150982509835098450985509865098750988509895099050991509925099350994509955099650997509985099951000510015100251003510045100551006510075100851009510105101151012510135101451015510165101751018510195102051021510225102351024510255102651027510285102951030510315103251033510345103551036510375103851039510405104151042510435104451045510465104751048510495105051051510525105351054510555105651057510585105951060510615106251063510645106551066510675106851069510705107151072510735107451075510765107751078510795108051081510825108351084510855108651087510885108951090510915109251093510945109551096510975109851099511005110151102511035110451105511065110751108511095111051111511125111351114511155111651117511185111951120511215112251123511245112551126511275112851129511305113151132511335113451135511365113751138511395114051141511425114351144511455114651147511485114951150511515115251153511545115551156511575115851159511605116151162511635116451165511665116751168511695117051171511725117351174511755117651177511785117951180511815118251183511845118551186511875118851189511905119151192511935119451195511965119751198511995120051201512025120351204512055120651207512085120951210512115121251213512145121551216512175121851219512205122151222512235122451225512265122751228512295123051231512325123351234512355123651237512385123951240512415124251243512445124551246512475124851249512505125151252512535125451255512565125751258512595126051261512625126351264512655126651267512685126951270512715127251273512745127551276512775127851279512805128151282512835128451285512865128751288512895129051291512925129351294512955129651297512985129951300513015130251303513045130551306513075130851309513105131151312513135131451315513165131751318513195132051321513225132351324513255132651327513285132951330513315133251333513345133551336513375133851339513405134151342513435134451345513465134751348513495135051351513525135351354513555135651357513585135951360513615136251363513645136551366513675136851369513705137151372513735137451375513765137751378513795138051381513825138351384513855138651387513885138951390513915139251393513945139551396513975139851399514005140151402514035140451405514065140751408514095141051411514125141351414514155141651417514185141951420514215142251423514245142551426514275142851429514305143151432514335143451435514365143751438514395144051441514425144351444514455144651447514485144951450514515145251453514545145551456514575145851459514605146151462514635146451465514665146751468514695147051471514725147351474514755147651477514785147951480514815148251483514845148551486514875148851489514905149151492514935149451495514965149751498514995150051501515025150351504515055150651507515085150951510515115151251513515145151551516515175151851519515205152151522515235152451525515265152751528515295153051531515325153351534515355153651537515385153951540515415154251543515445154551546515475154851549515505155151552515535155451555515565155751558515595156051561515625156351564515655156651567515685156951570515715157251573515745157551576515775157851579515805158151582515835158451585515865158751588515895159051591515925159351594515955159651597515985159951600516015160251603516045160551606516075160851609516105161151612516135161451615516165161751618516195162051621516225162351624516255162651627516285162951630516315163251633516345163551636516375163851639516405164151642516435164451645516465164751648516495165051651516525165351654516555165651657516585165951660516615166251663516645166551666516675166851669516705167151672516735167451675516765167751678516795168051681516825168351684516855168651687516885168951690516915169251693516945169551696516975169851699517005170151702517035170451705517065170751708517095171051711517125171351714517155171651717517185171951720517215172251723517245172551726517275172851729517305173151732517335173451735517365173751738517395174051741517425174351744517455174651747517485174951750517515175251753517545175551756517575175851759517605176151762517635176451765517665176751768517695177051771517725177351774517755177651777517785177951780517815178251783517845178551786517875178851789517905179151792517935179451795517965179751798517995180051801518025180351804518055180651807518085180951810518115181251813518145181551816518175181851819518205182151822518235182451825518265182751828518295183051831518325183351834518355183651837518385183951840518415184251843518445184551846518475184851849518505185151852518535185451855518565185751858518595186051861518625186351864518655186651867518685186951870518715187251873518745187551876518775187851879518805188151882518835188451885518865188751888518895189051891518925189351894518955189651897518985189951900519015190251903519045190551906519075190851909519105191151912519135191451915519165191751918519195192051921519225192351924519255192651927519285192951930519315193251933519345193551936519375193851939519405194151942519435194451945519465194751948519495195051951519525195351954519555195651957519585195951960519615196251963519645196551966519675196851969519705197151972519735197451975519765197751978519795198051981519825198351984519855198651987519885198951990519915199251993519945199551996519975199851999520005200152002520035200452005520065200752008520095201052011520125201352014520155201652017520185201952020520215202252023520245202552026520275202852029520305203152032520335203452035520365203752038520395204052041520425204352044520455204652047520485204952050520515205252053520545205552056520575205852059520605206152062520635206452065520665206752068520695207052071520725207352074520755207652077520785207952080520815208252083520845208552086520875208852089520905209152092520935209452095520965209752098520995210052101521025210352104521055210652107521085210952110521115211252113521145211552116521175211852119521205212152122521235212452125521265212752128521295213052131521325213352134521355213652137521385213952140521415214252143521445214552146521475214852149521505215152152521535215452155521565215752158521595216052161521625216352164521655216652167521685216952170521715217252173521745217552176521775217852179521805218152182521835218452185521865218752188521895219052191521925219352194521955219652197521985219952200522015220252203522045220552206522075220852209522105221152212522135221452215522165221752218522195222052221522225222352224522255222652227522285222952230522315223252233522345223552236522375223852239522405224152242522435224452245522465224752248522495225052251522525225352254522555225652257522585225952260522615226252263522645226552266522675226852269522705227152272522735227452275522765227752278522795228052281522825228352284522855228652287522885228952290522915229252293522945229552296522975229852299523005230152302523035230452305523065230752308523095231052311523125231352314523155231652317523185231952320523215232252323523245232552326523275232852329523305233152332523335233452335523365233752338523395234052341523425234352344523455234652347523485234952350523515235252353523545235552356523575235852359523605236152362523635236452365523665236752368523695237052371523725237352374523755237652377523785237952380523815238252383523845238552386523875238852389523905239152392523935239452395523965239752398523995240052401524025240352404524055240652407524085240952410524115241252413524145241552416524175241852419524205242152422524235242452425524265242752428524295243052431524325243352434524355243652437524385243952440524415244252443524445244552446524475244852449524505245152452524535245452455524565245752458524595246052461524625246352464524655246652467524685246952470524715247252473524745247552476524775247852479524805248152482524835248452485524865248752488524895249052491524925249352494524955249652497524985249952500525015250252503525045250552506525075250852509525105251152512525135251452515525165251752518525195252052521525225252352524525255252652527525285252952530525315253252533525345253552536525375253852539525405254152542525435254452545525465254752548525495255052551525525255352554525555255652557525585255952560525615256252563525645256552566525675256852569525705257152572525735257452575525765257752578525795258052581525825258352584525855258652587525885258952590525915259252593525945259552596525975259852599526005260152602526035260452605526065260752608526095261052611526125261352614526155261652617526185261952620526215262252623526245262552626526275262852629526305263152632526335263452635526365263752638526395264052641526425264352644526455264652647526485264952650526515265252653526545265552656526575265852659526605266152662526635266452665526665266752668526695267052671526725267352674526755267652677526785267952680526815268252683526845268552686526875268852689526905269152692526935269452695526965269752698526995270052701527025270352704527055270652707527085270952710527115271252713527145271552716527175271852719527205272152722527235272452725527265272752728527295273052731527325273352734527355273652737527385273952740527415274252743527445274552746527475274852749527505275152752527535275452755527565275752758527595276052761527625276352764527655276652767527685276952770527715277252773527745277552776527775277852779527805278152782527835278452785527865278752788527895279052791527925279352794527955279652797527985279952800528015280252803528045280552806528075280852809528105281152812528135281452815528165281752818528195282052821528225282352824528255282652827528285282952830528315283252833528345283552836528375283852839528405284152842528435284452845528465284752848528495285052851528525285352854528555285652857528585285952860528615286252863528645286552866528675286852869528705287152872528735287452875528765287752878528795288052881528825288352884528855288652887528885288952890528915289252893528945289552896528975289852899529005290152902529035290452905529065290752908529095291052911529125291352914529155291652917529185291952920529215292252923529245292552926529275292852929529305293152932529335293452935529365293752938529395294052941529425294352944529455294652947529485294952950529515295252953529545295552956529575295852959529605296152962529635296452965529665296752968529695297052971529725297352974529755297652977529785297952980529815298252983529845298552986529875298852989529905299152992529935299452995529965299752998529995300053001530025300353004530055300653007530085300953010530115301253013530145301553016530175301853019530205302153022530235302453025530265302753028530295303053031530325303353034530355303653037530385303953040530415304253043530445304553046530475304853049530505305153052530535305453055530565305753058530595306053061530625306353064530655306653067530685306953070530715307253073530745307553076530775307853079530805308153082530835308453085530865308753088530895309053091530925309353094530955309653097530985309953100531015310253103531045310553106531075310853109531105311153112531135311453115531165311753118531195312053121531225312353124531255312653127531285312953130531315313253133531345313553136531375313853139531405314153142531435314453145531465314753148531495315053151531525315353154531555315653157531585315953160531615316253163531645316553166531675316853169531705317153172531735317453175531765317753178531795318053181531825318353184531855318653187531885318953190531915319253193531945319553196531975319853199532005320153202532035320453205532065320753208532095321053211532125321353214532155321653217532185321953220532215322253223532245322553226532275322853229532305323153232532335323453235532365323753238532395324053241532425324353244532455324653247532485324953250532515325253253532545325553256532575325853259532605326153262532635326453265532665326753268532695327053271532725327353274532755327653277532785327953280532815328253283532845328553286532875328853289532905329153292532935329453295532965329753298532995330053301533025330353304533055330653307533085330953310533115331253313533145331553316533175331853319533205332153322533235332453325533265332753328533295333053331533325333353334533355333653337533385333953340533415334253343533445334553346533475334853349533505335153352533535335453355533565335753358533595336053361533625336353364533655336653367533685336953370533715337253373533745337553376533775337853379533805338153382533835338453385533865338753388533895339053391533925339353394533955339653397533985339953400534015340253403534045340553406534075340853409534105341153412534135341453415534165341753418534195342053421534225342353424534255342653427534285342953430534315343253433534345343553436534375343853439534405344153442534435344453445534465344753448534495345053451534525345353454534555345653457534585345953460534615346253463534645346553466534675346853469534705347153472534735347453475534765347753478534795348053481534825348353484534855348653487534885348953490534915349253493534945349553496534975349853499535005350153502535035350453505535065350753508535095351053511535125351353514535155351653517535185351953520535215352253523535245352553526535275352853529535305353153532535335353453535535365353753538535395354053541535425354353544535455354653547535485354953550535515355253553535545355553556535575355853559535605356153562535635356453565535665356753568535695357053571535725357353574535755357653577535785357953580535815358253583535845358553586535875358853589535905359153592535935359453595535965359753598535995360053601536025360353604536055360653607536085360953610536115361253613536145361553616536175361853619536205362153622536235362453625536265362753628536295363053631536325363353634536355363653637536385363953640536415364253643536445364553646536475364853649536505365153652536535365453655536565365753658536595366053661536625366353664536655366653667536685366953670536715367253673536745367553676536775367853679536805368153682536835368453685536865368753688536895369053691536925369353694536955369653697536985369953700537015370253703537045370553706537075370853709537105371153712537135371453715537165371753718537195372053721537225372353724537255372653727537285372953730537315373253733537345373553736537375373853739537405374153742537435374453745537465374753748537495375053751537525375353754537555375653757537585375953760537615376253763537645376553766537675376853769537705377153772537735377453775537765377753778537795378053781537825378353784537855378653787537885378953790537915379253793537945379553796537975379853799538005380153802538035380453805538065380753808538095381053811538125381353814538155381653817538185381953820538215382253823538245382553826538275382853829538305383153832538335383453835538365383753838538395384053841538425384353844538455384653847538485384953850538515385253853538545385553856538575385853859538605386153862538635386453865538665386753868538695387053871538725387353874538755387653877538785387953880538815388253883538845388553886538875388853889538905389153892538935389453895538965389753898538995390053901539025390353904539055390653907539085390953910539115391253913539145391553916539175391853919539205392153922539235392453925539265392753928539295393053931539325393353934539355393653937539385393953940539415394253943539445394553946539475394853949539505395153952539535395453955539565395753958539595396053961539625396353964539655396653967539685396953970539715397253973539745397553976539775397853979539805398153982539835398453985539865398753988539895399053991539925399353994539955399653997539985399954000540015400254003540045400554006540075400854009540105401154012540135401454015540165401754018540195402054021540225402354024540255402654027540285402954030540315403254033540345403554036540375403854039540405404154042540435404454045540465404754048540495405054051540525405354054540555405654057540585405954060540615406254063540645406554066540675406854069540705407154072540735407454075540765407754078540795408054081540825408354084540855408654087540885408954090540915409254093540945409554096540975409854099541005410154102541035410454105541065410754108541095411054111541125411354114541155411654117541185411954120541215412254123541245412554126541275412854129541305413154132541335413454135541365413754138541395414054141541425414354144541455414654147541485414954150541515415254153541545415554156541575415854159541605416154162541635416454165541665416754168541695417054171541725417354174541755417654177541785417954180541815418254183541845418554186541875418854189541905419154192541935419454195541965419754198541995420054201542025420354204542055420654207542085420954210542115421254213542145421554216542175421854219542205422154222542235422454225542265422754228542295423054231542325423354234542355423654237542385423954240542415424254243542445424554246542475424854249542505425154252542535425454255542565425754258542595426054261542625426354264542655426654267542685426954270542715427254273542745427554276542775427854279542805428154282542835428454285542865428754288542895429054291542925429354294542955429654297542985429954300543015430254303543045430554306543075430854309543105431154312543135431454315543165431754318543195432054321543225432354324543255432654327543285432954330543315433254333543345433554336543375433854339543405434154342543435434454345543465434754348543495435054351543525435354354543555435654357543585435954360543615436254363543645436554366543675436854369543705437154372543735437454375543765437754378543795438054381543825438354384543855438654387543885438954390543915439254393543945439554396543975439854399544005440154402544035440454405544065440754408544095441054411544125441354414544155441654417544185441954420544215442254423544245442554426544275442854429544305443154432544335443454435544365443754438544395444054441544425444354444544455444654447544485444954450544515445254453544545445554456544575445854459544605446154462544635446454465544665446754468544695447054471544725447354474544755447654477544785447954480544815448254483544845448554486544875448854489544905449154492544935449454495544965449754498544995450054501545025450354504545055450654507545085450954510545115451254513545145451554516545175451854519545205452154522545235452454525545265452754528545295453054531545325453354534545355453654537545385453954540545415454254543545445454554546545475454854549545505455154552545535455454555545565455754558545595456054561545625456354564545655456654567545685456954570545715457254573545745457554576545775457854579545805458154582545835458454585545865458754588545895459054591545925459354594545955459654597545985459954600546015460254603546045460554606546075460854609546105461154612546135461454615546165461754618546195462054621546225462354624546255462654627546285462954630546315463254633546345463554636546375463854639546405464154642546435464454645546465464754648546495465054651546525465354654546555465654657546585465954660546615466254663546645466554666546675466854669546705467154672546735467454675546765467754678546795468054681546825468354684546855468654687546885468954690546915469254693546945469554696546975469854699547005470154702547035470454705547065470754708547095471054711547125471354714547155471654717547185471954720547215472254723547245472554726547275472854729547305473154732547335473454735547365473754738547395474054741547425474354744547455474654747547485474954750547515475254753547545475554756547575475854759547605476154762547635476454765547665476754768547695477054771547725477354774547755477654777547785477954780547815478254783547845478554786547875478854789547905479154792547935479454795547965479754798547995480054801548025480354804548055480654807548085480954810548115481254813548145481554816548175481854819548205482154822548235482454825548265482754828548295483054831548325483354834548355483654837548385483954840548415484254843548445484554846548475484854849548505485154852548535485454855548565485754858548595486054861548625486354864548655486654867548685486954870548715487254873548745487554876548775487854879548805488154882548835488454885548865488754888548895489054891548925489354894548955489654897548985489954900549015490254903549045490554906549075490854909549105491154912549135491454915549165491754918549195492054921549225492354924549255492654927549285492954930549315493254933549345493554936549375493854939549405494154942549435494454945549465494754948549495495054951549525495354954549555495654957549585495954960549615496254963549645496554966549675496854969549705497154972549735497454975549765497754978549795498054981549825498354984549855498654987549885498954990549915499254993549945499554996549975499854999550005500155002550035500455005550065500755008550095501055011550125501355014550155501655017550185501955020550215502255023550245502555026550275502855029550305503155032550335503455035550365503755038550395504055041550425504355044550455504655047550485504955050550515505255053550545505555056550575505855059550605506155062550635506455065550665506755068550695507055071550725507355074550755507655077550785507955080550815508255083550845508555086550875508855089550905509155092550935509455095550965509755098550995510055101551025510355104551055510655107551085510955110551115511255113551145511555116551175511855119551205512155122551235512455125551265512755128551295513055131551325513355134551355513655137551385513955140551415514255143551445514555146551475514855149551505515155152551535515455155551565515755158551595516055161551625516355164551655516655167551685516955170551715517255173551745517555176551775517855179551805518155182551835518455185551865518755188551895519055191551925519355194551955519655197551985519955200552015520255203552045520555206552075520855209552105521155212552135521455215552165521755218552195522055221552225522355224552255522655227552285522955230552315523255233552345523555236552375523855239552405524155242552435524455245552465524755248552495525055251552525525355254552555525655257552585525955260552615526255263552645526555266552675526855269552705527155272552735527455275552765527755278552795528055281552825528355284552855528655287552885528955290552915529255293552945529555296552975529855299553005530155302553035530455305553065530755308553095531055311553125531355314553155531655317553185531955320553215532255323553245532555326553275532855329553305533155332553335533455335553365533755338553395534055341553425534355344553455534655347553485534955350553515535255353553545535555356553575535855359553605536155362553635536455365553665536755368553695537055371553725537355374553755537655377553785537955380553815538255383553845538555386553875538855389553905539155392553935539455395553965539755398553995540055401554025540355404554055540655407554085540955410554115541255413554145541555416554175541855419554205542155422554235542455425554265542755428554295543055431554325543355434554355543655437554385543955440554415544255443554445544555446554475544855449554505545155452554535545455455554565545755458554595546055461554625546355464554655546655467554685546955470554715547255473554745547555476554775547855479554805548155482554835548455485554865548755488554895549055491554925549355494554955549655497554985549955500555015550255503555045550555506555075550855509555105551155512555135551455515555165551755518555195552055521555225552355524555255552655527555285552955530555315553255533555345553555536555375553855539555405554155542555435554455545555465554755548555495555055551555525555355554555555555655557555585555955560555615556255563555645556555566555675556855569555705557155572555735557455575555765557755578555795558055581555825558355584555855558655587555885558955590555915559255593555945559555596555975559855599556005560155602556035560455605556065560755608556095561055611556125561355614556155561655617556185561955620556215562255623556245562555626556275562855629556305563155632556335563455635556365563755638556395564055641556425564355644556455564655647556485564955650556515565255653556545565555656556575565855659556605566155662556635566455665556665566755668556695567055671556725567355674556755567655677556785567955680556815568255683556845568555686556875568855689556905569155692556935569455695556965569755698556995570055701557025570355704557055570655707557085570955710557115571255713557145571555716557175571855719557205572155722557235572455725557265572755728557295573055731557325573355734557355573655737557385573955740557415574255743557445574555746557475574855749557505575155752557535575455755557565575755758557595576055761557625576355764557655576655767557685576955770557715577255773557745577555776557775577855779557805578155782557835578455785557865578755788557895579055791557925579355794557955579655797557985579955800558015580255803558045580555806558075580855809558105581155812558135581455815558165581755818558195582055821558225582355824558255582655827558285582955830558315583255833558345583555836558375583855839558405584155842558435584455845558465584755848558495585055851558525585355854558555585655857558585585955860558615586255863558645586555866558675586855869558705587155872558735587455875558765587755878558795588055881558825588355884558855588655887558885588955890558915589255893558945589555896558975589855899559005590155902559035590455905559065590755908559095591055911559125591355914559155591655917559185591955920559215592255923559245592555926559275592855929559305593155932559335593455935559365593755938559395594055941559425594355944559455594655947559485594955950559515595255953559545595555956559575595855959559605596155962559635596455965559665596755968559695597055971559725597355974559755597655977559785597955980559815598255983559845598555986559875598855989559905599155992559935599455995559965599755998559995600056001560025600356004560055600656007560085600956010560115601256013560145601556016560175601856019560205602156022560235602456025560265602756028560295603056031560325603356034560355603656037560385603956040560415604256043560445604556046560475604856049560505605156052560535605456055560565605756058560595606056061560625606356064560655606656067560685606956070560715607256073560745607556076560775607856079560805608156082560835608456085560865608756088560895609056091560925609356094560955609656097560985609956100561015610256103561045610556106561075610856109561105611156112561135611456115561165611756118561195612056121561225612356124561255612656127561285612956130561315613256133561345613556136561375613856139561405614156142561435614456145561465614756148561495615056151561525615356154561555615656157561585615956160561615616256163561645616556166561675616856169561705617156172561735617456175561765617756178561795618056181561825618356184561855618656187561885618956190561915619256193561945619556196561975619856199562005620156202562035620456205562065620756208562095621056211562125621356214562155621656217562185621956220562215622256223562245622556226562275622856229562305623156232562335623456235562365623756238562395624056241562425624356244562455624656247562485624956250562515625256253562545625556256562575625856259562605626156262562635626456265562665626756268562695627056271562725627356274562755627656277562785627956280562815628256283562845628556286562875628856289562905629156292562935629456295562965629756298562995630056301563025630356304563055630656307563085630956310563115631256313563145631556316563175631856319563205632156322563235632456325563265632756328563295633056331563325633356334563355633656337563385633956340563415634256343563445634556346563475634856349563505635156352563535635456355563565635756358563595636056361563625636356364563655636656367563685636956370563715637256373563745637556376563775637856379563805638156382563835638456385563865638756388563895639056391563925639356394563955639656397563985639956400564015640256403564045640556406564075640856409564105641156412564135641456415564165641756418564195642056421564225642356424564255642656427564285642956430564315643256433564345643556436564375643856439564405644156442564435644456445564465644756448564495645056451564525645356454564555645656457564585645956460564615646256463564645646556466564675646856469564705647156472564735647456475564765647756478564795648056481564825648356484564855648656487564885648956490564915649256493564945649556496564975649856499565005650156502565035650456505565065650756508565095651056511565125651356514565155651656517565185651956520565215652256523565245652556526565275652856529565305653156532565335653456535565365653756538565395654056541565425654356544565455654656547565485654956550565515655256553565545655556556565575655856559565605656156562565635656456565565665656756568565695657056571565725657356574565755657656577565785657956580565815658256583565845658556586565875658856589565905659156592565935659456595565965659756598565995660056601566025660356604566055660656607566085660956610566115661256613566145661556616566175661856619566205662156622566235662456625566265662756628566295663056631566325663356634566355663656637566385663956640566415664256643566445664556646566475664856649566505665156652566535665456655566565665756658566595666056661566625666356664566655666656667566685666956670566715667256673566745667556676566775667856679566805668156682566835668456685566865668756688566895669056691566925669356694566955669656697566985669956700567015670256703567045670556706567075670856709567105671156712567135671456715567165671756718567195672056721567225672356724567255672656727567285672956730567315673256733567345673556736567375673856739567405674156742567435674456745567465674756748567495675056751567525675356754567555675656757567585675956760567615676256763567645676556766567675676856769567705677156772567735677456775567765677756778567795678056781567825678356784567855678656787567885678956790567915679256793567945679556796567975679856799568005680156802568035680456805568065680756808568095681056811568125681356814568155681656817568185681956820568215682256823568245682556826568275682856829568305683156832568335683456835568365683756838568395684056841568425684356844568455684656847568485684956850568515685256853568545685556856568575685856859568605686156862568635686456865568665686756868568695687056871568725687356874568755687656877568785687956880568815688256883568845688556886568875688856889568905689156892568935689456895568965689756898568995690056901569025690356904569055690656907569085690956910569115691256913569145691556916569175691856919569205692156922569235692456925569265692756928569295693056931569325693356934569355693656937569385693956940569415694256943569445694556946569475694856949569505695156952569535695456955569565695756958569595696056961569625696356964569655696656967569685696956970569715697256973569745697556976569775697856979569805698156982569835698456985569865698756988569895699056991569925699356994569955699656997569985699957000570015700257003570045700557006570075700857009570105701157012570135701457015570165701757018570195702057021570225702357024570255702657027570285702957030570315703257033570345703557036570375703857039570405704157042570435704457045570465704757048570495705057051570525705357054570555705657057570585705957060570615706257063570645706557066570675706857069570705707157072570735707457075570765707757078570795708057081570825708357084570855708657087570885708957090570915709257093570945709557096570975709857099571005710157102571035710457105571065710757108571095711057111571125711357114571155711657117571185711957120571215712257123571245712557126571275712857129571305713157132571335713457135571365713757138571395714057141571425714357144571455714657147571485714957150571515715257153571545715557156571575715857159571605716157162571635716457165571665716757168571695717057171571725717357174571755717657177571785717957180571815718257183571845718557186571875718857189571905719157192571935719457195571965719757198571995720057201572025720357204572055720657207572085720957210572115721257213572145721557216572175721857219572205722157222572235722457225572265722757228572295723057231572325723357234572355723657237572385723957240572415724257243572445724557246572475724857249572505725157252572535725457255572565725757258572595726057261572625726357264572655726657267572685726957270572715727257273572745727557276572775727857279572805728157282572835728457285572865728757288572895729057291572925729357294572955729657297572985729957300573015730257303573045730557306573075730857309573105731157312573135731457315573165731757318573195732057321573225732357324573255732657327573285732957330573315733257333573345733557336573375733857339573405734157342573435734457345573465734757348573495735057351573525735357354573555735657357573585735957360573615736257363573645736557366573675736857369573705737157372573735737457375573765737757378573795738057381573825738357384573855738657387573885738957390573915739257393573945739557396573975739857399574005740157402574035740457405574065740757408574095741057411574125741357414574155741657417574185741957420574215742257423574245742557426574275742857429574305743157432574335743457435574365743757438574395744057441574425744357444574455744657447574485744957450574515745257453574545745557456574575745857459574605746157462574635746457465574665746757468574695747057471574725747357474574755747657477574785747957480574815748257483574845748557486574875748857489574905749157492574935749457495574965749757498574995750057501575025750357504575055750657507575085750957510575115751257513575145751557516575175751857519575205752157522575235752457525575265752757528575295753057531575325753357534575355753657537575385753957540575415754257543575445754557546575475754857549575505755157552575535755457555575565755757558575595756057561575625756357564575655756657567575685756957570575715757257573575745757557576575775757857579575805758157582575835758457585575865758757588575895759057591575925759357594575955759657597575985759957600576015760257603576045760557606576075760857609576105761157612576135761457615576165761757618576195762057621576225762357624576255762657627576285762957630576315763257633576345763557636576375763857639576405764157642576435764457645576465764757648576495765057651576525765357654576555765657657576585765957660576615766257663576645766557666576675766857669576705767157672576735767457675576765767757678576795768057681576825768357684576855768657687576885768957690576915769257693576945769557696576975769857699577005770157702577035770457705577065770757708577095771057711577125771357714577155771657717577185771957720577215772257723577245772557726577275772857729577305773157732577335773457735577365773757738577395774057741577425774357744577455774657747577485774957750577515775257753577545775557756577575775857759577605776157762577635776457765577665776757768577695777057771577725777357774577755777657777577785777957780577815778257783577845778557786577875778857789577905779157792577935779457795577965779757798577995780057801578025780357804578055780657807578085780957810578115781257813578145781557816578175781857819578205782157822578235782457825578265782757828578295783057831578325783357834578355783657837578385783957840578415784257843578445784557846578475784857849578505785157852578535785457855578565785757858578595786057861578625786357864578655786657867578685786957870578715787257873578745787557876578775787857879578805788157882578835788457885578865788757888578895789057891578925789357894578955789657897578985789957900579015790257903579045790557906579075790857909579105791157912579135791457915579165791757918579195792057921579225792357924579255792657927579285792957930579315793257933579345793557936579375793857939579405794157942579435794457945579465794757948579495795057951579525795357954579555795657957579585795957960579615796257963579645796557966579675796857969579705797157972579735797457975579765797757978579795798057981579825798357984579855798657987579885798957990579915799257993579945799557996579975799857999580005800158002580035800458005580065800758008580095801058011580125801358014580155801658017580185801958020580215802258023580245802558026580275802858029580305803158032580335803458035580365803758038580395804058041580425804358044580455804658047580485804958050580515805258053580545805558056580575805858059580605806158062580635806458065580665806758068580695807058071580725807358074580755807658077580785807958080580815808258083580845808558086580875808858089580905809158092580935809458095580965809758098580995810058101581025810358104581055810658107581085810958110581115811258113581145811558116581175811858119581205812158122581235812458125581265812758128581295813058131581325813358134581355813658137581385813958140581415814258143581445814558146581475814858149581505815158152581535815458155581565815758158581595816058161581625816358164581655816658167581685816958170581715817258173581745817558176581775817858179581805818158182581835818458185581865818758188581895819058191581925819358194581955819658197581985819958200582015820258203582045820558206582075820858209582105821158212582135821458215582165821758218582195822058221582225822358224582255822658227582285822958230582315823258233582345823558236582375823858239582405824158242582435824458245582465824758248582495825058251582525825358254582555825658257582585825958260582615826258263582645826558266582675826858269582705827158272582735827458275582765827758278582795828058281582825828358284582855828658287582885828958290582915829258293582945829558296582975829858299583005830158302583035830458305583065830758308583095831058311583125831358314583155831658317583185831958320583215832258323583245832558326583275832858329583305833158332583335833458335583365833758338583395834058341583425834358344583455834658347583485834958350583515835258353583545835558356583575835858359583605836158362583635836458365583665836758368583695837058371583725837358374583755837658377583785837958380583815838258383583845838558386583875838858389583905839158392583935839458395583965839758398583995840058401584025840358404584055840658407584085840958410584115841258413584145841558416584175841858419584205842158422584235842458425584265842758428584295843058431584325843358434584355843658437584385843958440584415844258443584445844558446584475844858449584505845158452584535845458455584565845758458584595846058461584625846358464584655846658467584685846958470584715847258473584745847558476584775847858479584805848158482584835848458485584865848758488584895849058491584925849358494584955849658497584985849958500585015850258503585045850558506585075850858509585105851158512585135851458515585165851758518585195852058521585225852358524585255852658527585285852958530585315853258533585345853558536585375853858539585405854158542585435854458545585465854758548585495855058551585525855358554585555855658557585585855958560585615856258563585645856558566585675856858569585705857158572585735857458575585765857758578585795858058581585825858358584585855858658587585885858958590585915859258593585945859558596585975859858599586005860158602586035860458605586065860758608586095861058611586125861358614586155861658617586185861958620586215862258623586245862558626586275862858629586305863158632586335863458635586365863758638586395864058641586425864358644586455864658647586485864958650586515865258653586545865558656586575865858659586605866158662586635866458665586665866758668586695867058671586725867358674586755867658677586785867958680586815868258683586845868558686586875868858689586905869158692586935869458695586965869758698586995870058701587025870358704587055870658707587085870958710587115871258713587145871558716587175871858719587205872158722587235872458725587265872758728587295873058731587325873358734587355873658737587385873958740587415874258743587445874558746587475874858749587505875158752587535875458755587565875758758587595876058761587625876358764587655876658767587685876958770587715877258773587745877558776587775877858779587805878158782587835878458785587865878758788587895879058791587925879358794587955879658797587985879958800588015880258803588045880558806588075880858809588105881158812588135881458815588165881758818588195882058821588225882358824588255882658827588285882958830588315883258833588345883558836588375883858839588405884158842588435884458845588465884758848588495885058851588525885358854588555885658857588585885958860588615886258863588645886558866588675886858869588705887158872588735887458875588765887758878588795888058881588825888358884588855888658887588885888958890588915889258893588945889558896588975889858899589005890158902589035890458905589065890758908589095891058911589125891358914589155891658917589185891958920589215892258923589245892558926589275892858929589305893158932589335893458935589365893758938589395894058941589425894358944589455894658947589485894958950589515895258953589545895558956589575895858959589605896158962589635896458965589665896758968589695897058971589725897358974589755897658977589785897958980589815898258983589845898558986589875898858989589905899158992589935899458995589965899758998589995900059001590025900359004590055900659007590085900959010590115901259013590145901559016590175901859019590205902159022590235902459025590265902759028590295903059031590325903359034590355903659037590385903959040590415904259043590445904559046590475904859049590505905159052590535905459055590565905759058590595906059061590625906359064590655906659067590685906959070590715907259073590745907559076590775907859079590805908159082590835908459085590865908759088590895909059091590925909359094590955909659097590985909959100591015910259103591045910559106591075910859109591105911159112591135911459115591165911759118591195912059121591225912359124591255912659127591285912959130591315913259133591345913559136591375913859139591405914159142591435914459145591465914759148591495915059151591525915359154591555915659157591585915959160591615916259163591645916559166591675916859169591705917159172591735917459175591765917759178591795918059181591825918359184591855918659187591885918959190591915919259193591945919559196591975919859199592005920159202592035920459205592065920759208592095921059211592125921359214592155921659217592185921959220592215922259223592245922559226592275922859229592305923159232592335923459235592365923759238592395924059241592425924359244592455924659247592485924959250592515925259253592545925559256592575925859259592605926159262592635926459265592665926759268592695927059271592725927359274592755927659277592785927959280592815928259283592845928559286592875928859289592905929159292592935929459295592965929759298592995930059301593025930359304593055930659307593085930959310593115931259313593145931559316593175931859319593205932159322593235932459325593265932759328593295933059331593325933359334593355933659337593385933959340593415934259343593445934559346593475934859349593505935159352593535935459355593565935759358593595936059361593625936359364593655936659367593685936959370593715937259373593745937559376593775937859379593805938159382593835938459385593865938759388593895939059391593925939359394593955939659397593985939959400594015940259403594045940559406594075940859409594105941159412594135941459415594165941759418594195942059421594225942359424594255942659427594285942959430594315943259433594345943559436594375943859439594405944159442594435944459445594465944759448594495945059451594525945359454594555945659457594585945959460594615946259463594645946559466594675946859469594705947159472594735947459475594765947759478594795948059481594825948359484594855948659487594885948959490594915949259493594945949559496594975949859499595005950159502595035950459505595065950759508595095951059511595125951359514595155951659517595185951959520595215952259523595245952559526595275952859529595305953159532595335953459535595365953759538595395954059541595425954359544595455954659547595485954959550595515955259553595545955559556595575955859559595605956159562595635956459565595665956759568595695957059571595725957359574595755957659577595785957959580595815958259583595845958559586595875958859589595905959159592595935959459595595965959759598595995960059601596025960359604596055960659607596085960959610596115961259613596145961559616596175961859619596205962159622596235962459625596265962759628596295963059631596325963359634596355963659637596385963959640596415964259643596445964559646596475964859649596505965159652596535965459655596565965759658596595966059661596625966359664596655966659667596685966959670596715967259673596745967559676596775967859679596805968159682596835968459685596865968759688596895969059691596925969359694596955969659697596985969959700597015970259703597045970559706597075970859709597105971159712597135971459715597165971759718597195972059721597225972359724597255972659727597285972959730597315973259733597345973559736597375973859739597405974159742597435974459745597465974759748597495975059751597525975359754597555975659757597585975959760597615976259763597645976559766597675976859769597705977159772597735977459775597765977759778597795978059781597825978359784597855978659787597885978959790597915979259793597945979559796597975979859799598005980159802598035980459805598065980759808598095981059811598125981359814598155981659817598185981959820598215982259823598245982559826598275982859829598305983159832598335983459835598365983759838598395984059841598425984359844598455984659847598485984959850598515985259853598545985559856598575985859859598605986159862598635986459865598665986759868598695987059871598725987359874598755987659877598785987959880598815988259883598845988559886598875988859889598905989159892598935989459895598965989759898598995990059901599025990359904599055990659907599085990959910599115991259913599145991559916599175991859919599205992159922599235992459925599265992759928599295993059931599325993359934599355993659937599385993959940599415994259943599445994559946599475994859949599505995159952599535995459955599565995759958599595996059961599625996359964599655996659967599685996959970599715997259973599745997559976599775997859979599805998159982599835998459985599865998759988599895999059991599925999359994599955999659997599985999960000600016000260003600046000560006600076000860009600106001160012600136001460015600166001760018600196002060021600226002360024600256002660027600286002960030600316003260033600346003560036600376003860039600406004160042600436004460045600466004760048600496005060051600526005360054600556005660057600586005960060600616006260063600646006560066600676006860069600706007160072600736007460075600766007760078600796008060081600826008360084600856008660087600886008960090600916009260093600946009560096600976009860099601006010160102601036010460105601066010760108601096011060111601126011360114601156011660117601186011960120601216012260123601246012560126601276012860129601306013160132601336013460135601366013760138601396014060141601426014360144601456014660147601486014960150601516015260153601546015560156601576015860159601606016160162601636016460165601666016760168601696017060171601726017360174601756017660177601786017960180601816018260183601846018560186601876018860189601906019160192601936019460195601966019760198601996020060201602026020360204602056020660207602086020960210602116021260213602146021560216602176021860219602206022160222602236022460225602266022760228602296023060231602326023360234602356023660237602386023960240602416024260243602446024560246602476024860249602506025160252602536025460255602566025760258602596026060261602626026360264602656026660267602686026960270602716027260273602746027560276602776027860279602806028160282602836028460285602866028760288602896029060291602926029360294602956029660297602986029960300603016030260303603046030560306603076030860309603106031160312603136031460315603166031760318603196032060321603226032360324603256032660327603286032960330603316033260333603346033560336603376033860339603406034160342603436034460345603466034760348603496035060351603526035360354603556035660357603586035960360603616036260363603646036560366603676036860369603706037160372603736037460375603766037760378603796038060381603826038360384603856038660387603886038960390603916039260393603946039560396603976039860399604006040160402604036040460405604066040760408604096041060411604126041360414604156041660417604186041960420604216042260423604246042560426604276042860429604306043160432604336043460435604366043760438604396044060441604426044360444604456044660447604486044960450604516045260453604546045560456604576045860459604606046160462604636046460465604666046760468604696047060471604726047360474604756047660477604786047960480604816048260483604846048560486604876048860489604906049160492604936049460495604966049760498604996050060501605026050360504605056050660507605086050960510605116051260513605146051560516605176051860519605206052160522605236052460525605266052760528605296053060531605326053360534605356053660537605386053960540605416054260543605446054560546605476054860549605506055160552605536055460555605566055760558605596056060561605626056360564605656056660567605686056960570605716057260573605746057560576605776057860579605806058160582605836058460585605866058760588605896059060591605926059360594605956059660597605986059960600606016060260603606046060560606606076060860609606106061160612606136061460615606166061760618606196062060621606226062360624606256062660627606286062960630606316063260633606346063560636606376063860639606406064160642606436064460645606466064760648606496065060651606526065360654606556065660657606586065960660606616066260663606646066560666606676066860669606706067160672606736067460675606766067760678606796068060681606826068360684606856068660687606886068960690606916069260693606946069560696606976069860699607006070160702607036070460705607066070760708607096071060711607126071360714607156071660717607186071960720607216072260723607246072560726607276072860729607306073160732607336073460735607366073760738607396074060741607426074360744607456074660747607486074960750607516075260753607546075560756607576075860759607606076160762607636076460765607666076760768607696077060771607726077360774607756077660777607786077960780607816078260783607846078560786607876078860789607906079160792607936079460795607966079760798607996080060801608026080360804608056080660807608086080960810608116081260813608146081560816608176081860819608206082160822608236082460825608266082760828608296083060831608326083360834608356083660837608386083960840608416084260843608446084560846608476084860849608506085160852608536085460855608566085760858608596086060861608626086360864608656086660867608686086960870608716087260873608746087560876608776087860879608806088160882608836088460885608866088760888608896089060891608926089360894608956089660897608986089960900609016090260903609046090560906609076090860909609106091160912609136091460915609166091760918609196092060921609226092360924609256092660927609286092960930609316093260933609346093560936609376093860939609406094160942609436094460945609466094760948609496095060951609526095360954609556095660957609586095960960609616096260963609646096560966609676096860969609706097160972609736097460975609766097760978609796098060981609826098360984609856098660987609886098960990609916099260993609946099560996609976099860999610006100161002610036100461005610066100761008610096101061011610126101361014610156101661017610186101961020610216102261023610246102561026610276102861029610306103161032610336103461035610366103761038610396104061041610426104361044610456104661047610486104961050610516105261053610546105561056610576105861059610606106161062610636106461065610666106761068610696107061071610726107361074610756107661077610786107961080610816108261083610846108561086610876108861089610906109161092610936109461095610966109761098610996110061101611026110361104611056110661107611086110961110611116111261113611146111561116611176111861119611206112161122611236112461125611266112761128611296113061131611326113361134611356113661137611386113961140611416114261143611446114561146611476114861149611506115161152611536115461155611566115761158611596116061161611626116361164611656116661167611686116961170611716117261173611746117561176611776117861179611806118161182611836118461185611866118761188611896119061191611926119361194611956119661197611986119961200612016120261203612046120561206612076120861209612106121161212612136121461215612166121761218612196122061221612226122361224612256122661227612286122961230612316123261233612346123561236612376123861239612406124161242612436124461245612466124761248612496125061251612526125361254612556125661257612586125961260612616126261263612646126561266612676126861269612706127161272612736127461275612766127761278612796128061281612826128361284612856128661287612886128961290612916129261293612946129561296612976129861299613006130161302613036130461305613066130761308613096131061311613126131361314613156131661317613186131961320613216132261323613246132561326613276132861329613306133161332613336133461335613366133761338613396134061341613426134361344613456134661347613486134961350613516135261353613546135561356613576135861359613606136161362613636136461365613666136761368613696137061371613726137361374613756137661377613786137961380613816138261383613846138561386613876138861389613906139161392613936139461395613966139761398613996140061401614026140361404614056140661407614086140961410614116141261413614146141561416614176141861419614206142161422614236142461425614266142761428614296143061431614326143361434614356143661437614386143961440614416144261443614446144561446614476144861449614506145161452614536145461455614566145761458614596146061461614626146361464614656146661467614686146961470614716147261473614746147561476614776147861479614806148161482614836148461485614866148761488614896149061491614926149361494614956149661497614986149961500615016150261503615046150561506615076150861509615106151161512615136151461515615166151761518615196152061521615226152361524615256152661527615286152961530615316153261533615346153561536615376153861539615406154161542615436154461545615466154761548615496155061551615526155361554615556155661557615586155961560615616156261563615646156561566615676156861569615706157161572615736157461575615766157761578615796158061581615826158361584615856158661587615886158961590615916159261593615946159561596615976159861599616006160161602616036160461605616066160761608616096161061611616126161361614616156161661617616186161961620616216162261623616246162561626616276162861629616306163161632616336163461635616366163761638616396164061641616426164361644616456164661647616486164961650616516165261653616546165561656616576165861659616606166161662616636166461665616666166761668616696167061671616726167361674616756167661677616786167961680616816168261683616846168561686616876168861689616906169161692616936169461695616966169761698616996170061701617026170361704617056170661707617086170961710617116171261713617146171561716617176171861719617206172161722617236172461725617266172761728617296173061731617326173361734617356173661737617386173961740617416174261743617446174561746617476174861749617506175161752617536175461755617566175761758617596176061761617626176361764617656176661767617686176961770617716177261773617746177561776617776177861779617806178161782617836178461785617866178761788617896179061791617926179361794617956179661797617986179961800618016180261803618046180561806618076180861809618106181161812618136181461815618166181761818618196182061821618226182361824618256182661827618286182961830618316183261833618346183561836618376183861839618406184161842618436184461845618466184761848618496185061851618526185361854618556185661857618586185961860618616186261863618646186561866618676186861869618706187161872618736187461875618766187761878618796188061881618826188361884618856188661887618886188961890618916189261893618946189561896618976189861899619006190161902619036190461905619066190761908619096191061911619126191361914619156191661917619186191961920619216192261923619246192561926619276192861929619306193161932619336193461935619366193761938619396194061941619426194361944619456194661947619486194961950619516195261953619546195561956619576195861959619606196161962619636196461965619666196761968619696197061971619726197361974619756197661977619786197961980619816198261983619846198561986619876198861989619906199161992619936199461995619966199761998619996200062001620026200362004620056200662007620086200962010620116201262013620146201562016620176201862019620206202162022620236202462025620266202762028620296203062031620326203362034620356203662037620386203962040620416204262043620446204562046620476204862049620506205162052620536205462055620566205762058620596206062061620626206362064620656206662067620686206962070620716207262073620746207562076620776207862079620806208162082620836208462085620866208762088620896209062091620926209362094620956209662097620986209962100621016210262103621046210562106621076210862109621106211162112621136211462115621166211762118621196212062121621226212362124621256212662127621286212962130621316213262133621346213562136621376213862139621406214162142621436214462145621466214762148621496215062151621526215362154621556215662157621586215962160621616216262163621646216562166621676216862169621706217162172621736217462175621766217762178621796218062181621826218362184621856218662187621886218962190621916219262193621946219562196621976219862199622006220162202622036220462205622066220762208622096221062211622126221362214622156221662217622186221962220622216222262223622246222562226622276222862229622306223162232622336223462235622366223762238622396224062241622426224362244622456224662247622486224962250622516225262253622546225562256622576225862259622606226162262622636226462265622666226762268622696227062271622726227362274622756227662277622786227962280622816228262283622846228562286622876228862289622906229162292622936229462295622966229762298622996230062301623026230362304623056230662307623086230962310623116231262313623146231562316623176231862319623206232162322623236232462325623266232762328623296233062331623326233362334623356233662337623386233962340623416234262343623446234562346623476234862349623506235162352623536235462355623566235762358623596236062361623626236362364623656236662367623686236962370623716237262373623746237562376623776237862379623806238162382623836238462385623866238762388623896239062391623926239362394623956239662397623986239962400624016240262403624046240562406624076240862409624106241162412624136241462415624166241762418624196242062421624226242362424624256242662427624286242962430624316243262433624346243562436624376243862439624406244162442624436244462445624466244762448624496245062451624526245362454624556245662457624586245962460624616246262463624646246562466624676246862469624706247162472624736247462475624766247762478624796248062481624826248362484624856248662487624886248962490624916249262493624946249562496624976249862499625006250162502625036250462505625066250762508625096251062511625126251362514625156251662517625186251962520625216252262523625246252562526625276252862529625306253162532625336253462535625366253762538625396254062541625426254362544625456254662547625486254962550625516255262553625546255562556625576255862559625606256162562625636256462565625666256762568625696257062571625726257362574625756257662577625786257962580625816258262583625846258562586625876258862589625906259162592625936259462595625966259762598625996260062601626026260362604626056260662607626086260962610626116261262613626146261562616626176261862619626206262162622626236262462625626266262762628626296263062631626326263362634626356263662637626386263962640626416264262643626446264562646626476264862649626506265162652626536265462655626566265762658626596266062661626626266362664626656266662667626686266962670626716267262673626746267562676626776267862679626806268162682626836268462685626866268762688626896269062691626926269362694626956269662697626986269962700627016270262703627046270562706627076270862709627106271162712627136271462715627166271762718627196272062721627226272362724627256272662727627286272962730627316273262733627346273562736627376273862739627406274162742627436274462745627466274762748627496275062751627526275362754627556275662757627586275962760627616276262763627646276562766627676276862769627706277162772627736277462775627766277762778627796278062781627826278362784627856278662787627886278962790627916279262793627946279562796627976279862799628006280162802628036280462805628066280762808628096281062811628126281362814628156281662817628186281962820628216282262823628246282562826628276282862829628306283162832628336283462835628366283762838628396284062841628426284362844628456284662847628486284962850628516285262853628546285562856628576285862859628606286162862628636286462865628666286762868628696287062871628726287362874628756287662877628786287962880628816288262883628846288562886628876288862889628906289162892628936289462895628966289762898628996290062901629026290362904629056290662907629086290962910629116291262913629146291562916629176291862919629206292162922629236292462925629266292762928629296293062931629326293362934629356293662937629386293962940629416294262943629446294562946629476294862949629506295162952629536295462955629566295762958629596296062961629626296362964629656296662967629686296962970629716297262973629746297562976629776297862979629806298162982629836298462985629866298762988629896299062991629926299362994629956299662997629986299963000630016300263003630046300563006630076300863009630106301163012630136301463015630166301763018630196302063021630226302363024630256302663027630286302963030630316303263033630346303563036630376303863039630406304163042630436304463045630466304763048630496305063051630526305363054630556305663057630586305963060630616306263063630646306563066630676306863069630706307163072630736307463075630766307763078630796308063081630826308363084630856308663087630886308963090630916309263093630946309563096630976309863099631006310163102631036310463105631066310763108631096311063111631126311363114631156311663117631186311963120631216312263123631246312563126631276312863129631306313163132631336313463135631366313763138631396314063141631426314363144631456314663147631486314963150631516315263153631546315563156631576315863159631606316163162631636316463165631666316763168631696317063171631726317363174631756317663177631786317963180631816318263183631846318563186631876318863189631906319163192631936319463195631966319763198631996320063201632026320363204632056320663207632086320963210632116321263213632146321563216632176321863219632206322163222632236322463225632266322763228632296323063231632326323363234632356323663237632386323963240632416324263243632446324563246632476324863249632506325163252632536325463255632566325763258632596326063261632626326363264632656326663267632686326963270632716327263273632746327563276632776327863279632806328163282632836328463285632866328763288632896329063291632926329363294632956329663297632986329963300633016330263303633046330563306633076330863309633106331163312633136331463315633166331763318633196332063321633226332363324633256332663327633286332963330633316333263333633346333563336633376333863339633406334163342633436334463345633466334763348633496335063351633526335363354633556335663357633586335963360633616336263363633646336563366633676336863369633706337163372633736337463375633766337763378633796338063381633826338363384633856338663387633886338963390633916339263393633946339563396633976339863399634006340163402634036340463405634066340763408634096341063411634126341363414634156341663417634186341963420634216342263423634246342563426634276342863429634306343163432634336343463435634366343763438634396344063441634426344363444634456344663447634486344963450634516345263453634546345563456634576345863459634606346163462634636346463465634666346763468634696347063471634726347363474634756347663477634786347963480634816348263483634846348563486634876348863489634906349163492634936349463495634966349763498634996350063501635026350363504635056350663507635086350963510635116351263513635146351563516635176351863519635206352163522635236352463525635266352763528635296353063531635326353363534635356353663537635386353963540635416354263543635446354563546635476354863549635506355163552635536355463555635566355763558635596356063561635626356363564635656356663567635686356963570635716357263573635746357563576635776357863579635806358163582635836358463585635866358763588635896359063591635926359363594635956359663597635986359963600636016360263603636046360563606636076360863609636106361163612636136361463615636166361763618636196362063621636226362363624636256362663627636286362963630636316363263633636346363563636636376363863639636406364163642636436364463645636466364763648636496365063651636526365363654636556365663657636586365963660636616366263663636646366563666636676366863669636706367163672636736367463675636766367763678636796368063681636826368363684636856368663687636886368963690636916369263693636946369563696636976369863699637006370163702637036370463705637066370763708637096371063711637126371363714637156371663717637186371963720637216372263723637246372563726637276372863729637306373163732637336373463735637366373763738637396374063741637426374363744637456374663747637486374963750637516375263753637546375563756637576375863759637606376163762637636376463765637666376763768637696377063771637726377363774637756377663777637786377963780637816378263783637846378563786637876378863789637906379163792637936379463795637966379763798637996380063801638026380363804638056380663807638086380963810638116381263813638146381563816638176381863819638206382163822638236382463825638266382763828638296383063831638326383363834638356383663837638386383963840638416384263843638446384563846638476384863849638506385163852638536385463855638566385763858638596386063861638626386363864638656386663867638686386963870638716387263873638746387563876638776387863879638806388163882638836388463885638866388763888638896389063891638926389363894638956389663897638986389963900639016390263903639046390563906639076390863909639106391163912639136391463915639166391763918639196392063921639226392363924639256392663927639286392963930639316393263933639346393563936639376393863939639406394163942639436394463945639466394763948639496395063951639526395363954639556395663957639586395963960639616396263963639646396563966639676396863969639706397163972639736397463975639766397763978639796398063981639826398363984639856398663987639886398963990639916399263993639946399563996639976399863999640006400164002640036400464005640066400764008640096401064011640126401364014640156401664017640186401964020640216402264023640246402564026640276402864029640306403164032640336403464035640366403764038640396404064041640426404364044640456404664047640486404964050640516405264053640546405564056640576405864059640606406164062640636406464065640666406764068640696407064071640726407364074640756407664077640786407964080640816408264083640846408564086640876408864089640906409164092640936409464095640966409764098640996410064101641026410364104641056410664107641086410964110641116411264113641146411564116641176411864119641206412164122641236412464125641266412764128641296413064131641326413364134641356413664137641386413964140641416414264143641446414564146641476414864149641506415164152641536415464155641566415764158641596416064161641626416364164641656416664167641686416964170641716417264173641746417564176641776417864179641806418164182641836418464185641866418764188641896419064191641926419364194641956419664197641986419964200642016420264203642046420564206642076420864209642106421164212642136421464215642166421764218642196422064221642226422364224642256422664227642286422964230642316423264233642346423564236642376423864239642406424164242642436424464245642466424764248642496425064251642526425364254642556425664257642586425964260642616426264263642646426564266642676426864269642706427164272642736427464275642766427764278642796428064281642826428364284642856428664287642886428964290642916429264293642946429564296642976429864299643006430164302643036430464305643066430764308643096431064311643126431364314643156431664317643186431964320643216432264323643246432564326643276432864329643306433164332643336433464335643366433764338643396434064341643426434364344643456434664347643486434964350643516435264353643546435564356643576435864359643606436164362643636436464365643666436764368643696437064371643726437364374643756437664377643786437964380643816438264383643846438564386643876438864389643906439164392643936439464395643966439764398643996440064401644026440364404644056440664407644086440964410644116441264413644146441564416644176441864419644206442164422644236442464425644266442764428644296443064431644326443364434644356443664437644386443964440644416444264443644446444564446644476444864449644506445164452644536445464455644566445764458644596446064461644626446364464644656446664467644686446964470644716447264473644746447564476644776447864479644806448164482644836448464485644866448764488644896449064491644926449364494644956449664497644986449964500645016450264503645046450564506645076450864509645106451164512645136451464515645166451764518645196452064521645226452364524645256452664527645286452964530645316453264533645346453564536645376453864539645406454164542645436454464545645466454764548645496455064551645526455364554645556455664557645586455964560645616456264563645646456564566645676456864569645706457164572645736457464575645766457764578645796458064581645826458364584645856458664587645886458964590645916459264593645946459564596645976459864599646006460164602646036460464605646066460764608646096461064611646126461364614646156461664617646186461964620646216462264623646246462564626646276462864629646306463164632646336463464635646366463764638646396464064641646426464364644646456464664647646486464964650646516465264653646546465564656646576465864659646606466164662646636466464665646666466764668646696467064671646726467364674646756467664677646786467964680646816468264683646846468564686646876468864689646906469164692646936469464695646966469764698646996470064701647026470364704647056470664707647086470964710647116471264713647146471564716647176471864719647206472164722647236472464725647266472764728647296473064731647326473364734647356473664737647386473964740647416474264743647446474564746647476474864749647506475164752647536475464755647566475764758647596476064761647626476364764647656476664767647686476964770647716477264773647746477564776647776477864779647806478164782647836478464785647866478764788647896479064791647926479364794647956479664797647986479964800648016480264803648046480564806648076480864809648106481164812648136481464815648166481764818648196482064821648226482364824648256482664827648286482964830648316483264833648346483564836648376483864839648406484164842648436484464845648466484764848648496485064851648526485364854648556485664857648586485964860648616486264863648646486564866648676486864869648706487164872648736487464875648766487764878648796488064881648826488364884648856488664887648886488964890648916489264893648946489564896648976489864899649006490164902649036490464905649066490764908649096491064911649126491364914649156491664917649186491964920649216492264923649246492564926649276492864929649306493164932649336493464935649366493764938649396494064941649426494364944649456494664947649486494964950649516495264953649546495564956649576495864959649606496164962649636496464965649666496764968649696497064971649726497364974649756497664977649786497964980649816498264983649846498564986649876498864989649906499164992649936499464995649966499764998649996500065001650026500365004650056500665007650086500965010650116501265013650146501565016650176501865019650206502165022650236502465025650266502765028650296503065031650326503365034650356503665037650386503965040650416504265043650446504565046650476504865049650506505165052650536505465055650566505765058650596506065061650626506365064650656506665067650686506965070650716507265073650746507565076650776507865079650806508165082650836508465085650866508765088650896509065091650926509365094650956509665097650986509965100651016510265103651046510565106651076510865109651106511165112651136511465115651166511765118651196512065121651226512365124651256512665127651286512965130651316513265133651346513565136651376513865139651406514165142651436514465145651466514765148651496515065151651526515365154651556515665157651586515965160651616516265163651646516565166651676516865169651706517165172651736517465175651766517765178651796518065181651826518365184651856518665187651886518965190651916519265193651946519565196651976519865199652006520165202652036520465205652066520765208652096521065211652126521365214652156521665217652186521965220652216522265223652246522565226652276522865229652306523165232652336523465235652366523765238652396524065241652426524365244652456524665247652486524965250652516525265253652546525565256652576525865259652606526165262652636526465265652666526765268652696527065271652726527365274652756527665277652786527965280652816528265283652846528565286652876528865289652906529165292652936529465295652966529765298652996530065301653026530365304653056530665307653086530965310653116531265313653146531565316653176531865319653206532165322653236532465325653266532765328653296533065331653326533365334653356533665337653386533965340653416534265343653446534565346653476534865349653506535165352653536535465355653566535765358653596536065361653626536365364653656536665367653686536965370653716537265373653746537565376653776537865379653806538165382653836538465385653866538765388653896539065391653926539365394653956539665397653986539965400654016540265403654046540565406654076540865409654106541165412654136541465415654166541765418654196542065421654226542365424654256542665427654286542965430654316543265433654346543565436654376543865439654406544165442654436544465445654466544765448654496545065451654526545365454654556545665457654586545965460654616546265463654646546565466654676546865469654706547165472654736547465475654766547765478654796548065481654826548365484654856548665487654886548965490654916549265493654946549565496654976549865499655006550165502655036550465505655066550765508655096551065511655126551365514655156551665517655186551965520655216552265523655246552565526655276552865529655306553165532655336553465535655366553765538655396554065541655426554365544655456554665547655486554965550655516555265553655546555565556655576555865559655606556165562655636556465565655666556765568655696557065571655726557365574655756557665577655786557965580655816558265583655846558565586655876558865589655906559165592655936559465595655966559765598655996560065601656026560365604656056560665607656086560965610656116561265613656146561565616656176561865619656206562165622656236562465625656266562765628656296563065631656326563365634656356563665637656386563965640656416564265643656446564565646656476564865649656506565165652656536565465655656566565765658656596566065661656626566365664656656566665667656686566965670656716567265673656746567565676656776567865679656806568165682656836568465685656866568765688656896569065691656926569365694656956569665697656986569965700657016570265703657046570565706657076570865709657106571165712657136571465715657166571765718657196572065721657226572365724657256572665727657286572965730657316573265733657346573565736657376573865739657406574165742657436574465745657466574765748657496575065751657526575365754657556575665757657586575965760657616576265763657646576565766657676576865769657706577165772657736577465775657766577765778657796578065781657826578365784657856578665787657886578965790657916579265793657946579565796657976579865799658006580165802658036580465805658066580765808658096581065811658126581365814658156581665817658186581965820658216582265823658246582565826658276582865829658306583165832658336583465835658366583765838658396584065841658426584365844658456584665847658486584965850658516585265853658546585565856658576585865859658606586165862658636586465865658666586765868658696587065871658726587365874658756587665877658786587965880658816588265883658846588565886658876588865889658906589165892658936589465895658966589765898658996590065901659026590365904659056590665907659086590965910659116591265913659146591565916659176591865919659206592165922659236592465925659266592765928659296593065931659326593365934659356593665937659386593965940659416594265943659446594565946659476594865949659506595165952659536595465955659566595765958659596596065961659626596365964659656596665967659686596965970659716597265973659746597565976659776597865979659806598165982659836598465985659866598765988659896599065991659926599365994659956599665997659986599966000660016600266003660046600566006660076600866009660106601166012660136601466015660166601766018660196602066021660226602366024660256602666027660286602966030660316603266033660346603566036660376603866039660406604166042660436604466045660466604766048660496605066051660526605366054660556605666057660586605966060660616606266063660646606566066660676606866069660706607166072660736607466075660766607766078660796608066081660826608366084660856608666087660886608966090660916609266093660946609566096660976609866099661006610166102661036610466105661066610766108661096611066111661126611366114661156611666117661186611966120661216612266123661246612566126661276612866129661306613166132661336613466135661366613766138661396614066141661426614366144661456614666147661486614966150661516615266153661546615566156661576615866159661606616166162661636616466165661666616766168661696617066171661726617366174661756617666177661786617966180661816618266183661846618566186661876618866189661906619166192661936619466195661966619766198661996620066201662026620366204662056620666207662086620966210662116621266213662146621566216662176621866219662206622166222662236622466225662266622766228662296623066231662326623366234662356623666237662386623966240662416624266243662446624566246662476624866249662506625166252662536625466255662566625766258662596626066261662626626366264662656626666267662686626966270662716627266273662746627566276662776627866279662806628166282662836628466285662866628766288662896629066291662926629366294662956629666297662986629966300663016630266303663046630566306663076630866309663106631166312663136631466315663166631766318663196632066321663226632366324663256632666327663286632966330663316633266333663346633566336663376633866339663406634166342663436634466345663466634766348663496635066351663526635366354663556635666357663586635966360663616636266363663646636566366663676636866369663706637166372663736637466375663766637766378663796638066381663826638366384663856638666387663886638966390663916639266393663946639566396663976639866399664006640166402664036640466405664066640766408664096641066411664126641366414664156641666417664186641966420664216642266423664246642566426664276642866429664306643166432664336643466435664366643766438664396644066441664426644366444664456644666447664486644966450664516645266453664546645566456664576645866459664606646166462664636646466465664666646766468664696647066471664726647366474664756647666477664786647966480664816648266483664846648566486664876648866489664906649166492664936649466495664966649766498664996650066501665026650366504665056650666507665086650966510665116651266513665146651566516665176651866519665206652166522665236652466525665266652766528665296653066531665326653366534665356653666537665386653966540665416654266543665446654566546665476654866549665506655166552665536655466555665566655766558665596656066561665626656366564665656656666567665686656966570665716657266573665746657566576665776657866579665806658166582665836658466585665866658766588665896659066591665926659366594665956659666597665986659966600666016660266603666046660566606666076660866609666106661166612666136661466615666166661766618666196662066621666226662366624666256662666627666286662966630666316663266633666346663566636666376663866639666406664166642666436664466645666466664766648666496665066651666526665366654666556665666657666586665966660666616666266663666646666566666666676666866669666706667166672666736667466675666766667766678666796668066681666826668366684666856668666687666886668966690666916669266693666946669566696666976669866699667006670166702667036670466705667066670766708667096671066711667126671366714667156671666717667186671966720667216672266723667246672566726667276672866729667306673166732667336673466735667366673766738667396674066741667426674366744667456674666747667486674966750667516675266753667546675566756667576675866759667606676166762667636676466765667666676766768667696677066771667726677366774667756677666777667786677966780667816678266783667846678566786667876678866789667906679166792667936679466795667966679766798667996680066801668026680366804668056680666807668086680966810668116681266813668146681566816668176681866819668206682166822668236682466825668266682766828668296683066831668326683366834668356683666837668386683966840668416684266843668446684566846668476684866849668506685166852668536685466855668566685766858668596686066861668626686366864668656686666867668686686966870668716687266873668746687566876668776687866879668806688166882668836688466885668866688766888668896689066891668926689366894668956689666897668986689966900669016690266903669046690566906669076690866909669106691166912669136691466915669166691766918669196692066921669226692366924669256692666927669286692966930669316693266933669346693566936669376693866939669406694166942669436694466945669466694766948669496695066951669526695366954669556695666957669586695966960669616696266963669646696566966669676696866969669706697166972669736697466975669766697766978669796698066981669826698366984669856698666987669886698966990669916699266993669946699566996669976699866999670006700167002670036700467005670066700767008670096701067011670126701367014670156701667017670186701967020670216702267023670246702567026670276702867029670306703167032670336703467035670366703767038670396704067041670426704367044670456704667047670486704967050670516705267053670546705567056670576705867059670606706167062670636706467065670666706767068670696707067071670726707367074670756707667077670786707967080670816708267083670846708567086670876708867089670906709167092670936709467095670966709767098670996710067101671026710367104671056710667107671086710967110671116711267113671146711567116671176711867119671206712167122671236712467125671266712767128671296713067131671326713367134671356713667137671386713967140671416714267143671446714567146671476714867149671506715167152671536715467155671566715767158671596716067161671626716367164671656716667167671686716967170671716717267173671746717567176671776717867179671806718167182671836718467185671866718767188671896719067191671926719367194671956719667197671986719967200672016720267203672046720567206672076720867209672106721167212672136721467215672166721767218672196722067221672226722367224672256722667227672286722967230672316723267233672346723567236672376723867239672406724167242672436724467245672466724767248672496725067251672526725367254672556725667257672586725967260672616726267263672646726567266672676726867269672706727167272672736727467275672766727767278672796728067281672826728367284672856728667287672886728967290672916729267293672946729567296672976729867299673006730167302673036730467305673066730767308673096731067311673126731367314673156731667317673186731967320673216732267323673246732567326673276732867329673306733167332673336733467335673366733767338673396734067341673426734367344673456734667347673486734967350673516735267353673546735567356673576735867359673606736167362673636736467365673666736767368673696737067371673726737367374673756737667377673786737967380673816738267383673846738567386673876738867389673906739167392673936739467395673966739767398673996740067401674026740367404674056740667407674086740967410674116741267413674146741567416674176741867419674206742167422674236742467425674266742767428674296743067431674326743367434674356743667437674386743967440674416744267443674446744567446674476744867449674506745167452674536745467455674566745767458674596746067461674626746367464674656746667467674686746967470674716747267473674746747567476674776747867479674806748167482674836748467485674866748767488674896749067491674926749367494674956749667497674986749967500675016750267503675046750567506675076750867509675106751167512675136751467515675166751767518675196752067521675226752367524675256752667527675286752967530675316753267533675346753567536675376753867539675406754167542675436754467545675466754767548675496755067551675526755367554675556755667557675586755967560675616756267563675646756567566675676756867569675706757167572675736757467575675766757767578675796758067581675826758367584675856758667587675886758967590675916759267593675946759567596675976759867599676006760167602676036760467605676066760767608676096761067611676126761367614676156761667617676186761967620676216762267623676246762567626676276762867629676306763167632676336763467635676366763767638676396764067641676426764367644676456764667647676486764967650676516765267653676546765567656676576765867659676606766167662676636766467665676666766767668676696767067671676726767367674676756767667677676786767967680676816768267683676846768567686676876768867689676906769167692676936769467695676966769767698676996770067701677026770367704677056770667707677086770967710677116771267713677146771567716677176771867719677206772167722677236772467725677266772767728677296773067731677326773367734677356773667737677386773967740677416774267743677446774567746677476774867749677506775167752677536775467755677566775767758677596776067761677626776367764677656776667767677686776967770677716777267773677746777567776677776777867779677806778167782677836778467785677866778767788677896779067791677926779367794677956779667797677986779967800678016780267803678046780567806678076780867809678106781167812678136781467815678166781767818678196782067821678226782367824678256782667827678286782967830678316783267833678346783567836678376783867839678406784167842678436784467845678466784767848678496785067851678526785367854678556785667857678586785967860678616786267863678646786567866678676786867869678706787167872678736787467875678766787767878678796788067881678826788367884678856788667887678886788967890678916789267893678946789567896678976789867899679006790167902679036790467905679066790767908679096791067911679126791367914679156791667917679186791967920679216792267923679246792567926679276792867929679306793167932679336793467935679366793767938679396794067941679426794367944679456794667947679486794967950679516795267953679546795567956679576795867959679606796167962679636796467965679666796767968679696797067971679726797367974679756797667977679786797967980679816798267983679846798567986679876798867989679906799167992679936799467995679966799767998679996800068001680026800368004680056800668007680086800968010680116801268013680146801568016680176801868019680206802168022680236802468025680266802768028680296803068031680326803368034680356803668037680386803968040680416804268043680446804568046680476804868049680506805168052680536805468055680566805768058680596806068061680626806368064680656806668067680686806968070680716807268073680746807568076680776807868079680806808168082680836808468085680866808768088680896809068091680926809368094680956809668097680986809968100681016810268103681046810568106681076810868109681106811168112681136811468115681166811768118681196812068121681226812368124681256812668127681286812968130681316813268133681346813568136681376813868139681406814168142681436814468145681466814768148681496815068151681526815368154681556815668157681586815968160681616816268163681646816568166681676816868169681706817168172681736817468175681766817768178681796818068181681826818368184681856818668187681886818968190681916819268193681946819568196681976819868199682006820168202682036820468205682066820768208682096821068211682126821368214682156821668217682186821968220682216822268223682246822568226682276822868229682306823168232682336823468235682366823768238682396824068241682426824368244682456824668247682486824968250682516825268253682546825568256682576825868259682606826168262682636826468265682666826768268682696827068271682726827368274682756827668277682786827968280682816828268283682846828568286682876828868289682906829168292682936829468295682966829768298682996830068301683026830368304683056830668307683086830968310683116831268313683146831568316683176831868319683206832168322683236832468325683266832768328683296833068331683326833368334683356833668337683386833968340683416834268343683446834568346683476834868349683506835168352683536835468355683566835768358683596836068361683626836368364683656836668367683686836968370683716837268373683746837568376683776837868379683806838168382683836838468385683866838768388683896839068391683926839368394683956839668397683986839968400684016840268403684046840568406684076840868409684106841168412684136841468415684166841768418684196842068421684226842368424684256842668427684286842968430684316843268433684346843568436684376843868439684406844168442684436844468445684466844768448684496845068451684526845368454684556845668457684586845968460684616846268463684646846568466684676846868469684706847168472684736847468475684766847768478684796848068481684826848368484684856848668487684886848968490684916849268493684946849568496684976849868499685006850168502685036850468505685066850768508685096851068511685126851368514685156851668517685186851968520685216852268523685246852568526685276852868529685306853168532685336853468535685366853768538685396854068541685426854368544685456854668547685486854968550685516855268553685546855568556685576855868559685606856168562685636856468565685666856768568685696857068571685726857368574685756857668577685786857968580685816858268583685846858568586685876858868589685906859168592685936859468595685966859768598685996860068601686026860368604686056860668607686086860968610686116861268613686146861568616686176861868619686206862168622686236862468625686266862768628686296863068631686326863368634686356863668637686386863968640686416864268643686446864568646686476864868649686506865168652686536865468655686566865768658686596866068661686626866368664686656866668667686686866968670686716867268673686746867568676686776867868679686806868168682686836868468685686866868768688686896869068691686926869368694686956869668697686986869968700687016870268703687046870568706687076870868709687106871168712687136871468715687166871768718687196872068721687226872368724687256872668727687286872968730687316873268733687346873568736687376873868739687406874168742687436874468745687466874768748687496875068751687526875368754687556875668757687586875968760687616876268763687646876568766687676876868769687706877168772687736877468775687766877768778687796878068781687826878368784687856878668787687886878968790687916879268793687946879568796687976879868799688006880168802688036880468805688066880768808688096881068811688126881368814688156881668817688186881968820688216882268823688246882568826688276882868829688306883168832688336883468835688366883768838688396884068841688426884368844688456884668847688486884968850688516885268853688546885568856688576885868859688606886168862688636886468865688666886768868688696887068871688726887368874688756887668877688786887968880688816888268883688846888568886688876888868889688906889168892688936889468895688966889768898688996890068901689026890368904689056890668907689086890968910689116891268913689146891568916689176891868919689206892168922689236892468925689266892768928689296893068931689326893368934689356893668937689386893968940689416894268943689446894568946689476894868949689506895168952689536895468955689566895768958689596896068961689626896368964689656896668967689686896968970689716897268973689746897568976689776897868979689806898168982689836898468985689866898768988689896899068991689926899368994689956899668997689986899969000690016900269003690046900569006690076900869009690106901169012690136901469015690166901769018690196902069021690226902369024690256902669027690286902969030690316903269033690346903569036690376903869039690406904169042690436904469045690466904769048690496905069051690526905369054690556905669057690586905969060690616906269063690646906569066690676906869069690706907169072690736907469075690766907769078690796908069081690826908369084690856908669087690886908969090690916909269093690946909569096690976909869099691006910169102691036910469105691066910769108691096911069111691126911369114691156911669117691186911969120691216912269123691246912569126691276912869129691306913169132691336913469135691366913769138691396914069141691426914369144691456914669147691486914969150691516915269153691546915569156691576915869159691606916169162691636916469165691666916769168691696917069171691726917369174691756917669177691786917969180691816918269183691846918569186691876918869189691906919169192691936919469195691966919769198691996920069201692026920369204692056920669207692086920969210692116921269213692146921569216692176921869219692206922169222692236922469225692266922769228692296923069231692326923369234692356923669237692386923969240692416924269243692446924569246692476924869249692506925169252692536925469255692566925769258692596926069261692626926369264692656926669267692686926969270692716927269273692746927569276692776927869279692806928169282692836928469285692866928769288692896929069291692926929369294692956929669297692986929969300693016930269303693046930569306693076930869309693106931169312693136931469315693166931769318693196932069321693226932369324693256932669327693286932969330693316933269333693346933569336693376933869339693406934169342693436934469345693466934769348693496935069351693526935369354693556935669357693586935969360693616936269363693646936569366693676936869369693706937169372693736937469375693766937769378693796938069381693826938369384693856938669387693886938969390693916939269393693946939569396693976939869399694006940169402694036940469405694066940769408694096941069411694126941369414694156941669417694186941969420694216942269423694246942569426694276942869429694306943169432694336943469435694366943769438694396944069441694426944369444694456944669447694486944969450694516945269453694546945569456694576945869459694606946169462694636946469465694666946769468694696947069471694726947369474694756947669477694786947969480694816948269483694846948569486694876948869489694906949169492694936949469495694966949769498694996950069501695026950369504695056950669507695086950969510695116951269513695146951569516695176951869519695206952169522695236952469525695266952769528695296953069531695326953369534695356953669537695386953969540695416954269543695446954569546695476954869549695506955169552695536955469555695566955769558695596956069561695626956369564695656956669567695686956969570695716957269573695746957569576695776957869579695806958169582695836958469585695866958769588695896959069591695926959369594695956959669597695986959969600696016960269603696046960569606696076960869609696106961169612696136961469615696166961769618696196962069621696226962369624696256962669627696286962969630696316963269633696346963569636696376963869639696406964169642696436964469645696466964769648696496965069651696526965369654696556965669657696586965969660696616966269663696646966569666696676966869669696706967169672696736967469675696766967769678696796968069681696826968369684696856968669687696886968969690696916969269693696946969569696696976969869699697006970169702697036970469705697066970769708697096971069711697126971369714697156971669717697186971969720697216972269723697246972569726697276972869729697306973169732697336973469735697366973769738697396974069741697426974369744697456974669747697486974969750697516975269753697546975569756697576975869759697606976169762697636976469765697666976769768697696977069771697726977369774697756977669777697786977969780697816978269783697846978569786697876978869789697906979169792697936979469795697966979769798697996980069801698026980369804698056980669807698086980969810698116981269813698146981569816698176981869819698206982169822698236982469825698266982769828698296983069831698326983369834698356983669837698386983969840698416984269843698446984569846698476984869849698506985169852698536985469855698566985769858698596986069861698626986369864698656986669867698686986969870698716987269873698746987569876698776987869879698806988169882698836988469885698866988769888698896989069891698926989369894698956989669897698986989969900699016990269903699046990569906699076990869909699106991169912699136991469915699166991769918699196992069921699226992369924699256992669927699286992969930699316993269933699346993569936699376993869939699406994169942699436994469945699466994769948699496995069951699526995369954699556995669957699586995969960699616996269963699646996569966699676996869969699706997169972699736997469975699766997769978699796998069981699826998369984699856998669987699886998969990699916999269993699946999569996699976999869999700007000170002700037000470005700067000770008700097001070011700127001370014700157001670017700187001970020700217002270023700247002570026700277002870029700307003170032700337003470035700367003770038700397004070041700427004370044700457004670047700487004970050700517005270053700547005570056700577005870059700607006170062700637006470065700667006770068700697007070071700727007370074700757007670077700787007970080700817008270083700847008570086700877008870089700907009170092700937009470095700967009770098700997010070101701027010370104701057010670107701087010970110701117011270113701147011570116701177011870119701207012170122701237012470125701267012770128701297013070131701327013370134701357013670137701387013970140701417014270143701447014570146701477014870149701507015170152701537015470155701567015770158701597016070161701627016370164701657016670167701687016970170701717017270173701747017570176701777017870179701807018170182701837018470185701867018770188701897019070191701927019370194701957019670197701987019970200702017020270203702047020570206702077020870209702107021170212702137021470215702167021770218702197022070221702227022370224702257022670227702287022970230702317023270233702347023570236702377023870239702407024170242702437024470245702467024770248702497025070251702527025370254702557025670257702587025970260702617026270263702647026570266702677026870269702707027170272702737027470275702767027770278702797028070281702827028370284702857028670287702887028970290702917029270293702947029570296702977029870299703007030170302703037030470305703067030770308703097031070311703127031370314703157031670317703187031970320703217032270323703247032570326703277032870329703307033170332703337033470335703367033770338703397034070341703427034370344703457034670347703487034970350703517035270353703547035570356703577035870359703607036170362703637036470365703667036770368703697037070371703727037370374703757037670377703787037970380703817038270383703847038570386703877038870389703907039170392703937039470395703967039770398703997040070401704027040370404704057040670407704087040970410704117041270413704147041570416704177041870419704207042170422704237042470425704267042770428704297043070431704327043370434704357043670437704387043970440704417044270443704447044570446704477044870449704507045170452704537045470455704567045770458704597046070461704627046370464704657046670467704687046970470704717047270473704747047570476704777047870479704807048170482704837048470485704867048770488704897049070491704927049370494704957049670497704987049970500705017050270503705047050570506705077050870509705107051170512705137051470515705167051770518705197052070521705227052370524705257052670527705287052970530705317053270533705347053570536705377053870539705407054170542705437054470545705467054770548705497055070551705527055370554705557055670557705587055970560705617056270563705647056570566705677056870569705707057170572705737057470575705767057770578705797058070581705827058370584705857058670587705887058970590705917059270593705947059570596705977059870599706007060170602706037060470605706067060770608706097061070611706127061370614706157061670617706187061970620706217062270623706247062570626706277062870629706307063170632706337063470635706367063770638706397064070641706427064370644706457064670647706487064970650706517065270653706547065570656706577065870659706607066170662706637066470665706667066770668706697067070671706727067370674706757067670677706787067970680706817068270683706847068570686706877068870689706907069170692706937069470695706967069770698706997070070701707027070370704707057070670707707087070970710707117071270713707147071570716707177071870719707207072170722707237072470725707267072770728707297073070731707327073370734707357073670737707387073970740707417074270743707447074570746707477074870749707507075170752707537075470755707567075770758707597076070761707627076370764707657076670767707687076970770707717077270773707747077570776707777077870779707807078170782707837078470785707867078770788707897079070791707927079370794707957079670797707987079970800708017080270803708047080570806708077080870809708107081170812708137081470815708167081770818708197082070821708227082370824708257082670827708287082970830708317083270833708347083570836708377083870839708407084170842708437084470845708467084770848708497085070851708527085370854708557085670857708587085970860708617086270863708647086570866708677086870869708707087170872708737087470875708767087770878708797088070881708827088370884708857088670887708887088970890708917089270893708947089570896708977089870899709007090170902709037090470905709067090770908709097091070911709127091370914709157091670917709187091970920709217092270923709247092570926709277092870929709307093170932709337093470935709367093770938709397094070941709427094370944709457094670947709487094970950709517095270953709547095570956709577095870959709607096170962709637096470965709667096770968709697097070971709727097370974709757097670977709787097970980709817098270983709847098570986709877098870989709907099170992709937099470995709967099770998709997100071001710027100371004710057100671007710087100971010710117101271013710147101571016710177101871019710207102171022710237102471025710267102771028710297103071031710327103371034710357103671037710387103971040710417104271043710447104571046710477104871049710507105171052710537105471055710567105771058710597106071061710627106371064710657106671067710687106971070710717107271073710747107571076710777107871079710807108171082710837108471085710867108771088710897109071091710927109371094710957109671097710987109971100711017110271103711047110571106711077110871109711107111171112711137111471115711167111771118711197112071121711227112371124711257112671127711287112971130711317113271133711347113571136711377113871139711407114171142711437114471145711467114771148711497115071151711527115371154711557115671157711587115971160711617116271163711647116571166711677116871169711707117171172711737117471175711767117771178711797118071181711827118371184711857118671187711887118971190711917119271193711947119571196711977119871199712007120171202712037120471205712067120771208712097121071211712127121371214712157121671217712187121971220712217122271223712247122571226712277122871229712307123171232712337123471235712367123771238712397124071241712427124371244712457124671247712487124971250712517125271253712547125571256712577125871259712607126171262712637126471265712667126771268712697127071271712727127371274712757127671277712787127971280712817128271283712847128571286712877128871289712907129171292712937129471295712967129771298712997130071301713027130371304713057130671307713087130971310713117131271313713147131571316713177131871319713207132171322713237132471325713267132771328713297133071331713327133371334713357133671337713387133971340713417134271343713447134571346713477134871349713507135171352713537135471355713567135771358713597136071361713627136371364713657136671367713687136971370713717137271373713747137571376713777137871379713807138171382713837138471385713867138771388713897139071391713927139371394713957139671397713987139971400714017140271403714047140571406714077140871409714107141171412714137141471415714167141771418714197142071421714227142371424714257142671427714287142971430714317143271433714347143571436714377143871439714407144171442714437144471445714467144771448714497145071451714527145371454714557145671457714587145971460714617146271463714647146571466714677146871469714707147171472714737147471475714767147771478714797148071481714827148371484714857148671487714887148971490714917149271493714947149571496714977149871499715007150171502715037150471505715067150771508715097151071511715127151371514715157151671517715187151971520715217152271523715247152571526715277152871529715307153171532715337153471535715367153771538715397154071541715427154371544715457154671547715487154971550715517155271553715547155571556715577155871559715607156171562715637156471565715667156771568715697157071571715727157371574715757157671577715787157971580715817158271583715847158571586715877158871589715907159171592715937159471595715967159771598715997160071601716027160371604716057160671607716087160971610716117161271613716147161571616716177161871619716207162171622716237162471625716267162771628716297163071631716327163371634716357163671637716387163971640716417164271643716447164571646716477164871649716507165171652716537165471655716567165771658716597166071661716627166371664716657166671667716687166971670716717167271673716747167571676716777167871679716807168171682716837168471685716867168771688716897169071691716927169371694716957169671697716987169971700717017170271703717047170571706717077170871709717107171171712717137171471715717167171771718717197172071721717227172371724717257172671727717287172971730717317173271733717347173571736717377173871739717407174171742717437174471745717467174771748717497175071751717527175371754717557175671757717587175971760717617176271763717647176571766717677176871769717707177171772717737177471775717767177771778717797178071781717827178371784717857178671787717887178971790717917179271793717947179571796717977179871799718007180171802718037180471805718067180771808718097181071811718127181371814718157181671817718187181971820718217182271823718247182571826718277182871829718307183171832718337183471835718367183771838718397184071841718427184371844718457184671847718487184971850718517185271853718547185571856718577185871859718607186171862718637186471865718667186771868718697187071871718727187371874718757187671877718787187971880718817188271883718847188571886718877188871889718907189171892718937189471895718967189771898718997190071901719027190371904719057190671907719087190971910719117191271913719147191571916719177191871919719207192171922719237192471925719267192771928719297193071931719327193371934719357193671937719387193971940719417194271943719447194571946719477194871949719507195171952719537195471955719567195771958719597196071961719627196371964719657196671967719687196971970719717197271973719747197571976719777197871979719807198171982719837198471985719867198771988719897199071991719927199371994719957199671997719987199972000720017200272003720047200572006720077200872009720107201172012720137201472015720167201772018720197202072021720227202372024720257202672027720287202972030720317203272033720347203572036720377203872039720407204172042720437204472045720467204772048720497205072051720527205372054720557205672057720587205972060720617206272063720647206572066720677206872069720707207172072720737207472075720767207772078720797208072081720827208372084720857208672087720887208972090720917209272093720947209572096720977209872099721007210172102721037210472105721067210772108721097211072111721127211372114721157211672117721187211972120721217212272123721247212572126721277212872129721307213172132721337213472135721367213772138721397214072141721427214372144721457214672147721487214972150721517215272153721547215572156721577215872159721607216172162721637216472165721667216772168721697217072171721727217372174721757217672177721787217972180721817218272183721847218572186721877218872189721907219172192721937219472195721967219772198721997220072201722027220372204722057220672207722087220972210722117221272213722147221572216722177221872219722207222172222722237222472225722267222772228722297223072231722327223372234722357223672237722387223972240722417224272243722447224572246722477224872249722507225172252722537225472255722567225772258722597226072261722627226372264722657226672267722687226972270722717227272273722747227572276722777227872279722807228172282722837228472285722867228772288722897229072291722927229372294722957229672297722987229972300723017230272303723047230572306723077230872309723107231172312723137231472315723167231772318723197232072321723227232372324723257232672327723287232972330723317233272333723347233572336723377233872339723407234172342723437234472345723467234772348723497235072351723527235372354723557235672357723587235972360723617236272363723647236572366723677236872369723707237172372723737237472375723767237772378723797238072381723827238372384723857238672387723887238972390723917239272393723947239572396723977239872399724007240172402724037240472405724067240772408724097241072411724127241372414724157241672417724187241972420724217242272423724247242572426724277242872429724307243172432724337243472435724367243772438724397244072441724427244372444724457244672447724487244972450724517245272453724547245572456724577245872459724607246172462724637246472465724667246772468724697247072471724727247372474724757247672477724787247972480724817248272483724847248572486724877248872489724907249172492724937249472495724967249772498724997250072501725027250372504725057250672507725087250972510725117251272513725147251572516725177251872519725207252172522725237252472525725267252772528725297253072531725327253372534725357253672537725387253972540725417254272543725447254572546725477254872549725507255172552725537255472555725567255772558725597256072561725627256372564725657256672567725687256972570725717257272573725747257572576725777257872579725807258172582725837258472585725867258772588725897259072591725927259372594725957259672597725987259972600726017260272603726047260572606726077260872609726107261172612726137261472615726167261772618726197262072621726227262372624726257262672627726287262972630726317263272633726347263572636726377263872639726407264172642726437264472645726467264772648726497265072651726527265372654726557265672657726587265972660726617266272663726647266572666726677266872669726707267172672726737267472675726767267772678726797268072681726827268372684726857268672687726887268972690726917269272693726947269572696726977269872699727007270172702727037270472705727067270772708727097271072711727127271372714727157271672717727187271972720727217272272723727247272572726727277272872729727307273172732727337273472735727367273772738727397274072741727427274372744727457274672747727487274972750727517275272753727547275572756727577275872759727607276172762727637276472765727667276772768727697277072771727727277372774727757277672777727787277972780727817278272783727847278572786727877278872789727907279172792727937279472795727967279772798727997280072801728027280372804728057280672807728087280972810728117281272813728147281572816728177281872819728207282172822728237282472825728267282772828728297283072831728327283372834728357283672837728387283972840728417284272843728447284572846728477284872849728507285172852728537285472855728567285772858728597286072861728627286372864728657286672867728687286972870728717287272873728747287572876728777287872879728807288172882728837288472885728867288772888728897289072891728927289372894728957289672897728987289972900729017290272903729047290572906729077290872909729107291172912729137291472915729167291772918729197292072921729227292372924729257292672927729287292972930729317293272933729347293572936729377293872939729407294172942729437294472945729467294772948729497295072951729527295372954729557295672957729587295972960729617296272963729647296572966729677296872969729707297172972729737297472975729767297772978729797298072981729827298372984729857298672987729887298972990729917299272993729947299572996729977299872999730007300173002730037300473005730067300773008730097301073011730127301373014730157301673017730187301973020730217302273023730247302573026730277302873029730307303173032730337303473035730367303773038730397304073041730427304373044730457304673047730487304973050730517305273053730547305573056730577305873059730607306173062730637306473065730667306773068730697307073071730727307373074730757307673077730787307973080730817308273083730847308573086730877308873089730907309173092730937309473095730967309773098730997310073101731027310373104731057310673107731087310973110731117311273113731147311573116731177311873119731207312173122731237312473125731267312773128731297313073131731327313373134731357313673137731387313973140731417314273143731447314573146731477314873149731507315173152731537315473155731567315773158731597316073161731627316373164731657316673167731687316973170731717317273173731747317573176731777317873179731807318173182731837318473185731867318773188731897319073191731927319373194731957319673197731987319973200732017320273203732047320573206732077320873209732107321173212732137321473215732167321773218732197322073221732227322373224732257322673227732287322973230732317323273233732347323573236732377323873239732407324173242732437324473245732467324773248732497325073251732527325373254732557325673257732587325973260732617326273263732647326573266732677326873269732707327173272732737327473275732767327773278732797328073281732827328373284732857328673287732887328973290732917329273293732947329573296732977329873299733007330173302733037330473305733067330773308733097331073311733127331373314733157331673317733187331973320733217332273323733247332573326733277332873329733307333173332733337333473335733367333773338733397334073341733427334373344733457334673347733487334973350733517335273353733547335573356733577335873359733607336173362733637336473365733667336773368733697337073371733727337373374733757337673377733787337973380733817338273383733847338573386733877338873389733907339173392733937339473395733967339773398733997340073401734027340373404734057340673407734087340973410734117341273413734147341573416734177341873419734207342173422734237342473425734267342773428734297343073431734327343373434734357343673437734387343973440734417344273443734447344573446734477344873449734507345173452734537345473455734567345773458734597346073461734627346373464734657346673467734687346973470734717347273473734747347573476734777347873479734807348173482734837348473485734867348773488734897349073491734927349373494734957349673497734987349973500735017350273503735047350573506735077350873509735107351173512735137351473515735167351773518735197352073521735227352373524735257352673527735287352973530735317353273533735347353573536735377353873539735407354173542735437354473545735467354773548735497355073551735527355373554735557355673557735587355973560735617356273563735647356573566735677356873569735707357173572735737357473575735767357773578735797358073581735827358373584735857358673587735887358973590735917359273593735947359573596735977359873599736007360173602736037360473605736067360773608736097361073611736127361373614736157361673617736187361973620736217362273623736247362573626736277362873629736307363173632736337363473635736367363773638736397364073641736427364373644736457364673647736487364973650736517365273653736547365573656736577365873659736607366173662736637366473665736667366773668736697367073671736727367373674736757367673677736787367973680736817368273683736847368573686736877368873689736907369173692736937369473695736967369773698736997370073701737027370373704737057370673707737087370973710737117371273713737147371573716737177371873719737207372173722737237372473725737267372773728737297373073731737327373373734737357373673737737387373973740737417374273743737447374573746737477374873749737507375173752737537375473755737567375773758737597376073761737627376373764737657376673767737687376973770737717377273773737747377573776737777377873779737807378173782737837378473785737867378773788737897379073791737927379373794737957379673797737987379973800738017380273803738047380573806738077380873809738107381173812738137381473815738167381773818738197382073821738227382373824738257382673827738287382973830738317383273833738347383573836738377383873839738407384173842738437384473845738467384773848738497385073851738527385373854738557385673857738587385973860738617386273863738647386573866738677386873869738707387173872738737387473875738767387773878738797388073881738827388373884738857388673887738887388973890738917389273893738947389573896738977389873899739007390173902739037390473905739067390773908739097391073911739127391373914739157391673917739187391973920739217392273923739247392573926739277392873929739307393173932739337393473935739367393773938739397394073941739427394373944739457394673947739487394973950739517395273953739547395573956739577395873959739607396173962739637396473965739667396773968739697397073971739727397373974739757397673977739787397973980739817398273983739847398573986739877398873989739907399173992739937399473995739967399773998739997400074001740027400374004740057400674007740087400974010740117401274013740147401574016740177401874019740207402174022740237402474025740267402774028740297403074031740327403374034740357403674037740387403974040740417404274043740447404574046740477404874049740507405174052740537405474055740567405774058740597406074061740627406374064740657406674067740687406974070740717407274073740747407574076740777407874079740807408174082740837408474085740867408774088740897409074091740927409374094740957409674097740987409974100741017410274103741047410574106741077410874109741107411174112741137411474115741167411774118741197412074121741227412374124741257412674127741287412974130741317413274133741347413574136741377413874139741407414174142741437414474145741467414774148741497415074151741527415374154741557415674157741587415974160741617416274163741647416574166741677416874169741707417174172741737417474175741767417774178741797418074181741827418374184741857418674187741887418974190741917419274193741947419574196741977419874199742007420174202742037420474205742067420774208742097421074211742127421374214742157421674217742187421974220742217422274223742247422574226742277422874229742307423174232742337423474235742367423774238742397424074241742427424374244742457424674247742487424974250742517425274253742547425574256742577425874259742607426174262742637426474265742667426774268742697427074271742727427374274742757427674277742787427974280742817428274283742847428574286742877428874289742907429174292742937429474295742967429774298742997430074301743027430374304743057430674307743087430974310743117431274313743147431574316743177431874319743207432174322743237432474325743267432774328743297433074331743327433374334743357433674337743387433974340743417434274343743447434574346743477434874349743507435174352743537435474355743567435774358743597436074361743627436374364743657436674367743687436974370743717437274373743747437574376743777437874379743807438174382743837438474385743867438774388743897439074391743927439374394743957439674397743987439974400744017440274403744047440574406744077440874409744107441174412744137441474415744167441774418744197442074421744227442374424744257442674427744287442974430744317443274433744347443574436744377443874439744407444174442744437444474445744467444774448744497445074451744527445374454744557445674457744587445974460744617446274463744647446574466744677446874469744707447174472744737447474475744767447774478744797448074481744827448374484744857448674487744887448974490744917449274493744947449574496744977449874499745007450174502745037450474505745067450774508745097451074511745127451374514745157451674517745187451974520745217452274523745247452574526745277452874529745307453174532745337453474535745367453774538745397454074541745427454374544745457454674547745487454974550745517455274553745547455574556745577455874559745607456174562745637456474565745667456774568745697457074571745727457374574745757457674577745787457974580745817458274583745847458574586745877458874589745907459174592745937459474595745967459774598745997460074601746027460374604746057460674607746087460974610746117461274613746147461574616746177461874619746207462174622746237462474625746267462774628746297463074631746327463374634746357463674637746387463974640746417464274643746447464574646746477464874649746507465174652746537465474655746567465774658746597466074661746627466374664746657466674667746687466974670746717467274673746747467574676746777467874679746807468174682746837468474685746867468774688746897469074691746927469374694746957469674697746987469974700747017470274703747047470574706747077470874709747107471174712747137471474715747167471774718747197472074721747227472374724747257472674727747287472974730747317473274733747347473574736747377473874739747407474174742747437474474745747467474774748747497475074751747527475374754747557475674757747587475974760747617476274763747647476574766747677476874769747707477174772747737477474775747767477774778747797478074781747827478374784747857478674787747887478974790747917479274793747947479574796747977479874799748007480174802748037480474805748067480774808748097481074811748127481374814748157481674817748187481974820748217482274823748247482574826748277482874829748307483174832748337483474835748367483774838748397484074841748427484374844748457484674847748487484974850748517485274853748547485574856748577485874859748607486174862748637486474865748667486774868748697487074871748727487374874748757487674877748787487974880748817488274883748847488574886748877488874889748907489174892748937489474895748967489774898748997490074901749027490374904749057490674907749087490974910749117491274913749147491574916749177491874919749207492174922749237492474925749267492774928749297493074931749327493374934749357493674937749387493974940749417494274943749447494574946749477494874949749507495174952749537495474955749567495774958749597496074961749627496374964749657496674967749687496974970749717497274973749747497574976749777497874979749807498174982749837498474985749867498774988749897499074991749927499374994749957499674997749987499975000750017500275003750047500575006750077500875009750107501175012750137501475015750167501775018750197502075021750227502375024750257502675027750287502975030750317503275033750347503575036750377503875039750407504175042750437504475045750467504775048750497505075051750527505375054750557505675057750587505975060750617506275063750647506575066750677506875069750707507175072750737507475075750767507775078750797508075081750827508375084750857508675087750887508975090750917509275093750947509575096750977509875099751007510175102751037510475105751067510775108751097511075111751127511375114751157511675117751187511975120751217512275123751247512575126751277512875129751307513175132751337513475135751367513775138751397514075141751427514375144751457514675147751487514975150751517515275153751547515575156751577515875159751607516175162751637516475165751667516775168751697517075171751727517375174751757517675177751787517975180751817518275183751847518575186751877518875189751907519175192751937519475195751967519775198751997520075201752027520375204752057520675207752087520975210752117521275213752147521575216752177521875219752207522175222752237522475225752267522775228752297523075231752327523375234752357523675237752387523975240752417524275243752447524575246752477524875249752507525175252752537525475255752567525775258752597526075261752627526375264752657526675267752687526975270752717527275273752747527575276752777527875279752807528175282752837528475285752867528775288752897529075291752927529375294752957529675297752987529975300753017530275303753047530575306753077530875309753107531175312753137531475315753167531775318753197532075321753227532375324753257532675327753287532975330753317533275333753347533575336753377533875339753407534175342753437534475345753467534775348753497535075351753527535375354753557535675357753587535975360753617536275363753647536575366753677536875369753707537175372753737537475375753767537775378753797538075381753827538375384753857538675387753887538975390753917539275393753947539575396753977539875399754007540175402754037540475405754067540775408754097541075411754127541375414754157541675417754187541975420754217542275423754247542575426754277542875429754307543175432754337543475435754367543775438754397544075441754427544375444754457544675447754487544975450754517545275453754547545575456754577545875459754607546175462754637546475465754667546775468754697547075471754727547375474754757547675477754787547975480754817548275483754847548575486754877548875489754907549175492754937549475495754967549775498754997550075501755027550375504755057550675507755087550975510755117551275513755147551575516755177551875519755207552175522755237552475525755267552775528755297553075531755327553375534755357553675537755387553975540755417554275543755447554575546755477554875549755507555175552755537555475555755567555775558755597556075561755627556375564755657556675567755687556975570755717557275573755747557575576755777557875579755807558175582755837558475585755867558775588755897559075591755927559375594755957559675597755987559975600756017560275603756047560575606756077560875609756107561175612756137561475615756167561775618756197562075621756227562375624756257562675627756287562975630756317563275633756347563575636756377563875639756407564175642756437564475645756467564775648756497565075651756527565375654756557565675657756587565975660756617566275663756647566575666756677566875669756707567175672756737567475675756767567775678756797568075681756827568375684756857568675687756887568975690756917569275693756947569575696756977569875699757007570175702757037570475705757067570775708757097571075711757127571375714757157571675717757187571975720757217572275723757247572575726757277572875729757307573175732757337573475735757367573775738757397574075741757427574375744757457574675747757487574975750757517575275753757547575575756757577575875759757607576175762757637576475765757667576775768757697577075771757727577375774757757577675777757787577975780757817578275783757847578575786757877578875789757907579175792757937579475795757967579775798757997580075801758027580375804758057580675807758087580975810758117581275813758147581575816758177581875819758207582175822758237582475825758267582775828758297583075831758327583375834758357583675837758387583975840758417584275843758447584575846758477584875849758507585175852758537585475855758567585775858758597586075861758627586375864758657586675867758687586975870758717587275873758747587575876758777587875879758807588175882758837588475885758867588775888758897589075891758927589375894758957589675897758987589975900759017590275903759047590575906759077590875909759107591175912759137591475915759167591775918759197592075921759227592375924759257592675927759287592975930759317593275933759347593575936759377593875939759407594175942759437594475945759467594775948759497595075951759527595375954759557595675957759587595975960759617596275963759647596575966759677596875969759707597175972759737597475975759767597775978759797598075981759827598375984759857598675987759887598975990759917599275993759947599575996759977599875999760007600176002760037600476005760067600776008760097601076011760127601376014760157601676017760187601976020760217602276023760247602576026760277602876029760307603176032760337603476035760367603776038760397604076041760427604376044760457604676047760487604976050760517605276053760547605576056760577605876059760607606176062760637606476065760667606776068760697607076071760727607376074760757607676077760787607976080760817608276083760847608576086760877608876089760907609176092760937609476095760967609776098760997610076101761027610376104761057610676107761087610976110761117611276113761147611576116761177611876119761207612176122761237612476125761267612776128761297613076131761327613376134761357613676137761387613976140761417614276143761447614576146761477614876149761507615176152761537615476155761567615776158761597616076161761627616376164761657616676167761687616976170761717617276173761747617576176761777617876179761807618176182761837618476185761867618776188761897619076191761927619376194761957619676197761987619976200762017620276203762047620576206762077620876209762107621176212762137621476215762167621776218762197622076221762227622376224762257622676227762287622976230762317623276233762347623576236762377623876239762407624176242762437624476245762467624776248762497625076251762527625376254762557625676257762587625976260762617626276263762647626576266762677626876269762707627176272762737627476275762767627776278762797628076281762827628376284762857628676287762887628976290762917629276293762947629576296762977629876299763007630176302763037630476305763067630776308763097631076311763127631376314763157631676317763187631976320763217632276323763247632576326763277632876329763307633176332763337633476335763367633776338763397634076341763427634376344763457634676347763487634976350763517635276353763547635576356763577635876359763607636176362763637636476365763667636776368763697637076371763727637376374763757637676377763787637976380763817638276383763847638576386763877638876389763907639176392763937639476395763967639776398763997640076401764027640376404764057640676407764087640976410764117641276413764147641576416764177641876419764207642176422764237642476425764267642776428764297643076431764327643376434764357643676437764387643976440764417644276443764447644576446764477644876449764507645176452764537645476455764567645776458764597646076461764627646376464764657646676467764687646976470764717647276473764747647576476764777647876479764807648176482764837648476485764867648776488764897649076491764927649376494764957649676497764987649976500765017650276503765047650576506765077650876509765107651176512765137651476515765167651776518765197652076521765227652376524765257652676527765287652976530765317653276533765347653576536765377653876539765407654176542765437654476545765467654776548765497655076551765527655376554765557655676557765587655976560765617656276563765647656576566765677656876569765707657176572765737657476575765767657776578765797658076581765827658376584765857658676587765887658976590765917659276593765947659576596765977659876599766007660176602766037660476605766067660776608766097661076611766127661376614766157661676617766187661976620766217662276623766247662576626766277662876629766307663176632766337663476635766367663776638766397664076641766427664376644766457664676647766487664976650766517665276653766547665576656766577665876659766607666176662766637666476665766667666776668766697667076671766727667376674766757667676677766787667976680766817668276683766847668576686766877668876689766907669176692766937669476695766967669776698766997670076701767027670376704767057670676707767087670976710767117671276713767147671576716767177671876719767207672176722767237672476725767267672776728767297673076731767327673376734767357673676737767387673976740767417674276743767447674576746767477674876749767507675176752767537675476755767567675776758767597676076761767627676376764767657676676767767687676976770767717677276773767747677576776767777677876779767807678176782767837678476785767867678776788767897679076791767927679376794767957679676797767987679976800768017680276803768047680576806768077680876809768107681176812768137681476815768167681776818768197682076821768227682376824768257682676827768287682976830768317683276833768347683576836768377683876839768407684176842768437684476845768467684776848768497685076851768527685376854768557685676857768587685976860768617686276863768647686576866768677686876869768707687176872768737687476875768767687776878768797688076881768827688376884768857688676887768887688976890768917689276893768947689576896768977689876899769007690176902769037690476905769067690776908769097691076911769127691376914769157691676917769187691976920769217692276923769247692576926769277692876929769307693176932769337693476935769367693776938769397694076941769427694376944769457694676947769487694976950769517695276953769547695576956769577695876959769607696176962769637696476965769667696776968769697697076971769727697376974769757697676977769787697976980769817698276983769847698576986769877698876989769907699176992769937699476995769967699776998769997700077001770027700377004770057700677007770087700977010770117701277013770147701577016770177701877019770207702177022770237702477025770267702777028770297703077031770327703377034770357703677037770387703977040770417704277043770447704577046770477704877049770507705177052770537705477055770567705777058770597706077061770627706377064770657706677067770687706977070770717707277073770747707577076770777707877079770807708177082770837708477085770867708777088770897709077091770927709377094770957709677097770987709977100771017710277103771047710577106771077710877109771107711177112771137711477115771167711777118771197712077121771227712377124771257712677127771287712977130771317713277133771347713577136771377713877139771407714177142771437714477145771467714777148771497715077151771527715377154771557715677157771587715977160771617716277163771647716577166771677716877169771707717177172771737717477175771767717777178771797718077181771827718377184771857718677187771887718977190771917719277193771947719577196771977719877199772007720177202772037720477205772067720777208772097721077211772127721377214772157721677217772187721977220772217722277223772247722577226772277722877229772307723177232772337723477235772367723777238772397724077241772427724377244772457724677247772487724977250772517725277253772547725577256772577725877259772607726177262772637726477265772667726777268772697727077271772727727377274772757727677277772787727977280772817728277283772847728577286772877728877289772907729177292772937729477295772967729777298772997730077301773027730377304773057730677307773087730977310773117731277313773147731577316773177731877319773207732177322773237732477325773267732777328773297733077331773327733377334773357733677337773387733977340773417734277343773447734577346773477734877349773507735177352773537735477355773567735777358773597736077361773627736377364773657736677367773687736977370773717737277373773747737577376773777737877379773807738177382773837738477385773867738777388773897739077391773927739377394773957739677397773987739977400774017740277403774047740577406774077740877409774107741177412774137741477415774167741777418774197742077421774227742377424774257742677427774287742977430774317743277433774347743577436774377743877439774407744177442774437744477445774467744777448774497745077451774527745377454774557745677457774587745977460774617746277463774647746577466774677746877469774707747177472774737747477475774767747777478774797748077481774827748377484774857748677487774887748977490774917749277493774947749577496774977749877499775007750177502775037750477505775067750777508775097751077511775127751377514775157751677517775187751977520775217752277523775247752577526775277752877529775307753177532775337753477535775367753777538775397754077541775427754377544775457754677547775487754977550775517755277553775547755577556775577755877559775607756177562775637756477565775667756777568775697757077571775727757377574775757757677577775787757977580775817758277583775847758577586775877758877589775907759177592775937759477595775967759777598775997760077601776027760377604776057760677607776087760977610776117761277613776147761577616776177761877619776207762177622776237762477625776267762777628776297763077631776327763377634776357763677637776387763977640776417764277643776447764577646776477764877649776507765177652776537765477655776567765777658776597766077661776627766377664776657766677667776687766977670776717767277673776747767577676776777767877679776807768177682776837768477685776867768777688776897769077691776927769377694776957769677697776987769977700777017770277703777047770577706777077770877709777107771177712777137771477715777167771777718777197772077721777227772377724777257772677727777287772977730777317773277733777347773577736777377773877739777407774177742777437774477745777467774777748777497775077751777527775377754777557775677757777587775977760777617776277763777647776577766777677776877769777707777177772777737777477775777767777777778777797778077781777827778377784777857778677787777887778977790777917779277793777947779577796777977779877799778007780177802778037780477805778067780777808778097781077811778127781377814778157781677817778187781977820778217782277823778247782577826778277782877829778307783177832778337783477835778367783777838778397784077841778427784377844778457784677847778487784977850778517785277853778547785577856778577785877859778607786177862778637786477865778667786777868778697787077871778727787377874778757787677877778787787977880778817788277883778847788577886778877788877889778907789177892778937789477895778967789777898778997790077901779027790377904779057790677907779087790977910779117791277913779147791577916779177791877919779207792177922779237792477925779267792777928779297793077931779327793377934779357793677937779387793977940779417794277943779447794577946779477794877949779507795177952779537795477955779567795777958779597796077961779627796377964779657796677967779687796977970779717797277973779747797577976779777797877979779807798177982779837798477985779867798777988779897799077991779927799377994779957799677997779987799978000780017800278003780047800578006780077800878009780107801178012780137801478015780167801778018780197802078021780227802378024780257802678027780287802978030780317803278033780347803578036780377803878039780407804178042780437804478045780467804778048780497805078051780527805378054780557805678057780587805978060780617806278063780647806578066780677806878069780707807178072780737807478075780767807778078780797808078081780827808378084780857808678087780887808978090780917809278093780947809578096780977809878099781007810178102781037810478105781067810778108781097811078111781127811378114781157811678117781187811978120781217812278123781247812578126781277812878129781307813178132781337813478135781367813778138781397814078141781427814378144781457814678147781487814978150781517815278153781547815578156781577815878159781607816178162781637816478165781667816778168781697817078171781727817378174781757817678177781787817978180781817818278183781847818578186781877818878189781907819178192781937819478195781967819778198781997820078201782027820378204782057820678207782087820978210782117821278213782147821578216782177821878219782207822178222782237822478225782267822778228782297823078231782327823378234782357823678237782387823978240782417824278243782447824578246782477824878249782507825178252782537825478255782567825778258782597826078261782627826378264782657826678267782687826978270782717827278273782747827578276782777827878279782807828178282782837828478285782867828778288782897829078291782927829378294782957829678297782987829978300783017830278303783047830578306783077830878309783107831178312783137831478315783167831778318783197832078321783227832378324783257832678327783287832978330783317833278333783347833578336783377833878339783407834178342783437834478345783467834778348783497835078351783527835378354783557835678357783587835978360783617836278363783647836578366783677836878369783707837178372783737837478375783767837778378783797838078381783827838378384783857838678387783887838978390783917839278393783947839578396783977839878399784007840178402784037840478405784067840778408784097841078411784127841378414784157841678417784187841978420784217842278423784247842578426784277842878429784307843178432784337843478435784367843778438784397844078441784427844378444784457844678447784487844978450784517845278453784547845578456784577845878459784607846178462784637846478465784667846778468784697847078471784727847378474784757847678477784787847978480784817848278483784847848578486784877848878489784907849178492784937849478495784967849778498784997850078501785027850378504785057850678507785087850978510785117851278513785147851578516785177851878519785207852178522785237852478525785267852778528785297853078531785327853378534785357853678537785387853978540785417854278543785447854578546785477854878549785507855178552785537855478555785567855778558785597856078561785627856378564785657856678567785687856978570785717857278573785747857578576785777857878579785807858178582785837858478585785867858778588785897859078591785927859378594785957859678597785987859978600786017860278603786047860578606786077860878609786107861178612786137861478615786167861778618786197862078621786227862378624786257862678627786287862978630786317863278633786347863578636786377863878639786407864178642786437864478645786467864778648786497865078651786527865378654786557865678657786587865978660786617866278663786647866578666786677866878669786707867178672786737867478675786767867778678786797868078681786827868378684786857868678687786887868978690786917869278693786947869578696786977869878699787007870178702787037870478705787067870778708787097871078711787127871378714787157871678717787187871978720787217872278723787247872578726787277872878729787307873178732787337873478735787367873778738787397874078741787427874378744787457874678747787487874978750787517875278753787547875578756787577875878759787607876178762787637876478765787667876778768787697877078771787727877378774787757877678777787787877978780787817878278783787847878578786787877878878789787907879178792787937879478795787967879778798787997880078801788027880378804788057880678807788087880978810788117881278813788147881578816788177881878819788207882178822788237882478825788267882778828788297883078831788327883378834788357883678837788387883978840788417884278843788447884578846788477884878849788507885178852788537885478855788567885778858788597886078861788627886378864788657886678867788687886978870788717887278873788747887578876788777887878879788807888178882788837888478885788867888778888788897889078891788927889378894788957889678897788987889978900789017890278903789047890578906789077890878909789107891178912789137891478915789167891778918789197892078921789227892378924789257892678927789287892978930789317893278933789347893578936789377893878939789407894178942789437894478945789467894778948789497895078951789527895378954789557895678957789587895978960789617896278963789647896578966789677896878969789707897178972789737897478975789767897778978789797898078981789827898378984789857898678987789887898978990789917899278993789947899578996789977899878999790007900179002790037900479005790067900779008790097901079011790127901379014790157901679017790187901979020790217902279023790247902579026790277902879029790307903179032790337903479035790367903779038790397904079041790427904379044790457904679047790487904979050790517905279053790547905579056790577905879059790607906179062790637906479065790667906779068790697907079071790727907379074790757907679077790787907979080790817908279083790847908579086790877908879089790907909179092790937909479095790967909779098790997910079101791027910379104791057910679107791087910979110791117911279113791147911579116791177911879119791207912179122791237912479125791267912779128791297913079131791327913379134791357913679137791387913979140791417914279143791447914579146791477914879149791507915179152791537915479155791567915779158791597916079161791627916379164791657916679167791687916979170791717917279173791747917579176791777917879179791807918179182791837918479185791867918779188791897919079191791927919379194791957919679197791987919979200792017920279203792047920579206792077920879209792107921179212792137921479215792167921779218792197922079221792227922379224792257922679227792287922979230792317923279233792347923579236792377923879239792407924179242792437924479245792467924779248792497925079251792527925379254792557925679257792587925979260792617926279263792647926579266792677926879269792707927179272792737927479275792767927779278792797928079281792827928379284792857928679287792887928979290792917929279293792947929579296792977929879299793007930179302793037930479305793067930779308793097931079311793127931379314793157931679317793187931979320793217932279323793247932579326793277932879329793307933179332793337933479335793367933779338793397934079341793427934379344793457934679347793487934979350793517935279353793547935579356793577935879359793607936179362793637936479365793667936779368793697937079371793727937379374793757937679377793787937979380793817938279383793847938579386793877938879389793907939179392793937939479395793967939779398793997940079401794027940379404794057940679407794087940979410794117941279413794147941579416794177941879419794207942179422794237942479425794267942779428794297943079431794327943379434794357943679437794387943979440794417944279443794447944579446794477944879449794507945179452794537945479455794567945779458794597946079461794627946379464794657946679467794687946979470794717947279473794747947579476794777947879479794807948179482794837948479485794867948779488794897949079491794927949379494794957949679497794987949979500795017950279503795047950579506795077950879509795107951179512795137951479515795167951779518795197952079521795227952379524795257952679527795287952979530795317953279533795347953579536795377953879539795407954179542795437954479545795467954779548795497955079551795527955379554795557955679557795587955979560795617956279563795647956579566795677956879569795707957179572795737957479575795767957779578795797958079581795827958379584795857958679587795887958979590795917959279593795947959579596795977959879599796007960179602796037960479605796067960779608796097961079611796127961379614796157961679617796187961979620796217962279623796247962579626796277962879629796307963179632796337963479635796367963779638796397964079641796427964379644796457964679647796487964979650796517965279653796547965579656796577965879659796607966179662796637966479665796667966779668796697967079671796727967379674796757967679677796787967979680796817968279683796847968579686796877968879689796907969179692796937969479695796967969779698796997970079701797027970379704797057970679707797087970979710797117971279713797147971579716797177971879719797207972179722797237972479725797267972779728797297973079731797327973379734797357973679737797387973979740797417974279743797447974579746797477974879749797507975179752797537975479755797567975779758797597976079761797627976379764797657976679767797687976979770797717977279773797747977579776797777977879779797807978179782797837978479785797867978779788797897979079791797927979379794797957979679797797987979979800798017980279803798047980579806798077980879809798107981179812798137981479815798167981779818798197982079821798227982379824798257982679827798287982979830798317983279833798347983579836798377983879839798407984179842798437984479845798467984779848798497985079851798527985379854798557985679857798587985979860798617986279863798647986579866798677986879869798707987179872798737987479875798767987779878798797988079881798827988379884798857988679887798887988979890798917989279893798947989579896798977989879899799007990179902799037990479905799067990779908799097991079911799127991379914799157991679917799187991979920799217992279923799247992579926799277992879929799307993179932799337993479935799367993779938799397994079941799427994379944799457994679947799487994979950799517995279953799547995579956799577995879959799607996179962799637996479965799667996779968799697997079971799727997379974799757997679977799787997979980799817998279983799847998579986799877998879989799907999179992799937999479995799967999779998799998000080001800028000380004800058000680007800088000980010800118001280013800148001580016800178001880019800208002180022800238002480025800268002780028800298003080031800328003380034800358003680037800388003980040800418004280043800448004580046800478004880049800508005180052800538005480055800568005780058800598006080061800628006380064800658006680067800688006980070800718007280073800748007580076800778007880079800808008180082800838008480085800868008780088800898009080091800928009380094800958009680097800988009980100801018010280103801048010580106801078010880109801108011180112801138011480115801168011780118801198012080121801228012380124801258012680127801288012980130801318013280133801348013580136801378013880139801408014180142801438014480145801468014780148801498015080151801528015380154801558015680157801588015980160801618016280163801648016580166801678016880169801708017180172801738017480175801768017780178801798018080181801828018380184801858018680187801888018980190801918019280193801948019580196801978019880199802008020180202802038020480205802068020780208802098021080211802128021380214802158021680217802188021980220802218022280223802248022580226802278022880229802308023180232802338023480235802368023780238802398024080241802428024380244802458024680247802488024980250802518025280253802548025580256802578025880259802608026180262802638026480265802668026780268802698027080271802728027380274802758027680277802788027980280802818028280283802848028580286802878028880289802908029180292802938029480295802968029780298802998030080301803028030380304803058030680307803088030980310803118031280313803148031580316803178031880319803208032180322803238032480325803268032780328803298033080331803328033380334803358033680337803388033980340803418034280343803448034580346803478034880349803508035180352803538035480355803568035780358803598036080361803628036380364803658036680367803688036980370803718037280373803748037580376803778037880379803808038180382803838038480385803868038780388803898039080391803928039380394803958039680397803988039980400804018040280403804048040580406804078040880409804108041180412804138041480415804168041780418804198042080421804228042380424804258042680427804288042980430804318043280433804348043580436804378043880439804408044180442804438044480445804468044780448804498045080451804528045380454804558045680457804588045980460804618046280463804648046580466804678046880469804708047180472804738047480475804768047780478804798048080481804828048380484804858048680487804888048980490804918049280493804948049580496804978049880499805008050180502805038050480505805068050780508805098051080511805128051380514805158051680517805188051980520805218052280523805248052580526805278052880529805308053180532805338053480535805368053780538805398054080541805428054380544805458054680547805488054980550805518055280553805548055580556805578055880559805608056180562805638056480565805668056780568805698057080571805728057380574805758057680577805788057980580805818058280583805848058580586805878058880589805908059180592805938059480595805968059780598805998060080601806028060380604806058060680607806088060980610806118061280613806148061580616806178061880619806208062180622806238062480625806268062780628806298063080631806328063380634806358063680637806388063980640806418064280643806448064580646806478064880649806508065180652806538065480655806568065780658806598066080661806628066380664806658066680667806688066980670806718067280673806748067580676806778067880679806808068180682806838068480685806868068780688806898069080691806928069380694806958069680697806988069980700807018070280703807048070580706807078070880709807108071180712807138071480715807168071780718807198072080721807228072380724807258072680727807288072980730807318073280733807348073580736807378073880739807408074180742807438074480745807468074780748807498075080751807528075380754807558075680757807588075980760807618076280763807648076580766807678076880769807708077180772807738077480775807768077780778807798078080781807828078380784807858078680787807888078980790807918079280793807948079580796807978079880799808008080180802808038080480805808068080780808808098081080811808128081380814808158081680817808188081980820808218082280823808248082580826808278082880829808308083180832808338083480835808368083780838808398084080841808428084380844808458084680847808488084980850808518085280853808548085580856808578085880859808608086180862808638086480865808668086780868808698087080871808728087380874808758087680877808788087980880808818088280883808848088580886808878088880889808908089180892808938089480895808968089780898808998090080901809028090380904809058090680907809088090980910809118091280913809148091580916809178091880919809208092180922809238092480925809268092780928809298093080931809328093380934809358093680937809388093980940809418094280943809448094580946809478094880949809508095180952809538095480955809568095780958809598096080961809628096380964809658096680967809688096980970809718097280973809748097580976809778097880979809808098180982809838098480985809868098780988809898099080991809928099380994809958099680997809988099981000810018100281003810048100581006810078100881009810108101181012810138101481015810168101781018810198102081021810228102381024810258102681027810288102981030810318103281033810348103581036810378103881039810408104181042810438104481045810468104781048810498105081051810528105381054810558105681057810588105981060810618106281063810648106581066810678106881069810708107181072810738107481075810768107781078810798108081081810828108381084810858108681087810888108981090810918109281093810948109581096810978109881099811008110181102811038110481105811068110781108811098111081111811128111381114811158111681117811188111981120811218112281123811248112581126811278112881129811308113181132811338113481135811368113781138811398114081141811428114381144811458114681147811488114981150811518115281153811548115581156811578115881159811608116181162811638116481165811668116781168811698117081171811728117381174811758117681177811788117981180811818118281183811848118581186811878118881189811908119181192811938119481195811968119781198811998120081201812028120381204812058120681207812088120981210812118121281213812148121581216812178121881219812208122181222812238122481225812268122781228812298123081231812328123381234812358123681237812388123981240812418124281243812448124581246812478124881249812508125181252812538125481255812568125781258812598126081261812628126381264812658126681267812688126981270812718127281273812748127581276812778127881279812808128181282812838128481285812868128781288812898129081291812928129381294812958129681297812988129981300813018130281303813048130581306813078130881309813108131181312813138131481315813168131781318813198132081321813228132381324813258132681327813288132981330813318133281333813348133581336813378133881339813408134181342813438134481345813468134781348813498135081351813528135381354813558135681357813588135981360813618136281363813648136581366813678136881369813708137181372813738137481375813768137781378813798138081381813828138381384813858138681387813888138981390813918139281393813948139581396813978139881399814008140181402814038140481405814068140781408814098141081411814128141381414814158141681417814188141981420814218142281423814248142581426814278142881429814308143181432814338143481435814368143781438814398144081441814428144381444814458144681447814488144981450814518145281453814548145581456814578145881459814608146181462814638146481465814668146781468814698147081471814728147381474814758147681477814788147981480814818148281483814848148581486814878148881489814908149181492814938149481495814968149781498814998150081501815028150381504815058150681507815088150981510815118151281513815148151581516815178151881519815208152181522815238152481525815268152781528815298153081531815328153381534815358153681537815388153981540815418154281543815448154581546815478154881549815508155181552815538155481555815568155781558815598156081561815628156381564815658156681567815688156981570815718157281573815748157581576815778157881579815808158181582815838158481585815868158781588815898159081591815928159381594815958159681597815988159981600816018160281603816048160581606816078160881609816108161181612816138161481615816168161781618816198162081621816228162381624816258162681627816288162981630816318163281633816348163581636816378163881639816408164181642816438164481645816468164781648816498165081651816528165381654816558165681657816588165981660816618166281663816648166581666816678166881669816708167181672816738167481675816768167781678816798168081681816828168381684816858168681687816888168981690816918169281693816948169581696816978169881699817008170181702817038170481705817068170781708817098171081711817128171381714817158171681717817188171981720817218172281723817248172581726817278172881729817308173181732817338173481735817368173781738817398174081741817428174381744817458174681747817488174981750817518175281753817548175581756817578175881759817608176181762817638176481765817668176781768817698177081771817728177381774817758177681777817788177981780817818178281783817848178581786817878178881789817908179181792817938179481795817968179781798817998180081801818028180381804818058180681807818088180981810818118181281813818148181581816818178181881819818208182181822818238182481825818268182781828818298183081831818328183381834818358183681837818388183981840818418184281843818448184581846818478184881849818508185181852818538185481855818568185781858818598186081861818628186381864818658186681867818688186981870818718187281873818748187581876818778187881879818808188181882818838188481885818868188781888818898189081891818928189381894818958189681897818988189981900819018190281903819048190581906819078190881909819108191181912819138191481915819168191781918819198192081921819228192381924819258192681927819288192981930819318193281933819348193581936819378193881939819408194181942819438194481945819468194781948819498195081951819528195381954819558195681957819588195981960819618196281963819648196581966819678196881969819708197181972819738197481975819768197781978819798198081981819828198381984819858198681987819888198981990819918199281993819948199581996819978199881999820008200182002820038200482005820068200782008820098201082011820128201382014820158201682017820188201982020820218202282023820248202582026820278202882029820308203182032820338203482035820368203782038820398204082041820428204382044820458204682047820488204982050820518205282053820548205582056820578205882059820608206182062820638206482065820668206782068820698207082071820728207382074820758207682077820788207982080820818208282083820848208582086820878208882089820908209182092820938209482095820968209782098820998210082101821028210382104821058210682107821088210982110821118211282113821148211582116821178211882119821208212182122821238212482125821268212782128821298213082131821328213382134821358213682137821388213982140821418214282143821448214582146821478214882149821508215182152821538215482155821568215782158821598216082161821628216382164821658216682167821688216982170821718217282173821748217582176821778217882179821808218182182821838218482185821868218782188821898219082191821928219382194821958219682197821988219982200822018220282203822048220582206822078220882209822108221182212822138221482215822168221782218822198222082221822228222382224822258222682227822288222982230822318223282233822348223582236822378223882239822408224182242822438224482245822468224782248822498225082251822528225382254822558225682257822588225982260822618226282263822648226582266822678226882269822708227182272822738227482275822768227782278822798228082281822828228382284822858228682287822888228982290822918229282293822948229582296822978229882299823008230182302823038230482305823068230782308823098231082311823128231382314823158231682317823188231982320823218232282323823248232582326823278232882329823308233182332823338233482335823368233782338823398234082341823428234382344823458234682347823488234982350823518235282353823548235582356823578235882359823608236182362823638236482365823668236782368823698237082371823728237382374823758237682377823788237982380823818238282383823848238582386823878238882389823908239182392823938239482395823968239782398823998240082401824028240382404824058240682407824088240982410824118241282413824148241582416824178241882419824208242182422824238242482425824268242782428824298243082431824328243382434824358243682437824388243982440824418244282443824448244582446824478244882449824508245182452824538245482455824568245782458824598246082461824628246382464824658246682467824688246982470824718247282473824748247582476824778247882479824808248182482824838248482485824868248782488824898249082491824928249382494824958249682497824988249982500825018250282503825048250582506825078250882509825108251182512825138251482515825168251782518825198252082521825228252382524825258252682527825288252982530825318253282533825348253582536825378253882539825408254182542825438254482545825468254782548825498255082551825528255382554825558255682557825588255982560825618256282563825648256582566825678256882569825708257182572825738257482575825768257782578825798258082581825828258382584825858258682587825888258982590825918259282593825948259582596825978259882599826008260182602826038260482605826068260782608826098261082611826128261382614826158261682617826188261982620826218262282623826248262582626826278262882629826308263182632826338263482635826368263782638826398264082641826428264382644826458264682647826488264982650826518265282653826548265582656826578265882659826608266182662826638266482665826668266782668826698267082671826728267382674826758267682677826788267982680826818268282683826848268582686826878268882689826908269182692826938269482695826968269782698826998270082701827028270382704827058270682707827088270982710827118271282713827148271582716827178271882719827208272182722827238272482725827268272782728827298273082731827328273382734827358273682737827388273982740827418274282743827448274582746827478274882749827508275182752827538275482755827568275782758827598276082761827628276382764827658276682767827688276982770827718277282773827748277582776827778277882779827808278182782827838278482785827868278782788827898279082791827928279382794827958279682797827988279982800828018280282803828048280582806828078280882809828108281182812828138281482815828168281782818828198282082821828228282382824828258282682827828288282982830828318283282833828348283582836828378283882839828408284182842828438284482845828468284782848828498285082851828528285382854828558285682857828588285982860828618286282863828648286582866828678286882869828708287182872828738287482875828768287782878828798288082881828828288382884828858288682887828888288982890828918289282893828948289582896828978289882899829008290182902829038290482905829068290782908829098291082911829128291382914829158291682917829188291982920829218292282923829248292582926829278292882929829308293182932829338293482935829368293782938829398294082941829428294382944829458294682947829488294982950829518295282953829548295582956829578295882959829608296182962829638296482965829668296782968829698297082971829728297382974829758297682977829788297982980829818298282983829848298582986829878298882989829908299182992829938299482995829968299782998829998300083001830028300383004830058300683007830088300983010830118301283013830148301583016830178301883019830208302183022830238302483025830268302783028830298303083031830328303383034830358303683037830388303983040830418304283043830448304583046830478304883049830508305183052830538305483055830568305783058830598306083061830628306383064830658306683067830688306983070830718307283073830748307583076830778307883079830808308183082830838308483085830868308783088830898309083091830928309383094830958309683097830988309983100831018310283103831048310583106831078310883109831108311183112831138311483115831168311783118831198312083121831228312383124831258312683127831288312983130831318313283133831348313583136831378313883139831408314183142831438314483145831468314783148831498315083151831528315383154831558315683157831588315983160831618316283163831648316583166831678316883169831708317183172831738317483175831768317783178831798318083181831828318383184831858318683187831888318983190831918319283193831948319583196831978319883199832008320183202832038320483205832068320783208832098321083211832128321383214832158321683217832188321983220832218322283223832248322583226832278322883229832308323183232832338323483235832368323783238832398324083241832428324383244832458324683247832488324983250832518325283253832548325583256832578325883259832608326183262832638326483265832668326783268832698327083271832728327383274832758327683277832788327983280832818328283283832848328583286832878328883289832908329183292832938329483295832968329783298832998330083301833028330383304833058330683307833088330983310833118331283313833148331583316833178331883319833208332183322833238332483325833268332783328833298333083331833328333383334833358333683337833388333983340833418334283343833448334583346833478334883349833508335183352833538335483355833568335783358833598336083361833628336383364833658336683367833688336983370833718337283373833748337583376833778337883379833808338183382833838338483385833868338783388833898339083391833928339383394833958339683397833988339983400834018340283403834048340583406834078340883409834108341183412834138341483415834168341783418834198342083421834228342383424834258342683427834288342983430834318343283433834348343583436834378343883439834408344183442834438344483445834468344783448834498345083451834528345383454834558345683457834588345983460834618346283463834648346583466834678346883469834708347183472834738347483475834768347783478834798348083481834828348383484834858348683487834888348983490834918349283493834948349583496834978349883499835008350183502835038350483505835068350783508835098351083511835128351383514835158351683517835188351983520835218352283523835248352583526835278352883529835308353183532835338353483535835368353783538835398354083541835428354383544835458354683547835488354983550835518355283553835548355583556835578355883559835608356183562835638356483565835668356783568835698357083571835728357383574835758357683577835788357983580835818358283583835848358583586835878358883589835908359183592835938359483595835968359783598835998360083601836028360383604836058360683607836088360983610836118361283613836148361583616836178361883619836208362183622836238362483625836268362783628836298363083631836328363383634836358363683637836388363983640836418364283643836448364583646836478364883649836508365183652836538365483655836568365783658836598366083661836628366383664836658366683667836688366983670836718367283673836748367583676836778367883679836808368183682836838368483685836868368783688836898369083691836928369383694836958369683697836988369983700837018370283703837048370583706837078370883709837108371183712837138371483715837168371783718837198372083721837228372383724837258372683727837288372983730837318373283733837348373583736837378373883739837408374183742837438374483745837468374783748837498375083751837528375383754837558375683757837588375983760837618376283763837648376583766837678376883769837708377183772837738377483775837768377783778837798378083781837828378383784837858378683787837888378983790837918379283793837948379583796837978379883799838008380183802838038380483805838068380783808838098381083811838128381383814838158381683817838188381983820838218382283823838248382583826838278382883829838308383183832838338383483835838368383783838838398384083841838428384383844838458384683847838488384983850838518385283853838548385583856838578385883859838608386183862838638386483865838668386783868838698387083871838728387383874838758387683877838788387983880838818388283883838848388583886838878388883889838908389183892838938389483895838968389783898838998390083901839028390383904839058390683907839088390983910839118391283913839148391583916839178391883919839208392183922839238392483925839268392783928839298393083931839328393383934839358393683937839388393983940839418394283943839448394583946839478394883949839508395183952839538395483955839568395783958839598396083961839628396383964839658396683967839688396983970839718397283973839748397583976839778397883979839808398183982839838398483985839868398783988839898399083991839928399383994839958399683997839988399984000840018400284003840048400584006840078400884009840108401184012840138401484015840168401784018840198402084021840228402384024840258402684027840288402984030840318403284033840348403584036840378403884039840408404184042840438404484045840468404784048840498405084051840528405384054840558405684057840588405984060840618406284063840648406584066840678406884069840708407184072840738407484075840768407784078840798408084081840828408384084840858408684087840888408984090840918409284093840948409584096840978409884099841008410184102841038410484105841068410784108841098411084111841128411384114841158411684117841188411984120841218412284123841248412584126841278412884129841308413184132841338413484135841368413784138841398414084141841428414384144841458414684147841488414984150841518415284153841548415584156841578415884159841608416184162841638416484165841668416784168841698417084171841728417384174841758417684177841788417984180841818418284183841848418584186841878418884189841908419184192841938419484195841968419784198841998420084201842028420384204842058420684207842088420984210842118421284213842148421584216842178421884219842208422184222842238422484225842268422784228842298423084231842328423384234842358423684237842388423984240842418424284243842448424584246842478424884249842508425184252842538425484255842568425784258842598426084261842628426384264842658426684267842688426984270842718427284273842748427584276842778427884279842808428184282842838428484285842868428784288842898429084291842928429384294842958429684297842988429984300843018430284303843048430584306843078430884309843108431184312843138431484315843168431784318843198432084321843228432384324843258432684327843288432984330843318433284333843348433584336843378433884339843408434184342843438434484345843468434784348843498435084351843528435384354843558435684357843588435984360843618436284363843648436584366843678436884369843708437184372843738437484375843768437784378843798438084381843828438384384843858438684387843888438984390843918439284393843948439584396843978439884399844008440184402844038440484405844068440784408844098441084411844128441384414844158441684417844188441984420844218442284423844248442584426844278442884429844308443184432844338443484435844368443784438844398444084441844428444384444844458444684447844488444984450844518445284453844548445584456844578445884459844608446184462844638446484465844668446784468844698447084471844728447384474844758447684477844788447984480844818448284483844848448584486844878448884489844908449184492844938449484495844968449784498844998450084501845028450384504845058450684507845088450984510845118451284513845148451584516845178451884519845208452184522845238452484525845268452784528845298453084531845328453384534845358453684537845388453984540845418454284543845448454584546845478454884549845508455184552845538455484555845568455784558845598456084561845628456384564845658456684567845688456984570845718457284573845748457584576845778457884579845808458184582845838458484585845868458784588845898459084591845928459384594845958459684597845988459984600846018460284603846048460584606846078460884609846108461184612846138461484615846168461784618846198462084621846228462384624846258462684627846288462984630846318463284633846348463584636846378463884639846408464184642846438464484645846468464784648846498465084651846528465384654846558465684657846588465984660846618466284663846648466584666846678466884669846708467184672846738467484675846768467784678846798468084681846828468384684846858468684687846888468984690846918469284693846948469584696846978469884699847008470184702847038470484705847068470784708847098471084711847128471384714847158471684717847188471984720847218472284723847248472584726847278472884729847308473184732847338473484735847368473784738847398474084741847428474384744847458474684747847488474984750847518475284753847548475584756847578475884759847608476184762847638476484765847668476784768847698477084771847728477384774847758477684777847788477984780847818478284783847848478584786847878478884789847908479184792847938479484795847968479784798847998480084801848028480384804848058480684807848088480984810848118481284813848148481584816848178481884819848208482184822848238482484825848268482784828848298483084831848328483384834848358483684837848388483984840848418484284843848448484584846848478484884849848508485184852848538485484855848568485784858848598486084861848628486384864848658486684867848688486984870848718487284873848748487584876848778487884879848808488184882848838488484885848868488784888848898489084891848928489384894848958489684897848988489984900849018490284903849048490584906849078490884909849108491184912849138491484915849168491784918849198492084921849228492384924849258492684927849288492984930849318493284933849348493584936849378493884939849408494184942849438494484945849468494784948849498495084951849528495384954849558495684957849588495984960849618496284963849648496584966849678496884969849708497184972849738497484975849768497784978849798498084981849828498384984849858498684987849888498984990849918499284993849948499584996849978499884999850008500185002850038500485005850068500785008850098501085011850128501385014850158501685017850188501985020850218502285023850248502585026850278502885029850308503185032850338503485035850368503785038850398504085041850428504385044850458504685047850488504985050850518505285053850548505585056850578505885059850608506185062850638506485065850668506785068850698507085071850728507385074850758507685077850788507985080850818508285083850848508585086850878508885089850908509185092850938509485095850968509785098850998510085101851028510385104851058510685107851088510985110851118511285113851148511585116851178511885119851208512185122851238512485125851268512785128851298513085131851328513385134851358513685137851388513985140851418514285143851448514585146851478514885149851508515185152851538515485155851568515785158851598516085161851628516385164851658516685167851688516985170851718517285173851748517585176851778517885179851808518185182851838518485185851868518785188851898519085191851928519385194851958519685197851988519985200852018520285203852048520585206852078520885209852108521185212852138521485215852168521785218852198522085221852228522385224852258522685227852288522985230852318523285233852348523585236852378523885239852408524185242852438524485245852468524785248852498525085251852528525385254852558525685257852588525985260852618526285263852648526585266852678526885269852708527185272852738527485275852768527785278852798528085281852828528385284852858528685287852888528985290852918529285293852948529585296852978529885299853008530185302853038530485305853068530785308853098531085311853128531385314853158531685317853188531985320853218532285323853248532585326853278532885329853308533185332853338533485335853368533785338853398534085341853428534385344853458534685347853488534985350853518535285353853548535585356853578535885359853608536185362853638536485365853668536785368853698537085371853728537385374853758537685377853788537985380853818538285383853848538585386853878538885389853908539185392853938539485395853968539785398853998540085401854028540385404854058540685407854088540985410854118541285413854148541585416854178541885419854208542185422854238542485425854268542785428854298543085431854328543385434854358543685437854388543985440854418544285443854448544585446854478544885449854508545185452854538545485455854568545785458854598546085461854628546385464854658546685467854688546985470854718547285473854748547585476854778547885479854808548185482854838548485485854868548785488854898549085491854928549385494854958549685497854988549985500855018550285503855048550585506855078550885509855108551185512855138551485515855168551785518855198552085521855228552385524855258552685527855288552985530855318553285533855348553585536855378553885539855408554185542855438554485545855468554785548855498555085551855528555385554855558555685557855588555985560855618556285563855648556585566855678556885569855708557185572855738557485575855768557785578855798558085581855828558385584855858558685587855888558985590855918559285593855948559585596855978559885599856008560185602856038560485605856068560785608856098561085611856128561385614856158561685617856188561985620856218562285623856248562585626856278562885629856308563185632856338563485635856368563785638856398564085641856428564385644856458564685647856488564985650856518565285653856548565585656856578565885659856608566185662856638566485665856668566785668856698567085671856728567385674856758567685677856788567985680856818568285683856848568585686856878568885689856908569185692856938569485695856968569785698856998570085701857028570385704857058570685707857088570985710857118571285713857148571585716857178571885719857208572185722857238572485725857268572785728857298573085731857328573385734857358573685737857388573985740857418574285743857448574585746857478574885749857508575185752857538575485755857568575785758857598576085761857628576385764857658576685767857688576985770857718577285773857748577585776857778577885779857808578185782857838578485785857868578785788857898579085791857928579385794857958579685797857988579985800858018580285803858048580585806858078580885809858108581185812858138581485815858168581785818858198582085821858228582385824858258582685827858288582985830858318583285833858348583585836858378583885839858408584185842858438584485845858468584785848858498585085851858528585385854858558585685857858588585985860858618586285863858648586585866858678586885869858708587185872858738587485875858768587785878858798588085881858828588385884858858588685887858888588985890858918589285893858948589585896858978589885899859008590185902859038590485905859068590785908859098591085911859128591385914859158591685917859188591985920859218592285923859248592585926859278592885929859308593185932859338593485935859368593785938859398594085941859428594385944859458594685947859488594985950859518595285953859548595585956859578595885959859608596185962859638596485965859668596785968859698597085971859728597385974859758597685977859788597985980859818598285983859848598585986859878598885989859908599185992859938599485995859968599785998859998600086001860028600386004860058600686007860088600986010860118601286013860148601586016860178601886019860208602186022860238602486025860268602786028860298603086031860328603386034860358603686037860388603986040860418604286043860448604586046860478604886049860508605186052860538605486055860568605786058860598606086061860628606386064860658606686067860688606986070860718607286073860748607586076860778607886079860808608186082860838608486085860868608786088860898609086091860928609386094860958609686097860988609986100861018610286103861048610586106861078610886109861108611186112861138611486115861168611786118861198612086121861228612386124861258612686127861288612986130861318613286133861348613586136861378613886139861408614186142861438614486145861468614786148861498615086151861528615386154861558615686157861588615986160861618616286163861648616586166861678616886169861708617186172861738617486175861768617786178861798618086181861828618386184861858618686187861888618986190861918619286193861948619586196861978619886199862008620186202862038620486205862068620786208862098621086211862128621386214862158621686217862188621986220862218622286223862248622586226862278622886229862308623186232862338623486235862368623786238862398624086241862428624386244862458624686247862488624986250862518625286253862548625586256862578625886259862608626186262862638626486265862668626786268862698627086271862728627386274862758627686277862788627986280862818628286283862848628586286862878628886289862908629186292862938629486295862968629786298862998630086301863028630386304863058630686307863088630986310863118631286313863148631586316863178631886319863208632186322863238632486325863268632786328863298633086331863328633386334863358633686337863388633986340863418634286343863448634586346863478634886349863508635186352863538635486355863568635786358863598636086361863628636386364863658636686367863688636986370863718637286373863748637586376863778637886379863808638186382863838638486385863868638786388863898639086391863928639386394863958639686397863988639986400864018640286403864048640586406864078640886409864108641186412864138641486415864168641786418864198642086421864228642386424864258642686427864288642986430864318643286433864348643586436864378643886439864408644186442864438644486445864468644786448864498645086451864528645386454864558645686457864588645986460864618646286463864648646586466864678646886469864708647186472864738647486475864768647786478864798648086481864828648386484864858648686487864888648986490864918649286493864948649586496864978649886499865008650186502865038650486505865068650786508865098651086511865128651386514865158651686517865188651986520865218652286523865248652586526865278652886529865308653186532865338653486535865368653786538865398654086541865428654386544865458654686547865488654986550865518655286553865548655586556865578655886559865608656186562865638656486565865668656786568865698657086571865728657386574865758657686577865788657986580865818658286583865848658586586865878658886589865908659186592865938659486595865968659786598865998660086601866028660386604866058660686607866088660986610866118661286613866148661586616866178661886619866208662186622866238662486625866268662786628866298663086631866328663386634866358663686637866388663986640866418664286643866448664586646866478664886649866508665186652866538665486655866568665786658866598666086661866628666386664866658666686667866688666986670866718667286673866748667586676866778667886679866808668186682866838668486685866868668786688866898669086691866928669386694866958669686697866988669986700867018670286703867048670586706867078670886709867108671186712867138671486715867168671786718867198672086721867228672386724867258672686727867288672986730867318673286733867348673586736867378673886739867408674186742867438674486745867468674786748867498675086751867528675386754867558675686757867588675986760867618676286763867648676586766867678676886769867708677186772867738677486775867768677786778867798678086781867828678386784867858678686787867888678986790867918679286793867948679586796867978679886799868008680186802868038680486805868068680786808868098681086811868128681386814868158681686817868188681986820868218682286823868248682586826868278682886829868308683186832868338683486835868368683786838868398684086841868428684386844868458684686847868488684986850868518685286853868548685586856868578685886859868608686186862868638686486865868668686786868868698687086871868728687386874868758687686877868788687986880868818688286883868848688586886868878688886889868908689186892868938689486895868968689786898868998690086901869028690386904869058690686907869088690986910869118691286913869148691586916869178691886919869208692186922869238692486925869268692786928869298693086931869328693386934869358693686937869388693986940869418694286943869448694586946869478694886949869508695186952869538695486955869568695786958869598696086961869628696386964869658696686967869688696986970869718697286973869748697586976869778697886979869808698186982869838698486985869868698786988869898699086991869928699386994869958699686997869988699987000870018700287003870048700587006870078700887009870108701187012870138701487015870168701787018870198702087021870228702387024870258702687027870288702987030870318703287033870348703587036870378703887039870408704187042870438704487045870468704787048870498705087051870528705387054870558705687057870588705987060870618706287063870648706587066870678706887069870708707187072870738707487075870768707787078870798708087081870828708387084870858708687087870888708987090870918709287093870948709587096870978709887099871008710187102871038710487105871068710787108871098711087111871128711387114871158711687117871188711987120871218712287123871248712587126871278712887129871308713187132871338713487135871368713787138871398714087141871428714387144871458714687147871488714987150871518715287153871548715587156871578715887159871608716187162871638716487165871668716787168871698717087171871728717387174871758717687177871788717987180871818718287183871848718587186871878718887189871908719187192871938719487195871968719787198871998720087201872028720387204872058720687207872088720987210872118721287213872148721587216872178721887219872208722187222872238722487225872268722787228872298723087231872328723387234872358723687237872388723987240872418724287243872448724587246872478724887249872508725187252872538725487255872568725787258872598726087261872628726387264872658726687267872688726987270872718727287273872748727587276872778727887279872808728187282872838728487285872868728787288872898729087291872928729387294872958729687297872988729987300873018730287303873048730587306873078730887309873108731187312873138731487315873168731787318873198732087321873228732387324873258732687327873288732987330873318733287333873348733587336873378733887339873408734187342873438734487345873468734787348873498735087351873528735387354873558735687357873588735987360873618736287363873648736587366873678736887369873708737187372873738737487375873768737787378873798738087381873828738387384873858738687387873888738987390873918739287393873948739587396873978739887399874008740187402874038740487405874068740787408874098741087411874128741387414874158741687417874188741987420874218742287423874248742587426874278742887429874308743187432874338743487435874368743787438874398744087441874428744387444874458744687447874488744987450874518745287453874548745587456874578745887459874608746187462874638746487465874668746787468874698747087471874728747387474874758747687477874788747987480874818748287483874848748587486874878748887489874908749187492874938749487495874968749787498874998750087501875028750387504875058750687507875088750987510875118751287513875148751587516875178751887519875208752187522875238752487525875268752787528875298753087531875328753387534875358753687537875388753987540875418754287543875448754587546875478754887549875508755187552875538755487555875568755787558875598756087561875628756387564875658756687567875688756987570875718757287573875748757587576875778757887579875808758187582875838758487585875868758787588875898759087591875928759387594875958759687597875988759987600876018760287603876048760587606876078760887609876108761187612876138761487615876168761787618876198762087621876228762387624876258762687627876288762987630876318763287633876348763587636876378763887639876408764187642876438764487645876468764787648876498765087651876528765387654876558765687657876588765987660876618766287663876648766587666876678766887669876708767187672876738767487675876768767787678876798768087681876828768387684876858768687687876888768987690876918769287693876948769587696876978769887699877008770187702877038770487705877068770787708877098771087711877128771387714877158771687717877188771987720877218772287723877248772587726877278772887729877308773187732877338773487735877368773787738877398774087741877428774387744877458774687747877488774987750877518775287753877548775587756877578775887759877608776187762877638776487765877668776787768877698777087771877728777387774877758777687777877788777987780877818778287783877848778587786877878778887789877908779187792877938779487795877968779787798877998780087801878028780387804878058780687807878088780987810878118781287813878148781587816878178781887819878208782187822878238782487825878268782787828878298783087831878328783387834878358783687837878388783987840878418784287843878448784587846878478784887849878508785187852878538785487855878568785787858878598786087861878628786387864878658786687867878688786987870878718787287873878748787587876878778787887879878808788187882878838788487885878868788787888878898789087891878928789387894878958789687897878988789987900879018790287903879048790587906879078790887909879108791187912879138791487915879168791787918879198792087921879228792387924879258792687927879288792987930879318793287933879348793587936879378793887939879408794187942879438794487945879468794787948879498795087951879528795387954879558795687957879588795987960879618796287963879648796587966879678796887969879708797187972879738797487975879768797787978879798798087981879828798387984879858798687987879888798987990879918799287993879948799587996879978799887999880008800188002880038800488005880068800788008880098801088011880128801388014880158801688017880188801988020880218802288023880248802588026880278802888029880308803188032880338803488035880368803788038880398804088041880428804388044880458804688047880488804988050880518805288053880548805588056880578805888059880608806188062880638806488065880668806788068880698807088071880728807388074880758807688077880788807988080880818808288083880848808588086880878808888089880908809188092880938809488095880968809788098880998810088101881028810388104881058810688107881088810988110881118811288113881148811588116881178811888119881208812188122881238812488125881268812788128881298813088131881328813388134881358813688137881388813988140881418814288143881448814588146881478814888149881508815188152881538815488155881568815788158881598816088161881628816388164881658816688167881688816988170881718817288173881748817588176881778817888179881808818188182881838818488185881868818788188881898819088191881928819388194881958819688197881988819988200882018820288203882048820588206882078820888209882108821188212882138821488215882168821788218882198822088221882228822388224882258822688227882288822988230882318823288233882348823588236882378823888239882408824188242882438824488245882468824788248882498825088251882528825388254882558825688257882588825988260882618826288263882648826588266882678826888269882708827188272882738827488275882768827788278882798828088281882828828388284882858828688287882888828988290882918829288293882948829588296882978829888299883008830188302883038830488305883068830788308883098831088311883128831388314883158831688317883188831988320883218832288323883248832588326883278832888329883308833188332883338833488335883368833788338883398834088341883428834388344883458834688347883488834988350883518835288353883548835588356883578835888359883608836188362883638836488365883668836788368883698837088371883728837388374883758837688377883788837988380883818838288383883848838588386883878838888389883908839188392883938839488395883968839788398883998840088401884028840388404884058840688407884088840988410884118841288413884148841588416884178841888419884208842188422884238842488425884268842788428884298843088431884328843388434884358843688437884388843988440884418844288443884448844588446884478844888449884508845188452884538845488455884568845788458884598846088461884628846388464884658846688467884688846988470884718847288473884748847588476884778847888479884808848188482884838848488485884868848788488884898849088491884928849388494884958849688497884988849988500885018850288503885048850588506885078850888509885108851188512885138851488515885168851788518885198852088521885228852388524885258852688527885288852988530885318853288533885348853588536885378853888539885408854188542885438854488545885468854788548885498855088551885528855388554885558855688557885588855988560885618856288563885648856588566885678856888569885708857188572885738857488575885768857788578885798858088581885828858388584885858858688587885888858988590885918859288593885948859588596885978859888599886008860188602886038860488605886068860788608886098861088611886128861388614886158861688617886188861988620886218862288623886248862588626886278862888629886308863188632886338863488635886368863788638886398864088641886428864388644886458864688647886488864988650886518865288653886548865588656886578865888659886608866188662886638866488665886668866788668886698867088671886728867388674886758867688677886788867988680886818868288683886848868588686886878868888689886908869188692886938869488695886968869788698886998870088701887028870388704887058870688707887088870988710887118871288713887148871588716887178871888719887208872188722887238872488725887268872788728887298873088731887328873388734887358873688737887388873988740887418874288743887448874588746887478874888749887508875188752887538875488755887568875788758887598876088761887628876388764887658876688767887688876988770887718877288773887748877588776887778877888779887808878188782887838878488785887868878788788887898879088791887928879388794887958879688797887988879988800888018880288803888048880588806888078880888809888108881188812888138881488815888168881788818888198882088821888228882388824888258882688827888288882988830888318883288833888348883588836888378883888839888408884188842888438884488845888468884788848888498885088851888528885388854888558885688857888588885988860888618886288863888648886588866888678886888869888708887188872888738887488875888768887788878888798888088881888828888388884888858888688887888888888988890888918889288893888948889588896888978889888899889008890188902889038890488905889068890788908889098891088911889128891388914889158891688917889188891988920889218892288923889248892588926889278892888929889308893188932889338893488935889368893788938889398894088941889428894388944889458894688947889488894988950889518895288953889548895588956889578895888959889608896188962889638896488965889668896788968889698897088971889728897388974889758897688977889788897988980889818898288983889848898588986889878898888989889908899188992889938899488995889968899788998889998900089001890028900389004890058900689007890088900989010890118901289013890148901589016890178901889019890208902189022890238902489025890268902789028890298903089031890328903389034890358903689037890388903989040890418904289043890448904589046890478904889049890508905189052890538905489055890568905789058890598906089061890628906389064890658906689067890688906989070890718907289073890748907589076890778907889079890808908189082890838908489085890868908789088890898909089091890928909389094890958909689097890988909989100891018910289103891048910589106891078910889109891108911189112891138911489115891168911789118891198912089121891228912389124891258912689127891288912989130891318913289133891348913589136891378913889139891408914189142891438914489145891468914789148891498915089151891528915389154891558915689157891588915989160891618916289163891648916589166891678916889169891708917189172891738917489175891768917789178891798918089181891828918389184891858918689187891888918989190891918919289193891948919589196891978919889199892008920189202892038920489205892068920789208892098921089211892128921389214892158921689217892188921989220892218922289223892248922589226892278922889229892308923189232892338923489235892368923789238892398924089241892428924389244892458924689247892488924989250892518925289253892548925589256892578925889259892608926189262892638926489265892668926789268892698927089271892728927389274892758927689277892788927989280892818928289283892848928589286892878928889289892908929189292892938929489295892968929789298892998930089301893028930389304893058930689307893088930989310893118931289313893148931589316893178931889319893208932189322893238932489325893268932789328893298933089331893328933389334893358933689337893388933989340893418934289343893448934589346893478934889349893508935189352893538935489355893568935789358893598936089361893628936389364893658936689367893688936989370893718937289373893748937589376893778937889379893808938189382893838938489385893868938789388893898939089391893928939389394893958939689397893988939989400894018940289403894048940589406894078940889409894108941189412894138941489415894168941789418894198942089421894228942389424894258942689427894288942989430894318943289433894348943589436894378943889439894408944189442894438944489445894468944789448894498945089451894528945389454894558945689457894588945989460894618946289463894648946589466894678946889469894708947189472894738947489475894768947789478894798948089481894828948389484894858948689487894888948989490894918949289493894948949589496894978949889499895008950189502895038950489505895068950789508895098951089511895128951389514895158951689517895188951989520895218952289523895248952589526895278952889529895308953189532895338953489535895368953789538895398954089541895428954389544895458954689547895488954989550895518955289553895548955589556895578955889559895608956189562895638956489565895668956789568895698957089571895728957389574895758957689577895788957989580895818958289583895848958589586895878958889589895908959189592895938959489595895968959789598895998960089601896028960389604896058960689607896088960989610896118961289613896148961589616896178961889619896208962189622896238962489625896268962789628896298963089631896328963389634896358963689637896388963989640896418964289643896448964589646896478964889649896508965189652896538965489655896568965789658896598966089661896628966389664896658966689667896688966989670896718967289673896748967589676896778967889679896808968189682896838968489685896868968789688896898969089691896928969389694896958969689697896988969989700897018970289703897048970589706897078970889709897108971189712897138971489715897168971789718897198972089721897228972389724897258972689727897288972989730897318973289733897348973589736897378973889739897408974189742897438974489745897468974789748897498975089751897528975389754897558975689757897588975989760897618976289763897648976589766897678976889769897708977189772897738977489775897768977789778897798978089781897828978389784897858978689787897888978989790897918979289793897948979589796897978979889799898008980189802898038980489805898068980789808898098981089811898128981389814898158981689817898188981989820898218982289823898248982589826898278982889829898308983189832898338983489835898368983789838898398984089841898428984389844898458984689847898488984989850898518985289853898548985589856898578985889859898608986189862898638986489865898668986789868898698987089871898728987389874898758987689877898788987989880898818988289883898848988589886898878988889889898908989189892898938989489895898968989789898898998990089901899028990389904899058990689907899088990989910899118991289913899148991589916899178991889919899208992189922899238992489925899268992789928899298993089931899328993389934899358993689937899388993989940899418994289943899448994589946899478994889949899508995189952899538995489955899568995789958899598996089961899628996389964899658996689967899688996989970899718997289973899748997589976899778997889979899808998189982899838998489985899868998789988899898999089991899928999389994899958999689997899988999990000900019000290003900049000590006900079000890009900109001190012900139001490015900169001790018900199002090021900229002390024900259002690027900289002990030900319003290033900349003590036900379003890039900409004190042900439004490045900469004790048900499005090051900529005390054900559005690057900589005990060900619006290063900649006590066900679006890069900709007190072900739007490075900769007790078900799008090081900829008390084900859008690087900889008990090900919009290093900949009590096900979009890099901009010190102901039010490105901069010790108901099011090111901129011390114901159011690117901189011990120901219012290123901249012590126901279012890129901309013190132901339013490135901369013790138901399014090141901429014390144901459014690147901489014990150901519015290153901549015590156901579015890159901609016190162901639016490165901669016790168901699017090171901729017390174901759017690177901789017990180901819018290183901849018590186901879018890189901909019190192901939019490195901969019790198901999020090201902029020390204902059020690207902089020990210902119021290213902149021590216902179021890219902209022190222902239022490225902269022790228902299023090231902329023390234902359023690237902389023990240902419024290243902449024590246902479024890249902509025190252902539025490255902569025790258902599026090261902629026390264902659026690267902689026990270902719027290273902749027590276902779027890279902809028190282902839028490285902869028790288902899029090291902929029390294902959029690297902989029990300903019030290303903049030590306903079030890309903109031190312903139031490315903169031790318903199032090321903229032390324903259032690327903289032990330903319033290333903349033590336903379033890339903409034190342903439034490345903469034790348903499035090351903529035390354903559035690357903589035990360903619036290363903649036590366903679036890369903709037190372903739037490375903769037790378903799038090381903829038390384903859038690387903889038990390903919039290393903949039590396903979039890399904009040190402904039040490405904069040790408904099041090411904129041390414904159041690417904189041990420904219042290423904249042590426904279042890429904309043190432904339043490435904369043790438904399044090441904429044390444904459044690447904489044990450904519045290453904549045590456904579045890459904609046190462904639046490465904669046790468904699047090471904729047390474904759047690477904789047990480904819048290483904849048590486904879048890489904909049190492904939049490495904969049790498904999050090501905029050390504905059050690507905089050990510905119051290513905149051590516905179051890519905209052190522905239052490525905269052790528905299053090531905329053390534905359053690537905389053990540905419054290543905449054590546905479054890549905509055190552905539055490555905569055790558905599056090561905629056390564905659056690567905689056990570905719057290573905749057590576905779057890579905809058190582905839058490585905869058790588905899059090591905929059390594905959059690597905989059990600906019060290603906049060590606906079060890609906109061190612906139061490615906169061790618906199062090621906229062390624906259062690627906289062990630906319063290633906349063590636906379063890639906409064190642906439064490645906469064790648906499065090651906529065390654906559065690657906589065990660906619066290663906649066590666906679066890669906709067190672906739067490675906769067790678906799068090681906829068390684906859068690687906889068990690906919069290693906949069590696906979069890699907009070190702907039070490705907069070790708907099071090711907129071390714907159071690717907189071990720907219072290723907249072590726907279072890729907309073190732907339073490735907369073790738907399074090741907429074390744907459074690747907489074990750907519075290753907549075590756907579075890759907609076190762907639076490765907669076790768907699077090771907729077390774907759077690777907789077990780907819078290783907849078590786907879078890789907909079190792907939079490795907969079790798907999080090801908029080390804908059080690807908089080990810908119081290813908149081590816908179081890819908209082190822908239082490825908269082790828908299083090831908329083390834908359083690837908389083990840908419084290843908449084590846908479084890849908509085190852908539085490855908569085790858908599086090861908629086390864908659086690867908689086990870908719087290873908749087590876908779087890879908809088190882908839088490885908869088790888908899089090891908929089390894908959089690897908989089990900909019090290903909049090590906909079090890909909109091190912909139091490915909169091790918909199092090921909229092390924909259092690927909289092990930909319093290933909349093590936909379093890939909409094190942909439094490945909469094790948909499095090951909529095390954909559095690957909589095990960909619096290963909649096590966909679096890969909709097190972909739097490975909769097790978909799098090981909829098390984909859098690987909889098990990909919099290993909949099590996909979099890999910009100191002910039100491005910069100791008910099101091011910129101391014910159101691017910189101991020910219102291023910249102591026910279102891029910309103191032910339103491035910369103791038910399104091041910429104391044910459104691047910489104991050910519105291053910549105591056910579105891059910609106191062910639106491065910669106791068910699107091071910729107391074910759107691077910789107991080910819108291083910849108591086910879108891089910909109191092910939109491095910969109791098910999110091101911029110391104911059110691107911089110991110911119111291113911149111591116911179111891119911209112191122911239112491125911269112791128911299113091131911329113391134911359113691137911389113991140911419114291143911449114591146911479114891149911509115191152911539115491155911569115791158911599116091161911629116391164911659116691167911689116991170911719117291173911749117591176911779117891179911809118191182911839118491185911869118791188911899119091191911929119391194911959119691197911989119991200912019120291203912049120591206912079120891209912109121191212912139121491215912169121791218912199122091221912229122391224912259122691227912289122991230912319123291233912349123591236912379123891239912409124191242912439124491245912469124791248912499125091251912529125391254912559125691257912589125991260912619126291263912649126591266912679126891269912709127191272912739127491275912769127791278912799128091281912829128391284912859128691287912889128991290912919129291293912949129591296912979129891299913009130191302913039130491305913069130791308913099131091311913129131391314913159131691317913189131991320913219132291323913249132591326913279132891329913309133191332913339133491335913369133791338913399134091341913429134391344913459134691347913489134991350913519135291353913549135591356913579135891359913609136191362913639136491365913669136791368913699137091371913729137391374913759137691377913789137991380913819138291383913849138591386913879138891389913909139191392913939139491395913969139791398913999140091401914029140391404914059140691407914089140991410914119141291413914149141591416914179141891419914209142191422914239142491425914269142791428914299143091431914329143391434914359143691437914389143991440914419144291443914449144591446914479144891449914509145191452914539145491455914569145791458914599146091461914629146391464914659146691467914689146991470914719147291473914749147591476914779147891479914809148191482914839148491485914869148791488914899149091491914929149391494914959149691497914989149991500915019150291503915049150591506915079150891509915109151191512915139151491515915169151791518915199152091521915229152391524915259152691527915289152991530915319153291533915349153591536915379153891539915409154191542915439154491545915469154791548915499155091551915529155391554915559155691557915589155991560915619156291563915649156591566915679156891569915709157191572915739157491575915769157791578915799158091581915829158391584915859158691587915889158991590915919159291593915949159591596915979159891599916009160191602916039160491605916069160791608916099161091611916129161391614916159161691617916189161991620916219162291623916249162591626916279162891629916309163191632916339163491635916369163791638916399164091641916429164391644916459164691647916489164991650916519165291653916549165591656916579165891659916609166191662916639166491665916669166791668916699167091671916729167391674916759167691677916789167991680916819168291683916849168591686916879168891689916909169191692916939169491695916969169791698916999170091701917029170391704917059170691707917089170991710917119171291713917149171591716917179171891719917209172191722917239172491725917269172791728917299173091731917329173391734917359173691737917389173991740917419174291743917449174591746917479174891749917509175191752917539175491755917569175791758917599176091761917629176391764917659176691767917689176991770917719177291773917749177591776917779177891779917809178191782917839178491785917869178791788917899179091791917929179391794917959179691797917989179991800918019180291803918049180591806918079180891809918109181191812918139181491815918169181791818918199182091821918229182391824918259182691827918289182991830918319183291833918349183591836918379183891839918409184191842918439184491845918469184791848918499185091851918529185391854918559185691857918589185991860918619186291863918649186591866918679186891869918709187191872918739187491875918769187791878918799188091881918829188391884918859188691887918889188991890918919189291893918949189591896918979189891899919009190191902919039190491905919069190791908919099191091911919129191391914919159191691917919189191991920919219192291923919249192591926919279192891929919309193191932919339193491935919369193791938919399194091941919429194391944919459194691947919489194991950919519195291953919549195591956919579195891959919609196191962919639196491965919669196791968919699197091971919729197391974919759197691977919789197991980919819198291983919849198591986919879198891989919909199191992919939199491995919969199791998919999200092001920029200392004920059200692007920089200992010920119201292013920149201592016920179201892019920209202192022920239202492025920269202792028920299203092031920329203392034920359203692037920389203992040920419204292043920449204592046920479204892049920509205192052920539205492055920569205792058920599206092061920629206392064920659206692067920689206992070920719207292073920749207592076920779207892079920809208192082920839208492085920869208792088920899209092091920929209392094920959209692097920989209992100921019210292103921049210592106921079210892109921109211192112921139211492115921169211792118921199212092121921229212392124921259212692127921289212992130921319213292133921349213592136921379213892139921409214192142921439214492145921469214792148921499215092151921529215392154921559215692157921589215992160921619216292163921649216592166921679216892169921709217192172921739217492175921769217792178921799218092181921829218392184921859218692187921889218992190921919219292193921949219592196921979219892199922009220192202922039220492205922069220792208922099221092211922129221392214922159221692217922189221992220922219222292223922249222592226922279222892229922309223192232922339223492235922369223792238922399224092241922429224392244922459224692247922489224992250922519225292253922549225592256922579225892259922609226192262922639226492265922669226792268922699227092271922729227392274922759227692277922789227992280922819228292283922849228592286922879228892289922909229192292922939229492295922969229792298922999230092301923029230392304923059230692307923089230992310923119231292313923149231592316923179231892319923209232192322923239232492325923269232792328923299233092331923329233392334923359233692337923389233992340923419234292343923449234592346923479234892349923509235192352923539235492355923569235792358923599236092361923629236392364923659236692367923689236992370923719237292373923749237592376923779237892379923809238192382923839238492385923869238792388923899239092391923929239392394923959239692397923989239992400924019240292403924049240592406924079240892409924109241192412924139241492415924169241792418924199242092421924229242392424924259242692427924289242992430924319243292433924349243592436924379243892439924409244192442924439244492445924469244792448924499245092451924529245392454924559245692457924589245992460924619246292463924649246592466924679246892469924709247192472924739247492475924769247792478924799248092481924829248392484924859248692487924889248992490924919249292493924949249592496924979249892499925009250192502925039250492505925069250792508925099251092511925129251392514925159251692517925189251992520925219252292523925249252592526925279252892529925309253192532925339253492535925369253792538925399254092541925429254392544925459254692547925489254992550925519255292553925549255592556925579255892559925609256192562925639256492565925669256792568925699257092571925729257392574925759257692577925789257992580925819258292583925849258592586925879258892589925909259192592925939259492595925969259792598925999260092601926029260392604926059260692607926089260992610926119261292613926149261592616926179261892619926209262192622926239262492625926269262792628926299263092631926329263392634926359263692637926389263992640926419264292643926449264592646926479264892649926509265192652926539265492655926569265792658926599266092661926629266392664926659266692667926689266992670926719267292673926749267592676926779267892679926809268192682926839268492685926869268792688926899269092691926929269392694926959269692697926989269992700927019270292703927049270592706927079270892709927109271192712927139271492715927169271792718927199272092721927229272392724927259272692727927289272992730927319273292733927349273592736927379273892739927409274192742927439274492745927469274792748927499275092751927529275392754927559275692757927589275992760927619276292763927649276592766927679276892769927709277192772927739277492775927769277792778927799278092781927829278392784927859278692787927889278992790927919279292793927949279592796927979279892799928009280192802928039280492805928069280792808928099281092811928129281392814928159281692817928189281992820928219282292823928249282592826928279282892829928309283192832928339283492835928369283792838928399284092841928429284392844928459284692847928489284992850928519285292853928549285592856928579285892859928609286192862928639286492865928669286792868928699287092871928729287392874928759287692877928789287992880928819288292883928849288592886928879288892889928909289192892928939289492895928969289792898928999290092901929029290392904929059290692907929089290992910929119291292913929149291592916929179291892919929209292192922929239292492925929269292792928929299293092931929329293392934929359293692937929389293992940929419294292943929449294592946929479294892949929509295192952929539295492955929569295792958929599296092961929629296392964929659296692967929689296992970929719297292973929749297592976929779297892979929809298192982929839298492985929869298792988929899299092991929929299392994929959299692997929989299993000930019300293003930049300593006930079300893009930109301193012930139301493015930169301793018930199302093021930229302393024930259302693027930289302993030930319303293033930349303593036930379303893039930409304193042930439304493045930469304793048930499305093051930529305393054930559305693057930589305993060930619306293063930649306593066930679306893069930709307193072930739307493075930769307793078930799308093081930829308393084930859308693087930889308993090930919309293093930949309593096930979309893099931009310193102931039310493105931069310793108931099311093111931129311393114931159311693117931189311993120931219312293123931249312593126931279312893129931309313193132931339313493135931369313793138931399314093141931429314393144931459314693147931489314993150931519315293153931549315593156931579315893159931609316193162931639316493165931669316793168931699317093171931729317393174931759317693177931789317993180931819318293183931849318593186931879318893189931909319193192931939319493195931969319793198931999320093201932029320393204932059320693207932089320993210932119321293213932149321593216932179321893219932209322193222932239322493225932269322793228932299323093231932329323393234932359323693237932389323993240932419324293243932449324593246932479324893249932509325193252932539325493255932569325793258932599326093261932629326393264932659326693267932689326993270932719327293273932749327593276932779327893279932809328193282932839328493285932869328793288932899329093291932929329393294932959329693297932989329993300933019330293303933049330593306933079330893309933109331193312933139331493315933169331793318933199332093321933229332393324933259332693327933289332993330933319333293333933349333593336933379333893339933409334193342933439334493345933469334793348933499335093351933529335393354933559335693357933589335993360933619336293363933649336593366933679336893369933709337193372933739337493375933769337793378933799338093381933829338393384933859338693387933889338993390933919339293393933949339593396933979339893399934009340193402934039340493405934069340793408934099341093411934129341393414934159341693417934189341993420934219342293423934249342593426934279342893429934309343193432934339343493435934369343793438934399344093441934429344393444934459344693447934489344993450934519345293453934549345593456934579345893459934609346193462934639346493465934669346793468934699347093471934729347393474934759347693477934789347993480934819348293483934849348593486934879348893489934909349193492934939349493495934969349793498934999350093501935029350393504935059350693507935089350993510935119351293513935149351593516935179351893519935209352193522935239352493525935269352793528935299353093531935329353393534935359353693537935389353993540935419354293543935449354593546935479354893549935509355193552935539355493555935569355793558935599356093561935629356393564935659356693567935689356993570935719357293573935749357593576935779357893579935809358193582935839358493585935869358793588935899359093591935929359393594935959359693597935989359993600936019360293603936049360593606936079360893609936109361193612936139361493615936169361793618936199362093621936229362393624936259362693627936289362993630936319363293633936349363593636936379363893639936409364193642936439364493645936469364793648936499365093651936529365393654936559365693657936589365993660936619366293663936649366593666936679366893669936709367193672936739367493675936769367793678936799368093681936829368393684936859368693687936889368993690936919369293693936949369593696936979369893699937009370193702937039370493705937069370793708937099371093711937129371393714937159371693717937189371993720937219372293723937249372593726937279372893729937309373193732937339373493735937369373793738937399374093741937429374393744937459374693747937489374993750937519375293753937549375593756937579375893759937609376193762937639376493765937669376793768937699377093771937729377393774937759377693777937789377993780937819378293783937849378593786937879378893789937909379193792937939379493795937969379793798937999380093801938029380393804938059380693807938089380993810938119381293813938149381593816938179381893819938209382193822938239382493825938269382793828938299383093831938329383393834938359383693837938389383993840938419384293843938449384593846938479384893849938509385193852938539385493855938569385793858938599386093861938629386393864938659386693867938689386993870938719387293873938749387593876938779387893879938809388193882938839388493885938869388793888938899389093891938929389393894938959389693897938989389993900939019390293903939049390593906939079390893909939109391193912939139391493915939169391793918939199392093921939229392393924939259392693927939289392993930939319393293933939349393593936939379393893939939409394193942939439394493945939469394793948939499395093951939529395393954939559395693957939589395993960939619396293963939649396593966939679396893969939709397193972939739397493975939769397793978939799398093981939829398393984939859398693987939889398993990939919399293993939949399593996939979399893999940009400194002940039400494005940069400794008940099401094011940129401394014940159401694017940189401994020940219402294023940249402594026940279402894029940309403194032940339403494035940369403794038940399404094041940429404394044940459404694047940489404994050940519405294053940549405594056940579405894059940609406194062940639406494065940669406794068940699407094071940729407394074940759407694077940789407994080940819408294083940849408594086940879408894089940909409194092940939409494095940969409794098940999410094101941029410394104941059410694107941089410994110941119411294113941149411594116941179411894119941209412194122941239412494125941269412794128941299413094131941329413394134941359413694137941389413994140941419414294143941449414594146941479414894149941509415194152941539415494155941569415794158941599416094161941629416394164941659416694167941689416994170941719417294173941749417594176941779417894179941809418194182941839418494185941869418794188941899419094191941929419394194941959419694197941989419994200942019420294203942049420594206942079420894209942109421194212942139421494215942169421794218942199422094221942229422394224942259422694227942289422994230942319423294233942349423594236942379423894239942409424194242942439424494245942469424794248942499425094251942529425394254942559425694257942589425994260942619426294263942649426594266942679426894269942709427194272942739427494275942769427794278942799428094281942829428394284942859428694287942889428994290942919429294293942949429594296942979429894299943009430194302943039430494305943069430794308943099431094311943129431394314943159431694317943189431994320943219432294323943249432594326943279432894329943309433194332943339433494335943369433794338943399434094341943429434394344943459434694347943489434994350943519435294353943549435594356943579435894359943609436194362943639436494365943669436794368943699437094371943729437394374943759437694377943789437994380943819438294383943849438594386943879438894389943909439194392943939439494395943969439794398943999440094401944029440394404944059440694407944089440994410944119441294413944149441594416944179441894419944209442194422944239442494425944269442794428944299443094431944329443394434944359443694437944389443994440944419444294443944449444594446944479444894449944509445194452944539445494455944569445794458944599446094461944629446394464944659446694467944689446994470944719447294473944749447594476944779447894479944809448194482944839448494485944869448794488944899449094491944929449394494944959449694497944989449994500945019450294503945049450594506945079450894509945109451194512945139451494515945169451794518945199452094521945229452394524945259452694527945289452994530945319453294533945349453594536945379453894539945409454194542945439454494545945469454794548945499455094551945529455394554945559455694557945589455994560945619456294563945649456594566945679456894569945709457194572945739457494575945769457794578945799458094581945829458394584945859458694587945889458994590945919459294593945949459594596945979459894599946009460194602946039460494605946069460794608946099461094611946129461394614946159461694617946189461994620946219462294623946249462594626946279462894629946309463194632946339463494635946369463794638946399464094641946429464394644946459464694647946489464994650946519465294653946549465594656946579465894659946609466194662946639466494665946669466794668946699467094671946729467394674946759467694677946789467994680946819468294683946849468594686946879468894689946909469194692946939469494695946969469794698946999470094701947029470394704947059470694707947089470994710947119471294713947149471594716947179471894719947209472194722947239472494725947269472794728947299473094731947329473394734947359473694737947389473994740947419474294743947449474594746947479474894749947509475194752947539475494755947569475794758947599476094761947629476394764947659476694767947689476994770947719477294773947749477594776947779477894779947809478194782947839478494785947869478794788947899479094791947929479394794947959479694797947989479994800948019480294803948049480594806948079480894809948109481194812948139481494815948169481794818948199482094821948229482394824948259482694827948289482994830948319483294833948349483594836948379483894839948409484194842948439484494845948469484794848948499485094851948529485394854948559485694857948589485994860948619486294863948649486594866948679486894869948709487194872948739487494875948769487794878948799488094881948829488394884948859488694887948889488994890948919489294893948949489594896948979489894899949009490194902949039490494905949069490794908949099491094911949129491394914949159491694917949189491994920949219492294923949249492594926949279492894929949309493194932949339493494935949369493794938949399494094941949429494394944949459494694947949489494994950949519495294953949549495594956949579495894959949609496194962949639496494965949669496794968949699497094971949729497394974949759497694977949789497994980949819498294983949849498594986949879498894989949909499194992949939499494995949969499794998949999500095001950029500395004950059500695007950089500995010950119501295013950149501595016950179501895019950209502195022950239502495025950269502795028950299503095031950329503395034950359503695037950389503995040950419504295043950449504595046950479504895049950509505195052950539505495055950569505795058950599506095061950629506395064950659506695067950689506995070950719507295073950749507595076950779507895079950809508195082950839508495085950869508795088950899509095091950929509395094950959509695097950989509995100951019510295103951049510595106951079510895109951109511195112951139511495115951169511795118951199512095121951229512395124951259512695127951289512995130951319513295133951349513595136951379513895139951409514195142951439514495145951469514795148951499515095151951529515395154951559515695157951589515995160951619516295163951649516595166951679516895169951709517195172951739517495175951769517795178951799518095181951829518395184951859518695187951889518995190951919519295193951949519595196951979519895199952009520195202952039520495205952069520795208952099521095211952129521395214952159521695217952189521995220952219522295223952249522595226952279522895229952309523195232952339523495235952369523795238952399524095241952429524395244952459524695247952489524995250952519525295253952549525595256952579525895259952609526195262952639526495265952669526795268952699527095271952729527395274952759527695277952789527995280952819528295283952849528595286952879528895289952909529195292952939529495295952969529795298952999530095301953029530395304953059530695307953089530995310953119531295313953149531595316953179531895319953209532195322953239532495325953269532795328953299533095331953329533395334953359533695337953389533995340953419534295343953449534595346953479534895349953509535195352953539535495355953569535795358953599536095361953629536395364953659536695367953689536995370953719537295373953749537595376953779537895379953809538195382953839538495385953869538795388953899539095391953929539395394953959539695397953989539995400954019540295403954049540595406954079540895409954109541195412954139541495415954169541795418954199542095421954229542395424954259542695427954289542995430954319543295433954349543595436954379543895439954409544195442954439544495445954469544795448954499545095451954529545395454954559545695457954589545995460954619546295463954649546595466954679546895469954709547195472954739547495475954769547795478954799548095481954829548395484954859548695487954889548995490954919549295493954949549595496954979549895499955009550195502955039550495505955069550795508955099551095511955129551395514955159551695517955189551995520955219552295523955249552595526955279552895529955309553195532955339553495535955369553795538955399554095541955429554395544955459554695547955489554995550955519555295553955549555595556955579555895559955609556195562955639556495565955669556795568955699557095571955729557395574955759557695577955789557995580955819558295583955849558595586955879558895589955909559195592955939559495595955969559795598955999560095601956029560395604956059560695607956089560995610956119561295613956149561595616956179561895619956209562195622956239562495625956269562795628956299563095631956329563395634956359563695637956389563995640956419564295643956449564595646956479564895649956509565195652956539565495655956569565795658956599566095661956629566395664956659566695667956689566995670956719567295673956749567595676956779567895679956809568195682956839568495685956869568795688956899569095691956929569395694956959569695697956989569995700957019570295703957049570595706957079570895709957109571195712957139571495715957169571795718957199572095721957229572395724957259572695727957289572995730957319573295733957349573595736957379573895739957409574195742957439574495745957469574795748957499575095751957529575395754957559575695757957589575995760957619576295763957649576595766957679576895769957709577195772957739577495775957769577795778957799578095781957829578395784957859578695787957889578995790957919579295793957949579595796957979579895799958009580195802958039580495805958069580795808958099581095811958129581395814958159581695817958189581995820958219582295823958249582595826958279582895829958309583195832958339583495835958369583795838958399584095841958429584395844958459584695847958489584995850958519585295853958549585595856958579585895859958609586195862958639586495865958669586795868958699587095871958729587395874958759587695877958789587995880958819588295883958849588595886958879588895889958909589195892958939589495895958969589795898958999590095901959029590395904959059590695907959089590995910959119591295913959149591595916959179591895919959209592195922959239592495925959269592795928959299593095931959329593395934959359593695937959389593995940959419594295943959449594595946959479594895949959509595195952959539595495955959569595795958959599596095961959629596395964959659596695967959689596995970959719597295973959749597595976959779597895979959809598195982959839598495985959869598795988959899599095991959929599395994959959599695997959989599996000960019600296003960049600596006960079600896009960109601196012960139601496015960169601796018960199602096021960229602396024960259602696027960289602996030960319603296033960349603596036960379603896039960409604196042960439604496045960469604796048960499605096051960529605396054960559605696057960589605996060960619606296063960649606596066960679606896069960709607196072960739607496075960769607796078960799608096081960829608396084960859608696087960889608996090960919609296093960949609596096960979609896099961009610196102961039610496105961069610796108961099611096111961129611396114961159611696117961189611996120961219612296123961249612596126961279612896129961309613196132961339613496135961369613796138961399614096141961429614396144961459614696147961489614996150961519615296153961549615596156961579615896159961609616196162961639616496165961669616796168961699617096171961729617396174961759617696177961789617996180961819618296183961849618596186961879618896189961909619196192961939619496195961969619796198961999620096201962029620396204962059620696207962089620996210962119621296213962149621596216962179621896219962209622196222962239622496225962269622796228962299623096231962329623396234962359623696237962389623996240962419624296243962449624596246962479624896249962509625196252962539625496255962569625796258962599626096261962629626396264962659626696267962689626996270962719627296273962749627596276962779627896279962809628196282962839628496285962869628796288962899629096291962929629396294962959629696297962989629996300963019630296303963049630596306963079630896309963109631196312963139631496315963169631796318963199632096321963229632396324963259632696327963289632996330963319633296333963349633596336963379633896339963409634196342963439634496345963469634796348963499635096351963529635396354963559635696357963589635996360963619636296363963649636596366963679636896369963709637196372963739637496375963769637796378963799638096381963829638396384963859638696387963889638996390963919639296393963949639596396963979639896399964009640196402964039640496405964069640796408964099641096411964129641396414964159641696417964189641996420964219642296423964249642596426964279642896429964309643196432964339643496435964369643796438964399644096441964429644396444964459644696447964489644996450964519645296453964549645596456964579645896459964609646196462964639646496465964669646796468964699647096471964729647396474964759647696477964789647996480964819648296483964849648596486964879648896489964909649196492964939649496495964969649796498964999650096501965029650396504965059650696507965089650996510965119651296513965149651596516965179651896519965209652196522965239652496525965269652796528965299653096531965329653396534965359653696537965389653996540965419654296543965449654596546965479654896549965509655196552965539655496555965569655796558965599656096561965629656396564965659656696567965689656996570965719657296573965749657596576965779657896579965809658196582965839658496585965869658796588965899659096591965929659396594965959659696597965989659996600966019660296603966049660596606966079660896609966109661196612966139661496615966169661796618966199662096621966229662396624966259662696627966289662996630966319663296633966349663596636966379663896639966409664196642966439664496645966469664796648966499665096651966529665396654966559665696657966589665996660966619666296663966649666596666966679666896669966709667196672966739667496675966769667796678966799668096681966829668396684966859668696687966889668996690966919669296693966949669596696966979669896699967009670196702967039670496705967069670796708967099671096711967129671396714967159671696717967189671996720967219672296723967249672596726967279672896729967309673196732967339673496735967369673796738967399674096741967429674396744967459674696747967489674996750967519675296753967549675596756967579675896759967609676196762967639676496765967669676796768967699677096771967729677396774967759677696777967789677996780967819678296783967849678596786967879678896789967909679196792967939679496795967969679796798967999680096801968029680396804968059680696807968089680996810968119681296813968149681596816968179681896819968209682196822968239682496825968269682796828968299683096831968329683396834968359683696837968389683996840968419684296843968449684596846968479684896849968509685196852968539685496855968569685796858968599686096861968629686396864968659686696867968689686996870968719687296873968749687596876968779687896879968809688196882968839688496885968869688796888968899689096891968929689396894968959689696897968989689996900969019690296903969049690596906969079690896909969109691196912969139691496915969169691796918969199692096921969229692396924969259692696927969289692996930969319693296933969349693596936969379693896939969409694196942969439694496945969469694796948969499695096951969529695396954969559695696957969589695996960969619696296963969649696596966969679696896969969709697196972969739697496975969769697796978969799698096981969829698396984969859698696987969889698996990969919699296993969949699596996969979699896999970009700197002970039700497005970069700797008970099701097011970129701397014970159701697017970189701997020970219702297023970249702597026970279702897029970309703197032970339703497035970369703797038970399704097041970429704397044970459704697047970489704997050970519705297053970549705597056970579705897059970609706197062970639706497065970669706797068970699707097071970729707397074970759707697077970789707997080970819708297083970849708597086970879708897089970909709197092970939709497095970969709797098970999710097101971029710397104971059710697107971089710997110971119711297113971149711597116971179711897119971209712197122971239712497125971269712797128971299713097131971329713397134971359713697137971389713997140971419714297143971449714597146971479714897149971509715197152971539715497155971569715797158971599716097161971629716397164971659716697167971689716997170971719717297173971749717597176971779717897179971809718197182971839718497185971869718797188971899719097191971929719397194971959719697197971989719997200972019720297203972049720597206972079720897209972109721197212972139721497215972169721797218972199722097221972229722397224972259722697227972289722997230972319723297233972349723597236972379723897239972409724197242972439724497245972469724797248972499725097251972529725397254972559725697257972589725997260972619726297263972649726597266972679726897269972709727197272972739727497275972769727797278972799728097281972829728397284972859728697287972889728997290972919729297293972949729597296972979729897299973009730197302973039730497305973069730797308973099731097311973129731397314973159731697317973189731997320973219732297323973249732597326973279732897329973309733197332973339733497335973369733797338973399734097341973429734397344973459734697347973489734997350973519735297353973549735597356973579735897359973609736197362973639736497365973669736797368973699737097371973729737397374973759737697377973789737997380973819738297383973849738597386973879738897389973909739197392973939739497395973969739797398973999740097401974029740397404974059740697407974089740997410974119741297413974149741597416974179741897419974209742197422974239742497425974269742797428974299743097431974329743397434974359743697437974389743997440974419744297443974449744597446974479744897449974509745197452974539745497455974569745797458974599746097461974629746397464974659746697467974689746997470974719747297473974749747597476974779747897479974809748197482974839748497485974869748797488974899749097491974929749397494974959749697497974989749997500975019750297503975049750597506975079750897509975109751197512975139751497515975169751797518975199752097521975229752397524975259752697527975289752997530975319753297533975349753597536975379753897539975409754197542975439754497545975469754797548975499755097551975529755397554975559755697557975589755997560975619756297563975649756597566975679756897569975709757197572975739757497575975769757797578975799758097581975829758397584975859758697587975889758997590975919759297593975949759597596975979759897599976009760197602976039760497605976069760797608976099761097611976129761397614976159761697617976189761997620976219762297623976249762597626976279762897629976309763197632976339763497635976369763797638976399764097641976429764397644976459764697647976489764997650976519765297653976549765597656976579765897659976609766197662976639766497665976669766797668976699767097671976729767397674976759767697677976789767997680976819768297683976849768597686976879768897689976909769197692976939769497695976969769797698976999770097701977029770397704977059770697707977089770997710977119771297713977149771597716977179771897719977209772197722977239772497725977269772797728977299773097731977329773397734977359773697737977389773997740977419774297743977449774597746977479774897749977509775197752977539775497755977569775797758977599776097761977629776397764977659776697767977689776997770977719777297773977749777597776977779777897779977809778197782977839778497785977869778797788977899779097791977929779397794977959779697797977989779997800978019780297803978049780597806978079780897809978109781197812978139781497815978169781797818978199782097821978229782397824978259782697827978289782997830978319783297833978349783597836978379783897839978409784197842978439784497845978469784797848978499785097851978529785397854978559785697857978589785997860978619786297863978649786597866978679786897869978709787197872978739787497875978769787797878978799788097881978829788397884978859788697887978889788997890978919789297893978949789597896978979789897899979009790197902979039790497905979069790797908979099791097911979129791397914979159791697917979189791997920979219792297923979249792597926979279792897929979309793197932979339793497935979369793797938979399794097941979429794397944979459794697947979489794997950979519795297953979549795597956979579795897959979609796197962979639796497965979669796797968979699797097971979729797397974979759797697977979789797997980979819798297983979849798597986979879798897989979909799197992979939799497995979969799797998979999800098001980029800398004980059800698007980089800998010980119801298013980149801598016980179801898019980209802198022980239802498025980269802798028980299803098031980329803398034980359803698037980389803998040980419804298043980449804598046980479804898049980509805198052980539805498055980569805798058980599806098061980629806398064980659806698067980689806998070980719807298073980749807598076980779807898079980809808198082980839808498085980869808798088980899809098091980929809398094980959809698097980989809998100981019810298103981049810598106981079810898109981109811198112981139811498115981169811798118981199812098121981229812398124981259812698127981289812998130981319813298133981349813598136981379813898139981409814198142981439814498145981469814798148981499815098151981529815398154981559815698157981589815998160981619816298163981649816598166981679816898169981709817198172981739817498175981769817798178981799818098181981829818398184981859818698187981889818998190981919819298193981949819598196981979819898199982009820198202982039820498205982069820798208982099821098211982129821398214982159821698217982189821998220982219822298223982249822598226982279822898229982309823198232982339823498235982369823798238982399824098241982429824398244982459824698247982489824998250982519825298253982549825598256982579825898259982609826198262982639826498265982669826798268982699827098271982729827398274982759827698277982789827998280982819828298283982849828598286982879828898289982909829198292982939829498295982969829798298982999830098301983029830398304983059830698307983089830998310983119831298313983149831598316983179831898319983209832198322983239832498325983269832798328983299833098331983329833398334983359833698337983389833998340983419834298343983449834598346983479834898349983509835198352983539835498355983569835798358983599836098361983629836398364983659836698367983689836998370983719837298373983749837598376983779837898379983809838198382983839838498385983869838798388983899839098391983929839398394983959839698397983989839998400984019840298403984049840598406984079840898409984109841198412984139841498415984169841798418984199842098421984229842398424984259842698427984289842998430984319843298433984349843598436984379843898439984409844198442984439844498445984469844798448984499845098451984529845398454984559845698457984589845998460984619846298463984649846598466984679846898469984709847198472984739847498475984769847798478984799848098481984829848398484984859848698487984889848998490984919849298493984949849598496984979849898499985009850198502985039850498505985069850798508985099851098511985129851398514985159851698517985189851998520985219852298523985249852598526985279852898529985309853198532985339853498535985369853798538985399854098541985429854398544985459854698547985489854998550985519855298553985549855598556985579855898559985609856198562985639856498565985669856798568985699857098571985729857398574985759857698577985789857998580985819858298583985849858598586985879858898589985909859198592985939859498595985969859798598985999860098601986029860398604986059860698607986089860998610986119861298613986149861598616986179861898619986209862198622986239862498625986269862798628986299863098631986329863398634986359863698637986389863998640986419864298643986449864598646986479864898649986509865198652986539865498655986569865798658986599866098661986629866398664986659866698667986689866998670986719867298673986749867598676986779867898679986809868198682986839868498685986869868798688986899869098691986929869398694986959869698697986989869998700987019870298703987049870598706987079870898709987109871198712987139871498715987169871798718987199872098721987229872398724987259872698727987289872998730987319873298733987349873598736987379873898739987409874198742987439874498745987469874798748987499875098751987529875398754987559875698757987589875998760987619876298763987649876598766987679876898769987709877198772987739877498775987769877798778987799878098781987829878398784987859878698787987889878998790987919879298793987949879598796987979879898799988009880198802988039880498805988069880798808988099881098811988129881398814988159881698817988189881998820988219882298823988249882598826988279882898829988309883198832988339883498835988369883798838988399884098841988429884398844988459884698847988489884998850988519885298853988549885598856988579885898859988609886198862988639886498865988669886798868988699887098871988729887398874988759887698877988789887998880988819888298883988849888598886988879888898889988909889198892988939889498895988969889798898988999890098901989029890398904989059890698907989089890998910989119891298913989149891598916989179891898919989209892198922989239892498925989269892798928989299893098931989329893398934989359893698937989389893998940989419894298943989449894598946989479894898949989509895198952989539895498955989569895798958989599896098961989629896398964989659896698967989689896998970989719897298973989749897598976989779897898979989809898198982989839898498985989869898798988989899899098991989929899398994989959899698997989989899999000990019900299003990049900599006990079900899009990109901199012990139901499015990169901799018990199902099021990229902399024990259902699027990289902999030990319903299033990349903599036990379903899039990409904199042990439904499045990469904799048990499905099051990529905399054990559905699057990589905999060990619906299063990649906599066990679906899069990709907199072990739907499075990769907799078990799908099081990829908399084990859908699087990889908999090990919909299093990949909599096990979909899099991009910199102991039910499105991069910799108991099911099111991129911399114991159911699117991189911999120991219912299123991249912599126991279912899129991309913199132991339913499135991369913799138991399914099141991429914399144991459914699147991489914999150991519915299153991549915599156991579915899159991609916199162991639916499165991669916799168991699917099171991729917399174991759917699177991789917999180991819918299183991849918599186991879918899189991909919199192991939919499195991969919799198991999920099201992029920399204992059920699207992089920999210992119921299213992149921599216992179921899219992209922199222992239922499225992269922799228992299923099231992329923399234992359923699237992389923999240992419924299243992449924599246992479924899249992509925199252992539925499255992569925799258992599926099261992629926399264992659926699267992689926999270992719927299273992749927599276992779927899279992809928199282992839928499285992869928799288992899929099291992929929399294992959929699297992989929999300993019930299303993049930599306993079930899309993109931199312993139931499315993169931799318993199932099321993229932399324993259932699327993289932999330993319933299333993349933599336993379933899339993409934199342993439934499345993469934799348993499935099351993529935399354993559935699357993589935999360993619936299363993649936599366993679936899369993709937199372993739937499375993769937799378993799938099381993829938399384993859938699387993889938999390993919939299393993949939599396993979939899399994009940199402994039940499405994069940799408994099941099411994129941399414994159941699417994189941999420994219942299423994249942599426994279942899429994309943199432994339943499435994369943799438994399944099441994429944399444994459944699447994489944999450994519945299453994549945599456994579945899459994609946199462994639946499465994669946799468994699947099471994729947399474994759947699477994789947999480994819948299483994849948599486994879948899489994909949199492994939949499495994969949799498994999950099501995029950399504995059950699507995089950999510995119951299513995149951599516995179951899519995209952199522995239952499525995269952799528995299953099531995329953399534995359953699537995389953999540995419954299543995449954599546995479954899549995509955199552995539955499555995569955799558995599956099561995629956399564995659956699567995689956999570995719957299573995749957599576995779957899579995809958199582995839958499585995869958799588995899959099591995929959399594995959959699597995989959999600996019960299603996049960599606996079960899609996109961199612996139961499615996169961799618996199962099621996229962399624996259962699627996289962999630996319963299633996349963599636996379963899639996409964199642996439964499645996469964799648996499965099651996529965399654996559965699657996589965999660996619966299663996649966599666996679966899669996709967199672996739967499675996769967799678996799968099681996829968399684996859968699687996889968999690996919969299693996949969599696996979969899699997009970199702997039970499705997069970799708997099971099711997129971399714997159971699717997189971999720997219972299723997249972599726997279972899729997309973199732997339973499735997369973799738997399974099741997429974399744997459974699747997489974999750997519975299753997549975599756997579975899759997609976199762997639976499765997669976799768997699977099771997729977399774997759977699777997789977999780997819978299783997849978599786997879978899789997909979199792997939979499795997969979799798997999980099801998029980399804998059980699807998089980999810998119981299813998149981599816998179981899819998209982199822998239982499825998269982799828998299983099831998329983399834998359983699837998389983999840998419984299843998449984599846998479984899849998509985199852998539985499855998569985799858998599986099861998629986399864998659986699867998689986999870998719987299873998749987599876998779987899879998809988199882998839988499885998869988799888998899989099891998929989399894998959989699897998989989999900999019990299903999049990599906999079990899909999109991199912999139991499915999169991799918999199992099921999229992399924999259992699927999289992999930999319993299933999349993599936999379993899939999409994199942999439994499945999469994799948999499995099951999529995399954999559995699957999589995999960999619996299963999649996599966999679996899969999709997199972999739997499975999769997799978999799998099981999829998399984999859998699987999889998999990999919999299993999949999599996999979999899999100000100001100002100003100004100005100006100007100008100009100010100011100012100013100014100015100016100017100018100019100020100021100022100023100024100025100026100027100028100029100030100031100032100033100034100035100036100037100038100039100040100041100042100043100044100045100046100047100048100049100050100051100052100053100054100055100056100057100058100059100060100061100062100063100064100065100066100067100068100069100070100071100072100073100074100075100076100077100078100079100080100081100082100083100084100085100086100087100088100089100090100091100092100093100094100095100096100097100098100099100100100101100102100103100104100105100106100107100108100109100110100111100112100113100114100115100116100117100118100119100120100121100122100123100124100125100126100127100128100129100130100131100132100133100134100135100136100137100138100139100140100141100142100143100144100145100146100147100148100149100150100151100152100153100154100155100156100157100158100159100160100161100162100163100164100165100166100167100168100169100170100171100172100173100174100175100176100177100178100179100180100181100182100183100184100185100186100187100188100189100190100191100192100193100194100195100196100197100198100199100200100201100202100203100204100205100206100207100208100209100210100211100212100213100214100215100216100217100218100219100220100221100222100223100224100225100226100227100228100229100230100231100232100233100234100235100236100237100238100239100240100241100242100243100244100245100246100247100248100249100250100251100252100253100254100255100256100257100258100259100260100261100262100263100264100265100266100267100268100269100270100271100272100273100274100275100276100277100278100279100280100281100282100283100284100285100286100287100288100289100290100291100292100293100294100295100296100297100298100299100300100301100302100303100304100305100306100307100308100309100310100311100312100313100314100315100316100317100318100319100320100321100322100323100324100325100326100327100328100329100330100331100332100333100334100335100336100337100338100339100340100341100342100343100344100345100346100347100348100349100350100351100352100353100354100355100356100357100358100359100360100361100362100363100364100365100366100367100368100369100370100371100372100373100374100375100376100377100378100379100380100381100382100383100384100385100386100387100388100389100390100391100392100393100394100395100396100397100398100399100400100401100402100403100404100405100406100407100408100409100410100411100412100413100414100415100416100417100418100419100420100421100422100423100424100425100426100427100428100429100430100431100432100433100434100435100436100437100438100439100440100441100442100443100444100445100446100447100448100449100450100451100452100453100454100455100456100457100458100459100460100461100462100463100464100465100466100467100468100469100470100471100472100473100474100475100476100477100478100479100480100481100482100483100484100485100486100487100488100489100490100491100492100493100494100495100496100497100498100499100500100501100502100503100504100505100506100507100508100509100510100511100512100513100514100515100516100517100518100519100520100521100522100523100524100525100526100527100528100529100530100531100532100533100534100535100536100537100538100539100540100541100542100543100544100545100546100547100548100549100550100551100552100553100554100555100556100557100558100559100560100561100562100563100564100565100566100567100568100569100570100571100572100573100574100575100576100577100578100579100580100581100582100583100584100585100586100587100588100589100590100591100592100593100594100595100596100597100598100599100600100601100602100603100604100605100606100607100608100609100610100611100612100613100614100615100616100617100618100619100620100621100622100623100624100625100626100627100628100629100630100631100632100633100634100635100636100637100638100639100640100641100642100643100644100645100646100647100648100649100650100651100652100653100654100655100656100657100658100659100660100661100662100663100664100665100666100667100668100669100670100671100672100673100674100675100676100677100678100679100680100681100682100683100684100685100686100687100688100689100690100691100692100693100694100695100696100697100698100699100700100701100702100703100704100705100706100707100708100709100710100711100712100713100714100715100716100717100718100719100720100721100722100723100724100725100726100727100728100729100730100731100732100733100734100735100736100737100738100739100740100741100742100743100744100745100746100747100748100749100750100751100752100753100754100755100756100757100758100759100760100761100762100763100764100765100766100767100768100769100770100771100772100773100774100775100776100777100778100779100780100781100782100783100784100785100786100787100788100789100790100791100792100793100794100795100796100797100798100799100800100801100802100803100804100805100806100807100808100809100810100811100812100813100814100815100816100817100818100819100820100821100822100823100824100825100826100827100828100829100830100831100832100833100834100835100836100837100838100839100840100841100842100843100844100845100846100847100848100849100850100851100852100853100854100855100856100857100858100859100860100861100862100863100864100865100866100867100868100869100870100871100872100873100874100875100876100877100878100879100880100881100882100883100884100885100886100887100888100889100890100891100892100893100894100895100896100897100898100899100900100901100902100903100904100905100906100907100908100909100910100911100912100913100914100915100916100917100918100919100920100921100922100923100924100925100926100927100928100929100930100931100932100933100934100935100936100937100938100939100940100941100942100943100944100945100946100947100948100949100950100951100952100953100954100955100956100957100958100959100960100961100962100963100964100965100966100967100968100969100970100971100972100973100974100975100976100977100978100979100980100981100982100983100984100985100986100987100988100989100990100991100992100993100994100995100996100997100998100999101000101001101002101003101004101005101006101007101008101009101010101011101012101013101014101015101016101017101018101019101020101021101022101023101024101025101026101027101028101029101030101031101032101033101034101035101036101037101038101039101040101041101042101043101044101045101046101047101048101049101050101051101052101053101054101055101056101057101058101059101060101061101062101063101064101065101066101067101068101069101070101071101072101073101074101075101076101077101078101079101080101081101082101083101084101085101086101087101088101089101090101091101092101093101094101095101096101097101098101099101100101101101102101103101104101105101106101107101108101109101110101111101112101113101114101115101116101117101118101119101120101121101122101123101124101125101126101127101128101129101130101131101132101133101134101135101136101137101138101139101140101141101142101143101144101145101146101147101148101149101150101151101152101153101154101155101156101157101158101159101160101161101162101163101164101165101166101167101168101169101170101171101172101173101174101175101176101177101178101179101180101181101182101183101184101185101186101187101188101189101190101191101192101193101194101195101196101197101198101199101200101201101202101203101204101205101206101207101208101209101210101211101212101213101214101215101216101217101218101219101220101221101222101223101224101225101226101227101228101229101230101231101232101233101234101235101236101237101238101239101240101241101242101243101244101245101246101247101248101249101250101251101252101253101254101255101256101257101258101259101260101261101262101263101264101265101266101267101268101269101270101271101272101273101274101275101276101277101278101279101280101281101282101283101284101285101286101287101288101289101290101291101292101293101294101295101296101297101298101299101300101301101302101303101304101305101306101307101308101309101310101311101312101313101314101315101316101317101318101319101320101321101322101323101324101325101326101327101328101329101330101331101332101333101334101335101336101337101338101339101340101341101342101343101344101345101346101347101348101349101350101351101352101353101354101355101356101357101358101359101360101361101362101363101364101365101366101367101368101369101370101371101372101373101374101375101376101377101378101379101380101381101382101383101384101385101386101387101388101389101390101391101392101393101394101395101396101397101398101399101400101401101402101403101404101405101406101407101408101409101410101411101412101413101414101415101416101417101418101419101420101421101422101423101424101425101426101427101428101429101430101431101432101433101434101435101436101437101438101439101440101441101442101443101444101445101446101447101448101449101450101451101452101453101454101455101456101457101458101459101460101461101462101463101464101465101466101467101468101469101470101471101472101473101474101475101476101477101478101479101480101481101482101483101484101485101486101487101488101489101490101491101492101493101494101495101496101497101498101499101500101501101502101503101504101505101506101507101508101509101510101511101512101513101514101515101516101517101518101519101520101521101522101523101524101525101526101527101528101529101530101531101532101533101534101535101536101537101538101539101540101541101542101543101544101545101546101547101548101549101550101551101552101553101554101555101556101557101558101559101560101561101562101563101564101565101566101567101568101569101570101571101572101573101574101575101576101577101578101579101580101581101582101583101584101585101586101587101588101589101590101591101592101593101594101595101596101597101598101599101600101601101602101603101604101605101606101607101608101609101610101611101612101613101614101615101616101617101618101619101620101621101622101623101624101625101626101627101628101629101630101631101632101633101634101635101636101637101638101639101640101641101642101643101644101645101646101647101648101649101650101651101652101653101654101655101656101657101658101659101660101661101662101663101664101665101666101667101668101669101670101671101672101673101674101675101676101677101678101679101680101681101682101683101684101685101686101687101688101689101690101691101692101693101694101695101696101697101698101699101700101701101702101703101704101705101706101707101708101709101710101711101712101713101714101715101716101717101718101719101720101721101722101723101724101725101726101727101728101729101730101731101732101733101734101735101736101737101738101739101740101741101742101743101744101745101746101747101748101749101750101751101752101753101754101755101756101757101758101759101760101761101762101763101764101765101766101767101768101769101770101771101772101773101774101775101776101777101778101779101780101781101782101783101784101785101786101787101788101789101790101791101792101793101794101795101796101797101798101799101800101801101802101803101804101805101806101807101808101809101810101811101812101813101814101815101816101817101818101819101820101821101822101823101824101825101826101827101828101829101830101831101832101833101834101835101836101837101838101839101840101841101842101843101844101845101846101847101848101849101850101851101852101853101854101855101856101857101858101859101860101861101862101863101864101865101866101867101868101869101870101871101872101873101874101875101876101877101878101879101880101881101882101883101884101885101886101887101888101889101890101891101892101893101894101895101896101897101898101899101900101901101902101903101904101905101906101907101908101909101910101911101912101913101914101915101916101917101918101919101920101921101922101923101924101925101926101927101928101929101930101931101932101933101934101935101936101937101938101939101940101941101942101943101944101945101946101947101948101949101950101951101952101953101954101955101956101957101958101959101960101961101962101963101964101965101966101967101968101969101970101971101972101973101974101975101976101977101978101979101980101981101982101983101984101985101986101987101988101989101990101991101992101993101994101995101996101997101998101999102000102001102002102003102004102005102006102007102008102009102010102011102012102013102014102015102016102017102018102019102020102021102022102023102024102025102026102027102028102029102030102031102032102033102034102035102036102037102038102039102040102041102042102043102044102045102046102047102048102049102050102051102052102053102054102055102056102057102058102059102060102061102062102063102064102065102066102067102068102069102070102071102072102073102074102075102076102077102078102079102080102081102082102083102084102085102086102087102088102089102090102091102092102093102094102095102096102097102098102099102100102101102102102103102104102105102106102107102108102109102110102111102112102113102114102115102116102117102118102119102120102121102122102123102124102125102126102127102128102129102130102131102132102133102134102135102136102137102138102139102140102141102142102143102144102145102146102147102148102149102150102151102152102153102154102155102156102157102158102159102160102161102162102163102164102165102166102167102168102169102170102171102172102173102174102175102176102177102178102179102180102181102182102183102184102185102186102187102188102189102190102191102192102193102194102195102196102197102198102199102200102201102202102203102204102205102206102207102208102209102210102211102212102213102214102215102216102217102218102219102220102221102222102223102224102225102226102227102228102229102230102231102232102233102234102235102236102237102238102239102240102241102242102243102244102245102246102247102248102249102250102251102252102253102254102255102256102257102258102259102260102261102262102263102264102265102266102267102268102269102270102271102272102273102274102275102276102277102278102279102280102281102282102283102284102285102286102287102288102289102290102291102292102293102294102295102296102297102298102299102300102301102302102303102304102305102306102307102308102309102310102311102312102313102314102315102316102317102318102319102320102321102322102323102324102325102326102327102328102329102330102331102332102333102334102335102336102337102338102339102340102341102342102343102344102345102346102347102348102349102350102351102352102353102354102355102356102357102358102359102360102361102362102363102364102365102366102367102368102369102370102371102372102373102374102375102376102377102378102379102380102381102382102383102384102385102386102387102388102389102390102391102392102393102394102395102396102397102398102399102400102401102402102403102404102405102406102407102408102409102410102411102412102413102414102415102416102417102418102419102420102421102422102423102424102425102426102427102428102429102430102431102432102433102434102435102436102437102438102439102440102441102442102443102444102445102446102447102448102449102450102451102452102453102454102455102456102457102458102459102460102461102462102463102464102465102466102467102468102469102470102471102472102473102474102475102476102477102478102479102480102481102482102483102484102485102486102487102488102489102490102491102492102493102494102495102496102497102498102499102500102501102502102503102504102505102506102507102508102509102510102511102512102513102514102515102516102517102518102519102520102521102522102523102524102525102526102527102528102529102530102531102532102533102534102535102536102537102538102539102540102541102542102543102544102545102546102547102548102549102550102551102552102553102554102555102556102557102558102559102560102561102562102563102564102565102566102567102568102569102570102571102572102573102574102575102576102577102578102579102580102581102582102583102584102585102586102587102588102589102590102591102592102593102594102595102596102597102598102599102600102601102602102603102604102605102606102607102608102609102610102611102612102613102614102615102616102617102618102619102620102621102622102623102624102625102626102627102628102629102630102631102632102633102634102635102636102637102638102639102640102641102642102643102644102645102646102647102648102649102650102651102652102653102654102655102656102657102658102659102660102661102662102663102664102665102666102667102668102669102670102671102672102673102674102675102676102677102678102679102680102681102682102683102684102685102686102687102688102689102690102691102692102693102694102695102696102697102698102699102700102701102702102703102704102705102706102707102708102709102710102711102712102713102714102715102716102717102718102719102720102721102722102723102724102725102726102727102728102729102730102731102732102733102734102735102736102737102738102739102740102741102742102743102744102745102746102747102748102749102750102751102752102753102754102755102756102757102758102759102760102761102762102763102764102765102766102767102768102769102770102771102772102773102774102775102776102777102778102779102780102781102782102783102784102785102786102787102788102789102790102791102792102793102794102795102796102797102798102799102800102801102802102803102804102805102806102807102808102809102810102811102812102813102814102815102816102817102818102819102820102821102822102823102824102825102826102827102828102829102830102831102832102833102834102835102836102837102838102839102840102841102842102843102844102845102846102847102848102849102850102851102852102853102854102855102856102857102858102859102860102861102862102863102864102865102866102867102868102869102870102871102872102873102874102875102876102877102878102879102880102881102882102883102884102885102886102887102888102889102890102891102892102893102894102895102896102897102898102899102900102901102902102903102904102905102906102907102908102909102910102911102912102913102914102915102916102917102918102919102920102921102922102923102924102925102926102927102928102929102930102931102932102933102934102935102936102937102938102939102940102941102942102943102944102945102946102947102948102949102950102951102952102953102954102955102956102957102958102959102960102961102962102963102964102965102966102967102968102969102970102971102972102973102974102975102976102977102978102979102980102981102982102983102984102985102986102987102988102989102990102991102992102993102994102995102996102997102998102999103000103001103002103003103004103005103006103007103008103009103010103011103012103013103014103015103016103017103018103019103020103021103022103023103024103025103026103027103028103029103030103031103032103033103034103035103036103037103038103039103040103041103042103043103044103045103046103047103048103049103050103051103052103053103054103055103056103057103058103059103060103061103062103063103064103065103066103067103068103069103070103071103072103073103074103075103076103077103078103079103080103081103082103083103084103085103086103087103088103089103090103091103092103093103094103095103096103097103098103099103100103101103102103103103104103105103106103107103108103109103110103111103112103113103114103115103116103117103118103119103120103121103122103123103124103125103126103127103128103129103130103131103132103133103134103135103136103137103138103139103140103141103142103143103144103145103146103147103148103149103150103151103152103153103154103155103156103157103158103159103160103161103162103163103164103165103166103167103168103169103170103171103172103173103174103175103176103177103178103179103180103181103182103183103184103185103186103187103188103189103190103191103192103193103194103195103196103197103198103199103200103201103202103203103204103205103206103207103208103209103210103211103212103213103214103215103216103217103218103219103220103221103222103223103224103225103226103227103228103229103230103231103232103233103234103235103236103237103238103239103240103241103242103243103244103245103246103247103248103249103250103251103252103253103254103255103256103257103258103259103260103261103262103263103264103265103266103267103268103269103270103271103272103273103274103275103276103277103278103279103280103281103282103283103284103285103286103287103288103289103290103291103292103293103294103295103296103297103298103299103300103301103302103303103304103305103306103307103308103309103310103311103312103313103314103315103316103317103318103319103320103321103322103323103324103325103326103327103328103329103330103331103332103333103334103335103336103337103338103339103340103341103342103343103344103345103346103347103348103349103350103351103352103353103354103355103356103357103358103359103360103361103362103363103364103365103366103367103368103369103370103371103372103373103374103375103376103377103378103379103380103381103382103383103384103385103386103387103388103389103390103391103392103393103394103395103396103397103398103399103400103401103402103403103404103405103406103407103408103409103410103411103412103413103414103415103416103417103418103419103420103421103422103423103424103425103426103427103428103429103430103431103432103433103434103435103436103437103438103439103440103441103442103443103444103445103446103447103448103449103450103451103452103453103454103455103456103457103458103459103460103461103462103463103464103465103466103467103468103469103470103471103472103473103474103475103476103477103478103479103480103481103482103483103484103485103486103487103488103489103490103491103492103493103494103495103496103497103498103499103500103501103502103503103504103505103506103507103508103509103510103511103512103513103514103515103516103517103518103519103520103521103522103523103524103525103526103527103528103529103530103531103532103533103534103535103536103537103538103539103540103541103542103543103544103545103546103547103548103549103550103551103552103553103554103555103556103557103558103559103560103561103562103563103564103565103566103567103568103569103570103571103572103573103574103575103576103577103578103579103580103581103582103583103584103585103586103587103588103589103590103591103592103593103594103595103596103597103598103599103600103601103602103603103604103605103606103607103608103609103610103611103612103613103614103615103616103617103618103619103620103621103622103623103624103625103626103627103628103629103630103631103632103633103634103635103636103637103638103639103640103641103642103643103644103645103646103647103648103649103650103651103652103653103654103655103656103657103658103659103660103661103662103663103664103665103666103667103668103669103670103671103672103673103674103675103676103677103678103679103680103681103682103683103684103685103686103687103688103689103690103691103692103693103694103695103696103697103698103699103700103701103702103703103704103705103706103707103708103709103710103711103712103713103714103715103716103717103718103719103720103721103722103723103724103725103726103727103728103729103730103731103732103733103734103735103736103737103738103739103740103741103742103743103744103745103746103747103748103749103750103751103752103753103754103755103756103757103758103759103760103761103762103763103764103765103766103767103768103769103770103771103772103773103774103775103776103777103778103779103780103781103782103783103784103785103786103787103788103789103790103791103792103793103794103795103796103797103798103799103800103801103802103803103804103805103806103807103808103809103810103811103812103813103814103815103816103817103818103819103820103821103822103823103824103825103826103827103828103829103830103831103832103833103834103835103836103837103838103839103840103841103842103843103844103845103846103847103848103849103850103851103852103853103854103855103856103857103858103859103860103861103862103863103864103865103866103867103868103869103870103871103872103873103874103875103876103877103878103879103880103881103882103883103884103885103886103887103888103889103890103891103892103893103894103895103896103897103898103899103900103901103902103903103904103905103906103907103908103909103910103911103912103913103914103915103916103917103918103919103920103921103922103923103924103925103926103927103928103929103930103931103932103933103934103935103936103937103938103939103940103941103942103943103944103945103946103947103948103949103950103951103952103953103954103955103956103957103958103959103960103961103962103963103964103965103966103967103968103969103970103971103972103973103974103975103976103977103978103979103980103981103982103983103984103985103986103987103988103989103990103991103992103993103994103995103996103997103998103999104000104001104002104003104004104005104006104007104008104009104010104011104012104013104014104015104016104017104018104019104020104021104022104023104024104025104026104027104028104029104030104031104032104033104034104035104036104037104038104039104040104041104042104043104044104045104046104047104048104049104050104051104052104053104054104055104056104057104058104059104060104061104062104063104064104065104066104067104068104069104070104071104072104073104074104075104076104077104078104079104080104081104082104083104084104085104086104087104088104089104090104091104092104093104094104095104096104097104098104099104100104101104102104103104104104105104106104107104108104109104110104111104112104113104114104115104116104117104118104119104120104121104122104123104124104125104126104127104128104129104130104131104132104133104134104135104136104137104138104139104140104141104142104143104144104145104146104147104148104149104150104151104152104153104154104155104156104157104158104159104160104161104162104163104164104165104166104167104168104169104170104171104172104173104174104175104176104177104178104179104180104181104182104183104184104185104186104187104188104189104190104191104192104193104194104195104196104197104198104199104200104201104202104203104204104205104206104207104208104209104210104211104212104213104214104215104216104217104218104219104220104221104222104223104224104225104226104227104228104229104230104231104232104233104234104235104236104237104238104239104240104241104242104243104244104245104246104247104248104249104250104251104252104253104254104255104256104257104258104259104260104261104262104263104264104265104266104267104268104269104270104271104272104273104274104275104276104277104278104279104280104281104282104283104284104285104286104287104288104289104290104291104292104293104294104295104296104297104298104299104300104301104302104303104304104305104306104307104308104309104310104311104312104313104314104315104316104317104318104319104320104321104322104323104324104325104326104327104328104329104330104331104332104333104334104335104336104337104338104339104340104341104342104343104344104345104346104347104348104349104350104351104352104353104354104355104356104357104358104359104360104361104362104363104364104365104366104367104368104369104370104371104372104373104374104375104376104377104378104379104380104381104382104383104384104385104386104387104388104389104390104391104392104393104394104395104396104397104398104399104400104401104402104403104404104405104406104407104408104409104410104411104412104413104414104415104416104417104418104419104420104421104422104423104424104425104426104427104428104429104430104431104432104433104434104435104436104437104438104439104440104441104442104443104444104445104446104447104448104449104450104451104452104453104454104455104456104457104458104459104460104461104462104463104464104465104466104467104468104469104470104471104472104473104474104475104476104477104478104479104480104481104482104483104484104485104486104487104488104489104490104491104492104493104494104495104496104497104498104499104500104501104502104503104504104505104506104507104508104509104510104511104512104513104514104515104516104517104518104519104520104521104522104523104524104525104526104527104528104529104530104531104532104533104534104535104536104537104538104539104540104541104542104543104544104545104546104547104548104549104550104551104552104553104554104555104556104557104558104559104560104561104562104563104564104565104566104567104568104569104570104571104572104573104574104575104576104577104578104579104580104581104582104583104584104585104586104587104588104589104590104591104592104593104594104595104596104597104598104599104600104601104602104603104604104605104606104607104608104609104610104611104612104613104614104615104616104617104618104619104620104621104622104623104624104625104626104627104628104629104630104631104632104633104634104635104636104637104638104639104640104641104642104643104644104645104646104647104648104649104650104651104652104653104654104655104656104657104658104659104660104661104662104663104664104665104666104667104668104669104670104671104672104673104674104675104676104677104678104679104680104681104682104683104684104685104686104687104688104689104690104691104692104693104694104695104696104697104698104699104700104701104702104703104704104705104706104707104708104709104710104711104712104713104714104715104716104717104718104719104720104721104722104723104724104725104726104727104728104729104730104731104732104733104734104735104736104737104738104739104740104741104742104743104744104745104746104747104748104749104750104751104752104753104754104755104756104757104758104759104760104761104762104763104764104765104766104767104768104769104770104771104772104773104774104775104776104777104778104779104780104781104782104783104784104785104786104787104788104789104790104791104792104793104794104795104796104797104798104799104800104801104802104803104804104805104806104807104808104809104810104811104812104813104814104815104816104817104818104819104820104821104822104823104824104825104826104827104828104829104830104831104832104833104834104835104836104837104838104839104840104841104842104843104844104845104846104847104848104849104850104851104852104853104854104855104856104857104858104859104860104861104862104863104864104865104866104867104868104869104870104871104872104873104874104875104876104877104878104879104880104881104882104883104884104885104886104887104888104889104890104891104892104893104894104895104896104897104898104899104900104901104902104903104904104905104906104907104908104909104910104911104912104913104914104915104916104917104918104919104920104921104922104923104924104925104926104927104928104929104930104931104932104933104934104935104936104937104938104939104940104941104942104943104944104945104946104947104948104949104950104951104952104953104954104955104956104957104958104959104960104961104962104963104964104965104966104967104968104969104970104971104972104973104974104975104976104977104978104979104980104981104982104983104984104985104986104987104988104989104990104991104992104993104994104995104996104997104998104999105000105001105002105003105004105005105006105007105008105009105010105011105012105013105014105015105016105017105018105019105020105021105022105023105024105025105026105027105028105029105030105031105032105033105034105035105036105037105038105039105040105041105042105043105044105045105046105047105048105049105050105051105052105053105054105055105056105057105058105059105060105061105062105063105064105065105066105067105068105069105070105071105072105073105074105075105076105077105078105079105080105081105082105083105084105085105086105087105088105089105090105091105092105093105094105095105096105097105098105099105100105101105102105103105104105105105106105107105108105109105110105111105112105113105114105115105116105117105118105119105120105121105122105123105124105125105126105127105128105129105130105131105132105133105134105135105136105137105138105139105140105141105142105143105144105145105146105147105148105149105150105151105152105153105154105155105156105157105158105159105160105161105162105163105164105165105166105167105168105169105170105171105172105173105174105175105176105177105178105179105180105181105182105183105184105185105186105187105188105189105190105191105192105193105194105195105196105197105198105199105200105201105202105203105204105205105206105207105208105209105210105211105212105213105214105215105216105217105218105219105220105221105222105223105224105225105226105227105228105229105230105231105232105233105234105235105236105237105238105239105240105241105242105243105244105245105246105247105248105249105250105251105252105253105254105255105256105257105258105259105260105261105262105263105264105265105266105267105268105269105270105271105272105273105274105275105276105277105278105279105280105281105282105283105284105285105286105287105288105289105290105291105292105293105294105295105296105297105298105299105300105301105302105303105304105305105306105307105308105309105310105311105312105313105314105315105316105317105318105319105320105321105322105323105324105325105326105327105328105329105330105331105332105333105334105335105336105337105338105339105340105341105342105343105344105345105346105347105348105349105350105351105352105353105354105355105356105357105358105359105360105361105362105363105364105365105366105367105368105369105370105371105372105373105374105375105376105377105378105379105380105381105382105383105384105385105386105387105388105389105390105391105392105393105394105395105396105397105398105399105400105401105402105403105404105405105406105407105408105409105410105411105412105413105414105415105416105417105418105419105420105421105422105423105424105425105426105427105428105429105430105431105432105433105434105435105436105437105438105439105440105441105442105443105444105445105446105447105448105449105450105451105452105453105454105455105456105457105458105459105460105461105462105463105464105465105466105467105468105469105470105471105472105473105474105475105476105477105478105479105480105481105482105483105484105485105486105487105488105489105490105491105492105493105494105495105496105497105498105499105500105501105502105503105504105505105506105507105508105509105510105511105512105513105514105515105516105517105518105519105520105521105522105523105524105525105526105527105528105529105530105531105532105533105534105535105536105537105538105539105540105541105542105543105544105545105546105547105548105549105550105551105552105553105554105555105556105557105558105559105560105561105562105563105564105565105566105567105568105569105570105571105572105573105574105575105576105577105578105579105580105581105582105583105584105585105586105587105588105589105590105591105592105593105594105595105596105597105598105599105600105601105602105603105604105605105606105607105608105609105610105611105612105613105614105615105616105617105618105619105620105621105622105623105624105625105626105627105628105629105630105631105632105633105634105635105636105637105638105639105640105641105642105643105644105645105646105647105648105649105650105651105652105653105654105655105656105657105658105659105660105661105662105663105664105665105666105667105668105669105670105671105672105673105674105675105676105677105678105679105680105681105682105683105684105685105686105687105688105689105690105691105692105693105694105695105696105697105698105699105700105701105702105703105704105705105706105707105708105709105710105711105712105713105714105715105716105717105718105719105720105721105722105723105724105725105726105727105728105729105730105731105732105733105734105735105736105737105738105739105740105741105742105743105744105745105746105747105748105749105750105751105752105753105754105755105756105757105758105759105760105761105762105763105764105765105766105767105768105769105770105771105772105773105774105775105776105777105778105779105780105781105782105783105784105785105786105787105788105789105790105791105792105793105794105795105796105797105798105799105800105801105802105803105804105805105806105807105808105809105810105811105812105813105814105815105816105817105818105819105820105821105822105823105824105825105826105827105828105829105830105831105832105833105834105835105836105837105838105839105840105841105842105843105844105845105846105847105848105849105850105851105852105853105854105855105856105857105858105859105860105861105862105863105864105865105866105867105868105869105870105871105872105873105874105875105876105877105878105879105880105881105882105883105884105885105886105887105888105889105890105891105892105893105894105895105896105897105898105899105900105901105902105903105904105905105906105907105908105909105910105911105912105913105914105915105916105917105918105919105920105921105922105923105924105925105926105927105928105929105930105931105932105933105934105935105936105937105938105939105940105941105942105943105944105945105946105947105948105949105950105951105952105953105954105955105956105957105958105959105960105961105962105963105964105965105966105967105968105969105970105971105972105973105974105975105976105977105978105979105980105981105982105983105984105985105986105987105988105989105990105991105992105993105994105995105996105997105998105999106000106001106002106003106004106005106006106007106008106009106010106011106012106013106014106015106016106017106018106019106020106021106022106023106024106025106026106027106028106029106030106031106032106033106034106035106036106037106038106039106040106041106042106043106044106045106046106047106048106049106050106051106052106053106054106055106056106057106058106059106060106061106062106063106064106065106066106067106068106069106070106071106072106073106074106075106076106077106078106079106080106081106082106083106084106085106086106087106088106089106090106091106092106093106094106095106096106097106098106099106100106101106102106103106104106105106106106107106108106109106110106111106112106113106114106115106116106117106118106119106120106121106122106123106124106125106126106127106128106129106130106131106132106133106134106135106136106137106138106139106140106141106142106143106144106145106146106147106148106149106150106151106152106153106154106155106156106157106158106159106160106161106162106163106164106165106166106167106168106169106170106171106172106173106174106175106176106177106178106179106180106181106182106183106184106185106186106187106188106189106190106191106192106193106194106195106196106197106198106199106200106201106202106203106204106205106206106207106208106209106210106211106212106213106214106215106216106217106218106219106220106221106222106223106224106225106226106227106228106229106230106231106232106233106234106235106236106237106238106239106240106241106242106243106244106245106246106247106248106249106250106251106252106253106254106255106256106257106258106259106260106261106262106263106264106265106266106267106268106269106270106271106272106273106274106275106276106277106278106279106280106281106282106283106284106285106286106287106288106289106290106291106292106293106294106295106296106297106298106299106300106301106302106303106304106305106306106307106308106309106310106311106312106313106314106315106316106317106318106319106320106321106322106323106324106325106326106327106328106329106330106331106332106333106334106335106336106337106338106339106340106341106342106343106344106345106346106347106348106349106350106351106352106353106354106355106356106357106358106359106360106361106362106363106364106365106366106367106368106369106370106371106372106373106374106375106376106377106378106379106380106381106382106383106384106385106386106387106388106389106390106391106392106393106394106395106396106397106398106399106400106401106402106403106404106405106406106407106408106409106410106411106412106413106414106415106416106417106418106419106420106421106422106423106424106425106426106427106428106429106430106431106432106433106434106435106436106437106438106439106440106441106442106443106444106445106446106447106448106449106450106451106452106453106454106455106456106457106458106459106460106461106462106463106464106465106466106467106468106469106470106471106472106473106474106475106476106477106478106479106480106481106482106483106484106485106486106487106488106489106490106491106492106493106494106495106496106497106498106499106500106501106502106503106504106505106506106507106508106509106510106511106512106513106514106515106516106517106518106519106520106521106522106523106524106525106526106527106528106529106530106531106532106533106534106535106536106537106538106539106540106541106542106543106544106545106546106547106548106549106550106551106552106553106554106555106556106557106558106559106560106561106562106563106564106565106566106567106568106569106570106571106572106573106574106575106576106577106578106579106580106581106582106583106584106585106586106587106588106589106590106591106592106593106594106595106596106597106598106599106600106601106602106603106604106605106606106607106608106609106610106611106612106613106614106615106616106617106618106619106620106621106622106623106624106625106626106627106628106629106630106631106632106633106634106635106636106637106638106639106640106641106642106643106644106645106646106647106648106649106650106651106652106653106654106655106656106657106658106659106660106661106662106663106664106665106666106667106668106669106670106671106672106673106674106675106676106677106678106679106680106681106682106683106684106685106686106687106688106689106690106691106692106693106694106695106696106697106698106699106700106701106702106703106704106705106706106707106708106709106710106711106712106713106714106715106716106717106718106719106720106721106722106723106724106725106726106727106728106729106730106731106732106733106734106735106736106737106738106739106740106741106742106743106744106745106746106747106748106749106750106751106752106753106754106755106756106757106758106759106760106761106762106763106764106765106766106767106768106769106770106771106772106773106774106775106776106777106778106779106780106781106782106783106784106785106786106787106788106789106790106791106792106793106794106795106796106797106798106799106800106801106802106803106804106805106806106807106808106809106810106811106812106813106814106815106816106817106818106819106820106821106822106823106824106825106826106827106828106829106830106831106832106833106834106835106836106837106838106839106840106841106842106843106844106845106846106847106848106849106850106851106852106853106854106855106856106857106858106859106860106861106862106863106864106865106866106867106868106869106870106871106872106873106874106875106876106877106878106879106880106881106882106883106884106885106886106887106888106889106890106891106892106893106894106895106896106897106898106899106900106901106902106903106904106905106906106907106908106909106910106911106912106913106914106915106916106917106918106919106920106921106922106923106924106925106926106927106928106929106930106931106932106933106934106935106936106937106938106939106940106941106942106943106944106945106946106947106948106949106950106951106952106953106954106955106956106957106958106959106960106961106962106963106964106965106966106967106968106969106970106971106972106973106974106975106976106977106978106979106980106981106982106983106984106985106986106987106988106989106990106991106992106993106994106995106996106997106998106999107000107001107002107003107004107005107006107007107008107009107010107011107012107013107014107015107016107017107018107019107020107021107022107023107024107025107026107027107028107029107030107031107032107033107034107035107036107037107038107039107040107041107042107043107044107045107046107047107048107049107050107051107052107053107054107055107056107057107058107059107060107061107062107063107064107065107066107067107068107069107070107071107072107073107074107075107076107077107078107079107080107081107082107083107084107085107086107087107088107089107090107091107092107093107094107095107096107097107098107099107100107101107102107103107104107105107106107107107108107109107110107111107112107113107114107115107116107117107118107119107120107121107122107123107124107125107126107127107128107129107130107131107132107133107134107135107136107137107138107139107140107141107142107143107144107145107146107147107148107149107150107151107152107153107154107155107156107157107158107159107160107161107162107163107164107165107166107167107168107169107170107171107172107173107174107175107176107177107178107179107180107181107182107183107184107185107186107187107188107189107190107191107192107193107194107195107196107197107198107199107200107201107202107203107204107205107206107207107208107209107210107211107212107213107214107215107216107217107218107219107220107221107222107223107224107225107226107227107228107229107230107231107232107233107234107235107236107237107238107239107240107241107242107243107244107245107246107247107248107249107250107251107252107253107254107255107256107257107258107259107260107261107262107263107264107265107266107267107268107269107270107271107272107273107274107275107276107277107278107279107280107281107282107283107284107285107286107287107288107289107290107291107292107293107294107295107296107297107298107299107300107301107302107303107304107305107306107307107308107309107310107311107312107313107314107315107316107317107318107319107320107321107322107323107324107325107326107327107328107329107330107331107332107333107334107335107336107337107338107339107340107341107342107343107344107345107346107347107348107349107350107351107352107353107354107355107356107357107358107359107360107361107362107363107364107365107366107367107368107369107370107371107372107373107374107375107376107377107378107379107380107381107382107383107384107385107386107387107388107389107390107391107392107393107394107395107396107397107398107399107400107401107402107403107404107405107406107407107408107409107410107411107412107413107414107415107416107417107418107419107420107421107422107423107424107425107426107427107428107429107430107431107432107433107434107435107436107437107438107439107440107441107442107443107444107445107446107447107448107449107450107451107452107453107454107455107456107457107458107459107460107461107462107463107464107465107466107467107468107469107470107471107472107473107474107475107476107477107478107479107480107481107482107483107484107485107486107487107488107489107490107491107492107493107494107495107496107497107498107499107500107501107502107503107504107505107506107507107508107509107510107511107512107513107514107515107516107517107518107519107520107521107522107523107524107525107526107527107528107529107530107531107532107533107534107535107536107537107538107539107540107541107542107543107544107545107546107547107548107549107550107551107552107553107554107555107556107557107558107559107560107561107562107563107564107565107566107567107568107569107570107571107572107573107574107575107576107577107578107579107580107581107582107583107584107585107586107587107588107589107590107591107592107593107594107595107596107597107598107599107600107601107602107603107604107605107606107607107608107609107610107611107612107613107614107615107616107617107618107619107620107621107622107623107624107625107626107627107628107629107630107631107632107633107634107635107636107637107638107639107640107641107642107643107644107645107646107647107648107649107650107651107652107653107654107655107656107657107658107659107660107661107662107663107664107665107666107667107668107669107670107671107672107673107674107675107676107677107678107679107680107681107682107683107684107685107686107687107688107689107690107691107692107693107694107695107696107697107698107699107700107701107702107703107704107705107706107707107708107709107710107711107712107713107714107715107716107717107718107719107720107721107722107723107724107725107726107727107728107729107730107731107732107733107734107735107736107737107738107739107740107741107742107743107744107745107746107747107748107749107750107751107752107753107754107755107756107757107758107759107760107761107762107763107764107765107766107767107768107769107770107771107772107773107774107775107776107777107778107779107780107781107782107783107784107785107786107787107788107789107790107791107792107793107794107795107796107797107798107799107800107801107802107803107804107805107806107807107808107809107810107811107812107813107814107815107816107817107818107819107820107821107822107823107824107825107826107827107828107829107830107831107832107833107834107835107836107837107838107839107840107841107842107843107844107845107846107847107848107849107850107851107852107853107854107855107856107857107858107859107860107861107862107863107864107865107866107867107868107869107870107871107872107873107874107875107876107877107878107879107880107881107882107883107884107885107886107887107888107889107890107891107892107893107894107895107896107897107898107899107900107901107902107903107904107905107906107907107908107909107910107911107912107913107914107915107916107917107918107919107920107921107922107923107924107925107926107927107928107929107930107931107932107933107934107935107936107937107938107939107940107941107942107943107944107945107946107947107948107949107950107951107952107953107954107955107956107957107958107959107960107961107962107963107964107965107966107967107968107969107970107971107972107973107974107975107976107977107978107979107980107981107982107983107984107985107986107987107988107989107990107991107992107993107994107995107996107997107998107999108000108001108002108003108004108005108006108007108008108009108010108011108012108013108014108015108016108017108018108019108020108021108022108023108024108025108026108027108028108029108030108031108032108033108034108035108036108037108038108039108040108041108042108043108044108045108046108047108048108049108050108051108052108053108054108055108056108057108058108059108060108061108062108063108064108065108066108067108068108069108070108071108072108073108074108075108076108077108078108079108080108081108082108083108084108085108086108087108088108089108090108091108092108093108094108095108096108097108098108099108100108101108102108103108104108105108106108107108108108109108110108111108112108113108114108115108116108117108118108119108120108121108122108123108124108125108126108127108128108129108130108131108132108133108134108135108136108137108138108139108140108141108142108143108144108145108146108147108148108149108150108151108152108153108154108155108156108157108158108159108160108161108162108163108164108165108166108167108168108169108170108171108172108173108174108175108176108177108178108179108180108181108182108183108184108185108186108187108188108189108190108191108192108193108194108195108196108197108198108199108200108201108202108203108204108205108206108207108208108209108210108211108212108213108214108215108216108217108218108219108220108221108222108223108224108225108226108227108228108229108230108231108232108233108234108235108236108237108238108239108240108241108242108243108244108245108246108247108248108249108250108251108252108253108254108255108256108257108258108259108260108261108262108263108264108265108266108267108268108269108270108271108272108273108274108275108276108277108278108279108280108281108282108283108284108285108286108287108288108289108290108291108292108293108294108295108296108297108298108299108300108301108302108303108304108305108306108307108308108309108310108311108312108313108314108315108316108317108318108319108320108321108322108323108324108325108326108327108328108329108330108331108332108333108334108335108336108337108338108339108340108341108342108343108344108345108346108347108348108349108350108351108352108353108354108355108356108357108358108359108360108361108362108363108364108365108366108367108368108369108370108371108372108373108374108375108376108377108378108379108380108381108382108383108384108385108386108387108388108389108390108391108392108393108394108395108396108397108398108399108400108401108402108403108404108405108406108407108408108409108410108411108412108413108414108415108416108417108418108419108420108421108422108423108424108425108426108427108428108429108430108431108432108433108434108435108436108437108438108439108440108441108442108443108444108445108446108447108448108449108450108451108452108453108454108455108456108457108458108459108460108461108462108463108464108465108466108467108468108469108470108471108472108473108474108475108476108477108478108479108480108481108482108483108484108485108486108487108488108489108490108491108492108493108494108495108496108497108498108499108500108501108502108503108504108505108506108507108508108509108510108511108512108513108514108515108516108517108518108519108520108521108522108523108524108525108526108527108528108529108530108531108532108533108534108535108536108537108538108539108540108541108542108543108544108545108546108547108548108549108550108551108552108553108554108555108556108557108558108559108560108561108562108563108564108565108566108567108568108569108570108571108572108573108574108575108576108577108578108579108580108581108582108583108584108585108586108587108588108589108590108591108592108593108594108595108596108597108598108599108600108601108602108603108604108605108606108607108608108609108610108611108612108613108614108615108616108617108618108619108620108621108622108623108624108625108626108627108628108629108630108631108632108633108634108635108636108637108638108639108640108641108642108643108644108645108646108647108648108649108650108651108652108653108654108655108656108657108658108659108660108661108662108663108664108665108666108667108668108669108670108671108672108673108674108675108676108677108678108679108680108681108682108683108684108685108686108687108688108689108690108691108692108693108694108695108696108697108698108699108700108701108702108703108704108705108706108707108708108709108710108711108712108713108714108715108716108717108718108719108720108721108722108723108724108725108726108727108728108729108730108731108732108733108734108735108736108737108738108739108740108741108742108743108744108745108746108747108748108749108750108751108752108753108754108755108756108757108758108759108760108761108762108763108764108765108766108767108768108769108770108771108772108773108774108775108776108777108778108779108780108781108782108783108784108785108786108787108788108789108790108791108792108793108794108795108796108797108798108799108800108801108802108803108804108805108806108807108808108809108810108811108812108813108814108815108816108817108818108819108820108821108822108823108824108825108826108827108828108829108830108831108832108833108834108835108836108837108838108839108840108841108842108843108844108845108846108847108848108849108850108851108852108853108854108855108856108857108858108859108860108861108862108863108864108865108866108867108868108869108870108871108872108873108874108875108876108877108878108879108880108881108882108883108884108885108886108887108888108889108890108891108892108893108894108895108896108897108898108899108900108901108902108903108904108905108906108907108908108909108910108911108912108913108914108915108916108917108918108919108920108921108922108923108924108925108926108927108928108929108930108931108932108933108934108935108936108937108938108939108940108941108942108943108944108945108946108947108948108949108950108951108952108953108954108955108956108957108958108959108960108961108962108963108964108965108966108967108968108969108970108971108972108973108974108975108976108977108978108979108980108981108982108983108984108985108986108987108988108989108990108991108992108993108994108995108996108997108998108999109000109001109002109003109004109005109006109007109008109009109010109011109012109013109014109015109016109017109018109019109020109021109022109023109024109025109026109027109028109029109030109031109032109033109034109035109036109037109038109039109040109041109042109043109044109045109046109047109048109049109050109051109052109053109054109055109056109057109058109059109060109061109062109063109064109065109066109067109068109069109070109071109072109073109074109075109076109077109078109079109080109081109082109083109084109085109086109087109088109089109090109091109092109093109094109095109096109097109098109099109100109101109102109103109104109105109106109107109108109109109110109111109112109113109114109115109116109117109118109119109120109121109122109123109124109125109126109127109128109129109130109131109132109133109134109135109136109137109138109139109140109141109142109143109144109145109146109147109148109149109150109151109152109153109154109155109156109157109158109159109160109161109162109163109164109165109166109167109168109169109170109171109172109173109174109175109176109177109178109179109180109181109182109183109184109185109186109187109188109189109190109191109192109193109194109195109196109197109198109199109200109201109202109203109204109205109206109207109208109209109210109211109212109213109214109215109216109217109218109219109220109221109222109223109224109225109226109227109228109229109230109231109232109233109234109235109236109237109238109239109240109241109242109243109244109245109246109247109248109249109250109251109252109253109254109255109256109257109258109259109260109261109262109263109264109265109266109267109268109269109270109271109272109273109274109275109276109277109278109279109280109281109282109283109284109285109286109287109288109289109290109291109292109293109294109295109296109297109298109299109300109301109302109303109304109305109306109307109308109309109310109311109312109313109314109315109316109317109318109319109320109321109322109323109324109325109326109327109328109329109330109331109332109333109334109335109336109337109338109339109340109341109342109343109344109345109346109347109348109349109350109351109352109353109354109355109356109357109358109359109360109361109362109363109364109365109366109367109368109369109370109371109372109373109374109375109376109377109378109379109380109381109382109383109384109385109386109387109388109389109390109391109392109393109394109395109396109397109398109399109400109401109402109403109404109405109406109407109408109409109410109411109412109413109414109415109416109417109418109419109420109421109422109423109424109425109426109427109428109429109430109431109432109433109434109435109436109437109438109439109440109441109442109443109444109445109446109447109448109449109450109451109452109453109454109455109456109457109458109459109460109461109462109463109464109465109466109467109468109469109470109471109472109473109474109475109476109477109478109479109480109481109482109483109484109485109486109487109488109489109490109491109492109493109494109495109496109497109498109499109500109501109502109503109504109505109506109507109508109509109510109511109512109513109514109515109516109517109518109519109520109521109522109523109524109525109526109527109528109529109530109531109532109533109534109535109536109537109538109539109540109541109542109543109544109545109546109547109548109549109550109551109552109553109554109555109556109557109558109559109560109561109562109563109564109565109566109567109568109569109570109571109572109573109574109575109576109577109578109579109580109581109582109583109584109585109586109587109588109589109590109591109592109593109594109595109596109597109598109599109600109601109602109603109604109605109606109607109608109609109610109611109612109613109614109615109616109617109618109619109620109621109622109623109624109625109626109627109628109629109630109631109632109633109634109635109636109637109638109639109640109641109642109643109644109645109646109647109648109649109650109651109652109653109654109655109656109657109658109659109660109661109662109663109664109665109666109667109668109669109670109671109672109673109674109675109676109677109678109679109680109681109682109683109684109685109686109687109688109689109690109691109692109693109694109695109696109697109698109699109700109701109702109703109704109705109706109707109708109709109710109711109712109713109714109715109716109717109718109719109720109721109722109723109724109725109726109727109728109729109730109731109732109733109734109735109736109737109738109739109740109741109742109743109744109745109746109747109748109749109750109751109752109753109754109755109756109757109758109759109760109761109762109763109764109765109766109767109768109769109770109771109772109773109774109775109776109777109778109779109780109781109782109783109784109785109786109787109788109789109790109791109792109793109794109795109796109797109798109799109800109801109802109803109804109805109806109807109808109809109810109811109812109813109814109815109816109817109818109819109820109821109822109823109824109825109826109827109828109829109830109831109832109833109834109835109836109837109838109839109840109841109842109843109844109845109846109847109848109849109850109851109852109853109854109855109856109857109858109859109860109861109862109863109864109865109866109867109868109869109870109871109872109873109874109875109876109877109878109879109880109881109882109883109884109885109886109887109888109889109890109891109892109893109894109895109896109897109898109899109900109901109902109903109904109905109906109907109908109909109910109911109912109913109914109915109916109917109918109919109920109921109922109923109924109925109926109927109928109929109930109931109932109933109934109935109936109937109938109939109940109941109942109943109944109945109946109947109948109949109950109951109952109953109954109955109956109957109958109959109960109961109962109963109964109965109966109967109968109969109970109971109972109973109974109975109976109977109978109979109980109981109982109983109984109985109986109987109988109989109990109991109992109993109994109995109996109997109998109999110000110001110002110003110004110005110006110007110008110009110010110011110012110013110014110015110016110017110018110019110020110021110022110023110024110025110026110027110028110029110030110031110032110033110034110035110036110037110038110039110040110041110042110043110044110045110046110047110048110049110050110051110052110053110054110055110056110057110058110059110060110061110062110063110064110065110066110067110068110069110070110071110072110073110074110075110076110077110078110079110080110081110082110083110084110085110086110087110088110089110090110091110092110093110094110095110096110097110098110099110100110101110102110103110104110105110106110107110108110109110110110111110112110113110114110115110116110117110118110119110120110121110122110123110124110125110126110127110128110129110130110131110132110133110134110135110136110137110138110139110140110141110142110143110144110145110146110147110148110149110150110151110152110153110154110155110156110157110158110159110160110161110162110163110164110165110166110167110168110169110170110171110172110173110174110175110176110177110178110179110180110181110182110183110184110185110186110187110188110189110190110191110192110193110194110195110196110197110198110199110200110201110202110203110204110205110206110207110208110209110210110211110212110213110214110215110216110217110218110219110220110221110222110223110224110225110226110227110228110229110230110231110232110233110234110235110236110237110238110239110240110241110242110243110244110245110246110247110248110249110250110251110252110253110254110255110256110257110258110259110260110261110262110263110264110265110266110267110268110269110270110271110272110273110274110275110276110277110278110279110280110281110282110283110284110285110286110287110288110289110290110291110292110293110294110295110296110297110298110299110300110301110302110303110304110305110306110307110308110309110310110311110312110313110314110315110316110317110318110319110320110321110322110323110324110325110326110327110328110329110330110331110332110333110334110335110336110337110338110339110340110341110342110343110344110345110346110347110348110349110350110351110352110353110354110355110356110357110358110359110360110361110362110363110364110365110366110367110368110369110370110371110372110373110374110375110376110377110378110379110380110381110382110383110384110385110386110387110388110389110390110391110392110393110394110395110396110397110398110399110400110401110402110403110404110405110406110407110408110409110410110411110412110413110414110415110416110417110418110419110420110421110422110423110424110425110426110427110428110429110430110431110432110433110434110435110436110437110438110439110440110441110442110443110444110445110446110447110448110449110450110451110452110453110454110455110456110457110458110459110460110461110462110463110464110465110466110467110468110469110470110471110472110473110474110475110476110477110478110479110480110481110482110483110484110485110486110487110488110489110490110491110492110493110494110495110496110497110498110499110500110501110502110503110504110505110506110507110508110509110510110511110512110513110514110515110516110517110518110519110520110521110522110523110524110525110526110527110528110529110530110531110532110533110534110535110536110537110538110539110540110541110542110543110544110545110546110547110548110549110550110551110552110553110554110555110556110557110558110559110560110561110562110563110564110565110566110567110568110569110570110571110572110573110574110575110576110577110578110579110580110581110582110583110584110585110586110587110588110589110590110591110592110593110594110595110596110597110598110599110600110601110602110603110604110605110606110607110608110609110610110611110612110613110614110615110616110617110618110619110620110621110622110623110624110625110626110627110628110629110630110631110632110633110634110635110636110637110638110639110640110641110642110643110644110645110646110647110648110649110650110651110652110653110654110655110656110657110658110659110660110661110662110663110664110665110666110667110668110669110670110671110672110673110674110675110676110677110678110679110680110681110682110683110684110685110686110687110688110689110690110691110692110693110694110695110696110697110698110699110700110701110702110703110704110705110706110707110708110709110710110711110712110713110714110715110716110717110718110719110720110721110722110723110724110725110726110727110728110729110730110731110732110733110734110735110736110737110738110739110740110741110742110743110744110745110746110747110748110749110750110751110752110753110754110755110756110757110758110759110760110761110762110763110764110765110766110767110768110769110770110771110772110773110774110775110776110777110778110779110780110781110782110783110784110785110786110787110788110789110790110791110792110793110794110795110796110797110798110799110800110801110802110803110804110805110806110807110808110809110810110811110812110813110814110815110816110817110818110819110820110821110822110823110824110825110826110827110828110829110830110831110832110833110834110835110836110837110838110839110840110841110842110843110844110845110846110847110848110849110850110851110852110853110854110855110856110857110858110859110860110861110862110863110864110865110866110867110868110869110870110871110872110873110874110875110876110877110878110879110880110881110882110883110884110885110886110887110888110889110890110891110892110893110894110895110896110897110898110899110900110901110902110903110904110905110906110907110908110909110910110911110912110913110914110915110916110917110918110919110920110921110922110923110924110925110926110927110928110929110930110931110932110933110934110935110936110937110938110939110940110941110942110943110944110945110946110947110948110949110950110951110952110953110954110955110956110957110958110959110960110961110962110963110964110965110966110967110968110969110970110971110972110973110974110975110976110977110978110979110980110981110982110983110984110985110986110987110988110989110990110991110992110993110994110995110996110997110998110999111000111001111002111003111004111005111006111007111008111009111010111011111012111013111014111015111016111017111018111019111020111021111022111023111024111025111026111027111028111029111030111031111032111033111034111035111036111037111038111039111040111041111042111043111044111045111046111047111048111049111050111051111052111053111054111055111056111057111058111059111060111061111062111063111064111065111066111067111068111069111070111071111072111073111074111075111076111077111078111079111080111081111082111083111084111085111086111087111088111089111090111091111092111093111094111095111096111097111098111099111100111101111102111103111104111105111106111107111108111109111110111111111112111113111114111115111116111117111118111119111120111121111122111123111124111125111126111127111128111129111130111131111132111133111134111135111136111137111138111139111140111141111142111143111144111145111146111147111148111149111150111151111152111153111154111155111156111157111158111159111160111161111162111163111164111165111166111167111168111169111170111171111172111173111174111175111176111177111178111179111180111181111182111183111184111185111186111187111188111189111190111191111192111193111194111195111196111197111198111199111200111201111202111203111204111205111206111207111208111209111210111211111212111213111214111215111216111217111218111219111220111221111222111223111224111225111226111227111228111229111230111231111232111233111234111235111236111237111238111239111240111241111242111243111244111245111246111247111248111249111250111251111252111253111254111255111256111257111258111259111260111261111262111263111264111265111266111267111268111269111270111271111272111273111274111275111276111277111278111279111280111281111282111283111284111285111286111287111288111289111290111291111292111293111294111295111296111297111298111299111300111301111302111303111304111305111306111307111308111309111310111311111312111313111314111315111316111317111318111319111320111321111322111323111324111325111326111327111328111329111330111331111332111333111334111335111336111337111338111339111340111341111342111343111344111345111346111347111348111349111350111351111352111353111354111355111356111357111358111359111360111361111362111363111364111365111366111367111368111369111370111371111372111373111374111375111376111377111378111379111380111381111382111383111384111385111386111387111388111389111390111391111392111393111394111395111396111397111398111399111400111401111402111403111404111405111406111407111408111409111410111411111412111413111414111415111416111417111418111419111420111421111422111423111424111425111426111427111428111429111430111431111432111433111434111435111436111437111438111439111440111441111442111443111444111445111446111447111448111449111450111451111452111453111454111455111456111457111458111459111460111461111462111463111464111465111466111467111468111469111470111471111472111473111474111475111476111477111478111479111480111481111482111483111484111485111486111487111488111489111490111491111492111493111494111495111496111497111498111499111500111501111502111503111504111505111506111507111508111509111510111511111512111513111514111515111516111517111518111519111520111521111522111523111524111525111526111527111528111529111530111531111532111533111534111535111536111537111538111539111540111541111542111543111544111545111546111547111548111549111550111551111552111553111554111555111556111557111558111559111560111561111562111563111564111565111566111567111568111569111570111571111572111573111574111575111576111577111578111579111580111581111582111583111584111585111586111587111588111589111590111591111592111593111594111595111596111597111598111599111600111601111602111603111604111605111606111607111608111609111610111611111612111613111614111615111616111617111618111619111620111621111622111623111624111625111626111627111628111629111630111631111632111633111634111635111636111637111638111639111640111641111642111643111644111645111646111647111648111649111650111651111652111653111654111655111656111657111658111659111660111661111662111663111664111665111666111667111668111669111670111671111672111673111674111675111676111677111678111679111680111681111682111683111684111685111686111687111688111689111690111691111692111693111694111695111696111697111698111699111700111701111702111703111704111705111706111707111708111709111710111711111712111713111714111715111716111717111718111719111720111721111722111723111724111725111726111727111728111729111730111731111732111733111734111735111736111737111738111739111740111741111742111743111744111745111746111747111748111749111750111751111752111753111754111755111756111757111758111759111760111761111762111763111764111765111766111767111768111769111770111771111772111773111774111775111776111777111778111779111780111781111782111783111784111785111786111787111788111789111790111791111792111793111794111795111796111797111798111799111800111801111802111803111804111805111806111807111808111809111810111811111812111813111814111815111816111817111818111819111820111821111822111823111824111825111826111827111828111829111830111831111832111833111834111835111836111837111838111839111840111841111842111843111844111845111846111847111848111849111850111851111852111853111854111855111856111857111858111859111860111861111862111863111864111865111866111867111868111869111870111871111872111873111874111875111876111877111878111879111880111881111882111883111884111885111886111887111888111889111890111891111892111893111894111895111896111897111898111899111900111901111902111903111904111905111906111907111908111909111910111911111912111913111914111915111916111917111918111919111920111921111922111923111924111925111926111927111928111929111930111931111932111933111934111935111936111937111938111939111940111941111942111943111944111945111946111947111948111949111950111951111952111953111954111955111956111957111958111959111960111961111962111963111964111965111966111967111968111969111970111971111972111973111974111975111976111977111978111979111980111981111982111983111984111985111986111987111988111989111990111991111992111993111994111995111996111997111998111999112000112001112002112003112004112005112006112007112008112009112010112011112012112013112014112015112016112017112018112019112020112021112022112023112024112025112026112027112028112029112030112031112032112033112034112035112036112037112038112039112040112041112042112043112044112045112046112047112048112049112050112051112052112053112054112055112056112057112058112059112060112061112062112063112064112065112066112067112068112069112070112071112072112073112074112075112076112077112078112079112080112081112082112083112084112085112086112087112088112089112090112091112092112093112094112095112096112097112098112099112100112101112102112103112104112105112106112107112108112109112110112111112112112113112114112115112116112117112118112119112120112121112122112123112124112125112126112127112128112129112130112131112132112133112134112135112136112137112138112139112140112141112142112143112144112145112146112147112148112149112150112151112152112153112154112155112156112157112158112159112160112161112162112163112164112165112166112167112168112169112170112171112172112173112174112175112176112177112178112179112180112181112182112183112184112185112186112187112188112189112190112191112192112193112194112195112196112197112198112199112200112201112202112203112204112205112206112207112208112209112210112211112212112213112214112215112216112217112218112219112220112221112222112223112224112225112226112227112228112229112230112231112232112233112234112235112236112237112238112239112240112241112242112243112244112245112246112247112248112249112250112251112252112253112254112255112256112257112258112259112260112261112262112263112264112265112266112267112268112269112270112271112272112273112274112275112276112277112278112279112280112281112282112283112284112285112286112287112288112289112290112291112292112293112294112295112296112297112298112299112300112301112302112303112304112305112306112307112308112309112310112311112312112313112314112315112316112317112318112319112320112321112322112323112324112325112326112327112328112329112330112331112332112333112334112335112336112337112338112339112340112341112342112343112344112345112346112347112348112349112350112351112352112353112354112355112356112357112358112359112360112361112362112363112364112365112366112367112368112369112370112371112372112373112374112375112376112377112378112379112380112381112382112383112384112385112386112387112388112389112390112391112392112393112394112395112396112397112398112399112400112401112402112403112404112405112406112407112408112409112410112411112412112413112414112415112416112417112418112419112420112421112422112423112424112425112426112427112428112429112430112431112432112433112434112435112436112437112438112439112440112441112442112443112444112445112446112447112448112449112450112451112452112453112454112455112456112457112458112459112460112461112462112463112464112465112466112467112468112469112470112471112472112473112474112475112476112477112478112479112480112481112482112483112484112485112486112487112488112489112490112491112492112493112494112495112496112497112498112499112500112501112502112503112504112505112506112507112508112509112510112511112512112513112514112515112516112517112518112519112520112521112522112523112524112525112526112527112528112529112530112531112532112533112534112535112536112537112538112539112540112541112542112543112544112545112546112547112548112549112550112551112552112553112554112555112556112557112558112559112560112561112562112563112564112565112566112567112568112569112570112571112572112573112574112575112576112577112578112579112580112581112582112583112584112585112586112587112588112589112590112591112592112593112594112595112596112597112598112599112600112601112602112603112604112605112606112607112608112609112610112611112612112613112614112615112616112617112618112619112620112621112622112623112624112625112626112627112628112629112630112631112632112633112634112635112636112637112638112639112640112641112642112643112644112645112646112647112648112649112650112651112652112653112654112655112656112657112658112659112660112661112662112663112664112665112666112667112668112669112670112671112672112673112674112675112676112677112678112679112680112681112682112683112684112685112686112687112688112689112690112691112692112693112694112695112696112697112698112699112700112701112702112703112704112705112706112707112708112709112710112711112712112713112714112715112716112717112718112719112720112721112722112723112724112725112726112727112728112729112730112731112732112733112734112735112736112737112738112739112740112741112742112743112744112745112746112747112748112749112750112751112752112753112754112755112756112757112758112759112760112761112762112763112764112765112766112767112768112769112770112771112772112773112774112775112776112777112778112779112780112781112782112783112784112785112786112787112788112789112790112791112792112793112794112795112796112797112798112799112800112801112802112803112804112805112806112807112808112809112810112811112812112813112814112815112816112817112818112819112820112821112822112823112824112825112826112827112828112829112830112831112832112833112834112835112836112837112838112839112840112841112842112843112844112845112846112847112848112849112850112851112852112853112854112855112856112857112858112859112860112861112862112863112864112865112866112867112868112869112870112871112872112873112874112875112876112877112878112879112880112881112882112883112884112885112886112887112888112889112890112891112892112893112894112895112896112897112898112899112900112901112902112903112904112905112906112907112908112909112910112911112912112913112914112915112916112917112918112919112920112921112922112923112924112925112926112927112928112929112930112931112932112933112934112935112936112937112938112939112940112941112942112943112944112945112946112947112948112949112950112951112952112953112954112955112956112957112958112959112960112961112962112963112964112965112966112967112968112969112970112971112972112973112974112975112976112977112978112979112980112981112982112983112984112985112986112987112988112989112990112991112992112993112994112995112996112997112998112999113000113001113002113003113004113005113006113007113008113009113010113011113012113013113014113015113016113017113018113019113020113021113022113023113024113025113026113027113028113029113030113031113032113033113034113035113036113037113038113039113040113041113042113043113044113045113046113047113048113049113050113051113052113053113054113055113056113057113058113059113060113061113062113063113064113065113066113067113068113069113070113071113072113073113074113075113076113077113078113079113080113081113082113083113084113085113086113087113088113089113090113091113092113093113094113095113096113097113098113099113100113101113102113103113104113105113106113107113108113109113110113111113112113113113114113115113116113117113118113119113120113121113122113123113124113125113126113127113128113129113130113131113132113133113134113135113136113137113138113139113140113141113142113143113144113145113146113147113148113149113150113151113152113153113154113155113156113157113158113159113160113161113162113163113164113165113166113167113168113169113170113171113172113173113174113175113176113177113178113179113180113181113182113183113184113185113186113187113188113189113190113191113192113193113194113195113196113197113198113199113200113201113202113203113204113205113206113207113208113209113210113211113212113213113214113215113216113217113218113219113220113221113222113223113224113225113226113227113228113229113230113231113232113233113234113235113236113237113238113239113240113241113242113243113244113245113246113247113248113249113250113251113252113253113254113255113256113257113258113259113260113261113262113263113264113265113266113267113268113269113270113271113272113273113274113275113276113277113278113279113280113281113282113283113284113285113286113287113288113289113290113291113292113293113294113295113296113297113298113299113300113301113302113303113304113305113306113307113308113309113310113311113312113313113314113315113316113317113318113319113320113321113322113323113324113325113326113327113328113329113330113331113332113333113334113335113336113337113338113339113340113341113342113343113344113345113346113347113348113349113350113351113352113353113354113355113356113357113358113359113360113361113362113363113364113365113366113367113368113369113370113371113372113373113374113375113376113377113378113379113380113381113382113383113384113385113386113387113388113389113390113391113392113393113394113395113396113397113398113399113400113401113402113403113404113405113406113407113408113409113410113411113412113413113414113415113416113417113418113419113420113421113422113423113424113425113426113427113428113429113430113431113432113433113434113435113436113437113438113439113440113441113442113443113444113445113446113447113448113449113450113451113452113453113454113455113456113457113458113459113460113461113462113463113464113465113466113467113468113469113470113471113472113473113474113475113476113477113478113479113480113481113482113483113484113485113486113487113488113489113490113491113492113493113494113495113496113497113498113499113500113501113502113503113504113505113506113507113508113509113510113511113512113513113514113515113516113517113518113519113520113521113522113523113524113525113526113527113528113529113530113531113532113533113534113535113536113537113538113539113540113541113542113543113544113545113546113547113548113549113550113551113552113553113554113555113556113557113558113559113560113561113562113563113564113565113566113567113568113569113570113571113572113573113574113575113576113577113578113579113580113581113582113583113584113585113586113587113588113589113590113591113592113593113594113595113596113597113598113599113600113601113602113603113604113605113606113607113608113609113610113611113612113613113614113615113616113617113618113619113620113621113622113623113624113625113626113627113628113629113630113631113632113633113634113635113636113637113638113639113640113641113642113643113644113645113646113647113648113649113650113651113652113653113654113655113656113657113658113659113660113661113662113663113664113665113666113667113668113669113670113671113672113673113674113675113676113677113678113679113680113681113682113683113684113685113686113687113688113689113690113691113692113693113694113695113696113697113698113699113700113701113702113703113704113705113706113707113708113709113710113711113712113713113714113715113716113717113718113719113720113721113722113723113724113725113726113727113728113729113730113731113732113733113734113735113736113737113738113739113740113741113742113743113744113745113746113747113748113749113750113751113752113753113754113755113756113757113758113759113760113761113762113763113764113765113766113767113768113769113770113771113772113773113774113775113776113777113778113779113780113781113782113783113784113785113786113787113788113789113790113791113792113793113794113795113796113797113798113799113800113801113802113803113804113805113806113807113808113809113810113811113812113813113814113815113816113817113818113819113820113821113822113823113824113825113826113827113828113829113830113831113832113833113834113835113836113837113838113839113840113841113842113843113844113845113846113847113848113849113850113851113852113853113854113855113856113857113858113859113860113861113862113863113864113865113866113867113868113869113870113871113872113873113874113875113876113877113878113879113880113881113882113883113884113885113886113887113888113889113890113891113892113893113894113895113896113897113898113899113900113901113902113903113904113905113906113907113908113909113910113911113912113913113914113915113916113917113918113919113920113921113922113923113924113925113926113927113928113929113930113931113932113933113934113935113936113937113938113939113940113941113942113943113944113945113946113947113948113949113950113951113952113953113954113955113956113957113958113959113960113961113962113963113964113965113966113967113968113969113970113971113972113973113974113975113976113977113978113979113980113981113982113983113984113985113986113987113988113989113990113991113992113993113994113995113996113997113998113999114000114001114002114003114004114005114006114007114008114009114010114011114012114013114014114015114016114017114018114019114020114021114022114023114024114025114026114027114028114029114030114031114032114033114034114035114036114037114038114039114040114041114042114043114044114045114046114047114048114049114050114051114052114053114054114055114056114057114058114059114060114061114062114063114064114065114066114067114068114069114070114071114072114073114074114075114076114077114078114079114080114081114082114083114084114085114086114087114088114089114090114091114092114093114094114095114096114097114098114099114100114101114102114103114104114105114106114107114108114109114110114111114112114113114114114115114116114117114118114119114120114121114122114123114124114125114126114127114128114129114130114131114132114133114134114135114136114137114138114139114140114141114142114143114144114145114146114147114148114149114150114151114152114153114154114155114156114157114158114159114160114161114162114163114164114165114166114167114168114169114170114171114172114173114174114175114176114177114178114179114180114181114182114183114184114185114186114187114188114189114190114191114192114193114194114195114196114197114198114199114200114201114202114203114204114205114206114207114208114209114210114211114212114213114214114215114216114217114218114219114220114221114222114223114224114225114226114227114228114229114230114231114232114233114234114235114236114237114238114239114240114241114242114243114244114245114246114247114248114249114250114251114252114253114254114255114256114257114258114259114260114261114262114263114264114265114266114267114268114269114270114271114272114273114274114275114276114277114278114279114280114281114282114283114284114285114286114287114288114289114290114291114292114293114294114295114296114297114298114299114300114301114302114303114304114305114306114307114308114309114310114311114312114313114314114315114316114317114318114319114320114321114322114323114324114325114326114327114328114329114330114331114332114333114334114335114336114337114338114339114340114341114342114343114344114345114346114347114348114349114350114351114352114353114354114355114356114357114358114359114360114361114362114363114364114365114366114367114368114369114370114371114372114373114374114375114376114377114378114379114380114381114382114383114384114385114386114387114388114389114390114391114392114393114394114395114396114397114398114399114400114401114402114403114404114405114406114407114408114409114410114411114412114413114414114415114416114417114418114419114420114421114422114423114424114425114426114427114428114429114430114431114432114433114434114435114436114437114438114439114440114441114442114443114444114445114446114447114448114449114450114451114452114453114454114455114456114457114458114459114460114461114462114463114464114465114466114467114468114469114470114471114472114473114474114475114476114477114478114479114480114481114482114483114484114485114486114487114488114489114490114491114492114493114494114495114496114497114498114499114500114501114502114503114504114505114506114507114508114509114510114511114512114513114514114515114516114517114518114519114520114521114522114523114524114525114526114527114528114529114530114531114532114533114534114535114536114537114538114539114540114541114542114543114544114545114546114547114548114549114550114551114552114553114554114555114556114557114558114559114560114561114562114563114564114565114566114567114568114569114570114571114572114573114574114575114576114577114578114579114580114581114582114583114584114585114586114587114588114589114590114591114592114593114594114595114596114597114598114599114600114601114602114603114604114605114606114607114608114609114610114611114612114613114614114615114616114617114618114619114620114621114622114623114624114625114626114627114628114629114630114631114632114633114634114635114636114637114638114639114640114641114642114643114644114645114646114647114648114649114650114651114652114653114654114655114656114657114658114659114660114661114662114663114664114665114666114667114668114669114670114671114672114673114674114675114676114677114678114679114680114681114682114683114684114685114686114687114688114689114690114691114692114693114694114695114696114697114698114699114700114701114702114703114704114705114706114707114708114709114710114711114712114713114714114715114716114717114718114719114720114721114722114723114724114725114726114727114728114729114730114731114732114733114734114735114736114737114738114739114740114741114742114743114744114745114746114747114748114749114750114751114752114753114754114755114756114757114758114759114760114761114762114763114764114765114766114767114768114769114770114771114772114773114774114775114776114777114778114779114780114781114782114783114784114785114786114787114788114789114790114791114792114793114794114795114796114797114798114799114800114801114802114803114804114805114806114807114808114809114810114811114812114813114814114815114816114817114818114819114820114821114822114823114824114825114826114827114828114829114830114831114832114833114834114835114836114837114838114839114840114841114842114843114844114845114846114847114848114849114850114851114852114853114854114855114856114857114858114859114860114861114862114863114864114865114866114867114868114869114870114871114872114873114874114875114876114877114878114879114880114881114882114883114884114885114886114887114888114889114890114891114892114893114894114895114896114897114898114899114900114901114902114903114904114905114906114907114908114909114910114911114912114913114914114915114916114917114918114919114920114921114922114923114924114925114926114927114928114929114930114931114932114933114934114935114936114937114938114939114940114941114942114943114944114945114946114947114948114949114950114951114952114953114954114955114956114957114958114959114960114961114962114963114964114965114966114967114968114969114970114971114972114973114974114975114976114977114978114979114980114981114982114983114984114985114986114987114988114989114990114991114992114993114994114995114996114997114998114999115000115001115002115003115004115005115006115007115008115009115010115011115012115013115014115015115016115017115018115019115020115021115022115023115024115025115026115027115028115029115030115031115032115033115034115035115036115037115038115039115040115041115042115043115044115045115046115047115048115049115050115051115052115053115054115055115056115057115058115059115060115061115062115063115064115065115066115067115068115069115070115071115072115073115074115075115076115077115078115079115080115081115082115083115084115085115086115087115088115089115090115091115092115093115094115095115096115097115098115099115100115101115102115103115104115105115106115107115108115109115110115111115112115113115114115115115116115117115118115119115120115121115122115123115124115125115126115127115128115129115130115131115132115133115134115135115136115137115138115139115140115141115142115143115144115145115146115147115148115149115150115151115152115153115154115155115156115157115158115159115160115161115162115163115164115165115166115167115168115169115170115171115172115173115174115175115176115177115178115179115180115181115182115183115184115185115186115187115188115189115190115191115192115193115194115195115196115197115198115199115200115201115202115203115204115205115206115207115208115209115210115211115212115213115214115215115216115217115218115219115220115221115222115223115224115225115226115227115228115229115230115231115232115233115234115235115236115237115238115239115240115241115242115243115244115245115246115247115248115249115250115251115252115253115254115255115256115257115258115259115260115261115262115263115264115265115266115267115268115269115270115271115272115273115274115275115276115277115278115279115280115281115282115283115284115285115286115287115288115289115290115291115292115293115294115295115296115297115298115299115300115301115302115303115304115305115306115307115308115309115310115311115312115313115314115315115316115317115318115319115320115321115322115323115324115325115326115327115328115329115330115331115332115333115334115335115336115337115338115339115340115341115342115343115344115345115346115347115348115349115350115351115352115353115354115355115356115357115358115359115360115361115362115363115364115365115366115367115368115369115370115371115372115373115374115375115376115377115378115379115380115381115382115383115384115385115386115387115388115389115390115391115392115393115394115395115396115397115398115399115400115401115402115403115404115405115406115407115408115409115410115411115412115413115414115415115416115417115418115419115420115421115422115423115424115425115426115427115428115429115430115431115432115433115434115435115436115437115438115439115440115441115442115443115444115445115446115447115448115449115450115451115452115453115454115455115456115457115458115459115460115461115462115463115464115465115466115467115468115469115470115471115472115473115474115475115476115477115478115479115480115481115482115483115484115485115486115487115488115489115490115491115492115493115494115495115496115497115498115499115500115501115502115503115504115505115506115507115508115509115510115511115512115513115514115515115516115517115518115519115520115521115522115523115524115525115526115527115528115529115530115531115532115533115534115535115536115537115538115539115540115541115542115543115544115545115546115547115548115549115550115551115552115553115554115555115556115557115558115559115560115561115562115563115564115565115566115567115568115569115570115571115572115573115574115575115576115577115578115579115580115581115582115583115584115585115586115587115588115589115590115591115592115593115594115595115596115597115598115599115600115601115602115603115604115605115606115607115608115609115610115611115612115613115614115615115616115617115618115619115620115621115622115623115624115625115626115627115628115629115630115631115632115633115634115635115636115637115638115639115640115641115642115643115644115645115646115647115648115649115650115651115652115653115654115655115656115657115658115659115660115661115662115663115664115665115666115667115668115669115670115671115672115673115674115675115676115677115678115679115680115681115682115683115684115685115686115687115688115689115690115691115692115693115694115695115696115697115698115699115700115701115702115703115704115705115706115707115708115709115710115711115712115713115714115715115716115717115718115719115720115721115722115723115724115725115726115727115728115729115730115731115732115733115734115735115736115737115738115739115740115741115742115743115744115745115746115747115748115749115750115751115752115753115754115755115756115757115758115759115760115761115762115763115764115765115766115767115768115769115770115771115772115773115774115775115776115777115778115779115780115781115782115783115784115785115786115787115788115789115790115791115792115793115794115795115796115797115798115799115800115801115802115803115804115805115806115807115808115809115810115811115812115813115814115815115816115817115818115819115820115821115822115823115824115825115826115827115828115829115830115831115832115833115834115835115836115837115838115839115840115841115842115843115844115845115846115847115848115849115850115851115852115853115854115855115856115857115858115859115860115861115862115863115864115865115866115867115868115869115870115871115872115873115874115875115876115877115878115879115880115881115882115883115884115885115886115887115888115889115890115891115892115893115894115895115896115897115898115899115900115901115902115903115904115905115906115907115908115909115910115911115912115913115914115915115916115917115918115919115920115921115922115923115924115925115926115927115928115929115930115931115932115933115934115935115936115937115938115939115940115941115942115943115944115945115946115947115948115949115950115951115952115953115954115955115956115957115958115959115960115961115962115963115964115965115966115967115968115969115970115971115972115973115974115975115976115977115978115979115980115981115982115983115984115985115986115987115988115989115990115991115992115993115994115995115996115997115998115999116000116001116002116003116004116005116006116007116008116009116010116011116012116013116014116015116016116017116018116019116020116021116022116023116024116025116026116027116028116029116030116031116032116033116034116035116036116037116038116039116040116041116042116043116044116045116046116047116048116049116050116051116052116053116054116055116056116057116058116059116060116061116062116063116064116065116066116067116068116069116070116071116072116073116074116075116076116077116078116079116080116081116082116083116084116085116086116087116088116089116090116091116092116093116094116095116096116097116098116099116100116101116102116103116104116105116106116107116108116109116110116111116112116113116114116115116116116117116118116119116120116121116122116123116124116125116126116127116128116129116130116131116132116133116134116135116136116137116138116139116140116141116142116143116144116145116146116147116148116149116150116151116152116153116154116155116156116157116158116159116160116161116162116163116164116165116166116167116168116169116170116171116172116173116174116175116176116177116178116179116180116181116182116183116184116185116186116187116188116189116190116191116192116193116194116195116196116197116198116199116200116201116202116203116204116205116206116207116208116209116210116211116212116213116214116215116216116217116218116219116220116221116222116223116224116225116226116227116228116229116230116231116232116233116234116235116236116237116238116239116240116241116242116243116244116245116246116247116248116249116250116251116252116253116254116255116256116257116258116259116260116261116262116263116264116265116266116267116268116269116270116271116272116273116274116275116276116277116278116279116280116281116282116283116284116285116286116287116288116289116290116291116292116293116294116295116296116297116298116299116300116301116302116303116304116305116306116307116308116309116310116311116312116313116314116315116316116317116318116319116320116321116322116323116324116325116326116327116328116329116330116331116332116333116334116335116336116337116338116339116340116341116342116343116344116345116346116347116348116349116350116351116352116353116354116355116356116357116358116359116360116361116362116363116364116365116366116367116368116369116370116371116372116373116374116375116376116377116378116379116380116381116382116383116384116385116386116387116388116389116390116391116392116393116394116395116396116397116398116399116400116401116402116403116404116405116406116407116408116409116410116411116412116413116414116415116416116417116418116419116420116421116422116423116424116425116426116427116428116429116430116431116432116433116434116435116436116437116438116439116440116441116442116443116444116445116446116447116448116449116450116451116452116453116454116455116456116457116458116459116460116461116462116463116464116465116466116467116468116469116470116471116472116473116474116475116476116477116478116479116480116481116482116483116484116485116486116487116488116489116490116491116492116493116494116495116496116497116498116499116500116501116502116503116504116505116506116507116508116509116510116511116512116513116514116515116516116517116518116519116520116521116522116523116524116525116526116527116528116529116530116531116532116533116534116535116536116537116538116539116540116541116542116543116544116545116546116547116548116549116550116551116552116553116554116555116556116557116558116559116560116561116562116563116564116565116566116567116568116569116570116571116572116573116574116575116576116577116578116579116580116581116582116583116584116585116586116587116588116589116590116591116592116593116594116595116596116597116598116599116600116601116602116603116604116605116606116607116608116609116610116611116612116613116614116615116616116617116618116619116620116621116622116623116624116625116626116627116628116629116630116631116632116633116634116635116636116637116638116639116640116641116642116643116644116645116646116647116648116649116650116651116652116653116654116655116656116657116658116659116660116661116662116663116664116665116666116667116668116669116670116671116672116673116674116675116676116677116678116679116680116681116682116683116684116685116686116687116688116689116690116691116692116693116694116695116696116697116698116699116700116701116702116703116704116705116706116707116708116709116710116711116712116713116714116715116716116717116718116719116720116721116722116723116724116725116726116727116728116729116730116731116732116733116734116735116736116737116738116739116740116741116742116743116744116745116746116747116748116749116750116751116752116753116754116755116756116757116758116759116760116761116762116763116764116765116766116767116768116769116770116771116772116773116774116775116776116777116778116779116780116781116782116783116784116785116786116787116788116789116790116791116792116793116794116795116796116797116798116799116800116801116802116803116804116805116806116807116808116809116810116811116812116813116814116815116816116817116818116819116820116821116822116823116824116825116826116827116828116829116830116831116832116833116834116835116836116837116838116839116840116841116842116843116844116845116846116847116848116849116850116851116852116853116854116855116856116857116858116859116860116861116862116863116864116865116866116867116868116869116870116871116872116873116874116875116876116877116878116879116880116881116882116883116884116885116886116887116888116889116890116891116892116893116894116895116896116897116898116899116900116901116902116903116904116905116906116907116908116909116910116911116912116913116914116915116916116917116918116919116920116921116922116923116924116925116926116927116928116929116930116931116932116933116934116935116936116937116938116939116940116941116942116943116944116945116946116947116948116949116950116951116952116953116954116955116956116957116958116959116960116961116962116963116964116965116966116967116968116969116970116971116972116973116974116975116976116977116978116979116980116981116982116983116984116985116986116987116988116989116990116991116992116993116994116995116996116997116998116999117000117001117002117003117004117005117006117007117008117009117010117011117012117013117014117015117016117017117018117019117020117021117022117023117024117025117026117027117028117029117030117031117032117033117034117035117036117037117038117039117040117041117042117043117044117045117046117047117048117049117050117051117052117053117054117055117056117057117058117059117060117061117062117063117064117065117066117067117068117069117070117071117072117073117074117075117076117077117078117079117080117081117082117083117084117085117086117087117088117089117090117091117092117093117094117095117096117097117098117099117100117101117102117103117104117105117106117107117108117109117110117111117112117113117114117115117116117117117118117119117120117121117122117123117124117125117126117127117128117129117130117131117132117133117134117135117136117137117138117139117140117141117142117143117144117145117146117147117148117149117150117151117152117153117154117155117156117157117158117159117160117161117162117163117164117165117166117167117168117169117170117171117172117173117174117175117176117177117178117179117180117181117182117183117184117185117186117187117188117189117190117191117192117193117194117195117196117197117198117199117200117201117202117203117204117205117206117207117208117209117210117211117212117213117214117215117216117217117218117219117220117221117222117223117224117225117226117227117228117229117230117231117232117233117234117235117236117237117238117239117240117241117242117243117244117245117246117247117248117249117250117251117252117253117254117255117256117257117258117259117260117261117262117263117264117265117266117267117268117269117270117271117272117273117274117275117276117277117278117279117280117281117282117283117284117285117286117287117288117289117290117291117292117293117294117295117296117297117298117299117300117301117302117303117304117305117306117307117308117309117310117311117312117313117314117315117316117317117318117319117320117321117322117323117324117325117326117327117328117329117330117331117332117333117334117335117336117337117338117339117340117341117342117343117344117345117346117347117348117349117350117351117352117353117354117355117356117357117358117359117360117361117362117363117364117365117366117367117368117369117370117371117372117373117374117375117376117377117378117379117380117381117382117383117384117385117386117387117388117389117390117391117392117393117394117395117396117397117398117399117400117401117402117403117404117405117406117407117408117409117410117411117412117413117414117415117416117417117418117419117420117421117422117423117424117425117426117427117428117429117430117431117432117433117434117435117436117437117438117439117440117441117442117443117444117445117446117447117448117449117450117451117452117453117454117455117456117457117458117459117460117461117462117463117464117465117466117467117468117469117470117471117472117473117474117475117476117477117478117479117480117481117482117483117484117485117486117487117488117489117490117491117492117493117494117495117496117497117498117499117500117501117502117503117504117505117506117507117508117509117510117511117512117513117514117515117516117517117518117519117520117521117522117523117524117525117526117527117528117529117530117531117532117533117534117535117536117537117538117539117540117541117542117543117544117545117546117547117548117549117550117551117552117553117554117555117556117557117558117559117560117561117562117563117564117565117566117567117568117569117570117571117572117573117574117575117576117577117578117579117580117581117582117583117584117585117586117587117588117589117590117591117592117593117594117595117596117597117598117599117600117601117602117603117604117605117606117607117608117609117610117611117612117613117614117615117616117617117618117619117620117621117622117623117624117625117626117627117628117629117630117631117632117633117634117635117636117637117638117639117640117641117642117643117644117645117646117647117648117649117650117651117652117653117654117655117656117657117658117659117660117661117662117663117664117665117666117667117668117669117670117671117672117673117674117675117676117677117678117679117680117681117682117683117684117685117686117687117688117689117690117691117692117693117694117695117696117697117698117699117700117701117702117703117704117705117706117707117708117709117710117711117712117713117714117715117716117717117718117719117720117721117722117723117724117725117726117727117728117729117730117731117732117733117734117735117736117737117738117739117740117741117742117743117744117745117746117747117748117749117750117751117752117753117754117755117756117757117758117759117760117761117762117763117764117765117766117767117768117769117770117771117772117773117774117775117776117777117778117779117780117781117782117783117784117785117786117787117788117789117790117791117792117793117794117795117796117797117798117799117800117801117802117803117804117805117806117807117808117809117810117811117812117813117814117815117816117817117818117819117820117821117822117823117824117825117826117827117828117829117830117831117832117833117834117835117836117837117838117839117840117841117842117843117844117845117846117847117848117849117850117851117852117853117854117855117856117857117858117859117860117861117862117863117864117865117866117867117868117869117870117871117872117873117874117875117876117877117878117879117880117881117882117883117884117885117886117887117888117889117890117891117892117893117894117895117896117897117898117899117900117901117902117903117904117905117906117907117908117909117910117911117912117913117914117915117916117917117918117919117920117921117922117923117924117925117926117927117928117929117930117931117932117933117934117935117936117937117938117939117940117941117942117943117944117945117946117947117948117949117950117951117952117953117954117955117956117957117958117959117960117961117962117963117964117965117966117967117968117969117970117971117972117973117974117975117976117977117978117979117980117981117982117983117984117985117986117987117988117989117990117991117992117993117994117995117996117997117998117999118000118001118002118003118004118005118006118007118008118009118010118011118012118013118014118015118016118017118018118019118020118021118022118023118024118025118026118027118028118029118030118031118032118033118034118035118036118037118038118039118040118041118042118043118044118045118046118047118048118049118050118051118052118053118054118055118056118057118058118059118060118061118062118063118064118065118066118067118068118069118070118071118072118073118074118075118076118077118078118079118080118081118082118083118084118085118086118087118088118089118090118091118092118093118094118095118096118097118098118099118100118101118102118103118104118105118106118107118108118109118110118111118112118113118114118115118116118117118118118119118120118121118122118123118124118125118126118127118128118129118130118131118132118133118134118135118136118137118138118139118140118141118142118143118144118145118146118147118148118149118150118151118152118153118154118155118156118157118158118159118160118161118162118163118164118165118166118167118168118169118170118171118172118173118174118175118176118177118178118179118180118181118182118183118184118185118186118187118188118189118190118191118192118193118194118195118196118197118198118199118200118201118202118203118204118205118206118207118208118209118210118211118212118213118214118215118216118217118218118219118220118221118222118223118224118225118226118227118228118229118230118231118232118233118234118235118236118237118238118239118240118241118242118243118244118245118246118247118248118249118250118251118252118253118254118255118256118257118258118259118260118261118262118263118264118265118266118267118268118269118270118271118272118273118274118275118276118277118278118279118280118281118282118283118284118285118286118287118288118289118290118291118292118293118294118295118296118297118298118299118300118301118302118303118304118305118306118307118308118309118310118311118312118313118314118315118316118317118318118319118320118321118322118323118324118325118326118327118328118329118330118331118332118333118334118335118336118337118338118339118340118341118342118343118344118345118346118347118348118349118350118351118352118353118354118355118356118357118358118359118360118361118362118363118364118365118366118367118368118369118370118371118372118373118374118375118376118377118378118379118380118381118382118383118384118385118386118387118388118389118390118391118392118393118394118395118396118397118398118399118400118401118402118403118404118405118406118407118408118409118410118411118412118413118414118415118416118417118418118419118420118421118422118423118424118425118426118427118428118429118430118431118432118433118434118435118436118437118438118439118440118441118442118443118444118445118446118447118448118449118450118451118452118453118454118455118456118457118458118459118460118461118462118463118464118465118466118467118468118469118470118471118472118473118474118475118476118477118478118479118480118481118482118483118484118485118486118487118488118489118490118491118492118493118494118495118496118497118498118499118500118501118502118503118504118505118506118507118508118509118510118511118512118513118514118515118516118517118518118519118520118521118522118523118524118525118526118527118528118529118530118531118532118533118534118535118536118537118538118539118540118541118542118543118544118545118546118547118548118549118550118551118552118553118554118555118556118557118558118559118560118561118562118563118564118565118566118567118568118569118570118571118572118573118574118575118576118577118578118579118580118581118582118583118584118585118586118587118588118589118590118591118592118593118594118595118596118597118598118599118600118601118602118603118604118605118606118607118608118609118610118611118612118613118614118615118616118617118618118619118620118621118622118623118624118625118626118627118628118629118630118631118632118633118634118635118636118637118638118639118640118641118642118643118644118645118646118647118648118649118650118651118652118653118654118655118656118657118658118659118660118661118662118663118664118665118666118667118668118669118670118671118672118673118674118675118676118677118678118679118680118681118682118683118684118685118686118687118688118689118690118691118692118693118694118695118696118697118698118699118700118701118702118703118704118705118706118707118708118709118710118711118712118713118714118715118716118717118718118719118720118721118722118723118724118725118726118727118728118729118730118731118732118733118734118735118736118737118738118739118740118741118742118743118744118745118746118747118748118749118750118751118752118753118754118755118756118757118758118759118760118761118762118763118764118765118766118767118768118769118770118771118772118773118774118775118776118777118778118779118780118781118782118783118784118785118786118787118788118789118790118791118792118793118794118795118796118797118798118799118800118801118802118803118804118805118806118807118808118809118810118811118812118813118814118815118816118817118818118819118820118821118822118823118824118825118826118827118828118829118830118831118832118833118834118835118836118837118838118839118840118841118842118843118844118845118846118847118848118849118850118851118852118853118854118855118856118857118858118859118860118861118862118863118864118865118866118867118868118869118870118871118872118873118874118875118876118877118878118879118880118881118882118883118884118885118886118887118888118889118890118891118892118893118894118895118896118897118898118899118900118901118902118903118904118905118906118907118908118909118910118911118912118913118914118915118916118917118918118919118920118921118922118923118924118925118926118927118928118929118930118931118932118933118934118935118936118937118938118939118940118941118942118943118944118945118946118947118948118949118950118951118952118953118954118955118956118957118958118959118960118961118962118963118964118965118966118967118968118969118970118971118972118973118974118975118976118977118978118979118980118981118982118983118984118985118986118987118988118989118990118991118992118993118994118995118996118997118998118999119000119001119002119003119004119005119006119007119008119009119010119011119012119013119014119015119016119017119018119019119020119021119022119023119024119025119026119027119028119029119030119031119032119033119034119035119036119037119038119039119040119041119042119043119044119045119046119047119048119049119050119051119052119053119054119055119056119057119058119059119060119061119062119063119064119065119066119067119068119069119070119071119072119073119074119075119076119077119078119079119080119081119082119083119084119085119086119087119088119089119090119091119092119093119094119095119096119097119098119099119100119101119102119103119104119105119106119107119108119109119110119111119112119113119114119115119116119117119118119119119120119121119122119123119124119125119126119127119128119129119130119131119132119133119134119135119136119137119138119139119140119141119142119143119144119145119146119147119148119149119150119151119152119153119154119155119156119157119158119159119160119161119162119163119164119165119166119167119168119169119170119171119172119173119174119175119176119177119178119179119180119181119182119183119184119185119186119187119188119189119190119191119192119193119194119195119196119197119198119199119200119201119202119203119204119205119206119207119208119209119210119211119212119213119214119215119216119217119218119219119220119221119222119223119224119225119226119227119228119229119230119231119232119233119234119235119236119237119238119239119240119241119242119243119244119245119246119247119248119249119250119251119252119253119254119255119256119257119258119259119260119261119262119263119264119265119266119267119268119269119270119271119272119273119274119275119276119277119278119279119280119281119282119283119284119285119286119287119288119289119290119291119292119293119294119295119296119297119298119299119300119301119302119303119304119305119306119307119308119309119310119311119312119313119314119315119316119317119318119319119320119321119322119323119324119325119326119327119328119329119330119331119332119333119334119335119336119337119338119339119340119341119342119343119344119345119346119347119348119349119350119351119352119353119354119355119356119357119358119359119360119361119362119363119364119365119366119367119368119369119370119371119372119373119374119375119376119377119378119379119380119381119382119383119384119385119386119387119388119389119390119391119392119393119394119395119396119397119398119399119400119401119402119403119404119405119406119407119408119409119410119411119412119413119414119415119416119417119418119419119420119421119422119423119424119425119426119427119428119429119430119431119432119433119434119435119436119437119438119439119440119441119442119443119444119445119446119447119448119449119450119451119452119453119454119455119456119457119458119459119460119461119462119463119464119465119466119467119468119469119470119471119472119473119474119475119476119477119478119479119480119481119482119483119484119485119486119487119488119489119490119491119492119493119494119495119496119497119498119499119500119501119502119503119504119505119506119507119508119509119510119511119512119513119514119515119516119517119518119519119520119521119522119523119524119525119526119527119528119529119530119531119532119533119534119535119536119537119538119539119540119541119542119543119544119545119546119547119548119549119550119551119552119553119554119555119556119557119558119559119560119561119562119563119564119565119566119567119568119569119570119571119572119573119574119575119576119577119578119579119580119581119582119583119584119585119586119587119588119589119590119591119592119593119594119595119596119597119598119599119600119601119602119603119604119605119606119607119608119609119610119611119612119613119614119615119616119617119618119619119620119621119622119623119624119625119626119627119628119629119630119631119632119633119634119635119636119637119638119639119640119641119642119643119644119645119646119647119648119649119650119651119652119653119654119655119656119657119658119659119660119661119662119663119664119665119666119667119668119669119670119671119672119673119674119675119676119677119678119679119680119681119682119683119684119685119686119687119688119689119690119691119692119693119694119695119696119697119698119699119700119701119702119703119704119705119706119707119708119709119710119711119712119713119714119715119716119717119718119719119720119721119722119723119724119725119726119727119728119729119730119731119732119733119734119735119736119737119738119739119740119741119742119743119744119745119746119747119748119749119750119751119752119753119754119755119756119757119758119759119760119761119762119763119764119765119766119767119768119769119770119771119772119773119774119775119776119777119778119779119780119781119782119783119784119785119786119787119788119789119790119791119792119793119794119795119796119797119798119799119800119801119802119803119804119805119806119807119808119809119810119811119812119813119814119815119816119817119818119819119820119821119822119823119824119825119826119827119828119829119830119831119832119833119834119835119836119837119838119839119840119841119842119843119844119845119846119847119848119849119850119851119852119853119854119855119856119857119858119859119860119861119862119863119864119865119866119867119868119869119870119871119872119873119874119875119876119877119878119879119880119881119882119883119884119885119886119887119888119889119890119891119892119893119894119895119896119897119898119899119900119901119902119903119904119905119906119907119908119909119910119911119912119913119914119915119916119917119918119919119920119921119922119923119924119925119926119927119928119929119930119931119932119933119934119935119936119937119938119939119940119941119942119943119944119945119946119947119948119949119950119951119952119953119954119955119956119957119958119959119960119961119962119963119964119965119966119967119968119969119970119971119972119973119974119975119976119977119978119979119980119981119982119983119984119985119986119987119988119989119990119991119992119993119994119995119996119997119998119999120000120001120002120003120004120005120006120007120008120009120010120011120012120013120014120015120016120017120018120019120020120021120022120023120024120025120026120027120028120029120030120031120032120033120034120035120036120037120038120039120040120041120042120043120044120045120046120047120048120049120050120051120052120053120054120055120056120057120058120059120060120061120062120063120064120065120066120067120068120069120070120071120072120073120074120075120076120077120078120079120080120081120082120083120084120085120086120087120088120089120090120091120092120093120094120095120096120097120098120099120100120101120102120103120104120105120106120107120108120109120110120111120112120113120114120115120116120117120118120119120120120121120122120123120124120125120126120127120128120129120130120131120132120133120134120135120136120137120138120139120140120141120142120143120144120145120146120147120148120149120150120151120152120153120154120155120156120157120158120159120160120161120162120163120164120165120166120167120168120169120170120171120172120173120174120175120176120177120178120179120180120181120182120183120184120185120186120187120188120189120190120191120192120193120194120195120196120197120198120199120200120201120202120203120204120205120206120207120208120209120210120211120212120213120214120215120216120217120218120219120220120221120222120223120224120225120226120227120228120229120230120231120232120233120234120235120236120237120238120239120240120241120242120243120244120245120246120247120248120249120250120251120252120253120254120255120256120257120258120259120260120261120262120263120264120265120266120267120268120269120270120271120272120273120274120275120276120277120278120279120280120281120282120283120284120285120286120287120288120289120290120291120292120293120294120295120296120297120298120299120300120301120302120303120304120305120306120307120308120309120310120311120312120313120314120315120316120317120318120319120320120321120322120323120324120325120326120327120328120329120330120331120332120333120334120335120336120337120338120339120340120341120342120343120344120345120346120347120348120349120350120351120352120353120354120355120356120357120358120359120360120361120362120363120364120365120366120367120368120369120370120371120372120373120374120375120376120377120378120379120380120381120382120383120384120385120386120387120388120389120390120391120392120393120394120395120396120397120398120399120400120401120402120403120404120405120406120407120408120409120410120411120412120413120414120415120416120417120418120419120420120421120422120423120424120425120426120427120428120429120430120431120432120433120434120435120436120437120438120439120440120441120442120443120444120445120446120447120448120449120450120451120452120453120454120455120456120457120458120459120460120461120462120463120464120465120466120467120468120469120470120471120472120473120474120475120476120477120478120479120480120481120482120483120484120485120486120487120488120489120490120491120492120493120494120495120496120497120498120499120500120501120502120503120504120505120506120507120508120509120510120511120512120513120514120515120516120517120518120519120520120521120522120523120524120525120526120527120528120529120530120531120532120533120534120535120536120537120538120539120540120541120542120543120544120545120546120547120548120549120550120551120552120553120554120555120556120557120558120559120560120561120562120563120564120565120566120567120568120569120570120571120572120573120574120575120576120577120578120579120580120581120582120583120584120585120586120587120588120589120590120591120592120593120594120595120596120597120598120599120600120601120602120603120604120605120606120607120608120609120610120611120612120613120614120615120616120617120618120619120620120621120622120623120624120625120626120627120628120629120630120631120632120633120634120635120636120637120638120639120640120641120642120643120644120645120646120647120648120649120650120651120652120653120654120655120656120657120658120659120660120661120662120663120664120665120666120667120668120669120670120671120672120673120674120675120676120677120678120679120680120681120682120683120684120685120686120687120688120689120690120691120692120693120694120695120696120697120698120699120700120701120702120703120704120705120706120707120708120709120710120711120712120713120714120715120716120717120718120719120720120721120722120723120724120725120726120727120728120729120730120731120732120733120734120735120736120737120738120739120740120741120742120743120744120745120746120747120748120749120750120751120752120753120754120755120756120757120758120759120760120761120762120763120764120765120766120767120768120769120770120771120772120773120774120775120776120777120778120779120780120781120782120783120784120785120786120787120788120789120790120791120792120793120794120795120796120797120798120799120800120801120802120803120804120805120806120807120808120809120810120811120812120813120814120815120816120817120818120819120820120821120822120823120824120825120826120827120828120829120830120831120832120833120834120835120836120837120838120839120840120841120842120843120844120845120846120847120848120849120850120851120852120853120854120855120856120857120858120859120860120861120862120863120864120865120866120867120868120869120870120871120872120873120874120875120876120877120878120879120880120881120882120883120884120885120886120887120888120889120890120891120892120893120894120895120896120897120898120899120900120901120902120903120904120905120906120907120908120909120910120911120912120913120914120915120916120917120918120919120920120921120922120923120924120925120926120927120928120929120930120931120932120933120934120935120936120937120938120939120940120941120942120943120944120945120946120947120948120949120950120951120952120953120954120955120956120957120958120959120960120961120962120963120964120965120966120967120968120969120970120971120972120973120974120975120976120977120978120979120980120981120982120983120984120985120986120987120988120989120990120991120992120993120994120995120996120997120998120999121000121001121002121003121004121005121006121007121008121009121010121011121012121013121014121015121016121017121018121019121020121021121022121023121024121025121026121027121028121029121030121031121032121033121034121035121036121037121038121039121040121041121042121043121044121045121046121047121048121049121050121051121052121053121054121055121056121057121058121059121060121061121062121063121064121065121066121067121068121069121070121071121072121073121074121075121076121077121078121079121080121081121082121083121084121085121086121087121088121089121090121091121092121093121094121095121096121097121098121099121100121101121102121103121104121105121106121107121108121109121110121111121112121113121114121115121116121117121118121119121120121121121122121123121124121125121126121127121128121129121130121131121132121133121134121135121136121137121138121139121140121141121142121143121144121145121146121147121148121149121150121151121152121153121154121155121156121157121158121159121160121161121162121163121164121165121166121167121168121169121170121171121172121173121174121175121176121177121178121179121180121181121182121183121184121185121186121187121188121189121190121191121192121193121194121195121196121197121198121199121200121201121202121203121204121205121206121207121208121209121210121211121212121213121214121215121216121217121218121219121220121221121222121223121224121225121226121227121228121229121230121231121232121233121234121235121236121237121238121239121240121241121242121243121244121245121246121247121248121249121250121251121252121253121254121255121256121257121258121259121260121261121262121263121264121265121266121267121268121269121270121271121272121273121274121275121276121277121278121279121280121281121282121283121284121285121286121287121288121289121290121291121292121293121294121295121296121297121298121299121300121301121302121303121304121305121306121307121308121309121310121311121312121313121314121315121316121317121318121319121320121321121322121323121324121325121326121327121328121329121330121331121332121333121334121335121336121337121338121339121340121341121342121343121344121345121346121347121348121349121350121351121352121353121354121355121356121357121358121359121360121361121362121363121364121365121366121367121368121369121370121371121372121373121374121375121376121377121378121379121380121381121382121383121384121385121386121387121388121389121390121391121392121393121394121395121396121397121398121399121400121401121402121403121404121405121406121407121408121409121410121411121412121413121414121415121416121417121418121419121420121421121422121423121424121425121426121427121428121429121430121431121432121433121434121435121436121437121438121439121440121441121442121443121444121445121446121447121448121449121450121451121452121453121454121455121456121457121458121459121460121461121462121463121464121465121466121467121468121469121470121471121472121473121474121475121476121477121478121479121480121481121482121483121484121485121486121487121488121489121490121491121492121493121494121495121496121497121498121499121500121501121502121503121504121505121506121507121508121509121510121511121512121513121514121515121516121517121518121519121520121521121522121523121524121525121526121527121528121529121530121531121532121533121534121535121536121537121538121539121540121541121542121543121544121545121546121547121548121549121550121551121552121553121554121555121556121557121558121559121560121561121562121563121564121565121566121567121568121569121570121571121572121573121574121575121576121577121578121579121580121581121582121583121584121585121586121587121588121589121590121591121592121593121594121595121596121597121598121599121600121601121602121603121604121605121606121607121608121609121610121611121612121613121614121615121616121617121618121619121620121621121622121623121624121625121626121627121628121629121630121631121632121633121634121635121636121637121638121639121640121641121642121643121644121645121646121647121648121649121650121651121652121653121654121655121656121657121658121659121660121661121662121663121664121665121666121667121668121669121670121671121672121673121674121675121676121677121678121679121680121681121682121683121684121685121686121687121688121689121690121691121692121693121694121695121696121697121698121699121700121701121702121703121704121705121706121707121708121709121710121711121712121713121714121715121716121717121718121719121720121721121722121723121724121725121726121727121728121729121730121731121732121733121734121735121736121737121738121739121740121741121742121743121744121745121746121747121748121749121750121751121752121753121754121755121756121757121758121759121760121761121762121763121764121765121766121767121768121769121770121771121772121773121774121775121776121777121778121779121780121781121782121783121784121785121786121787121788121789121790121791121792121793121794121795121796121797121798121799121800121801121802121803121804121805121806121807121808121809121810121811121812121813121814121815121816121817121818121819121820121821121822121823121824121825121826121827121828121829121830121831121832121833121834121835121836121837121838121839121840121841121842121843121844121845121846121847121848121849121850121851121852121853121854121855121856121857121858121859121860121861121862121863121864121865121866121867121868121869121870121871121872121873121874121875121876121877121878121879121880121881121882121883121884121885121886121887121888121889121890121891121892121893121894121895121896121897121898121899121900121901121902121903121904121905121906121907121908121909121910121911121912121913121914121915121916121917121918121919121920121921121922121923121924121925121926121927121928121929121930121931121932121933121934121935121936121937121938121939121940121941121942121943121944121945121946121947121948121949121950121951121952121953121954121955121956121957121958121959121960121961121962121963121964121965121966121967121968121969121970121971121972121973121974121975121976121977121978121979121980121981121982121983121984121985121986121987121988121989121990121991121992121993121994121995121996121997121998121999122000122001122002122003122004122005122006122007122008122009122010122011122012122013122014122015122016122017122018122019122020122021122022122023122024122025122026122027122028122029122030122031122032122033122034122035122036122037122038122039122040122041122042122043122044122045122046122047122048122049122050122051122052122053122054122055122056122057122058122059122060122061122062122063122064122065122066122067122068122069122070122071122072122073122074122075122076122077122078122079122080122081122082122083122084122085122086122087122088122089122090122091122092122093122094122095122096122097122098122099122100122101122102122103122104122105122106122107122108122109122110122111122112122113122114122115122116122117122118122119122120122121122122122123122124122125122126122127122128122129122130122131122132122133122134122135122136122137122138122139122140122141122142122143122144122145122146122147122148122149122150122151122152122153122154122155122156122157122158122159122160122161122162122163122164122165122166122167122168122169122170122171122172122173122174122175122176122177122178122179122180122181122182122183122184122185122186122187122188122189122190122191122192122193122194122195122196122197122198122199122200122201122202122203122204122205122206122207122208122209122210122211122212122213122214122215122216122217122218122219122220122221122222122223122224122225122226122227122228122229122230122231122232122233122234122235122236122237122238122239122240122241122242122243122244122245122246122247122248122249122250122251122252122253122254122255122256122257122258122259122260122261122262122263122264122265122266122267122268122269122270122271122272122273122274122275122276122277122278122279122280122281122282122283122284122285122286122287122288122289122290122291122292122293122294122295122296122297122298122299122300122301122302122303122304122305122306122307122308122309122310122311122312122313122314122315122316122317122318122319122320122321122322122323122324122325122326122327122328122329122330122331122332122333122334122335122336122337122338122339122340122341122342122343122344122345122346122347122348122349122350122351122352122353122354122355122356122357122358122359122360122361122362122363122364122365122366122367122368122369122370122371122372122373122374122375122376122377122378122379122380122381122382122383122384122385122386122387122388122389122390122391122392122393122394122395122396122397122398122399122400122401122402122403122404122405122406122407122408122409122410122411122412122413122414122415122416122417122418122419122420122421122422122423122424122425122426122427122428122429122430122431122432122433122434122435122436122437122438122439122440122441122442122443122444122445122446122447122448122449122450122451122452122453122454122455122456122457122458122459122460122461122462122463122464122465122466122467122468122469122470122471122472122473122474122475122476122477122478122479122480122481122482122483122484122485122486122487122488122489122490122491122492122493122494122495122496122497122498122499122500122501122502122503122504122505122506122507122508122509122510122511122512122513122514122515122516122517122518122519122520122521122522122523122524122525122526122527122528122529122530122531122532122533122534122535122536122537122538122539122540122541122542122543122544122545122546122547122548122549122550122551122552122553122554122555122556122557122558122559122560122561122562122563122564122565122566122567122568122569122570122571122572122573122574122575122576122577122578122579122580122581122582122583122584122585122586122587122588122589122590122591122592122593122594122595122596122597122598122599122600122601122602122603122604122605122606122607122608122609122610122611122612122613122614122615122616122617122618122619122620122621122622122623122624122625122626122627122628122629122630122631122632122633122634122635122636122637122638122639122640122641122642122643122644122645122646122647122648122649122650122651122652122653122654122655122656122657122658122659122660122661122662122663122664122665122666122667122668122669122670122671122672122673122674122675122676122677122678122679122680122681122682122683122684122685122686122687122688122689122690122691122692122693122694122695122696122697122698122699122700122701122702122703122704122705122706122707122708122709122710122711122712122713122714122715122716122717122718122719122720122721122722122723122724122725122726122727122728122729122730122731122732122733122734122735122736122737122738122739122740122741122742122743122744122745122746122747122748122749122750122751122752122753122754122755122756122757122758122759122760122761122762122763122764122765122766122767122768122769122770122771122772122773122774122775122776122777122778122779122780122781122782122783122784122785122786122787122788122789122790122791122792122793122794122795122796122797122798122799122800122801122802122803122804122805122806122807122808122809122810122811122812122813122814122815122816122817122818122819122820122821122822122823122824122825122826122827122828122829122830122831122832122833122834122835122836122837122838122839122840122841122842122843122844122845122846122847122848122849122850122851122852122853122854122855122856122857122858122859122860122861122862122863122864122865122866122867122868122869122870122871122872122873122874122875122876122877122878122879122880122881122882122883122884122885122886122887122888122889122890122891122892122893122894122895122896122897122898122899122900122901122902122903122904122905122906122907122908122909122910122911122912122913122914122915122916122917122918122919122920122921122922122923122924122925122926122927122928122929122930122931122932122933122934122935122936122937122938122939122940122941122942122943122944122945122946122947122948122949122950122951122952122953122954122955122956122957122958122959122960122961122962122963122964122965122966122967122968122969122970122971122972122973122974122975122976122977122978122979122980122981122982122983122984122985122986122987122988122989122990122991122992122993122994122995122996122997122998122999123000123001123002123003123004123005123006123007123008123009123010123011123012123013123014123015123016123017123018123019123020123021123022123023123024123025123026123027123028123029123030123031123032123033123034123035123036123037123038123039123040123041123042123043123044123045123046123047123048123049123050123051123052123053123054123055123056123057123058123059123060123061123062123063123064123065123066123067123068123069123070123071123072123073123074123075123076123077123078123079123080123081123082123083123084123085123086123087123088123089123090123091123092123093123094123095123096123097123098123099123100123101123102123103123104123105123106123107123108123109123110123111123112123113123114123115123116123117123118123119123120123121123122123123123124123125123126123127123128123129123130123131123132123133123134123135123136123137123138123139123140123141123142123143123144123145123146123147123148123149123150123151123152123153123154123155123156123157123158123159123160123161123162123163123164123165123166123167123168123169123170123171123172123173123174123175123176123177123178123179123180123181123182123183123184123185123186123187123188123189123190123191123192123193123194123195123196123197123198123199123200123201123202123203123204123205123206123207123208123209123210123211123212123213123214123215123216123217123218123219123220123221123222123223123224123225123226123227123228123229123230123231123232123233123234123235123236123237123238123239123240123241123242123243123244123245123246123247123248123249123250123251123252123253123254123255123256123257123258123259123260123261123262123263123264123265123266123267123268123269123270123271123272123273123274123275123276123277123278123279123280123281123282123283123284123285123286123287123288123289123290123291123292123293123294123295123296123297123298123299123300123301123302123303123304123305123306123307123308123309123310123311123312123313123314123315123316123317123318123319123320123321123322123323123324123325123326123327123328123329123330123331123332123333123334123335123336123337123338123339123340123341123342123343123344123345123346123347123348123349123350123351123352123353123354123355123356123357123358123359123360123361123362123363123364123365123366123367123368123369123370123371123372123373123374123375123376123377123378123379123380123381123382123383123384123385123386123387123388123389123390123391123392123393123394123395123396123397123398123399123400123401123402123403123404123405123406123407123408123409123410123411123412123413123414123415123416123417123418123419123420123421123422123423123424123425123426123427123428123429123430123431123432123433123434123435123436123437123438123439123440123441123442123443123444123445123446123447123448123449123450123451123452123453123454123455123456123457123458123459123460123461123462123463123464123465123466123467123468123469123470123471123472123473123474123475123476123477123478123479123480123481123482123483123484123485123486123487123488123489123490123491123492123493123494123495123496123497123498123499123500123501123502123503123504123505123506123507123508123509123510123511123512123513123514123515123516123517123518123519123520123521123522123523123524123525123526123527123528123529123530123531123532123533123534123535123536123537123538123539123540123541123542123543123544123545123546123547123548123549123550123551123552123553123554123555123556123557123558123559123560123561123562123563123564123565123566123567123568123569123570123571123572123573123574123575123576123577123578123579123580123581123582123583123584123585123586123587123588123589123590123591123592123593123594123595123596123597123598123599123600123601123602123603123604123605123606123607123608123609123610123611123612123613123614123615123616123617123618123619123620123621123622123623123624123625123626123627123628123629123630123631123632123633123634123635123636123637123638123639123640123641123642123643123644123645123646123647123648123649123650123651123652123653123654123655123656123657123658123659123660123661123662123663123664123665123666123667123668123669123670123671123672123673123674123675123676123677123678123679123680123681123682123683123684123685123686123687123688123689123690123691123692123693123694123695123696123697123698123699123700123701123702123703123704123705123706123707123708123709123710123711123712123713123714123715123716123717123718123719123720123721123722123723123724123725123726123727123728123729123730123731123732123733123734123735123736123737123738123739123740123741123742123743123744123745123746123747123748123749123750123751123752123753123754123755123756123757123758123759123760123761123762123763123764123765123766123767123768123769123770123771123772123773123774123775123776123777123778123779123780123781123782123783123784123785123786123787123788123789123790123791123792123793123794123795123796123797123798123799123800123801123802123803123804123805123806123807123808123809123810123811123812123813123814123815123816123817123818123819123820123821123822123823123824123825123826123827123828123829123830123831123832123833123834123835123836123837123838123839123840123841123842123843123844123845123846123847123848123849123850123851123852123853123854123855123856123857123858123859123860123861123862123863123864123865123866123867123868123869123870123871123872123873123874123875123876123877123878123879123880123881123882123883123884123885123886123887123888123889123890123891123892123893123894123895123896123897123898123899123900123901123902123903123904123905123906123907123908123909123910123911123912123913123914123915123916123917123918123919123920123921123922123923123924123925123926123927123928123929123930123931123932123933123934123935123936123937123938123939123940123941123942123943123944123945123946123947123948123949123950123951123952123953123954123955123956123957123958123959123960123961123962123963123964123965123966123967123968123969123970123971123972123973123974123975123976123977123978123979123980123981123982123983123984123985123986123987123988123989123990123991123992123993123994123995123996123997123998123999124000124001124002124003124004124005124006124007124008124009124010124011124012124013124014124015124016124017124018124019124020124021124022124023124024124025124026124027124028124029124030124031124032124033124034124035124036124037124038124039124040124041124042124043124044124045124046124047124048124049124050124051124052124053124054124055124056124057124058124059124060124061124062124063124064124065124066124067124068124069124070124071124072124073124074124075124076124077124078124079124080124081124082124083124084124085124086124087124088124089124090124091124092124093124094124095124096124097124098124099124100124101124102124103124104124105124106124107124108124109124110124111124112124113124114124115124116124117124118124119124120124121124122124123124124124125124126124127124128124129124130124131124132124133124134124135124136124137124138124139124140124141124142124143124144124145124146124147124148124149124150124151124152124153124154124155124156124157124158124159124160124161124162124163124164124165124166124167124168124169124170124171124172124173124174124175124176124177124178124179124180124181124182124183124184124185124186124187124188124189124190124191124192124193124194124195124196124197124198124199124200124201124202124203124204124205124206124207124208124209124210124211124212124213124214124215124216124217124218124219124220124221124222124223124224124225124226124227124228124229124230124231124232124233124234124235124236124237124238124239124240124241124242124243124244124245124246124247124248124249124250124251124252124253124254124255124256124257124258124259124260124261124262124263124264124265124266124267124268124269124270124271124272124273124274124275124276124277124278124279124280124281124282124283124284124285124286124287124288124289124290124291124292124293124294124295124296124297124298124299124300124301124302124303124304124305124306124307124308124309124310124311124312124313124314124315124316124317124318124319124320124321124322124323124324124325124326124327124328124329124330124331124332124333124334124335124336124337124338124339124340124341124342124343124344124345124346124347124348124349124350124351124352124353124354124355124356124357124358124359124360124361124362124363124364124365124366124367124368124369124370124371124372124373124374124375124376124377124378124379124380124381124382124383124384124385124386124387124388124389124390124391124392124393124394124395124396124397124398124399124400124401124402124403124404124405124406124407124408124409124410124411124412124413124414124415124416124417124418124419124420124421124422124423124424124425124426124427124428124429124430124431124432124433124434124435124436124437124438124439124440124441124442124443124444124445124446124447124448124449124450124451124452124453124454124455124456124457124458124459124460124461124462124463124464124465124466124467124468124469124470124471124472124473124474124475124476124477124478124479124480124481124482124483124484124485124486124487124488124489124490124491124492124493124494124495124496124497124498124499124500124501124502124503124504124505124506124507124508124509124510124511124512124513124514124515124516124517124518124519124520124521124522124523124524124525124526124527124528124529124530124531124532124533124534124535124536124537124538124539124540124541124542124543124544124545124546124547124548124549124550124551124552124553124554124555124556124557124558124559124560124561124562124563124564124565124566124567124568124569124570124571124572124573124574124575124576124577124578124579124580124581124582124583124584124585124586124587124588124589124590124591124592124593124594124595124596124597124598124599124600124601124602124603124604124605124606124607124608124609124610124611124612124613124614124615124616124617124618124619124620124621124622124623124624124625124626124627124628124629124630124631124632124633124634124635124636124637124638124639124640124641124642124643124644124645124646124647124648124649124650124651124652124653124654124655124656124657124658124659124660124661124662124663124664124665124666124667124668124669124670124671124672124673124674124675124676124677124678124679124680124681124682124683124684124685124686124687124688124689124690124691124692124693124694124695124696124697124698124699124700124701124702124703124704124705124706124707124708124709124710124711124712124713124714124715124716124717124718124719124720124721124722124723124724124725124726124727124728124729124730124731124732124733124734124735124736124737124738124739124740124741124742124743124744124745124746124747124748124749124750124751124752124753124754124755124756124757124758124759124760124761124762124763124764124765124766124767124768124769124770124771124772124773124774124775124776124777124778124779124780124781124782124783124784124785124786124787124788124789124790124791124792124793124794124795124796124797124798124799124800124801124802124803124804124805124806124807124808124809124810124811124812124813124814124815124816124817124818124819124820124821124822124823124824124825124826124827124828124829124830124831124832124833124834124835124836124837124838124839124840124841124842124843124844124845124846124847124848124849124850124851124852124853124854124855124856124857124858124859124860124861124862124863124864124865124866124867124868124869124870124871124872124873124874124875124876124877124878124879124880124881124882124883124884124885124886124887124888124889124890124891124892124893124894124895124896124897124898124899124900124901124902124903124904124905124906124907124908124909124910124911124912124913124914124915124916124917124918124919124920124921124922124923124924124925124926124927124928124929124930124931124932124933124934124935124936124937124938124939124940124941124942124943124944124945124946124947124948124949124950124951124952124953124954124955124956124957124958124959124960124961124962124963124964124965124966124967124968124969124970124971124972124973124974124975124976124977124978124979124980124981124982124983124984124985124986124987124988124989124990124991124992124993124994124995124996124997124998124999125000125001125002125003125004125005125006125007125008125009125010125011125012125013125014125015125016125017125018125019125020125021125022125023125024125025125026125027125028125029125030125031125032125033125034125035125036125037125038125039125040125041125042125043125044125045125046125047125048125049125050125051125052125053125054125055125056125057125058125059125060125061125062125063125064125065125066125067125068125069125070125071125072125073125074125075125076125077125078125079125080125081125082125083125084125085125086125087125088125089125090125091125092125093125094125095125096125097125098125099125100125101125102125103125104125105125106125107125108125109125110125111125112125113125114125115125116125117125118125119125120125121125122125123125124125125125126125127125128125129125130125131125132125133125134125135125136125137125138125139125140125141125142125143125144125145125146125147125148125149125150125151125152125153125154125155125156125157125158125159125160125161125162125163125164125165125166125167125168125169125170125171125172125173125174125175125176125177125178125179125180125181125182125183125184125185125186125187125188125189125190125191125192125193125194125195125196125197125198125199125200125201125202125203125204125205125206125207125208125209125210125211125212125213125214125215125216125217125218125219125220125221125222125223125224125225125226125227125228125229125230125231125232125233125234125235125236125237125238125239125240125241125242125243125244125245125246125247125248125249125250125251125252125253125254125255125256125257125258125259125260125261125262125263125264125265125266125267125268125269125270125271125272125273125274125275125276125277125278125279125280125281125282125283125284125285125286125287125288125289125290125291125292125293125294125295125296125297125298125299125300125301125302125303125304125305125306125307125308125309125310125311125312125313125314125315125316125317125318125319125320125321125322125323125324125325125326125327125328125329125330125331125332125333125334125335125336125337125338125339125340125341125342125343125344125345125346125347125348125349125350125351125352125353125354125355125356125357125358125359125360125361125362125363125364125365125366125367125368125369125370125371125372125373125374125375125376125377125378125379125380125381125382125383125384125385125386125387125388125389125390125391125392125393125394125395125396125397125398125399125400125401125402125403125404125405125406125407125408125409125410125411125412125413125414125415125416125417125418125419125420125421125422125423125424125425125426125427125428125429125430125431125432125433125434125435125436125437125438125439125440125441125442125443125444125445125446125447125448125449125450125451125452125453125454125455125456125457125458125459125460125461125462125463125464125465125466125467125468125469125470125471125472125473125474125475125476125477125478125479125480125481125482125483125484125485125486125487125488125489125490125491125492125493125494125495125496125497125498125499125500125501125502125503125504125505125506125507125508125509125510125511125512125513125514125515125516125517125518125519125520125521125522125523125524125525125526125527125528125529125530125531125532125533125534125535125536125537125538125539125540125541125542125543125544125545125546125547125548125549125550125551125552125553125554125555125556125557125558125559125560125561125562125563125564125565125566125567125568125569125570125571125572125573125574125575125576125577125578125579125580125581125582125583125584125585125586125587125588125589125590125591125592125593125594125595125596125597125598125599125600125601125602125603125604125605125606125607125608125609125610125611125612125613125614125615125616125617125618125619125620125621125622125623125624125625125626125627125628125629125630125631125632125633125634125635125636125637125638125639125640125641125642125643125644125645125646125647125648125649125650125651125652125653125654125655125656125657125658125659125660125661125662125663125664125665125666125667125668125669125670125671125672125673125674125675125676125677125678125679125680125681125682125683125684125685125686125687125688125689125690125691125692125693125694125695125696125697125698125699125700125701125702125703125704125705125706125707125708125709125710125711125712125713125714125715125716125717125718125719125720125721125722125723125724125725125726125727125728125729125730125731125732125733125734125735125736125737125738125739125740125741125742125743125744125745125746125747125748125749125750125751125752125753125754125755125756125757125758125759125760125761125762125763125764125765125766125767125768125769125770125771125772125773125774125775125776125777125778125779125780125781125782125783125784125785125786125787125788125789125790125791125792125793125794125795125796125797125798125799125800125801125802125803125804125805125806125807125808125809125810125811125812125813125814125815125816125817125818125819125820125821125822125823125824125825125826125827125828125829125830125831125832125833125834125835125836125837125838125839125840125841125842125843125844125845125846125847125848125849125850125851125852125853125854125855125856125857125858125859125860125861125862125863125864125865125866125867125868125869125870125871125872125873125874125875125876125877125878125879125880125881125882125883125884125885125886125887125888125889125890125891125892125893125894125895125896125897125898125899125900125901125902125903125904125905125906125907125908125909125910125911125912125913125914125915125916125917125918125919125920125921125922125923125924125925125926125927125928125929125930125931125932125933125934125935125936125937125938125939125940125941125942125943125944125945125946125947125948125949125950125951125952125953125954125955125956125957125958125959125960125961125962125963125964125965125966125967125968125969125970125971125972125973125974125975125976125977125978125979125980125981125982125983125984125985125986125987125988125989125990125991125992125993125994125995125996125997125998125999126000126001126002126003126004126005126006126007126008126009126010126011126012126013126014126015126016126017126018126019126020126021126022126023126024126025126026126027126028126029126030126031126032126033126034126035126036126037126038126039126040126041126042126043126044126045126046126047126048126049126050126051126052126053126054126055126056126057126058126059126060126061126062126063126064126065126066126067126068126069126070126071126072126073126074126075126076126077126078126079126080126081126082126083126084126085126086126087126088126089126090126091126092126093126094126095126096126097126098126099126100126101126102126103126104126105126106126107126108126109126110126111126112126113126114126115126116126117126118126119126120126121126122126123126124126125126126126127126128126129126130126131126132126133126134126135126136126137126138126139126140126141126142126143126144126145126146126147126148126149126150126151126152126153126154126155126156126157126158126159126160126161126162126163126164126165126166126167126168126169126170126171126172126173126174126175126176126177126178126179126180126181126182126183126184126185126186126187126188126189126190126191126192126193126194126195126196126197126198126199126200126201126202126203126204126205126206126207126208126209126210126211126212126213126214126215126216126217126218126219126220126221126222126223126224126225126226126227126228126229126230126231126232126233126234126235126236126237126238126239126240126241126242126243126244126245126246126247126248126249126250126251126252126253126254126255126256126257126258126259126260126261126262126263126264126265126266126267126268126269126270126271126272126273126274126275126276126277126278126279126280126281126282126283126284126285126286126287126288126289126290126291126292126293126294126295126296126297126298126299126300126301126302126303126304126305126306126307126308126309126310126311126312126313126314126315126316126317126318126319126320126321126322126323126324126325126326126327126328126329126330126331126332126333126334126335126336126337126338126339126340126341126342126343126344126345126346126347126348126349126350126351126352126353126354126355126356126357126358126359126360126361126362126363126364126365126366126367126368126369126370126371126372126373126374126375126376126377126378126379126380126381126382126383126384126385126386126387126388126389126390126391126392126393126394126395126396126397126398126399126400126401126402126403126404126405126406126407126408126409126410126411126412126413126414126415126416126417126418126419126420126421126422126423126424126425126426126427126428126429126430126431126432126433126434126435126436126437126438126439126440126441126442126443126444126445126446126447126448126449126450126451126452126453126454126455126456126457126458126459126460126461126462126463126464126465126466126467126468126469126470126471126472126473126474126475126476126477126478126479126480126481126482126483126484126485126486126487126488126489126490126491126492126493126494126495126496126497126498126499126500126501126502126503126504126505126506126507126508126509126510126511126512126513126514126515126516126517126518126519126520126521126522126523126524126525126526126527126528126529126530126531126532126533126534126535126536126537126538126539126540126541126542126543126544126545126546126547126548126549126550126551126552126553126554126555126556126557126558126559126560126561126562126563126564126565126566126567126568126569126570126571126572126573126574126575126576126577126578126579126580126581126582126583126584126585126586126587126588126589126590126591126592126593126594126595126596126597126598126599126600126601126602126603126604126605126606126607126608126609126610126611126612126613126614126615126616126617126618126619126620126621126622126623126624126625126626126627126628126629126630126631126632126633126634126635126636126637126638126639126640126641126642126643126644126645126646126647126648126649126650126651126652126653126654126655126656126657126658126659126660126661126662126663126664126665126666126667126668126669126670126671126672126673126674126675126676126677126678126679126680126681126682126683126684126685126686126687126688126689126690126691126692126693126694126695126696126697126698126699126700126701126702126703126704126705126706126707126708126709126710126711126712126713126714126715126716126717126718126719126720126721126722126723126724126725126726126727126728126729126730126731126732126733126734126735126736126737126738126739126740126741126742126743126744126745126746126747126748126749126750126751126752126753126754126755126756126757126758126759126760126761126762126763126764126765126766126767126768126769126770126771126772126773126774126775126776126777126778126779126780126781126782126783126784126785126786126787126788126789126790126791126792126793126794126795126796126797126798126799126800126801126802126803126804126805126806126807126808126809126810126811126812126813126814126815126816126817126818126819126820126821126822126823126824126825126826126827126828126829126830126831126832126833126834126835126836126837126838126839126840126841126842126843126844126845126846126847126848126849126850126851126852126853126854126855126856126857126858126859126860126861126862126863126864126865126866126867126868126869126870126871126872126873126874126875126876126877126878126879126880126881126882126883126884126885126886126887126888126889126890126891126892126893126894126895126896126897126898126899126900126901126902126903126904126905126906126907126908126909126910126911126912126913126914126915126916126917126918126919126920126921126922126923126924126925126926126927126928126929126930126931126932126933126934126935126936126937126938126939126940126941126942126943126944126945126946126947126948126949126950126951126952126953126954126955126956126957126958126959126960126961126962126963126964126965126966126967126968126969126970126971126972126973126974126975126976126977126978126979126980126981126982126983126984126985126986126987126988126989126990126991126992126993126994126995126996126997126998126999127000127001127002127003127004127005127006127007127008127009127010127011127012127013127014127015127016127017127018127019127020127021127022127023127024127025127026127027127028127029127030127031127032127033127034127035127036127037127038127039127040127041127042127043127044127045127046127047127048127049127050127051127052127053127054127055127056127057127058127059127060127061127062127063127064127065127066127067127068127069127070127071127072127073127074127075127076127077127078127079127080127081127082127083127084127085127086127087127088127089127090127091127092127093127094127095127096127097127098127099127100127101127102127103127104127105127106127107127108127109127110127111127112127113127114127115127116127117127118127119127120127121127122127123127124127125127126127127127128127129127130127131127132127133127134127135127136127137127138127139127140127141127142127143127144127145127146127147127148127149127150127151127152127153127154127155127156127157127158127159127160127161127162127163127164127165127166127167127168127169127170127171127172127173127174127175127176127177127178127179127180127181127182127183127184127185127186127187127188127189127190127191127192127193127194127195127196127197127198127199127200127201127202127203127204127205127206127207127208127209127210127211127212127213127214127215127216127217127218127219127220127221127222127223127224127225127226127227127228127229127230127231127232127233127234127235127236127237127238127239127240127241127242127243127244127245127246127247127248127249127250127251127252127253127254127255127256127257127258127259127260127261127262127263127264127265127266127267127268127269127270127271127272127273127274127275127276127277127278127279127280127281127282127283127284127285127286127287127288127289127290127291127292127293127294127295127296127297127298127299127300127301127302127303127304127305127306127307127308127309127310127311127312127313127314127315127316127317127318127319127320127321127322127323127324127325127326127327127328127329127330127331127332127333127334127335127336127337127338127339127340127341127342127343127344127345127346127347127348127349127350127351127352127353127354127355127356127357127358127359127360127361127362127363127364127365127366127367127368127369127370127371127372127373127374127375127376127377127378127379127380127381127382127383127384127385127386127387127388127389127390127391127392127393127394127395127396127397127398127399127400127401127402127403127404127405127406127407127408127409127410127411127412127413127414127415127416127417127418127419127420127421127422127423127424127425127426127427127428127429127430127431127432127433127434127435127436127437127438127439127440127441127442127443127444127445127446127447127448127449127450127451127452127453127454127455127456127457127458127459127460127461127462127463127464127465127466127467127468127469127470127471127472127473127474127475127476127477127478127479127480127481127482127483127484127485127486127487127488127489127490127491127492127493127494127495127496127497127498127499127500127501127502127503127504127505127506127507127508127509127510127511127512127513127514127515127516127517127518127519127520127521127522127523127524127525127526127527127528127529127530127531127532127533127534127535127536127537127538127539127540127541127542127543127544127545127546127547127548127549127550127551127552127553127554127555127556127557127558127559127560127561127562127563127564127565127566127567127568127569127570127571127572127573127574127575127576127577127578127579127580127581127582127583127584127585127586127587127588127589127590127591127592127593127594127595127596127597127598127599127600127601127602127603127604127605127606127607127608127609127610127611127612127613127614127615127616127617127618127619127620127621127622127623127624127625127626127627127628127629127630127631127632127633127634127635127636127637127638127639127640127641127642127643127644127645127646127647127648127649127650127651127652127653127654127655127656127657127658127659127660127661127662127663127664127665127666127667127668127669127670127671127672127673127674127675127676127677127678127679127680127681127682127683127684127685127686127687127688127689127690127691127692127693127694127695127696127697127698127699127700127701127702127703127704127705127706127707127708127709127710127711127712127713127714127715127716127717127718127719127720127721127722127723127724127725127726127727127728127729127730127731127732127733127734127735127736127737127738127739127740127741127742127743127744127745127746127747127748127749127750127751127752127753127754127755127756127757127758127759127760127761127762127763127764127765127766127767127768127769127770127771127772127773127774127775127776127777127778127779127780127781127782127783127784127785127786127787127788127789127790127791127792127793127794127795127796127797127798127799127800127801127802127803127804127805127806127807127808127809127810127811127812127813127814127815127816127817127818127819127820127821127822127823127824127825127826127827127828127829127830127831127832127833127834127835127836127837127838127839127840127841127842127843127844127845127846127847127848127849127850127851127852127853127854127855127856127857127858127859127860127861127862127863127864127865127866127867127868127869127870127871127872127873127874127875127876127877127878127879127880127881127882127883127884127885127886127887127888127889127890127891127892127893127894127895127896127897127898127899127900127901127902127903127904127905127906127907127908127909127910127911127912127913127914127915127916127917127918127919127920127921127922127923127924127925127926127927127928127929127930127931127932127933127934127935127936127937127938127939127940127941127942127943127944127945127946127947127948127949127950127951127952127953127954127955127956127957127958127959127960127961127962127963127964127965127966127967127968127969127970127971127972127973127974127975127976127977127978127979127980127981127982127983127984127985127986127987127988127989127990127991127992127993127994127995127996127997127998127999128000128001128002128003128004128005128006128007128008128009128010128011128012128013128014128015128016128017128018128019128020128021128022128023128024128025128026128027128028128029128030128031128032128033128034128035128036128037128038128039128040128041128042128043128044128045128046128047128048128049128050128051128052128053128054128055128056128057128058128059128060128061128062128063128064128065128066128067128068128069128070128071128072128073128074128075128076128077128078128079128080128081128082128083128084128085128086128087128088128089128090128091128092128093128094128095128096128097128098128099128100128101128102128103128104128105128106128107128108128109128110128111128112128113128114128115128116128117128118128119128120128121128122128123128124128125128126128127128128128129128130128131128132128133128134128135128136128137128138128139128140128141128142128143128144128145128146128147128148128149128150128151128152128153128154128155128156128157128158128159128160128161128162128163128164128165128166128167128168128169128170128171128172128173128174128175128176128177128178128179128180128181128182128183128184128185128186128187128188128189128190128191128192128193128194128195128196128197128198128199128200128201128202128203128204128205128206128207128208128209128210128211128212128213128214128215128216128217128218128219128220128221128222128223128224128225128226128227128228128229128230128231128232128233128234128235128236128237128238128239128240128241128242128243128244128245128246128247128248128249128250128251128252128253128254128255128256128257128258128259128260128261128262128263128264128265128266128267128268128269128270128271128272128273128274128275128276128277128278128279128280128281128282128283128284128285128286128287128288128289128290128291128292128293128294128295128296128297128298128299128300128301128302128303128304128305128306128307128308128309128310128311128312128313128314128315128316128317128318128319128320128321128322128323128324128325128326128327128328128329128330128331128332128333128334128335128336128337128338128339128340128341128342128343128344128345128346128347128348128349128350128351128352128353128354128355128356128357128358128359128360128361128362128363128364128365128366128367128368128369128370128371128372128373128374128375128376128377128378128379128380128381128382128383128384128385128386128387128388128389128390128391128392128393128394128395128396128397128398128399128400128401128402128403128404128405128406128407128408128409128410128411128412128413128414128415128416128417128418128419128420128421128422128423128424128425128426128427128428128429128430128431128432128433128434128435128436128437128438128439128440128441128442128443128444128445128446128447128448128449128450128451128452128453128454128455128456128457128458128459128460128461128462128463128464128465128466128467128468128469128470128471128472128473128474128475128476128477128478128479128480128481128482128483128484128485128486128487128488128489128490128491128492128493128494128495128496128497128498128499128500128501128502128503128504128505128506128507128508128509128510128511128512128513128514128515128516128517128518128519128520128521128522128523128524128525128526128527128528128529128530128531128532128533128534128535128536128537128538128539128540128541128542128543128544128545128546128547128548128549128550128551128552128553128554128555128556128557128558128559128560128561128562128563128564128565128566128567128568128569128570128571128572128573128574128575128576128577128578128579128580128581128582128583128584128585128586128587128588128589128590128591128592128593128594128595128596128597128598128599128600128601128602128603128604128605128606128607128608128609128610128611128612128613128614128615128616128617128618128619128620128621128622128623128624128625128626128627128628128629128630128631128632128633128634128635128636128637128638128639128640128641128642128643128644128645128646128647128648128649128650128651128652128653128654128655128656128657128658128659128660128661128662128663128664128665128666128667128668128669128670128671128672128673128674128675128676128677128678128679128680128681128682128683128684128685128686128687128688128689128690128691128692128693128694128695128696128697128698128699128700128701128702128703128704128705128706128707128708128709128710128711128712128713128714128715128716128717128718128719128720128721128722128723128724128725128726128727128728128729128730128731128732128733128734128735128736128737128738128739128740128741128742128743128744128745128746128747128748128749128750128751128752128753128754128755128756128757128758128759128760128761128762128763128764128765128766128767128768128769128770128771128772128773128774128775128776128777128778128779128780128781128782128783128784128785128786128787128788128789128790128791128792128793128794128795128796128797128798128799128800128801128802128803128804128805128806128807128808128809128810128811128812128813128814128815128816128817128818128819128820128821128822128823128824128825128826128827128828128829128830128831128832128833128834128835128836128837128838128839128840128841128842128843128844128845128846128847128848128849128850128851128852128853128854128855128856128857128858128859128860128861128862128863128864128865128866128867128868128869128870128871128872128873128874128875128876128877128878128879128880128881128882128883128884128885128886128887128888128889128890128891128892128893128894128895128896128897128898128899128900128901128902128903128904128905128906128907128908128909128910128911128912128913128914128915128916128917128918128919128920128921128922128923128924128925128926128927128928128929128930128931128932128933128934128935128936128937128938128939128940128941128942128943128944128945128946128947128948128949128950128951128952128953128954128955128956128957128958128959128960128961128962128963128964128965128966128967128968128969128970128971128972128973128974128975128976128977128978128979128980128981128982128983128984128985128986128987128988128989128990128991128992128993128994128995128996128997128998128999129000129001129002129003129004129005129006129007129008129009129010129011129012129013129014129015129016129017129018129019129020129021129022129023129024129025129026129027129028129029129030129031129032129033129034129035129036129037129038129039129040129041129042129043129044129045129046129047129048129049129050129051129052129053129054129055129056129057129058129059129060129061129062129063129064129065129066129067129068129069129070129071129072129073129074129075129076129077129078129079129080129081129082129083129084129085129086129087129088129089129090129091129092129093129094129095129096129097129098129099129100129101129102129103129104129105129106129107129108129109129110129111129112129113129114129115129116129117129118129119129120129121129122129123129124129125129126129127129128129129129130129131129132129133129134129135129136129137129138129139129140129141129142129143129144129145129146129147129148129149129150129151129152129153129154129155129156129157129158129159129160129161129162129163129164129165129166129167129168129169129170129171129172129173129174129175129176129177129178129179129180129181129182129183129184129185129186129187129188129189129190129191129192129193129194129195129196129197129198129199129200129201129202129203129204129205129206129207129208129209129210129211129212129213129214129215129216129217129218129219129220129221129222129223129224129225129226129227129228129229129230129231129232129233129234129235129236129237129238129239129240129241129242129243129244129245129246129247129248129249129250129251129252129253129254129255129256129257129258129259129260129261129262129263129264129265129266129267129268129269129270129271129272129273129274129275129276129277129278129279129280129281129282129283129284129285129286129287129288129289129290129291129292129293129294129295129296129297129298129299129300129301129302129303129304129305129306129307129308129309129310129311129312129313129314129315129316129317129318129319129320129321129322129323129324129325129326129327129328129329129330129331129332129333129334129335129336129337129338129339129340129341129342129343129344129345129346129347129348129349129350129351129352129353129354129355129356129357129358129359129360129361129362129363129364129365129366129367129368129369129370129371129372129373129374129375129376129377129378129379129380129381129382129383129384129385129386129387129388129389129390129391129392129393129394129395129396129397129398129399129400129401129402129403129404129405129406129407129408129409129410129411129412129413129414129415129416129417129418129419129420129421129422129423129424129425129426129427129428129429129430129431129432129433129434129435129436129437129438129439129440129441129442129443129444129445129446129447129448129449129450129451129452129453129454129455129456129457129458129459129460129461129462129463129464129465129466129467129468129469129470129471129472129473129474129475129476129477129478129479129480129481129482129483129484129485129486129487129488129489129490129491129492129493129494129495129496129497129498129499129500129501129502129503129504129505129506129507129508129509129510129511129512129513129514129515129516129517129518129519129520129521129522129523129524129525129526129527129528129529129530129531129532129533129534129535129536129537129538129539129540129541129542129543129544129545129546129547129548129549129550129551129552129553129554129555129556129557129558129559129560129561129562129563129564129565129566129567129568129569129570129571129572129573129574129575129576129577129578129579129580129581129582129583129584129585129586129587129588129589129590129591129592129593129594129595129596129597129598129599129600129601129602129603129604129605129606129607129608129609129610129611129612129613129614129615129616129617129618129619129620129621129622129623129624129625129626129627129628129629129630129631129632129633129634129635129636129637129638129639129640129641129642129643129644129645129646129647129648129649129650129651129652129653129654129655129656129657129658129659129660129661129662129663129664129665129666129667129668129669129670129671129672129673129674129675129676129677129678129679129680129681129682129683129684129685129686129687129688129689129690129691129692129693129694129695129696129697129698129699129700129701129702129703129704129705129706129707129708129709129710129711129712129713129714129715129716129717129718129719129720129721129722129723129724129725129726129727129728129729129730129731129732129733129734129735129736129737129738129739129740129741129742129743129744129745129746129747129748129749129750129751129752129753129754129755129756129757129758129759129760129761129762129763129764129765129766129767129768129769129770129771129772129773129774129775129776129777129778129779129780129781129782129783129784129785129786129787129788129789129790129791129792129793129794129795129796129797129798129799129800129801129802129803129804129805129806129807129808129809129810129811129812129813129814129815129816129817129818129819129820129821129822129823129824129825129826129827129828129829129830129831129832129833129834129835129836129837129838129839129840129841129842129843129844129845129846129847129848129849129850129851129852129853129854129855129856129857129858129859129860129861129862129863129864129865129866129867129868129869129870129871129872129873129874129875129876129877129878129879129880129881129882129883129884129885129886129887129888129889129890129891129892129893129894129895129896129897129898129899129900129901129902129903129904129905129906129907129908129909129910129911129912129913129914129915129916129917129918129919129920129921129922129923129924129925129926129927129928129929129930129931129932129933129934129935129936129937129938129939129940129941129942129943129944129945129946129947129948129949129950129951129952129953129954129955129956129957129958129959129960129961129962129963129964129965129966129967129968129969129970129971129972129973129974129975129976129977129978129979129980129981129982129983129984129985129986129987129988129989129990129991129992129993129994129995129996129997129998129999130000130001130002130003130004130005130006130007130008130009130010130011130012130013130014130015130016130017130018130019130020130021130022130023130024130025130026130027130028130029130030130031130032130033130034130035130036130037130038130039130040130041130042130043130044130045130046130047130048130049130050130051130052130053130054130055130056130057130058130059130060130061130062130063130064130065130066130067130068130069130070130071130072130073130074130075130076130077130078130079130080130081130082130083130084130085130086130087130088130089130090130091130092130093130094130095130096130097130098130099130100130101130102130103130104130105130106130107130108130109130110130111130112130113130114130115130116130117130118130119130120130121130122130123130124130125130126130127130128130129130130130131130132130133130134130135130136130137130138130139130140130141130142130143130144130145130146130147130148130149130150130151130152130153130154130155130156130157130158130159130160130161130162130163130164130165130166130167130168130169130170130171130172130173130174130175130176130177130178130179130180130181130182130183130184130185130186130187130188130189130190130191130192130193130194130195130196130197130198130199130200130201130202130203130204130205130206130207130208130209130210130211130212130213130214130215130216130217130218130219130220130221130222130223130224130225130226130227130228130229130230130231130232130233130234130235130236130237130238130239130240130241130242130243130244130245130246130247130248130249130250130251130252130253130254130255130256130257130258130259130260130261130262130263130264130265130266130267130268130269130270130271130272130273130274130275130276130277130278130279130280130281130282130283130284130285130286130287130288130289130290130291130292130293130294130295130296130297130298130299130300130301130302130303130304130305130306130307130308130309130310130311130312130313130314130315130316130317130318130319130320130321130322130323130324130325130326130327130328130329130330130331130332130333130334130335130336130337130338130339130340130341130342130343130344130345130346130347130348130349130350130351130352130353130354130355130356130357130358130359130360130361130362130363130364130365130366130367130368130369130370130371130372130373130374130375130376130377130378130379130380130381130382130383130384130385130386130387130388130389130390130391130392130393130394130395130396130397130398130399130400130401130402130403130404130405130406130407130408130409130410130411130412130413130414130415130416130417130418130419130420130421130422130423130424130425130426130427130428130429130430130431130432130433130434130435130436130437130438130439130440130441130442130443130444130445130446130447130448130449130450130451130452130453130454130455130456130457130458130459130460130461130462130463130464130465130466130467130468130469130470130471130472130473130474130475130476130477130478130479130480130481130482130483130484130485130486130487130488130489130490130491130492130493130494130495130496130497130498130499130500130501130502130503130504130505130506130507130508130509130510130511130512130513130514130515130516130517130518130519130520130521130522130523130524130525130526130527130528130529130530130531130532130533130534130535130536130537130538130539130540130541130542130543130544130545130546130547130548130549130550130551130552130553130554130555130556130557130558130559130560130561130562130563130564130565130566130567130568130569130570130571130572130573130574130575130576130577130578130579130580130581130582130583130584130585130586130587130588130589130590130591130592130593130594130595130596130597130598130599130600130601130602130603130604130605130606130607130608130609130610130611130612130613130614130615130616130617130618130619130620130621130622130623130624130625130626130627130628130629130630130631130632130633130634130635130636130637130638130639130640130641130642130643130644130645130646130647130648130649130650130651130652130653130654130655130656130657130658130659130660130661130662130663130664130665130666130667130668130669130670130671130672130673130674130675130676130677130678130679130680130681130682130683130684130685130686130687130688130689130690130691130692130693130694130695130696130697130698130699130700130701130702130703130704130705130706130707130708130709130710130711130712130713130714130715130716130717130718130719130720130721130722130723130724130725130726130727130728130729130730130731130732130733130734130735130736130737130738130739130740130741130742130743130744130745130746130747130748130749130750130751130752130753130754130755130756130757130758130759130760130761130762130763130764130765130766130767130768130769130770130771130772130773130774130775130776130777130778130779130780130781130782130783130784130785130786130787130788130789130790130791130792130793130794130795130796130797130798130799130800130801130802130803130804130805130806130807130808130809130810130811130812130813130814130815130816130817130818130819130820130821130822130823130824130825130826130827130828130829130830130831130832130833130834130835130836130837130838130839130840130841130842130843130844130845130846130847130848130849130850130851130852130853130854130855130856130857130858130859130860130861130862130863130864130865130866130867130868130869130870130871130872130873130874130875130876130877130878130879130880130881130882130883130884130885130886130887130888130889130890130891130892130893130894130895130896130897130898130899130900130901130902130903130904130905130906130907130908130909130910130911130912130913130914130915130916130917130918130919130920130921130922130923130924130925130926130927130928130929130930130931130932130933130934130935130936130937130938130939130940130941130942130943130944130945130946130947130948130949130950130951130952130953130954130955130956130957130958130959130960130961130962130963130964130965130966130967130968130969130970130971130972130973130974130975130976130977130978130979130980130981130982130983130984130985130986130987130988130989130990130991130992130993130994130995130996130997130998130999131000131001131002131003131004131005131006131007131008131009131010131011131012131013131014131015131016131017131018131019131020131021131022131023131024131025131026131027131028131029131030131031131032131033131034131035131036131037131038131039131040131041131042131043131044131045131046131047131048131049131050131051131052131053131054131055131056131057131058131059131060131061131062131063131064131065131066131067131068131069131070131071131072131073131074131075131076131077131078131079131080131081131082131083131084131085131086131087131088131089131090131091131092131093131094131095131096131097131098131099131100131101131102131103131104131105131106131107131108131109131110131111131112131113131114131115131116131117131118131119131120131121131122131123131124131125131126131127131128131129131130131131131132131133131134131135131136131137131138131139131140131141131142131143131144131145131146131147131148131149131150131151131152131153131154131155131156131157131158131159131160131161131162131163131164131165131166131167131168131169131170131171131172131173131174131175131176131177131178131179131180131181131182131183131184131185131186131187131188131189131190131191131192131193131194131195131196131197131198131199131200131201131202131203131204131205131206131207131208131209131210131211131212131213131214131215131216131217131218131219131220131221131222131223131224131225131226131227131228131229131230131231131232131233131234131235131236131237131238131239131240131241131242131243131244131245131246131247131248131249131250131251131252131253131254131255131256131257131258131259131260131261131262131263131264131265131266131267131268131269131270131271131272131273131274131275131276131277131278131279131280131281131282131283131284131285131286131287131288131289131290131291131292131293131294131295131296131297131298131299131300131301131302131303131304131305131306131307131308131309131310131311131312131313131314131315131316131317131318131319131320131321131322131323131324131325131326131327131328131329131330131331131332131333131334131335131336131337131338131339131340131341131342131343131344131345131346131347131348131349131350131351131352131353131354131355131356131357131358131359131360131361131362131363131364131365131366131367131368131369131370131371131372131373131374131375131376131377131378131379131380131381131382131383131384131385131386131387131388131389131390131391131392131393131394131395131396131397131398131399131400131401131402131403131404131405131406131407131408131409131410131411131412131413131414131415131416131417131418131419131420131421131422131423131424131425131426131427131428131429131430131431131432131433131434131435131436131437131438131439131440131441131442131443131444131445131446131447131448131449131450131451131452131453131454131455131456131457131458131459131460131461131462131463131464131465131466131467131468131469131470131471131472131473131474131475131476131477131478131479131480131481131482131483131484131485131486131487131488131489131490131491131492131493131494131495131496131497131498131499131500131501131502131503131504131505131506131507131508131509131510131511131512131513131514131515131516131517131518131519131520131521131522131523131524131525131526131527131528131529131530131531131532131533131534131535131536131537131538131539131540131541131542131543131544131545131546131547131548131549131550131551131552131553131554131555131556131557131558131559131560131561131562131563131564131565131566131567131568131569131570131571131572131573131574131575131576131577131578131579131580131581131582131583131584131585131586131587131588131589131590131591131592131593131594131595131596131597131598131599131600131601131602131603131604131605131606131607131608131609131610131611131612131613131614131615131616131617131618131619131620131621131622131623131624131625131626131627131628131629131630131631131632131633131634131635131636131637131638131639131640131641131642131643131644131645131646131647131648131649131650131651131652131653131654131655131656131657131658131659131660131661131662131663131664131665131666131667131668131669131670131671131672131673131674131675131676131677131678131679131680131681131682131683131684131685131686131687131688131689131690131691131692131693131694131695131696131697131698131699131700131701131702131703131704131705131706131707131708131709131710131711131712131713131714131715131716131717131718131719131720131721131722131723131724131725131726131727131728131729131730131731131732131733131734131735131736131737131738131739131740131741131742131743131744131745131746131747131748131749131750131751131752131753131754131755131756131757131758131759131760131761131762131763131764131765131766131767131768131769131770131771131772131773131774131775131776131777131778131779131780131781131782131783131784131785131786131787131788131789131790131791131792131793131794131795131796131797131798131799131800131801131802131803131804131805131806131807131808131809131810131811131812131813131814131815131816131817131818131819131820131821131822131823131824131825131826131827131828131829131830131831131832131833131834131835131836131837131838131839131840131841131842131843131844131845131846131847131848131849131850131851131852131853131854131855131856131857131858131859131860131861131862131863131864131865131866131867131868131869131870131871131872131873131874131875131876131877131878131879131880131881131882131883131884131885131886131887131888131889131890131891131892131893131894131895131896131897131898131899131900131901131902131903131904131905131906131907131908131909131910131911131912131913131914131915131916131917131918131919131920131921131922131923131924131925131926131927131928131929131930131931131932131933131934131935131936131937131938131939131940131941131942131943131944131945131946131947131948131949131950131951131952131953131954131955131956131957131958131959131960131961131962131963131964131965131966131967131968131969131970131971131972131973131974131975131976131977131978131979131980131981131982131983131984131985131986131987131988131989131990131991131992131993131994131995131996131997131998131999132000132001132002132003132004132005132006132007132008132009132010132011132012132013132014132015132016132017132018132019132020132021132022132023132024132025132026132027132028132029132030132031132032132033132034132035132036132037132038132039132040132041132042132043132044132045132046132047132048132049132050132051132052132053132054132055132056132057132058132059132060132061132062132063132064132065132066132067132068132069132070132071132072132073132074132075132076132077132078132079132080132081132082132083132084132085132086132087132088132089132090132091132092132093132094132095132096132097132098132099132100132101132102132103132104132105132106132107132108132109132110132111132112132113132114132115132116132117132118132119132120132121132122132123132124132125132126132127132128132129132130132131132132132133132134132135132136132137132138132139132140132141132142132143132144132145132146132147132148132149132150132151132152132153132154132155132156132157132158132159132160132161132162132163132164132165132166132167132168132169132170132171132172132173132174132175132176132177132178132179132180132181132182132183132184132185132186132187132188132189132190132191132192132193132194132195132196132197132198132199132200132201132202132203132204132205132206132207132208132209132210132211132212132213132214132215132216132217132218132219132220132221132222132223132224132225132226132227132228132229132230132231132232132233132234132235132236132237132238132239132240132241132242132243132244132245132246132247132248132249132250132251132252132253132254132255132256132257132258132259132260132261132262132263132264132265132266132267132268132269132270132271132272132273132274132275132276132277132278132279132280132281132282132283132284132285132286132287132288132289132290132291132292132293132294132295132296132297132298132299132300132301132302132303132304132305132306132307132308132309132310132311132312132313132314132315132316132317132318132319132320132321132322132323132324132325132326132327132328132329132330132331132332132333132334132335132336132337132338132339132340132341132342132343132344132345132346132347132348132349132350132351132352132353132354132355132356132357132358132359132360132361132362132363132364132365132366132367132368132369132370132371132372132373132374132375132376132377132378132379132380132381132382132383132384132385132386132387132388132389132390132391132392132393132394132395132396132397132398132399132400132401132402132403132404132405132406132407132408132409132410132411132412132413132414132415132416132417132418132419132420132421132422132423132424132425132426132427132428132429132430132431132432132433132434132435132436132437132438132439132440132441132442132443132444132445132446132447132448132449132450132451132452132453132454132455132456132457132458132459132460132461132462132463132464132465132466132467132468132469132470132471132472132473132474132475132476132477132478132479132480132481132482132483132484132485132486132487132488132489132490132491132492132493132494132495132496132497132498132499132500132501132502132503132504132505132506132507132508132509132510132511132512132513132514132515132516132517132518132519132520132521132522132523132524132525132526132527132528132529132530132531132532132533132534132535132536132537132538132539132540132541132542132543132544132545132546132547132548132549132550132551132552132553132554132555132556132557132558132559132560132561132562132563132564132565132566132567132568132569132570132571132572132573132574132575132576132577132578132579132580132581132582132583132584132585132586132587132588132589132590132591132592132593132594132595132596132597132598132599132600132601132602132603132604132605132606132607132608132609132610132611132612132613132614132615132616132617132618132619132620132621132622132623132624132625132626132627132628132629132630132631132632132633132634132635132636132637132638132639132640132641132642132643132644132645132646132647132648132649132650132651132652132653132654132655132656132657132658132659132660132661132662132663132664132665132666132667132668132669132670132671132672132673132674132675132676132677132678132679132680132681132682132683132684132685132686132687132688132689132690132691132692132693132694132695132696132697132698132699132700132701132702132703132704132705132706132707132708132709132710132711132712132713132714132715132716132717132718132719132720132721132722132723132724132725132726132727132728132729132730132731132732132733132734132735132736132737132738132739132740132741132742132743132744132745132746132747132748132749132750132751132752132753132754132755132756132757132758132759132760132761132762132763132764132765132766132767132768132769132770132771132772132773132774132775132776132777132778132779132780132781132782132783132784132785132786132787132788132789132790132791132792132793132794132795132796132797132798132799132800132801132802132803132804132805132806132807132808132809132810132811132812132813132814132815132816132817132818132819132820132821132822132823132824132825132826132827132828132829132830132831132832132833132834132835132836132837132838132839132840132841132842132843132844132845132846132847132848132849132850132851132852132853132854132855132856132857132858132859132860132861132862132863132864132865132866132867132868132869132870132871132872132873132874132875132876132877132878132879132880132881132882132883132884132885132886132887132888132889132890132891132892132893132894132895132896132897132898132899132900132901132902132903132904132905132906132907132908132909132910132911132912132913132914132915132916132917132918132919132920132921132922132923132924132925132926132927132928132929132930132931132932132933132934132935132936132937132938132939132940132941132942132943132944132945132946132947132948132949132950132951132952132953132954132955132956132957132958132959132960132961132962132963132964132965132966132967132968132969132970132971132972132973132974132975132976132977132978132979132980132981132982132983132984132985132986132987132988132989132990132991132992132993132994132995132996132997132998132999133000133001133002133003133004133005133006133007133008133009133010133011133012133013133014133015133016133017133018133019133020133021133022133023133024133025133026133027133028133029133030133031133032133033133034133035133036133037133038133039133040133041133042133043133044133045133046133047133048133049133050133051133052133053133054133055133056133057133058133059133060133061133062133063133064133065133066133067133068133069133070133071133072133073133074133075133076133077133078133079133080133081133082133083133084133085133086133087133088133089133090133091133092133093133094133095133096133097133098133099133100133101133102133103133104133105133106133107133108133109133110133111133112133113133114133115133116133117133118133119133120133121133122133123133124133125133126133127133128133129133130133131133132133133133134133135133136133137133138133139133140133141133142133143133144133145133146133147133148133149133150133151133152133153133154133155133156133157133158133159133160133161133162133163133164133165133166133167133168133169133170133171133172133173133174133175133176133177133178133179133180133181133182133183133184133185133186133187133188133189133190133191133192133193133194133195133196133197133198133199133200133201133202133203133204133205133206133207133208133209133210133211133212133213133214133215133216133217133218133219133220133221133222133223133224133225133226133227133228133229133230133231133232133233133234133235133236133237133238133239133240133241133242133243133244133245133246133247133248133249133250133251133252133253133254133255133256133257133258133259133260133261133262133263133264133265133266133267133268133269133270133271133272133273133274133275133276133277133278133279133280133281133282133283133284133285133286133287133288133289133290133291133292133293133294133295133296133297133298133299133300133301133302133303133304133305133306133307133308133309133310133311133312133313133314133315133316133317133318133319133320133321133322133323133324133325133326133327133328133329133330133331133332133333133334133335133336133337133338133339133340133341133342133343133344133345133346133347133348133349133350133351133352133353133354133355133356133357133358133359133360133361133362133363133364133365133366133367133368133369133370133371133372133373133374133375133376133377133378133379133380133381133382133383133384133385133386133387133388133389133390133391133392133393133394133395133396133397133398133399133400133401133402133403133404133405133406133407133408133409133410133411133412133413133414133415133416133417133418133419133420133421133422133423133424133425133426133427133428133429133430133431133432133433133434133435133436133437133438133439133440133441133442133443133444133445133446133447133448133449133450133451133452133453133454133455133456133457133458133459133460133461133462133463133464133465133466133467133468133469133470133471133472133473133474133475133476133477133478133479133480133481133482133483133484133485133486133487133488133489133490133491133492133493133494133495133496133497133498133499133500133501133502133503133504133505133506133507133508133509133510133511133512133513133514133515133516133517133518133519133520133521133522133523133524133525133526133527133528133529133530133531133532133533133534133535133536133537133538133539133540133541133542133543133544133545133546133547133548133549133550133551133552133553133554133555133556133557133558133559133560133561133562133563133564133565133566133567133568133569133570133571133572133573133574133575133576133577133578133579133580133581133582133583133584133585133586133587133588133589133590133591133592133593133594133595133596133597133598133599133600133601133602133603133604133605133606133607133608133609133610133611133612133613133614133615133616133617133618133619133620133621133622133623133624133625133626133627133628133629133630133631133632133633133634133635133636133637133638133639133640133641133642133643133644133645133646133647133648133649133650133651133652133653133654133655133656133657133658133659133660133661133662133663133664133665133666133667133668133669133670133671133672133673133674133675133676133677133678133679133680133681133682133683133684133685133686133687133688133689133690133691133692133693133694133695133696133697133698133699133700133701133702133703133704133705133706133707133708133709133710133711133712133713133714133715133716133717133718133719133720133721133722133723133724133725133726133727133728133729133730133731133732133733133734133735133736133737133738133739133740133741133742133743133744133745133746133747133748133749133750133751133752133753133754133755133756133757133758133759133760133761133762133763133764133765133766133767133768133769133770133771133772133773133774133775133776133777133778133779133780133781133782133783133784133785133786133787133788133789133790133791133792133793133794133795133796133797133798133799133800133801133802133803133804133805133806133807133808133809133810133811133812133813133814133815133816133817133818133819133820133821133822133823133824133825133826133827133828133829133830133831133832133833133834133835133836133837133838133839133840133841133842133843133844133845133846133847133848133849133850133851133852133853133854133855133856133857133858133859133860133861133862133863133864133865133866133867133868133869133870133871133872133873133874133875133876133877133878133879133880133881133882133883133884133885133886133887133888133889133890133891133892133893133894133895133896133897133898133899133900133901133902133903133904133905133906133907133908133909133910133911133912133913133914133915133916133917133918133919133920133921133922133923133924133925133926133927133928133929133930133931133932133933133934133935133936133937133938133939133940133941133942133943133944133945133946133947133948133949133950133951133952133953133954133955133956133957133958133959133960133961133962133963133964133965133966133967133968133969133970133971133972133973133974133975133976133977133978133979133980133981133982133983133984133985133986133987133988133989133990133991133992133993133994133995133996133997133998133999134000134001134002134003134004134005134006134007134008134009134010134011134012134013134014134015134016134017134018134019134020134021134022134023134024134025134026134027134028134029134030134031134032134033134034134035134036134037134038134039134040134041134042134043134044134045134046134047134048134049134050134051134052134053134054134055134056134057134058134059134060134061134062134063134064134065134066134067134068134069134070134071134072134073134074134075134076134077134078134079134080134081134082134083134084134085134086134087134088134089134090134091134092134093134094134095134096134097134098134099134100134101134102134103134104134105134106134107134108134109134110134111134112134113134114134115134116134117134118134119134120134121134122134123134124134125134126134127134128134129134130134131134132134133134134134135134136134137134138134139134140134141134142134143134144134145134146134147134148134149134150134151134152134153134154134155134156134157134158134159134160134161134162134163134164134165134166134167134168134169134170134171134172134173134174134175134176134177134178134179134180134181134182134183134184134185134186134187134188134189134190134191134192134193134194134195134196134197134198134199134200134201134202134203134204134205134206134207134208134209134210134211134212134213134214134215134216134217134218134219134220134221134222134223134224134225134226134227134228134229134230134231134232134233134234134235134236134237134238134239134240134241134242134243134244134245134246134247134248134249134250134251134252134253134254134255134256134257134258134259134260134261134262134263134264134265134266134267134268134269134270134271134272134273134274134275134276134277134278134279134280134281134282134283134284134285134286134287134288134289134290134291134292134293134294134295134296134297134298134299134300134301134302134303134304134305134306134307134308134309134310134311134312134313134314134315134316134317134318134319134320134321134322134323134324134325134326134327134328134329134330134331134332134333134334134335134336134337134338134339134340134341134342134343134344134345134346134347134348134349134350134351134352134353134354134355134356134357134358134359134360134361134362134363134364134365134366134367134368134369134370134371134372134373134374134375134376134377134378134379134380134381134382134383134384134385134386134387134388134389134390134391134392134393134394134395134396134397134398134399134400134401134402134403134404134405134406134407134408134409134410134411134412134413134414134415134416134417134418134419134420134421134422134423134424134425134426134427134428134429134430134431134432134433134434134435134436134437134438134439134440134441134442134443134444134445134446134447134448134449134450134451134452134453134454134455134456134457134458134459134460134461134462134463134464134465134466134467134468134469134470134471134472134473134474134475134476134477134478134479134480134481134482134483134484134485134486134487134488134489134490134491134492134493134494134495134496134497134498134499134500134501134502134503134504134505134506134507134508134509134510134511134512134513134514134515134516134517134518134519134520134521134522134523134524134525134526134527134528134529134530134531134532134533134534134535134536134537134538134539134540134541134542134543134544134545134546134547134548134549134550134551134552134553134554134555134556134557134558134559134560134561134562134563134564134565134566134567134568134569134570134571134572134573134574134575134576134577134578134579134580134581134582134583134584134585134586134587134588134589134590134591134592134593134594134595134596134597134598134599134600134601134602134603134604134605134606134607134608134609134610134611134612134613134614134615134616134617134618134619134620134621134622134623134624134625134626134627134628134629134630134631134632134633134634134635134636134637134638134639134640134641134642134643134644134645134646134647134648134649134650134651134652134653134654134655134656134657134658134659134660134661134662134663134664134665134666134667134668134669134670134671134672134673134674134675134676134677134678134679134680134681134682134683134684134685134686134687134688134689134690134691134692134693134694134695134696134697134698134699134700134701134702134703134704134705134706134707134708134709134710134711134712134713134714134715134716134717134718134719134720134721134722134723134724134725134726134727134728134729134730134731134732134733134734134735134736134737134738134739134740134741134742134743134744134745134746134747134748134749134750134751134752134753134754134755134756134757134758134759134760134761134762134763134764134765134766134767134768134769134770134771134772134773134774134775134776134777134778134779134780134781134782134783134784134785134786134787134788134789134790134791134792134793134794134795134796134797134798134799134800134801134802134803134804134805134806134807134808134809134810134811134812134813134814134815134816134817134818134819134820134821134822134823134824134825134826134827134828134829134830134831134832134833134834134835134836134837134838134839134840134841134842134843134844134845134846134847134848134849134850134851134852134853134854134855134856134857134858134859134860134861134862134863134864134865134866134867134868134869134870134871134872134873134874134875134876134877134878134879134880134881134882134883134884134885134886134887134888134889134890134891134892134893134894134895134896134897134898134899134900134901134902134903134904134905134906134907134908134909134910134911134912134913134914134915134916134917134918134919134920134921134922134923134924134925134926134927134928134929134930134931134932134933134934134935134936134937134938134939134940134941134942134943134944134945134946134947134948134949134950134951134952134953134954134955134956134957134958134959134960134961134962134963134964134965134966134967134968134969134970134971134972134973134974134975134976134977134978134979134980134981134982134983134984134985134986134987134988134989134990134991134992134993134994134995134996134997134998134999135000135001135002135003135004135005135006135007135008135009135010135011135012135013135014135015135016135017135018135019135020135021135022135023135024135025135026135027135028135029135030135031135032135033135034135035135036135037135038135039135040135041135042135043135044135045135046135047135048135049135050135051135052135053135054135055135056135057135058135059135060135061135062135063135064135065135066135067135068135069135070135071135072135073135074135075135076135077135078135079135080135081135082135083135084135085135086135087135088135089135090135091135092135093135094135095135096135097135098135099135100135101135102135103135104135105135106135107135108135109135110135111135112135113135114135115135116135117135118135119135120135121135122135123135124135125135126135127135128135129135130135131135132135133135134135135135136135137135138135139135140135141135142135143135144135145135146135147135148135149135150135151135152135153135154135155135156135157135158135159135160135161135162135163135164135165135166135167135168135169135170135171135172135173135174135175135176135177135178135179135180135181135182135183135184135185135186135187135188135189135190135191135192135193135194135195135196135197135198135199135200135201135202135203135204135205135206135207135208135209135210135211135212135213135214135215135216135217135218135219135220135221135222135223135224135225135226135227135228135229135230135231135232135233135234135235135236135237135238135239135240135241135242135243135244135245135246135247135248135249135250135251135252135253135254135255135256135257135258135259135260135261135262135263135264135265135266135267135268135269135270135271135272135273135274135275135276135277135278135279135280135281135282135283135284135285135286135287135288135289135290135291135292135293135294135295135296135297135298135299135300135301135302135303135304135305135306135307135308135309135310135311135312135313135314135315135316135317135318135319135320135321135322135323135324135325135326135327135328135329135330135331135332135333135334135335135336135337135338135339135340135341135342135343135344135345135346135347135348135349135350135351135352135353135354135355135356135357135358135359135360135361135362135363135364135365135366135367135368135369135370135371135372135373135374135375135376135377135378135379135380135381135382135383135384135385135386135387135388135389135390135391135392135393135394135395135396135397135398135399135400135401135402135403135404135405135406135407135408135409135410135411135412135413135414135415135416135417135418135419135420135421135422135423135424135425135426135427135428135429135430135431135432135433135434135435135436135437135438135439135440135441135442135443135444135445135446135447135448135449135450135451135452135453135454135455135456135457135458135459135460135461135462135463135464135465135466135467135468135469135470135471135472135473135474135475135476135477135478135479135480135481135482135483135484135485135486135487135488135489135490135491135492135493135494135495135496135497135498135499135500135501135502135503135504135505135506135507135508135509135510135511135512135513135514135515135516135517135518135519135520135521135522135523135524135525135526135527135528135529135530135531135532135533135534135535135536135537135538135539135540135541135542135543135544135545135546135547135548135549135550135551135552135553135554135555135556135557135558135559135560135561135562135563135564135565135566135567135568135569135570135571135572135573135574135575135576135577135578135579135580135581135582135583135584135585135586135587135588135589135590135591135592135593135594135595135596135597135598135599135600135601135602135603135604135605135606135607135608135609135610135611135612135613135614135615135616135617135618135619135620135621135622135623135624135625135626135627135628135629135630135631135632135633135634135635135636135637135638135639135640135641135642135643135644135645135646135647135648135649135650135651135652135653135654135655135656135657135658135659135660135661135662135663135664135665135666135667135668135669135670135671135672135673135674135675135676135677135678135679135680135681135682135683135684135685135686135687135688135689135690135691135692135693135694135695135696135697135698135699135700135701135702135703135704135705135706135707135708135709135710135711135712135713135714135715135716135717135718135719135720135721135722135723135724135725135726135727135728135729135730135731135732135733135734135735135736135737135738135739135740135741135742135743135744135745135746135747135748135749135750135751135752135753135754135755135756135757135758135759135760135761135762135763135764135765135766135767135768135769135770135771135772135773135774135775135776135777135778135779135780135781135782135783135784135785135786135787135788135789135790135791135792135793135794135795135796135797135798135799135800135801135802135803135804135805135806135807135808135809135810135811135812135813135814135815135816135817135818135819135820135821135822135823135824135825135826135827135828135829135830135831135832135833135834135835135836135837135838135839135840135841135842135843135844135845135846135847135848135849135850135851135852135853135854135855135856135857135858135859135860135861135862135863135864135865135866135867135868135869135870135871135872135873135874135875135876135877135878135879135880135881135882135883135884135885135886135887135888135889135890135891135892135893135894135895135896135897135898135899135900135901135902135903135904135905135906135907135908135909135910135911135912135913135914135915135916135917135918135919135920135921135922135923135924135925135926135927135928135929135930135931135932135933135934135935135936135937135938135939135940135941135942135943135944135945135946135947135948135949135950135951135952135953135954135955135956135957135958135959135960135961135962135963135964135965135966135967135968135969135970135971135972135973135974135975135976135977135978135979135980135981135982135983135984135985135986135987135988135989135990135991135992135993135994135995135996135997135998135999136000136001136002136003136004136005136006136007136008136009136010136011136012136013136014136015136016136017136018136019136020136021136022136023136024136025136026136027136028136029136030136031136032136033136034136035136036136037136038136039136040136041136042136043136044136045136046136047136048136049136050136051136052136053136054136055136056136057136058136059136060136061136062136063136064136065136066136067136068136069136070136071136072136073136074136075136076136077136078136079136080136081136082136083136084136085136086136087136088136089136090136091136092136093136094136095136096136097136098136099136100136101136102136103136104136105136106136107136108136109136110136111136112136113136114136115136116136117136118136119136120136121136122136123136124136125136126136127136128136129136130136131136132136133136134136135136136136137136138136139136140136141136142136143136144136145136146136147136148136149136150136151136152136153136154136155136156136157136158136159136160136161136162136163136164136165136166136167136168136169136170136171136172136173136174136175136176136177136178136179136180136181136182136183136184136185136186136187136188136189136190136191136192136193136194136195136196136197136198136199136200136201136202136203136204136205136206136207136208136209136210136211136212136213136214136215136216136217136218136219136220136221136222136223136224136225136226136227136228136229136230136231136232136233136234136235136236136237136238136239136240136241136242136243136244136245136246136247136248136249136250136251136252136253136254136255136256136257136258136259136260136261136262136263136264136265136266136267136268136269136270136271136272136273136274136275136276136277136278136279136280136281136282136283136284136285136286136287136288136289136290136291136292136293136294136295136296136297136298136299136300136301136302136303136304136305136306136307136308136309136310136311136312136313136314136315136316136317136318136319136320136321136322136323136324136325136326136327136328136329136330136331136332136333136334136335136336136337136338136339136340136341136342136343136344136345136346136347136348136349136350136351136352136353136354136355136356136357136358136359136360136361136362136363136364136365136366136367136368136369136370136371136372136373136374136375136376136377136378136379136380136381136382136383136384136385136386136387136388136389136390136391136392136393136394136395136396136397136398136399136400136401136402136403136404136405136406136407136408136409136410136411136412136413136414136415136416136417136418136419136420136421136422136423136424136425136426136427136428136429136430136431136432136433136434136435136436136437136438136439136440136441136442136443136444136445136446136447136448136449136450136451136452136453136454136455136456136457136458136459136460136461136462136463136464136465136466136467136468136469136470136471136472136473136474136475136476136477136478136479136480136481136482136483136484136485136486136487136488136489136490136491136492136493136494136495136496136497136498136499136500136501136502136503136504136505136506136507136508136509136510136511136512136513136514136515136516136517136518136519136520136521136522136523136524136525136526136527136528136529136530136531136532136533136534136535136536136537136538136539136540136541136542136543136544136545136546136547136548136549136550136551136552136553136554136555136556136557136558136559136560136561136562136563136564136565136566136567136568136569136570136571136572136573136574136575136576136577136578136579136580136581136582136583136584136585136586136587136588136589136590136591136592136593136594136595136596136597136598136599136600136601136602136603136604136605136606136607136608136609136610136611136612136613136614136615136616136617136618136619136620136621136622136623136624136625136626136627136628136629136630136631136632136633136634136635136636136637136638136639136640136641136642136643136644136645136646136647136648136649136650136651136652136653136654136655136656136657136658136659136660136661136662136663136664136665136666136667136668136669136670136671136672136673136674136675136676136677136678136679136680136681136682136683136684136685136686136687136688136689136690136691136692136693136694136695136696136697136698136699136700136701136702136703136704136705136706136707136708136709136710136711136712136713136714136715136716136717136718136719136720136721136722136723136724136725136726136727136728136729136730136731136732136733136734136735136736136737136738136739136740136741136742136743136744136745136746136747136748136749136750136751136752136753136754136755136756136757136758136759136760136761136762136763136764136765136766136767136768136769136770136771136772136773136774136775136776136777136778136779136780136781136782136783136784136785136786136787136788136789136790136791136792136793136794136795136796136797136798136799136800136801136802136803136804136805136806136807136808136809136810136811136812136813136814136815136816136817136818136819136820136821136822136823136824136825136826136827136828136829136830136831136832136833136834136835136836136837136838136839136840136841136842136843136844136845136846136847136848136849136850136851136852136853136854136855136856136857136858136859136860136861136862136863136864136865136866136867136868136869136870136871136872136873136874136875136876136877136878136879136880136881136882136883136884136885136886136887136888136889136890136891136892136893136894136895136896136897136898136899136900136901136902136903136904136905136906136907136908136909136910136911136912136913136914136915136916136917136918136919136920136921136922136923136924136925136926136927136928136929136930136931136932136933136934136935136936136937136938136939136940136941136942136943136944136945136946136947136948136949136950136951136952136953136954136955136956136957136958136959136960136961136962136963136964136965136966136967136968136969136970136971136972136973136974136975136976136977136978136979136980136981136982136983136984136985136986136987136988136989136990136991136992136993136994136995136996136997136998136999137000137001137002137003137004137005137006137007137008137009137010137011137012137013137014137015137016137017137018137019137020137021137022137023137024137025137026137027137028137029137030137031137032137033137034137035137036137037137038137039137040137041137042137043137044137045137046137047137048137049137050137051137052137053137054137055137056137057137058137059137060137061137062137063137064137065137066137067137068137069137070137071137072137073137074137075137076137077137078137079137080137081137082137083137084137085137086137087137088137089137090137091137092137093137094137095137096137097137098137099137100137101137102137103137104137105137106137107137108137109137110137111137112137113137114137115137116137117137118137119137120137121137122137123137124137125137126137127137128137129137130137131137132137133137134137135137136137137137138137139137140137141137142137143137144137145137146137147137148137149137150137151137152137153137154137155137156137157137158137159137160137161137162137163137164137165137166137167137168137169137170137171137172137173137174137175137176137177137178137179137180137181137182137183137184137185137186137187137188137189137190137191137192137193137194137195137196137197137198137199137200137201137202137203137204137205137206137207137208137209137210137211137212137213137214137215137216137217137218137219137220137221137222137223137224137225137226137227137228137229137230137231137232137233137234137235137236137237137238137239137240137241137242137243137244137245137246137247137248137249137250137251137252137253137254137255137256137257137258137259137260137261137262137263137264137265137266137267137268137269137270137271137272137273137274137275137276137277137278137279137280137281137282137283137284137285137286137287137288137289137290137291137292137293137294137295137296137297137298137299137300137301137302137303137304137305137306137307137308137309137310137311137312137313137314137315137316137317137318137319137320137321137322137323137324137325137326137327137328137329137330137331137332137333137334137335137336137337137338137339137340137341137342137343137344137345137346137347137348137349137350137351137352137353137354137355137356137357137358137359137360137361137362137363137364137365137366137367137368137369137370137371137372137373137374137375137376137377137378137379137380137381137382137383137384137385137386137387137388137389137390137391137392137393137394137395137396137397137398137399137400137401137402137403137404137405137406137407137408137409137410137411137412137413137414137415137416137417137418137419137420137421137422137423137424137425137426137427137428137429137430137431137432137433137434137435137436137437137438137439137440137441137442137443137444137445137446137447137448137449137450137451137452137453137454137455137456137457137458137459137460137461137462137463137464137465137466137467137468137469137470137471137472137473137474137475137476137477137478137479137480137481137482137483137484137485137486137487137488137489137490137491137492137493137494137495137496137497137498137499137500137501137502137503137504137505137506137507137508137509137510137511137512137513137514137515137516137517137518137519137520137521137522137523137524137525137526137527137528137529137530137531137532137533137534137535137536137537137538137539137540137541137542137543137544137545137546137547137548137549137550137551137552137553137554137555137556137557137558137559137560137561137562137563137564137565137566137567137568137569137570137571137572137573137574137575137576137577137578137579137580137581137582137583137584137585137586137587137588137589137590137591137592137593137594137595137596137597137598137599137600137601137602137603137604137605137606137607137608137609137610137611137612137613137614137615137616137617137618137619137620137621137622137623137624137625137626137627137628137629137630137631137632137633137634137635137636137637137638137639137640137641137642137643137644137645137646137647137648137649137650137651137652137653137654137655137656137657137658137659137660137661137662137663137664137665137666137667137668137669137670137671137672137673137674137675137676137677137678137679137680137681137682137683137684137685137686137687137688137689137690137691137692137693137694137695137696137697137698137699137700137701137702137703137704137705137706137707137708137709137710137711137712137713137714137715137716137717137718137719137720137721137722137723137724137725137726137727137728137729137730137731137732137733137734137735137736137737137738137739137740137741137742137743137744137745137746137747137748137749137750137751137752137753137754137755137756137757137758137759137760137761137762137763137764137765137766137767137768137769137770137771137772137773137774137775137776137777137778137779137780137781137782137783137784137785137786137787137788137789137790137791137792137793137794137795137796137797137798137799137800137801137802137803137804137805137806137807137808137809137810137811137812137813137814137815137816137817137818137819137820137821137822137823137824137825137826137827137828137829137830137831137832137833137834137835137836137837137838137839137840137841137842137843137844137845137846137847137848137849137850137851137852137853137854137855137856137857137858137859137860137861137862137863137864137865137866137867137868137869137870137871137872137873137874137875137876137877137878137879137880137881137882137883137884137885137886137887137888137889137890137891137892137893137894137895137896137897137898137899137900137901137902137903137904137905137906137907137908137909137910137911137912137913137914137915137916137917137918137919137920137921137922137923137924137925137926137927137928137929137930137931137932137933137934137935137936137937137938137939137940137941137942137943137944137945137946137947137948137949137950137951137952137953137954137955137956137957137958137959137960137961137962137963137964137965137966137967137968137969137970137971137972137973137974137975137976137977137978137979137980137981137982137983137984137985137986137987137988137989137990137991137992137993137994137995137996137997137998137999138000138001138002138003138004138005138006138007138008138009138010138011138012138013138014138015138016138017138018138019138020138021138022138023138024138025138026138027138028138029138030138031138032138033138034138035138036138037138038138039138040138041138042138043138044138045138046138047138048138049138050138051138052138053138054138055138056138057138058138059138060138061138062138063138064138065138066138067138068138069138070138071138072138073138074138075138076138077138078138079138080138081138082138083138084138085138086138087138088138089138090138091138092138093138094138095138096138097138098138099138100138101138102138103138104138105138106138107138108138109138110138111138112138113138114138115138116138117138118138119138120138121138122138123138124138125138126138127138128138129138130138131138132138133138134138135138136138137138138138139138140138141138142138143138144138145138146138147138148138149138150138151138152138153138154138155138156138157138158138159138160138161138162138163138164138165138166138167138168138169138170138171138172138173138174138175138176138177138178138179138180138181138182138183138184138185138186138187138188138189138190138191138192138193138194138195138196138197138198138199138200138201138202138203138204138205138206138207138208138209138210138211138212138213138214138215138216138217138218138219138220138221138222138223138224138225138226138227138228138229138230138231138232138233138234138235138236138237138238138239138240138241138242138243138244138245138246138247138248138249138250138251138252138253138254138255138256138257138258138259138260138261138262138263138264138265138266138267138268138269138270138271138272138273138274138275138276138277138278138279138280138281138282138283138284138285138286138287138288138289138290138291138292138293138294138295138296138297138298138299138300138301138302138303138304138305138306138307138308138309138310138311138312138313138314138315138316138317138318138319138320138321138322138323138324138325138326138327138328138329138330138331138332138333138334138335138336138337138338138339138340138341138342138343138344138345138346138347138348138349138350138351138352138353138354138355138356138357138358138359138360138361138362138363138364138365138366138367138368138369138370138371138372138373138374138375138376138377138378138379138380138381138382138383138384138385138386138387138388138389138390138391138392138393138394138395138396138397138398138399138400138401138402138403138404138405138406138407138408138409138410138411138412138413138414138415138416138417138418138419138420138421138422138423138424138425138426138427138428138429138430138431138432138433138434138435138436138437138438138439138440138441138442138443138444138445138446138447138448138449138450138451138452138453138454138455138456138457138458138459138460138461138462138463138464138465138466138467138468138469138470138471138472138473138474138475138476138477138478138479138480138481138482138483138484138485138486138487138488138489138490138491138492138493138494138495138496138497138498138499138500138501138502138503138504138505138506138507138508138509138510138511138512138513138514138515138516138517138518138519138520138521138522138523138524138525138526138527138528138529138530138531138532138533138534138535138536138537138538138539138540138541138542138543138544138545138546138547138548138549138550138551138552138553138554138555138556138557138558138559138560138561138562138563138564138565138566138567138568138569138570138571138572138573138574138575138576138577138578138579138580138581138582138583138584138585138586138587138588138589138590138591138592138593138594138595138596138597138598138599138600138601138602138603138604138605138606138607138608138609138610138611138612138613138614138615138616138617138618138619138620138621138622138623138624138625138626138627138628138629138630138631138632138633138634138635138636138637138638138639138640138641138642138643138644138645138646138647138648138649138650138651138652138653138654138655138656138657138658138659138660138661138662138663138664138665138666138667138668138669138670138671138672138673138674138675138676138677138678138679138680138681138682138683138684138685138686138687138688138689138690138691138692138693138694138695138696138697138698138699138700138701138702138703138704138705138706138707138708138709138710138711138712138713138714138715138716138717138718138719138720138721138722138723138724138725138726138727138728138729138730138731138732138733138734138735138736138737138738138739138740138741138742138743138744138745138746138747138748138749138750138751138752138753138754138755138756138757138758138759138760138761138762138763138764138765138766138767138768138769138770138771138772138773138774138775138776138777138778138779138780138781138782138783138784138785138786138787138788138789138790138791138792138793138794138795138796138797138798138799138800138801138802138803138804138805138806138807138808138809138810138811138812138813138814138815138816138817138818138819138820138821138822138823138824138825138826138827138828138829138830138831138832138833138834138835138836138837138838138839138840138841138842138843138844138845138846138847138848138849138850138851138852138853138854138855138856138857138858138859138860138861138862138863138864138865138866138867138868138869138870138871138872138873138874138875138876138877138878138879138880138881138882138883138884138885138886138887138888138889138890138891138892138893138894138895138896138897138898138899138900138901138902138903138904138905138906138907138908138909138910138911138912138913138914138915138916138917138918138919138920138921138922138923138924138925138926138927138928138929138930138931138932138933138934138935138936138937138938138939138940138941138942138943138944138945138946138947138948138949138950138951138952138953138954138955138956138957138958138959138960138961138962138963138964138965138966138967138968138969138970138971138972138973138974138975138976138977138978138979138980138981138982138983138984138985138986138987138988138989138990138991138992138993138994138995138996138997138998138999139000139001139002139003139004139005139006139007139008139009139010139011139012139013139014139015139016139017139018139019139020139021139022139023139024139025139026139027139028139029139030139031139032139033139034139035139036139037139038139039139040139041139042139043139044139045139046139047139048139049139050139051139052139053139054139055139056139057139058139059139060139061139062139063139064139065139066139067139068139069139070139071139072139073139074139075139076139077139078139079139080139081139082139083139084139085139086139087139088139089139090139091139092139093139094139095139096139097139098139099139100139101139102139103139104139105139106139107139108139109139110139111139112139113139114139115139116139117139118139119139120139121139122139123139124139125139126139127139128139129139130139131139132139133139134139135139136139137139138139139139140139141139142139143139144139145139146139147139148139149139150139151139152139153139154139155139156139157139158139159139160139161139162139163139164139165139166139167139168139169139170139171139172139173139174139175139176139177139178139179139180139181139182139183139184139185139186139187139188139189139190139191139192139193139194139195139196139197139198139199139200139201139202139203139204139205139206139207139208139209139210139211139212139213139214139215139216139217139218139219139220139221139222139223139224139225139226139227139228139229139230139231139232139233139234139235139236139237139238139239139240139241139242139243139244139245139246139247139248139249139250139251139252139253139254139255139256139257139258139259139260139261139262139263139264139265139266139267139268139269139270139271139272139273139274139275139276139277139278139279139280139281139282139283139284139285139286139287139288139289139290139291139292139293139294139295139296139297139298139299139300139301139302139303139304139305139306139307139308139309139310139311139312139313139314139315139316139317139318139319139320139321139322139323139324139325139326139327139328139329139330139331139332139333139334139335139336139337139338139339139340139341139342139343139344139345139346139347139348139349139350139351139352139353139354139355139356139357139358139359139360139361139362139363139364139365139366139367139368139369139370139371139372139373139374139375139376139377139378139379139380139381139382139383139384139385139386139387139388139389139390139391139392139393139394139395139396139397139398139399139400139401139402139403139404139405139406139407139408139409139410139411139412139413139414139415139416139417139418139419139420139421139422139423139424139425139426139427139428139429139430139431139432139433139434139435139436139437139438139439139440139441139442139443139444139445139446139447139448139449139450139451139452139453139454139455139456139457139458139459139460139461139462139463139464139465139466139467139468139469139470139471139472139473139474139475139476139477139478139479139480139481139482139483139484139485139486139487139488139489139490139491139492139493139494139495139496139497139498139499139500139501139502139503139504139505139506139507139508139509139510139511139512139513139514139515139516139517139518139519139520139521139522139523139524139525139526139527139528139529139530139531139532139533139534139535139536139537139538139539139540139541139542139543139544139545139546139547139548139549139550139551139552139553139554139555139556139557139558139559139560139561139562139563139564139565139566139567139568139569139570139571139572139573139574139575139576139577139578139579139580139581139582139583139584139585139586139587139588139589139590139591139592139593139594139595139596139597139598139599139600139601139602139603139604139605139606139607139608139609139610139611139612139613139614139615139616139617139618139619139620139621139622139623139624139625139626139627139628139629139630139631139632139633139634139635139636139637139638139639139640139641139642139643139644139645139646139647139648139649139650139651139652139653139654139655139656139657139658139659139660139661139662139663139664139665139666139667139668139669139670139671139672139673139674139675139676139677139678139679139680139681139682139683139684139685139686139687139688139689139690139691139692139693139694139695139696139697139698139699139700139701139702139703139704139705139706139707139708139709139710139711139712139713139714139715139716139717139718139719139720139721139722139723139724139725139726139727139728139729139730139731139732139733139734139735139736139737139738139739139740139741139742139743139744139745139746139747139748139749139750139751139752139753139754139755139756139757139758139759139760139761139762139763139764139765139766139767139768139769139770139771139772139773139774139775139776139777139778139779139780139781139782139783139784139785139786139787139788139789139790139791139792139793139794139795139796139797139798139799139800139801139802139803139804139805139806139807139808139809139810139811139812139813139814139815139816139817139818139819139820139821139822139823139824139825139826139827139828139829139830139831139832139833139834139835139836139837139838139839139840139841139842139843139844139845139846139847139848139849139850139851139852139853139854139855139856139857139858139859139860139861139862139863139864139865139866139867139868139869139870139871139872139873139874139875139876139877139878139879139880139881139882139883139884139885139886139887139888139889139890139891139892139893139894139895139896139897139898139899139900139901139902139903139904139905139906139907139908139909139910139911139912139913139914139915139916139917139918139919139920139921139922139923139924139925139926139927139928139929139930139931139932139933139934139935139936139937139938139939139940139941139942139943139944139945139946139947139948139949139950139951139952139953139954139955139956139957139958139959139960139961139962139963139964139965139966139967139968139969139970139971139972139973139974139975139976139977139978139979139980139981139982139983139984139985139986139987139988139989139990139991139992139993139994139995139996139997139998139999140000140001140002140003140004140005140006140007140008140009140010140011140012140013140014140015140016140017140018140019140020140021140022140023140024140025140026140027140028140029140030140031140032140033140034140035140036140037140038140039140040140041140042140043140044140045140046140047140048140049140050140051140052140053140054140055140056140057140058140059140060140061140062140063140064140065140066140067140068140069140070140071140072140073140074140075140076140077140078140079140080140081140082140083140084140085140086140087140088140089140090140091140092140093140094140095140096140097140098140099140100140101140102140103140104140105140106140107140108140109140110140111140112140113140114140115140116140117140118140119140120140121140122140123140124140125140126140127140128140129140130140131140132140133140134140135140136140137140138140139140140140141140142140143140144140145140146140147140148140149140150140151140152140153140154140155140156140157140158140159140160140161140162140163140164140165140166140167140168140169140170140171140172140173140174140175140176140177140178140179140180140181140182140183140184140185140186140187140188140189140190140191140192140193140194140195140196140197140198140199140200140201140202140203140204140205140206140207140208140209140210140211140212140213140214140215140216140217140218140219140220140221140222140223140224140225140226140227140228140229140230140231140232140233140234140235140236140237140238140239140240140241140242140243140244140245140246140247140248140249140250140251140252140253140254140255140256140257140258140259140260140261140262140263140264140265140266140267140268140269140270140271140272140273140274140275140276140277140278140279140280140281140282140283140284140285140286140287140288140289140290140291140292140293140294140295140296140297140298140299140300140301140302140303140304140305140306140307140308140309140310140311140312140313140314140315140316140317140318140319140320140321140322140323140324140325140326140327140328140329140330140331140332140333140334140335140336140337140338140339140340140341140342140343140344140345140346140347140348140349140350140351140352140353140354140355140356140357140358140359140360140361140362140363140364140365140366140367140368140369140370140371140372140373140374140375140376140377140378140379140380140381140382140383140384140385140386140387140388140389140390140391140392140393140394140395140396140397140398140399140400140401140402140403140404140405140406140407140408140409140410140411140412140413140414140415140416140417140418140419140420140421140422140423140424140425140426140427140428140429140430140431140432140433140434140435140436140437140438140439140440140441140442140443140444140445140446140447140448140449140450140451140452140453140454140455140456140457140458140459140460140461140462140463140464140465140466140467140468140469140470140471140472140473140474140475140476140477140478140479140480140481140482140483140484140485140486140487140488140489140490140491140492140493140494140495140496140497140498140499140500140501140502140503140504140505140506140507140508140509140510140511140512140513140514140515140516140517140518140519140520140521140522140523140524140525140526140527140528140529140530140531140532140533140534140535140536140537140538140539140540140541140542140543140544140545140546140547140548140549140550140551140552140553140554140555140556140557140558140559140560140561140562140563140564140565140566140567140568140569140570140571140572140573140574140575140576140577140578140579140580140581140582140583140584140585140586140587140588140589140590140591140592140593140594140595140596140597140598140599140600140601140602140603140604140605140606140607140608140609140610140611140612140613140614140615140616140617140618140619140620140621140622140623140624140625140626140627140628140629140630140631140632140633140634140635140636140637140638140639140640140641140642140643140644140645140646140647140648140649140650140651140652140653140654140655140656140657140658140659140660140661140662140663140664140665140666140667140668140669140670140671140672140673140674140675140676140677140678140679140680140681140682140683140684140685140686140687140688140689140690140691140692140693140694140695140696140697140698140699140700140701140702140703140704140705140706140707140708140709140710140711140712140713140714140715140716140717140718140719140720140721140722140723140724140725140726140727140728140729140730140731140732140733140734140735140736140737140738140739140740140741140742140743140744140745140746140747140748140749140750140751140752140753140754140755140756140757140758140759140760140761140762140763140764140765140766140767140768140769140770140771140772140773140774140775140776140777140778140779140780140781140782140783140784140785140786140787140788140789140790140791140792140793140794140795140796140797140798140799140800140801140802140803140804140805140806140807140808140809140810140811140812140813140814140815140816140817140818140819140820140821140822140823140824140825140826140827140828140829140830140831140832140833140834140835140836140837140838140839140840140841140842140843140844140845140846140847140848140849140850140851140852140853140854140855140856140857140858140859140860140861140862140863140864140865140866140867140868140869140870140871140872140873140874140875140876140877140878140879140880140881140882140883140884140885140886140887140888140889140890140891140892140893140894140895140896140897140898140899140900140901140902140903140904140905140906140907140908140909140910140911140912140913140914140915140916140917140918140919140920140921140922140923140924140925140926140927140928140929140930140931140932140933140934140935140936140937140938140939140940140941140942140943140944140945140946140947140948140949140950140951140952140953140954140955140956140957140958140959140960140961140962140963140964140965140966140967140968140969140970140971140972140973140974140975140976140977140978140979140980140981140982140983140984140985140986140987140988140989140990140991140992140993140994140995140996140997140998140999141000141001141002141003141004141005141006141007141008141009141010141011141012141013141014141015141016141017141018141019141020141021141022141023141024141025141026141027141028141029141030141031141032141033141034141035141036141037141038141039141040141041141042141043141044141045141046141047141048141049141050141051141052141053141054141055141056141057141058141059141060141061141062141063141064141065141066141067141068141069141070141071141072141073141074141075141076141077141078141079141080141081141082141083141084141085141086141087141088141089141090141091141092141093141094141095141096141097141098141099141100141101141102141103141104141105141106141107141108141109141110141111141112141113141114141115141116141117141118141119141120141121141122141123141124141125141126141127141128141129141130141131141132141133141134141135141136141137141138141139141140141141141142141143141144141145141146141147141148141149141150141151141152141153141154141155141156141157141158141159141160141161141162141163141164141165141166141167141168141169141170141171141172141173141174141175141176141177141178141179141180141181141182141183141184141185141186141187141188141189141190141191141192141193141194141195141196141197141198141199141200141201141202141203141204141205141206141207141208141209141210141211141212141213141214141215141216141217141218141219141220141221141222141223141224141225141226141227141228141229141230141231141232141233141234141235141236141237141238141239141240141241141242141243141244141245141246141247141248141249141250141251141252141253141254141255141256141257141258141259141260141261141262141263141264141265141266141267141268141269141270141271141272141273141274141275141276141277141278141279141280141281141282141283141284141285141286141287141288141289141290141291141292141293141294141295141296141297141298141299141300141301141302141303141304141305141306141307141308141309141310141311141312141313141314141315141316141317141318141319141320141321141322141323141324141325141326141327141328141329141330141331141332141333141334141335141336141337141338141339141340141341141342141343141344141345141346141347141348141349141350141351141352141353141354141355141356141357141358141359141360141361141362141363141364141365141366141367141368141369141370141371141372141373141374141375141376141377141378141379141380141381141382141383141384141385141386141387141388141389141390141391141392141393141394141395141396141397141398141399141400141401141402141403141404141405141406141407141408141409141410141411141412141413141414141415141416141417141418141419141420141421141422141423141424141425141426141427141428141429141430141431141432141433141434141435141436141437141438141439141440141441141442141443141444141445141446141447141448141449141450141451141452141453141454141455141456141457141458141459141460141461141462141463141464141465141466141467141468141469141470141471141472141473141474141475141476141477141478141479141480141481141482141483141484141485141486141487141488141489141490141491141492141493141494141495141496141497141498141499141500141501141502141503141504141505141506141507141508141509141510141511141512141513141514141515141516141517141518141519141520141521141522141523141524141525141526141527141528141529141530141531141532141533141534141535141536141537141538141539141540141541141542141543141544141545141546141547141548141549141550141551141552141553141554141555141556141557141558141559141560141561141562141563141564141565141566141567141568141569141570141571141572141573141574141575141576141577141578141579141580141581141582141583141584141585141586141587141588141589141590141591141592141593141594141595141596141597141598141599141600141601141602141603141604141605141606141607141608141609141610141611141612141613141614141615141616141617141618141619141620141621141622141623141624141625141626141627141628141629141630141631141632141633141634141635141636141637141638141639141640141641141642141643141644141645141646141647141648141649141650141651141652141653141654141655141656141657141658141659141660141661141662141663141664141665141666141667141668141669141670141671141672141673141674141675141676141677141678141679141680141681141682141683141684141685141686141687141688141689141690141691141692141693141694141695141696141697141698141699141700141701141702141703141704141705141706141707141708141709141710141711141712141713141714141715141716141717141718141719141720141721141722141723141724141725141726141727141728141729141730141731141732141733141734141735141736141737141738141739141740141741141742141743141744141745141746141747141748141749141750141751141752141753141754141755141756141757141758141759141760141761141762141763141764141765141766141767141768141769141770141771141772141773141774141775141776141777141778141779141780141781141782141783141784141785141786141787141788141789141790141791141792141793141794141795141796141797141798141799141800141801141802141803141804141805141806141807141808141809141810141811141812141813141814141815141816141817141818141819141820141821141822141823141824141825141826141827141828141829141830141831141832141833141834141835141836141837141838141839141840141841141842141843141844141845141846141847141848141849141850141851141852141853141854141855141856141857141858141859141860141861141862141863141864141865141866141867141868141869141870141871141872141873141874141875141876141877141878141879141880141881141882141883141884141885141886141887141888141889141890141891141892141893141894141895141896141897141898141899141900141901141902141903141904141905141906141907141908141909141910141911141912141913141914141915141916141917141918141919141920141921141922141923141924141925141926141927141928141929141930141931141932141933141934141935141936141937141938141939141940141941141942141943141944141945141946141947141948141949141950141951141952141953141954141955141956141957141958141959141960141961141962141963141964141965141966141967141968141969141970141971141972141973141974141975141976141977141978141979141980141981141982141983141984141985141986141987141988141989141990141991141992141993141994141995141996141997141998141999142000142001142002142003142004142005142006142007142008142009142010142011142012142013142014142015142016142017142018142019142020142021142022142023142024142025142026142027142028142029142030142031142032142033142034142035142036142037142038142039142040142041142042142043142044142045142046142047142048142049142050142051142052142053142054142055142056142057142058142059142060142061142062142063142064142065142066142067142068142069142070142071142072142073142074142075142076142077142078142079142080142081142082142083142084142085142086142087142088142089142090142091142092142093142094142095142096142097142098142099142100142101142102142103142104142105142106142107142108142109142110142111142112142113142114142115142116142117142118142119142120142121142122142123142124142125142126142127142128142129142130142131142132142133142134142135142136142137142138142139142140142141142142142143142144142145142146142147142148142149142150142151142152142153142154142155142156142157142158142159142160142161142162142163142164142165142166142167142168142169142170142171142172142173142174142175142176142177142178142179142180142181142182142183142184142185142186142187142188142189142190142191142192142193142194142195142196142197142198142199142200142201142202142203142204142205142206142207142208142209142210142211142212142213142214142215142216142217142218142219142220142221142222142223142224142225142226142227142228142229142230142231142232142233142234142235142236142237142238142239142240142241142242142243142244142245142246142247142248142249142250142251142252142253142254142255142256142257142258142259142260142261142262142263142264142265142266142267142268142269142270142271142272142273142274142275142276142277142278142279142280142281142282142283142284142285142286142287142288142289142290142291142292142293142294142295142296142297142298142299142300142301142302142303142304142305142306142307142308142309142310142311142312142313142314142315142316142317142318142319142320142321142322142323142324142325142326142327142328142329142330142331142332142333142334142335142336142337142338142339142340142341142342142343142344142345142346142347142348142349142350142351142352142353142354142355142356142357142358142359142360142361142362142363142364142365142366142367142368142369142370142371142372142373142374142375142376142377142378142379142380142381142382142383142384142385142386142387142388142389142390142391142392142393142394142395142396142397142398142399142400142401142402142403142404142405142406142407142408142409142410142411142412142413142414142415142416142417142418142419142420142421142422142423142424142425142426142427142428142429142430142431142432142433142434142435142436142437142438142439142440142441142442142443142444142445142446142447142448142449142450142451142452142453142454142455142456142457142458142459142460142461142462142463142464142465142466142467142468142469142470142471142472142473142474142475142476142477142478142479142480142481142482142483142484142485142486142487142488142489142490142491142492142493142494142495142496142497142498142499142500142501142502142503142504142505142506142507142508142509142510142511142512142513142514142515142516142517142518142519142520142521142522142523142524142525142526142527142528142529142530142531142532142533142534142535142536142537142538142539142540142541142542142543142544142545142546142547142548142549142550142551142552142553142554142555142556142557142558142559142560142561142562142563142564142565142566142567142568142569142570142571142572142573142574142575142576142577142578142579142580142581142582142583142584142585142586142587142588142589142590142591142592142593142594142595142596142597142598142599142600142601142602142603142604142605142606142607142608142609142610142611142612142613142614142615142616142617142618142619142620142621142622142623142624142625142626142627142628142629142630142631142632142633142634142635142636142637142638142639142640142641142642142643142644142645142646142647142648142649142650142651142652142653142654142655142656142657142658142659142660142661142662142663142664142665142666142667142668142669142670142671142672142673142674142675142676142677142678142679142680142681142682142683142684142685142686142687142688142689142690142691142692142693142694142695142696142697142698142699142700142701142702142703142704142705142706142707142708142709142710142711142712142713142714142715142716142717142718142719142720142721142722142723142724142725142726142727142728142729142730142731142732142733142734142735142736142737142738142739142740142741142742142743142744142745142746142747142748142749142750142751142752142753142754142755142756142757142758142759142760142761142762142763142764142765142766142767142768142769142770142771142772142773142774142775142776142777142778142779142780142781142782142783142784142785142786142787142788142789142790142791142792142793142794142795142796142797142798142799142800142801142802142803142804142805142806142807142808142809142810142811142812142813142814142815142816142817142818142819142820142821142822142823142824142825142826142827142828142829142830142831142832142833142834142835142836142837142838142839142840142841142842142843142844142845142846142847142848142849142850142851142852142853142854142855142856142857142858142859142860142861142862142863142864142865142866142867142868142869142870142871142872142873142874142875142876142877142878142879142880142881142882142883142884142885142886142887142888142889142890142891142892142893142894142895142896142897142898142899142900142901142902142903142904142905142906142907142908142909142910142911142912142913142914142915142916142917142918142919142920142921142922142923142924142925142926142927142928142929142930142931142932142933142934142935142936142937142938142939142940142941142942142943142944142945142946142947142948142949142950142951142952142953142954142955142956142957142958142959142960142961142962142963142964142965142966142967142968142969142970142971142972142973142974142975142976142977142978142979142980142981142982142983142984142985142986142987142988142989142990142991142992142993142994142995142996142997142998142999143000143001143002143003143004143005143006143007143008143009143010143011143012143013143014143015143016143017143018143019143020143021143022143023143024143025143026143027143028143029143030143031143032143033143034143035143036143037143038143039143040143041143042143043143044143045143046143047143048143049143050143051143052143053143054143055143056143057143058143059143060143061143062143063143064143065143066143067143068143069143070143071143072143073143074143075143076143077143078143079143080143081143082143083143084143085143086143087143088143089143090143091143092143093143094143095143096143097143098143099143100143101143102143103143104143105143106143107143108143109143110143111143112143113143114143115143116143117143118143119143120143121143122143123143124143125143126143127143128143129143130143131143132143133143134143135143136143137143138143139143140143141143142143143143144143145143146143147143148143149143150143151143152143153143154143155143156143157143158143159143160143161143162143163143164143165143166143167143168143169143170143171143172143173143174143175143176143177143178143179143180143181143182143183143184143185143186143187143188143189143190143191143192143193143194143195143196143197143198143199143200143201143202143203143204143205143206143207143208143209143210143211143212143213143214143215143216143217143218143219143220143221143222143223143224143225143226143227143228143229143230143231143232143233143234143235143236143237143238143239143240143241143242143243143244143245143246143247143248143249143250143251143252143253143254143255143256143257143258143259143260143261143262143263143264143265143266143267143268143269143270143271143272143273143274143275143276143277143278143279143280143281143282143283143284143285143286143287143288143289143290143291143292143293143294143295143296143297143298143299143300143301143302143303143304143305143306143307143308143309143310143311143312143313143314143315143316143317143318143319143320143321143322143323143324143325143326143327143328143329143330143331143332143333143334143335143336143337143338143339143340143341143342143343143344143345143346143347143348143349143350143351143352143353143354143355143356143357143358143359143360143361143362143363143364143365143366143367143368143369143370143371143372143373143374143375143376143377143378143379143380143381143382143383143384143385143386143387143388143389143390143391143392143393143394143395143396143397143398143399143400143401143402143403143404143405143406143407143408143409143410143411143412143413143414143415143416143417143418143419143420143421143422143423143424143425143426143427143428143429143430143431143432143433143434143435143436143437143438143439143440143441143442143443143444143445143446143447143448143449143450143451143452143453143454143455143456143457143458143459143460143461143462143463143464143465143466143467143468143469143470143471143472143473143474143475143476143477143478143479143480143481143482143483143484143485143486143487143488143489143490143491143492143493143494143495143496143497143498143499143500143501143502143503143504143505143506143507143508143509143510143511143512143513143514143515143516143517143518143519143520143521143522143523143524143525143526143527143528143529143530143531143532143533143534143535143536143537143538143539143540143541143542143543143544143545143546143547143548143549143550143551143552143553143554143555143556143557143558143559143560143561143562143563143564143565143566143567143568143569143570143571143572143573143574143575143576143577143578143579143580143581143582143583143584143585143586143587143588143589143590143591143592143593143594143595143596143597143598143599143600143601143602143603143604143605143606143607143608143609143610143611143612143613143614143615143616143617143618143619143620143621143622143623143624143625143626143627143628143629143630143631143632143633143634143635143636143637143638143639143640143641143642143643143644143645143646143647143648143649143650143651143652143653143654143655143656143657143658143659143660143661143662143663143664143665143666143667143668143669143670143671143672143673143674143675143676143677143678143679143680143681143682143683143684143685143686143687143688143689143690143691143692143693143694143695143696143697143698143699143700143701143702143703143704143705143706143707143708143709143710143711143712143713143714143715143716143717143718143719143720143721143722143723143724143725143726143727143728143729143730143731143732143733143734143735143736143737143738143739143740143741143742143743143744143745143746143747143748143749143750143751143752143753143754143755143756143757143758143759143760143761143762143763143764143765143766143767143768143769143770143771143772143773143774143775143776143777143778143779143780143781143782143783143784143785143786143787143788143789143790143791143792143793143794143795143796143797143798143799143800143801143802143803143804143805143806143807143808143809143810143811143812143813143814143815143816143817143818143819143820143821143822143823143824143825143826143827143828143829143830143831143832143833143834143835143836143837143838143839143840143841143842143843143844143845143846143847143848143849143850143851143852143853143854143855143856143857143858143859143860143861143862143863143864143865143866143867143868143869143870143871143872143873143874143875143876143877143878143879143880143881143882143883143884143885143886143887143888143889143890143891143892143893143894143895143896143897143898143899143900143901143902143903143904143905143906143907143908143909143910143911143912143913143914143915143916143917143918143919143920143921143922143923143924143925143926143927143928143929143930143931143932143933143934143935143936143937143938143939143940143941143942143943143944143945143946143947143948143949143950143951143952143953143954143955143956143957143958143959143960143961143962143963143964143965143966143967143968143969143970143971143972143973143974143975143976143977143978143979143980143981143982143983143984143985143986143987143988143989143990143991143992143993143994143995143996143997143998143999144000144001144002144003144004144005144006144007144008144009144010144011144012144013144014144015144016144017144018144019144020144021144022144023144024144025144026144027144028144029144030144031144032144033144034144035144036144037144038144039144040144041144042144043144044144045144046144047144048144049144050144051144052144053144054144055144056144057144058144059144060144061144062144063144064144065144066144067144068144069144070144071144072144073144074144075144076144077144078144079144080144081144082144083144084144085144086144087144088144089144090144091144092144093144094144095144096144097144098144099144100144101144102144103144104144105144106144107144108144109144110144111144112144113144114144115144116144117144118144119144120144121144122144123144124144125144126144127144128144129144130144131144132144133144134144135144136144137144138144139144140144141144142144143144144144145144146144147144148144149144150144151144152144153144154144155144156144157144158144159144160144161144162144163144164144165144166144167144168144169144170144171144172144173144174144175144176144177144178144179144180144181144182144183144184144185144186144187144188144189144190144191144192144193144194144195144196144197144198144199144200144201144202144203144204144205144206144207144208144209144210144211144212144213144214144215144216144217144218144219144220144221144222144223144224144225144226144227144228144229144230144231144232144233144234144235144236144237144238144239144240144241144242144243144244144245144246144247144248144249144250144251144252144253144254144255144256144257144258144259144260144261144262144263144264144265144266144267144268144269144270144271144272144273144274144275144276144277144278144279144280144281144282144283144284144285144286144287144288144289144290144291144292144293144294144295144296144297144298144299144300144301144302144303144304144305144306144307144308144309144310144311144312144313144314144315144316144317144318144319144320144321144322144323144324144325144326144327144328144329144330144331144332144333144334144335144336144337144338144339144340144341144342144343144344144345144346144347144348144349144350144351144352144353144354144355144356144357144358144359144360144361144362144363144364144365144366144367144368144369144370144371144372144373144374144375144376144377144378144379144380144381144382144383144384144385144386144387144388144389144390144391144392144393144394144395144396144397144398144399144400144401144402144403144404144405144406144407144408144409144410144411144412144413144414144415144416144417144418144419144420144421144422144423144424144425144426144427144428144429144430144431144432144433144434144435144436144437144438144439144440144441144442144443144444144445144446144447144448144449144450144451144452144453144454144455144456144457144458144459144460144461144462144463144464144465144466144467144468144469144470144471144472144473144474144475144476144477144478144479144480144481144482144483144484144485144486144487144488144489144490144491144492144493144494144495144496144497144498144499144500144501144502144503144504144505144506144507144508144509144510144511144512144513144514144515144516144517144518144519144520144521144522144523144524144525144526144527144528144529144530144531144532144533144534144535144536144537144538144539144540144541144542144543144544144545144546144547144548144549144550144551144552144553144554144555144556144557144558144559144560144561144562144563144564144565144566144567144568144569144570144571144572144573144574144575144576144577144578144579144580144581144582144583144584144585144586144587144588144589144590144591144592144593144594144595144596144597144598144599144600144601144602144603144604144605144606144607144608144609144610144611144612144613144614144615144616144617144618144619144620144621144622144623144624144625144626144627144628144629144630144631144632144633144634144635144636144637144638144639144640144641144642144643144644144645144646144647144648144649144650144651144652144653144654144655144656144657144658144659144660144661144662144663144664144665144666144667144668144669144670144671144672144673144674144675144676144677144678144679144680144681144682144683144684144685144686144687144688144689144690144691144692144693144694144695144696144697144698144699144700144701144702144703144704144705144706144707144708144709144710144711144712144713144714144715144716144717144718144719144720144721144722144723144724144725144726144727144728144729144730144731144732144733144734144735144736144737144738144739144740144741144742144743144744144745144746144747144748144749144750144751144752144753144754144755144756144757144758144759144760144761144762144763144764144765144766144767144768144769144770144771144772144773144774144775144776144777144778144779144780144781144782144783144784144785144786144787144788144789144790144791144792144793144794144795144796144797144798144799144800144801144802144803144804144805144806144807144808144809144810144811144812144813144814144815144816144817144818144819144820144821144822144823144824144825144826144827144828144829144830144831144832144833144834144835144836144837144838144839144840144841144842144843144844144845144846144847144848144849144850144851144852144853144854144855144856144857144858144859144860144861144862144863144864144865144866144867144868144869144870144871144872144873144874144875144876144877144878144879144880144881144882144883144884144885144886144887144888144889144890144891144892144893144894144895144896144897144898144899144900144901144902144903144904144905144906144907144908144909144910144911144912144913144914144915144916144917144918144919144920144921144922144923144924144925144926144927144928144929144930144931144932144933144934144935144936144937144938144939144940144941144942144943144944144945144946144947144948144949144950144951144952144953144954144955144956144957144958144959144960144961144962144963144964144965144966144967144968144969144970144971144972144973144974144975144976144977144978144979144980144981144982144983144984144985144986144987144988144989144990144991144992144993144994144995144996144997144998144999145000145001145002145003145004145005145006145007145008145009145010145011145012145013145014145015145016145017145018145019145020145021145022145023145024145025145026145027145028145029145030145031145032145033145034145035145036145037145038145039145040145041145042145043145044145045145046145047145048145049145050145051145052145053145054145055145056145057145058145059145060145061145062145063145064145065145066145067145068145069145070145071145072145073145074145075145076145077145078145079145080145081145082145083145084145085145086145087145088145089145090145091145092145093145094145095145096145097145098145099145100145101145102145103145104145105145106145107145108145109145110145111145112145113145114145115145116145117145118145119145120145121145122145123145124145125145126145127145128145129145130145131145132145133145134145135145136145137145138145139145140145141145142145143145144145145145146145147145148145149145150145151145152145153145154145155145156145157145158145159145160145161145162145163145164145165145166145167145168145169145170145171145172145173145174145175145176145177145178145179145180145181145182145183145184145185145186145187145188145189145190145191145192145193145194145195145196145197145198145199145200145201145202145203145204145205145206145207145208145209145210145211145212145213145214145215145216145217145218145219145220145221145222145223145224145225145226145227145228145229145230145231145232145233145234145235145236145237145238145239145240145241145242145243145244145245145246145247145248145249145250145251145252145253145254145255145256145257145258145259145260145261145262145263145264145265145266145267145268145269145270145271145272145273145274145275145276145277145278145279145280145281145282145283145284145285145286145287145288145289145290145291145292145293145294145295145296145297145298145299145300145301145302145303145304145305145306145307145308145309145310145311145312145313145314145315145316145317145318145319145320145321145322145323145324145325145326145327145328145329145330145331145332145333145334145335145336145337145338145339145340145341145342145343145344145345145346145347145348145349145350145351145352145353145354145355145356145357145358145359145360145361145362145363145364145365145366145367145368145369145370145371145372145373145374145375145376145377145378145379145380145381145382145383145384145385145386145387145388145389145390145391145392145393145394145395145396145397145398145399145400145401145402145403145404145405145406145407145408145409145410145411145412145413145414145415145416145417145418145419145420145421145422145423145424145425145426145427145428145429145430145431145432145433145434145435145436145437145438145439145440145441145442145443145444145445145446145447145448145449145450145451145452145453145454145455145456145457145458145459145460145461145462145463145464145465145466145467145468145469145470145471145472145473145474145475145476145477145478145479145480145481145482145483145484145485145486145487145488145489145490145491145492145493145494145495145496145497145498145499145500145501145502145503145504145505145506145507145508145509145510145511145512145513145514145515145516145517145518145519145520145521145522145523145524145525145526145527145528145529145530145531145532145533145534145535145536145537145538145539145540145541145542145543145544145545145546145547145548145549145550145551145552145553145554145555145556145557145558145559145560145561145562145563145564145565145566145567145568145569145570145571145572145573145574145575145576145577145578145579145580145581145582145583145584145585145586145587145588145589145590145591145592145593145594145595145596145597145598145599145600145601145602145603145604145605145606145607145608145609145610145611145612145613145614145615145616145617145618145619145620145621145622145623145624145625145626145627145628145629145630145631145632145633145634145635145636145637145638145639145640145641145642145643145644145645145646145647145648145649145650145651145652145653145654145655145656145657145658145659145660145661145662145663145664145665145666145667145668145669145670145671145672145673145674145675145676145677145678145679145680145681145682145683145684145685145686145687145688145689145690145691145692145693145694145695145696145697145698145699145700145701145702145703145704145705145706145707145708145709145710145711145712145713145714145715145716145717145718145719145720145721145722145723145724145725145726145727145728145729145730145731145732145733145734145735145736145737145738145739145740145741145742145743145744145745145746145747145748145749145750145751145752145753145754145755145756145757145758145759145760145761145762145763145764145765145766145767145768145769145770145771145772145773145774145775145776145777145778145779145780145781145782145783145784145785145786145787145788145789145790145791145792145793145794145795145796145797145798145799145800145801145802145803145804145805145806145807145808145809145810145811145812145813145814145815145816145817145818145819145820145821145822145823145824145825145826145827145828145829145830145831145832145833145834145835145836145837145838145839145840145841145842145843145844145845145846145847145848145849145850145851145852145853145854145855145856145857145858145859145860145861145862145863145864145865145866145867145868145869145870145871145872145873145874145875145876145877145878145879145880145881145882145883145884145885145886145887145888145889145890145891145892145893145894145895145896145897145898145899145900145901145902145903145904145905145906145907145908145909145910145911145912145913145914145915145916145917145918145919145920145921145922145923145924145925145926145927145928145929145930145931145932145933145934145935145936145937145938145939145940145941145942145943145944145945145946145947145948145949145950145951145952145953145954145955145956145957145958145959145960145961145962145963145964145965145966145967145968145969145970145971145972145973145974145975145976145977145978145979145980145981145982145983145984145985145986145987145988145989145990145991145992145993145994145995145996145997145998145999146000146001146002146003146004146005146006146007146008146009146010146011146012146013146014146015146016146017146018146019146020146021146022146023146024146025146026146027146028146029146030146031146032146033146034146035146036146037146038146039146040146041146042146043146044146045146046146047146048146049146050146051146052146053146054146055146056146057146058146059146060146061146062146063146064146065146066146067146068146069146070146071146072146073146074146075146076146077146078146079146080146081146082146083146084146085146086146087146088146089146090146091146092146093146094146095146096146097146098146099146100146101146102146103146104146105146106146107146108146109146110146111146112146113146114146115146116146117146118146119146120146121146122146123146124146125146126146127146128146129146130146131146132146133146134146135146136146137146138146139146140146141146142146143146144146145146146146147146148146149146150146151146152146153146154146155146156146157146158146159146160146161146162146163146164146165146166146167146168146169146170146171146172146173146174146175146176146177146178146179146180146181146182146183146184146185146186146187146188146189146190146191146192146193146194146195146196146197146198146199146200146201146202146203146204146205146206146207146208146209146210146211146212146213146214146215146216146217146218146219146220146221146222146223146224146225146226146227146228146229146230146231146232146233146234146235146236146237146238146239146240146241146242146243146244146245146246146247146248146249146250146251146252146253146254146255146256146257146258146259146260146261146262146263146264146265146266146267146268146269146270146271146272146273146274146275146276146277146278146279146280146281146282146283146284146285146286146287146288146289146290146291146292146293146294146295146296146297146298146299146300146301146302146303146304146305146306146307146308146309146310146311146312146313146314146315146316146317146318146319146320146321146322146323146324146325146326146327146328146329146330146331146332146333146334146335146336146337146338146339146340146341146342146343146344146345146346146347146348146349146350146351146352146353146354146355146356146357146358146359146360146361146362146363146364146365146366146367146368146369146370146371146372146373146374146375146376146377146378146379146380146381146382146383146384146385146386146387146388146389146390146391146392146393146394146395146396146397146398146399146400146401146402146403146404146405146406146407146408146409146410146411146412146413146414146415146416146417146418146419146420146421146422146423146424146425146426146427146428146429146430146431146432146433146434146435146436146437146438146439146440146441146442146443146444146445146446146447146448146449146450146451146452146453146454146455146456146457146458146459146460146461146462146463146464146465146466146467146468146469146470146471146472146473146474146475146476146477146478146479146480146481146482146483146484146485146486146487146488146489146490146491146492146493146494146495146496146497146498146499146500146501146502146503146504146505146506146507146508146509146510146511146512146513146514146515146516146517146518146519146520146521146522146523146524146525146526146527146528146529146530146531146532146533146534146535146536146537146538146539146540146541146542146543146544146545146546146547146548146549146550146551146552146553146554146555146556146557146558146559146560146561146562146563146564146565146566146567146568146569146570146571146572146573146574146575146576146577146578146579146580146581146582146583146584146585146586146587146588146589146590146591146592146593146594146595146596146597146598146599146600146601146602146603146604146605146606146607146608146609146610146611146612146613146614146615146616146617146618146619146620146621146622146623146624146625146626146627146628146629146630146631146632146633146634146635146636146637146638146639146640146641146642146643146644146645146646146647146648146649146650146651146652146653146654146655146656146657146658146659146660146661146662146663146664146665146666146667146668146669146670146671146672146673146674146675146676146677146678146679146680146681146682146683146684146685146686146687146688146689146690146691146692146693146694146695146696146697146698146699146700146701146702146703146704146705146706146707146708146709146710146711146712146713146714146715146716146717146718146719146720146721146722146723146724146725146726146727146728146729146730146731146732146733146734146735146736146737146738146739146740146741146742146743146744146745146746146747146748146749146750146751146752146753146754146755146756146757146758146759146760146761146762146763146764146765146766146767146768146769146770146771146772146773146774146775146776146777146778146779146780146781146782146783146784146785146786146787146788146789146790146791146792146793146794146795146796146797146798146799146800146801146802146803146804146805146806146807146808146809146810146811146812146813146814146815146816146817146818146819146820146821146822146823146824146825146826146827146828146829146830146831146832146833146834146835146836146837146838146839146840146841146842146843146844146845146846146847146848146849146850146851146852146853146854146855146856146857146858146859146860146861146862146863146864146865146866146867146868146869146870146871146872146873146874146875146876146877146878146879146880146881146882146883146884146885146886146887146888146889146890146891146892146893146894146895146896146897146898146899146900146901146902146903146904146905146906146907146908146909146910146911146912146913146914146915146916146917146918146919146920146921146922146923146924146925146926146927146928146929146930146931146932146933146934146935146936146937146938146939146940146941146942146943146944146945146946146947146948146949146950146951146952146953146954146955146956146957146958146959146960146961146962146963146964146965146966146967146968146969146970146971146972146973146974146975146976146977146978146979146980146981146982146983146984146985146986146987146988146989146990146991146992146993146994146995146996146997146998146999147000147001147002147003147004147005147006147007147008147009147010147011147012147013147014147015147016147017147018147019147020147021147022147023147024147025147026147027147028147029147030147031147032147033147034147035147036147037147038147039147040147041147042147043147044147045147046147047147048147049147050147051147052147053147054147055147056147057147058147059147060147061147062147063147064147065147066147067147068147069147070147071147072147073147074147075147076147077147078147079147080147081147082147083147084147085147086147087147088147089147090147091147092147093147094147095147096147097147098147099147100147101147102147103147104147105147106147107147108147109147110147111147112147113147114147115147116147117147118147119147120147121147122147123147124147125147126147127147128147129147130147131147132147133147134147135147136147137147138147139147140147141147142147143147144147145147146147147147148147149147150147151147152147153147154147155147156147157147158147159147160147161147162147163147164147165147166147167147168147169147170147171147172147173147174147175147176147177147178147179147180147181147182147183147184147185147186147187147188147189147190147191147192147193147194147195147196147197147198147199147200147201147202147203147204147205147206147207147208147209147210147211147212147213147214147215147216147217147218147219147220147221147222147223147224147225147226147227147228147229147230147231147232147233147234147235147236147237147238147239147240147241147242147243147244147245147246147247147248147249147250147251147252147253147254147255147256147257147258147259147260147261147262147263147264147265147266147267147268147269147270147271147272147273147274147275147276147277147278147279147280147281147282147283147284147285147286147287147288147289147290147291147292147293147294147295147296147297147298147299147300147301147302147303147304147305147306147307147308147309147310147311147312147313147314147315147316147317147318147319147320147321147322147323147324147325147326147327147328147329147330147331147332147333147334147335147336147337147338147339147340147341147342147343147344147345147346147347147348147349147350147351147352147353147354147355147356147357147358147359147360147361147362147363147364147365147366147367147368147369147370147371147372147373147374147375147376147377147378147379147380147381147382147383147384147385147386147387147388147389147390147391147392147393147394147395147396147397147398147399147400147401147402147403147404147405147406147407147408147409147410147411147412147413147414147415147416147417147418147419147420147421147422147423147424147425147426147427147428147429147430147431147432147433147434147435147436147437147438147439147440147441147442147443147444147445147446147447147448147449147450147451147452147453147454147455147456147457147458147459147460147461147462147463147464147465147466147467147468147469147470147471147472147473147474147475147476147477147478147479147480147481147482147483147484147485147486147487147488147489147490147491147492147493147494147495147496147497147498147499147500147501147502147503147504147505147506147507147508147509147510147511147512147513147514147515147516147517147518147519147520147521147522147523147524147525147526147527147528147529147530147531147532147533147534147535147536147537147538147539147540147541147542147543147544147545147546147547147548147549147550147551147552147553147554147555147556147557147558147559147560147561147562147563147564147565147566147567147568147569147570147571147572147573147574147575147576147577147578147579147580147581147582147583147584147585147586147587147588147589147590147591147592147593147594147595147596147597147598147599147600147601147602147603147604147605147606147607147608147609147610147611147612147613147614147615147616147617147618147619147620147621147622147623147624147625147626147627147628147629147630147631147632147633147634147635147636147637147638147639147640147641147642147643147644147645147646147647147648147649147650147651147652147653147654147655147656147657147658147659147660147661147662147663147664147665147666147667147668147669147670147671147672147673147674147675147676147677147678147679147680147681147682147683147684147685147686147687147688147689147690147691147692147693147694147695147696147697147698147699147700147701147702147703147704147705147706147707147708147709147710147711147712147713147714147715147716147717147718147719147720147721147722147723147724147725147726147727147728147729147730147731147732147733147734147735147736147737147738147739147740147741147742147743147744147745147746147747147748147749147750147751147752147753147754147755147756147757147758147759147760147761147762147763147764147765147766147767147768147769147770147771147772147773147774147775147776147777147778147779147780147781147782147783147784147785147786147787147788147789147790147791147792147793147794147795147796147797147798147799147800147801147802147803147804147805147806147807147808147809147810147811147812147813147814147815147816147817147818147819147820147821147822147823147824147825147826147827147828147829147830147831147832147833147834147835147836147837147838147839147840147841147842147843147844147845147846147847147848147849147850147851147852147853147854147855147856147857147858147859147860147861147862147863147864147865147866147867147868147869147870147871147872147873147874147875147876147877147878147879147880147881147882147883147884147885147886147887147888147889147890147891147892147893147894147895147896147897147898147899147900147901147902147903147904147905147906147907147908147909147910147911147912147913147914147915147916147917147918147919147920147921147922147923147924147925147926147927147928147929147930147931147932147933147934147935147936147937147938147939147940147941147942147943147944147945147946147947147948147949147950147951147952147953147954147955147956147957147958147959147960147961147962147963147964147965147966147967147968147969147970147971147972147973147974147975147976147977147978147979147980147981147982147983147984147985147986147987147988147989147990147991147992147993147994147995147996147997147998147999148000148001148002148003148004148005148006148007148008148009148010148011148012148013148014148015148016148017148018148019148020148021148022148023148024148025148026148027148028148029148030148031148032148033148034148035148036148037148038148039148040148041148042148043148044148045148046148047148048148049148050148051148052148053148054148055148056148057148058148059148060148061148062148063148064148065148066148067148068148069148070148071148072148073148074148075148076148077148078148079148080148081148082148083148084148085148086148087148088148089148090148091148092148093148094148095148096148097148098148099148100148101148102148103148104148105148106148107148108148109148110148111148112148113148114148115148116148117148118148119148120148121148122148123148124148125148126148127148128148129148130148131148132148133148134148135148136148137148138148139148140148141148142148143148144148145148146148147148148148149148150148151148152148153148154148155148156148157148158148159148160148161148162148163148164148165148166148167148168148169148170148171148172148173148174148175148176148177148178148179148180148181148182148183148184148185148186148187148188148189148190148191148192148193148194148195148196148197148198148199148200148201148202148203148204148205148206148207148208148209148210148211148212148213148214148215148216148217148218148219148220148221148222148223148224148225148226148227148228148229148230148231148232148233148234148235148236148237148238148239148240148241148242148243148244148245148246148247148248148249148250148251148252148253148254148255148256148257148258148259148260148261148262148263148264148265148266148267148268148269148270148271148272148273148274148275148276148277148278148279148280148281148282148283148284148285148286148287148288148289148290148291148292148293148294148295148296148297148298148299148300148301148302148303148304148305148306148307148308148309148310148311148312148313148314148315148316148317148318148319148320148321148322148323148324148325148326148327148328148329148330148331148332148333148334148335148336148337148338148339148340148341148342148343148344148345148346148347148348148349148350148351148352148353148354148355148356148357148358148359148360148361148362148363148364148365148366148367148368148369148370148371148372148373148374148375148376148377148378148379148380148381148382148383148384148385148386148387148388148389148390148391148392148393148394148395148396148397148398148399148400148401148402148403148404148405148406148407148408148409148410148411148412148413148414148415148416148417148418148419148420148421148422148423148424148425148426148427148428148429148430148431148432148433148434148435148436148437148438148439148440148441148442148443148444148445148446148447148448148449148450148451148452148453148454148455148456148457148458148459148460148461148462148463148464148465148466148467148468148469148470148471148472148473148474148475148476148477148478148479148480148481148482148483148484148485148486148487148488148489148490148491148492148493148494148495148496148497148498148499148500148501148502148503148504148505148506148507148508148509148510148511148512148513148514148515148516148517148518148519148520148521148522148523148524148525148526148527148528148529148530148531148532148533148534148535148536148537148538148539148540148541148542148543148544148545148546148547148548148549148550148551148552148553148554148555148556148557148558148559148560148561148562148563148564148565148566148567148568148569148570148571148572148573148574148575148576148577148578148579148580148581148582148583148584148585148586148587148588148589148590148591148592148593148594148595148596148597148598148599148600148601148602148603148604148605148606148607148608148609148610148611148612148613148614148615148616148617148618148619148620148621148622148623148624148625148626148627148628148629148630148631148632148633148634148635148636148637148638148639148640148641148642148643148644148645148646148647148648148649148650148651148652148653148654148655148656148657148658148659148660148661148662148663148664148665148666148667148668148669148670148671148672148673148674148675148676148677148678148679148680148681148682148683148684148685148686148687148688148689148690148691148692148693148694148695148696148697148698148699148700148701148702148703148704148705148706148707148708148709148710148711148712148713148714148715148716148717148718148719148720148721148722148723148724148725148726148727148728148729148730148731148732148733148734148735148736148737148738148739148740148741148742148743148744148745148746148747148748148749148750148751148752148753148754148755148756148757148758148759148760148761148762148763148764148765148766148767148768148769148770148771148772148773148774148775148776148777148778148779148780148781148782148783148784148785148786148787148788148789148790148791148792148793148794148795148796148797148798148799148800148801148802148803148804148805148806148807148808148809148810148811148812148813148814148815148816148817148818148819148820148821148822148823148824148825148826148827148828148829148830148831148832148833148834148835148836148837148838148839148840148841148842148843148844148845148846148847148848148849148850148851148852148853148854148855148856148857148858148859148860148861148862148863148864148865148866148867148868148869148870148871148872148873148874148875148876148877148878148879148880148881148882148883148884148885148886148887148888148889148890148891148892148893148894148895148896148897148898148899148900148901148902148903148904148905148906148907148908148909148910148911148912148913148914148915148916148917148918148919148920148921148922148923148924148925148926148927148928148929148930148931148932148933148934148935148936148937148938148939148940148941148942148943148944148945148946148947148948148949148950148951148952148953148954148955148956148957148958148959148960148961148962148963148964148965148966148967148968148969148970148971148972148973148974148975148976148977148978148979148980148981148982148983148984148985148986148987148988148989148990148991148992148993148994148995148996148997148998148999149000149001149002149003149004149005149006149007149008149009149010149011149012149013149014149015149016149017149018149019149020149021149022149023149024149025149026149027149028149029149030149031149032149033149034149035149036149037149038149039149040149041149042149043149044149045149046149047149048149049149050149051149052149053149054149055149056149057149058149059149060149061149062149063149064149065149066149067149068149069149070149071149072149073149074149075149076149077149078149079149080149081149082149083149084149085149086149087149088149089149090149091149092149093149094149095149096149097149098149099149100149101149102149103149104149105149106149107149108149109149110149111149112149113149114149115149116149117149118149119149120149121149122149123149124149125149126149127149128149129149130149131149132149133149134149135149136149137149138149139149140149141149142149143149144149145149146149147149148149149149150149151149152149153149154149155149156149157149158149159149160149161149162149163149164149165149166149167149168149169149170149171149172149173149174149175149176149177149178149179149180149181149182149183149184149185149186149187149188149189149190149191149192149193149194149195149196149197149198149199149200149201149202149203149204149205149206149207149208149209149210149211149212149213149214149215149216149217149218149219149220149221149222149223149224149225149226149227149228149229149230149231149232149233149234149235149236149237149238149239149240149241149242149243149244149245149246149247149248149249149250149251149252149253149254149255149256149257149258149259149260149261149262149263149264149265149266149267149268149269149270149271149272149273149274149275149276149277149278149279149280149281149282149283149284149285149286149287149288149289149290149291149292149293149294149295149296149297149298149299149300149301149302149303149304149305149306149307149308149309149310149311149312149313149314149315149316149317149318149319149320149321149322149323149324149325149326149327149328149329149330149331149332149333149334149335149336149337149338149339149340149341149342149343149344149345149346149347149348149349149350149351149352149353149354149355149356149357149358149359149360149361149362149363149364149365149366149367149368149369149370149371149372149373149374149375149376149377149378149379149380149381149382149383149384149385149386149387149388149389149390149391149392149393149394149395149396149397149398149399149400149401149402149403149404149405149406149407149408149409149410149411149412149413149414149415149416149417149418149419149420149421149422149423149424149425149426149427149428149429149430149431149432149433149434149435149436149437149438149439149440149441149442149443149444149445149446149447149448149449149450149451149452149453149454149455149456149457149458149459149460149461149462149463149464149465149466149467149468149469149470149471149472149473149474149475149476149477149478149479149480149481149482149483149484149485149486149487149488149489149490149491149492149493149494149495149496149497149498149499149500149501149502149503149504149505149506149507149508149509149510149511149512149513149514149515149516149517149518149519149520149521149522149523149524149525149526149527149528149529149530149531149532149533149534149535149536149537149538149539149540149541149542149543149544149545149546149547149548149549149550149551149552149553149554149555149556149557149558149559149560149561149562149563149564149565149566149567149568149569149570149571149572149573149574149575149576149577149578149579149580149581149582149583149584149585149586149587149588149589149590149591149592149593149594149595149596149597149598149599149600149601149602149603149604149605149606149607149608149609149610149611149612149613149614149615149616149617149618149619149620149621149622149623149624149625149626149627149628149629149630149631149632149633149634149635149636149637149638149639149640149641149642149643149644149645149646149647149648149649149650149651149652149653149654149655149656149657149658149659149660149661149662149663149664149665149666149667149668149669149670149671149672149673149674149675149676149677149678149679149680149681149682149683149684149685149686149687149688149689149690149691149692149693149694149695149696149697149698149699149700149701149702149703149704149705149706149707149708149709149710149711149712149713149714149715149716149717149718149719149720149721149722149723149724149725149726149727149728149729149730149731149732149733149734149735149736149737149738149739149740149741149742149743149744149745149746149747149748149749149750149751149752149753149754149755149756149757149758149759149760149761149762149763149764149765149766149767149768149769149770149771149772149773149774149775149776149777149778149779149780149781149782149783149784149785149786149787149788149789149790149791149792149793149794149795149796149797149798149799149800149801149802149803149804149805149806149807149808149809149810149811149812149813149814149815149816149817149818149819149820149821149822149823149824149825149826149827149828149829149830149831149832149833149834149835149836149837149838149839149840149841149842149843149844149845149846149847149848149849149850149851149852149853149854149855149856149857149858149859149860149861149862149863149864149865149866149867149868149869149870149871149872149873149874149875149876149877149878149879149880149881149882149883149884149885149886149887149888149889149890149891149892149893149894149895149896149897149898149899149900149901149902149903149904149905149906149907149908149909149910149911149912149913149914149915149916149917149918149919149920149921149922149923149924149925149926149927149928149929149930149931149932149933149934149935149936149937149938149939149940149941149942149943149944149945149946149947149948149949149950149951149952149953149954149955149956149957149958149959149960149961149962149963149964149965149966149967149968149969149970149971149972149973149974149975149976149977149978149979149980149981149982149983149984149985149986149987149988149989149990149991149992149993149994149995149996149997149998149999150000150001150002150003150004150005150006150007150008150009150010150011150012150013150014150015150016150017150018150019150020150021150022150023150024150025150026150027150028150029150030150031150032150033150034150035150036150037150038150039150040150041150042150043150044150045150046150047150048150049150050150051150052150053150054150055150056150057150058150059150060150061150062150063150064150065150066150067150068150069150070150071150072150073150074150075150076150077150078150079150080150081150082150083150084150085150086150087150088150089150090150091150092150093150094150095150096150097150098150099150100150101150102150103150104150105150106150107150108150109150110150111150112150113150114150115150116150117150118150119150120150121150122150123150124150125150126150127150128150129150130150131150132150133150134150135150136150137150138150139150140150141150142150143150144150145150146150147150148150149150150150151150152150153150154150155150156150157150158150159150160150161150162150163150164150165150166150167150168150169150170150171150172150173150174150175150176150177150178150179150180150181150182150183150184150185150186150187150188150189150190150191150192150193150194150195150196150197150198150199150200150201150202150203150204150205150206150207150208150209150210150211150212150213150214150215150216150217150218150219150220150221150222150223150224150225150226150227150228150229150230150231150232150233150234150235150236150237150238150239150240150241150242150243150244150245150246150247150248150249150250150251150252150253150254150255150256150257150258150259150260150261150262150263150264150265150266150267150268150269150270150271150272150273150274150275150276150277150278150279150280150281150282150283150284150285150286150287150288150289150290150291150292150293150294150295150296150297150298150299150300150301150302150303150304150305150306150307150308150309150310150311150312150313150314150315150316150317150318150319150320150321150322150323150324150325150326150327150328150329150330150331150332150333150334150335150336150337150338150339150340150341150342150343150344150345150346150347150348150349150350150351150352150353150354150355150356150357150358150359150360150361150362150363150364150365150366150367150368150369150370150371150372150373150374150375150376150377150378150379150380150381150382150383150384150385150386150387150388150389150390150391150392150393150394150395150396150397150398150399150400150401150402150403150404150405150406150407150408150409150410150411150412150413150414150415150416150417150418150419150420150421150422150423150424150425150426150427150428150429150430150431150432150433150434150435150436150437150438150439150440150441150442150443150444150445150446150447150448150449150450150451150452150453150454150455150456150457150458150459150460150461150462150463150464150465150466150467150468150469150470150471150472150473150474150475150476150477150478150479150480150481150482150483150484150485150486150487150488150489150490150491150492150493150494150495150496150497150498150499150500150501150502150503150504150505150506150507150508150509150510150511150512150513150514150515150516150517150518150519150520150521150522150523150524150525150526150527150528150529150530150531150532150533150534150535150536150537150538150539150540150541150542150543150544150545150546150547150548150549150550150551150552150553150554150555150556150557150558150559150560150561150562150563150564150565150566150567150568150569150570150571150572150573150574150575150576150577150578150579150580150581150582150583150584150585150586150587150588150589150590150591150592150593150594150595150596150597150598150599150600150601150602150603150604150605150606150607150608150609150610150611150612150613150614150615150616150617150618150619150620150621150622150623150624150625150626150627150628150629150630150631150632150633150634150635150636150637150638150639150640150641150642150643150644150645150646150647150648150649150650150651150652150653150654150655150656150657150658150659150660150661150662150663150664150665150666150667150668150669150670150671150672150673150674150675150676150677150678150679150680150681150682150683150684150685150686150687150688150689150690150691150692150693150694150695150696150697150698150699150700150701150702150703150704150705150706150707150708150709150710150711150712150713150714150715150716150717150718150719150720150721150722150723150724150725150726150727150728150729150730150731150732150733150734150735150736150737150738150739150740150741150742150743150744150745150746150747150748150749150750150751150752150753150754150755150756150757150758150759150760150761150762150763150764150765150766150767150768150769150770150771150772150773150774150775150776150777150778150779150780150781150782150783150784150785150786150787150788150789150790150791150792150793150794150795150796150797150798150799150800150801150802150803150804150805150806150807150808150809150810150811150812150813150814150815150816150817150818150819150820150821150822150823150824150825150826150827150828150829150830150831150832150833150834150835150836150837150838150839150840150841150842150843150844150845150846150847150848150849150850150851150852150853150854150855150856150857150858150859150860150861150862150863150864150865150866150867150868150869150870150871150872150873150874150875150876150877150878150879150880150881150882150883150884150885150886150887150888150889150890150891150892150893150894150895150896150897150898150899150900150901150902150903150904150905150906150907150908150909150910150911150912150913150914150915150916150917150918150919150920150921150922150923150924150925150926150927150928150929150930150931150932150933150934150935150936150937150938150939150940150941150942150943150944150945150946150947150948150949150950150951150952150953150954150955150956150957150958150959150960150961150962150963150964150965150966150967150968150969150970150971150972150973150974150975150976150977150978150979150980150981150982150983150984150985150986150987150988150989150990150991150992150993150994150995150996150997150998150999151000151001151002151003151004151005151006151007151008151009151010151011151012151013151014151015151016151017151018151019151020151021151022151023151024151025151026151027151028151029151030151031151032151033151034151035151036151037151038151039151040151041151042151043151044151045151046151047151048151049151050151051151052151053151054151055151056151057151058151059151060151061151062151063151064151065151066151067151068151069151070151071151072151073151074151075151076151077151078151079151080151081151082151083151084151085151086151087151088151089151090151091151092151093151094151095151096151097151098151099151100151101151102151103151104151105151106151107151108151109151110151111151112151113151114151115151116151117151118151119151120151121151122151123151124151125151126151127151128151129151130151131151132151133151134151135151136151137151138151139151140151141151142151143151144151145151146151147151148151149151150151151151152151153151154151155151156151157151158151159151160151161151162151163151164151165151166151167151168151169151170151171151172151173151174151175151176151177151178151179151180151181151182151183151184151185151186151187151188151189151190151191151192151193151194151195151196151197151198151199151200151201151202151203151204151205151206151207151208151209151210151211151212151213151214151215151216151217151218151219151220151221151222151223151224151225151226151227151228151229151230151231151232151233151234151235151236151237151238151239151240151241151242151243151244151245151246151247151248151249151250151251151252151253151254151255151256151257151258151259151260151261151262151263151264151265151266151267151268151269151270151271151272151273151274151275151276151277151278151279151280151281151282151283151284151285151286151287151288151289151290151291151292151293151294151295151296151297151298151299151300151301151302151303151304151305151306151307151308151309151310151311151312151313151314151315151316151317151318151319151320151321151322151323151324151325151326151327151328151329151330151331151332151333151334151335151336151337151338151339151340151341151342151343151344151345151346151347151348151349151350151351151352151353151354151355151356151357151358151359151360151361151362151363151364151365151366151367151368151369151370151371151372151373151374151375151376151377151378151379151380151381151382151383151384151385151386151387151388151389151390151391151392151393151394151395151396151397151398151399151400151401151402151403151404151405151406151407151408151409151410151411151412151413151414151415151416151417151418151419151420151421151422151423151424151425151426151427151428151429151430151431151432151433151434151435151436151437151438151439151440151441151442151443151444151445151446151447151448151449151450151451151452151453151454151455151456151457151458151459151460151461151462151463151464151465151466151467151468151469151470151471151472151473151474151475151476151477151478151479151480151481151482151483151484151485151486151487151488151489151490151491151492151493151494151495151496151497151498151499151500151501151502151503151504151505151506151507151508151509151510151511151512151513151514151515151516151517151518151519151520151521151522151523151524151525151526151527151528151529151530151531151532151533151534151535151536151537151538151539151540151541151542151543151544151545151546151547151548151549151550151551151552151553151554151555151556151557151558151559151560151561151562151563151564151565151566151567151568151569151570151571151572151573151574151575151576151577151578151579151580151581151582151583151584151585151586151587151588151589151590151591151592151593151594151595151596151597151598151599151600151601151602151603151604151605151606151607151608151609151610151611151612151613151614151615151616151617151618151619151620151621151622151623151624151625151626151627151628151629151630151631151632151633151634151635151636151637151638151639151640151641151642151643151644151645151646151647151648151649151650151651151652151653151654151655151656151657151658151659151660151661151662151663151664151665151666151667151668151669151670151671151672151673151674151675151676151677151678151679151680151681151682151683151684151685151686151687151688151689151690151691151692151693151694151695151696151697151698151699151700151701151702151703151704151705151706151707151708151709151710151711151712151713151714151715151716151717151718151719151720151721151722151723151724151725151726151727151728151729151730151731151732151733151734151735151736151737151738151739151740151741151742151743151744151745151746151747151748151749151750151751151752151753151754151755151756151757151758151759151760151761151762151763151764151765151766151767151768151769151770151771151772151773151774151775151776151777151778151779151780151781151782151783151784151785151786151787151788151789151790151791151792151793151794151795151796151797151798151799151800151801151802151803151804151805151806151807151808151809151810151811151812151813151814151815151816151817151818151819151820151821151822151823151824151825151826151827151828151829151830151831151832151833151834151835151836151837151838151839151840151841151842151843151844151845151846151847151848151849151850151851151852151853151854151855151856151857151858151859151860151861151862151863151864151865151866151867151868151869151870151871151872151873151874151875151876151877151878151879151880151881151882151883151884151885151886151887151888151889151890151891151892151893151894151895151896151897151898151899151900151901151902151903151904151905151906151907151908151909151910151911151912151913151914151915151916151917151918151919151920151921151922151923151924151925151926151927151928151929151930151931151932151933151934151935151936151937151938151939151940151941151942151943151944151945151946151947151948151949151950151951151952151953151954151955151956151957151958151959151960151961151962151963151964151965151966151967151968151969151970151971151972151973151974151975151976151977151978151979151980151981151982151983151984151985151986151987151988151989151990151991151992151993151994151995151996151997151998151999152000152001152002152003152004152005152006152007152008152009152010152011152012152013152014152015152016152017152018152019152020152021152022152023152024152025152026152027152028152029152030152031152032152033152034152035152036152037152038152039152040152041152042152043152044152045152046152047152048152049152050152051152052152053152054152055152056152057152058152059152060152061152062152063152064152065152066152067152068152069152070152071152072152073152074152075152076152077152078152079152080152081152082152083152084152085152086152087152088152089152090152091152092152093152094152095152096152097152098152099152100152101152102152103152104152105152106152107152108152109152110152111152112152113152114152115152116152117152118152119152120152121152122152123152124152125152126152127152128152129152130152131152132152133152134152135152136152137152138152139152140152141152142152143152144152145152146152147152148152149152150152151152152152153152154152155152156152157152158152159152160152161152162152163152164152165152166152167152168152169152170152171152172152173152174152175152176152177152178152179152180152181152182152183152184152185152186152187152188152189152190152191152192152193152194152195152196152197152198152199152200152201152202152203152204152205152206152207152208152209152210152211152212152213152214152215152216152217152218152219152220152221152222152223152224152225152226152227152228152229152230152231152232152233152234152235152236152237152238152239152240152241152242152243152244152245152246152247152248152249152250152251152252152253152254152255152256152257152258152259152260152261152262152263152264152265152266152267152268152269152270152271152272152273152274152275152276152277152278152279152280152281152282152283152284152285152286152287152288152289152290152291152292152293152294152295152296152297152298152299152300152301152302152303152304152305152306152307152308152309152310152311152312152313152314152315152316152317152318152319152320152321152322152323152324152325152326152327152328152329152330152331152332152333152334152335152336152337152338152339152340152341152342152343152344152345152346152347152348152349152350152351152352152353152354152355152356152357152358152359152360152361152362152363152364152365152366152367152368152369152370152371152372152373152374152375152376152377152378152379152380152381152382152383152384152385152386152387152388152389152390152391152392152393152394152395152396152397152398152399152400152401152402152403152404152405152406152407152408152409152410152411152412152413152414152415152416152417152418152419152420152421152422152423152424152425152426152427152428152429152430152431152432152433152434152435152436152437152438152439152440152441152442152443152444152445152446152447152448152449152450152451152452152453152454152455152456152457152458152459152460152461152462152463152464152465152466152467152468152469152470152471152472152473152474152475152476152477152478152479152480152481152482152483152484152485152486152487152488152489152490152491152492152493152494152495152496152497152498152499152500152501152502152503152504152505152506152507152508152509152510152511152512152513152514152515152516152517152518152519152520152521152522152523152524152525152526152527152528152529152530152531152532152533152534152535152536152537152538152539152540152541152542152543152544152545152546152547152548152549152550152551152552152553152554152555152556152557152558152559152560152561152562152563152564152565152566152567152568152569152570152571152572152573152574152575152576152577152578152579152580152581152582152583152584152585152586152587152588152589152590152591152592152593152594152595152596152597152598152599152600152601152602152603152604152605152606152607152608152609152610152611152612152613152614152615152616152617152618152619152620152621152622152623152624152625152626152627152628152629152630152631152632152633152634152635152636152637152638152639152640152641152642152643152644152645152646152647152648152649152650152651152652152653152654152655152656152657152658152659152660152661152662152663152664152665152666152667152668152669152670152671152672152673152674152675152676152677152678152679152680152681152682152683152684152685152686152687152688152689152690152691152692152693152694152695152696152697152698152699152700152701152702152703152704152705152706152707152708152709152710152711152712152713152714152715152716152717152718152719152720152721152722152723152724152725152726152727152728152729152730152731152732152733152734152735152736152737152738152739152740152741152742152743152744152745152746152747152748152749152750152751152752152753152754152755152756152757152758152759152760152761152762152763152764152765152766152767152768152769152770152771152772152773152774152775152776152777152778152779152780152781152782152783152784152785152786152787152788152789152790152791152792152793152794152795152796152797152798152799152800152801152802152803152804152805152806152807152808152809152810152811152812152813152814152815152816152817152818152819152820152821152822152823152824152825152826152827152828152829152830152831152832152833152834152835152836152837152838152839152840152841152842152843152844152845152846152847152848152849152850152851152852152853152854152855152856152857152858152859152860152861152862152863152864152865152866152867152868152869152870152871152872152873152874152875152876152877152878152879152880152881152882152883152884152885152886152887152888152889152890152891152892152893152894152895152896152897152898152899152900152901152902152903152904152905152906152907152908152909152910152911152912152913152914152915152916152917152918152919152920152921152922152923152924152925152926152927152928152929152930152931152932152933152934152935152936152937152938152939152940152941152942152943152944152945152946152947152948152949152950152951152952152953152954152955152956152957152958152959152960152961152962152963152964152965152966152967152968152969152970152971152972152973152974152975152976152977152978152979152980152981152982152983152984152985152986152987152988152989152990152991152992152993152994152995152996152997152998152999153000153001153002153003153004153005153006153007153008153009153010153011153012153013153014153015153016153017153018153019153020153021153022153023153024153025153026153027153028153029153030153031153032153033153034153035153036153037153038153039153040153041153042153043153044153045153046153047153048153049153050153051153052153053153054153055153056153057153058153059153060153061153062153063153064153065153066153067153068153069153070153071153072153073153074153075153076153077153078153079153080153081153082153083153084153085153086153087153088153089153090153091153092153093153094153095153096153097153098153099153100153101153102153103153104153105153106153107153108153109153110153111153112153113153114153115153116153117153118153119153120153121153122153123153124153125153126153127153128153129153130153131153132153133153134153135153136153137153138153139153140153141153142153143153144153145153146153147153148153149153150153151153152153153153154153155153156153157153158153159153160153161153162153163153164153165153166153167153168153169153170153171153172153173153174153175153176153177153178153179153180153181153182153183153184153185153186153187153188153189153190153191153192153193153194153195153196153197153198153199153200153201153202153203153204153205153206153207153208153209153210153211153212153213153214153215153216153217153218153219153220153221153222153223153224153225153226153227153228153229153230153231153232153233153234153235153236153237153238153239153240153241153242153243153244153245153246153247153248153249153250153251153252153253153254153255153256153257153258153259153260153261153262153263153264153265153266153267153268153269153270153271153272153273153274153275153276153277153278153279153280153281153282153283153284153285153286153287153288153289153290153291153292153293153294153295153296153297153298153299153300153301153302153303153304153305153306153307153308153309153310153311153312153313153314153315153316153317153318153319153320153321153322153323153324153325153326153327153328153329153330153331153332153333153334153335153336153337153338153339153340153341153342153343153344153345153346153347153348153349153350153351153352153353153354153355153356153357153358153359153360153361153362153363153364153365153366153367153368153369153370153371153372153373153374153375153376153377153378153379153380153381153382153383153384153385153386153387153388153389153390153391153392153393153394153395153396153397153398153399153400153401153402153403153404153405153406153407153408153409153410153411153412153413153414153415153416153417153418153419153420153421153422153423153424153425153426153427153428153429153430153431153432153433153434153435153436153437153438153439153440153441153442153443153444153445153446153447153448153449153450153451153452153453153454153455153456153457153458153459153460153461153462153463153464153465153466153467153468153469153470153471153472153473153474153475153476153477153478153479153480153481153482153483153484153485153486153487153488153489153490153491153492153493153494153495153496153497153498153499153500153501153502153503153504153505153506153507153508153509153510153511153512153513153514153515153516153517153518153519153520153521153522153523153524153525153526153527153528153529153530153531153532153533153534153535153536153537153538153539153540153541153542153543153544153545153546153547153548153549153550153551153552153553153554153555153556153557153558153559153560153561153562153563153564153565153566153567153568153569153570153571153572153573153574153575153576153577153578153579153580153581153582153583153584153585153586153587153588153589153590153591153592153593153594153595153596153597153598153599153600153601153602153603153604153605153606153607153608153609153610153611153612153613153614153615153616153617153618153619153620153621153622153623153624153625153626153627153628153629153630153631153632153633153634153635153636153637153638153639153640153641153642153643153644153645153646153647153648153649153650153651153652153653153654153655153656153657153658153659153660153661153662153663153664153665153666153667153668153669153670153671153672153673153674153675153676153677153678153679153680153681153682153683153684153685153686153687153688153689153690153691153692153693153694153695153696153697153698153699153700153701153702153703153704153705153706153707153708153709153710153711153712153713153714153715153716153717153718153719153720153721153722153723153724153725153726153727153728153729153730153731153732153733153734153735153736153737153738153739153740153741153742153743153744153745153746153747153748153749153750153751153752153753153754153755153756153757153758153759153760153761153762153763153764153765153766153767153768153769153770153771153772153773153774153775153776153777153778153779153780153781153782153783153784153785153786153787153788153789153790153791153792153793153794153795153796153797153798153799153800153801153802153803153804153805153806153807153808153809153810153811153812153813153814153815153816153817153818153819153820153821153822153823153824153825153826153827153828153829153830153831153832153833153834153835153836153837153838153839153840153841153842153843153844153845153846153847153848153849153850153851153852153853153854153855153856153857153858153859153860153861153862153863153864153865153866153867153868153869153870153871153872153873153874153875153876153877153878153879153880153881153882153883153884153885153886153887153888153889153890153891153892153893153894153895153896153897153898153899153900153901153902153903153904153905153906153907153908153909153910153911153912153913153914153915153916153917153918153919153920153921153922153923153924153925153926153927153928153929153930153931153932153933153934153935153936153937153938153939153940153941153942153943153944153945153946153947153948153949153950153951153952153953153954153955153956153957153958153959153960153961153962153963153964153965153966153967153968153969153970153971153972153973153974153975153976153977153978153979153980153981153982153983153984153985153986153987153988153989153990153991153992153993153994153995153996153997153998153999154000154001154002154003154004154005154006154007154008154009154010154011154012154013154014154015154016154017154018154019154020154021154022154023154024154025154026154027154028154029154030154031154032154033154034154035154036154037154038154039154040154041154042154043154044154045154046154047154048154049154050154051154052154053154054154055154056154057154058154059154060154061154062154063154064154065154066154067154068154069154070154071154072154073154074154075154076154077154078154079154080154081154082154083154084154085154086154087154088154089154090154091154092154093154094154095154096154097154098154099154100154101154102154103154104154105154106154107154108154109154110154111154112154113154114154115154116154117154118154119154120154121154122154123154124154125154126154127154128154129154130154131154132154133154134154135154136154137154138154139154140154141154142154143154144154145154146154147154148154149154150154151154152154153154154154155154156154157154158154159154160154161154162154163154164154165154166154167154168154169154170154171154172154173154174154175154176154177154178154179154180154181154182154183154184154185154186154187154188154189154190154191154192154193154194154195154196154197154198154199154200154201154202154203154204154205154206154207154208154209154210154211154212154213154214154215154216154217154218154219154220154221154222154223154224154225154226154227154228154229154230154231154232154233154234154235154236154237154238154239154240154241154242154243154244154245154246154247154248154249154250154251154252154253154254154255154256154257154258154259154260154261154262154263154264154265154266154267154268154269154270154271154272154273154274154275154276154277154278154279154280154281154282154283154284154285154286154287154288154289154290154291154292154293154294154295154296154297154298154299154300154301154302154303154304154305154306154307154308154309154310154311154312154313154314154315154316154317154318154319154320154321154322154323154324154325154326154327154328154329154330154331154332154333154334154335154336154337154338154339154340154341154342154343154344154345154346154347154348154349154350154351154352154353154354154355154356154357154358154359154360154361154362154363154364154365154366154367154368154369154370154371154372154373154374154375154376154377154378154379154380154381154382154383154384154385154386154387154388154389154390154391154392154393154394154395154396154397154398154399154400154401154402154403154404154405154406154407154408154409154410154411154412154413154414154415154416154417154418154419154420154421154422154423154424154425154426154427154428154429154430154431154432154433154434154435154436154437154438154439154440154441154442154443154444154445154446154447154448154449154450154451154452154453154454154455154456154457154458154459154460154461154462154463154464154465154466154467154468154469154470154471154472154473154474154475154476154477154478154479154480154481154482154483154484154485154486154487154488154489154490154491154492154493154494154495154496154497154498154499154500154501154502154503154504154505154506154507154508154509154510154511154512154513154514154515154516154517154518154519154520154521154522154523154524154525154526154527154528154529154530154531154532154533154534154535154536154537154538154539154540154541154542154543154544154545154546154547154548154549154550154551154552154553154554154555154556154557154558154559154560154561154562154563154564154565154566154567154568154569154570154571154572154573154574154575154576154577154578154579154580154581154582154583154584154585154586154587154588154589154590154591154592154593154594154595154596154597154598154599154600154601154602154603154604154605154606154607154608154609154610154611154612154613154614154615154616154617154618154619154620154621154622154623154624154625154626154627154628154629154630154631154632154633154634154635154636154637154638154639154640154641154642154643154644154645154646154647154648154649154650154651154652154653154654154655154656154657154658154659154660154661154662154663154664154665154666154667154668154669154670154671154672154673154674154675154676154677154678154679154680154681154682154683154684154685154686154687154688154689154690154691154692154693154694154695154696154697154698154699154700154701154702154703154704154705154706154707154708154709154710154711154712154713154714154715154716154717154718154719154720154721154722154723154724154725154726154727154728154729154730154731154732154733154734154735154736154737154738154739154740154741154742154743154744154745154746154747154748154749154750154751154752154753154754154755154756154757154758154759154760154761154762154763154764154765154766154767154768154769154770154771154772154773154774154775154776154777154778154779154780154781154782154783154784154785154786154787154788154789154790154791154792154793154794154795154796154797154798154799154800154801154802154803154804154805154806154807154808154809154810154811154812154813154814154815154816154817154818154819154820154821154822154823154824154825154826154827154828154829154830154831154832154833154834154835154836154837154838154839154840154841154842154843154844154845154846154847154848154849154850154851154852154853154854154855154856154857154858154859154860154861154862154863154864154865154866154867154868154869154870154871154872154873154874154875154876154877154878154879154880154881154882154883154884154885154886154887154888154889154890154891154892154893154894154895154896154897154898154899154900154901154902154903154904154905154906154907154908154909154910154911154912154913154914154915154916154917154918154919154920154921154922154923154924154925154926154927154928154929154930154931154932154933154934154935154936154937154938154939154940154941154942154943154944154945154946154947154948154949154950154951154952154953154954154955154956154957154958154959154960154961154962154963154964154965154966154967154968154969154970154971154972154973154974154975154976154977154978154979154980154981154982154983154984154985154986154987154988154989154990154991154992154993154994154995154996154997154998154999155000155001155002155003155004155005155006155007155008155009155010155011155012155013155014155015155016155017155018155019155020155021155022155023155024155025155026155027155028155029155030155031155032155033155034155035155036155037155038155039155040155041155042155043155044155045155046155047155048155049155050155051155052155053155054155055155056155057155058155059155060155061155062155063155064155065155066155067155068155069155070155071155072155073155074155075155076155077155078155079155080155081155082155083155084155085155086155087155088155089155090155091155092155093155094155095155096155097155098155099155100155101155102155103155104155105155106155107155108155109155110155111155112155113155114155115155116155117155118155119155120155121155122155123155124155125155126155127155128155129155130155131155132155133155134155135155136155137155138155139155140155141155142155143155144155145155146155147155148155149155150155151155152155153155154155155155156155157155158155159155160155161155162155163155164155165155166155167155168155169155170155171155172155173155174155175155176155177155178155179155180155181155182155183155184155185155186155187155188155189155190155191155192155193155194155195155196155197155198155199155200155201155202155203155204155205155206155207155208155209155210155211155212155213155214155215155216155217155218155219155220155221155222155223155224155225155226155227155228155229155230155231155232155233155234155235155236155237155238155239155240155241155242155243155244155245155246155247155248155249155250155251155252155253155254155255155256155257155258155259155260155261155262155263155264155265155266155267155268155269155270155271155272155273155274155275155276155277155278155279155280155281155282155283155284155285155286155287155288155289155290155291155292155293155294155295155296155297155298155299155300155301155302155303155304155305155306155307155308155309155310155311155312155313155314155315155316155317155318155319155320155321155322155323155324155325155326155327155328155329155330155331155332155333155334155335155336155337155338155339155340155341155342155343155344155345155346155347155348155349155350155351155352155353155354155355155356155357155358155359155360155361155362155363155364155365155366155367155368155369155370155371155372155373155374155375155376155377155378155379155380155381155382155383155384155385155386155387155388155389155390155391155392155393155394155395155396155397155398155399155400155401155402155403155404155405155406155407155408155409155410155411155412155413155414155415155416155417155418155419155420155421155422155423155424155425155426155427155428155429155430155431155432155433155434155435155436155437155438155439155440155441155442155443155444155445155446155447155448155449155450155451155452155453155454155455155456155457155458155459155460155461155462155463155464155465155466155467155468155469155470155471155472155473155474155475155476155477155478155479155480155481155482155483155484155485155486155487155488155489155490155491155492155493155494155495155496155497155498155499155500155501155502155503155504155505155506155507155508155509155510155511155512155513155514155515155516155517155518155519155520155521155522155523155524155525155526155527155528155529155530155531155532155533155534155535155536155537155538155539155540155541155542155543155544155545155546155547155548155549155550155551155552155553155554155555155556155557155558155559155560155561155562155563155564155565155566155567155568155569155570155571155572155573155574155575155576155577155578155579155580155581155582155583155584155585155586155587155588155589155590155591155592155593155594155595155596155597155598155599155600155601155602155603155604155605155606155607155608155609155610155611155612155613155614155615155616155617155618155619155620155621155622155623155624155625155626155627155628155629155630155631155632155633155634155635155636155637155638155639155640155641155642155643155644155645155646155647155648155649155650155651155652155653155654155655155656155657155658155659155660155661155662155663155664155665155666155667155668155669155670155671155672155673155674155675155676155677155678155679155680155681155682155683155684155685155686155687155688155689155690155691155692155693155694155695155696155697155698155699155700155701155702155703155704155705155706155707155708155709155710155711155712155713155714155715155716155717155718155719155720155721155722155723155724155725155726155727155728155729155730155731155732155733155734155735155736155737155738155739155740155741155742155743155744155745155746155747155748155749155750155751155752155753155754155755155756155757155758155759155760155761155762155763155764155765155766155767155768155769155770155771155772155773155774155775155776155777155778155779155780155781155782155783155784155785155786155787155788155789155790155791155792155793155794155795155796155797155798155799155800155801155802155803155804155805155806155807155808155809155810155811155812155813155814155815155816155817155818155819155820155821155822155823155824155825155826155827155828155829155830155831155832155833155834155835155836155837155838155839155840155841155842155843155844155845155846155847155848155849155850155851155852155853155854155855155856155857155858155859155860155861155862155863155864155865155866
  1. /******************************************************************************
  2. ** This file is an amalgamation of many separate C source files from SQLite
  3. ** version 3.8.10.2. By combining all the individual C code files into this
  4. ** single large file, the entire code can be compiled as a single translation
  5. ** unit. This allows many compilers to do optimizations that would not be
  6. ** possible if the files were compiled separately. Performance improvements
  7. ** of 5% or more are commonly seen when SQLite is compiled as a single
  8. ** translation unit.
  9. **
  10. ** This file is all you need to compile SQLite. To use SQLite in other
  11. ** programs, you need this file and the "sqlite3.h" header file that defines
  12. ** the programming interface to the SQLite library. (If you do not have
  13. ** the "sqlite3.h" header file at hand, you will find a copy embedded within
  14. ** the text of this file. Search for "Begin file sqlite3.h" to find the start
  15. ** of the embedded sqlite3.h header file.) Additional code files may be needed
  16. ** if you want a wrapper to interface SQLite with your choice of programming
  17. ** language. The code for the "sqlite3" command-line shell is also in a
  18. ** separate file. This file contains only code for the core SQLite library.
  19. */
  20. #define SQLITE_CORE 1
  21. #define SQLITE_AMALGAMATION 1
  22. #ifndef SQLITE_PRIVATE
  23. # define SQLITE_PRIVATE static
  24. #endif
  25. /************** Begin file sqliteInt.h ***************************************/
  26. /*
  27. ** 2001 September 15
  28. **
  29. ** The author disclaims copyright to this source code. In place of
  30. ** a legal notice, here is a blessing:
  31. **
  32. ** May you do good and not evil.
  33. ** May you find forgiveness for yourself and forgive others.
  34. ** May you share freely, never taking more than you give.
  35. **
  36. *************************************************************************
  37. ** Internal interface definitions for SQLite.
  38. **
  39. */
  40. #ifndef _SQLITEINT_H_
  41. #define _SQLITEINT_H_
  42. /*
  43. ** Include the header file used to customize the compiler options for MSVC.
  44. ** This should be done first so that it can successfully prevent spurious
  45. ** compiler warnings due to subsequent content in this file and other files
  46. ** that are included by this file.
  47. */
  48. /************** Include msvc.h in the middle of sqliteInt.h ******************/
  49. /************** Begin file msvc.h ********************************************/
  50. /*
  51. ** 2015 January 12
  52. **
  53. ** The author disclaims copyright to this source code. In place of
  54. ** a legal notice, here is a blessing:
  55. **
  56. ** May you do good and not evil.
  57. ** May you find forgiveness for yourself and forgive others.
  58. ** May you share freely, never taking more than you give.
  59. **
  60. ******************************************************************************
  61. **
  62. ** This file contains code that is specific to MSVC.
  63. */
  64. #ifndef _MSVC_H_
  65. #define _MSVC_H_
  66. #if defined(_MSC_VER)
  67. #pragma warning(disable : 4054)
  68. #pragma warning(disable : 4055)
  69. #pragma warning(disable : 4100)
  70. #pragma warning(disable : 4127)
  71. #pragma warning(disable : 4130)
  72. #pragma warning(disable : 4152)
  73. #pragma warning(disable : 4189)
  74. #pragma warning(disable : 4206)
  75. #pragma warning(disable : 4210)
  76. #pragma warning(disable : 4232)
  77. #pragma warning(disable : 4244)
  78. #pragma warning(disable : 4305)
  79. #pragma warning(disable : 4306)
  80. #pragma warning(disable : 4702)
  81. #pragma warning(disable : 4706)
  82. #endif /* defined(_MSC_VER) */
  83. #endif /* _MSVC_H_ */
  84. /************** End of msvc.h ************************************************/
  85. /************** Continuing where we left off in sqliteInt.h ******************/
  86. /*
  87. ** Special setup for VxWorks
  88. */
  89. /************** Include vxworks.h in the middle of sqliteInt.h ***************/
  90. /************** Begin file vxworks.h *****************************************/
  91. /*
  92. ** 2015-03-02
  93. **
  94. ** The author disclaims copyright to this source code. In place of
  95. ** a legal notice, here is a blessing:
  96. **
  97. ** May you do good and not evil.
  98. ** May you find forgiveness for yourself and forgive others.
  99. ** May you share freely, never taking more than you give.
  100. **
  101. ******************************************************************************
  102. **
  103. ** This file contains code that is specific to Wind River's VxWorks
  104. */
  105. #if defined(__RTP__) || defined(_WRS_KERNEL)
  106. /* This is VxWorks. Set up things specially for that OS
  107. */
  108. #include <vxWorks.h>
  109. #include <pthread.h> /* amalgamator: dontcache */
  110. #define OS_VXWORKS 1
  111. #define SQLITE_OS_OTHER 0
  112. #define SQLITE_HOMEGROWN_RECURSIVE_MUTEX 1
  113. #define SQLITE_OMIT_LOAD_EXTENSION 1
  114. #define SQLITE_ENABLE_LOCKING_STYLE 0
  115. #define HAVE_UTIME 1
  116. #else
  117. /* This is not VxWorks. */
  118. #define OS_VXWORKS 0
  119. #endif /* defined(_WRS_KERNEL) */
  120. /************** End of vxworks.h *********************************************/
  121. /************** Continuing where we left off in sqliteInt.h ******************/
  122. /*
  123. ** These #defines should enable >2GB file support on POSIX if the
  124. ** underlying operating system supports it. If the OS lacks
  125. ** large file support, or if the OS is windows, these should be no-ops.
  126. **
  127. ** Ticket #2739: The _LARGEFILE_SOURCE macro must appear before any
  128. ** system #includes. Hence, this block of code must be the very first
  129. ** code in all source files.
  130. **
  131. ** Large file support can be disabled using the -DSQLITE_DISABLE_LFS switch
  132. ** on the compiler command line. This is necessary if you are compiling
  133. ** on a recent machine (ex: Red Hat 7.2) but you want your code to work
  134. ** on an older machine (ex: Red Hat 6.0). If you compile on Red Hat 7.2
  135. ** without this option, LFS is enable. But LFS does not exist in the kernel
  136. ** in Red Hat 6.0, so the code won't work. Hence, for maximum binary
  137. ** portability you should omit LFS.
  138. **
  139. ** The previous paragraph was written in 2005. (This paragraph is written
  140. ** on 2008-11-28.) These days, all Linux kernels support large files, so
  141. ** you should probably leave LFS enabled. But some embedded platforms might
  142. ** lack LFS in which case the SQLITE_DISABLE_LFS macro might still be useful.
  143. **
  144. ** Similar is true for Mac OS X. LFS is only supported on Mac OS X 9 and later.
  145. */
  146. #ifndef SQLITE_DISABLE_LFS
  147. # define _LARGE_FILE 1
  148. # ifndef _FILE_OFFSET_BITS
  149. # define _FILE_OFFSET_BITS 64
  150. # endif
  151. # define _LARGEFILE_SOURCE 1
  152. #endif
  153. /* Needed for various definitions... */
  154. #if defined(__GNUC__) && !defined(_GNU_SOURCE)
  155. # define _GNU_SOURCE
  156. #endif
  157. #if defined(__OpenBSD__) && !defined(_BSD_SOURCE)
  158. # define _BSD_SOURCE
  159. #endif
  160. /*
  161. ** For MinGW, check to see if we can include the header file containing its
  162. ** version information, among other things. Normally, this internal MinGW
  163. ** header file would [only] be included automatically by other MinGW header
  164. ** files; however, the contained version information is now required by this
  165. ** header file to work around binary compatibility issues (see below) and
  166. ** this is the only known way to reliably obtain it. This entire #if block
  167. ** would be completely unnecessary if there was any other way of detecting
  168. ** MinGW via their preprocessor (e.g. if they customized their GCC to define
  169. ** some MinGW-specific macros). When compiling for MinGW, either the
  170. ** _HAVE_MINGW_H or _HAVE__MINGW_H (note the extra underscore) macro must be
  171. ** defined; otherwise, detection of conditions specific to MinGW will be
  172. ** disabled.
  173. */
  174. #if defined(_HAVE_MINGW_H)
  175. # include "mingw.h"
  176. #elif defined(_HAVE__MINGW_H)
  177. # include "_mingw.h"
  178. #endif
  179. /*
  180. ** For MinGW version 4.x (and higher), check to see if the _USE_32BIT_TIME_T
  181. ** define is required to maintain binary compatibility with the MSVC runtime
  182. ** library in use (e.g. for Windows XP).
  183. */
  184. #if !defined(_USE_32BIT_TIME_T) && !defined(_USE_64BIT_TIME_T) && \
  185. defined(_WIN32) && !defined(_WIN64) && \
  186. defined(__MINGW_MAJOR_VERSION) && __MINGW_MAJOR_VERSION >= 4 && \
  187. defined(__MSVCRT__)
  188. # define _USE_32BIT_TIME_T
  189. #endif
  190. /* The public SQLite interface. The _FILE_OFFSET_BITS macro must appear
  191. ** first in QNX. Also, the _USE_32BIT_TIME_T macro must appear first for
  192. ** MinGW.
  193. */
  194. /************** Include sqlite3.h in the middle of sqliteInt.h ***************/
  195. /************** Begin file sqlite3.h *****************************************/
  196. /*
  197. ** 2001 September 15
  198. **
  199. ** The author disclaims copyright to this source code. In place of
  200. ** a legal notice, here is a blessing:
  201. **
  202. ** May you do good and not evil.
  203. ** May you find forgiveness for yourself and forgive others.
  204. ** May you share freely, never taking more than you give.
  205. **
  206. *************************************************************************
  207. ** This header file defines the interface that the SQLite library
  208. ** presents to client programs. If a C-function, structure, datatype,
  209. ** or constant definition does not appear in this file, then it is
  210. ** not a published API of SQLite, is subject to change without
  211. ** notice, and should not be referenced by programs that use SQLite.
  212. **
  213. ** Some of the definitions that are in this file are marked as
  214. ** "experimental". Experimental interfaces are normally new
  215. ** features recently added to SQLite. We do not anticipate changes
  216. ** to experimental interfaces but reserve the right to make minor changes
  217. ** if experience from use "in the wild" suggest such changes are prudent.
  218. **
  219. ** The official C-language API documentation for SQLite is derived
  220. ** from comments in this file. This file is the authoritative source
  221. ** on how SQLite interfaces are suppose to operate.
  222. **
  223. ** The name of this file under configuration management is "sqlite.h.in".
  224. ** The makefile makes some minor changes to this file (such as inserting
  225. ** the version number) and changes its name to "sqlite3.h" as
  226. ** part of the build process.
  227. */
  228. #ifndef _SQLITE3_H_
  229. #define _SQLITE3_H_
  230. #include <stdarg.h> /* Needed for the definition of va_list */
  231. /*
  232. ** Make sure we can call this stuff from C++.
  233. */
  234. #if 0
  235. extern "C" {
  236. #endif
  237. /*
  238. ** Provide the ability to override linkage features of the interface.
  239. */
  240. #ifndef SQLITE_EXTERN
  241. # define SQLITE_EXTERN extern
  242. #endif
  243. #ifndef SQLITE_API
  244. # define SQLITE_API
  245. #endif
  246. #ifndef SQLITE_CDECL
  247. # define SQLITE_CDECL
  248. #endif
  249. #ifndef SQLITE_STDCALL
  250. # define SQLITE_STDCALL
  251. #endif
  252. /*
  253. ** These no-op macros are used in front of interfaces to mark those
  254. ** interfaces as either deprecated or experimental. New applications
  255. ** should not use deprecated interfaces - they are supported for backwards
  256. ** compatibility only. Application writers should be aware that
  257. ** experimental interfaces are subject to change in point releases.
  258. **
  259. ** These macros used to resolve to various kinds of compiler magic that
  260. ** would generate warning messages when they were used. But that
  261. ** compiler magic ended up generating such a flurry of bug reports
  262. ** that we have taken it all out and gone back to using simple
  263. ** noop macros.
  264. */
  265. #define SQLITE_DEPRECATED
  266. #define SQLITE_EXPERIMENTAL
  267. /*
  268. ** Ensure these symbols were not defined by some previous header file.
  269. */
  270. #ifdef SQLITE_VERSION
  271. # undef SQLITE_VERSION
  272. #endif
  273. #ifdef SQLITE_VERSION_NUMBER
  274. # undef SQLITE_VERSION_NUMBER
  275. #endif
  276. /*
  277. ** CAPI3REF: Compile-Time Library Version Numbers
  278. **
  279. ** ^(The [SQLITE_VERSION] C preprocessor macro in the sqlite3.h header
  280. ** evaluates to a string literal that is the SQLite version in the
  281. ** format "X.Y.Z" where X is the major version number (always 3 for
  282. ** SQLite3) and Y is the minor version number and Z is the release number.)^
  283. ** ^(The [SQLITE_VERSION_NUMBER] C preprocessor macro resolves to an integer
  284. ** with the value (X*1000000 + Y*1000 + Z) where X, Y, and Z are the same
  285. ** numbers used in [SQLITE_VERSION].)^
  286. ** The SQLITE_VERSION_NUMBER for any given release of SQLite will also
  287. ** be larger than the release from which it is derived. Either Y will
  288. ** be held constant and Z will be incremented or else Y will be incremented
  289. ** and Z will be reset to zero.
  290. **
  291. ** Since version 3.6.18, SQLite source code has been stored in the
  292. ** <a href="http://www.fossil-scm.org/">Fossil configuration management
  293. ** system</a>. ^The SQLITE_SOURCE_ID macro evaluates to
  294. ** a string which identifies a particular check-in of SQLite
  295. ** within its configuration management system. ^The SQLITE_SOURCE_ID
  296. ** string contains the date and time of the check-in (UTC) and an SHA1
  297. ** hash of the entire source tree.
  298. **
  299. ** See also: [sqlite3_libversion()],
  300. ** [sqlite3_libversion_number()], [sqlite3_sourceid()],
  301. ** [sqlite_version()] and [sqlite_source_id()].
  302. */
  303. #define SQLITE_VERSION "3.8.10.2"
  304. #define SQLITE_VERSION_NUMBER 3008010
  305. #define SQLITE_SOURCE_ID "2015-05-20 18:17:19 2ef4f3a5b1d1d0c4338f8243d40a2452cc1f7fe4"
  306. /*
  307. ** CAPI3REF: Run-Time Library Version Numbers
  308. ** KEYWORDS: sqlite3_version, sqlite3_sourceid
  309. **
  310. ** These interfaces provide the same information as the [SQLITE_VERSION],
  311. ** [SQLITE_VERSION_NUMBER], and [SQLITE_SOURCE_ID] C preprocessor macros
  312. ** but are associated with the library instead of the header file. ^(Cautious
  313. ** programmers might include assert() statements in their application to
  314. ** verify that values returned by these interfaces match the macros in
  315. ** the header, and thus insure that the application is
  316. ** compiled with matching library and header files.
  317. **
  318. ** <blockquote><pre>
  319. ** assert( sqlite3_libversion_number()==SQLITE_VERSION_NUMBER );
  320. ** assert( strcmp(sqlite3_sourceid(),SQLITE_SOURCE_ID)==0 );
  321. ** assert( strcmp(sqlite3_libversion(),SQLITE_VERSION)==0 );
  322. ** </pre></blockquote>)^
  323. **
  324. ** ^The sqlite3_version[] string constant contains the text of [SQLITE_VERSION]
  325. ** macro. ^The sqlite3_libversion() function returns a pointer to the
  326. ** to the sqlite3_version[] string constant. The sqlite3_libversion()
  327. ** function is provided for use in DLLs since DLL users usually do not have
  328. ** direct access to string constants within the DLL. ^The
  329. ** sqlite3_libversion_number() function returns an integer equal to
  330. ** [SQLITE_VERSION_NUMBER]. ^The sqlite3_sourceid() function returns
  331. ** a pointer to a string constant whose value is the same as the
  332. ** [SQLITE_SOURCE_ID] C preprocessor macro.
  333. **
  334. ** See also: [sqlite_version()] and [sqlite_source_id()].
  335. */
  336. SQLITE_API const char sqlite3_version[] = SQLITE_VERSION;
  337. SQLITE_API const char *SQLITE_STDCALL sqlite3_libversion(void);
  338. SQLITE_API const char *SQLITE_STDCALL sqlite3_sourceid(void);
  339. SQLITE_API int SQLITE_STDCALL sqlite3_libversion_number(void);
  340. /*
  341. ** CAPI3REF: Run-Time Library Compilation Options Diagnostics
  342. **
  343. ** ^The sqlite3_compileoption_used() function returns 0 or 1
  344. ** indicating whether the specified option was defined at
  345. ** compile time. ^The SQLITE_ prefix may be omitted from the
  346. ** option name passed to sqlite3_compileoption_used().
  347. **
  348. ** ^The sqlite3_compileoption_get() function allows iterating
  349. ** over the list of options that were defined at compile time by
  350. ** returning the N-th compile time option string. ^If N is out of range,
  351. ** sqlite3_compileoption_get() returns a NULL pointer. ^The SQLITE_
  352. ** prefix is omitted from any strings returned by
  353. ** sqlite3_compileoption_get().
  354. **
  355. ** ^Support for the diagnostic functions sqlite3_compileoption_used()
  356. ** and sqlite3_compileoption_get() may be omitted by specifying the
  357. ** [SQLITE_OMIT_COMPILEOPTION_DIAGS] option at compile time.
  358. **
  359. ** See also: SQL functions [sqlite_compileoption_used()] and
  360. ** [sqlite_compileoption_get()] and the [compile_options pragma].
  361. */
  362. #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
  363. SQLITE_API int SQLITE_STDCALL sqlite3_compileoption_used(const char *zOptName);
  364. SQLITE_API const char *SQLITE_STDCALL sqlite3_compileoption_get(int N);
  365. #endif
  366. /*
  367. ** CAPI3REF: Test To See If The Library Is Threadsafe
  368. **
  369. ** ^The sqlite3_threadsafe() function returns zero if and only if
  370. ** SQLite was compiled with mutexing code omitted due to the
  371. ** [SQLITE_THREADSAFE] compile-time option being set to 0.
  372. **
  373. ** SQLite can be compiled with or without mutexes. When
  374. ** the [SQLITE_THREADSAFE] C preprocessor macro is 1 or 2, mutexes
  375. ** are enabled and SQLite is threadsafe. When the
  376. ** [SQLITE_THREADSAFE] macro is 0,
  377. ** the mutexes are omitted. Without the mutexes, it is not safe
  378. ** to use SQLite concurrently from more than one thread.
  379. **
  380. ** Enabling mutexes incurs a measurable performance penalty.
  381. ** So if speed is of utmost importance, it makes sense to disable
  382. ** the mutexes. But for maximum safety, mutexes should be enabled.
  383. ** ^The default behavior is for mutexes to be enabled.
  384. **
  385. ** This interface can be used by an application to make sure that the
  386. ** version of SQLite that it is linking against was compiled with
  387. ** the desired setting of the [SQLITE_THREADSAFE] macro.
  388. **
  389. ** This interface only reports on the compile-time mutex setting
  390. ** of the [SQLITE_THREADSAFE] flag. If SQLite is compiled with
  391. ** SQLITE_THREADSAFE=1 or =2 then mutexes are enabled by default but
  392. ** can be fully or partially disabled using a call to [sqlite3_config()]
  393. ** with the verbs [SQLITE_CONFIG_SINGLETHREAD], [SQLITE_CONFIG_MULTITHREAD],
  394. ** or [SQLITE_CONFIG_SERIALIZED]. ^(The return value of the
  395. ** sqlite3_threadsafe() function shows only the compile-time setting of
  396. ** thread safety, not any run-time changes to that setting made by
  397. ** sqlite3_config(). In other words, the return value from sqlite3_threadsafe()
  398. ** is unchanged by calls to sqlite3_config().)^
  399. **
  400. ** See the [threading mode] documentation for additional information.
  401. */
  402. SQLITE_API int SQLITE_STDCALL sqlite3_threadsafe(void);
  403. /*
  404. ** CAPI3REF: Database Connection Handle
  405. ** KEYWORDS: {database connection} {database connections}
  406. **
  407. ** Each open SQLite database is represented by a pointer to an instance of
  408. ** the opaque structure named "sqlite3". It is useful to think of an sqlite3
  409. ** pointer as an object. The [sqlite3_open()], [sqlite3_open16()], and
  410. ** [sqlite3_open_v2()] interfaces are its constructors, and [sqlite3_close()]
  411. ** and [sqlite3_close_v2()] are its destructors. There are many other
  412. ** interfaces (such as
  413. ** [sqlite3_prepare_v2()], [sqlite3_create_function()], and
  414. ** [sqlite3_busy_timeout()] to name but three) that are methods on an
  415. ** sqlite3 object.
  416. */
  417. typedef struct sqlite3 sqlite3;
  418. /*
  419. ** CAPI3REF: 64-Bit Integer Types
  420. ** KEYWORDS: sqlite_int64 sqlite_uint64
  421. **
  422. ** Because there is no cross-platform way to specify 64-bit integer types
  423. ** SQLite includes typedefs for 64-bit signed and unsigned integers.
  424. **
  425. ** The sqlite3_int64 and sqlite3_uint64 are the preferred type definitions.
  426. ** The sqlite_int64 and sqlite_uint64 types are supported for backwards
  427. ** compatibility only.
  428. **
  429. ** ^The sqlite3_int64 and sqlite_int64 types can store integer values
  430. ** between -9223372036854775808 and +9223372036854775807 inclusive. ^The
  431. ** sqlite3_uint64 and sqlite_uint64 types can store integer values
  432. ** between 0 and +18446744073709551615 inclusive.
  433. */
  434. #ifdef SQLITE_INT64_TYPE
  435. typedef SQLITE_INT64_TYPE sqlite_int64;
  436. typedef unsigned SQLITE_INT64_TYPE sqlite_uint64;
  437. #elif defined(_MSC_VER) || defined(__BORLANDC__)
  438. typedef __int64 sqlite_int64;
  439. typedef unsigned __int64 sqlite_uint64;
  440. #else
  441. typedef long long int sqlite_int64;
  442. typedef unsigned long long int sqlite_uint64;
  443. #endif
  444. typedef sqlite_int64 sqlite3_int64;
  445. typedef sqlite_uint64 sqlite3_uint64;
  446. /*
  447. ** If compiling for a processor that lacks floating point support,
  448. ** substitute integer for floating-point.
  449. */
  450. #ifdef SQLITE_OMIT_FLOATING_POINT
  451. # define double sqlite3_int64
  452. #endif
  453. /*
  454. ** CAPI3REF: Closing A Database Connection
  455. ** DESTRUCTOR: sqlite3
  456. **
  457. ** ^The sqlite3_close() and sqlite3_close_v2() routines are destructors
  458. ** for the [sqlite3] object.
  459. ** ^Calls to sqlite3_close() and sqlite3_close_v2() return [SQLITE_OK] if
  460. ** the [sqlite3] object is successfully destroyed and all associated
  461. ** resources are deallocated.
  462. **
  463. ** ^If the database connection is associated with unfinalized prepared
  464. ** statements or unfinished sqlite3_backup objects then sqlite3_close()
  465. ** will leave the database connection open and return [SQLITE_BUSY].
  466. ** ^If sqlite3_close_v2() is called with unfinalized prepared statements
  467. ** and/or unfinished sqlite3_backups, then the database connection becomes
  468. ** an unusable "zombie" which will automatically be deallocated when the
  469. ** last prepared statement is finalized or the last sqlite3_backup is
  470. ** finished. The sqlite3_close_v2() interface is intended for use with
  471. ** host languages that are garbage collected, and where the order in which
  472. ** destructors are called is arbitrary.
  473. **
  474. ** Applications should [sqlite3_finalize | finalize] all [prepared statements],
  475. ** [sqlite3_blob_close | close] all [BLOB handles], and
  476. ** [sqlite3_backup_finish | finish] all [sqlite3_backup] objects associated
  477. ** with the [sqlite3] object prior to attempting to close the object. ^If
  478. ** sqlite3_close_v2() is called on a [database connection] that still has
  479. ** outstanding [prepared statements], [BLOB handles], and/or
  480. ** [sqlite3_backup] objects then it returns [SQLITE_OK] and the deallocation
  481. ** of resources is deferred until all [prepared statements], [BLOB handles],
  482. ** and [sqlite3_backup] objects are also destroyed.
  483. **
  484. ** ^If an [sqlite3] object is destroyed while a transaction is open,
  485. ** the transaction is automatically rolled back.
  486. **
  487. ** The C parameter to [sqlite3_close(C)] and [sqlite3_close_v2(C)]
  488. ** must be either a NULL
  489. ** pointer or an [sqlite3] object pointer obtained
  490. ** from [sqlite3_open()], [sqlite3_open16()], or
  491. ** [sqlite3_open_v2()], and not previously closed.
  492. ** ^Calling sqlite3_close() or sqlite3_close_v2() with a NULL pointer
  493. ** argument is a harmless no-op.
  494. */
  495. SQLITE_API int SQLITE_STDCALL sqlite3_close(sqlite3*);
  496. SQLITE_API int SQLITE_STDCALL sqlite3_close_v2(sqlite3*);
  497. /*
  498. ** The type for a callback function.
  499. ** This is legacy and deprecated. It is included for historical
  500. ** compatibility and is not documented.
  501. */
  502. typedef int (*sqlite3_callback)(void*,int,char**, char**);
  503. /*
  504. ** CAPI3REF: One-Step Query Execution Interface
  505. ** METHOD: sqlite3
  506. **
  507. ** The sqlite3_exec() interface is a convenience wrapper around
  508. ** [sqlite3_prepare_v2()], [sqlite3_step()], and [sqlite3_finalize()],
  509. ** that allows an application to run multiple statements of SQL
  510. ** without having to use a lot of C code.
  511. **
  512. ** ^The sqlite3_exec() interface runs zero or more UTF-8 encoded,
  513. ** semicolon-separate SQL statements passed into its 2nd argument,
  514. ** in the context of the [database connection] passed in as its 1st
  515. ** argument. ^If the callback function of the 3rd argument to
  516. ** sqlite3_exec() is not NULL, then it is invoked for each result row
  517. ** coming out of the evaluated SQL statements. ^The 4th argument to
  518. ** sqlite3_exec() is relayed through to the 1st argument of each
  519. ** callback invocation. ^If the callback pointer to sqlite3_exec()
  520. ** is NULL, then no callback is ever invoked and result rows are
  521. ** ignored.
  522. **
  523. ** ^If an error occurs while evaluating the SQL statements passed into
  524. ** sqlite3_exec(), then execution of the current statement stops and
  525. ** subsequent statements are skipped. ^If the 5th parameter to sqlite3_exec()
  526. ** is not NULL then any error message is written into memory obtained
  527. ** from [sqlite3_malloc()] and passed back through the 5th parameter.
  528. ** To avoid memory leaks, the application should invoke [sqlite3_free()]
  529. ** on error message strings returned through the 5th parameter of
  530. ** of sqlite3_exec() after the error message string is no longer needed.
  531. ** ^If the 5th parameter to sqlite3_exec() is not NULL and no errors
  532. ** occur, then sqlite3_exec() sets the pointer in its 5th parameter to
  533. ** NULL before returning.
  534. **
  535. ** ^If an sqlite3_exec() callback returns non-zero, the sqlite3_exec()
  536. ** routine returns SQLITE_ABORT without invoking the callback again and
  537. ** without running any subsequent SQL statements.
  538. **
  539. ** ^The 2nd argument to the sqlite3_exec() callback function is the
  540. ** number of columns in the result. ^The 3rd argument to the sqlite3_exec()
  541. ** callback is an array of pointers to strings obtained as if from
  542. ** [sqlite3_column_text()], one for each column. ^If an element of a
  543. ** result row is NULL then the corresponding string pointer for the
  544. ** sqlite3_exec() callback is a NULL pointer. ^The 4th argument to the
  545. ** sqlite3_exec() callback is an array of pointers to strings where each
  546. ** entry represents the name of corresponding result column as obtained
  547. ** from [sqlite3_column_name()].
  548. **
  549. ** ^If the 2nd parameter to sqlite3_exec() is a NULL pointer, a pointer
  550. ** to an empty string, or a pointer that contains only whitespace and/or
  551. ** SQL comments, then no SQL statements are evaluated and the database
  552. ** is not changed.
  553. **
  554. ** Restrictions:
  555. **
  556. ** <ul>
  557. ** <li> The application must insure that the 1st parameter to sqlite3_exec()
  558. ** is a valid and open [database connection].
  559. ** <li> The application must not close the [database connection] specified by
  560. ** the 1st parameter to sqlite3_exec() while sqlite3_exec() is running.
  561. ** <li> The application must not modify the SQL statement text passed into
  562. ** the 2nd parameter of sqlite3_exec() while sqlite3_exec() is running.
  563. ** </ul>
  564. */
  565. SQLITE_API int SQLITE_STDCALL sqlite3_exec(
  566. sqlite3*, /* An open database */
  567. const char *sql, /* SQL to be evaluated */
  568. int (*callback)(void*,int,char**,char**), /* Callback function */
  569. void *, /* 1st argument to callback */
  570. char **errmsg /* Error msg written here */
  571. );
  572. /*
  573. ** CAPI3REF: Result Codes
  574. ** KEYWORDS: {result code definitions}
  575. **
  576. ** Many SQLite functions return an integer result code from the set shown
  577. ** here in order to indicate success or failure.
  578. **
  579. ** New error codes may be added in future versions of SQLite.
  580. **
  581. ** See also: [extended result code definitions]
  582. */
  583. #define SQLITE_OK 0 /* Successful result */
  584. /* beginning-of-error-codes */
  585. #define SQLITE_ERROR 1 /* SQL error or missing database */
  586. #define SQLITE_INTERNAL 2 /* Internal logic error in SQLite */
  587. #define SQLITE_PERM 3 /* Access permission denied */
  588. #define SQLITE_ABORT 4 /* Callback routine requested an abort */
  589. #define SQLITE_BUSY 5 /* The database file is locked */
  590. #define SQLITE_LOCKED 6 /* A table in the database is locked */
  591. #define SQLITE_NOMEM 7 /* A malloc() failed */
  592. #define SQLITE_READONLY 8 /* Attempt to write a readonly database */
  593. #define SQLITE_INTERRUPT 9 /* Operation terminated by sqlite3_interrupt()*/
  594. #define SQLITE_IOERR 10 /* Some kind of disk I/O error occurred */
  595. #define SQLITE_CORRUPT 11 /* The database disk image is malformed */
  596. #define SQLITE_NOTFOUND 12 /* Unknown opcode in sqlite3_file_control() */
  597. #define SQLITE_FULL 13 /* Insertion failed because database is full */
  598. #define SQLITE_CANTOPEN 14 /* Unable to open the database file */
  599. #define SQLITE_PROTOCOL 15 /* Database lock protocol error */
  600. #define SQLITE_EMPTY 16 /* Database is empty */
  601. #define SQLITE_SCHEMA 17 /* The database schema changed */
  602. #define SQLITE_TOOBIG 18 /* String or BLOB exceeds size limit */
  603. #define SQLITE_CONSTRAINT 19 /* Abort due to constraint violation */
  604. #define SQLITE_MISMATCH 20 /* Data type mismatch */
  605. #define SQLITE_MISUSE 21 /* Library used incorrectly */
  606. #define SQLITE_NOLFS 22 /* Uses OS features not supported on host */
  607. #define SQLITE_AUTH 23 /* Authorization denied */
  608. #define SQLITE_FORMAT 24 /* Auxiliary database format error */
  609. #define SQLITE_RANGE 25 /* 2nd parameter to sqlite3_bind out of range */
  610. #define SQLITE_NOTADB 26 /* File opened that is not a database file */
  611. #define SQLITE_NOTICE 27 /* Notifications from sqlite3_log() */
  612. #define SQLITE_WARNING 28 /* Warnings from sqlite3_log() */
  613. #define SQLITE_ROW 100 /* sqlite3_step() has another row ready */
  614. #define SQLITE_DONE 101 /* sqlite3_step() has finished executing */
  615. /* end-of-error-codes */
  616. /*
  617. ** CAPI3REF: Extended Result Codes
  618. ** KEYWORDS: {extended result code definitions}
  619. **
  620. ** In its default configuration, SQLite API routines return one of 30 integer
  621. ** [result codes]. However, experience has shown that many of
  622. ** these result codes are too coarse-grained. They do not provide as
  623. ** much information about problems as programmers might like. In an effort to
  624. ** address this, newer versions of SQLite (version 3.3.8 and later) include
  625. ** support for additional result codes that provide more detailed information
  626. ** about errors. These [extended result codes] are enabled or disabled
  627. ** on a per database connection basis using the
  628. ** [sqlite3_extended_result_codes()] API. Or, the extended code for
  629. ** the most recent error can be obtained using
  630. ** [sqlite3_extended_errcode()].
  631. */
  632. #define SQLITE_IOERR_READ (SQLITE_IOERR | (1<<8))
  633. #define SQLITE_IOERR_SHORT_READ (SQLITE_IOERR | (2<<8))
  634. #define SQLITE_IOERR_WRITE (SQLITE_IOERR | (3<<8))
  635. #define SQLITE_IOERR_FSYNC (SQLITE_IOERR | (4<<8))
  636. #define SQLITE_IOERR_DIR_FSYNC (SQLITE_IOERR | (5<<8))
  637. #define SQLITE_IOERR_TRUNCATE (SQLITE_IOERR | (6<<8))
  638. #define SQLITE_IOERR_FSTAT (SQLITE_IOERR | (7<<8))
  639. #define SQLITE_IOERR_UNLOCK (SQLITE_IOERR | (8<<8))
  640. #define SQLITE_IOERR_RDLOCK (SQLITE_IOERR | (9<<8))
  641. #define SQLITE_IOERR_DELETE (SQLITE_IOERR | (10<<8))
  642. #define SQLITE_IOERR_BLOCKED (SQLITE_IOERR | (11<<8))
  643. #define SQLITE_IOERR_NOMEM (SQLITE_IOERR | (12<<8))
  644. #define SQLITE_IOERR_ACCESS (SQLITE_IOERR | (13<<8))
  645. #define SQLITE_IOERR_CHECKRESERVEDLOCK (SQLITE_IOERR | (14<<8))
  646. #define SQLITE_IOERR_LOCK (SQLITE_IOERR | (15<<8))
  647. #define SQLITE_IOERR_CLOSE (SQLITE_IOERR | (16<<8))
  648. #define SQLITE_IOERR_DIR_CLOSE (SQLITE_IOERR | (17<<8))
  649. #define SQLITE_IOERR_SHMOPEN (SQLITE_IOERR | (18<<8))
  650. #define SQLITE_IOERR_SHMSIZE (SQLITE_IOERR | (19<<8))
  651. #define SQLITE_IOERR_SHMLOCK (SQLITE_IOERR | (20<<8))
  652. #define SQLITE_IOERR_SHMMAP (SQLITE_IOERR | (21<<8))
  653. #define SQLITE_IOERR_SEEK (SQLITE_IOERR | (22<<8))
  654. #define SQLITE_IOERR_DELETE_NOENT (SQLITE_IOERR | (23<<8))
  655. #define SQLITE_IOERR_MMAP (SQLITE_IOERR | (24<<8))
  656. #define SQLITE_IOERR_GETTEMPPATH (SQLITE_IOERR | (25<<8))
  657. #define SQLITE_IOERR_CONVPATH (SQLITE_IOERR | (26<<8))
  658. #define SQLITE_LOCKED_SHAREDCACHE (SQLITE_LOCKED | (1<<8))
  659. #define SQLITE_BUSY_RECOVERY (SQLITE_BUSY | (1<<8))
  660. #define SQLITE_BUSY_SNAPSHOT (SQLITE_BUSY | (2<<8))
  661. #define SQLITE_CANTOPEN_NOTEMPDIR (SQLITE_CANTOPEN | (1<<8))
  662. #define SQLITE_CANTOPEN_ISDIR (SQLITE_CANTOPEN | (2<<8))
  663. #define SQLITE_CANTOPEN_FULLPATH (SQLITE_CANTOPEN | (3<<8))
  664. #define SQLITE_CANTOPEN_CONVPATH (SQLITE_CANTOPEN | (4<<8))
  665. #define SQLITE_CORRUPT_VTAB (SQLITE_CORRUPT | (1<<8))
  666. #define SQLITE_READONLY_RECOVERY (SQLITE_READONLY | (1<<8))
  667. #define SQLITE_READONLY_CANTLOCK (SQLITE_READONLY | (2<<8))
  668. #define SQLITE_READONLY_ROLLBACK (SQLITE_READONLY | (3<<8))
  669. #define SQLITE_READONLY_DBMOVED (SQLITE_READONLY | (4<<8))
  670. #define SQLITE_ABORT_ROLLBACK (SQLITE_ABORT | (2<<8))
  671. #define SQLITE_CONSTRAINT_CHECK (SQLITE_CONSTRAINT | (1<<8))
  672. #define SQLITE_CONSTRAINT_COMMITHOOK (SQLITE_CONSTRAINT | (2<<8))
  673. #define SQLITE_CONSTRAINT_FOREIGNKEY (SQLITE_CONSTRAINT | (3<<8))
  674. #define SQLITE_CONSTRAINT_FUNCTION (SQLITE_CONSTRAINT | (4<<8))
  675. #define SQLITE_CONSTRAINT_NOTNULL (SQLITE_CONSTRAINT | (5<<8))
  676. #define SQLITE_CONSTRAINT_PRIMARYKEY (SQLITE_CONSTRAINT | (6<<8))
  677. #define SQLITE_CONSTRAINT_TRIGGER (SQLITE_CONSTRAINT | (7<<8))
  678. #define SQLITE_CONSTRAINT_UNIQUE (SQLITE_CONSTRAINT | (8<<8))
  679. #define SQLITE_CONSTRAINT_VTAB (SQLITE_CONSTRAINT | (9<<8))
  680. #define SQLITE_CONSTRAINT_ROWID (SQLITE_CONSTRAINT |(10<<8))
  681. #define SQLITE_NOTICE_RECOVER_WAL (SQLITE_NOTICE | (1<<8))
  682. #define SQLITE_NOTICE_RECOVER_ROLLBACK (SQLITE_NOTICE | (2<<8))
  683. #define SQLITE_WARNING_AUTOINDEX (SQLITE_WARNING | (1<<8))
  684. #define SQLITE_AUTH_USER (SQLITE_AUTH | (1<<8))
  685. /*
  686. ** CAPI3REF: Flags For File Open Operations
  687. **
  688. ** These bit values are intended for use in the
  689. ** 3rd parameter to the [sqlite3_open_v2()] interface and
  690. ** in the 4th parameter to the [sqlite3_vfs.xOpen] method.
  691. */
  692. #define SQLITE_OPEN_READONLY 0x00000001 /* Ok for sqlite3_open_v2() */
  693. #define SQLITE_OPEN_READWRITE 0x00000002 /* Ok for sqlite3_open_v2() */
  694. #define SQLITE_OPEN_CREATE 0x00000004 /* Ok for sqlite3_open_v2() */
  695. #define SQLITE_OPEN_DELETEONCLOSE 0x00000008 /* VFS only */
  696. #define SQLITE_OPEN_EXCLUSIVE 0x00000010 /* VFS only */
  697. #define SQLITE_OPEN_AUTOPROXY 0x00000020 /* VFS only */
  698. #define SQLITE_OPEN_URI 0x00000040 /* Ok for sqlite3_open_v2() */
  699. #define SQLITE_OPEN_MEMORY 0x00000080 /* Ok for sqlite3_open_v2() */
  700. #define SQLITE_OPEN_MAIN_DB 0x00000100 /* VFS only */
  701. #define SQLITE_OPEN_TEMP_DB 0x00000200 /* VFS only */
  702. #define SQLITE_OPEN_TRANSIENT_DB 0x00000400 /* VFS only */
  703. #define SQLITE_OPEN_MAIN_JOURNAL 0x00000800 /* VFS only */
  704. #define SQLITE_OPEN_TEMP_JOURNAL 0x00001000 /* VFS only */
  705. #define SQLITE_OPEN_SUBJOURNAL 0x00002000 /* VFS only */
  706. #define SQLITE_OPEN_MASTER_JOURNAL 0x00004000 /* VFS only */
  707. #define SQLITE_OPEN_NOMUTEX 0x00008000 /* Ok for sqlite3_open_v2() */
  708. #define SQLITE_OPEN_FULLMUTEX 0x00010000 /* Ok for sqlite3_open_v2() */
  709. #define SQLITE_OPEN_SHAREDCACHE 0x00020000 /* Ok for sqlite3_open_v2() */
  710. #define SQLITE_OPEN_PRIVATECACHE 0x00040000 /* Ok for sqlite3_open_v2() */
  711. #define SQLITE_OPEN_WAL 0x00080000 /* VFS only */
  712. /* Reserved: 0x00F00000 */
  713. /*
  714. ** CAPI3REF: Device Characteristics
  715. **
  716. ** The xDeviceCharacteristics method of the [sqlite3_io_methods]
  717. ** object returns an integer which is a vector of these
  718. ** bit values expressing I/O characteristics of the mass storage
  719. ** device that holds the file that the [sqlite3_io_methods]
  720. ** refers to.
  721. **
  722. ** The SQLITE_IOCAP_ATOMIC property means that all writes of
  723. ** any size are atomic. The SQLITE_IOCAP_ATOMICnnn values
  724. ** mean that writes of blocks that are nnn bytes in size and
  725. ** are aligned to an address which is an integer multiple of
  726. ** nnn are atomic. The SQLITE_IOCAP_SAFE_APPEND value means
  727. ** that when data is appended to a file, the data is appended
  728. ** first then the size of the file is extended, never the other
  729. ** way around. The SQLITE_IOCAP_SEQUENTIAL property means that
  730. ** information is written to disk in the same order as calls
  731. ** to xWrite(). The SQLITE_IOCAP_POWERSAFE_OVERWRITE property means that
  732. ** after reboot following a crash or power loss, the only bytes in a
  733. ** file that were written at the application level might have changed
  734. ** and that adjacent bytes, even bytes within the same sector are
  735. ** guaranteed to be unchanged. The SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN
  736. ** flag indicate that a file cannot be deleted when open. The
  737. ** SQLITE_IOCAP_IMMUTABLE flag indicates that the file is on
  738. ** read-only media and cannot be changed even by processes with
  739. ** elevated privileges.
  740. */
  741. #define SQLITE_IOCAP_ATOMIC 0x00000001
  742. #define SQLITE_IOCAP_ATOMIC512 0x00000002
  743. #define SQLITE_IOCAP_ATOMIC1K 0x00000004
  744. #define SQLITE_IOCAP_ATOMIC2K 0x00000008
  745. #define SQLITE_IOCAP_ATOMIC4K 0x00000010
  746. #define SQLITE_IOCAP_ATOMIC8K 0x00000020
  747. #define SQLITE_IOCAP_ATOMIC16K 0x00000040
  748. #define SQLITE_IOCAP_ATOMIC32K 0x00000080
  749. #define SQLITE_IOCAP_ATOMIC64K 0x00000100
  750. #define SQLITE_IOCAP_SAFE_APPEND 0x00000200
  751. #define SQLITE_IOCAP_SEQUENTIAL 0x00000400
  752. #define SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN 0x00000800
  753. #define SQLITE_IOCAP_POWERSAFE_OVERWRITE 0x00001000
  754. #define SQLITE_IOCAP_IMMUTABLE 0x00002000
  755. /*
  756. ** CAPI3REF: File Locking Levels
  757. **
  758. ** SQLite uses one of these integer values as the second
  759. ** argument to calls it makes to the xLock() and xUnlock() methods
  760. ** of an [sqlite3_io_methods] object.
  761. */
  762. #define SQLITE_LOCK_NONE 0
  763. #define SQLITE_LOCK_SHARED 1
  764. #define SQLITE_LOCK_RESERVED 2
  765. #define SQLITE_LOCK_PENDING 3
  766. #define SQLITE_LOCK_EXCLUSIVE 4
  767. /*
  768. ** CAPI3REF: Synchronization Type Flags
  769. **
  770. ** When SQLite invokes the xSync() method of an
  771. ** [sqlite3_io_methods] object it uses a combination of
  772. ** these integer values as the second argument.
  773. **
  774. ** When the SQLITE_SYNC_DATAONLY flag is used, it means that the
  775. ** sync operation only needs to flush data to mass storage. Inode
  776. ** information need not be flushed. If the lower four bits of the flag
  777. ** equal SQLITE_SYNC_NORMAL, that means to use normal fsync() semantics.
  778. ** If the lower four bits equal SQLITE_SYNC_FULL, that means
  779. ** to use Mac OS X style fullsync instead of fsync().
  780. **
  781. ** Do not confuse the SQLITE_SYNC_NORMAL and SQLITE_SYNC_FULL flags
  782. ** with the [PRAGMA synchronous]=NORMAL and [PRAGMA synchronous]=FULL
  783. ** settings. The [synchronous pragma] determines when calls to the
  784. ** xSync VFS method occur and applies uniformly across all platforms.
  785. ** The SQLITE_SYNC_NORMAL and SQLITE_SYNC_FULL flags determine how
  786. ** energetic or rigorous or forceful the sync operations are and
  787. ** only make a difference on Mac OSX for the default SQLite code.
  788. ** (Third-party VFS implementations might also make the distinction
  789. ** between SQLITE_SYNC_NORMAL and SQLITE_SYNC_FULL, but among the
  790. ** operating systems natively supported by SQLite, only Mac OSX
  791. ** cares about the difference.)
  792. */
  793. #define SQLITE_SYNC_NORMAL 0x00002
  794. #define SQLITE_SYNC_FULL 0x00003
  795. #define SQLITE_SYNC_DATAONLY 0x00010
  796. /*
  797. ** CAPI3REF: OS Interface Open File Handle
  798. **
  799. ** An [sqlite3_file] object represents an open file in the
  800. ** [sqlite3_vfs | OS interface layer]. Individual OS interface
  801. ** implementations will
  802. ** want to subclass this object by appending additional fields
  803. ** for their own use. The pMethods entry is a pointer to an
  804. ** [sqlite3_io_methods] object that defines methods for performing
  805. ** I/O operations on the open file.
  806. */
  807. typedef struct sqlite3_file sqlite3_file;
  808. struct sqlite3_file {
  809. const struct sqlite3_io_methods *pMethods; /* Methods for an open file */
  810. };
  811. /*
  812. ** CAPI3REF: OS Interface File Virtual Methods Object
  813. **
  814. ** Every file opened by the [sqlite3_vfs.xOpen] method populates an
  815. ** [sqlite3_file] object (or, more commonly, a subclass of the
  816. ** [sqlite3_file] object) with a pointer to an instance of this object.
  817. ** This object defines the methods used to perform various operations
  818. ** against the open file represented by the [sqlite3_file] object.
  819. **
  820. ** If the [sqlite3_vfs.xOpen] method sets the sqlite3_file.pMethods element
  821. ** to a non-NULL pointer, then the sqlite3_io_methods.xClose method
  822. ** may be invoked even if the [sqlite3_vfs.xOpen] reported that it failed. The
  823. ** only way to prevent a call to xClose following a failed [sqlite3_vfs.xOpen]
  824. ** is for the [sqlite3_vfs.xOpen] to set the sqlite3_file.pMethods element
  825. ** to NULL.
  826. **
  827. ** The flags argument to xSync may be one of [SQLITE_SYNC_NORMAL] or
  828. ** [SQLITE_SYNC_FULL]. The first choice is the normal fsync().
  829. ** The second choice is a Mac OS X style fullsync. The [SQLITE_SYNC_DATAONLY]
  830. ** flag may be ORed in to indicate that only the data of the file
  831. ** and not its inode needs to be synced.
  832. **
  833. ** The integer values to xLock() and xUnlock() are one of
  834. ** <ul>
  835. ** <li> [SQLITE_LOCK_NONE],
  836. ** <li> [SQLITE_LOCK_SHARED],
  837. ** <li> [SQLITE_LOCK_RESERVED],
  838. ** <li> [SQLITE_LOCK_PENDING], or
  839. ** <li> [SQLITE_LOCK_EXCLUSIVE].
  840. ** </ul>
  841. ** xLock() increases the lock. xUnlock() decreases the lock.
  842. ** The xCheckReservedLock() method checks whether any database connection,
  843. ** either in this process or in some other process, is holding a RESERVED,
  844. ** PENDING, or EXCLUSIVE lock on the file. It returns true
  845. ** if such a lock exists and false otherwise.
  846. **
  847. ** The xFileControl() method is a generic interface that allows custom
  848. ** VFS implementations to directly control an open file using the
  849. ** [sqlite3_file_control()] interface. The second "op" argument is an
  850. ** integer opcode. The third argument is a generic pointer intended to
  851. ** point to a structure that may contain arguments or space in which to
  852. ** write return values. Potential uses for xFileControl() might be
  853. ** functions to enable blocking locks with timeouts, to change the
  854. ** locking strategy (for example to use dot-file locks), to inquire
  855. ** about the status of a lock, or to break stale locks. The SQLite
  856. ** core reserves all opcodes less than 100 for its own use.
  857. ** A [file control opcodes | list of opcodes] less than 100 is available.
  858. ** Applications that define a custom xFileControl method should use opcodes
  859. ** greater than 100 to avoid conflicts. VFS implementations should
  860. ** return [SQLITE_NOTFOUND] for file control opcodes that they do not
  861. ** recognize.
  862. **
  863. ** The xSectorSize() method returns the sector size of the
  864. ** device that underlies the file. The sector size is the
  865. ** minimum write that can be performed without disturbing
  866. ** other bytes in the file. The xDeviceCharacteristics()
  867. ** method returns a bit vector describing behaviors of the
  868. ** underlying device:
  869. **
  870. ** <ul>
  871. ** <li> [SQLITE_IOCAP_ATOMIC]
  872. ** <li> [SQLITE_IOCAP_ATOMIC512]
  873. ** <li> [SQLITE_IOCAP_ATOMIC1K]
  874. ** <li> [SQLITE_IOCAP_ATOMIC2K]
  875. ** <li> [SQLITE_IOCAP_ATOMIC4K]
  876. ** <li> [SQLITE_IOCAP_ATOMIC8K]
  877. ** <li> [SQLITE_IOCAP_ATOMIC16K]
  878. ** <li> [SQLITE_IOCAP_ATOMIC32K]
  879. ** <li> [SQLITE_IOCAP_ATOMIC64K]
  880. ** <li> [SQLITE_IOCAP_SAFE_APPEND]
  881. ** <li> [SQLITE_IOCAP_SEQUENTIAL]
  882. ** </ul>
  883. **
  884. ** The SQLITE_IOCAP_ATOMIC property means that all writes of
  885. ** any size are atomic. The SQLITE_IOCAP_ATOMICnnn values
  886. ** mean that writes of blocks that are nnn bytes in size and
  887. ** are aligned to an address which is an integer multiple of
  888. ** nnn are atomic. The SQLITE_IOCAP_SAFE_APPEND value means
  889. ** that when data is appended to a file, the data is appended
  890. ** first then the size of the file is extended, never the other
  891. ** way around. The SQLITE_IOCAP_SEQUENTIAL property means that
  892. ** information is written to disk in the same order as calls
  893. ** to xWrite().
  894. **
  895. ** If xRead() returns SQLITE_IOERR_SHORT_READ it must also fill
  896. ** in the unread portions of the buffer with zeros. A VFS that
  897. ** fails to zero-fill short reads might seem to work. However,
  898. ** failure to zero-fill short reads will eventually lead to
  899. ** database corruption.
  900. */
  901. typedef struct sqlite3_io_methods sqlite3_io_methods;
  902. struct sqlite3_io_methods {
  903. int iVersion;
  904. int (*xClose)(sqlite3_file*);
  905. int (*xRead)(sqlite3_file*, void*, int iAmt, sqlite3_int64 iOfst);
  906. int (*xWrite)(sqlite3_file*, const void*, int iAmt, sqlite3_int64 iOfst);
  907. int (*xTruncate)(sqlite3_file*, sqlite3_int64 size);
  908. int (*xSync)(sqlite3_file*, int flags);
  909. int (*xFileSize)(sqlite3_file*, sqlite3_int64 *pSize);
  910. int (*xLock)(sqlite3_file*, int);
  911. int (*xUnlock)(sqlite3_file*, int);
  912. int (*xCheckReservedLock)(sqlite3_file*, int *pResOut);
  913. int (*xFileControl)(sqlite3_file*, int op, void *pArg);
  914. int (*xSectorSize)(sqlite3_file*);
  915. int (*xDeviceCharacteristics)(sqlite3_file*);
  916. /* Methods above are valid for version 1 */
  917. int (*xShmMap)(sqlite3_file*, int iPg, int pgsz, int, void volatile**);
  918. int (*xShmLock)(sqlite3_file*, int offset, int n, int flags);
  919. void (*xShmBarrier)(sqlite3_file*);
  920. int (*xShmUnmap)(sqlite3_file*, int deleteFlag);
  921. /* Methods above are valid for version 2 */
  922. int (*xFetch)(sqlite3_file*, sqlite3_int64 iOfst, int iAmt, void **pp);
  923. int (*xUnfetch)(sqlite3_file*, sqlite3_int64 iOfst, void *p);
  924. /* Methods above are valid for version 3 */
  925. /* Additional methods may be added in future releases */
  926. };
  927. /*
  928. ** CAPI3REF: Standard File Control Opcodes
  929. ** KEYWORDS: {file control opcodes} {file control opcode}
  930. **
  931. ** These integer constants are opcodes for the xFileControl method
  932. ** of the [sqlite3_io_methods] object and for the [sqlite3_file_control()]
  933. ** interface.
  934. **
  935. ** <ul>
  936. ** <li>[[SQLITE_FCNTL_LOCKSTATE]]
  937. ** The [SQLITE_FCNTL_LOCKSTATE] opcode is used for debugging. This
  938. ** opcode causes the xFileControl method to write the current state of
  939. ** the lock (one of [SQLITE_LOCK_NONE], [SQLITE_LOCK_SHARED],
  940. ** [SQLITE_LOCK_RESERVED], [SQLITE_LOCK_PENDING], or [SQLITE_LOCK_EXCLUSIVE])
  941. ** into an integer that the pArg argument points to. This capability
  942. ** is used during testing and is only available when the SQLITE_TEST
  943. ** compile-time option is used.
  944. **
  945. ** <li>[[SQLITE_FCNTL_SIZE_HINT]]
  946. ** The [SQLITE_FCNTL_SIZE_HINT] opcode is used by SQLite to give the VFS
  947. ** layer a hint of how large the database file will grow to be during the
  948. ** current transaction. This hint is not guaranteed to be accurate but it
  949. ** is often close. The underlying VFS might choose to preallocate database
  950. ** file space based on this hint in order to help writes to the database
  951. ** file run faster.
  952. **
  953. ** <li>[[SQLITE_FCNTL_CHUNK_SIZE]]
  954. ** The [SQLITE_FCNTL_CHUNK_SIZE] opcode is used to request that the VFS
  955. ** extends and truncates the database file in chunks of a size specified
  956. ** by the user. The fourth argument to [sqlite3_file_control()] should
  957. ** point to an integer (type int) containing the new chunk-size to use
  958. ** for the nominated database. Allocating database file space in large
  959. ** chunks (say 1MB at a time), may reduce file-system fragmentation and
  960. ** improve performance on some systems.
  961. **
  962. ** <li>[[SQLITE_FCNTL_FILE_POINTER]]
  963. ** The [SQLITE_FCNTL_FILE_POINTER] opcode is used to obtain a pointer
  964. ** to the [sqlite3_file] object associated with a particular database
  965. ** connection. See the [sqlite3_file_control()] documentation for
  966. ** additional information.
  967. **
  968. ** <li>[[SQLITE_FCNTL_SYNC_OMITTED]]
  969. ** No longer in use.
  970. **
  971. ** <li>[[SQLITE_FCNTL_SYNC]]
  972. ** The [SQLITE_FCNTL_SYNC] opcode is generated internally by SQLite and
  973. ** sent to the VFS immediately before the xSync method is invoked on a
  974. ** database file descriptor. Or, if the xSync method is not invoked
  975. ** because the user has configured SQLite with
  976. ** [PRAGMA synchronous | PRAGMA synchronous=OFF] it is invoked in place
  977. ** of the xSync method. In most cases, the pointer argument passed with
  978. ** this file-control is NULL. However, if the database file is being synced
  979. ** as part of a multi-database commit, the argument points to a nul-terminated
  980. ** string containing the transactions master-journal file name. VFSes that
  981. ** do not need this signal should silently ignore this opcode. Applications
  982. ** should not call [sqlite3_file_control()] with this opcode as doing so may
  983. ** disrupt the operation of the specialized VFSes that do require it.
  984. **
  985. ** <li>[[SQLITE_FCNTL_COMMIT_PHASETWO]]
  986. ** The [SQLITE_FCNTL_COMMIT_PHASETWO] opcode is generated internally by SQLite
  987. ** and sent to the VFS after a transaction has been committed immediately
  988. ** but before the database is unlocked. VFSes that do not need this signal
  989. ** should silently ignore this opcode. Applications should not call
  990. ** [sqlite3_file_control()] with this opcode as doing so may disrupt the
  991. ** operation of the specialized VFSes that do require it.
  992. **
  993. ** <li>[[SQLITE_FCNTL_WIN32_AV_RETRY]]
  994. ** ^The [SQLITE_FCNTL_WIN32_AV_RETRY] opcode is used to configure automatic
  995. ** retry counts and intervals for certain disk I/O operations for the
  996. ** windows [VFS] in order to provide robustness in the presence of
  997. ** anti-virus programs. By default, the windows VFS will retry file read,
  998. ** file write, and file delete operations up to 10 times, with a delay
  999. ** of 25 milliseconds before the first retry and with the delay increasing
  1000. ** by an additional 25 milliseconds with each subsequent retry. This
  1001. ** opcode allows these two values (10 retries and 25 milliseconds of delay)
  1002. ** to be adjusted. The values are changed for all database connections
  1003. ** within the same process. The argument is a pointer to an array of two
  1004. ** integers where the first integer i the new retry count and the second
  1005. ** integer is the delay. If either integer is negative, then the setting
  1006. ** is not changed but instead the prior value of that setting is written
  1007. ** into the array entry, allowing the current retry settings to be
  1008. ** interrogated. The zDbName parameter is ignored.
  1009. **
  1010. ** <li>[[SQLITE_FCNTL_PERSIST_WAL]]
  1011. ** ^The [SQLITE_FCNTL_PERSIST_WAL] opcode is used to set or query the
  1012. ** persistent [WAL | Write Ahead Log] setting. By default, the auxiliary
  1013. ** write ahead log and shared memory files used for transaction control
  1014. ** are automatically deleted when the latest connection to the database
  1015. ** closes. Setting persistent WAL mode causes those files to persist after
  1016. ** close. Persisting the files is useful when other processes that do not
  1017. ** have write permission on the directory containing the database file want
  1018. ** to read the database file, as the WAL and shared memory files must exist
  1019. ** in order for the database to be readable. The fourth parameter to
  1020. ** [sqlite3_file_control()] for this opcode should be a pointer to an integer.
  1021. ** That integer is 0 to disable persistent WAL mode or 1 to enable persistent
  1022. ** WAL mode. If the integer is -1, then it is overwritten with the current
  1023. ** WAL persistence setting.
  1024. **
  1025. ** <li>[[SQLITE_FCNTL_POWERSAFE_OVERWRITE]]
  1026. ** ^The [SQLITE_FCNTL_POWERSAFE_OVERWRITE] opcode is used to set or query the
  1027. ** persistent "powersafe-overwrite" or "PSOW" setting. The PSOW setting
  1028. ** determines the [SQLITE_IOCAP_POWERSAFE_OVERWRITE] bit of the
  1029. ** xDeviceCharacteristics methods. The fourth parameter to
  1030. ** [sqlite3_file_control()] for this opcode should be a pointer to an integer.
  1031. ** That integer is 0 to disable zero-damage mode or 1 to enable zero-damage
  1032. ** mode. If the integer is -1, then it is overwritten with the current
  1033. ** zero-damage mode setting.
  1034. **
  1035. ** <li>[[SQLITE_FCNTL_OVERWRITE]]
  1036. ** ^The [SQLITE_FCNTL_OVERWRITE] opcode is invoked by SQLite after opening
  1037. ** a write transaction to indicate that, unless it is rolled back for some
  1038. ** reason, the entire database file will be overwritten by the current
  1039. ** transaction. This is used by VACUUM operations.
  1040. **
  1041. ** <li>[[SQLITE_FCNTL_VFSNAME]]
  1042. ** ^The [SQLITE_FCNTL_VFSNAME] opcode can be used to obtain the names of
  1043. ** all [VFSes] in the VFS stack. The names are of all VFS shims and the
  1044. ** final bottom-level VFS are written into memory obtained from
  1045. ** [sqlite3_malloc()] and the result is stored in the char* variable
  1046. ** that the fourth parameter of [sqlite3_file_control()] points to.
  1047. ** The caller is responsible for freeing the memory when done. As with
  1048. ** all file-control actions, there is no guarantee that this will actually
  1049. ** do anything. Callers should initialize the char* variable to a NULL
  1050. ** pointer in case this file-control is not implemented. This file-control
  1051. ** is intended for diagnostic use only.
  1052. **
  1053. ** <li>[[SQLITE_FCNTL_PRAGMA]]
  1054. ** ^Whenever a [PRAGMA] statement is parsed, an [SQLITE_FCNTL_PRAGMA]
  1055. ** file control is sent to the open [sqlite3_file] object corresponding
  1056. ** to the database file to which the pragma statement refers. ^The argument
  1057. ** to the [SQLITE_FCNTL_PRAGMA] file control is an array of
  1058. ** pointers to strings (char**) in which the second element of the array
  1059. ** is the name of the pragma and the third element is the argument to the
  1060. ** pragma or NULL if the pragma has no argument. ^The handler for an
  1061. ** [SQLITE_FCNTL_PRAGMA] file control can optionally make the first element
  1062. ** of the char** argument point to a string obtained from [sqlite3_mprintf()]
  1063. ** or the equivalent and that string will become the result of the pragma or
  1064. ** the error message if the pragma fails. ^If the
  1065. ** [SQLITE_FCNTL_PRAGMA] file control returns [SQLITE_NOTFOUND], then normal
  1066. ** [PRAGMA] processing continues. ^If the [SQLITE_FCNTL_PRAGMA]
  1067. ** file control returns [SQLITE_OK], then the parser assumes that the
  1068. ** VFS has handled the PRAGMA itself and the parser generates a no-op
  1069. ** prepared statement if result string is NULL, or that returns a copy
  1070. ** of the result string if the string is non-NULL.
  1071. ** ^If the [SQLITE_FCNTL_PRAGMA] file control returns
  1072. ** any result code other than [SQLITE_OK] or [SQLITE_NOTFOUND], that means
  1073. ** that the VFS encountered an error while handling the [PRAGMA] and the
  1074. ** compilation of the PRAGMA fails with an error. ^The [SQLITE_FCNTL_PRAGMA]
  1075. ** file control occurs at the beginning of pragma statement analysis and so
  1076. ** it is able to override built-in [PRAGMA] statements.
  1077. **
  1078. ** <li>[[SQLITE_FCNTL_BUSYHANDLER]]
  1079. ** ^The [SQLITE_FCNTL_BUSYHANDLER]
  1080. ** file-control may be invoked by SQLite on the database file handle
  1081. ** shortly after it is opened in order to provide a custom VFS with access
  1082. ** to the connections busy-handler callback. The argument is of type (void **)
  1083. ** - an array of two (void *) values. The first (void *) actually points
  1084. ** to a function of type (int (*)(void *)). In order to invoke the connections
  1085. ** busy-handler, this function should be invoked with the second (void *) in
  1086. ** the array as the only argument. If it returns non-zero, then the operation
  1087. ** should be retried. If it returns zero, the custom VFS should abandon the
  1088. ** current operation.
  1089. **
  1090. ** <li>[[SQLITE_FCNTL_TEMPFILENAME]]
  1091. ** ^Application can invoke the [SQLITE_FCNTL_TEMPFILENAME] file-control
  1092. ** to have SQLite generate a
  1093. ** temporary filename using the same algorithm that is followed to generate
  1094. ** temporary filenames for TEMP tables and other internal uses. The
  1095. ** argument should be a char** which will be filled with the filename
  1096. ** written into memory obtained from [sqlite3_malloc()]. The caller should
  1097. ** invoke [sqlite3_free()] on the result to avoid a memory leak.
  1098. **
  1099. ** <li>[[SQLITE_FCNTL_MMAP_SIZE]]
  1100. ** The [SQLITE_FCNTL_MMAP_SIZE] file control is used to query or set the
  1101. ** maximum number of bytes that will be used for memory-mapped I/O.
  1102. ** The argument is a pointer to a value of type sqlite3_int64 that
  1103. ** is an advisory maximum number of bytes in the file to memory map. The
  1104. ** pointer is overwritten with the old value. The limit is not changed if
  1105. ** the value originally pointed to is negative, and so the current limit
  1106. ** can be queried by passing in a pointer to a negative number. This
  1107. ** file-control is used internally to implement [PRAGMA mmap_size].
  1108. **
  1109. ** <li>[[SQLITE_FCNTL_TRACE]]
  1110. ** The [SQLITE_FCNTL_TRACE] file control provides advisory information
  1111. ** to the VFS about what the higher layers of the SQLite stack are doing.
  1112. ** This file control is used by some VFS activity tracing [shims].
  1113. ** The argument is a zero-terminated string. Higher layers in the
  1114. ** SQLite stack may generate instances of this file control if
  1115. ** the [SQLITE_USE_FCNTL_TRACE] compile-time option is enabled.
  1116. **
  1117. ** <li>[[SQLITE_FCNTL_HAS_MOVED]]
  1118. ** The [SQLITE_FCNTL_HAS_MOVED] file control interprets its argument as a
  1119. ** pointer to an integer and it writes a boolean into that integer depending
  1120. ** on whether or not the file has been renamed, moved, or deleted since it
  1121. ** was first opened.
  1122. **
  1123. ** <li>[[SQLITE_FCNTL_WIN32_SET_HANDLE]]
  1124. ** The [SQLITE_FCNTL_WIN32_SET_HANDLE] opcode is used for debugging. This
  1125. ** opcode causes the xFileControl method to swap the file handle with the one
  1126. ** pointed to by the pArg argument. This capability is used during testing
  1127. ** and only needs to be supported when SQLITE_TEST is defined.
  1128. **
  1129. ** <li>[[SQLITE_FCNTL_WAL_BLOCK]]
  1130. ** The [SQLITE_FCNTL_WAL_BLOCK] is a signal to the VFS layer that it might
  1131. ** be advantageous to block on the next WAL lock if the lock is not immediately
  1132. ** available. The WAL subsystem issues this signal during rare
  1133. ** circumstances in order to fix a problem with priority inversion.
  1134. ** Applications should <em>not</em> use this file-control.
  1135. **
  1136. ** </ul>
  1137. */
  1138. #define SQLITE_FCNTL_LOCKSTATE 1
  1139. #define SQLITE_FCNTL_GET_LOCKPROXYFILE 2
  1140. #define SQLITE_FCNTL_SET_LOCKPROXYFILE 3
  1141. #define SQLITE_FCNTL_LAST_ERRNO 4
  1142. #define SQLITE_FCNTL_SIZE_HINT 5
  1143. #define SQLITE_FCNTL_CHUNK_SIZE 6
  1144. #define SQLITE_FCNTL_FILE_POINTER 7
  1145. #define SQLITE_FCNTL_SYNC_OMITTED 8
  1146. #define SQLITE_FCNTL_WIN32_AV_RETRY 9
  1147. #define SQLITE_FCNTL_PERSIST_WAL 10
  1148. #define SQLITE_FCNTL_OVERWRITE 11
  1149. #define SQLITE_FCNTL_VFSNAME 12
  1150. #define SQLITE_FCNTL_POWERSAFE_OVERWRITE 13
  1151. #define SQLITE_FCNTL_PRAGMA 14
  1152. #define SQLITE_FCNTL_BUSYHANDLER 15
  1153. #define SQLITE_FCNTL_TEMPFILENAME 16
  1154. #define SQLITE_FCNTL_MMAP_SIZE 18
  1155. #define SQLITE_FCNTL_TRACE 19
  1156. #define SQLITE_FCNTL_HAS_MOVED 20
  1157. #define SQLITE_FCNTL_SYNC 21
  1158. #define SQLITE_FCNTL_COMMIT_PHASETWO 22
  1159. #define SQLITE_FCNTL_WIN32_SET_HANDLE 23
  1160. #define SQLITE_FCNTL_WAL_BLOCK 24
  1161. /* deprecated names */
  1162. #define SQLITE_GET_LOCKPROXYFILE SQLITE_FCNTL_GET_LOCKPROXYFILE
  1163. #define SQLITE_SET_LOCKPROXYFILE SQLITE_FCNTL_SET_LOCKPROXYFILE
  1164. #define SQLITE_LAST_ERRNO SQLITE_FCNTL_LAST_ERRNO
  1165. /*
  1166. ** CAPI3REF: Mutex Handle
  1167. **
  1168. ** The mutex module within SQLite defines [sqlite3_mutex] to be an
  1169. ** abstract type for a mutex object. The SQLite core never looks
  1170. ** at the internal representation of an [sqlite3_mutex]. It only
  1171. ** deals with pointers to the [sqlite3_mutex] object.
  1172. **
  1173. ** Mutexes are created using [sqlite3_mutex_alloc()].
  1174. */
  1175. typedef struct sqlite3_mutex sqlite3_mutex;
  1176. /*
  1177. ** CAPI3REF: OS Interface Object
  1178. **
  1179. ** An instance of the sqlite3_vfs object defines the interface between
  1180. ** the SQLite core and the underlying operating system. The "vfs"
  1181. ** in the name of the object stands for "virtual file system". See
  1182. ** the [VFS | VFS documentation] for further information.
  1183. **
  1184. ** The value of the iVersion field is initially 1 but may be larger in
  1185. ** future versions of SQLite. Additional fields may be appended to this
  1186. ** object when the iVersion value is increased. Note that the structure
  1187. ** of the sqlite3_vfs object changes in the transaction between
  1188. ** SQLite version 3.5.9 and 3.6.0 and yet the iVersion field was not
  1189. ** modified.
  1190. **
  1191. ** The szOsFile field is the size of the subclassed [sqlite3_file]
  1192. ** structure used by this VFS. mxPathname is the maximum length of
  1193. ** a pathname in this VFS.
  1194. **
  1195. ** Registered sqlite3_vfs objects are kept on a linked list formed by
  1196. ** the pNext pointer. The [sqlite3_vfs_register()]
  1197. ** and [sqlite3_vfs_unregister()] interfaces manage this list
  1198. ** in a thread-safe way. The [sqlite3_vfs_find()] interface
  1199. ** searches the list. Neither the application code nor the VFS
  1200. ** implementation should use the pNext pointer.
  1201. **
  1202. ** The pNext field is the only field in the sqlite3_vfs
  1203. ** structure that SQLite will ever modify. SQLite will only access
  1204. ** or modify this field while holding a particular static mutex.
  1205. ** The application should never modify anything within the sqlite3_vfs
  1206. ** object once the object has been registered.
  1207. **
  1208. ** The zName field holds the name of the VFS module. The name must
  1209. ** be unique across all VFS modules.
  1210. **
  1211. ** [[sqlite3_vfs.xOpen]]
  1212. ** ^SQLite guarantees that the zFilename parameter to xOpen
  1213. ** is either a NULL pointer or string obtained
  1214. ** from xFullPathname() with an optional suffix added.
  1215. ** ^If a suffix is added to the zFilename parameter, it will
  1216. ** consist of a single "-" character followed by no more than
  1217. ** 11 alphanumeric and/or "-" characters.
  1218. ** ^SQLite further guarantees that
  1219. ** the string will be valid and unchanged until xClose() is
  1220. ** called. Because of the previous sentence,
  1221. ** the [sqlite3_file] can safely store a pointer to the
  1222. ** filename if it needs to remember the filename for some reason.
  1223. ** If the zFilename parameter to xOpen is a NULL pointer then xOpen
  1224. ** must invent its own temporary name for the file. ^Whenever the
  1225. ** xFilename parameter is NULL it will also be the case that the
  1226. ** flags parameter will include [SQLITE_OPEN_DELETEONCLOSE].
  1227. **
  1228. ** The flags argument to xOpen() includes all bits set in
  1229. ** the flags argument to [sqlite3_open_v2()]. Or if [sqlite3_open()]
  1230. ** or [sqlite3_open16()] is used, then flags includes at least
  1231. ** [SQLITE_OPEN_READWRITE] | [SQLITE_OPEN_CREATE].
  1232. ** If xOpen() opens a file read-only then it sets *pOutFlags to
  1233. ** include [SQLITE_OPEN_READONLY]. Other bits in *pOutFlags may be set.
  1234. **
  1235. ** ^(SQLite will also add one of the following flags to the xOpen()
  1236. ** call, depending on the object being opened:
  1237. **
  1238. ** <ul>
  1239. ** <li> [SQLITE_OPEN_MAIN_DB]
  1240. ** <li> [SQLITE_OPEN_MAIN_JOURNAL]
  1241. ** <li> [SQLITE_OPEN_TEMP_DB]
  1242. ** <li> [SQLITE_OPEN_TEMP_JOURNAL]
  1243. ** <li> [SQLITE_OPEN_TRANSIENT_DB]
  1244. ** <li> [SQLITE_OPEN_SUBJOURNAL]
  1245. ** <li> [SQLITE_OPEN_MASTER_JOURNAL]
  1246. ** <li> [SQLITE_OPEN_WAL]
  1247. ** </ul>)^
  1248. **
  1249. ** The file I/O implementation can use the object type flags to
  1250. ** change the way it deals with files. For example, an application
  1251. ** that does not care about crash recovery or rollback might make
  1252. ** the open of a journal file a no-op. Writes to this journal would
  1253. ** also be no-ops, and any attempt to read the journal would return
  1254. ** SQLITE_IOERR. Or the implementation might recognize that a database
  1255. ** file will be doing page-aligned sector reads and writes in a random
  1256. ** order and set up its I/O subsystem accordingly.
  1257. **
  1258. ** SQLite might also add one of the following flags to the xOpen method:
  1259. **
  1260. ** <ul>
  1261. ** <li> [SQLITE_OPEN_DELETEONCLOSE]
  1262. ** <li> [SQLITE_OPEN_EXCLUSIVE]
  1263. ** </ul>
  1264. **
  1265. ** The [SQLITE_OPEN_DELETEONCLOSE] flag means the file should be
  1266. ** deleted when it is closed. ^The [SQLITE_OPEN_DELETEONCLOSE]
  1267. ** will be set for TEMP databases and their journals, transient
  1268. ** databases, and subjournals.
  1269. **
  1270. ** ^The [SQLITE_OPEN_EXCLUSIVE] flag is always used in conjunction
  1271. ** with the [SQLITE_OPEN_CREATE] flag, which are both directly
  1272. ** analogous to the O_EXCL and O_CREAT flags of the POSIX open()
  1273. ** API. The SQLITE_OPEN_EXCLUSIVE flag, when paired with the
  1274. ** SQLITE_OPEN_CREATE, is used to indicate that file should always
  1275. ** be created, and that it is an error if it already exists.
  1276. ** It is <i>not</i> used to indicate the file should be opened
  1277. ** for exclusive access.
  1278. **
  1279. ** ^At least szOsFile bytes of memory are allocated by SQLite
  1280. ** to hold the [sqlite3_file] structure passed as the third
  1281. ** argument to xOpen. The xOpen method does not have to
  1282. ** allocate the structure; it should just fill it in. Note that
  1283. ** the xOpen method must set the sqlite3_file.pMethods to either
  1284. ** a valid [sqlite3_io_methods] object or to NULL. xOpen must do
  1285. ** this even if the open fails. SQLite expects that the sqlite3_file.pMethods
  1286. ** element will be valid after xOpen returns regardless of the success
  1287. ** or failure of the xOpen call.
  1288. **
  1289. ** [[sqlite3_vfs.xAccess]]
  1290. ** ^The flags argument to xAccess() may be [SQLITE_ACCESS_EXISTS]
  1291. ** to test for the existence of a file, or [SQLITE_ACCESS_READWRITE] to
  1292. ** test whether a file is readable and writable, or [SQLITE_ACCESS_READ]
  1293. ** to test whether a file is at least readable. The file can be a
  1294. ** directory.
  1295. **
  1296. ** ^SQLite will always allocate at least mxPathname+1 bytes for the
  1297. ** output buffer xFullPathname. The exact size of the output buffer
  1298. ** is also passed as a parameter to both methods. If the output buffer
  1299. ** is not large enough, [SQLITE_CANTOPEN] should be returned. Since this is
  1300. ** handled as a fatal error by SQLite, vfs implementations should endeavor
  1301. ** to prevent this by setting mxPathname to a sufficiently large value.
  1302. **
  1303. ** The xRandomness(), xSleep(), xCurrentTime(), and xCurrentTimeInt64()
  1304. ** interfaces are not strictly a part of the filesystem, but they are
  1305. ** included in the VFS structure for completeness.
  1306. ** The xRandomness() function attempts to return nBytes bytes
  1307. ** of good-quality randomness into zOut. The return value is
  1308. ** the actual number of bytes of randomness obtained.
  1309. ** The xSleep() method causes the calling thread to sleep for at
  1310. ** least the number of microseconds given. ^The xCurrentTime()
  1311. ** method returns a Julian Day Number for the current date and time as
  1312. ** a floating point value.
  1313. ** ^The xCurrentTimeInt64() method returns, as an integer, the Julian
  1314. ** Day Number multiplied by 86400000 (the number of milliseconds in
  1315. ** a 24-hour day).
  1316. ** ^SQLite will use the xCurrentTimeInt64() method to get the current
  1317. ** date and time if that method is available (if iVersion is 2 or
  1318. ** greater and the function pointer is not NULL) and will fall back
  1319. ** to xCurrentTime() if xCurrentTimeInt64() is unavailable.
  1320. **
  1321. ** ^The xSetSystemCall(), xGetSystemCall(), and xNestSystemCall() interfaces
  1322. ** are not used by the SQLite core. These optional interfaces are provided
  1323. ** by some VFSes to facilitate testing of the VFS code. By overriding
  1324. ** system calls with functions under its control, a test program can
  1325. ** simulate faults and error conditions that would otherwise be difficult
  1326. ** or impossible to induce. The set of system calls that can be overridden
  1327. ** varies from one VFS to another, and from one version of the same VFS to the
  1328. ** next. Applications that use these interfaces must be prepared for any
  1329. ** or all of these interfaces to be NULL or for their behavior to change
  1330. ** from one release to the next. Applications must not attempt to access
  1331. ** any of these methods if the iVersion of the VFS is less than 3.
  1332. */
  1333. typedef struct sqlite3_vfs sqlite3_vfs;
  1334. typedef void (*sqlite3_syscall_ptr)(void);
  1335. struct sqlite3_vfs {
  1336. int iVersion; /* Structure version number (currently 3) */
  1337. int szOsFile; /* Size of subclassed sqlite3_file */
  1338. int mxPathname; /* Maximum file pathname length */
  1339. sqlite3_vfs *pNext; /* Next registered VFS */
  1340. const char *zName; /* Name of this virtual file system */
  1341. void *pAppData; /* Pointer to application-specific data */
  1342. int (*xOpen)(sqlite3_vfs*, const char *zName, sqlite3_file*,
  1343. int flags, int *pOutFlags);
  1344. int (*xDelete)(sqlite3_vfs*, const char *zName, int syncDir);
  1345. int (*xAccess)(sqlite3_vfs*, const char *zName, int flags, int *pResOut);
  1346. int (*xFullPathname)(sqlite3_vfs*, const char *zName, int nOut, char *zOut);
  1347. void *(*xDlOpen)(sqlite3_vfs*, const char *zFilename);
  1348. void (*xDlError)(sqlite3_vfs*, int nByte, char *zErrMsg);
  1349. void (*(*xDlSym)(sqlite3_vfs*,void*, const char *zSymbol))(void);
  1350. void (*xDlClose)(sqlite3_vfs*, void*);
  1351. int (*xRandomness)(sqlite3_vfs*, int nByte, char *zOut);
  1352. int (*xSleep)(sqlite3_vfs*, int microseconds);
  1353. int (*xCurrentTime)(sqlite3_vfs*, double*);
  1354. int (*xGetLastError)(sqlite3_vfs*, int, char *);
  1355. /*
  1356. ** The methods above are in version 1 of the sqlite_vfs object
  1357. ** definition. Those that follow are added in version 2 or later
  1358. */
  1359. int (*xCurrentTimeInt64)(sqlite3_vfs*, sqlite3_int64*);
  1360. /*
  1361. ** The methods above are in versions 1 and 2 of the sqlite_vfs object.
  1362. ** Those below are for version 3 and greater.
  1363. */
  1364. int (*xSetSystemCall)(sqlite3_vfs*, const char *zName, sqlite3_syscall_ptr);
  1365. sqlite3_syscall_ptr (*xGetSystemCall)(sqlite3_vfs*, const char *zName);
  1366. const char *(*xNextSystemCall)(sqlite3_vfs*, const char *zName);
  1367. /*
  1368. ** The methods above are in versions 1 through 3 of the sqlite_vfs object.
  1369. ** New fields may be appended in figure versions. The iVersion
  1370. ** value will increment whenever this happens.
  1371. */
  1372. };
  1373. /*
  1374. ** CAPI3REF: Flags for the xAccess VFS method
  1375. **
  1376. ** These integer constants can be used as the third parameter to
  1377. ** the xAccess method of an [sqlite3_vfs] object. They determine
  1378. ** what kind of permissions the xAccess method is looking for.
  1379. ** With SQLITE_ACCESS_EXISTS, the xAccess method
  1380. ** simply checks whether the file exists.
  1381. ** With SQLITE_ACCESS_READWRITE, the xAccess method
  1382. ** checks whether the named directory is both readable and writable
  1383. ** (in other words, if files can be added, removed, and renamed within
  1384. ** the directory).
  1385. ** The SQLITE_ACCESS_READWRITE constant is currently used only by the
  1386. ** [temp_store_directory pragma], though this could change in a future
  1387. ** release of SQLite.
  1388. ** With SQLITE_ACCESS_READ, the xAccess method
  1389. ** checks whether the file is readable. The SQLITE_ACCESS_READ constant is
  1390. ** currently unused, though it might be used in a future release of
  1391. ** SQLite.
  1392. */
  1393. #define SQLITE_ACCESS_EXISTS 0
  1394. #define SQLITE_ACCESS_READWRITE 1 /* Used by PRAGMA temp_store_directory */
  1395. #define SQLITE_ACCESS_READ 2 /* Unused */
  1396. /*
  1397. ** CAPI3REF: Flags for the xShmLock VFS method
  1398. **
  1399. ** These integer constants define the various locking operations
  1400. ** allowed by the xShmLock method of [sqlite3_io_methods]. The
  1401. ** following are the only legal combinations of flags to the
  1402. ** xShmLock method:
  1403. **
  1404. ** <ul>
  1405. ** <li> SQLITE_SHM_LOCK | SQLITE_SHM_SHARED
  1406. ** <li> SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE
  1407. ** <li> SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED
  1408. ** <li> SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE
  1409. ** </ul>
  1410. **
  1411. ** When unlocking, the same SHARED or EXCLUSIVE flag must be supplied as
  1412. ** was given on the corresponding lock.
  1413. **
  1414. ** The xShmLock method can transition between unlocked and SHARED or
  1415. ** between unlocked and EXCLUSIVE. It cannot transition between SHARED
  1416. ** and EXCLUSIVE.
  1417. */
  1418. #define SQLITE_SHM_UNLOCK 1
  1419. #define SQLITE_SHM_LOCK 2
  1420. #define SQLITE_SHM_SHARED 4
  1421. #define SQLITE_SHM_EXCLUSIVE 8
  1422. /*
  1423. ** CAPI3REF: Maximum xShmLock index
  1424. **
  1425. ** The xShmLock method on [sqlite3_io_methods] may use values
  1426. ** between 0 and this upper bound as its "offset" argument.
  1427. ** The SQLite core will never attempt to acquire or release a
  1428. ** lock outside of this range
  1429. */
  1430. #define SQLITE_SHM_NLOCK 8
  1431. /*
  1432. ** CAPI3REF: Initialize The SQLite Library
  1433. **
  1434. ** ^The sqlite3_initialize() routine initializes the
  1435. ** SQLite library. ^The sqlite3_shutdown() routine
  1436. ** deallocates any resources that were allocated by sqlite3_initialize().
  1437. ** These routines are designed to aid in process initialization and
  1438. ** shutdown on embedded systems. Workstation applications using
  1439. ** SQLite normally do not need to invoke either of these routines.
  1440. **
  1441. ** A call to sqlite3_initialize() is an "effective" call if it is
  1442. ** the first time sqlite3_initialize() is invoked during the lifetime of
  1443. ** the process, or if it is the first time sqlite3_initialize() is invoked
  1444. ** following a call to sqlite3_shutdown(). ^(Only an effective call
  1445. ** of sqlite3_initialize() does any initialization. All other calls
  1446. ** are harmless no-ops.)^
  1447. **
  1448. ** A call to sqlite3_shutdown() is an "effective" call if it is the first
  1449. ** call to sqlite3_shutdown() since the last sqlite3_initialize(). ^(Only
  1450. ** an effective call to sqlite3_shutdown() does any deinitialization.
  1451. ** All other valid calls to sqlite3_shutdown() are harmless no-ops.)^
  1452. **
  1453. ** The sqlite3_initialize() interface is threadsafe, but sqlite3_shutdown()
  1454. ** is not. The sqlite3_shutdown() interface must only be called from a
  1455. ** single thread. All open [database connections] must be closed and all
  1456. ** other SQLite resources must be deallocated prior to invoking
  1457. ** sqlite3_shutdown().
  1458. **
  1459. ** Among other things, ^sqlite3_initialize() will invoke
  1460. ** sqlite3_os_init(). Similarly, ^sqlite3_shutdown()
  1461. ** will invoke sqlite3_os_end().
  1462. **
  1463. ** ^The sqlite3_initialize() routine returns [SQLITE_OK] on success.
  1464. ** ^If for some reason, sqlite3_initialize() is unable to initialize
  1465. ** the library (perhaps it is unable to allocate a needed resource such
  1466. ** as a mutex) it returns an [error code] other than [SQLITE_OK].
  1467. **
  1468. ** ^The sqlite3_initialize() routine is called internally by many other
  1469. ** SQLite interfaces so that an application usually does not need to
  1470. ** invoke sqlite3_initialize() directly. For example, [sqlite3_open()]
  1471. ** calls sqlite3_initialize() so the SQLite library will be automatically
  1472. ** initialized when [sqlite3_open()] is called if it has not be initialized
  1473. ** already. ^However, if SQLite is compiled with the [SQLITE_OMIT_AUTOINIT]
  1474. ** compile-time option, then the automatic calls to sqlite3_initialize()
  1475. ** are omitted and the application must call sqlite3_initialize() directly
  1476. ** prior to using any other SQLite interface. For maximum portability,
  1477. ** it is recommended that applications always invoke sqlite3_initialize()
  1478. ** directly prior to using any other SQLite interface. Future releases
  1479. ** of SQLite may require this. In other words, the behavior exhibited
  1480. ** when SQLite is compiled with [SQLITE_OMIT_AUTOINIT] might become the
  1481. ** default behavior in some future release of SQLite.
  1482. **
  1483. ** The sqlite3_os_init() routine does operating-system specific
  1484. ** initialization of the SQLite library. The sqlite3_os_end()
  1485. ** routine undoes the effect of sqlite3_os_init(). Typical tasks
  1486. ** performed by these routines include allocation or deallocation
  1487. ** of static resources, initialization of global variables,
  1488. ** setting up a default [sqlite3_vfs] module, or setting up
  1489. ** a default configuration using [sqlite3_config()].
  1490. **
  1491. ** The application should never invoke either sqlite3_os_init()
  1492. ** or sqlite3_os_end() directly. The application should only invoke
  1493. ** sqlite3_initialize() and sqlite3_shutdown(). The sqlite3_os_init()
  1494. ** interface is called automatically by sqlite3_initialize() and
  1495. ** sqlite3_os_end() is called by sqlite3_shutdown(). Appropriate
  1496. ** implementations for sqlite3_os_init() and sqlite3_os_end()
  1497. ** are built into SQLite when it is compiled for Unix, Windows, or OS/2.
  1498. ** When [custom builds | built for other platforms]
  1499. ** (using the [SQLITE_OS_OTHER=1] compile-time
  1500. ** option) the application must supply a suitable implementation for
  1501. ** sqlite3_os_init() and sqlite3_os_end(). An application-supplied
  1502. ** implementation of sqlite3_os_init() or sqlite3_os_end()
  1503. ** must return [SQLITE_OK] on success and some other [error code] upon
  1504. ** failure.
  1505. */
  1506. SQLITE_API int SQLITE_STDCALL sqlite3_initialize(void);
  1507. SQLITE_API int SQLITE_STDCALL sqlite3_shutdown(void);
  1508. SQLITE_API int SQLITE_STDCALL sqlite3_os_init(void);
  1509. SQLITE_API int SQLITE_STDCALL sqlite3_os_end(void);
  1510. /*
  1511. ** CAPI3REF: Configuring The SQLite Library
  1512. **
  1513. ** The sqlite3_config() interface is used to make global configuration
  1514. ** changes to SQLite in order to tune SQLite to the specific needs of
  1515. ** the application. The default configuration is recommended for most
  1516. ** applications and so this routine is usually not necessary. It is
  1517. ** provided to support rare applications with unusual needs.
  1518. **
  1519. ** The sqlite3_config() interface is not threadsafe. The application
  1520. ** must insure that no other SQLite interfaces are invoked by other
  1521. ** threads while sqlite3_config() is running. Furthermore, sqlite3_config()
  1522. ** may only be invoked prior to library initialization using
  1523. ** [sqlite3_initialize()] or after shutdown by [sqlite3_shutdown()].
  1524. ** ^If sqlite3_config() is called after [sqlite3_initialize()] and before
  1525. ** [sqlite3_shutdown()] then it will return SQLITE_MISUSE.
  1526. ** Note, however, that ^sqlite3_config() can be called as part of the
  1527. ** implementation of an application-defined [sqlite3_os_init()].
  1528. **
  1529. ** The first argument to sqlite3_config() is an integer
  1530. ** [configuration option] that determines
  1531. ** what property of SQLite is to be configured. Subsequent arguments
  1532. ** vary depending on the [configuration option]
  1533. ** in the first argument.
  1534. **
  1535. ** ^When a configuration option is set, sqlite3_config() returns [SQLITE_OK].
  1536. ** ^If the option is unknown or SQLite is unable to set the option
  1537. ** then this routine returns a non-zero [error code].
  1538. */
  1539. SQLITE_API int SQLITE_CDECL sqlite3_config(int, ...);
  1540. /*
  1541. ** CAPI3REF: Configure database connections
  1542. ** METHOD: sqlite3
  1543. **
  1544. ** The sqlite3_db_config() interface is used to make configuration
  1545. ** changes to a [database connection]. The interface is similar to
  1546. ** [sqlite3_config()] except that the changes apply to a single
  1547. ** [database connection] (specified in the first argument).
  1548. **
  1549. ** The second argument to sqlite3_db_config(D,V,...) is the
  1550. ** [SQLITE_DBCONFIG_LOOKASIDE | configuration verb] - an integer code
  1551. ** that indicates what aspect of the [database connection] is being configured.
  1552. ** Subsequent arguments vary depending on the configuration verb.
  1553. **
  1554. ** ^Calls to sqlite3_db_config() return SQLITE_OK if and only if
  1555. ** the call is considered successful.
  1556. */
  1557. SQLITE_API int SQLITE_CDECL sqlite3_db_config(sqlite3*, int op, ...);
  1558. /*
  1559. ** CAPI3REF: Memory Allocation Routines
  1560. **
  1561. ** An instance of this object defines the interface between SQLite
  1562. ** and low-level memory allocation routines.
  1563. **
  1564. ** This object is used in only one place in the SQLite interface.
  1565. ** A pointer to an instance of this object is the argument to
  1566. ** [sqlite3_config()] when the configuration option is
  1567. ** [SQLITE_CONFIG_MALLOC] or [SQLITE_CONFIG_GETMALLOC].
  1568. ** By creating an instance of this object
  1569. ** and passing it to [sqlite3_config]([SQLITE_CONFIG_MALLOC])
  1570. ** during configuration, an application can specify an alternative
  1571. ** memory allocation subsystem for SQLite to use for all of its
  1572. ** dynamic memory needs.
  1573. **
  1574. ** Note that SQLite comes with several [built-in memory allocators]
  1575. ** that are perfectly adequate for the overwhelming majority of applications
  1576. ** and that this object is only useful to a tiny minority of applications
  1577. ** with specialized memory allocation requirements. This object is
  1578. ** also used during testing of SQLite in order to specify an alternative
  1579. ** memory allocator that simulates memory out-of-memory conditions in
  1580. ** order to verify that SQLite recovers gracefully from such
  1581. ** conditions.
  1582. **
  1583. ** The xMalloc, xRealloc, and xFree methods must work like the
  1584. ** malloc(), realloc() and free() functions from the standard C library.
  1585. ** ^SQLite guarantees that the second argument to
  1586. ** xRealloc is always a value returned by a prior call to xRoundup.
  1587. **
  1588. ** xSize should return the allocated size of a memory allocation
  1589. ** previously obtained from xMalloc or xRealloc. The allocated size
  1590. ** is always at least as big as the requested size but may be larger.
  1591. **
  1592. ** The xRoundup method returns what would be the allocated size of
  1593. ** a memory allocation given a particular requested size. Most memory
  1594. ** allocators round up memory allocations at least to the next multiple
  1595. ** of 8. Some allocators round up to a larger multiple or to a power of 2.
  1596. ** Every memory allocation request coming in through [sqlite3_malloc()]
  1597. ** or [sqlite3_realloc()] first calls xRoundup. If xRoundup returns 0,
  1598. ** that causes the corresponding memory allocation to fail.
  1599. **
  1600. ** The xInit method initializes the memory allocator. For example,
  1601. ** it might allocate any require mutexes or initialize internal data
  1602. ** structures. The xShutdown method is invoked (indirectly) by
  1603. ** [sqlite3_shutdown()] and should deallocate any resources acquired
  1604. ** by xInit. The pAppData pointer is used as the only parameter to
  1605. ** xInit and xShutdown.
  1606. **
  1607. ** SQLite holds the [SQLITE_MUTEX_STATIC_MASTER] mutex when it invokes
  1608. ** the xInit method, so the xInit method need not be threadsafe. The
  1609. ** xShutdown method is only called from [sqlite3_shutdown()] so it does
  1610. ** not need to be threadsafe either. For all other methods, SQLite
  1611. ** holds the [SQLITE_MUTEX_STATIC_MEM] mutex as long as the
  1612. ** [SQLITE_CONFIG_MEMSTATUS] configuration option is turned on (which
  1613. ** it is by default) and so the methods are automatically serialized.
  1614. ** However, if [SQLITE_CONFIG_MEMSTATUS] is disabled, then the other
  1615. ** methods must be threadsafe or else make their own arrangements for
  1616. ** serialization.
  1617. **
  1618. ** SQLite will never invoke xInit() more than once without an intervening
  1619. ** call to xShutdown().
  1620. */
  1621. typedef struct sqlite3_mem_methods sqlite3_mem_methods;
  1622. struct sqlite3_mem_methods {
  1623. void *(*xMalloc)(int); /* Memory allocation function */
  1624. void (*xFree)(void*); /* Free a prior allocation */
  1625. void *(*xRealloc)(void*,int); /* Resize an allocation */
  1626. int (*xSize)(void*); /* Return the size of an allocation */
  1627. int (*xRoundup)(int); /* Round up request size to allocation size */
  1628. int (*xInit)(void*); /* Initialize the memory allocator */
  1629. void (*xShutdown)(void*); /* Deinitialize the memory allocator */
  1630. void *pAppData; /* Argument to xInit() and xShutdown() */
  1631. };
  1632. /*
  1633. ** CAPI3REF: Configuration Options
  1634. ** KEYWORDS: {configuration option}
  1635. **
  1636. ** These constants are the available integer configuration options that
  1637. ** can be passed as the first argument to the [sqlite3_config()] interface.
  1638. **
  1639. ** New configuration options may be added in future releases of SQLite.
  1640. ** Existing configuration options might be discontinued. Applications
  1641. ** should check the return code from [sqlite3_config()] to make sure that
  1642. ** the call worked. The [sqlite3_config()] interface will return a
  1643. ** non-zero [error code] if a discontinued or unsupported configuration option
  1644. ** is invoked.
  1645. **
  1646. ** <dl>
  1647. ** [[SQLITE_CONFIG_SINGLETHREAD]] <dt>SQLITE_CONFIG_SINGLETHREAD</dt>
  1648. ** <dd>There are no arguments to this option. ^This option sets the
  1649. ** [threading mode] to Single-thread. In other words, it disables
  1650. ** all mutexing and puts SQLite into a mode where it can only be used
  1651. ** by a single thread. ^If SQLite is compiled with
  1652. ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
  1653. ** it is not possible to change the [threading mode] from its default
  1654. ** value of Single-thread and so [sqlite3_config()] will return
  1655. ** [SQLITE_ERROR] if called with the SQLITE_CONFIG_SINGLETHREAD
  1656. ** configuration option.</dd>
  1657. **
  1658. ** [[SQLITE_CONFIG_MULTITHREAD]] <dt>SQLITE_CONFIG_MULTITHREAD</dt>
  1659. ** <dd>There are no arguments to this option. ^This option sets the
  1660. ** [threading mode] to Multi-thread. In other words, it disables
  1661. ** mutexing on [database connection] and [prepared statement] objects.
  1662. ** The application is responsible for serializing access to
  1663. ** [database connections] and [prepared statements]. But other mutexes
  1664. ** are enabled so that SQLite will be safe to use in a multi-threaded
  1665. ** environment as long as no two threads attempt to use the same
  1666. ** [database connection] at the same time. ^If SQLite is compiled with
  1667. ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
  1668. ** it is not possible to set the Multi-thread [threading mode] and
  1669. ** [sqlite3_config()] will return [SQLITE_ERROR] if called with the
  1670. ** SQLITE_CONFIG_MULTITHREAD configuration option.</dd>
  1671. **
  1672. ** [[SQLITE_CONFIG_SERIALIZED]] <dt>SQLITE_CONFIG_SERIALIZED</dt>
  1673. ** <dd>There are no arguments to this option. ^This option sets the
  1674. ** [threading mode] to Serialized. In other words, this option enables
  1675. ** all mutexes including the recursive
  1676. ** mutexes on [database connection] and [prepared statement] objects.
  1677. ** In this mode (which is the default when SQLite is compiled with
  1678. ** [SQLITE_THREADSAFE=1]) the SQLite library will itself serialize access
  1679. ** to [database connections] and [prepared statements] so that the
  1680. ** application is free to use the same [database connection] or the
  1681. ** same [prepared statement] in different threads at the same time.
  1682. ** ^If SQLite is compiled with
  1683. ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
  1684. ** it is not possible to set the Serialized [threading mode] and
  1685. ** [sqlite3_config()] will return [SQLITE_ERROR] if called with the
  1686. ** SQLITE_CONFIG_SERIALIZED configuration option.</dd>
  1687. **
  1688. ** [[SQLITE_CONFIG_MALLOC]] <dt>SQLITE_CONFIG_MALLOC</dt>
  1689. ** <dd> ^(The SQLITE_CONFIG_MALLOC option takes a single argument which is
  1690. ** a pointer to an instance of the [sqlite3_mem_methods] structure.
  1691. ** The argument specifies
  1692. ** alternative low-level memory allocation routines to be used in place of
  1693. ** the memory allocation routines built into SQLite.)^ ^SQLite makes
  1694. ** its own private copy of the content of the [sqlite3_mem_methods] structure
  1695. ** before the [sqlite3_config()] call returns.</dd>
  1696. **
  1697. ** [[SQLITE_CONFIG_GETMALLOC]] <dt>SQLITE_CONFIG_GETMALLOC</dt>
  1698. ** <dd> ^(The SQLITE_CONFIG_GETMALLOC option takes a single argument which
  1699. ** is a pointer to an instance of the [sqlite3_mem_methods] structure.
  1700. ** The [sqlite3_mem_methods]
  1701. ** structure is filled with the currently defined memory allocation routines.)^
  1702. ** This option can be used to overload the default memory allocation
  1703. ** routines with a wrapper that simulations memory allocation failure or
  1704. ** tracks memory usage, for example. </dd>
  1705. **
  1706. ** [[SQLITE_CONFIG_MEMSTATUS]] <dt>SQLITE_CONFIG_MEMSTATUS</dt>
  1707. ** <dd> ^The SQLITE_CONFIG_MEMSTATUS option takes single argument of type int,
  1708. ** interpreted as a boolean, which enables or disables the collection of
  1709. ** memory allocation statistics. ^(When memory allocation statistics are
  1710. ** disabled, the following SQLite interfaces become non-operational:
  1711. ** <ul>
  1712. ** <li> [sqlite3_memory_used()]
  1713. ** <li> [sqlite3_memory_highwater()]
  1714. ** <li> [sqlite3_soft_heap_limit64()]
  1715. ** <li> [sqlite3_status64()]
  1716. ** </ul>)^
  1717. ** ^Memory allocation statistics are enabled by default unless SQLite is
  1718. ** compiled with [SQLITE_DEFAULT_MEMSTATUS]=0 in which case memory
  1719. ** allocation statistics are disabled by default.
  1720. ** </dd>
  1721. **
  1722. ** [[SQLITE_CONFIG_SCRATCH]] <dt>SQLITE_CONFIG_SCRATCH</dt>
  1723. ** <dd> ^The SQLITE_CONFIG_SCRATCH option specifies a static memory buffer
  1724. ** that SQLite can use for scratch memory. ^(There are three arguments
  1725. ** to SQLITE_CONFIG_SCRATCH: A pointer an 8-byte
  1726. ** aligned memory buffer from which the scratch allocations will be
  1727. ** drawn, the size of each scratch allocation (sz),
  1728. ** and the maximum number of scratch allocations (N).)^
  1729. ** The first argument must be a pointer to an 8-byte aligned buffer
  1730. ** of at least sz*N bytes of memory.
  1731. ** ^SQLite will not use more than one scratch buffers per thread.
  1732. ** ^SQLite will never request a scratch buffer that is more than 6
  1733. ** times the database page size.
  1734. ** ^If SQLite needs needs additional
  1735. ** scratch memory beyond what is provided by this configuration option, then
  1736. ** [sqlite3_malloc()] will be used to obtain the memory needed.<p>
  1737. ** ^When the application provides any amount of scratch memory using
  1738. ** SQLITE_CONFIG_SCRATCH, SQLite avoids unnecessary large
  1739. ** [sqlite3_malloc|heap allocations].
  1740. ** This can help [Robson proof|prevent memory allocation failures] due to heap
  1741. ** fragmentation in low-memory embedded systems.
  1742. ** </dd>
  1743. **
  1744. ** [[SQLITE_CONFIG_PAGECACHE]] <dt>SQLITE_CONFIG_PAGECACHE</dt>
  1745. ** <dd> ^The SQLITE_CONFIG_PAGECACHE option specifies a static memory buffer
  1746. ** that SQLite can use for the database page cache with the default page
  1747. ** cache implementation.
  1748. ** This configuration should not be used if an application-define page
  1749. ** cache implementation is loaded using the [SQLITE_CONFIG_PCACHE2]
  1750. ** configuration option.
  1751. ** ^There are three arguments to SQLITE_CONFIG_PAGECACHE: A pointer to
  1752. ** 8-byte aligned
  1753. ** memory, the size of each page buffer (sz), and the number of pages (N).
  1754. ** The sz argument should be the size of the largest database page
  1755. ** (a power of two between 512 and 65536) plus some extra bytes for each
  1756. ** page header. ^The number of extra bytes needed by the page header
  1757. ** can be determined using the [SQLITE_CONFIG_PCACHE_HDRSZ] option
  1758. ** to [sqlite3_config()].
  1759. ** ^It is harmless, apart from the wasted memory,
  1760. ** for the sz parameter to be larger than necessary. The first
  1761. ** argument should pointer to an 8-byte aligned block of memory that
  1762. ** is at least sz*N bytes of memory, otherwise subsequent behavior is
  1763. ** undefined.
  1764. ** ^SQLite will use the memory provided by the first argument to satisfy its
  1765. ** memory needs for the first N pages that it adds to cache. ^If additional
  1766. ** page cache memory is needed beyond what is provided by this option, then
  1767. ** SQLite goes to [sqlite3_malloc()] for the additional storage space.</dd>
  1768. **
  1769. ** [[SQLITE_CONFIG_HEAP]] <dt>SQLITE_CONFIG_HEAP</dt>
  1770. ** <dd> ^The SQLITE_CONFIG_HEAP option specifies a static memory buffer
  1771. ** that SQLite will use for all of its dynamic memory allocation needs
  1772. ** beyond those provided for by [SQLITE_CONFIG_SCRATCH] and
  1773. ** [SQLITE_CONFIG_PAGECACHE].
  1774. ** ^The SQLITE_CONFIG_HEAP option is only available if SQLite is compiled
  1775. ** with either [SQLITE_ENABLE_MEMSYS3] or [SQLITE_ENABLE_MEMSYS5] and returns
  1776. ** [SQLITE_ERROR] if invoked otherwise.
  1777. ** ^There are three arguments to SQLITE_CONFIG_HEAP:
  1778. ** An 8-byte aligned pointer to the memory,
  1779. ** the number of bytes in the memory buffer, and the minimum allocation size.
  1780. ** ^If the first pointer (the memory pointer) is NULL, then SQLite reverts
  1781. ** to using its default memory allocator (the system malloc() implementation),
  1782. ** undoing any prior invocation of [SQLITE_CONFIG_MALLOC]. ^If the
  1783. ** memory pointer is not NULL then the alternative memory
  1784. ** allocator is engaged to handle all of SQLites memory allocation needs.
  1785. ** The first pointer (the memory pointer) must be aligned to an 8-byte
  1786. ** boundary or subsequent behavior of SQLite will be undefined.
  1787. ** The minimum allocation size is capped at 2**12. Reasonable values
  1788. ** for the minimum allocation size are 2**5 through 2**8.</dd>
  1789. **
  1790. ** [[SQLITE_CONFIG_MUTEX]] <dt>SQLITE_CONFIG_MUTEX</dt>
  1791. ** <dd> ^(The SQLITE_CONFIG_MUTEX option takes a single argument which is a
  1792. ** pointer to an instance of the [sqlite3_mutex_methods] structure.
  1793. ** The argument specifies alternative low-level mutex routines to be used
  1794. ** in place the mutex routines built into SQLite.)^ ^SQLite makes a copy of
  1795. ** the content of the [sqlite3_mutex_methods] structure before the call to
  1796. ** [sqlite3_config()] returns. ^If SQLite is compiled with
  1797. ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
  1798. ** the entire mutexing subsystem is omitted from the build and hence calls to
  1799. ** [sqlite3_config()] with the SQLITE_CONFIG_MUTEX configuration option will
  1800. ** return [SQLITE_ERROR].</dd>
  1801. **
  1802. ** [[SQLITE_CONFIG_GETMUTEX]] <dt>SQLITE_CONFIG_GETMUTEX</dt>
  1803. ** <dd> ^(The SQLITE_CONFIG_GETMUTEX option takes a single argument which
  1804. ** is a pointer to an instance of the [sqlite3_mutex_methods] structure. The
  1805. ** [sqlite3_mutex_methods]
  1806. ** structure is filled with the currently defined mutex routines.)^
  1807. ** This option can be used to overload the default mutex allocation
  1808. ** routines with a wrapper used to track mutex usage for performance
  1809. ** profiling or testing, for example. ^If SQLite is compiled with
  1810. ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
  1811. ** the entire mutexing subsystem is omitted from the build and hence calls to
  1812. ** [sqlite3_config()] with the SQLITE_CONFIG_GETMUTEX configuration option will
  1813. ** return [SQLITE_ERROR].</dd>
  1814. **
  1815. ** [[SQLITE_CONFIG_LOOKASIDE]] <dt>SQLITE_CONFIG_LOOKASIDE</dt>
  1816. ** <dd> ^(The SQLITE_CONFIG_LOOKASIDE option takes two arguments that determine
  1817. ** the default size of lookaside memory on each [database connection].
  1818. ** The first argument is the
  1819. ** size of each lookaside buffer slot and the second is the number of
  1820. ** slots allocated to each database connection.)^ ^(SQLITE_CONFIG_LOOKASIDE
  1821. ** sets the <i>default</i> lookaside size. The [SQLITE_DBCONFIG_LOOKASIDE]
  1822. ** option to [sqlite3_db_config()] can be used to change the lookaside
  1823. ** configuration on individual connections.)^ </dd>
  1824. **
  1825. ** [[SQLITE_CONFIG_PCACHE2]] <dt>SQLITE_CONFIG_PCACHE2</dt>
  1826. ** <dd> ^(The SQLITE_CONFIG_PCACHE2 option takes a single argument which is
  1827. ** a pointer to an [sqlite3_pcache_methods2] object. This object specifies
  1828. ** the interface to a custom page cache implementation.)^
  1829. ** ^SQLite makes a copy of the [sqlite3_pcache_methods2] object.</dd>
  1830. **
  1831. ** [[SQLITE_CONFIG_GETPCACHE2]] <dt>SQLITE_CONFIG_GETPCACHE2</dt>
  1832. ** <dd> ^(The SQLITE_CONFIG_GETPCACHE2 option takes a single argument which
  1833. ** is a pointer to an [sqlite3_pcache_methods2] object. SQLite copies of
  1834. ** the current page cache implementation into that object.)^ </dd>
  1835. **
  1836. ** [[SQLITE_CONFIG_LOG]] <dt>SQLITE_CONFIG_LOG</dt>
  1837. ** <dd> The SQLITE_CONFIG_LOG option is used to configure the SQLite
  1838. ** global [error log].
  1839. ** (^The SQLITE_CONFIG_LOG option takes two arguments: a pointer to a
  1840. ** function with a call signature of void(*)(void*,int,const char*),
  1841. ** and a pointer to void. ^If the function pointer is not NULL, it is
  1842. ** invoked by [sqlite3_log()] to process each logging event. ^If the
  1843. ** function pointer is NULL, the [sqlite3_log()] interface becomes a no-op.
  1844. ** ^The void pointer that is the second argument to SQLITE_CONFIG_LOG is
  1845. ** passed through as the first parameter to the application-defined logger
  1846. ** function whenever that function is invoked. ^The second parameter to
  1847. ** the logger function is a copy of the first parameter to the corresponding
  1848. ** [sqlite3_log()] call and is intended to be a [result code] or an
  1849. ** [extended result code]. ^The third parameter passed to the logger is
  1850. ** log message after formatting via [sqlite3_snprintf()].
  1851. ** The SQLite logging interface is not reentrant; the logger function
  1852. ** supplied by the application must not invoke any SQLite interface.
  1853. ** In a multi-threaded application, the application-defined logger
  1854. ** function must be threadsafe. </dd>
  1855. **
  1856. ** [[SQLITE_CONFIG_URI]] <dt>SQLITE_CONFIG_URI
  1857. ** <dd>^(The SQLITE_CONFIG_URI option takes a single argument of type int.
  1858. ** If non-zero, then URI handling is globally enabled. If the parameter is zero,
  1859. ** then URI handling is globally disabled.)^ ^If URI handling is globally
  1860. ** enabled, all filenames passed to [sqlite3_open()], [sqlite3_open_v2()],
  1861. ** [sqlite3_open16()] or
  1862. ** specified as part of [ATTACH] commands are interpreted as URIs, regardless
  1863. ** of whether or not the [SQLITE_OPEN_URI] flag is set when the database
  1864. ** connection is opened. ^If it is globally disabled, filenames are
  1865. ** only interpreted as URIs if the SQLITE_OPEN_URI flag is set when the
  1866. ** database connection is opened. ^(By default, URI handling is globally
  1867. ** disabled. The default value may be changed by compiling with the
  1868. ** [SQLITE_USE_URI] symbol defined.)^
  1869. **
  1870. ** [[SQLITE_CONFIG_COVERING_INDEX_SCAN]] <dt>SQLITE_CONFIG_COVERING_INDEX_SCAN
  1871. ** <dd>^The SQLITE_CONFIG_COVERING_INDEX_SCAN option takes a single integer
  1872. ** argument which is interpreted as a boolean in order to enable or disable
  1873. ** the use of covering indices for full table scans in the query optimizer.
  1874. ** ^The default setting is determined
  1875. ** by the [SQLITE_ALLOW_COVERING_INDEX_SCAN] compile-time option, or is "on"
  1876. ** if that compile-time option is omitted.
  1877. ** The ability to disable the use of covering indices for full table scans
  1878. ** is because some incorrectly coded legacy applications might malfunction
  1879. ** when the optimization is enabled. Providing the ability to
  1880. ** disable the optimization allows the older, buggy application code to work
  1881. ** without change even with newer versions of SQLite.
  1882. **
  1883. ** [[SQLITE_CONFIG_PCACHE]] [[SQLITE_CONFIG_GETPCACHE]]
  1884. ** <dt>SQLITE_CONFIG_PCACHE and SQLITE_CONFIG_GETPCACHE
  1885. ** <dd> These options are obsolete and should not be used by new code.
  1886. ** They are retained for backwards compatibility but are now no-ops.
  1887. ** </dd>
  1888. **
  1889. ** [[SQLITE_CONFIG_SQLLOG]]
  1890. ** <dt>SQLITE_CONFIG_SQLLOG
  1891. ** <dd>This option is only available if sqlite is compiled with the
  1892. ** [SQLITE_ENABLE_SQLLOG] pre-processor macro defined. The first argument should
  1893. ** be a pointer to a function of type void(*)(void*,sqlite3*,const char*, int).
  1894. ** The second should be of type (void*). The callback is invoked by the library
  1895. ** in three separate circumstances, identified by the value passed as the
  1896. ** fourth parameter. If the fourth parameter is 0, then the database connection
  1897. ** passed as the second argument has just been opened. The third argument
  1898. ** points to a buffer containing the name of the main database file. If the
  1899. ** fourth parameter is 1, then the SQL statement that the third parameter
  1900. ** points to has just been executed. Or, if the fourth parameter is 2, then
  1901. ** the connection being passed as the second parameter is being closed. The
  1902. ** third parameter is passed NULL In this case. An example of using this
  1903. ** configuration option can be seen in the "test_sqllog.c" source file in
  1904. ** the canonical SQLite source tree.</dd>
  1905. **
  1906. ** [[SQLITE_CONFIG_MMAP_SIZE]]
  1907. ** <dt>SQLITE_CONFIG_MMAP_SIZE
  1908. ** <dd>^SQLITE_CONFIG_MMAP_SIZE takes two 64-bit integer (sqlite3_int64) values
  1909. ** that are the default mmap size limit (the default setting for
  1910. ** [PRAGMA mmap_size]) and the maximum allowed mmap size limit.
  1911. ** ^The default setting can be overridden by each database connection using
  1912. ** either the [PRAGMA mmap_size] command, or by using the
  1913. ** [SQLITE_FCNTL_MMAP_SIZE] file control. ^(The maximum allowed mmap size
  1914. ** will be silently truncated if necessary so that it does not exceed the
  1915. ** compile-time maximum mmap size set by the
  1916. ** [SQLITE_MAX_MMAP_SIZE] compile-time option.)^
  1917. ** ^If either argument to this option is negative, then that argument is
  1918. ** changed to its compile-time default.
  1919. **
  1920. ** [[SQLITE_CONFIG_WIN32_HEAPSIZE]]
  1921. ** <dt>SQLITE_CONFIG_WIN32_HEAPSIZE
  1922. ** <dd>^The SQLITE_CONFIG_WIN32_HEAPSIZE option is only available if SQLite is
  1923. ** compiled for Windows with the [SQLITE_WIN32_MALLOC] pre-processor macro
  1924. ** defined. ^SQLITE_CONFIG_WIN32_HEAPSIZE takes a 32-bit unsigned integer value
  1925. ** that specifies the maximum size of the created heap.
  1926. **
  1927. ** [[SQLITE_CONFIG_PCACHE_HDRSZ]]
  1928. ** <dt>SQLITE_CONFIG_PCACHE_HDRSZ
  1929. ** <dd>^The SQLITE_CONFIG_PCACHE_HDRSZ option takes a single parameter which
  1930. ** is a pointer to an integer and writes into that integer the number of extra
  1931. ** bytes per page required for each page in [SQLITE_CONFIG_PAGECACHE].
  1932. ** The amount of extra space required can change depending on the compiler,
  1933. ** target platform, and SQLite version.
  1934. **
  1935. ** [[SQLITE_CONFIG_PMASZ]]
  1936. ** <dt>SQLITE_CONFIG_PMASZ
  1937. ** <dd>^The SQLITE_CONFIG_PMASZ option takes a single parameter which
  1938. ** is an unsigned integer and sets the "Minimum PMA Size" for the multithreaded
  1939. ** sorter to that integer. The default minimum PMA Size is set by the
  1940. ** [SQLITE_SORTER_PMASZ] compile-time option. New threads are launched
  1941. ** to help with sort operations when multithreaded sorting
  1942. ** is enabled (using the [PRAGMA threads] command) and the amount of content
  1943. ** to be sorted exceeds the page size times the minimum of the
  1944. ** [PRAGMA cache_size] setting and this value.
  1945. ** </dl>
  1946. */
  1947. #define SQLITE_CONFIG_SINGLETHREAD 1 /* nil */
  1948. #define SQLITE_CONFIG_MULTITHREAD 2 /* nil */
  1949. #define SQLITE_CONFIG_SERIALIZED 3 /* nil */
  1950. #define SQLITE_CONFIG_MALLOC 4 /* sqlite3_mem_methods* */
  1951. #define SQLITE_CONFIG_GETMALLOC 5 /* sqlite3_mem_methods* */
  1952. #define SQLITE_CONFIG_SCRATCH 6 /* void*, int sz, int N */
  1953. #define SQLITE_CONFIG_PAGECACHE 7 /* void*, int sz, int N */
  1954. #define SQLITE_CONFIG_HEAP 8 /* void*, int nByte, int min */
  1955. #define SQLITE_CONFIG_MEMSTATUS 9 /* boolean */
  1956. #define SQLITE_CONFIG_MUTEX 10 /* sqlite3_mutex_methods* */
  1957. #define SQLITE_CONFIG_GETMUTEX 11 /* sqlite3_mutex_methods* */
  1958. /* previously SQLITE_CONFIG_CHUNKALLOC 12 which is now unused. */
  1959. #define SQLITE_CONFIG_LOOKASIDE 13 /* int int */
  1960. #define SQLITE_CONFIG_PCACHE 14 /* no-op */
  1961. #define SQLITE_CONFIG_GETPCACHE 15 /* no-op */
  1962. #define SQLITE_CONFIG_LOG 16 /* xFunc, void* */
  1963. #define SQLITE_CONFIG_URI 17 /* int */
  1964. #define SQLITE_CONFIG_PCACHE2 18 /* sqlite3_pcache_methods2* */
  1965. #define SQLITE_CONFIG_GETPCACHE2 19 /* sqlite3_pcache_methods2* */
  1966. #define SQLITE_CONFIG_COVERING_INDEX_SCAN 20 /* int */
  1967. #define SQLITE_CONFIG_SQLLOG 21 /* xSqllog, void* */
  1968. #define SQLITE_CONFIG_MMAP_SIZE 22 /* sqlite3_int64, sqlite3_int64 */
  1969. #define SQLITE_CONFIG_WIN32_HEAPSIZE 23 /* int nByte */
  1970. #define SQLITE_CONFIG_PCACHE_HDRSZ 24 /* int *psz */
  1971. #define SQLITE_CONFIG_PMASZ 25 /* unsigned int szPma */
  1972. /*
  1973. ** CAPI3REF: Database Connection Configuration Options
  1974. **
  1975. ** These constants are the available integer configuration options that
  1976. ** can be passed as the second argument to the [sqlite3_db_config()] interface.
  1977. **
  1978. ** New configuration options may be added in future releases of SQLite.
  1979. ** Existing configuration options might be discontinued. Applications
  1980. ** should check the return code from [sqlite3_db_config()] to make sure that
  1981. ** the call worked. ^The [sqlite3_db_config()] interface will return a
  1982. ** non-zero [error code] if a discontinued or unsupported configuration option
  1983. ** is invoked.
  1984. **
  1985. ** <dl>
  1986. ** <dt>SQLITE_DBCONFIG_LOOKASIDE</dt>
  1987. ** <dd> ^This option takes three additional arguments that determine the
  1988. ** [lookaside memory allocator] configuration for the [database connection].
  1989. ** ^The first argument (the third parameter to [sqlite3_db_config()] is a
  1990. ** pointer to a memory buffer to use for lookaside memory.
  1991. ** ^The first argument after the SQLITE_DBCONFIG_LOOKASIDE verb
  1992. ** may be NULL in which case SQLite will allocate the
  1993. ** lookaside buffer itself using [sqlite3_malloc()]. ^The second argument is the
  1994. ** size of each lookaside buffer slot. ^The third argument is the number of
  1995. ** slots. The size of the buffer in the first argument must be greater than
  1996. ** or equal to the product of the second and third arguments. The buffer
  1997. ** must be aligned to an 8-byte boundary. ^If the second argument to
  1998. ** SQLITE_DBCONFIG_LOOKASIDE is not a multiple of 8, it is internally
  1999. ** rounded down to the next smaller multiple of 8. ^(The lookaside memory
  2000. ** configuration for a database connection can only be changed when that
  2001. ** connection is not currently using lookaside memory, or in other words
  2002. ** when the "current value" returned by
  2003. ** [sqlite3_db_status](D,[SQLITE_CONFIG_LOOKASIDE],...) is zero.
  2004. ** Any attempt to change the lookaside memory configuration when lookaside
  2005. ** memory is in use leaves the configuration unchanged and returns
  2006. ** [SQLITE_BUSY].)^</dd>
  2007. **
  2008. ** <dt>SQLITE_DBCONFIG_ENABLE_FKEY</dt>
  2009. ** <dd> ^This option is used to enable or disable the enforcement of
  2010. ** [foreign key constraints]. There should be two additional arguments.
  2011. ** The first argument is an integer which is 0 to disable FK enforcement,
  2012. ** positive to enable FK enforcement or negative to leave FK enforcement
  2013. ** unchanged. The second parameter is a pointer to an integer into which
  2014. ** is written 0 or 1 to indicate whether FK enforcement is off or on
  2015. ** following this call. The second parameter may be a NULL pointer, in
  2016. ** which case the FK enforcement setting is not reported back. </dd>
  2017. **
  2018. ** <dt>SQLITE_DBCONFIG_ENABLE_TRIGGER</dt>
  2019. ** <dd> ^This option is used to enable or disable [CREATE TRIGGER | triggers].
  2020. ** There should be two additional arguments.
  2021. ** The first argument is an integer which is 0 to disable triggers,
  2022. ** positive to enable triggers or negative to leave the setting unchanged.
  2023. ** The second parameter is a pointer to an integer into which
  2024. ** is written 0 or 1 to indicate whether triggers are disabled or enabled
  2025. ** following this call. The second parameter may be a NULL pointer, in
  2026. ** which case the trigger setting is not reported back. </dd>
  2027. **
  2028. ** </dl>
  2029. */
  2030. #define SQLITE_DBCONFIG_LOOKASIDE 1001 /* void* int int */
  2031. #define SQLITE_DBCONFIG_ENABLE_FKEY 1002 /* int int* */
  2032. #define SQLITE_DBCONFIG_ENABLE_TRIGGER 1003 /* int int* */
  2033. /*
  2034. ** CAPI3REF: Enable Or Disable Extended Result Codes
  2035. ** METHOD: sqlite3
  2036. **
  2037. ** ^The sqlite3_extended_result_codes() routine enables or disables the
  2038. ** [extended result codes] feature of SQLite. ^The extended result
  2039. ** codes are disabled by default for historical compatibility.
  2040. */
  2041. SQLITE_API int SQLITE_STDCALL sqlite3_extended_result_codes(sqlite3*, int onoff);
  2042. /*
  2043. ** CAPI3REF: Last Insert Rowid
  2044. ** METHOD: sqlite3
  2045. **
  2046. ** ^Each entry in most SQLite tables (except for [WITHOUT ROWID] tables)
  2047. ** has a unique 64-bit signed
  2048. ** integer key called the [ROWID | "rowid"]. ^The rowid is always available
  2049. ** as an undeclared column named ROWID, OID, or _ROWID_ as long as those
  2050. ** names are not also used by explicitly declared columns. ^If
  2051. ** the table has a column of type [INTEGER PRIMARY KEY] then that column
  2052. ** is another alias for the rowid.
  2053. **
  2054. ** ^The sqlite3_last_insert_rowid(D) interface returns the [rowid] of the
  2055. ** most recent successful [INSERT] into a rowid table or [virtual table]
  2056. ** on database connection D.
  2057. ** ^Inserts into [WITHOUT ROWID] tables are not recorded.
  2058. ** ^If no successful [INSERT]s into rowid tables
  2059. ** have ever occurred on the database connection D,
  2060. ** then sqlite3_last_insert_rowid(D) returns zero.
  2061. **
  2062. ** ^(If an [INSERT] occurs within a trigger or within a [virtual table]
  2063. ** method, then this routine will return the [rowid] of the inserted
  2064. ** row as long as the trigger or virtual table method is running.
  2065. ** But once the trigger or virtual table method ends, the value returned
  2066. ** by this routine reverts to what it was before the trigger or virtual
  2067. ** table method began.)^
  2068. **
  2069. ** ^An [INSERT] that fails due to a constraint violation is not a
  2070. ** successful [INSERT] and does not change the value returned by this
  2071. ** routine. ^Thus INSERT OR FAIL, INSERT OR IGNORE, INSERT OR ROLLBACK,
  2072. ** and INSERT OR ABORT make no changes to the return value of this
  2073. ** routine when their insertion fails. ^(When INSERT OR REPLACE
  2074. ** encounters a constraint violation, it does not fail. The
  2075. ** INSERT continues to completion after deleting rows that caused
  2076. ** the constraint problem so INSERT OR REPLACE will always change
  2077. ** the return value of this interface.)^
  2078. **
  2079. ** ^For the purposes of this routine, an [INSERT] is considered to
  2080. ** be successful even if it is subsequently rolled back.
  2081. **
  2082. ** This function is accessible to SQL statements via the
  2083. ** [last_insert_rowid() SQL function].
  2084. **
  2085. ** If a separate thread performs a new [INSERT] on the same
  2086. ** database connection while the [sqlite3_last_insert_rowid()]
  2087. ** function is running and thus changes the last insert [rowid],
  2088. ** then the value returned by [sqlite3_last_insert_rowid()] is
  2089. ** unpredictable and might not equal either the old or the new
  2090. ** last insert [rowid].
  2091. */
  2092. SQLITE_API sqlite3_int64 SQLITE_STDCALL sqlite3_last_insert_rowid(sqlite3*);
  2093. /*
  2094. ** CAPI3REF: Count The Number Of Rows Modified
  2095. ** METHOD: sqlite3
  2096. **
  2097. ** ^This function returns the number of rows modified, inserted or
  2098. ** deleted by the most recently completed INSERT, UPDATE or DELETE
  2099. ** statement on the database connection specified by the only parameter.
  2100. ** ^Executing any other type of SQL statement does not modify the value
  2101. ** returned by this function.
  2102. **
  2103. ** ^Only changes made directly by the INSERT, UPDATE or DELETE statement are
  2104. ** considered - auxiliary changes caused by [CREATE TRIGGER | triggers],
  2105. ** [foreign key actions] or [REPLACE] constraint resolution are not counted.
  2106. **
  2107. ** Changes to a view that are intercepted by
  2108. ** [INSTEAD OF trigger | INSTEAD OF triggers] are not counted. ^The value
  2109. ** returned by sqlite3_changes() immediately after an INSERT, UPDATE or
  2110. ** DELETE statement run on a view is always zero. Only changes made to real
  2111. ** tables are counted.
  2112. **
  2113. ** Things are more complicated if the sqlite3_changes() function is
  2114. ** executed while a trigger program is running. This may happen if the
  2115. ** program uses the [changes() SQL function], or if some other callback
  2116. ** function invokes sqlite3_changes() directly. Essentially:
  2117. **
  2118. ** <ul>
  2119. ** <li> ^(Before entering a trigger program the value returned by
  2120. ** sqlite3_changes() function is saved. After the trigger program
  2121. ** has finished, the original value is restored.)^
  2122. **
  2123. ** <li> ^(Within a trigger program each INSERT, UPDATE and DELETE
  2124. ** statement sets the value returned by sqlite3_changes()
  2125. ** upon completion as normal. Of course, this value will not include
  2126. ** any changes performed by sub-triggers, as the sqlite3_changes()
  2127. ** value will be saved and restored after each sub-trigger has run.)^
  2128. ** </ul>
  2129. **
  2130. ** ^This means that if the changes() SQL function (or similar) is used
  2131. ** by the first INSERT, UPDATE or DELETE statement within a trigger, it
  2132. ** returns the value as set when the calling statement began executing.
  2133. ** ^If it is used by the second or subsequent such statement within a trigger
  2134. ** program, the value returned reflects the number of rows modified by the
  2135. ** previous INSERT, UPDATE or DELETE statement within the same trigger.
  2136. **
  2137. ** See also the [sqlite3_total_changes()] interface, the
  2138. ** [count_changes pragma], and the [changes() SQL function].
  2139. **
  2140. ** If a separate thread makes changes on the same database connection
  2141. ** while [sqlite3_changes()] is running then the value returned
  2142. ** is unpredictable and not meaningful.
  2143. */
  2144. SQLITE_API int SQLITE_STDCALL sqlite3_changes(sqlite3*);
  2145. /*
  2146. ** CAPI3REF: Total Number Of Rows Modified
  2147. ** METHOD: sqlite3
  2148. **
  2149. ** ^This function returns the total number of rows inserted, modified or
  2150. ** deleted by all [INSERT], [UPDATE] or [DELETE] statements completed
  2151. ** since the database connection was opened, including those executed as
  2152. ** part of trigger programs. ^Executing any other type of SQL statement
  2153. ** does not affect the value returned by sqlite3_total_changes().
  2154. **
  2155. ** ^Changes made as part of [foreign key actions] are included in the
  2156. ** count, but those made as part of REPLACE constraint resolution are
  2157. ** not. ^Changes to a view that are intercepted by INSTEAD OF triggers
  2158. ** are not counted.
  2159. **
  2160. ** See also the [sqlite3_changes()] interface, the
  2161. ** [count_changes pragma], and the [total_changes() SQL function].
  2162. **
  2163. ** If a separate thread makes changes on the same database connection
  2164. ** while [sqlite3_total_changes()] is running then the value
  2165. ** returned is unpredictable and not meaningful.
  2166. */
  2167. SQLITE_API int SQLITE_STDCALL sqlite3_total_changes(sqlite3*);
  2168. /*
  2169. ** CAPI3REF: Interrupt A Long-Running Query
  2170. ** METHOD: sqlite3
  2171. **
  2172. ** ^This function causes any pending database operation to abort and
  2173. ** return at its earliest opportunity. This routine is typically
  2174. ** called in response to a user action such as pressing "Cancel"
  2175. ** or Ctrl-C where the user wants a long query operation to halt
  2176. ** immediately.
  2177. **
  2178. ** ^It is safe to call this routine from a thread different from the
  2179. ** thread that is currently running the database operation. But it
  2180. ** is not safe to call this routine with a [database connection] that
  2181. ** is closed or might close before sqlite3_interrupt() returns.
  2182. **
  2183. ** ^If an SQL operation is very nearly finished at the time when
  2184. ** sqlite3_interrupt() is called, then it might not have an opportunity
  2185. ** to be interrupted and might continue to completion.
  2186. **
  2187. ** ^An SQL operation that is interrupted will return [SQLITE_INTERRUPT].
  2188. ** ^If the interrupted SQL operation is an INSERT, UPDATE, or DELETE
  2189. ** that is inside an explicit transaction, then the entire transaction
  2190. ** will be rolled back automatically.
  2191. **
  2192. ** ^The sqlite3_interrupt(D) call is in effect until all currently running
  2193. ** SQL statements on [database connection] D complete. ^Any new SQL statements
  2194. ** that are started after the sqlite3_interrupt() call and before the
  2195. ** running statements reaches zero are interrupted as if they had been
  2196. ** running prior to the sqlite3_interrupt() call. ^New SQL statements
  2197. ** that are started after the running statement count reaches zero are
  2198. ** not effected by the sqlite3_interrupt().
  2199. ** ^A call to sqlite3_interrupt(D) that occurs when there are no running
  2200. ** SQL statements is a no-op and has no effect on SQL statements
  2201. ** that are started after the sqlite3_interrupt() call returns.
  2202. **
  2203. ** If the database connection closes while [sqlite3_interrupt()]
  2204. ** is running then bad things will likely happen.
  2205. */
  2206. SQLITE_API void SQLITE_STDCALL sqlite3_interrupt(sqlite3*);
  2207. /*
  2208. ** CAPI3REF: Determine If An SQL Statement Is Complete
  2209. **
  2210. ** These routines are useful during command-line input to determine if the
  2211. ** currently entered text seems to form a complete SQL statement or
  2212. ** if additional input is needed before sending the text into
  2213. ** SQLite for parsing. ^These routines return 1 if the input string
  2214. ** appears to be a complete SQL statement. ^A statement is judged to be
  2215. ** complete if it ends with a semicolon token and is not a prefix of a
  2216. ** well-formed CREATE TRIGGER statement. ^Semicolons that are embedded within
  2217. ** string literals or quoted identifier names or comments are not
  2218. ** independent tokens (they are part of the token in which they are
  2219. ** embedded) and thus do not count as a statement terminator. ^Whitespace
  2220. ** and comments that follow the final semicolon are ignored.
  2221. **
  2222. ** ^These routines return 0 if the statement is incomplete. ^If a
  2223. ** memory allocation fails, then SQLITE_NOMEM is returned.
  2224. **
  2225. ** ^These routines do not parse the SQL statements thus
  2226. ** will not detect syntactically incorrect SQL.
  2227. **
  2228. ** ^(If SQLite has not been initialized using [sqlite3_initialize()] prior
  2229. ** to invoking sqlite3_complete16() then sqlite3_initialize() is invoked
  2230. ** automatically by sqlite3_complete16(). If that initialization fails,
  2231. ** then the return value from sqlite3_complete16() will be non-zero
  2232. ** regardless of whether or not the input SQL is complete.)^
  2233. **
  2234. ** The input to [sqlite3_complete()] must be a zero-terminated
  2235. ** UTF-8 string.
  2236. **
  2237. ** The input to [sqlite3_complete16()] must be a zero-terminated
  2238. ** UTF-16 string in native byte order.
  2239. */
  2240. SQLITE_API int SQLITE_STDCALL sqlite3_complete(const char *sql);
  2241. SQLITE_API int SQLITE_STDCALL sqlite3_complete16(const void *sql);
  2242. /*
  2243. ** CAPI3REF: Register A Callback To Handle SQLITE_BUSY Errors
  2244. ** KEYWORDS: {busy-handler callback} {busy handler}
  2245. ** METHOD: sqlite3
  2246. **
  2247. ** ^The sqlite3_busy_handler(D,X,P) routine sets a callback function X
  2248. ** that might be invoked with argument P whenever
  2249. ** an attempt is made to access a database table associated with
  2250. ** [database connection] D when another thread
  2251. ** or process has the table locked.
  2252. ** The sqlite3_busy_handler() interface is used to implement
  2253. ** [sqlite3_busy_timeout()] and [PRAGMA busy_timeout].
  2254. **
  2255. ** ^If the busy callback is NULL, then [SQLITE_BUSY]
  2256. ** is returned immediately upon encountering the lock. ^If the busy callback
  2257. ** is not NULL, then the callback might be invoked with two arguments.
  2258. **
  2259. ** ^The first argument to the busy handler is a copy of the void* pointer which
  2260. ** is the third argument to sqlite3_busy_handler(). ^The second argument to
  2261. ** the busy handler callback is the number of times that the busy handler has
  2262. ** been invoked previously for the same locking event. ^If the
  2263. ** busy callback returns 0, then no additional attempts are made to
  2264. ** access the database and [SQLITE_BUSY] is returned
  2265. ** to the application.
  2266. ** ^If the callback returns non-zero, then another attempt
  2267. ** is made to access the database and the cycle repeats.
  2268. **
  2269. ** The presence of a busy handler does not guarantee that it will be invoked
  2270. ** when there is lock contention. ^If SQLite determines that invoking the busy
  2271. ** handler could result in a deadlock, it will go ahead and return [SQLITE_BUSY]
  2272. ** to the application instead of invoking the
  2273. ** busy handler.
  2274. ** Consider a scenario where one process is holding a read lock that
  2275. ** it is trying to promote to a reserved lock and
  2276. ** a second process is holding a reserved lock that it is trying
  2277. ** to promote to an exclusive lock. The first process cannot proceed
  2278. ** because it is blocked by the second and the second process cannot
  2279. ** proceed because it is blocked by the first. If both processes
  2280. ** invoke the busy handlers, neither will make any progress. Therefore,
  2281. ** SQLite returns [SQLITE_BUSY] for the first process, hoping that this
  2282. ** will induce the first process to release its read lock and allow
  2283. ** the second process to proceed.
  2284. **
  2285. ** ^The default busy callback is NULL.
  2286. **
  2287. ** ^(There can only be a single busy handler defined for each
  2288. ** [database connection]. Setting a new busy handler clears any
  2289. ** previously set handler.)^ ^Note that calling [sqlite3_busy_timeout()]
  2290. ** or evaluating [PRAGMA busy_timeout=N] will change the
  2291. ** busy handler and thus clear any previously set busy handler.
  2292. **
  2293. ** The busy callback should not take any actions which modify the
  2294. ** database connection that invoked the busy handler. In other words,
  2295. ** the busy handler is not reentrant. Any such actions
  2296. ** result in undefined behavior.
  2297. **
  2298. ** A busy handler must not close the database connection
  2299. ** or [prepared statement] that invoked the busy handler.
  2300. */
  2301. SQLITE_API int SQLITE_STDCALL sqlite3_busy_handler(sqlite3*, int(*)(void*,int), void*);
  2302. /*
  2303. ** CAPI3REF: Set A Busy Timeout
  2304. ** METHOD: sqlite3
  2305. **
  2306. ** ^This routine sets a [sqlite3_busy_handler | busy handler] that sleeps
  2307. ** for a specified amount of time when a table is locked. ^The handler
  2308. ** will sleep multiple times until at least "ms" milliseconds of sleeping
  2309. ** have accumulated. ^After at least "ms" milliseconds of sleeping,
  2310. ** the handler returns 0 which causes [sqlite3_step()] to return
  2311. ** [SQLITE_BUSY].
  2312. **
  2313. ** ^Calling this routine with an argument less than or equal to zero
  2314. ** turns off all busy handlers.
  2315. **
  2316. ** ^(There can only be a single busy handler for a particular
  2317. ** [database connection] at any given moment. If another busy handler
  2318. ** was defined (using [sqlite3_busy_handler()]) prior to calling
  2319. ** this routine, that other busy handler is cleared.)^
  2320. **
  2321. ** See also: [PRAGMA busy_timeout]
  2322. */
  2323. SQLITE_API int SQLITE_STDCALL sqlite3_busy_timeout(sqlite3*, int ms);
  2324. /*
  2325. ** CAPI3REF: Convenience Routines For Running Queries
  2326. ** METHOD: sqlite3
  2327. **
  2328. ** This is a legacy interface that is preserved for backwards compatibility.
  2329. ** Use of this interface is not recommended.
  2330. **
  2331. ** Definition: A <b>result table</b> is memory data structure created by the
  2332. ** [sqlite3_get_table()] interface. A result table records the
  2333. ** complete query results from one or more queries.
  2334. **
  2335. ** The table conceptually has a number of rows and columns. But
  2336. ** these numbers are not part of the result table itself. These
  2337. ** numbers are obtained separately. Let N be the number of rows
  2338. ** and M be the number of columns.
  2339. **
  2340. ** A result table is an array of pointers to zero-terminated UTF-8 strings.
  2341. ** There are (N+1)*M elements in the array. The first M pointers point
  2342. ** to zero-terminated strings that contain the names of the columns.
  2343. ** The remaining entries all point to query results. NULL values result
  2344. ** in NULL pointers. All other values are in their UTF-8 zero-terminated
  2345. ** string representation as returned by [sqlite3_column_text()].
  2346. **
  2347. ** A result table might consist of one or more memory allocations.
  2348. ** It is not safe to pass a result table directly to [sqlite3_free()].
  2349. ** A result table should be deallocated using [sqlite3_free_table()].
  2350. **
  2351. ** ^(As an example of the result table format, suppose a query result
  2352. ** is as follows:
  2353. **
  2354. ** <blockquote><pre>
  2355. ** Name | Age
  2356. ** -----------------------
  2357. ** Alice | 43
  2358. ** Bob | 28
  2359. ** Cindy | 21
  2360. ** </pre></blockquote>
  2361. **
  2362. ** There are two column (M==2) and three rows (N==3). Thus the
  2363. ** result table has 8 entries. Suppose the result table is stored
  2364. ** in an array names azResult. Then azResult holds this content:
  2365. **
  2366. ** <blockquote><pre>
  2367. ** azResult&#91;0] = "Name";
  2368. ** azResult&#91;1] = "Age";
  2369. ** azResult&#91;2] = "Alice";
  2370. ** azResult&#91;3] = "43";
  2371. ** azResult&#91;4] = "Bob";
  2372. ** azResult&#91;5] = "28";
  2373. ** azResult&#91;6] = "Cindy";
  2374. ** azResult&#91;7] = "21";
  2375. ** </pre></blockquote>)^
  2376. **
  2377. ** ^The sqlite3_get_table() function evaluates one or more
  2378. ** semicolon-separated SQL statements in the zero-terminated UTF-8
  2379. ** string of its 2nd parameter and returns a result table to the
  2380. ** pointer given in its 3rd parameter.
  2381. **
  2382. ** After the application has finished with the result from sqlite3_get_table(),
  2383. ** it must pass the result table pointer to sqlite3_free_table() in order to
  2384. ** release the memory that was malloced. Because of the way the
  2385. ** [sqlite3_malloc()] happens within sqlite3_get_table(), the calling
  2386. ** function must not try to call [sqlite3_free()] directly. Only
  2387. ** [sqlite3_free_table()] is able to release the memory properly and safely.
  2388. **
  2389. ** The sqlite3_get_table() interface is implemented as a wrapper around
  2390. ** [sqlite3_exec()]. The sqlite3_get_table() routine does not have access
  2391. ** to any internal data structures of SQLite. It uses only the public
  2392. ** interface defined here. As a consequence, errors that occur in the
  2393. ** wrapper layer outside of the internal [sqlite3_exec()] call are not
  2394. ** reflected in subsequent calls to [sqlite3_errcode()] or
  2395. ** [sqlite3_errmsg()].
  2396. */
  2397. SQLITE_API int SQLITE_STDCALL sqlite3_get_table(
  2398. sqlite3 *db, /* An open database */
  2399. const char *zSql, /* SQL to be evaluated */
  2400. char ***pazResult, /* Results of the query */
  2401. int *pnRow, /* Number of result rows written here */
  2402. int *pnColumn, /* Number of result columns written here */
  2403. char **pzErrmsg /* Error msg written here */
  2404. );
  2405. SQLITE_API void SQLITE_STDCALL sqlite3_free_table(char **result);
  2406. /*
  2407. ** CAPI3REF: Formatted String Printing Functions
  2408. **
  2409. ** These routines are work-alikes of the "printf()" family of functions
  2410. ** from the standard C library.
  2411. ** These routines understand most of the common K&R formatting options,
  2412. ** plus some additional non-standard formats, detailed below.
  2413. ** Note that some of the more obscure formatting options from recent
  2414. ** C-library standards are omitted from this implementation.
  2415. **
  2416. ** ^The sqlite3_mprintf() and sqlite3_vmprintf() routines write their
  2417. ** results into memory obtained from [sqlite3_malloc()].
  2418. ** The strings returned by these two routines should be
  2419. ** released by [sqlite3_free()]. ^Both routines return a
  2420. ** NULL pointer if [sqlite3_malloc()] is unable to allocate enough
  2421. ** memory to hold the resulting string.
  2422. **
  2423. ** ^(The sqlite3_snprintf() routine is similar to "snprintf()" from
  2424. ** the standard C library. The result is written into the
  2425. ** buffer supplied as the second parameter whose size is given by
  2426. ** the first parameter. Note that the order of the
  2427. ** first two parameters is reversed from snprintf().)^ This is an
  2428. ** historical accident that cannot be fixed without breaking
  2429. ** backwards compatibility. ^(Note also that sqlite3_snprintf()
  2430. ** returns a pointer to its buffer instead of the number of
  2431. ** characters actually written into the buffer.)^ We admit that
  2432. ** the number of characters written would be a more useful return
  2433. ** value but we cannot change the implementation of sqlite3_snprintf()
  2434. ** now without breaking compatibility.
  2435. **
  2436. ** ^As long as the buffer size is greater than zero, sqlite3_snprintf()
  2437. ** guarantees that the buffer is always zero-terminated. ^The first
  2438. ** parameter "n" is the total size of the buffer, including space for
  2439. ** the zero terminator. So the longest string that can be completely
  2440. ** written will be n-1 characters.
  2441. **
  2442. ** ^The sqlite3_vsnprintf() routine is a varargs version of sqlite3_snprintf().
  2443. **
  2444. ** These routines all implement some additional formatting
  2445. ** options that are useful for constructing SQL statements.
  2446. ** All of the usual printf() formatting options apply. In addition, there
  2447. ** is are "%q", "%Q", "%w" and "%z" options.
  2448. **
  2449. ** ^(The %q option works like %s in that it substitutes a nul-terminated
  2450. ** string from the argument list. But %q also doubles every '\'' character.
  2451. ** %q is designed for use inside a string literal.)^ By doubling each '\''
  2452. ** character it escapes that character and allows it to be inserted into
  2453. ** the string.
  2454. **
  2455. ** For example, assume the string variable zText contains text as follows:
  2456. **
  2457. ** <blockquote><pre>
  2458. ** char *zText = "It's a happy day!";
  2459. ** </pre></blockquote>
  2460. **
  2461. ** One can use this text in an SQL statement as follows:
  2462. **
  2463. ** <blockquote><pre>
  2464. ** char *zSQL = sqlite3_mprintf("INSERT INTO table VALUES('%q')", zText);
  2465. ** sqlite3_exec(db, zSQL, 0, 0, 0);
  2466. ** sqlite3_free(zSQL);
  2467. ** </pre></blockquote>
  2468. **
  2469. ** Because the %q format string is used, the '\'' character in zText
  2470. ** is escaped and the SQL generated is as follows:
  2471. **
  2472. ** <blockquote><pre>
  2473. ** INSERT INTO table1 VALUES('It''s a happy day!')
  2474. ** </pre></blockquote>
  2475. **
  2476. ** This is correct. Had we used %s instead of %q, the generated SQL
  2477. ** would have looked like this:
  2478. **
  2479. ** <blockquote><pre>
  2480. ** INSERT INTO table1 VALUES('It's a happy day!');
  2481. ** </pre></blockquote>
  2482. **
  2483. ** This second example is an SQL syntax error. As a general rule you should
  2484. ** always use %q instead of %s when inserting text into a string literal.
  2485. **
  2486. ** ^(The %Q option works like %q except it also adds single quotes around
  2487. ** the outside of the total string. Additionally, if the parameter in the
  2488. ** argument list is a NULL pointer, %Q substitutes the text "NULL" (without
  2489. ** single quotes).)^ So, for example, one could say:
  2490. **
  2491. ** <blockquote><pre>
  2492. ** char *zSQL = sqlite3_mprintf("INSERT INTO table VALUES(%Q)", zText);
  2493. ** sqlite3_exec(db, zSQL, 0, 0, 0);
  2494. ** sqlite3_free(zSQL);
  2495. ** </pre></blockquote>
  2496. **
  2497. ** The code above will render a correct SQL statement in the zSQL
  2498. ** variable even if the zText variable is a NULL pointer.
  2499. **
  2500. ** ^(The "%w" formatting option is like "%q" except that it expects to
  2501. ** be contained within double-quotes instead of single quotes, and it
  2502. ** escapes the double-quote character instead of the single-quote
  2503. ** character.)^ The "%w" formatting option is intended for safely inserting
  2504. ** table and column names into a constructed SQL statement.
  2505. **
  2506. ** ^(The "%z" formatting option works like "%s" but with the
  2507. ** addition that after the string has been read and copied into
  2508. ** the result, [sqlite3_free()] is called on the input string.)^
  2509. */
  2510. SQLITE_API char *SQLITE_CDECL sqlite3_mprintf(const char*,...);
  2511. SQLITE_API char *SQLITE_STDCALL sqlite3_vmprintf(const char*, va_list);
  2512. SQLITE_API char *SQLITE_CDECL sqlite3_snprintf(int,char*,const char*, ...);
  2513. SQLITE_API char *SQLITE_STDCALL sqlite3_vsnprintf(int,char*,const char*, va_list);
  2514. /*
  2515. ** CAPI3REF: Memory Allocation Subsystem
  2516. **
  2517. ** The SQLite core uses these three routines for all of its own
  2518. ** internal memory allocation needs. "Core" in the previous sentence
  2519. ** does not include operating-system specific VFS implementation. The
  2520. ** Windows VFS uses native malloc() and free() for some operations.
  2521. **
  2522. ** ^The sqlite3_malloc() routine returns a pointer to a block
  2523. ** of memory at least N bytes in length, where N is the parameter.
  2524. ** ^If sqlite3_malloc() is unable to obtain sufficient free
  2525. ** memory, it returns a NULL pointer. ^If the parameter N to
  2526. ** sqlite3_malloc() is zero or negative then sqlite3_malloc() returns
  2527. ** a NULL pointer.
  2528. **
  2529. ** ^The sqlite3_malloc64(N) routine works just like
  2530. ** sqlite3_malloc(N) except that N is an unsigned 64-bit integer instead
  2531. ** of a signed 32-bit integer.
  2532. **
  2533. ** ^Calling sqlite3_free() with a pointer previously returned
  2534. ** by sqlite3_malloc() or sqlite3_realloc() releases that memory so
  2535. ** that it might be reused. ^The sqlite3_free() routine is
  2536. ** a no-op if is called with a NULL pointer. Passing a NULL pointer
  2537. ** to sqlite3_free() is harmless. After being freed, memory
  2538. ** should neither be read nor written. Even reading previously freed
  2539. ** memory might result in a segmentation fault or other severe error.
  2540. ** Memory corruption, a segmentation fault, or other severe error
  2541. ** might result if sqlite3_free() is called with a non-NULL pointer that
  2542. ** was not obtained from sqlite3_malloc() or sqlite3_realloc().
  2543. **
  2544. ** ^The sqlite3_realloc(X,N) interface attempts to resize a
  2545. ** prior memory allocation X to be at least N bytes.
  2546. ** ^If the X parameter to sqlite3_realloc(X,N)
  2547. ** is a NULL pointer then its behavior is identical to calling
  2548. ** sqlite3_malloc(N).
  2549. ** ^If the N parameter to sqlite3_realloc(X,N) is zero or
  2550. ** negative then the behavior is exactly the same as calling
  2551. ** sqlite3_free(X).
  2552. ** ^sqlite3_realloc(X,N) returns a pointer to a memory allocation
  2553. ** of at least N bytes in size or NULL if insufficient memory is available.
  2554. ** ^If M is the size of the prior allocation, then min(N,M) bytes
  2555. ** of the prior allocation are copied into the beginning of buffer returned
  2556. ** by sqlite3_realloc(X,N) and the prior allocation is freed.
  2557. ** ^If sqlite3_realloc(X,N) returns NULL and N is positive, then the
  2558. ** prior allocation is not freed.
  2559. **
  2560. ** ^The sqlite3_realloc64(X,N) interfaces works the same as
  2561. ** sqlite3_realloc(X,N) except that N is a 64-bit unsigned integer instead
  2562. ** of a 32-bit signed integer.
  2563. **
  2564. ** ^If X is a memory allocation previously obtained from sqlite3_malloc(),
  2565. ** sqlite3_malloc64(), sqlite3_realloc(), or sqlite3_realloc64(), then
  2566. ** sqlite3_msize(X) returns the size of that memory allocation in bytes.
  2567. ** ^The value returned by sqlite3_msize(X) might be larger than the number
  2568. ** of bytes requested when X was allocated. ^If X is a NULL pointer then
  2569. ** sqlite3_msize(X) returns zero. If X points to something that is not
  2570. ** the beginning of memory allocation, or if it points to a formerly
  2571. ** valid memory allocation that has now been freed, then the behavior
  2572. ** of sqlite3_msize(X) is undefined and possibly harmful.
  2573. **
  2574. ** ^The memory returned by sqlite3_malloc(), sqlite3_realloc(),
  2575. ** sqlite3_malloc64(), and sqlite3_realloc64()
  2576. ** is always aligned to at least an 8 byte boundary, or to a
  2577. ** 4 byte boundary if the [SQLITE_4_BYTE_ALIGNED_MALLOC] compile-time
  2578. ** option is used.
  2579. **
  2580. ** In SQLite version 3.5.0 and 3.5.1, it was possible to define
  2581. ** the SQLITE_OMIT_MEMORY_ALLOCATION which would cause the built-in
  2582. ** implementation of these routines to be omitted. That capability
  2583. ** is no longer provided. Only built-in memory allocators can be used.
  2584. **
  2585. ** Prior to SQLite version 3.7.10, the Windows OS interface layer called
  2586. ** the system malloc() and free() directly when converting
  2587. ** filenames between the UTF-8 encoding used by SQLite
  2588. ** and whatever filename encoding is used by the particular Windows
  2589. ** installation. Memory allocation errors were detected, but
  2590. ** they were reported back as [SQLITE_CANTOPEN] or
  2591. ** [SQLITE_IOERR] rather than [SQLITE_NOMEM].
  2592. **
  2593. ** The pointer arguments to [sqlite3_free()] and [sqlite3_realloc()]
  2594. ** must be either NULL or else pointers obtained from a prior
  2595. ** invocation of [sqlite3_malloc()] or [sqlite3_realloc()] that have
  2596. ** not yet been released.
  2597. **
  2598. ** The application must not read or write any part of
  2599. ** a block of memory after it has been released using
  2600. ** [sqlite3_free()] or [sqlite3_realloc()].
  2601. */
  2602. SQLITE_API void *SQLITE_STDCALL sqlite3_malloc(int);
  2603. SQLITE_API void *SQLITE_STDCALL sqlite3_malloc64(sqlite3_uint64);
  2604. SQLITE_API void *SQLITE_STDCALL sqlite3_realloc(void*, int);
  2605. SQLITE_API void *SQLITE_STDCALL sqlite3_realloc64(void*, sqlite3_uint64);
  2606. SQLITE_API void SQLITE_STDCALL sqlite3_free(void*);
  2607. SQLITE_API sqlite3_uint64 SQLITE_STDCALL sqlite3_msize(void*);
  2608. /*
  2609. ** CAPI3REF: Memory Allocator Statistics
  2610. **
  2611. ** SQLite provides these two interfaces for reporting on the status
  2612. ** of the [sqlite3_malloc()], [sqlite3_free()], and [sqlite3_realloc()]
  2613. ** routines, which form the built-in memory allocation subsystem.
  2614. **
  2615. ** ^The [sqlite3_memory_used()] routine returns the number of bytes
  2616. ** of memory currently outstanding (malloced but not freed).
  2617. ** ^The [sqlite3_memory_highwater()] routine returns the maximum
  2618. ** value of [sqlite3_memory_used()] since the high-water mark
  2619. ** was last reset. ^The values returned by [sqlite3_memory_used()] and
  2620. ** [sqlite3_memory_highwater()] include any overhead
  2621. ** added by SQLite in its implementation of [sqlite3_malloc()],
  2622. ** but not overhead added by the any underlying system library
  2623. ** routines that [sqlite3_malloc()] may call.
  2624. **
  2625. ** ^The memory high-water mark is reset to the current value of
  2626. ** [sqlite3_memory_used()] if and only if the parameter to
  2627. ** [sqlite3_memory_highwater()] is true. ^The value returned
  2628. ** by [sqlite3_memory_highwater(1)] is the high-water mark
  2629. ** prior to the reset.
  2630. */
  2631. SQLITE_API sqlite3_int64 SQLITE_STDCALL sqlite3_memory_used(void);
  2632. SQLITE_API sqlite3_int64 SQLITE_STDCALL sqlite3_memory_highwater(int resetFlag);
  2633. /*
  2634. ** CAPI3REF: Pseudo-Random Number Generator
  2635. **
  2636. ** SQLite contains a high-quality pseudo-random number generator (PRNG) used to
  2637. ** select random [ROWID | ROWIDs] when inserting new records into a table that
  2638. ** already uses the largest possible [ROWID]. The PRNG is also used for
  2639. ** the build-in random() and randomblob() SQL functions. This interface allows
  2640. ** applications to access the same PRNG for other purposes.
  2641. **
  2642. ** ^A call to this routine stores N bytes of randomness into buffer P.
  2643. ** ^The P parameter can be a NULL pointer.
  2644. **
  2645. ** ^If this routine has not been previously called or if the previous
  2646. ** call had N less than one or a NULL pointer for P, then the PRNG is
  2647. ** seeded using randomness obtained from the xRandomness method of
  2648. ** the default [sqlite3_vfs] object.
  2649. ** ^If the previous call to this routine had an N of 1 or more and a
  2650. ** non-NULL P then the pseudo-randomness is generated
  2651. ** internally and without recourse to the [sqlite3_vfs] xRandomness
  2652. ** method.
  2653. */
  2654. SQLITE_API void SQLITE_STDCALL sqlite3_randomness(int N, void *P);
  2655. /*
  2656. ** CAPI3REF: Compile-Time Authorization Callbacks
  2657. ** METHOD: sqlite3
  2658. **
  2659. ** ^This routine registers an authorizer callback with a particular
  2660. ** [database connection], supplied in the first argument.
  2661. ** ^The authorizer callback is invoked as SQL statements are being compiled
  2662. ** by [sqlite3_prepare()] or its variants [sqlite3_prepare_v2()],
  2663. ** [sqlite3_prepare16()] and [sqlite3_prepare16_v2()]. ^At various
  2664. ** points during the compilation process, as logic is being created
  2665. ** to perform various actions, the authorizer callback is invoked to
  2666. ** see if those actions are allowed. ^The authorizer callback should
  2667. ** return [SQLITE_OK] to allow the action, [SQLITE_IGNORE] to disallow the
  2668. ** specific action but allow the SQL statement to continue to be
  2669. ** compiled, or [SQLITE_DENY] to cause the entire SQL statement to be
  2670. ** rejected with an error. ^If the authorizer callback returns
  2671. ** any value other than [SQLITE_IGNORE], [SQLITE_OK], or [SQLITE_DENY]
  2672. ** then the [sqlite3_prepare_v2()] or equivalent call that triggered
  2673. ** the authorizer will fail with an error message.
  2674. **
  2675. ** When the callback returns [SQLITE_OK], that means the operation
  2676. ** requested is ok. ^When the callback returns [SQLITE_DENY], the
  2677. ** [sqlite3_prepare_v2()] or equivalent call that triggered the
  2678. ** authorizer will fail with an error message explaining that
  2679. ** access is denied.
  2680. **
  2681. ** ^The first parameter to the authorizer callback is a copy of the third
  2682. ** parameter to the sqlite3_set_authorizer() interface. ^The second parameter
  2683. ** to the callback is an integer [SQLITE_COPY | action code] that specifies
  2684. ** the particular action to be authorized. ^The third through sixth parameters
  2685. ** to the callback are zero-terminated strings that contain additional
  2686. ** details about the action to be authorized.
  2687. **
  2688. ** ^If the action code is [SQLITE_READ]
  2689. ** and the callback returns [SQLITE_IGNORE] then the
  2690. ** [prepared statement] statement is constructed to substitute
  2691. ** a NULL value in place of the table column that would have
  2692. ** been read if [SQLITE_OK] had been returned. The [SQLITE_IGNORE]
  2693. ** return can be used to deny an untrusted user access to individual
  2694. ** columns of a table.
  2695. ** ^If the action code is [SQLITE_DELETE] and the callback returns
  2696. ** [SQLITE_IGNORE] then the [DELETE] operation proceeds but the
  2697. ** [truncate optimization] is disabled and all rows are deleted individually.
  2698. **
  2699. ** An authorizer is used when [sqlite3_prepare | preparing]
  2700. ** SQL statements from an untrusted source, to ensure that the SQL statements
  2701. ** do not try to access data they are not allowed to see, or that they do not
  2702. ** try to execute malicious statements that damage the database. For
  2703. ** example, an application may allow a user to enter arbitrary
  2704. ** SQL queries for evaluation by a database. But the application does
  2705. ** not want the user to be able to make arbitrary changes to the
  2706. ** database. An authorizer could then be put in place while the
  2707. ** user-entered SQL is being [sqlite3_prepare | prepared] that
  2708. ** disallows everything except [SELECT] statements.
  2709. **
  2710. ** Applications that need to process SQL from untrusted sources
  2711. ** might also consider lowering resource limits using [sqlite3_limit()]
  2712. ** and limiting database size using the [max_page_count] [PRAGMA]
  2713. ** in addition to using an authorizer.
  2714. **
  2715. ** ^(Only a single authorizer can be in place on a database connection
  2716. ** at a time. Each call to sqlite3_set_authorizer overrides the
  2717. ** previous call.)^ ^Disable the authorizer by installing a NULL callback.
  2718. ** The authorizer is disabled by default.
  2719. **
  2720. ** The authorizer callback must not do anything that will modify
  2721. ** the database connection that invoked the authorizer callback.
  2722. ** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
  2723. ** database connections for the meaning of "modify" in this paragraph.
  2724. **
  2725. ** ^When [sqlite3_prepare_v2()] is used to prepare a statement, the
  2726. ** statement might be re-prepared during [sqlite3_step()] due to a
  2727. ** schema change. Hence, the application should ensure that the
  2728. ** correct authorizer callback remains in place during the [sqlite3_step()].
  2729. **
  2730. ** ^Note that the authorizer callback is invoked only during
  2731. ** [sqlite3_prepare()] or its variants. Authorization is not
  2732. ** performed during statement evaluation in [sqlite3_step()], unless
  2733. ** as stated in the previous paragraph, sqlite3_step() invokes
  2734. ** sqlite3_prepare_v2() to reprepare a statement after a schema change.
  2735. */
  2736. SQLITE_API int SQLITE_STDCALL sqlite3_set_authorizer(
  2737. sqlite3*,
  2738. int (*xAuth)(void*,int,const char*,const char*,const char*,const char*),
  2739. void *pUserData
  2740. );
  2741. /*
  2742. ** CAPI3REF: Authorizer Return Codes
  2743. **
  2744. ** The [sqlite3_set_authorizer | authorizer callback function] must
  2745. ** return either [SQLITE_OK] or one of these two constants in order
  2746. ** to signal SQLite whether or not the action is permitted. See the
  2747. ** [sqlite3_set_authorizer | authorizer documentation] for additional
  2748. ** information.
  2749. **
  2750. ** Note that SQLITE_IGNORE is also used as a [conflict resolution mode]
  2751. ** returned from the [sqlite3_vtab_on_conflict()] interface.
  2752. */
  2753. #define SQLITE_DENY 1 /* Abort the SQL statement with an error */
  2754. #define SQLITE_IGNORE 2 /* Don't allow access, but don't generate an error */
  2755. /*
  2756. ** CAPI3REF: Authorizer Action Codes
  2757. **
  2758. ** The [sqlite3_set_authorizer()] interface registers a callback function
  2759. ** that is invoked to authorize certain SQL statement actions. The
  2760. ** second parameter to the callback is an integer code that specifies
  2761. ** what action is being authorized. These are the integer action codes that
  2762. ** the authorizer callback may be passed.
  2763. **
  2764. ** These action code values signify what kind of operation is to be
  2765. ** authorized. The 3rd and 4th parameters to the authorization
  2766. ** callback function will be parameters or NULL depending on which of these
  2767. ** codes is used as the second parameter. ^(The 5th parameter to the
  2768. ** authorizer callback is the name of the database ("main", "temp",
  2769. ** etc.) if applicable.)^ ^The 6th parameter to the authorizer callback
  2770. ** is the name of the inner-most trigger or view that is responsible for
  2771. ** the access attempt or NULL if this access attempt is directly from
  2772. ** top-level SQL code.
  2773. */
  2774. /******************************************* 3rd ************ 4th ***********/
  2775. #define SQLITE_CREATE_INDEX 1 /* Index Name Table Name */
  2776. #define SQLITE_CREATE_TABLE 2 /* Table Name NULL */
  2777. #define SQLITE_CREATE_TEMP_INDEX 3 /* Index Name Table Name */
  2778. #define SQLITE_CREATE_TEMP_TABLE 4 /* Table Name NULL */
  2779. #define SQLITE_CREATE_TEMP_TRIGGER 5 /* Trigger Name Table Name */
  2780. #define SQLITE_CREATE_TEMP_VIEW 6 /* View Name NULL */
  2781. #define SQLITE_CREATE_TRIGGER 7 /* Trigger Name Table Name */
  2782. #define SQLITE_CREATE_VIEW 8 /* View Name NULL */
  2783. #define SQLITE_DELETE 9 /* Table Name NULL */
  2784. #define SQLITE_DROP_INDEX 10 /* Index Name Table Name */
  2785. #define SQLITE_DROP_TABLE 11 /* Table Name NULL */
  2786. #define SQLITE_DROP_TEMP_INDEX 12 /* Index Name Table Name */
  2787. #define SQLITE_DROP_TEMP_TABLE 13 /* Table Name NULL */
  2788. #define SQLITE_DROP_TEMP_TRIGGER 14 /* Trigger Name Table Name */
  2789. #define SQLITE_DROP_TEMP_VIEW 15 /* View Name NULL */
  2790. #define SQLITE_DROP_TRIGGER 16 /* Trigger Name Table Name */
  2791. #define SQLITE_DROP_VIEW 17 /* View Name NULL */
  2792. #define SQLITE_INSERT 18 /* Table Name NULL */
  2793. #define SQLITE_PRAGMA 19 /* Pragma Name 1st arg or NULL */
  2794. #define SQLITE_READ 20 /* Table Name Column Name */
  2795. #define SQLITE_SELECT 21 /* NULL NULL */
  2796. #define SQLITE_TRANSACTION 22 /* Operation NULL */
  2797. #define SQLITE_UPDATE 23 /* Table Name Column Name */
  2798. #define SQLITE_ATTACH 24 /* Filename NULL */
  2799. #define SQLITE_DETACH 25 /* Database Name NULL */
  2800. #define SQLITE_ALTER_TABLE 26 /* Database Name Table Name */
  2801. #define SQLITE_REINDEX 27 /* Index Name NULL */
  2802. #define SQLITE_ANALYZE 28 /* Table Name NULL */
  2803. #define SQLITE_CREATE_VTABLE 29 /* Table Name Module Name */
  2804. #define SQLITE_DROP_VTABLE 30 /* Table Name Module Name */
  2805. #define SQLITE_FUNCTION 31 /* NULL Function Name */
  2806. #define SQLITE_SAVEPOINT 32 /* Operation Savepoint Name */
  2807. #define SQLITE_COPY 0 /* No longer used */
  2808. #define SQLITE_RECURSIVE 33 /* NULL NULL */
  2809. /*
  2810. ** CAPI3REF: Tracing And Profiling Functions
  2811. ** METHOD: sqlite3
  2812. **
  2813. ** These routines register callback functions that can be used for
  2814. ** tracing and profiling the execution of SQL statements.
  2815. **
  2816. ** ^The callback function registered by sqlite3_trace() is invoked at
  2817. ** various times when an SQL statement is being run by [sqlite3_step()].
  2818. ** ^The sqlite3_trace() callback is invoked with a UTF-8 rendering of the
  2819. ** SQL statement text as the statement first begins executing.
  2820. ** ^(Additional sqlite3_trace() callbacks might occur
  2821. ** as each triggered subprogram is entered. The callbacks for triggers
  2822. ** contain a UTF-8 SQL comment that identifies the trigger.)^
  2823. **
  2824. ** The [SQLITE_TRACE_SIZE_LIMIT] compile-time option can be used to limit
  2825. ** the length of [bound parameter] expansion in the output of sqlite3_trace().
  2826. **
  2827. ** ^The callback function registered by sqlite3_profile() is invoked
  2828. ** as each SQL statement finishes. ^The profile callback contains
  2829. ** the original statement text and an estimate of wall-clock time
  2830. ** of how long that statement took to run. ^The profile callback
  2831. ** time is in units of nanoseconds, however the current implementation
  2832. ** is only capable of millisecond resolution so the six least significant
  2833. ** digits in the time are meaningless. Future versions of SQLite
  2834. ** might provide greater resolution on the profiler callback. The
  2835. ** sqlite3_profile() function is considered experimental and is
  2836. ** subject to change in future versions of SQLite.
  2837. */
  2838. SQLITE_API void *SQLITE_STDCALL sqlite3_trace(sqlite3*, void(*xTrace)(void*,const char*), void*);
  2839. SQLITE_API SQLITE_EXPERIMENTAL void *SQLITE_STDCALL sqlite3_profile(sqlite3*,
  2840. void(*xProfile)(void*,const char*,sqlite3_uint64), void*);
  2841. /*
  2842. ** CAPI3REF: Query Progress Callbacks
  2843. ** METHOD: sqlite3
  2844. **
  2845. ** ^The sqlite3_progress_handler(D,N,X,P) interface causes the callback
  2846. ** function X to be invoked periodically during long running calls to
  2847. ** [sqlite3_exec()], [sqlite3_step()] and [sqlite3_get_table()] for
  2848. ** database connection D. An example use for this
  2849. ** interface is to keep a GUI updated during a large query.
  2850. **
  2851. ** ^The parameter P is passed through as the only parameter to the
  2852. ** callback function X. ^The parameter N is the approximate number of
  2853. ** [virtual machine instructions] that are evaluated between successive
  2854. ** invocations of the callback X. ^If N is less than one then the progress
  2855. ** handler is disabled.
  2856. **
  2857. ** ^Only a single progress handler may be defined at one time per
  2858. ** [database connection]; setting a new progress handler cancels the
  2859. ** old one. ^Setting parameter X to NULL disables the progress handler.
  2860. ** ^The progress handler is also disabled by setting N to a value less
  2861. ** than 1.
  2862. **
  2863. ** ^If the progress callback returns non-zero, the operation is
  2864. ** interrupted. This feature can be used to implement a
  2865. ** "Cancel" button on a GUI progress dialog box.
  2866. **
  2867. ** The progress handler callback must not do anything that will modify
  2868. ** the database connection that invoked the progress handler.
  2869. ** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
  2870. ** database connections for the meaning of "modify" in this paragraph.
  2871. **
  2872. */
  2873. SQLITE_API void SQLITE_STDCALL sqlite3_progress_handler(sqlite3*, int, int(*)(void*), void*);
  2874. /*
  2875. ** CAPI3REF: Opening A New Database Connection
  2876. ** CONSTRUCTOR: sqlite3
  2877. **
  2878. ** ^These routines open an SQLite database file as specified by the
  2879. ** filename argument. ^The filename argument is interpreted as UTF-8 for
  2880. ** sqlite3_open() and sqlite3_open_v2() and as UTF-16 in the native byte
  2881. ** order for sqlite3_open16(). ^(A [database connection] handle is usually
  2882. ** returned in *ppDb, even if an error occurs. The only exception is that
  2883. ** if SQLite is unable to allocate memory to hold the [sqlite3] object,
  2884. ** a NULL will be written into *ppDb instead of a pointer to the [sqlite3]
  2885. ** object.)^ ^(If the database is opened (and/or created) successfully, then
  2886. ** [SQLITE_OK] is returned. Otherwise an [error code] is returned.)^ ^The
  2887. ** [sqlite3_errmsg()] or [sqlite3_errmsg16()] routines can be used to obtain
  2888. ** an English language description of the error following a failure of any
  2889. ** of the sqlite3_open() routines.
  2890. **
  2891. ** ^The default encoding will be UTF-8 for databases created using
  2892. ** sqlite3_open() or sqlite3_open_v2(). ^The default encoding for databases
  2893. ** created using sqlite3_open16() will be UTF-16 in the native byte order.
  2894. **
  2895. ** Whether or not an error occurs when it is opened, resources
  2896. ** associated with the [database connection] handle should be released by
  2897. ** passing it to [sqlite3_close()] when it is no longer required.
  2898. **
  2899. ** The sqlite3_open_v2() interface works like sqlite3_open()
  2900. ** except that it accepts two additional parameters for additional control
  2901. ** over the new database connection. ^(The flags parameter to
  2902. ** sqlite3_open_v2() can take one of
  2903. ** the following three values, optionally combined with the
  2904. ** [SQLITE_OPEN_NOMUTEX], [SQLITE_OPEN_FULLMUTEX], [SQLITE_OPEN_SHAREDCACHE],
  2905. ** [SQLITE_OPEN_PRIVATECACHE], and/or [SQLITE_OPEN_URI] flags:)^
  2906. **
  2907. ** <dl>
  2908. ** ^(<dt>[SQLITE_OPEN_READONLY]</dt>
  2909. ** <dd>The database is opened in read-only mode. If the database does not
  2910. ** already exist, an error is returned.</dd>)^
  2911. **
  2912. ** ^(<dt>[SQLITE_OPEN_READWRITE]</dt>
  2913. ** <dd>The database is opened for reading and writing if possible, or reading
  2914. ** only if the file is write protected by the operating system. In either
  2915. ** case the database must already exist, otherwise an error is returned.</dd>)^
  2916. **
  2917. ** ^(<dt>[SQLITE_OPEN_READWRITE] | [SQLITE_OPEN_CREATE]</dt>
  2918. ** <dd>The database is opened for reading and writing, and is created if
  2919. ** it does not already exist. This is the behavior that is always used for
  2920. ** sqlite3_open() and sqlite3_open16().</dd>)^
  2921. ** </dl>
  2922. **
  2923. ** If the 3rd parameter to sqlite3_open_v2() is not one of the
  2924. ** combinations shown above optionally combined with other
  2925. ** [SQLITE_OPEN_READONLY | SQLITE_OPEN_* bits]
  2926. ** then the behavior is undefined.
  2927. **
  2928. ** ^If the [SQLITE_OPEN_NOMUTEX] flag is set, then the database connection
  2929. ** opens in the multi-thread [threading mode] as long as the single-thread
  2930. ** mode has not been set at compile-time or start-time. ^If the
  2931. ** [SQLITE_OPEN_FULLMUTEX] flag is set then the database connection opens
  2932. ** in the serialized [threading mode] unless single-thread was
  2933. ** previously selected at compile-time or start-time.
  2934. ** ^The [SQLITE_OPEN_SHAREDCACHE] flag causes the database connection to be
  2935. ** eligible to use [shared cache mode], regardless of whether or not shared
  2936. ** cache is enabled using [sqlite3_enable_shared_cache()]. ^The
  2937. ** [SQLITE_OPEN_PRIVATECACHE] flag causes the database connection to not
  2938. ** participate in [shared cache mode] even if it is enabled.
  2939. **
  2940. ** ^The fourth parameter to sqlite3_open_v2() is the name of the
  2941. ** [sqlite3_vfs] object that defines the operating system interface that
  2942. ** the new database connection should use. ^If the fourth parameter is
  2943. ** a NULL pointer then the default [sqlite3_vfs] object is used.
  2944. **
  2945. ** ^If the filename is ":memory:", then a private, temporary in-memory database
  2946. ** is created for the connection. ^This in-memory database will vanish when
  2947. ** the database connection is closed. Future versions of SQLite might
  2948. ** make use of additional special filenames that begin with the ":" character.
  2949. ** It is recommended that when a database filename actually does begin with
  2950. ** a ":" character you should prefix the filename with a pathname such as
  2951. ** "./" to avoid ambiguity.
  2952. **
  2953. ** ^If the filename is an empty string, then a private, temporary
  2954. ** on-disk database will be created. ^This private database will be
  2955. ** automatically deleted as soon as the database connection is closed.
  2956. **
  2957. ** [[URI filenames in sqlite3_open()]] <h3>URI Filenames</h3>
  2958. **
  2959. ** ^If [URI filename] interpretation is enabled, and the filename argument
  2960. ** begins with "file:", then the filename is interpreted as a URI. ^URI
  2961. ** filename interpretation is enabled if the [SQLITE_OPEN_URI] flag is
  2962. ** set in the fourth argument to sqlite3_open_v2(), or if it has
  2963. ** been enabled globally using the [SQLITE_CONFIG_URI] option with the
  2964. ** [sqlite3_config()] method or by the [SQLITE_USE_URI] compile-time option.
  2965. ** As of SQLite version 3.7.7, URI filename interpretation is turned off
  2966. ** by default, but future releases of SQLite might enable URI filename
  2967. ** interpretation by default. See "[URI filenames]" for additional
  2968. ** information.
  2969. **
  2970. ** URI filenames are parsed according to RFC 3986. ^If the URI contains an
  2971. ** authority, then it must be either an empty string or the string
  2972. ** "localhost". ^If the authority is not an empty string or "localhost", an
  2973. ** error is returned to the caller. ^The fragment component of a URI, if
  2974. ** present, is ignored.
  2975. **
  2976. ** ^SQLite uses the path component of the URI as the name of the disk file
  2977. ** which contains the database. ^If the path begins with a '/' character,
  2978. ** then it is interpreted as an absolute path. ^If the path does not begin
  2979. ** with a '/' (meaning that the authority section is omitted from the URI)
  2980. ** then the path is interpreted as a relative path.
  2981. ** ^(On windows, the first component of an absolute path
  2982. ** is a drive specification (e.g. "C:").)^
  2983. **
  2984. ** [[core URI query parameters]]
  2985. ** The query component of a URI may contain parameters that are interpreted
  2986. ** either by SQLite itself, or by a [VFS | custom VFS implementation].
  2987. ** SQLite and its built-in [VFSes] interpret the
  2988. ** following query parameters:
  2989. **
  2990. ** <ul>
  2991. ** <li> <b>vfs</b>: ^The "vfs" parameter may be used to specify the name of
  2992. ** a VFS object that provides the operating system interface that should
  2993. ** be used to access the database file on disk. ^If this option is set to
  2994. ** an empty string the default VFS object is used. ^Specifying an unknown
  2995. ** VFS is an error. ^If sqlite3_open_v2() is used and the vfs option is
  2996. ** present, then the VFS specified by the option takes precedence over
  2997. ** the value passed as the fourth parameter to sqlite3_open_v2().
  2998. **
  2999. ** <li> <b>mode</b>: ^(The mode parameter may be set to either "ro", "rw",
  3000. ** "rwc", or "memory". Attempting to set it to any other value is
  3001. ** an error)^.
  3002. ** ^If "ro" is specified, then the database is opened for read-only
  3003. ** access, just as if the [SQLITE_OPEN_READONLY] flag had been set in the
  3004. ** third argument to sqlite3_open_v2(). ^If the mode option is set to
  3005. ** "rw", then the database is opened for read-write (but not create)
  3006. ** access, as if SQLITE_OPEN_READWRITE (but not SQLITE_OPEN_CREATE) had
  3007. ** been set. ^Value "rwc" is equivalent to setting both
  3008. ** SQLITE_OPEN_READWRITE and SQLITE_OPEN_CREATE. ^If the mode option is
  3009. ** set to "memory" then a pure [in-memory database] that never reads
  3010. ** or writes from disk is used. ^It is an error to specify a value for
  3011. ** the mode parameter that is less restrictive than that specified by
  3012. ** the flags passed in the third parameter to sqlite3_open_v2().
  3013. **
  3014. ** <li> <b>cache</b>: ^The cache parameter may be set to either "shared" or
  3015. ** "private". ^Setting it to "shared" is equivalent to setting the
  3016. ** SQLITE_OPEN_SHAREDCACHE bit in the flags argument passed to
  3017. ** sqlite3_open_v2(). ^Setting the cache parameter to "private" is
  3018. ** equivalent to setting the SQLITE_OPEN_PRIVATECACHE bit.
  3019. ** ^If sqlite3_open_v2() is used and the "cache" parameter is present in
  3020. ** a URI filename, its value overrides any behavior requested by setting
  3021. ** SQLITE_OPEN_PRIVATECACHE or SQLITE_OPEN_SHAREDCACHE flag.
  3022. **
  3023. ** <li> <b>psow</b>: ^The psow parameter indicates whether or not the
  3024. ** [powersafe overwrite] property does or does not apply to the
  3025. ** storage media on which the database file resides.
  3026. **
  3027. ** <li> <b>nolock</b>: ^The nolock parameter is a boolean query parameter
  3028. ** which if set disables file locking in rollback journal modes. This
  3029. ** is useful for accessing a database on a filesystem that does not
  3030. ** support locking. Caution: Database corruption might result if two
  3031. ** or more processes write to the same database and any one of those
  3032. ** processes uses nolock=1.
  3033. **
  3034. ** <li> <b>immutable</b>: ^The immutable parameter is a boolean query
  3035. ** parameter that indicates that the database file is stored on
  3036. ** read-only media. ^When immutable is set, SQLite assumes that the
  3037. ** database file cannot be changed, even by a process with higher
  3038. ** privilege, and so the database is opened read-only and all locking
  3039. ** and change detection is disabled. Caution: Setting the immutable
  3040. ** property on a database file that does in fact change can result
  3041. ** in incorrect query results and/or [SQLITE_CORRUPT] errors.
  3042. ** See also: [SQLITE_IOCAP_IMMUTABLE].
  3043. **
  3044. ** </ul>
  3045. **
  3046. ** ^Specifying an unknown parameter in the query component of a URI is not an
  3047. ** error. Future versions of SQLite might understand additional query
  3048. ** parameters. See "[query parameters with special meaning to SQLite]" for
  3049. ** additional information.
  3050. **
  3051. ** [[URI filename examples]] <h3>URI filename examples</h3>
  3052. **
  3053. ** <table border="1" align=center cellpadding=5>
  3054. ** <tr><th> URI filenames <th> Results
  3055. ** <tr><td> file:data.db <td>
  3056. ** Open the file "data.db" in the current directory.
  3057. ** <tr><td> file:/home/fred/data.db<br>
  3058. ** file:///home/fred/data.db <br>
  3059. ** file://localhost/home/fred/data.db <br> <td>
  3060. ** Open the database file "/home/fred/data.db".
  3061. ** <tr><td> file://darkstar/home/fred/data.db <td>
  3062. ** An error. "darkstar" is not a recognized authority.
  3063. ** <tr><td style="white-space:nowrap">
  3064. ** file:///C:/Documents%20and%20Settings/fred/Desktop/data.db
  3065. ** <td> Windows only: Open the file "data.db" on fred's desktop on drive
  3066. ** C:. Note that the %20 escaping in this example is not strictly
  3067. ** necessary - space characters can be used literally
  3068. ** in URI filenames.
  3069. ** <tr><td> file:data.db?mode=ro&cache=private <td>
  3070. ** Open file "data.db" in the current directory for read-only access.
  3071. ** Regardless of whether or not shared-cache mode is enabled by
  3072. ** default, use a private cache.
  3073. ** <tr><td> file:/home/fred/data.db?vfs=unix-dotfile <td>
  3074. ** Open file "/home/fred/data.db". Use the special VFS "unix-dotfile"
  3075. ** that uses dot-files in place of posix advisory locking.
  3076. ** <tr><td> file:data.db?mode=readonly <td>
  3077. ** An error. "readonly" is not a valid option for the "mode" parameter.
  3078. ** </table>
  3079. **
  3080. ** ^URI hexadecimal escape sequences (%HH) are supported within the path and
  3081. ** query components of a URI. A hexadecimal escape sequence consists of a
  3082. ** percent sign - "%" - followed by exactly two hexadecimal digits
  3083. ** specifying an octet value. ^Before the path or query components of a
  3084. ** URI filename are interpreted, they are encoded using UTF-8 and all
  3085. ** hexadecimal escape sequences replaced by a single byte containing the
  3086. ** corresponding octet. If this process generates an invalid UTF-8 encoding,
  3087. ** the results are undefined.
  3088. **
  3089. ** <b>Note to Windows users:</b> The encoding used for the filename argument
  3090. ** of sqlite3_open() and sqlite3_open_v2() must be UTF-8, not whatever
  3091. ** codepage is currently defined. Filenames containing international
  3092. ** characters must be converted to UTF-8 prior to passing them into
  3093. ** sqlite3_open() or sqlite3_open_v2().
  3094. **
  3095. ** <b>Note to Windows Runtime users:</b> The temporary directory must be set
  3096. ** prior to calling sqlite3_open() or sqlite3_open_v2(). Otherwise, various
  3097. ** features that require the use of temporary files may fail.
  3098. **
  3099. ** See also: [sqlite3_temp_directory]
  3100. */
  3101. SQLITE_API int SQLITE_STDCALL sqlite3_open(
  3102. const char *filename, /* Database filename (UTF-8) */
  3103. sqlite3 **ppDb /* OUT: SQLite db handle */
  3104. );
  3105. SQLITE_API int SQLITE_STDCALL sqlite3_open16(
  3106. const void *filename, /* Database filename (UTF-16) */
  3107. sqlite3 **ppDb /* OUT: SQLite db handle */
  3108. );
  3109. SQLITE_API int SQLITE_STDCALL sqlite3_open_v2(
  3110. const char *filename, /* Database filename (UTF-8) */
  3111. sqlite3 **ppDb, /* OUT: SQLite db handle */
  3112. int flags, /* Flags */
  3113. const char *zVfs /* Name of VFS module to use */
  3114. );
  3115. /*
  3116. ** CAPI3REF: Obtain Values For URI Parameters
  3117. **
  3118. ** These are utility routines, useful to VFS implementations, that check
  3119. ** to see if a database file was a URI that contained a specific query
  3120. ** parameter, and if so obtains the value of that query parameter.
  3121. **
  3122. ** If F is the database filename pointer passed into the xOpen() method of
  3123. ** a VFS implementation when the flags parameter to xOpen() has one or
  3124. ** more of the [SQLITE_OPEN_URI] or [SQLITE_OPEN_MAIN_DB] bits set and
  3125. ** P is the name of the query parameter, then
  3126. ** sqlite3_uri_parameter(F,P) returns the value of the P
  3127. ** parameter if it exists or a NULL pointer if P does not appear as a
  3128. ** query parameter on F. If P is a query parameter of F
  3129. ** has no explicit value, then sqlite3_uri_parameter(F,P) returns
  3130. ** a pointer to an empty string.
  3131. **
  3132. ** The sqlite3_uri_boolean(F,P,B) routine assumes that P is a boolean
  3133. ** parameter and returns true (1) or false (0) according to the value
  3134. ** of P. The sqlite3_uri_boolean(F,P,B) routine returns true (1) if the
  3135. ** value of query parameter P is one of "yes", "true", or "on" in any
  3136. ** case or if the value begins with a non-zero number. The
  3137. ** sqlite3_uri_boolean(F,P,B) routines returns false (0) if the value of
  3138. ** query parameter P is one of "no", "false", or "off" in any case or
  3139. ** if the value begins with a numeric zero. If P is not a query
  3140. ** parameter on F or if the value of P is does not match any of the
  3141. ** above, then sqlite3_uri_boolean(F,P,B) returns (B!=0).
  3142. **
  3143. ** The sqlite3_uri_int64(F,P,D) routine converts the value of P into a
  3144. ** 64-bit signed integer and returns that integer, or D if P does not
  3145. ** exist. If the value of P is something other than an integer, then
  3146. ** zero is returned.
  3147. **
  3148. ** If F is a NULL pointer, then sqlite3_uri_parameter(F,P) returns NULL and
  3149. ** sqlite3_uri_boolean(F,P,B) returns B. If F is not a NULL pointer and
  3150. ** is not a database file pathname pointer that SQLite passed into the xOpen
  3151. ** VFS method, then the behavior of this routine is undefined and probably
  3152. ** undesirable.
  3153. */
  3154. SQLITE_API const char *SQLITE_STDCALL sqlite3_uri_parameter(const char *zFilename, const char *zParam);
  3155. SQLITE_API int SQLITE_STDCALL sqlite3_uri_boolean(const char *zFile, const char *zParam, int bDefault);
  3156. SQLITE_API sqlite3_int64 SQLITE_STDCALL sqlite3_uri_int64(const char*, const char*, sqlite3_int64);
  3157. /*
  3158. ** CAPI3REF: Error Codes And Messages
  3159. ** METHOD: sqlite3
  3160. **
  3161. ** ^If the most recent sqlite3_* API call associated with
  3162. ** [database connection] D failed, then the sqlite3_errcode(D) interface
  3163. ** returns the numeric [result code] or [extended result code] for that
  3164. ** API call.
  3165. ** If the most recent API call was successful,
  3166. ** then the return value from sqlite3_errcode() is undefined.
  3167. ** ^The sqlite3_extended_errcode()
  3168. ** interface is the same except that it always returns the
  3169. ** [extended result code] even when extended result codes are
  3170. ** disabled.
  3171. **
  3172. ** ^The sqlite3_errmsg() and sqlite3_errmsg16() return English-language
  3173. ** text that describes the error, as either UTF-8 or UTF-16 respectively.
  3174. ** ^(Memory to hold the error message string is managed internally.
  3175. ** The application does not need to worry about freeing the result.
  3176. ** However, the error string might be overwritten or deallocated by
  3177. ** subsequent calls to other SQLite interface functions.)^
  3178. **
  3179. ** ^The sqlite3_errstr() interface returns the English-language text
  3180. ** that describes the [result code], as UTF-8.
  3181. ** ^(Memory to hold the error message string is managed internally
  3182. ** and must not be freed by the application)^.
  3183. **
  3184. ** When the serialized [threading mode] is in use, it might be the
  3185. ** case that a second error occurs on a separate thread in between
  3186. ** the time of the first error and the call to these interfaces.
  3187. ** When that happens, the second error will be reported since these
  3188. ** interfaces always report the most recent result. To avoid
  3189. ** this, each thread can obtain exclusive use of the [database connection] D
  3190. ** by invoking [sqlite3_mutex_enter]([sqlite3_db_mutex](D)) before beginning
  3191. ** to use D and invoking [sqlite3_mutex_leave]([sqlite3_db_mutex](D)) after
  3192. ** all calls to the interfaces listed here are completed.
  3193. **
  3194. ** If an interface fails with SQLITE_MISUSE, that means the interface
  3195. ** was invoked incorrectly by the application. In that case, the
  3196. ** error code and message may or may not be set.
  3197. */
  3198. SQLITE_API int SQLITE_STDCALL sqlite3_errcode(sqlite3 *db);
  3199. SQLITE_API int SQLITE_STDCALL sqlite3_extended_errcode(sqlite3 *db);
  3200. SQLITE_API const char *SQLITE_STDCALL sqlite3_errmsg(sqlite3*);
  3201. SQLITE_API const void *SQLITE_STDCALL sqlite3_errmsg16(sqlite3*);
  3202. SQLITE_API const char *SQLITE_STDCALL sqlite3_errstr(int);
  3203. /*
  3204. ** CAPI3REF: Prepared Statement Object
  3205. ** KEYWORDS: {prepared statement} {prepared statements}
  3206. **
  3207. ** An instance of this object represents a single SQL statement that
  3208. ** has been compiled into binary form and is ready to be evaluated.
  3209. **
  3210. ** Think of each SQL statement as a separate computer program. The
  3211. ** original SQL text is source code. A prepared statement object
  3212. ** is the compiled object code. All SQL must be converted into a
  3213. ** prepared statement before it can be run.
  3214. **
  3215. ** The life-cycle of a prepared statement object usually goes like this:
  3216. **
  3217. ** <ol>
  3218. ** <li> Create the prepared statement object using [sqlite3_prepare_v2()].
  3219. ** <li> Bind values to [parameters] using the sqlite3_bind_*()
  3220. ** interfaces.
  3221. ** <li> Run the SQL by calling [sqlite3_step()] one or more times.
  3222. ** <li> Reset the prepared statement using [sqlite3_reset()] then go back
  3223. ** to step 2. Do this zero or more times.
  3224. ** <li> Destroy the object using [sqlite3_finalize()].
  3225. ** </ol>
  3226. */
  3227. typedef struct sqlite3_stmt sqlite3_stmt;
  3228. /*
  3229. ** CAPI3REF: Run-time Limits
  3230. ** METHOD: sqlite3
  3231. **
  3232. ** ^(This interface allows the size of various constructs to be limited
  3233. ** on a connection by connection basis. The first parameter is the
  3234. ** [database connection] whose limit is to be set or queried. The
  3235. ** second parameter is one of the [limit categories] that define a
  3236. ** class of constructs to be size limited. The third parameter is the
  3237. ** new limit for that construct.)^
  3238. **
  3239. ** ^If the new limit is a negative number, the limit is unchanged.
  3240. ** ^(For each limit category SQLITE_LIMIT_<i>NAME</i> there is a
  3241. ** [limits | hard upper bound]
  3242. ** set at compile-time by a C preprocessor macro called
  3243. ** [limits | SQLITE_MAX_<i>NAME</i>].
  3244. ** (The "_LIMIT_" in the name is changed to "_MAX_".))^
  3245. ** ^Attempts to increase a limit above its hard upper bound are
  3246. ** silently truncated to the hard upper bound.
  3247. **
  3248. ** ^Regardless of whether or not the limit was changed, the
  3249. ** [sqlite3_limit()] interface returns the prior value of the limit.
  3250. ** ^Hence, to find the current value of a limit without changing it,
  3251. ** simply invoke this interface with the third parameter set to -1.
  3252. **
  3253. ** Run-time limits are intended for use in applications that manage
  3254. ** both their own internal database and also databases that are controlled
  3255. ** by untrusted external sources. An example application might be a
  3256. ** web browser that has its own databases for storing history and
  3257. ** separate databases controlled by JavaScript applications downloaded
  3258. ** off the Internet. The internal databases can be given the
  3259. ** large, default limits. Databases managed by external sources can
  3260. ** be given much smaller limits designed to prevent a denial of service
  3261. ** attack. Developers might also want to use the [sqlite3_set_authorizer()]
  3262. ** interface to further control untrusted SQL. The size of the database
  3263. ** created by an untrusted script can be contained using the
  3264. ** [max_page_count] [PRAGMA].
  3265. **
  3266. ** New run-time limit categories may be added in future releases.
  3267. */
  3268. SQLITE_API int SQLITE_STDCALL sqlite3_limit(sqlite3*, int id, int newVal);
  3269. /*
  3270. ** CAPI3REF: Run-Time Limit Categories
  3271. ** KEYWORDS: {limit category} {*limit categories}
  3272. **
  3273. ** These constants define various performance limits
  3274. ** that can be lowered at run-time using [sqlite3_limit()].
  3275. ** The synopsis of the meanings of the various limits is shown below.
  3276. ** Additional information is available at [limits | Limits in SQLite].
  3277. **
  3278. ** <dl>
  3279. ** [[SQLITE_LIMIT_LENGTH]] ^(<dt>SQLITE_LIMIT_LENGTH</dt>
  3280. ** <dd>The maximum size of any string or BLOB or table row, in bytes.<dd>)^
  3281. **
  3282. ** [[SQLITE_LIMIT_SQL_LENGTH]] ^(<dt>SQLITE_LIMIT_SQL_LENGTH</dt>
  3283. ** <dd>The maximum length of an SQL statement, in bytes.</dd>)^
  3284. **
  3285. ** [[SQLITE_LIMIT_COLUMN]] ^(<dt>SQLITE_LIMIT_COLUMN</dt>
  3286. ** <dd>The maximum number of columns in a table definition or in the
  3287. ** result set of a [SELECT] or the maximum number of columns in an index
  3288. ** or in an ORDER BY or GROUP BY clause.</dd>)^
  3289. **
  3290. ** [[SQLITE_LIMIT_EXPR_DEPTH]] ^(<dt>SQLITE_LIMIT_EXPR_DEPTH</dt>
  3291. ** <dd>The maximum depth of the parse tree on any expression.</dd>)^
  3292. **
  3293. ** [[SQLITE_LIMIT_COMPOUND_SELECT]] ^(<dt>SQLITE_LIMIT_COMPOUND_SELECT</dt>
  3294. ** <dd>The maximum number of terms in a compound SELECT statement.</dd>)^
  3295. **
  3296. ** [[SQLITE_LIMIT_VDBE_OP]] ^(<dt>SQLITE_LIMIT_VDBE_OP</dt>
  3297. ** <dd>The maximum number of instructions in a virtual machine program
  3298. ** used to implement an SQL statement. This limit is not currently
  3299. ** enforced, though that might be added in some future release of
  3300. ** SQLite.</dd>)^
  3301. **
  3302. ** [[SQLITE_LIMIT_FUNCTION_ARG]] ^(<dt>SQLITE_LIMIT_FUNCTION_ARG</dt>
  3303. ** <dd>The maximum number of arguments on a function.</dd>)^
  3304. **
  3305. ** [[SQLITE_LIMIT_ATTACHED]] ^(<dt>SQLITE_LIMIT_ATTACHED</dt>
  3306. ** <dd>The maximum number of [ATTACH | attached databases].)^</dd>
  3307. **
  3308. ** [[SQLITE_LIMIT_LIKE_PATTERN_LENGTH]]
  3309. ** ^(<dt>SQLITE_LIMIT_LIKE_PATTERN_LENGTH</dt>
  3310. ** <dd>The maximum length of the pattern argument to the [LIKE] or
  3311. ** [GLOB] operators.</dd>)^
  3312. **
  3313. ** [[SQLITE_LIMIT_VARIABLE_NUMBER]]
  3314. ** ^(<dt>SQLITE_LIMIT_VARIABLE_NUMBER</dt>
  3315. ** <dd>The maximum index number of any [parameter] in an SQL statement.)^
  3316. **
  3317. ** [[SQLITE_LIMIT_TRIGGER_DEPTH]] ^(<dt>SQLITE_LIMIT_TRIGGER_DEPTH</dt>
  3318. ** <dd>The maximum depth of recursion for triggers.</dd>)^
  3319. **
  3320. ** [[SQLITE_LIMIT_WORKER_THREADS]] ^(<dt>SQLITE_LIMIT_WORKER_THREADS</dt>
  3321. ** <dd>The maximum number of auxiliary worker threads that a single
  3322. ** [prepared statement] may start.</dd>)^
  3323. ** </dl>
  3324. */
  3325. #define SQLITE_LIMIT_LENGTH 0
  3326. #define SQLITE_LIMIT_SQL_LENGTH 1
  3327. #define SQLITE_LIMIT_COLUMN 2
  3328. #define SQLITE_LIMIT_EXPR_DEPTH 3
  3329. #define SQLITE_LIMIT_COMPOUND_SELECT 4
  3330. #define SQLITE_LIMIT_VDBE_OP 5
  3331. #define SQLITE_LIMIT_FUNCTION_ARG 6
  3332. #define SQLITE_LIMIT_ATTACHED 7
  3333. #define SQLITE_LIMIT_LIKE_PATTERN_LENGTH 8
  3334. #define SQLITE_LIMIT_VARIABLE_NUMBER 9
  3335. #define SQLITE_LIMIT_TRIGGER_DEPTH 10
  3336. #define SQLITE_LIMIT_WORKER_THREADS 11
  3337. /*
  3338. ** CAPI3REF: Compiling An SQL Statement
  3339. ** KEYWORDS: {SQL statement compiler}
  3340. ** METHOD: sqlite3
  3341. ** CONSTRUCTOR: sqlite3_stmt
  3342. **
  3343. ** To execute an SQL query, it must first be compiled into a byte-code
  3344. ** program using one of these routines.
  3345. **
  3346. ** The first argument, "db", is a [database connection] obtained from a
  3347. ** prior successful call to [sqlite3_open()], [sqlite3_open_v2()] or
  3348. ** [sqlite3_open16()]. The database connection must not have been closed.
  3349. **
  3350. ** The second argument, "zSql", is the statement to be compiled, encoded
  3351. ** as either UTF-8 or UTF-16. The sqlite3_prepare() and sqlite3_prepare_v2()
  3352. ** interfaces use UTF-8, and sqlite3_prepare16() and sqlite3_prepare16_v2()
  3353. ** use UTF-16.
  3354. **
  3355. ** ^If the nByte argument is negative, then zSql is read up to the
  3356. ** first zero terminator. ^If nByte is positive, then it is the
  3357. ** number of bytes read from zSql. ^If nByte is zero, then no prepared
  3358. ** statement is generated.
  3359. ** If the caller knows that the supplied string is nul-terminated, then
  3360. ** there is a small performance advantage to passing an nByte parameter that
  3361. ** is the number of bytes in the input string <i>including</i>
  3362. ** the nul-terminator.
  3363. **
  3364. ** ^If pzTail is not NULL then *pzTail is made to point to the first byte
  3365. ** past the end of the first SQL statement in zSql. These routines only
  3366. ** compile the first statement in zSql, so *pzTail is left pointing to
  3367. ** what remains uncompiled.
  3368. **
  3369. ** ^*ppStmt is left pointing to a compiled [prepared statement] that can be
  3370. ** executed using [sqlite3_step()]. ^If there is an error, *ppStmt is set
  3371. ** to NULL. ^If the input text contains no SQL (if the input is an empty
  3372. ** string or a comment) then *ppStmt is set to NULL.
  3373. ** The calling procedure is responsible for deleting the compiled
  3374. ** SQL statement using [sqlite3_finalize()] after it has finished with it.
  3375. ** ppStmt may not be NULL.
  3376. **
  3377. ** ^On success, the sqlite3_prepare() family of routines return [SQLITE_OK];
  3378. ** otherwise an [error code] is returned.
  3379. **
  3380. ** The sqlite3_prepare_v2() and sqlite3_prepare16_v2() interfaces are
  3381. ** recommended for all new programs. The two older interfaces are retained
  3382. ** for backwards compatibility, but their use is discouraged.
  3383. ** ^In the "v2" interfaces, the prepared statement
  3384. ** that is returned (the [sqlite3_stmt] object) contains a copy of the
  3385. ** original SQL text. This causes the [sqlite3_step()] interface to
  3386. ** behave differently in three ways:
  3387. **
  3388. ** <ol>
  3389. ** <li>
  3390. ** ^If the database schema changes, instead of returning [SQLITE_SCHEMA] as it
  3391. ** always used to do, [sqlite3_step()] will automatically recompile the SQL
  3392. ** statement and try to run it again. As many as [SQLITE_MAX_SCHEMA_RETRY]
  3393. ** retries will occur before sqlite3_step() gives up and returns an error.
  3394. ** </li>
  3395. **
  3396. ** <li>
  3397. ** ^When an error occurs, [sqlite3_step()] will return one of the detailed
  3398. ** [error codes] or [extended error codes]. ^The legacy behavior was that
  3399. ** [sqlite3_step()] would only return a generic [SQLITE_ERROR] result code
  3400. ** and the application would have to make a second call to [sqlite3_reset()]
  3401. ** in order to find the underlying cause of the problem. With the "v2" prepare
  3402. ** interfaces, the underlying reason for the error is returned immediately.
  3403. ** </li>
  3404. **
  3405. ** <li>
  3406. ** ^If the specific value bound to [parameter | host parameter] in the
  3407. ** WHERE clause might influence the choice of query plan for a statement,
  3408. ** then the statement will be automatically recompiled, as if there had been
  3409. ** a schema change, on the first [sqlite3_step()] call following any change
  3410. ** to the [sqlite3_bind_text | bindings] of that [parameter].
  3411. ** ^The specific value of WHERE-clause [parameter] might influence the
  3412. ** choice of query plan if the parameter is the left-hand side of a [LIKE]
  3413. ** or [GLOB] operator or if the parameter is compared to an indexed column
  3414. ** and the [SQLITE_ENABLE_STAT3] compile-time option is enabled.
  3415. ** </li>
  3416. ** </ol>
  3417. */
  3418. SQLITE_API int SQLITE_STDCALL sqlite3_prepare(
  3419. sqlite3 *db, /* Database handle */
  3420. const char *zSql, /* SQL statement, UTF-8 encoded */
  3421. int nByte, /* Maximum length of zSql in bytes. */
  3422. sqlite3_stmt **ppStmt, /* OUT: Statement handle */
  3423. const char **pzTail /* OUT: Pointer to unused portion of zSql */
  3424. );
  3425. SQLITE_API int SQLITE_STDCALL sqlite3_prepare_v2(
  3426. sqlite3 *db, /* Database handle */
  3427. const char *zSql, /* SQL statement, UTF-8 encoded */
  3428. int nByte, /* Maximum length of zSql in bytes. */
  3429. sqlite3_stmt **ppStmt, /* OUT: Statement handle */
  3430. const char **pzTail /* OUT: Pointer to unused portion of zSql */
  3431. );
  3432. SQLITE_API int SQLITE_STDCALL sqlite3_prepare16(
  3433. sqlite3 *db, /* Database handle */
  3434. const void *zSql, /* SQL statement, UTF-16 encoded */
  3435. int nByte, /* Maximum length of zSql in bytes. */
  3436. sqlite3_stmt **ppStmt, /* OUT: Statement handle */
  3437. const void **pzTail /* OUT: Pointer to unused portion of zSql */
  3438. );
  3439. SQLITE_API int SQLITE_STDCALL sqlite3_prepare16_v2(
  3440. sqlite3 *db, /* Database handle */
  3441. const void *zSql, /* SQL statement, UTF-16 encoded */
  3442. int nByte, /* Maximum length of zSql in bytes. */
  3443. sqlite3_stmt **ppStmt, /* OUT: Statement handle */
  3444. const void **pzTail /* OUT: Pointer to unused portion of zSql */
  3445. );
  3446. /*
  3447. ** CAPI3REF: Retrieving Statement SQL
  3448. ** METHOD: sqlite3_stmt
  3449. **
  3450. ** ^This interface can be used to retrieve a saved copy of the original
  3451. ** SQL text used to create a [prepared statement] if that statement was
  3452. ** compiled using either [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()].
  3453. */
  3454. SQLITE_API const char *SQLITE_STDCALL sqlite3_sql(sqlite3_stmt *pStmt);
  3455. /*
  3456. ** CAPI3REF: Determine If An SQL Statement Writes The Database
  3457. ** METHOD: sqlite3_stmt
  3458. **
  3459. ** ^The sqlite3_stmt_readonly(X) interface returns true (non-zero) if
  3460. ** and only if the [prepared statement] X makes no direct changes to
  3461. ** the content of the database file.
  3462. **
  3463. ** Note that [application-defined SQL functions] or
  3464. ** [virtual tables] might change the database indirectly as a side effect.
  3465. ** ^(For example, if an application defines a function "eval()" that
  3466. ** calls [sqlite3_exec()], then the following SQL statement would
  3467. ** change the database file through side-effects:
  3468. **
  3469. ** <blockquote><pre>
  3470. ** SELECT eval('DELETE FROM t1') FROM t2;
  3471. ** </pre></blockquote>
  3472. **
  3473. ** But because the [SELECT] statement does not change the database file
  3474. ** directly, sqlite3_stmt_readonly() would still return true.)^
  3475. **
  3476. ** ^Transaction control statements such as [BEGIN], [COMMIT], [ROLLBACK],
  3477. ** [SAVEPOINT], and [RELEASE] cause sqlite3_stmt_readonly() to return true,
  3478. ** since the statements themselves do not actually modify the database but
  3479. ** rather they control the timing of when other statements modify the
  3480. ** database. ^The [ATTACH] and [DETACH] statements also cause
  3481. ** sqlite3_stmt_readonly() to return true since, while those statements
  3482. ** change the configuration of a database connection, they do not make
  3483. ** changes to the content of the database files on disk.
  3484. */
  3485. SQLITE_API int SQLITE_STDCALL sqlite3_stmt_readonly(sqlite3_stmt *pStmt);
  3486. /*
  3487. ** CAPI3REF: Determine If A Prepared Statement Has Been Reset
  3488. ** METHOD: sqlite3_stmt
  3489. **
  3490. ** ^The sqlite3_stmt_busy(S) interface returns true (non-zero) if the
  3491. ** [prepared statement] S has been stepped at least once using
  3492. ** [sqlite3_step(S)] but has not run to completion and/or has not
  3493. ** been reset using [sqlite3_reset(S)]. ^The sqlite3_stmt_busy(S)
  3494. ** interface returns false if S is a NULL pointer. If S is not a
  3495. ** NULL pointer and is not a pointer to a valid [prepared statement]
  3496. ** object, then the behavior is undefined and probably undesirable.
  3497. **
  3498. ** This interface can be used in combination [sqlite3_next_stmt()]
  3499. ** to locate all prepared statements associated with a database
  3500. ** connection that are in need of being reset. This can be used,
  3501. ** for example, in diagnostic routines to search for prepared
  3502. ** statements that are holding a transaction open.
  3503. */
  3504. SQLITE_API int SQLITE_STDCALL sqlite3_stmt_busy(sqlite3_stmt*);
  3505. /*
  3506. ** CAPI3REF: Dynamically Typed Value Object
  3507. ** KEYWORDS: {protected sqlite3_value} {unprotected sqlite3_value}
  3508. **
  3509. ** SQLite uses the sqlite3_value object to represent all values
  3510. ** that can be stored in a database table. SQLite uses dynamic typing
  3511. ** for the values it stores. ^Values stored in sqlite3_value objects
  3512. ** can be integers, floating point values, strings, BLOBs, or NULL.
  3513. **
  3514. ** An sqlite3_value object may be either "protected" or "unprotected".
  3515. ** Some interfaces require a protected sqlite3_value. Other interfaces
  3516. ** will accept either a protected or an unprotected sqlite3_value.
  3517. ** Every interface that accepts sqlite3_value arguments specifies
  3518. ** whether or not it requires a protected sqlite3_value.
  3519. **
  3520. ** The terms "protected" and "unprotected" refer to whether or not
  3521. ** a mutex is held. An internal mutex is held for a protected
  3522. ** sqlite3_value object but no mutex is held for an unprotected
  3523. ** sqlite3_value object. If SQLite is compiled to be single-threaded
  3524. ** (with [SQLITE_THREADSAFE=0] and with [sqlite3_threadsafe()] returning 0)
  3525. ** or if SQLite is run in one of reduced mutex modes
  3526. ** [SQLITE_CONFIG_SINGLETHREAD] or [SQLITE_CONFIG_MULTITHREAD]
  3527. ** then there is no distinction between protected and unprotected
  3528. ** sqlite3_value objects and they can be used interchangeably. However,
  3529. ** for maximum code portability it is recommended that applications
  3530. ** still make the distinction between protected and unprotected
  3531. ** sqlite3_value objects even when not strictly required.
  3532. **
  3533. ** ^The sqlite3_value objects that are passed as parameters into the
  3534. ** implementation of [application-defined SQL functions] are protected.
  3535. ** ^The sqlite3_value object returned by
  3536. ** [sqlite3_column_value()] is unprotected.
  3537. ** Unprotected sqlite3_value objects may only be used with
  3538. ** [sqlite3_result_value()] and [sqlite3_bind_value()].
  3539. ** The [sqlite3_value_blob | sqlite3_value_type()] family of
  3540. ** interfaces require protected sqlite3_value objects.
  3541. */
  3542. typedef struct Mem sqlite3_value;
  3543. /*
  3544. ** CAPI3REF: SQL Function Context Object
  3545. **
  3546. ** The context in which an SQL function executes is stored in an
  3547. ** sqlite3_context object. ^A pointer to an sqlite3_context object
  3548. ** is always first parameter to [application-defined SQL functions].
  3549. ** The application-defined SQL function implementation will pass this
  3550. ** pointer through into calls to [sqlite3_result_int | sqlite3_result()],
  3551. ** [sqlite3_aggregate_context()], [sqlite3_user_data()],
  3552. ** [sqlite3_context_db_handle()], [sqlite3_get_auxdata()],
  3553. ** and/or [sqlite3_set_auxdata()].
  3554. */
  3555. typedef struct sqlite3_context sqlite3_context;
  3556. /*
  3557. ** CAPI3REF: Binding Values To Prepared Statements
  3558. ** KEYWORDS: {host parameter} {host parameters} {host parameter name}
  3559. ** KEYWORDS: {SQL parameter} {SQL parameters} {parameter binding}
  3560. ** METHOD: sqlite3_stmt
  3561. **
  3562. ** ^(In the SQL statement text input to [sqlite3_prepare_v2()] and its variants,
  3563. ** literals may be replaced by a [parameter] that matches one of following
  3564. ** templates:
  3565. **
  3566. ** <ul>
  3567. ** <li> ?
  3568. ** <li> ?NNN
  3569. ** <li> :VVV
  3570. ** <li> @VVV
  3571. ** <li> $VVV
  3572. ** </ul>
  3573. **
  3574. ** In the templates above, NNN represents an integer literal,
  3575. ** and VVV represents an alphanumeric identifier.)^ ^The values of these
  3576. ** parameters (also called "host parameter names" or "SQL parameters")
  3577. ** can be set using the sqlite3_bind_*() routines defined here.
  3578. **
  3579. ** ^The first argument to the sqlite3_bind_*() routines is always
  3580. ** a pointer to the [sqlite3_stmt] object returned from
  3581. ** [sqlite3_prepare_v2()] or its variants.
  3582. **
  3583. ** ^The second argument is the index of the SQL parameter to be set.
  3584. ** ^The leftmost SQL parameter has an index of 1. ^When the same named
  3585. ** SQL parameter is used more than once, second and subsequent
  3586. ** occurrences have the same index as the first occurrence.
  3587. ** ^The index for named parameters can be looked up using the
  3588. ** [sqlite3_bind_parameter_index()] API if desired. ^The index
  3589. ** for "?NNN" parameters is the value of NNN.
  3590. ** ^The NNN value must be between 1 and the [sqlite3_limit()]
  3591. ** parameter [SQLITE_LIMIT_VARIABLE_NUMBER] (default value: 999).
  3592. **
  3593. ** ^The third argument is the value to bind to the parameter.
  3594. ** ^If the third parameter to sqlite3_bind_text() or sqlite3_bind_text16()
  3595. ** or sqlite3_bind_blob() is a NULL pointer then the fourth parameter
  3596. ** is ignored and the end result is the same as sqlite3_bind_null().
  3597. **
  3598. ** ^(In those routines that have a fourth argument, its value is the
  3599. ** number of bytes in the parameter. To be clear: the value is the
  3600. ** number of <u>bytes</u> in the value, not the number of characters.)^
  3601. ** ^If the fourth parameter to sqlite3_bind_text() or sqlite3_bind_text16()
  3602. ** is negative, then the length of the string is
  3603. ** the number of bytes up to the first zero terminator.
  3604. ** If the fourth parameter to sqlite3_bind_blob() is negative, then
  3605. ** the behavior is undefined.
  3606. ** If a non-negative fourth parameter is provided to sqlite3_bind_text()
  3607. ** or sqlite3_bind_text16() or sqlite3_bind_text64() then
  3608. ** that parameter must be the byte offset
  3609. ** where the NUL terminator would occur assuming the string were NUL
  3610. ** terminated. If any NUL characters occur at byte offsets less than
  3611. ** the value of the fourth parameter then the resulting string value will
  3612. ** contain embedded NULs. The result of expressions involving strings
  3613. ** with embedded NULs is undefined.
  3614. **
  3615. ** ^The fifth argument to the BLOB and string binding interfaces
  3616. ** is a destructor used to dispose of the BLOB or
  3617. ** string after SQLite has finished with it. ^The destructor is called
  3618. ** to dispose of the BLOB or string even if the call to bind API fails.
  3619. ** ^If the fifth argument is
  3620. ** the special value [SQLITE_STATIC], then SQLite assumes that the
  3621. ** information is in static, unmanaged space and does not need to be freed.
  3622. ** ^If the fifth argument has the value [SQLITE_TRANSIENT], then
  3623. ** SQLite makes its own private copy of the data immediately, before
  3624. ** the sqlite3_bind_*() routine returns.
  3625. **
  3626. ** ^The sixth argument to sqlite3_bind_text64() must be one of
  3627. ** [SQLITE_UTF8], [SQLITE_UTF16], [SQLITE_UTF16BE], or [SQLITE_UTF16LE]
  3628. ** to specify the encoding of the text in the third parameter. If
  3629. ** the sixth argument to sqlite3_bind_text64() is not one of the
  3630. ** allowed values shown above, or if the text encoding is different
  3631. ** from the encoding specified by the sixth parameter, then the behavior
  3632. ** is undefined.
  3633. **
  3634. ** ^The sqlite3_bind_zeroblob() routine binds a BLOB of length N that
  3635. ** is filled with zeroes. ^A zeroblob uses a fixed amount of memory
  3636. ** (just an integer to hold its size) while it is being processed.
  3637. ** Zeroblobs are intended to serve as placeholders for BLOBs whose
  3638. ** content is later written using
  3639. ** [sqlite3_blob_open | incremental BLOB I/O] routines.
  3640. ** ^A negative value for the zeroblob results in a zero-length BLOB.
  3641. **
  3642. ** ^If any of the sqlite3_bind_*() routines are called with a NULL pointer
  3643. ** for the [prepared statement] or with a prepared statement for which
  3644. ** [sqlite3_step()] has been called more recently than [sqlite3_reset()],
  3645. ** then the call will return [SQLITE_MISUSE]. If any sqlite3_bind_()
  3646. ** routine is passed a [prepared statement] that has been finalized, the
  3647. ** result is undefined and probably harmful.
  3648. **
  3649. ** ^Bindings are not cleared by the [sqlite3_reset()] routine.
  3650. ** ^Unbound parameters are interpreted as NULL.
  3651. **
  3652. ** ^The sqlite3_bind_* routines return [SQLITE_OK] on success or an
  3653. ** [error code] if anything goes wrong.
  3654. ** ^[SQLITE_TOOBIG] might be returned if the size of a string or BLOB
  3655. ** exceeds limits imposed by [sqlite3_limit]([SQLITE_LIMIT_LENGTH]) or
  3656. ** [SQLITE_MAX_LENGTH].
  3657. ** ^[SQLITE_RANGE] is returned if the parameter
  3658. ** index is out of range. ^[SQLITE_NOMEM] is returned if malloc() fails.
  3659. **
  3660. ** See also: [sqlite3_bind_parameter_count()],
  3661. ** [sqlite3_bind_parameter_name()], and [sqlite3_bind_parameter_index()].
  3662. */
  3663. SQLITE_API int SQLITE_STDCALL sqlite3_bind_blob(sqlite3_stmt*, int, const void*, int n, void(*)(void*));
  3664. SQLITE_API int SQLITE_STDCALL sqlite3_bind_blob64(sqlite3_stmt*, int, const void*, sqlite3_uint64,
  3665. void(*)(void*));
  3666. SQLITE_API int SQLITE_STDCALL sqlite3_bind_double(sqlite3_stmt*, int, double);
  3667. SQLITE_API int SQLITE_STDCALL sqlite3_bind_int(sqlite3_stmt*, int, int);
  3668. SQLITE_API int SQLITE_STDCALL sqlite3_bind_int64(sqlite3_stmt*, int, sqlite3_int64);
  3669. SQLITE_API int SQLITE_STDCALL sqlite3_bind_null(sqlite3_stmt*, int);
  3670. SQLITE_API int SQLITE_STDCALL sqlite3_bind_text(sqlite3_stmt*,int,const char*,int,void(*)(void*));
  3671. SQLITE_API int SQLITE_STDCALL sqlite3_bind_text16(sqlite3_stmt*, int, const void*, int, void(*)(void*));
  3672. SQLITE_API int SQLITE_STDCALL sqlite3_bind_text64(sqlite3_stmt*, int, const char*, sqlite3_uint64,
  3673. void(*)(void*), unsigned char encoding);
  3674. SQLITE_API int SQLITE_STDCALL sqlite3_bind_value(sqlite3_stmt*, int, const sqlite3_value*);
  3675. SQLITE_API int SQLITE_STDCALL sqlite3_bind_zeroblob(sqlite3_stmt*, int, int n);
  3676. /*
  3677. ** CAPI3REF: Number Of SQL Parameters
  3678. ** METHOD: sqlite3_stmt
  3679. **
  3680. ** ^This routine can be used to find the number of [SQL parameters]
  3681. ** in a [prepared statement]. SQL parameters are tokens of the
  3682. ** form "?", "?NNN", ":AAA", "$AAA", or "@AAA" that serve as
  3683. ** placeholders for values that are [sqlite3_bind_blob | bound]
  3684. ** to the parameters at a later time.
  3685. **
  3686. ** ^(This routine actually returns the index of the largest (rightmost)
  3687. ** parameter. For all forms except ?NNN, this will correspond to the
  3688. ** number of unique parameters. If parameters of the ?NNN form are used,
  3689. ** there may be gaps in the list.)^
  3690. **
  3691. ** See also: [sqlite3_bind_blob|sqlite3_bind()],
  3692. ** [sqlite3_bind_parameter_name()], and
  3693. ** [sqlite3_bind_parameter_index()].
  3694. */
  3695. SQLITE_API int SQLITE_STDCALL sqlite3_bind_parameter_count(sqlite3_stmt*);
  3696. /*
  3697. ** CAPI3REF: Name Of A Host Parameter
  3698. ** METHOD: sqlite3_stmt
  3699. **
  3700. ** ^The sqlite3_bind_parameter_name(P,N) interface returns
  3701. ** the name of the N-th [SQL parameter] in the [prepared statement] P.
  3702. ** ^(SQL parameters of the form "?NNN" or ":AAA" or "@AAA" or "$AAA"
  3703. ** have a name which is the string "?NNN" or ":AAA" or "@AAA" or "$AAA"
  3704. ** respectively.
  3705. ** In other words, the initial ":" or "$" or "@" or "?"
  3706. ** is included as part of the name.)^
  3707. ** ^Parameters of the form "?" without a following integer have no name
  3708. ** and are referred to as "nameless" or "anonymous parameters".
  3709. **
  3710. ** ^The first host parameter has an index of 1, not 0.
  3711. **
  3712. ** ^If the value N is out of range or if the N-th parameter is
  3713. ** nameless, then NULL is returned. ^The returned string is
  3714. ** always in UTF-8 encoding even if the named parameter was
  3715. ** originally specified as UTF-16 in [sqlite3_prepare16()] or
  3716. ** [sqlite3_prepare16_v2()].
  3717. **
  3718. ** See also: [sqlite3_bind_blob|sqlite3_bind()],
  3719. ** [sqlite3_bind_parameter_count()], and
  3720. ** [sqlite3_bind_parameter_index()].
  3721. */
  3722. SQLITE_API const char *SQLITE_STDCALL sqlite3_bind_parameter_name(sqlite3_stmt*, int);
  3723. /*
  3724. ** CAPI3REF: Index Of A Parameter With A Given Name
  3725. ** METHOD: sqlite3_stmt
  3726. **
  3727. ** ^Return the index of an SQL parameter given its name. ^The
  3728. ** index value returned is suitable for use as the second
  3729. ** parameter to [sqlite3_bind_blob|sqlite3_bind()]. ^A zero
  3730. ** is returned if no matching parameter is found. ^The parameter
  3731. ** name must be given in UTF-8 even if the original statement
  3732. ** was prepared from UTF-16 text using [sqlite3_prepare16_v2()].
  3733. **
  3734. ** See also: [sqlite3_bind_blob|sqlite3_bind()],
  3735. ** [sqlite3_bind_parameter_count()], and
  3736. ** [sqlite3_bind_parameter_index()].
  3737. */
  3738. SQLITE_API int SQLITE_STDCALL sqlite3_bind_parameter_index(sqlite3_stmt*, const char *zName);
  3739. /*
  3740. ** CAPI3REF: Reset All Bindings On A Prepared Statement
  3741. ** METHOD: sqlite3_stmt
  3742. **
  3743. ** ^Contrary to the intuition of many, [sqlite3_reset()] does not reset
  3744. ** the [sqlite3_bind_blob | bindings] on a [prepared statement].
  3745. ** ^Use this routine to reset all host parameters to NULL.
  3746. */
  3747. SQLITE_API int SQLITE_STDCALL sqlite3_clear_bindings(sqlite3_stmt*);
  3748. /*
  3749. ** CAPI3REF: Number Of Columns In A Result Set
  3750. ** METHOD: sqlite3_stmt
  3751. **
  3752. ** ^Return the number of columns in the result set returned by the
  3753. ** [prepared statement]. ^This routine returns 0 if pStmt is an SQL
  3754. ** statement that does not return data (for example an [UPDATE]).
  3755. **
  3756. ** See also: [sqlite3_data_count()]
  3757. */
  3758. SQLITE_API int SQLITE_STDCALL sqlite3_column_count(sqlite3_stmt *pStmt);
  3759. /*
  3760. ** CAPI3REF: Column Names In A Result Set
  3761. ** METHOD: sqlite3_stmt
  3762. **
  3763. ** ^These routines return the name assigned to a particular column
  3764. ** in the result set of a [SELECT] statement. ^The sqlite3_column_name()
  3765. ** interface returns a pointer to a zero-terminated UTF-8 string
  3766. ** and sqlite3_column_name16() returns a pointer to a zero-terminated
  3767. ** UTF-16 string. ^The first parameter is the [prepared statement]
  3768. ** that implements the [SELECT] statement. ^The second parameter is the
  3769. ** column number. ^The leftmost column is number 0.
  3770. **
  3771. ** ^The returned string pointer is valid until either the [prepared statement]
  3772. ** is destroyed by [sqlite3_finalize()] or until the statement is automatically
  3773. ** reprepared by the first call to [sqlite3_step()] for a particular run
  3774. ** or until the next call to
  3775. ** sqlite3_column_name() or sqlite3_column_name16() on the same column.
  3776. **
  3777. ** ^If sqlite3_malloc() fails during the processing of either routine
  3778. ** (for example during a conversion from UTF-8 to UTF-16) then a
  3779. ** NULL pointer is returned.
  3780. **
  3781. ** ^The name of a result column is the value of the "AS" clause for
  3782. ** that column, if there is an AS clause. If there is no AS clause
  3783. ** then the name of the column is unspecified and may change from
  3784. ** one release of SQLite to the next.
  3785. */
  3786. SQLITE_API const char *SQLITE_STDCALL sqlite3_column_name(sqlite3_stmt*, int N);
  3787. SQLITE_API const void *SQLITE_STDCALL sqlite3_column_name16(sqlite3_stmt*, int N);
  3788. /*
  3789. ** CAPI3REF: Source Of Data In A Query Result
  3790. ** METHOD: sqlite3_stmt
  3791. **
  3792. ** ^These routines provide a means to determine the database, table, and
  3793. ** table column that is the origin of a particular result column in
  3794. ** [SELECT] statement.
  3795. ** ^The name of the database or table or column can be returned as
  3796. ** either a UTF-8 or UTF-16 string. ^The _database_ routines return
  3797. ** the database name, the _table_ routines return the table name, and
  3798. ** the origin_ routines return the column name.
  3799. ** ^The returned string is valid until the [prepared statement] is destroyed
  3800. ** using [sqlite3_finalize()] or until the statement is automatically
  3801. ** reprepared by the first call to [sqlite3_step()] for a particular run
  3802. ** or until the same information is requested
  3803. ** again in a different encoding.
  3804. **
  3805. ** ^The names returned are the original un-aliased names of the
  3806. ** database, table, and column.
  3807. **
  3808. ** ^The first argument to these interfaces is a [prepared statement].
  3809. ** ^These functions return information about the Nth result column returned by
  3810. ** the statement, where N is the second function argument.
  3811. ** ^The left-most column is column 0 for these routines.
  3812. **
  3813. ** ^If the Nth column returned by the statement is an expression or
  3814. ** subquery and is not a column value, then all of these functions return
  3815. ** NULL. ^These routine might also return NULL if a memory allocation error
  3816. ** occurs. ^Otherwise, they return the name of the attached database, table,
  3817. ** or column that query result column was extracted from.
  3818. **
  3819. ** ^As with all other SQLite APIs, those whose names end with "16" return
  3820. ** UTF-16 encoded strings and the other functions return UTF-8.
  3821. **
  3822. ** ^These APIs are only available if the library was compiled with the
  3823. ** [SQLITE_ENABLE_COLUMN_METADATA] C-preprocessor symbol.
  3824. **
  3825. ** If two or more threads call one or more of these routines against the same
  3826. ** prepared statement and column at the same time then the results are
  3827. ** undefined.
  3828. **
  3829. ** If two or more threads call one or more
  3830. ** [sqlite3_column_database_name | column metadata interfaces]
  3831. ** for the same [prepared statement] and result column
  3832. ** at the same time then the results are undefined.
  3833. */
  3834. SQLITE_API const char *SQLITE_STDCALL sqlite3_column_database_name(sqlite3_stmt*,int);
  3835. SQLITE_API const void *SQLITE_STDCALL sqlite3_column_database_name16(sqlite3_stmt*,int);
  3836. SQLITE_API const char *SQLITE_STDCALL sqlite3_column_table_name(sqlite3_stmt*,int);
  3837. SQLITE_API const void *SQLITE_STDCALL sqlite3_column_table_name16(sqlite3_stmt*,int);
  3838. SQLITE_API const char *SQLITE_STDCALL sqlite3_column_origin_name(sqlite3_stmt*,int);
  3839. SQLITE_API const void *SQLITE_STDCALL sqlite3_column_origin_name16(sqlite3_stmt*,int);
  3840. /*
  3841. ** CAPI3REF: Declared Datatype Of A Query Result
  3842. ** METHOD: sqlite3_stmt
  3843. **
  3844. ** ^(The first parameter is a [prepared statement].
  3845. ** If this statement is a [SELECT] statement and the Nth column of the
  3846. ** returned result set of that [SELECT] is a table column (not an
  3847. ** expression or subquery) then the declared type of the table
  3848. ** column is returned.)^ ^If the Nth column of the result set is an
  3849. ** expression or subquery, then a NULL pointer is returned.
  3850. ** ^The returned string is always UTF-8 encoded.
  3851. **
  3852. ** ^(For example, given the database schema:
  3853. **
  3854. ** CREATE TABLE t1(c1 VARIANT);
  3855. **
  3856. ** and the following statement to be compiled:
  3857. **
  3858. ** SELECT c1 + 1, c1 FROM t1;
  3859. **
  3860. ** this routine would return the string "VARIANT" for the second result
  3861. ** column (i==1), and a NULL pointer for the first result column (i==0).)^
  3862. **
  3863. ** ^SQLite uses dynamic run-time typing. ^So just because a column
  3864. ** is declared to contain a particular type does not mean that the
  3865. ** data stored in that column is of the declared type. SQLite is
  3866. ** strongly typed, but the typing is dynamic not static. ^Type
  3867. ** is associated with individual values, not with the containers
  3868. ** used to hold those values.
  3869. */
  3870. SQLITE_API const char *SQLITE_STDCALL sqlite3_column_decltype(sqlite3_stmt*,int);
  3871. SQLITE_API const void *SQLITE_STDCALL sqlite3_column_decltype16(sqlite3_stmt*,int);
  3872. /*
  3873. ** CAPI3REF: Evaluate An SQL Statement
  3874. ** METHOD: sqlite3_stmt
  3875. **
  3876. ** After a [prepared statement] has been prepared using either
  3877. ** [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()] or one of the legacy
  3878. ** interfaces [sqlite3_prepare()] or [sqlite3_prepare16()], this function
  3879. ** must be called one or more times to evaluate the statement.
  3880. **
  3881. ** The details of the behavior of the sqlite3_step() interface depend
  3882. ** on whether the statement was prepared using the newer "v2" interface
  3883. ** [sqlite3_prepare_v2()] and [sqlite3_prepare16_v2()] or the older legacy
  3884. ** interface [sqlite3_prepare()] and [sqlite3_prepare16()]. The use of the
  3885. ** new "v2" interface is recommended for new applications but the legacy
  3886. ** interface will continue to be supported.
  3887. **
  3888. ** ^In the legacy interface, the return value will be either [SQLITE_BUSY],
  3889. ** [SQLITE_DONE], [SQLITE_ROW], [SQLITE_ERROR], or [SQLITE_MISUSE].
  3890. ** ^With the "v2" interface, any of the other [result codes] or
  3891. ** [extended result codes] might be returned as well.
  3892. **
  3893. ** ^[SQLITE_BUSY] means that the database engine was unable to acquire the
  3894. ** database locks it needs to do its job. ^If the statement is a [COMMIT]
  3895. ** or occurs outside of an explicit transaction, then you can retry the
  3896. ** statement. If the statement is not a [COMMIT] and occurs within an
  3897. ** explicit transaction then you should rollback the transaction before
  3898. ** continuing.
  3899. **
  3900. ** ^[SQLITE_DONE] means that the statement has finished executing
  3901. ** successfully. sqlite3_step() should not be called again on this virtual
  3902. ** machine without first calling [sqlite3_reset()] to reset the virtual
  3903. ** machine back to its initial state.
  3904. **
  3905. ** ^If the SQL statement being executed returns any data, then [SQLITE_ROW]
  3906. ** is returned each time a new row of data is ready for processing by the
  3907. ** caller. The values may be accessed using the [column access functions].
  3908. ** sqlite3_step() is called again to retrieve the next row of data.
  3909. **
  3910. ** ^[SQLITE_ERROR] means that a run-time error (such as a constraint
  3911. ** violation) has occurred. sqlite3_step() should not be called again on
  3912. ** the VM. More information may be found by calling [sqlite3_errmsg()].
  3913. ** ^With the legacy interface, a more specific error code (for example,
  3914. ** [SQLITE_INTERRUPT], [SQLITE_SCHEMA], [SQLITE_CORRUPT], and so forth)
  3915. ** can be obtained by calling [sqlite3_reset()] on the
  3916. ** [prepared statement]. ^In the "v2" interface,
  3917. ** the more specific error code is returned directly by sqlite3_step().
  3918. **
  3919. ** [SQLITE_MISUSE] means that the this routine was called inappropriately.
  3920. ** Perhaps it was called on a [prepared statement] that has
  3921. ** already been [sqlite3_finalize | finalized] or on one that had
  3922. ** previously returned [SQLITE_ERROR] or [SQLITE_DONE]. Or it could
  3923. ** be the case that the same database connection is being used by two or
  3924. ** more threads at the same moment in time.
  3925. **
  3926. ** For all versions of SQLite up to and including 3.6.23.1, a call to
  3927. ** [sqlite3_reset()] was required after sqlite3_step() returned anything
  3928. ** other than [SQLITE_ROW] before any subsequent invocation of
  3929. ** sqlite3_step(). Failure to reset the prepared statement using
  3930. ** [sqlite3_reset()] would result in an [SQLITE_MISUSE] return from
  3931. ** sqlite3_step(). But after version 3.6.23.1, sqlite3_step() began
  3932. ** calling [sqlite3_reset()] automatically in this circumstance rather
  3933. ** than returning [SQLITE_MISUSE]. This is not considered a compatibility
  3934. ** break because any application that ever receives an SQLITE_MISUSE error
  3935. ** is broken by definition. The [SQLITE_OMIT_AUTORESET] compile-time option
  3936. ** can be used to restore the legacy behavior.
  3937. **
  3938. ** <b>Goofy Interface Alert:</b> In the legacy interface, the sqlite3_step()
  3939. ** API always returns a generic error code, [SQLITE_ERROR], following any
  3940. ** error other than [SQLITE_BUSY] and [SQLITE_MISUSE]. You must call
  3941. ** [sqlite3_reset()] or [sqlite3_finalize()] in order to find one of the
  3942. ** specific [error codes] that better describes the error.
  3943. ** We admit that this is a goofy design. The problem has been fixed
  3944. ** with the "v2" interface. If you prepare all of your SQL statements
  3945. ** using either [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()] instead
  3946. ** of the legacy [sqlite3_prepare()] and [sqlite3_prepare16()] interfaces,
  3947. ** then the more specific [error codes] are returned directly
  3948. ** by sqlite3_step(). The use of the "v2" interface is recommended.
  3949. */
  3950. SQLITE_API int SQLITE_STDCALL sqlite3_step(sqlite3_stmt*);
  3951. /*
  3952. ** CAPI3REF: Number of columns in a result set
  3953. ** METHOD: sqlite3_stmt
  3954. **
  3955. ** ^The sqlite3_data_count(P) interface returns the number of columns in the
  3956. ** current row of the result set of [prepared statement] P.
  3957. ** ^If prepared statement P does not have results ready to return
  3958. ** (via calls to the [sqlite3_column_int | sqlite3_column_*()] of
  3959. ** interfaces) then sqlite3_data_count(P) returns 0.
  3960. ** ^The sqlite3_data_count(P) routine also returns 0 if P is a NULL pointer.
  3961. ** ^The sqlite3_data_count(P) routine returns 0 if the previous call to
  3962. ** [sqlite3_step](P) returned [SQLITE_DONE]. ^The sqlite3_data_count(P)
  3963. ** will return non-zero if previous call to [sqlite3_step](P) returned
  3964. ** [SQLITE_ROW], except in the case of the [PRAGMA incremental_vacuum]
  3965. ** where it always returns zero since each step of that multi-step
  3966. ** pragma returns 0 columns of data.
  3967. **
  3968. ** See also: [sqlite3_column_count()]
  3969. */
  3970. SQLITE_API int SQLITE_STDCALL sqlite3_data_count(sqlite3_stmt *pStmt);
  3971. /*
  3972. ** CAPI3REF: Fundamental Datatypes
  3973. ** KEYWORDS: SQLITE_TEXT
  3974. **
  3975. ** ^(Every value in SQLite has one of five fundamental datatypes:
  3976. **
  3977. ** <ul>
  3978. ** <li> 64-bit signed integer
  3979. ** <li> 64-bit IEEE floating point number
  3980. ** <li> string
  3981. ** <li> BLOB
  3982. ** <li> NULL
  3983. ** </ul>)^
  3984. **
  3985. ** These constants are codes for each of those types.
  3986. **
  3987. ** Note that the SQLITE_TEXT constant was also used in SQLite version 2
  3988. ** for a completely different meaning. Software that links against both
  3989. ** SQLite version 2 and SQLite version 3 should use SQLITE3_TEXT, not
  3990. ** SQLITE_TEXT.
  3991. */
  3992. #define SQLITE_INTEGER 1
  3993. #define SQLITE_FLOAT 2
  3994. #define SQLITE_BLOB 4
  3995. #define SQLITE_NULL 5
  3996. #ifdef SQLITE_TEXT
  3997. # undef SQLITE_TEXT
  3998. #else
  3999. # define SQLITE_TEXT 3
  4000. #endif
  4001. #define SQLITE3_TEXT 3
  4002. /*
  4003. ** CAPI3REF: Result Values From A Query
  4004. ** KEYWORDS: {column access functions}
  4005. ** METHOD: sqlite3_stmt
  4006. **
  4007. ** These routines form the "result set" interface.
  4008. **
  4009. ** ^These routines return information about a single column of the current
  4010. ** result row of a query. ^In every case the first argument is a pointer
  4011. ** to the [prepared statement] that is being evaluated (the [sqlite3_stmt*]
  4012. ** that was returned from [sqlite3_prepare_v2()] or one of its variants)
  4013. ** and the second argument is the index of the column for which information
  4014. ** should be returned. ^The leftmost column of the result set has the index 0.
  4015. ** ^The number of columns in the result can be determined using
  4016. ** [sqlite3_column_count()].
  4017. **
  4018. ** If the SQL statement does not currently point to a valid row, or if the
  4019. ** column index is out of range, the result is undefined.
  4020. ** These routines may only be called when the most recent call to
  4021. ** [sqlite3_step()] has returned [SQLITE_ROW] and neither
  4022. ** [sqlite3_reset()] nor [sqlite3_finalize()] have been called subsequently.
  4023. ** If any of these routines are called after [sqlite3_reset()] or
  4024. ** [sqlite3_finalize()] or after [sqlite3_step()] has returned
  4025. ** something other than [SQLITE_ROW], the results are undefined.
  4026. ** If [sqlite3_step()] or [sqlite3_reset()] or [sqlite3_finalize()]
  4027. ** are called from a different thread while any of these routines
  4028. ** are pending, then the results are undefined.
  4029. **
  4030. ** ^The sqlite3_column_type() routine returns the
  4031. ** [SQLITE_INTEGER | datatype code] for the initial data type
  4032. ** of the result column. ^The returned value is one of [SQLITE_INTEGER],
  4033. ** [SQLITE_FLOAT], [SQLITE_TEXT], [SQLITE_BLOB], or [SQLITE_NULL]. The value
  4034. ** returned by sqlite3_column_type() is only meaningful if no type
  4035. ** conversions have occurred as described below. After a type conversion,
  4036. ** the value returned by sqlite3_column_type() is undefined. Future
  4037. ** versions of SQLite may change the behavior of sqlite3_column_type()
  4038. ** following a type conversion.
  4039. **
  4040. ** ^If the result is a BLOB or UTF-8 string then the sqlite3_column_bytes()
  4041. ** routine returns the number of bytes in that BLOB or string.
  4042. ** ^If the result is a UTF-16 string, then sqlite3_column_bytes() converts
  4043. ** the string to UTF-8 and then returns the number of bytes.
  4044. ** ^If the result is a numeric value then sqlite3_column_bytes() uses
  4045. ** [sqlite3_snprintf()] to convert that value to a UTF-8 string and returns
  4046. ** the number of bytes in that string.
  4047. ** ^If the result is NULL, then sqlite3_column_bytes() returns zero.
  4048. **
  4049. ** ^If the result is a BLOB or UTF-16 string then the sqlite3_column_bytes16()
  4050. ** routine returns the number of bytes in that BLOB or string.
  4051. ** ^If the result is a UTF-8 string, then sqlite3_column_bytes16() converts
  4052. ** the string to UTF-16 and then returns the number of bytes.
  4053. ** ^If the result is a numeric value then sqlite3_column_bytes16() uses
  4054. ** [sqlite3_snprintf()] to convert that value to a UTF-16 string and returns
  4055. ** the number of bytes in that string.
  4056. ** ^If the result is NULL, then sqlite3_column_bytes16() returns zero.
  4057. **
  4058. ** ^The values returned by [sqlite3_column_bytes()] and
  4059. ** [sqlite3_column_bytes16()] do not include the zero terminators at the end
  4060. ** of the string. ^For clarity: the values returned by
  4061. ** [sqlite3_column_bytes()] and [sqlite3_column_bytes16()] are the number of
  4062. ** bytes in the string, not the number of characters.
  4063. **
  4064. ** ^Strings returned by sqlite3_column_text() and sqlite3_column_text16(),
  4065. ** even empty strings, are always zero-terminated. ^The return
  4066. ** value from sqlite3_column_blob() for a zero-length BLOB is a NULL pointer.
  4067. **
  4068. ** ^The object returned by [sqlite3_column_value()] is an
  4069. ** [unprotected sqlite3_value] object. An unprotected sqlite3_value object
  4070. ** may only be used with [sqlite3_bind_value()] and [sqlite3_result_value()].
  4071. ** If the [unprotected sqlite3_value] object returned by
  4072. ** [sqlite3_column_value()] is used in any other way, including calls
  4073. ** to routines like [sqlite3_value_int()], [sqlite3_value_text()],
  4074. ** or [sqlite3_value_bytes()], then the behavior is undefined.
  4075. **
  4076. ** These routines attempt to convert the value where appropriate. ^For
  4077. ** example, if the internal representation is FLOAT and a text result
  4078. ** is requested, [sqlite3_snprintf()] is used internally to perform the
  4079. ** conversion automatically. ^(The following table details the conversions
  4080. ** that are applied:
  4081. **
  4082. ** <blockquote>
  4083. ** <table border="1">
  4084. ** <tr><th> Internal<br>Type <th> Requested<br>Type <th> Conversion
  4085. **
  4086. ** <tr><td> NULL <td> INTEGER <td> Result is 0
  4087. ** <tr><td> NULL <td> FLOAT <td> Result is 0.0
  4088. ** <tr><td> NULL <td> TEXT <td> Result is a NULL pointer
  4089. ** <tr><td> NULL <td> BLOB <td> Result is a NULL pointer
  4090. ** <tr><td> INTEGER <td> FLOAT <td> Convert from integer to float
  4091. ** <tr><td> INTEGER <td> TEXT <td> ASCII rendering of the integer
  4092. ** <tr><td> INTEGER <td> BLOB <td> Same as INTEGER->TEXT
  4093. ** <tr><td> FLOAT <td> INTEGER <td> [CAST] to INTEGER
  4094. ** <tr><td> FLOAT <td> TEXT <td> ASCII rendering of the float
  4095. ** <tr><td> FLOAT <td> BLOB <td> [CAST] to BLOB
  4096. ** <tr><td> TEXT <td> INTEGER <td> [CAST] to INTEGER
  4097. ** <tr><td> TEXT <td> FLOAT <td> [CAST] to REAL
  4098. ** <tr><td> TEXT <td> BLOB <td> No change
  4099. ** <tr><td> BLOB <td> INTEGER <td> [CAST] to INTEGER
  4100. ** <tr><td> BLOB <td> FLOAT <td> [CAST] to REAL
  4101. ** <tr><td> BLOB <td> TEXT <td> Add a zero terminator if needed
  4102. ** </table>
  4103. ** </blockquote>)^
  4104. **
  4105. ** The table above makes reference to standard C library functions atoi()
  4106. ** and atof(). SQLite does not really use these functions. It has its
  4107. ** own equivalent internal routines. The atoi() and atof() names are
  4108. ** used in the table for brevity and because they are familiar to most
  4109. ** C programmers.
  4110. **
  4111. ** Note that when type conversions occur, pointers returned by prior
  4112. ** calls to sqlite3_column_blob(), sqlite3_column_text(), and/or
  4113. ** sqlite3_column_text16() may be invalidated.
  4114. ** Type conversions and pointer invalidations might occur
  4115. ** in the following cases:
  4116. **
  4117. ** <ul>
  4118. ** <li> The initial content is a BLOB and sqlite3_column_text() or
  4119. ** sqlite3_column_text16() is called. A zero-terminator might
  4120. ** need to be added to the string.</li>
  4121. ** <li> The initial content is UTF-8 text and sqlite3_column_bytes16() or
  4122. ** sqlite3_column_text16() is called. The content must be converted
  4123. ** to UTF-16.</li>
  4124. ** <li> The initial content is UTF-16 text and sqlite3_column_bytes() or
  4125. ** sqlite3_column_text() is called. The content must be converted
  4126. ** to UTF-8.</li>
  4127. ** </ul>
  4128. **
  4129. ** ^Conversions between UTF-16be and UTF-16le are always done in place and do
  4130. ** not invalidate a prior pointer, though of course the content of the buffer
  4131. ** that the prior pointer references will have been modified. Other kinds
  4132. ** of conversion are done in place when it is possible, but sometimes they
  4133. ** are not possible and in those cases prior pointers are invalidated.
  4134. **
  4135. ** The safest and easiest to remember policy is to invoke these routines
  4136. ** in one of the following ways:
  4137. **
  4138. ** <ul>
  4139. ** <li>sqlite3_column_text() followed by sqlite3_column_bytes()</li>
  4140. ** <li>sqlite3_column_blob() followed by sqlite3_column_bytes()</li>
  4141. ** <li>sqlite3_column_text16() followed by sqlite3_column_bytes16()</li>
  4142. ** </ul>
  4143. **
  4144. ** In other words, you should call sqlite3_column_text(),
  4145. ** sqlite3_column_blob(), or sqlite3_column_text16() first to force the result
  4146. ** into the desired format, then invoke sqlite3_column_bytes() or
  4147. ** sqlite3_column_bytes16() to find the size of the result. Do not mix calls
  4148. ** to sqlite3_column_text() or sqlite3_column_blob() with calls to
  4149. ** sqlite3_column_bytes16(), and do not mix calls to sqlite3_column_text16()
  4150. ** with calls to sqlite3_column_bytes().
  4151. **
  4152. ** ^The pointers returned are valid until a type conversion occurs as
  4153. ** described above, or until [sqlite3_step()] or [sqlite3_reset()] or
  4154. ** [sqlite3_finalize()] is called. ^The memory space used to hold strings
  4155. ** and BLOBs is freed automatically. Do <b>not</b> pass the pointers returned
  4156. ** from [sqlite3_column_blob()], [sqlite3_column_text()], etc. into
  4157. ** [sqlite3_free()].
  4158. **
  4159. ** ^(If a memory allocation error occurs during the evaluation of any
  4160. ** of these routines, a default value is returned. The default value
  4161. ** is either the integer 0, the floating point number 0.0, or a NULL
  4162. ** pointer. Subsequent calls to [sqlite3_errcode()] will return
  4163. ** [SQLITE_NOMEM].)^
  4164. */
  4165. SQLITE_API const void *SQLITE_STDCALL sqlite3_column_blob(sqlite3_stmt*, int iCol);
  4166. SQLITE_API int SQLITE_STDCALL sqlite3_column_bytes(sqlite3_stmt*, int iCol);
  4167. SQLITE_API int SQLITE_STDCALL sqlite3_column_bytes16(sqlite3_stmt*, int iCol);
  4168. SQLITE_API double SQLITE_STDCALL sqlite3_column_double(sqlite3_stmt*, int iCol);
  4169. SQLITE_API int SQLITE_STDCALL sqlite3_column_int(sqlite3_stmt*, int iCol);
  4170. SQLITE_API sqlite3_int64 SQLITE_STDCALL sqlite3_column_int64(sqlite3_stmt*, int iCol);
  4171. SQLITE_API const unsigned char *SQLITE_STDCALL sqlite3_column_text(sqlite3_stmt*, int iCol);
  4172. SQLITE_API const void *SQLITE_STDCALL sqlite3_column_text16(sqlite3_stmt*, int iCol);
  4173. SQLITE_API int SQLITE_STDCALL sqlite3_column_type(sqlite3_stmt*, int iCol);
  4174. SQLITE_API sqlite3_value *SQLITE_STDCALL sqlite3_column_value(sqlite3_stmt*, int iCol);
  4175. /*
  4176. ** CAPI3REF: Destroy A Prepared Statement Object
  4177. ** DESTRUCTOR: sqlite3_stmt
  4178. **
  4179. ** ^The sqlite3_finalize() function is called to delete a [prepared statement].
  4180. ** ^If the most recent evaluation of the statement encountered no errors
  4181. ** or if the statement is never been evaluated, then sqlite3_finalize() returns
  4182. ** SQLITE_OK. ^If the most recent evaluation of statement S failed, then
  4183. ** sqlite3_finalize(S) returns the appropriate [error code] or
  4184. ** [extended error code].
  4185. **
  4186. ** ^The sqlite3_finalize(S) routine can be called at any point during
  4187. ** the life cycle of [prepared statement] S:
  4188. ** before statement S is ever evaluated, after
  4189. ** one or more calls to [sqlite3_reset()], or after any call
  4190. ** to [sqlite3_step()] regardless of whether or not the statement has
  4191. ** completed execution.
  4192. **
  4193. ** ^Invoking sqlite3_finalize() on a NULL pointer is a harmless no-op.
  4194. **
  4195. ** The application must finalize every [prepared statement] in order to avoid
  4196. ** resource leaks. It is a grievous error for the application to try to use
  4197. ** a prepared statement after it has been finalized. Any use of a prepared
  4198. ** statement after it has been finalized can result in undefined and
  4199. ** undesirable behavior such as segfaults and heap corruption.
  4200. */
  4201. SQLITE_API int SQLITE_STDCALL sqlite3_finalize(sqlite3_stmt *pStmt);
  4202. /*
  4203. ** CAPI3REF: Reset A Prepared Statement Object
  4204. ** METHOD: sqlite3_stmt
  4205. **
  4206. ** The sqlite3_reset() function is called to reset a [prepared statement]
  4207. ** object back to its initial state, ready to be re-executed.
  4208. ** ^Any SQL statement variables that had values bound to them using
  4209. ** the [sqlite3_bind_blob | sqlite3_bind_*() API] retain their values.
  4210. ** Use [sqlite3_clear_bindings()] to reset the bindings.
  4211. **
  4212. ** ^The [sqlite3_reset(S)] interface resets the [prepared statement] S
  4213. ** back to the beginning of its program.
  4214. **
  4215. ** ^If the most recent call to [sqlite3_step(S)] for the
  4216. ** [prepared statement] S returned [SQLITE_ROW] or [SQLITE_DONE],
  4217. ** or if [sqlite3_step(S)] has never before been called on S,
  4218. ** then [sqlite3_reset(S)] returns [SQLITE_OK].
  4219. **
  4220. ** ^If the most recent call to [sqlite3_step(S)] for the
  4221. ** [prepared statement] S indicated an error, then
  4222. ** [sqlite3_reset(S)] returns an appropriate [error code].
  4223. **
  4224. ** ^The [sqlite3_reset(S)] interface does not change the values
  4225. ** of any [sqlite3_bind_blob|bindings] on the [prepared statement] S.
  4226. */
  4227. SQLITE_API int SQLITE_STDCALL sqlite3_reset(sqlite3_stmt *pStmt);
  4228. /*
  4229. ** CAPI3REF: Create Or Redefine SQL Functions
  4230. ** KEYWORDS: {function creation routines}
  4231. ** KEYWORDS: {application-defined SQL function}
  4232. ** KEYWORDS: {application-defined SQL functions}
  4233. ** METHOD: sqlite3
  4234. **
  4235. ** ^These functions (collectively known as "function creation routines")
  4236. ** are used to add SQL functions or aggregates or to redefine the behavior
  4237. ** of existing SQL functions or aggregates. The only differences between
  4238. ** these routines are the text encoding expected for
  4239. ** the second parameter (the name of the function being created)
  4240. ** and the presence or absence of a destructor callback for
  4241. ** the application data pointer.
  4242. **
  4243. ** ^The first parameter is the [database connection] to which the SQL
  4244. ** function is to be added. ^If an application uses more than one database
  4245. ** connection then application-defined SQL functions must be added
  4246. ** to each database connection separately.
  4247. **
  4248. ** ^The second parameter is the name of the SQL function to be created or
  4249. ** redefined. ^The length of the name is limited to 255 bytes in a UTF-8
  4250. ** representation, exclusive of the zero-terminator. ^Note that the name
  4251. ** length limit is in UTF-8 bytes, not characters nor UTF-16 bytes.
  4252. ** ^Any attempt to create a function with a longer name
  4253. ** will result in [SQLITE_MISUSE] being returned.
  4254. **
  4255. ** ^The third parameter (nArg)
  4256. ** is the number of arguments that the SQL function or
  4257. ** aggregate takes. ^If this parameter is -1, then the SQL function or
  4258. ** aggregate may take any number of arguments between 0 and the limit
  4259. ** set by [sqlite3_limit]([SQLITE_LIMIT_FUNCTION_ARG]). If the third
  4260. ** parameter is less than -1 or greater than 127 then the behavior is
  4261. ** undefined.
  4262. **
  4263. ** ^The fourth parameter, eTextRep, specifies what
  4264. ** [SQLITE_UTF8 | text encoding] this SQL function prefers for
  4265. ** its parameters. The application should set this parameter to
  4266. ** [SQLITE_UTF16LE] if the function implementation invokes
  4267. ** [sqlite3_value_text16le()] on an input, or [SQLITE_UTF16BE] if the
  4268. ** implementation invokes [sqlite3_value_text16be()] on an input, or
  4269. ** [SQLITE_UTF16] if [sqlite3_value_text16()] is used, or [SQLITE_UTF8]
  4270. ** otherwise. ^The same SQL function may be registered multiple times using
  4271. ** different preferred text encodings, with different implementations for
  4272. ** each encoding.
  4273. ** ^When multiple implementations of the same function are available, SQLite
  4274. ** will pick the one that involves the least amount of data conversion.
  4275. **
  4276. ** ^The fourth parameter may optionally be ORed with [SQLITE_DETERMINISTIC]
  4277. ** to signal that the function will always return the same result given
  4278. ** the same inputs within a single SQL statement. Most SQL functions are
  4279. ** deterministic. The built-in [random()] SQL function is an example of a
  4280. ** function that is not deterministic. The SQLite query planner is able to
  4281. ** perform additional optimizations on deterministic functions, so use
  4282. ** of the [SQLITE_DETERMINISTIC] flag is recommended where possible.
  4283. **
  4284. ** ^(The fifth parameter is an arbitrary pointer. The implementation of the
  4285. ** function can gain access to this pointer using [sqlite3_user_data()].)^
  4286. **
  4287. ** ^The sixth, seventh and eighth parameters, xFunc, xStep and xFinal, are
  4288. ** pointers to C-language functions that implement the SQL function or
  4289. ** aggregate. ^A scalar SQL function requires an implementation of the xFunc
  4290. ** callback only; NULL pointers must be passed as the xStep and xFinal
  4291. ** parameters. ^An aggregate SQL function requires an implementation of xStep
  4292. ** and xFinal and NULL pointer must be passed for xFunc. ^To delete an existing
  4293. ** SQL function or aggregate, pass NULL pointers for all three function
  4294. ** callbacks.
  4295. **
  4296. ** ^(If the ninth parameter to sqlite3_create_function_v2() is not NULL,
  4297. ** then it is destructor for the application data pointer.
  4298. ** The destructor is invoked when the function is deleted, either by being
  4299. ** overloaded or when the database connection closes.)^
  4300. ** ^The destructor is also invoked if the call to
  4301. ** sqlite3_create_function_v2() fails.
  4302. ** ^When the destructor callback of the tenth parameter is invoked, it
  4303. ** is passed a single argument which is a copy of the application data
  4304. ** pointer which was the fifth parameter to sqlite3_create_function_v2().
  4305. **
  4306. ** ^It is permitted to register multiple implementations of the same
  4307. ** functions with the same name but with either differing numbers of
  4308. ** arguments or differing preferred text encodings. ^SQLite will use
  4309. ** the implementation that most closely matches the way in which the
  4310. ** SQL function is used. ^A function implementation with a non-negative
  4311. ** nArg parameter is a better match than a function implementation with
  4312. ** a negative nArg. ^A function where the preferred text encoding
  4313. ** matches the database encoding is a better
  4314. ** match than a function where the encoding is different.
  4315. ** ^A function where the encoding difference is between UTF16le and UTF16be
  4316. ** is a closer match than a function where the encoding difference is
  4317. ** between UTF8 and UTF16.
  4318. **
  4319. ** ^Built-in functions may be overloaded by new application-defined functions.
  4320. **
  4321. ** ^An application-defined function is permitted to call other
  4322. ** SQLite interfaces. However, such calls must not
  4323. ** close the database connection nor finalize or reset the prepared
  4324. ** statement in which the function is running.
  4325. */
  4326. SQLITE_API int SQLITE_STDCALL sqlite3_create_function(
  4327. sqlite3 *db,
  4328. const char *zFunctionName,
  4329. int nArg,
  4330. int eTextRep,
  4331. void *pApp,
  4332. void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
  4333. void (*xStep)(sqlite3_context*,int,sqlite3_value**),
  4334. void (*xFinal)(sqlite3_context*)
  4335. );
  4336. SQLITE_API int SQLITE_STDCALL sqlite3_create_function16(
  4337. sqlite3 *db,
  4338. const void *zFunctionName,
  4339. int nArg,
  4340. int eTextRep,
  4341. void *pApp,
  4342. void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
  4343. void (*xStep)(sqlite3_context*,int,sqlite3_value**),
  4344. void (*xFinal)(sqlite3_context*)
  4345. );
  4346. SQLITE_API int SQLITE_STDCALL sqlite3_create_function_v2(
  4347. sqlite3 *db,
  4348. const char *zFunctionName,
  4349. int nArg,
  4350. int eTextRep,
  4351. void *pApp,
  4352. void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
  4353. void (*xStep)(sqlite3_context*,int,sqlite3_value**),
  4354. void (*xFinal)(sqlite3_context*),
  4355. void(*xDestroy)(void*)
  4356. );
  4357. /*
  4358. ** CAPI3REF: Text Encodings
  4359. **
  4360. ** These constant define integer codes that represent the various
  4361. ** text encodings supported by SQLite.
  4362. */
  4363. #define SQLITE_UTF8 1 /* IMP: R-37514-35566 */
  4364. #define SQLITE_UTF16LE 2 /* IMP: R-03371-37637 */
  4365. #define SQLITE_UTF16BE 3 /* IMP: R-51971-34154 */
  4366. #define SQLITE_UTF16 4 /* Use native byte order */
  4367. #define SQLITE_ANY 5 /* Deprecated */
  4368. #define SQLITE_UTF16_ALIGNED 8 /* sqlite3_create_collation only */
  4369. /*
  4370. ** CAPI3REF: Function Flags
  4371. **
  4372. ** These constants may be ORed together with the
  4373. ** [SQLITE_UTF8 | preferred text encoding] as the fourth argument
  4374. ** to [sqlite3_create_function()], [sqlite3_create_function16()], or
  4375. ** [sqlite3_create_function_v2()].
  4376. */
  4377. #define SQLITE_DETERMINISTIC 0x800
  4378. /*
  4379. ** CAPI3REF: Deprecated Functions
  4380. ** DEPRECATED
  4381. **
  4382. ** These functions are [deprecated]. In order to maintain
  4383. ** backwards compatibility with older code, these functions continue
  4384. ** to be supported. However, new applications should avoid
  4385. ** the use of these functions. To encourage programmers to avoid
  4386. ** these functions, we will not explain what they do.
  4387. */
  4388. #ifndef SQLITE_OMIT_DEPRECATED
  4389. SQLITE_API SQLITE_DEPRECATED int SQLITE_STDCALL sqlite3_aggregate_count(sqlite3_context*);
  4390. SQLITE_API SQLITE_DEPRECATED int SQLITE_STDCALL sqlite3_expired(sqlite3_stmt*);
  4391. SQLITE_API SQLITE_DEPRECATED int SQLITE_STDCALL sqlite3_transfer_bindings(sqlite3_stmt*, sqlite3_stmt*);
  4392. SQLITE_API SQLITE_DEPRECATED int SQLITE_STDCALL sqlite3_global_recover(void);
  4393. SQLITE_API SQLITE_DEPRECATED void SQLITE_STDCALL sqlite3_thread_cleanup(void);
  4394. SQLITE_API SQLITE_DEPRECATED int SQLITE_STDCALL sqlite3_memory_alarm(void(*)(void*,sqlite3_int64,int),
  4395. void*,sqlite3_int64);
  4396. #endif
  4397. /*
  4398. ** CAPI3REF: Obtaining SQL Function Parameter Values
  4399. ** METHOD: sqlite3_value
  4400. **
  4401. ** The C-language implementation of SQL functions and aggregates uses
  4402. ** this set of interface routines to access the parameter values on
  4403. ** the function or aggregate.
  4404. **
  4405. ** The xFunc (for scalar functions) or xStep (for aggregates) parameters
  4406. ** to [sqlite3_create_function()] and [sqlite3_create_function16()]
  4407. ** define callbacks that implement the SQL functions and aggregates.
  4408. ** The 3rd parameter to these callbacks is an array of pointers to
  4409. ** [protected sqlite3_value] objects. There is one [sqlite3_value] object for
  4410. ** each parameter to the SQL function. These routines are used to
  4411. ** extract values from the [sqlite3_value] objects.
  4412. **
  4413. ** These routines work only with [protected sqlite3_value] objects.
  4414. ** Any attempt to use these routines on an [unprotected sqlite3_value]
  4415. ** object results in undefined behavior.
  4416. **
  4417. ** ^These routines work just like the corresponding [column access functions]
  4418. ** except that these routines take a single [protected sqlite3_value] object
  4419. ** pointer instead of a [sqlite3_stmt*] pointer and an integer column number.
  4420. **
  4421. ** ^The sqlite3_value_text16() interface extracts a UTF-16 string
  4422. ** in the native byte-order of the host machine. ^The
  4423. ** sqlite3_value_text16be() and sqlite3_value_text16le() interfaces
  4424. ** extract UTF-16 strings as big-endian and little-endian respectively.
  4425. **
  4426. ** ^(The sqlite3_value_numeric_type() interface attempts to apply
  4427. ** numeric affinity to the value. This means that an attempt is
  4428. ** made to convert the value to an integer or floating point. If
  4429. ** such a conversion is possible without loss of information (in other
  4430. ** words, if the value is a string that looks like a number)
  4431. ** then the conversion is performed. Otherwise no conversion occurs.
  4432. ** The [SQLITE_INTEGER | datatype] after conversion is returned.)^
  4433. **
  4434. ** Please pay particular attention to the fact that the pointer returned
  4435. ** from [sqlite3_value_blob()], [sqlite3_value_text()], or
  4436. ** [sqlite3_value_text16()] can be invalidated by a subsequent call to
  4437. ** [sqlite3_value_bytes()], [sqlite3_value_bytes16()], [sqlite3_value_text()],
  4438. ** or [sqlite3_value_text16()].
  4439. **
  4440. ** These routines must be called from the same thread as
  4441. ** the SQL function that supplied the [sqlite3_value*] parameters.
  4442. */
  4443. SQLITE_API const void *SQLITE_STDCALL sqlite3_value_blob(sqlite3_value*);
  4444. SQLITE_API int SQLITE_STDCALL sqlite3_value_bytes(sqlite3_value*);
  4445. SQLITE_API int SQLITE_STDCALL sqlite3_value_bytes16(sqlite3_value*);
  4446. SQLITE_API double SQLITE_STDCALL sqlite3_value_double(sqlite3_value*);
  4447. SQLITE_API int SQLITE_STDCALL sqlite3_value_int(sqlite3_value*);
  4448. SQLITE_API sqlite3_int64 SQLITE_STDCALL sqlite3_value_int64(sqlite3_value*);
  4449. SQLITE_API const unsigned char *SQLITE_STDCALL sqlite3_value_text(sqlite3_value*);
  4450. SQLITE_API const void *SQLITE_STDCALL sqlite3_value_text16(sqlite3_value*);
  4451. SQLITE_API const void *SQLITE_STDCALL sqlite3_value_text16le(sqlite3_value*);
  4452. SQLITE_API const void *SQLITE_STDCALL sqlite3_value_text16be(sqlite3_value*);
  4453. SQLITE_API int SQLITE_STDCALL sqlite3_value_type(sqlite3_value*);
  4454. SQLITE_API int SQLITE_STDCALL sqlite3_value_numeric_type(sqlite3_value*);
  4455. /*
  4456. ** CAPI3REF: Obtain Aggregate Function Context
  4457. ** METHOD: sqlite3_context
  4458. **
  4459. ** Implementations of aggregate SQL functions use this
  4460. ** routine to allocate memory for storing their state.
  4461. **
  4462. ** ^The first time the sqlite3_aggregate_context(C,N) routine is called
  4463. ** for a particular aggregate function, SQLite
  4464. ** allocates N of memory, zeroes out that memory, and returns a pointer
  4465. ** to the new memory. ^On second and subsequent calls to
  4466. ** sqlite3_aggregate_context() for the same aggregate function instance,
  4467. ** the same buffer is returned. Sqlite3_aggregate_context() is normally
  4468. ** called once for each invocation of the xStep callback and then one
  4469. ** last time when the xFinal callback is invoked. ^(When no rows match
  4470. ** an aggregate query, the xStep() callback of the aggregate function
  4471. ** implementation is never called and xFinal() is called exactly once.
  4472. ** In those cases, sqlite3_aggregate_context() might be called for the
  4473. ** first time from within xFinal().)^
  4474. **
  4475. ** ^The sqlite3_aggregate_context(C,N) routine returns a NULL pointer
  4476. ** when first called if N is less than or equal to zero or if a memory
  4477. ** allocate error occurs.
  4478. **
  4479. ** ^(The amount of space allocated by sqlite3_aggregate_context(C,N) is
  4480. ** determined by the N parameter on first successful call. Changing the
  4481. ** value of N in subsequent call to sqlite3_aggregate_context() within
  4482. ** the same aggregate function instance will not resize the memory
  4483. ** allocation.)^ Within the xFinal callback, it is customary to set
  4484. ** N=0 in calls to sqlite3_aggregate_context(C,N) so that no
  4485. ** pointless memory allocations occur.
  4486. **
  4487. ** ^SQLite automatically frees the memory allocated by
  4488. ** sqlite3_aggregate_context() when the aggregate query concludes.
  4489. **
  4490. ** The first parameter must be a copy of the
  4491. ** [sqlite3_context | SQL function context] that is the first parameter
  4492. ** to the xStep or xFinal callback routine that implements the aggregate
  4493. ** function.
  4494. **
  4495. ** This routine must be called from the same thread in which
  4496. ** the aggregate SQL function is running.
  4497. */
  4498. SQLITE_API void *SQLITE_STDCALL sqlite3_aggregate_context(sqlite3_context*, int nBytes);
  4499. /*
  4500. ** CAPI3REF: User Data For Functions
  4501. ** METHOD: sqlite3_context
  4502. **
  4503. ** ^The sqlite3_user_data() interface returns a copy of
  4504. ** the pointer that was the pUserData parameter (the 5th parameter)
  4505. ** of the [sqlite3_create_function()]
  4506. ** and [sqlite3_create_function16()] routines that originally
  4507. ** registered the application defined function.
  4508. **
  4509. ** This routine must be called from the same thread in which
  4510. ** the application-defined function is running.
  4511. */
  4512. SQLITE_API void *SQLITE_STDCALL sqlite3_user_data(sqlite3_context*);
  4513. /*
  4514. ** CAPI3REF: Database Connection For Functions
  4515. ** METHOD: sqlite3_context
  4516. **
  4517. ** ^The sqlite3_context_db_handle() interface returns a copy of
  4518. ** the pointer to the [database connection] (the 1st parameter)
  4519. ** of the [sqlite3_create_function()]
  4520. ** and [sqlite3_create_function16()] routines that originally
  4521. ** registered the application defined function.
  4522. */
  4523. SQLITE_API sqlite3 *SQLITE_STDCALL sqlite3_context_db_handle(sqlite3_context*);
  4524. /*
  4525. ** CAPI3REF: Function Auxiliary Data
  4526. ** METHOD: sqlite3_context
  4527. **
  4528. ** These functions may be used by (non-aggregate) SQL functions to
  4529. ** associate metadata with argument values. If the same value is passed to
  4530. ** multiple invocations of the same SQL function during query execution, under
  4531. ** some circumstances the associated metadata may be preserved. An example
  4532. ** of where this might be useful is in a regular-expression matching
  4533. ** function. The compiled version of the regular expression can be stored as
  4534. ** metadata associated with the pattern string.
  4535. ** Then as long as the pattern string remains the same,
  4536. ** the compiled regular expression can be reused on multiple
  4537. ** invocations of the same function.
  4538. **
  4539. ** ^The sqlite3_get_auxdata() interface returns a pointer to the metadata
  4540. ** associated by the sqlite3_set_auxdata() function with the Nth argument
  4541. ** value to the application-defined function. ^If there is no metadata
  4542. ** associated with the function argument, this sqlite3_get_auxdata() interface
  4543. ** returns a NULL pointer.
  4544. **
  4545. ** ^The sqlite3_set_auxdata(C,N,P,X) interface saves P as metadata for the N-th
  4546. ** argument of the application-defined function. ^Subsequent
  4547. ** calls to sqlite3_get_auxdata(C,N) return P from the most recent
  4548. ** sqlite3_set_auxdata(C,N,P,X) call if the metadata is still valid or
  4549. ** NULL if the metadata has been discarded.
  4550. ** ^After each call to sqlite3_set_auxdata(C,N,P,X) where X is not NULL,
  4551. ** SQLite will invoke the destructor function X with parameter P exactly
  4552. ** once, when the metadata is discarded.
  4553. ** SQLite is free to discard the metadata at any time, including: <ul>
  4554. ** <li> when the corresponding function parameter changes, or
  4555. ** <li> when [sqlite3_reset()] or [sqlite3_finalize()] is called for the
  4556. ** SQL statement, or
  4557. ** <li> when sqlite3_set_auxdata() is invoked again on the same parameter, or
  4558. ** <li> during the original sqlite3_set_auxdata() call when a memory
  4559. ** allocation error occurs. </ul>)^
  4560. **
  4561. ** Note the last bullet in particular. The destructor X in
  4562. ** sqlite3_set_auxdata(C,N,P,X) might be called immediately, before the
  4563. ** sqlite3_set_auxdata() interface even returns. Hence sqlite3_set_auxdata()
  4564. ** should be called near the end of the function implementation and the
  4565. ** function implementation should not make any use of P after
  4566. ** sqlite3_set_auxdata() has been called.
  4567. **
  4568. ** ^(In practice, metadata is preserved between function calls for
  4569. ** function parameters that are compile-time constants, including literal
  4570. ** values and [parameters] and expressions composed from the same.)^
  4571. **
  4572. ** These routines must be called from the same thread in which
  4573. ** the SQL function is running.
  4574. */
  4575. SQLITE_API void *SQLITE_STDCALL sqlite3_get_auxdata(sqlite3_context*, int N);
  4576. SQLITE_API void SQLITE_STDCALL sqlite3_set_auxdata(sqlite3_context*, int N, void*, void (*)(void*));
  4577. /*
  4578. ** CAPI3REF: Constants Defining Special Destructor Behavior
  4579. **
  4580. ** These are special values for the destructor that is passed in as the
  4581. ** final argument to routines like [sqlite3_result_blob()]. ^If the destructor
  4582. ** argument is SQLITE_STATIC, it means that the content pointer is constant
  4583. ** and will never change. It does not need to be destroyed. ^The
  4584. ** SQLITE_TRANSIENT value means that the content will likely change in
  4585. ** the near future and that SQLite should make its own private copy of
  4586. ** the content before returning.
  4587. **
  4588. ** The typedef is necessary to work around problems in certain
  4589. ** C++ compilers.
  4590. */
  4591. typedef void (*sqlite3_destructor_type)(void*);
  4592. #define SQLITE_STATIC ((sqlite3_destructor_type)0)
  4593. #define SQLITE_TRANSIENT ((sqlite3_destructor_type)-1)
  4594. /*
  4595. ** CAPI3REF: Setting The Result Of An SQL Function
  4596. ** METHOD: sqlite3_context
  4597. **
  4598. ** These routines are used by the xFunc or xFinal callbacks that
  4599. ** implement SQL functions and aggregates. See
  4600. ** [sqlite3_create_function()] and [sqlite3_create_function16()]
  4601. ** for additional information.
  4602. **
  4603. ** These functions work very much like the [parameter binding] family of
  4604. ** functions used to bind values to host parameters in prepared statements.
  4605. ** Refer to the [SQL parameter] documentation for additional information.
  4606. **
  4607. ** ^The sqlite3_result_blob() interface sets the result from
  4608. ** an application-defined function to be the BLOB whose content is pointed
  4609. ** to by the second parameter and which is N bytes long where N is the
  4610. ** third parameter.
  4611. **
  4612. ** ^The sqlite3_result_zeroblob() interfaces set the result of
  4613. ** the application-defined function to be a BLOB containing all zero
  4614. ** bytes and N bytes in size, where N is the value of the 2nd parameter.
  4615. **
  4616. ** ^The sqlite3_result_double() interface sets the result from
  4617. ** an application-defined function to be a floating point value specified
  4618. ** by its 2nd argument.
  4619. **
  4620. ** ^The sqlite3_result_error() and sqlite3_result_error16() functions
  4621. ** cause the implemented SQL function to throw an exception.
  4622. ** ^SQLite uses the string pointed to by the
  4623. ** 2nd parameter of sqlite3_result_error() or sqlite3_result_error16()
  4624. ** as the text of an error message. ^SQLite interprets the error
  4625. ** message string from sqlite3_result_error() as UTF-8. ^SQLite
  4626. ** interprets the string from sqlite3_result_error16() as UTF-16 in native
  4627. ** byte order. ^If the third parameter to sqlite3_result_error()
  4628. ** or sqlite3_result_error16() is negative then SQLite takes as the error
  4629. ** message all text up through the first zero character.
  4630. ** ^If the third parameter to sqlite3_result_error() or
  4631. ** sqlite3_result_error16() is non-negative then SQLite takes that many
  4632. ** bytes (not characters) from the 2nd parameter as the error message.
  4633. ** ^The sqlite3_result_error() and sqlite3_result_error16()
  4634. ** routines make a private copy of the error message text before
  4635. ** they return. Hence, the calling function can deallocate or
  4636. ** modify the text after they return without harm.
  4637. ** ^The sqlite3_result_error_code() function changes the error code
  4638. ** returned by SQLite as a result of an error in a function. ^By default,
  4639. ** the error code is SQLITE_ERROR. ^A subsequent call to sqlite3_result_error()
  4640. ** or sqlite3_result_error16() resets the error code to SQLITE_ERROR.
  4641. **
  4642. ** ^The sqlite3_result_error_toobig() interface causes SQLite to throw an
  4643. ** error indicating that a string or BLOB is too long to represent.
  4644. **
  4645. ** ^The sqlite3_result_error_nomem() interface causes SQLite to throw an
  4646. ** error indicating that a memory allocation failed.
  4647. **
  4648. ** ^The sqlite3_result_int() interface sets the return value
  4649. ** of the application-defined function to be the 32-bit signed integer
  4650. ** value given in the 2nd argument.
  4651. ** ^The sqlite3_result_int64() interface sets the return value
  4652. ** of the application-defined function to be the 64-bit signed integer
  4653. ** value given in the 2nd argument.
  4654. **
  4655. ** ^The sqlite3_result_null() interface sets the return value
  4656. ** of the application-defined function to be NULL.
  4657. **
  4658. ** ^The sqlite3_result_text(), sqlite3_result_text16(),
  4659. ** sqlite3_result_text16le(), and sqlite3_result_text16be() interfaces
  4660. ** set the return value of the application-defined function to be
  4661. ** a text string which is represented as UTF-8, UTF-16 native byte order,
  4662. ** UTF-16 little endian, or UTF-16 big endian, respectively.
  4663. ** ^The sqlite3_result_text64() interface sets the return value of an
  4664. ** application-defined function to be a text string in an encoding
  4665. ** specified by the fifth (and last) parameter, which must be one
  4666. ** of [SQLITE_UTF8], [SQLITE_UTF16], [SQLITE_UTF16BE], or [SQLITE_UTF16LE].
  4667. ** ^SQLite takes the text result from the application from
  4668. ** the 2nd parameter of the sqlite3_result_text* interfaces.
  4669. ** ^If the 3rd parameter to the sqlite3_result_text* interfaces
  4670. ** is negative, then SQLite takes result text from the 2nd parameter
  4671. ** through the first zero character.
  4672. ** ^If the 3rd parameter to the sqlite3_result_text* interfaces
  4673. ** is non-negative, then as many bytes (not characters) of the text
  4674. ** pointed to by the 2nd parameter are taken as the application-defined
  4675. ** function result. If the 3rd parameter is non-negative, then it
  4676. ** must be the byte offset into the string where the NUL terminator would
  4677. ** appear if the string where NUL terminated. If any NUL characters occur
  4678. ** in the string at a byte offset that is less than the value of the 3rd
  4679. ** parameter, then the resulting string will contain embedded NULs and the
  4680. ** result of expressions operating on strings with embedded NULs is undefined.
  4681. ** ^If the 4th parameter to the sqlite3_result_text* interfaces
  4682. ** or sqlite3_result_blob is a non-NULL pointer, then SQLite calls that
  4683. ** function as the destructor on the text or BLOB result when it has
  4684. ** finished using that result.
  4685. ** ^If the 4th parameter to the sqlite3_result_text* interfaces or to
  4686. ** sqlite3_result_blob is the special constant SQLITE_STATIC, then SQLite
  4687. ** assumes that the text or BLOB result is in constant space and does not
  4688. ** copy the content of the parameter nor call a destructor on the content
  4689. ** when it has finished using that result.
  4690. ** ^If the 4th parameter to the sqlite3_result_text* interfaces
  4691. ** or sqlite3_result_blob is the special constant SQLITE_TRANSIENT
  4692. ** then SQLite makes a copy of the result into space obtained from
  4693. ** from [sqlite3_malloc()] before it returns.
  4694. **
  4695. ** ^The sqlite3_result_value() interface sets the result of
  4696. ** the application-defined function to be a copy the
  4697. ** [unprotected sqlite3_value] object specified by the 2nd parameter. ^The
  4698. ** sqlite3_result_value() interface makes a copy of the [sqlite3_value]
  4699. ** so that the [sqlite3_value] specified in the parameter may change or
  4700. ** be deallocated after sqlite3_result_value() returns without harm.
  4701. ** ^A [protected sqlite3_value] object may always be used where an
  4702. ** [unprotected sqlite3_value] object is required, so either
  4703. ** kind of [sqlite3_value] object can be used with this interface.
  4704. **
  4705. ** If these routines are called from within the different thread
  4706. ** than the one containing the application-defined function that received
  4707. ** the [sqlite3_context] pointer, the results are undefined.
  4708. */
  4709. SQLITE_API void SQLITE_STDCALL sqlite3_result_blob(sqlite3_context*, const void*, int, void(*)(void*));
  4710. SQLITE_API void SQLITE_STDCALL sqlite3_result_blob64(sqlite3_context*,const void*,
  4711. sqlite3_uint64,void(*)(void*));
  4712. SQLITE_API void SQLITE_STDCALL sqlite3_result_double(sqlite3_context*, double);
  4713. SQLITE_API void SQLITE_STDCALL sqlite3_result_error(sqlite3_context*, const char*, int);
  4714. SQLITE_API void SQLITE_STDCALL sqlite3_result_error16(sqlite3_context*, const void*, int);
  4715. SQLITE_API void SQLITE_STDCALL sqlite3_result_error_toobig(sqlite3_context*);
  4716. SQLITE_API void SQLITE_STDCALL sqlite3_result_error_nomem(sqlite3_context*);
  4717. SQLITE_API void SQLITE_STDCALL sqlite3_result_error_code(sqlite3_context*, int);
  4718. SQLITE_API void SQLITE_STDCALL sqlite3_result_int(sqlite3_context*, int);
  4719. SQLITE_API void SQLITE_STDCALL sqlite3_result_int64(sqlite3_context*, sqlite3_int64);
  4720. SQLITE_API void SQLITE_STDCALL sqlite3_result_null(sqlite3_context*);
  4721. SQLITE_API void SQLITE_STDCALL sqlite3_result_text(sqlite3_context*, const char*, int, void(*)(void*));
  4722. SQLITE_API void SQLITE_STDCALL sqlite3_result_text64(sqlite3_context*, const char*,sqlite3_uint64,
  4723. void(*)(void*), unsigned char encoding);
  4724. SQLITE_API void SQLITE_STDCALL sqlite3_result_text16(sqlite3_context*, const void*, int, void(*)(void*));
  4725. SQLITE_API void SQLITE_STDCALL sqlite3_result_text16le(sqlite3_context*, const void*, int,void(*)(void*));
  4726. SQLITE_API void SQLITE_STDCALL sqlite3_result_text16be(sqlite3_context*, const void*, int,void(*)(void*));
  4727. SQLITE_API void SQLITE_STDCALL sqlite3_result_value(sqlite3_context*, sqlite3_value*);
  4728. SQLITE_API void SQLITE_STDCALL sqlite3_result_zeroblob(sqlite3_context*, int n);
  4729. /*
  4730. ** CAPI3REF: Define New Collating Sequences
  4731. ** METHOD: sqlite3
  4732. **
  4733. ** ^These functions add, remove, or modify a [collation] associated
  4734. ** with the [database connection] specified as the first argument.
  4735. **
  4736. ** ^The name of the collation is a UTF-8 string
  4737. ** for sqlite3_create_collation() and sqlite3_create_collation_v2()
  4738. ** and a UTF-16 string in native byte order for sqlite3_create_collation16().
  4739. ** ^Collation names that compare equal according to [sqlite3_strnicmp()] are
  4740. ** considered to be the same name.
  4741. **
  4742. ** ^(The third argument (eTextRep) must be one of the constants:
  4743. ** <ul>
  4744. ** <li> [SQLITE_UTF8],
  4745. ** <li> [SQLITE_UTF16LE],
  4746. ** <li> [SQLITE_UTF16BE],
  4747. ** <li> [SQLITE_UTF16], or
  4748. ** <li> [SQLITE_UTF16_ALIGNED].
  4749. ** </ul>)^
  4750. ** ^The eTextRep argument determines the encoding of strings passed
  4751. ** to the collating function callback, xCallback.
  4752. ** ^The [SQLITE_UTF16] and [SQLITE_UTF16_ALIGNED] values for eTextRep
  4753. ** force strings to be UTF16 with native byte order.
  4754. ** ^The [SQLITE_UTF16_ALIGNED] value for eTextRep forces strings to begin
  4755. ** on an even byte address.
  4756. **
  4757. ** ^The fourth argument, pArg, is an application data pointer that is passed
  4758. ** through as the first argument to the collating function callback.
  4759. **
  4760. ** ^The fifth argument, xCallback, is a pointer to the collating function.
  4761. ** ^Multiple collating functions can be registered using the same name but
  4762. ** with different eTextRep parameters and SQLite will use whichever
  4763. ** function requires the least amount of data transformation.
  4764. ** ^If the xCallback argument is NULL then the collating function is
  4765. ** deleted. ^When all collating functions having the same name are deleted,
  4766. ** that collation is no longer usable.
  4767. **
  4768. ** ^The collating function callback is invoked with a copy of the pArg
  4769. ** application data pointer and with two strings in the encoding specified
  4770. ** by the eTextRep argument. The collating function must return an
  4771. ** integer that is negative, zero, or positive
  4772. ** if the first string is less than, equal to, or greater than the second,
  4773. ** respectively. A collating function must always return the same answer
  4774. ** given the same inputs. If two or more collating functions are registered
  4775. ** to the same collation name (using different eTextRep values) then all
  4776. ** must give an equivalent answer when invoked with equivalent strings.
  4777. ** The collating function must obey the following properties for all
  4778. ** strings A, B, and C:
  4779. **
  4780. ** <ol>
  4781. ** <li> If A==B then B==A.
  4782. ** <li> If A==B and B==C then A==C.
  4783. ** <li> If A&lt;B THEN B&gt;A.
  4784. ** <li> If A&lt;B and B&lt;C then A&lt;C.
  4785. ** </ol>
  4786. **
  4787. ** If a collating function fails any of the above constraints and that
  4788. ** collating function is registered and used, then the behavior of SQLite
  4789. ** is undefined.
  4790. **
  4791. ** ^The sqlite3_create_collation_v2() works like sqlite3_create_collation()
  4792. ** with the addition that the xDestroy callback is invoked on pArg when
  4793. ** the collating function is deleted.
  4794. ** ^Collating functions are deleted when they are overridden by later
  4795. ** calls to the collation creation functions or when the
  4796. ** [database connection] is closed using [sqlite3_close()].
  4797. **
  4798. ** ^The xDestroy callback is <u>not</u> called if the
  4799. ** sqlite3_create_collation_v2() function fails. Applications that invoke
  4800. ** sqlite3_create_collation_v2() with a non-NULL xDestroy argument should
  4801. ** check the return code and dispose of the application data pointer
  4802. ** themselves rather than expecting SQLite to deal with it for them.
  4803. ** This is different from every other SQLite interface. The inconsistency
  4804. ** is unfortunate but cannot be changed without breaking backwards
  4805. ** compatibility.
  4806. **
  4807. ** See also: [sqlite3_collation_needed()] and [sqlite3_collation_needed16()].
  4808. */
  4809. SQLITE_API int SQLITE_STDCALL sqlite3_create_collation(
  4810. sqlite3*,
  4811. const char *zName,
  4812. int eTextRep,
  4813. void *pArg,
  4814. int(*xCompare)(void*,int,const void*,int,const void*)
  4815. );
  4816. SQLITE_API int SQLITE_STDCALL sqlite3_create_collation_v2(
  4817. sqlite3*,
  4818. const char *zName,
  4819. int eTextRep,
  4820. void *pArg,
  4821. int(*xCompare)(void*,int,const void*,int,const void*),
  4822. void(*xDestroy)(void*)
  4823. );
  4824. SQLITE_API int SQLITE_STDCALL sqlite3_create_collation16(
  4825. sqlite3*,
  4826. const void *zName,
  4827. int eTextRep,
  4828. void *pArg,
  4829. int(*xCompare)(void*,int,const void*,int,const void*)
  4830. );
  4831. /*
  4832. ** CAPI3REF: Collation Needed Callbacks
  4833. ** METHOD: sqlite3
  4834. **
  4835. ** ^To avoid having to register all collation sequences before a database
  4836. ** can be used, a single callback function may be registered with the
  4837. ** [database connection] to be invoked whenever an undefined collation
  4838. ** sequence is required.
  4839. **
  4840. ** ^If the function is registered using the sqlite3_collation_needed() API,
  4841. ** then it is passed the names of undefined collation sequences as strings
  4842. ** encoded in UTF-8. ^If sqlite3_collation_needed16() is used,
  4843. ** the names are passed as UTF-16 in machine native byte order.
  4844. ** ^A call to either function replaces the existing collation-needed callback.
  4845. **
  4846. ** ^(When the callback is invoked, the first argument passed is a copy
  4847. ** of the second argument to sqlite3_collation_needed() or
  4848. ** sqlite3_collation_needed16(). The second argument is the database
  4849. ** connection. The third argument is one of [SQLITE_UTF8], [SQLITE_UTF16BE],
  4850. ** or [SQLITE_UTF16LE], indicating the most desirable form of the collation
  4851. ** sequence function required. The fourth parameter is the name of the
  4852. ** required collation sequence.)^
  4853. **
  4854. ** The callback function should register the desired collation using
  4855. ** [sqlite3_create_collation()], [sqlite3_create_collation16()], or
  4856. ** [sqlite3_create_collation_v2()].
  4857. */
  4858. SQLITE_API int SQLITE_STDCALL sqlite3_collation_needed(
  4859. sqlite3*,
  4860. void*,
  4861. void(*)(void*,sqlite3*,int eTextRep,const char*)
  4862. );
  4863. SQLITE_API int SQLITE_STDCALL sqlite3_collation_needed16(
  4864. sqlite3*,
  4865. void*,
  4866. void(*)(void*,sqlite3*,int eTextRep,const void*)
  4867. );
  4868. #ifdef SQLITE_HAS_CODEC
  4869. /*
  4870. ** Specify the key for an encrypted database. This routine should be
  4871. ** called right after sqlite3_open().
  4872. **
  4873. ** The code to implement this API is not available in the public release
  4874. ** of SQLite.
  4875. */
  4876. SQLITE_API int SQLITE_STDCALL sqlite3_key(
  4877. sqlite3 *db, /* Database to be rekeyed */
  4878. const void *pKey, int nKey /* The key */
  4879. );
  4880. SQLITE_API int SQLITE_STDCALL sqlite3_key_v2(
  4881. sqlite3 *db, /* Database to be rekeyed */
  4882. const char *zDbName, /* Name of the database */
  4883. const void *pKey, int nKey /* The key */
  4884. );
  4885. /*
  4886. ** Change the key on an open database. If the current database is not
  4887. ** encrypted, this routine will encrypt it. If pNew==0 or nNew==0, the
  4888. ** database is decrypted.
  4889. **
  4890. ** The code to implement this API is not available in the public release
  4891. ** of SQLite.
  4892. */
  4893. SQLITE_API int SQLITE_STDCALL sqlite3_rekey(
  4894. sqlite3 *db, /* Database to be rekeyed */
  4895. const void *pKey, int nKey /* The new key */
  4896. );
  4897. SQLITE_API int SQLITE_STDCALL sqlite3_rekey_v2(
  4898. sqlite3 *db, /* Database to be rekeyed */
  4899. const char *zDbName, /* Name of the database */
  4900. const void *pKey, int nKey /* The new key */
  4901. );
  4902. /*
  4903. ** Specify the activation key for a SEE database. Unless
  4904. ** activated, none of the SEE routines will work.
  4905. */
  4906. SQLITE_API void SQLITE_STDCALL sqlite3_activate_see(
  4907. const char *zPassPhrase /* Activation phrase */
  4908. );
  4909. #endif
  4910. #ifdef SQLITE_ENABLE_CEROD
  4911. /*
  4912. ** Specify the activation key for a CEROD database. Unless
  4913. ** activated, none of the CEROD routines will work.
  4914. */
  4915. SQLITE_API void SQLITE_STDCALL sqlite3_activate_cerod(
  4916. const char *zPassPhrase /* Activation phrase */
  4917. );
  4918. #endif
  4919. /*
  4920. ** CAPI3REF: Suspend Execution For A Short Time
  4921. **
  4922. ** The sqlite3_sleep() function causes the current thread to suspend execution
  4923. ** for at least a number of milliseconds specified in its parameter.
  4924. **
  4925. ** If the operating system does not support sleep requests with
  4926. ** millisecond time resolution, then the time will be rounded up to
  4927. ** the nearest second. The number of milliseconds of sleep actually
  4928. ** requested from the operating system is returned.
  4929. **
  4930. ** ^SQLite implements this interface by calling the xSleep()
  4931. ** method of the default [sqlite3_vfs] object. If the xSleep() method
  4932. ** of the default VFS is not implemented correctly, or not implemented at
  4933. ** all, then the behavior of sqlite3_sleep() may deviate from the description
  4934. ** in the previous paragraphs.
  4935. */
  4936. SQLITE_API int SQLITE_STDCALL sqlite3_sleep(int);
  4937. /*
  4938. ** CAPI3REF: Name Of The Folder Holding Temporary Files
  4939. **
  4940. ** ^(If this global variable is made to point to a string which is
  4941. ** the name of a folder (a.k.a. directory), then all temporary files
  4942. ** created by SQLite when using a built-in [sqlite3_vfs | VFS]
  4943. ** will be placed in that directory.)^ ^If this variable
  4944. ** is a NULL pointer, then SQLite performs a search for an appropriate
  4945. ** temporary file directory.
  4946. **
  4947. ** Applications are strongly discouraged from using this global variable.
  4948. ** It is required to set a temporary folder on Windows Runtime (WinRT).
  4949. ** But for all other platforms, it is highly recommended that applications
  4950. ** neither read nor write this variable. This global variable is a relic
  4951. ** that exists for backwards compatibility of legacy applications and should
  4952. ** be avoided in new projects.
  4953. **
  4954. ** It is not safe to read or modify this variable in more than one
  4955. ** thread at a time. It is not safe to read or modify this variable
  4956. ** if a [database connection] is being used at the same time in a separate
  4957. ** thread.
  4958. ** It is intended that this variable be set once
  4959. ** as part of process initialization and before any SQLite interface
  4960. ** routines have been called and that this variable remain unchanged
  4961. ** thereafter.
  4962. **
  4963. ** ^The [temp_store_directory pragma] may modify this variable and cause
  4964. ** it to point to memory obtained from [sqlite3_malloc]. ^Furthermore,
  4965. ** the [temp_store_directory pragma] always assumes that any string
  4966. ** that this variable points to is held in memory obtained from
  4967. ** [sqlite3_malloc] and the pragma may attempt to free that memory
  4968. ** using [sqlite3_free].
  4969. ** Hence, if this variable is modified directly, either it should be
  4970. ** made NULL or made to point to memory obtained from [sqlite3_malloc]
  4971. ** or else the use of the [temp_store_directory pragma] should be avoided.
  4972. ** Except when requested by the [temp_store_directory pragma], SQLite
  4973. ** does not free the memory that sqlite3_temp_directory points to. If
  4974. ** the application wants that memory to be freed, it must do
  4975. ** so itself, taking care to only do so after all [database connection]
  4976. ** objects have been destroyed.
  4977. **
  4978. ** <b>Note to Windows Runtime users:</b> The temporary directory must be set
  4979. ** prior to calling [sqlite3_open] or [sqlite3_open_v2]. Otherwise, various
  4980. ** features that require the use of temporary files may fail. Here is an
  4981. ** example of how to do this using C++ with the Windows Runtime:
  4982. **
  4983. ** <blockquote><pre>
  4984. ** LPCWSTR zPath = Windows::Storage::ApplicationData::Current->
  4985. ** &nbsp; TemporaryFolder->Path->Data();
  4986. ** char zPathBuf&#91;MAX_PATH + 1&#93;;
  4987. ** memset(zPathBuf, 0, sizeof(zPathBuf));
  4988. ** WideCharToMultiByte(CP_UTF8, 0, zPath, -1, zPathBuf, sizeof(zPathBuf),
  4989. ** &nbsp; NULL, NULL);
  4990. ** sqlite3_temp_directory = sqlite3_mprintf("%s", zPathBuf);
  4991. ** </pre></blockquote>
  4992. */
  4993. SQLITE_API char *sqlite3_temp_directory;
  4994. /*
  4995. ** CAPI3REF: Name Of The Folder Holding Database Files
  4996. **
  4997. ** ^(If this global variable is made to point to a string which is
  4998. ** the name of a folder (a.k.a. directory), then all database files
  4999. ** specified with a relative pathname and created or accessed by
  5000. ** SQLite when using a built-in windows [sqlite3_vfs | VFS] will be assumed
  5001. ** to be relative to that directory.)^ ^If this variable is a NULL
  5002. ** pointer, then SQLite assumes that all database files specified
  5003. ** with a relative pathname are relative to the current directory
  5004. ** for the process. Only the windows VFS makes use of this global
  5005. ** variable; it is ignored by the unix VFS.
  5006. **
  5007. ** Changing the value of this variable while a database connection is
  5008. ** open can result in a corrupt database.
  5009. **
  5010. ** It is not safe to read or modify this variable in more than one
  5011. ** thread at a time. It is not safe to read or modify this variable
  5012. ** if a [database connection] is being used at the same time in a separate
  5013. ** thread.
  5014. ** It is intended that this variable be set once
  5015. ** as part of process initialization and before any SQLite interface
  5016. ** routines have been called and that this variable remain unchanged
  5017. ** thereafter.
  5018. **
  5019. ** ^The [data_store_directory pragma] may modify this variable and cause
  5020. ** it to point to memory obtained from [sqlite3_malloc]. ^Furthermore,
  5021. ** the [data_store_directory pragma] always assumes that any string
  5022. ** that this variable points to is held in memory obtained from
  5023. ** [sqlite3_malloc] and the pragma may attempt to free that memory
  5024. ** using [sqlite3_free].
  5025. ** Hence, if this variable is modified directly, either it should be
  5026. ** made NULL or made to point to memory obtained from [sqlite3_malloc]
  5027. ** or else the use of the [data_store_directory pragma] should be avoided.
  5028. */
  5029. SQLITE_API char *sqlite3_data_directory;
  5030. /*
  5031. ** CAPI3REF: Test For Auto-Commit Mode
  5032. ** KEYWORDS: {autocommit mode}
  5033. ** METHOD: sqlite3
  5034. **
  5035. ** ^The sqlite3_get_autocommit() interface returns non-zero or
  5036. ** zero if the given database connection is or is not in autocommit mode,
  5037. ** respectively. ^Autocommit mode is on by default.
  5038. ** ^Autocommit mode is disabled by a [BEGIN] statement.
  5039. ** ^Autocommit mode is re-enabled by a [COMMIT] or [ROLLBACK].
  5040. **
  5041. ** If certain kinds of errors occur on a statement within a multi-statement
  5042. ** transaction (errors including [SQLITE_FULL], [SQLITE_IOERR],
  5043. ** [SQLITE_NOMEM], [SQLITE_BUSY], and [SQLITE_INTERRUPT]) then the
  5044. ** transaction might be rolled back automatically. The only way to
  5045. ** find out whether SQLite automatically rolled back the transaction after
  5046. ** an error is to use this function.
  5047. **
  5048. ** If another thread changes the autocommit status of the database
  5049. ** connection while this routine is running, then the return value
  5050. ** is undefined.
  5051. */
  5052. SQLITE_API int SQLITE_STDCALL sqlite3_get_autocommit(sqlite3*);
  5053. /*
  5054. ** CAPI3REF: Find The Database Handle Of A Prepared Statement
  5055. ** METHOD: sqlite3_stmt
  5056. **
  5057. ** ^The sqlite3_db_handle interface returns the [database connection] handle
  5058. ** to which a [prepared statement] belongs. ^The [database connection]
  5059. ** returned by sqlite3_db_handle is the same [database connection]
  5060. ** that was the first argument
  5061. ** to the [sqlite3_prepare_v2()] call (or its variants) that was used to
  5062. ** create the statement in the first place.
  5063. */
  5064. SQLITE_API sqlite3 *SQLITE_STDCALL sqlite3_db_handle(sqlite3_stmt*);
  5065. /*
  5066. ** CAPI3REF: Return The Filename For A Database Connection
  5067. ** METHOD: sqlite3
  5068. **
  5069. ** ^The sqlite3_db_filename(D,N) interface returns a pointer to a filename
  5070. ** associated with database N of connection D. ^The main database file
  5071. ** has the name "main". If there is no attached database N on the database
  5072. ** connection D, or if database N is a temporary or in-memory database, then
  5073. ** a NULL pointer is returned.
  5074. **
  5075. ** ^The filename returned by this function is the output of the
  5076. ** xFullPathname method of the [VFS]. ^In other words, the filename
  5077. ** will be an absolute pathname, even if the filename used
  5078. ** to open the database originally was a URI or relative pathname.
  5079. */
  5080. SQLITE_API const char *SQLITE_STDCALL sqlite3_db_filename(sqlite3 *db, const char *zDbName);
  5081. /*
  5082. ** CAPI3REF: Determine if a database is read-only
  5083. ** METHOD: sqlite3
  5084. **
  5085. ** ^The sqlite3_db_readonly(D,N) interface returns 1 if the database N
  5086. ** of connection D is read-only, 0 if it is read/write, or -1 if N is not
  5087. ** the name of a database on connection D.
  5088. */
  5089. SQLITE_API int SQLITE_STDCALL sqlite3_db_readonly(sqlite3 *db, const char *zDbName);
  5090. /*
  5091. ** CAPI3REF: Find the next prepared statement
  5092. ** METHOD: sqlite3
  5093. **
  5094. ** ^This interface returns a pointer to the next [prepared statement] after
  5095. ** pStmt associated with the [database connection] pDb. ^If pStmt is NULL
  5096. ** then this interface returns a pointer to the first prepared statement
  5097. ** associated with the database connection pDb. ^If no prepared statement
  5098. ** satisfies the conditions of this routine, it returns NULL.
  5099. **
  5100. ** The [database connection] pointer D in a call to
  5101. ** [sqlite3_next_stmt(D,S)] must refer to an open database
  5102. ** connection and in particular must not be a NULL pointer.
  5103. */
  5104. SQLITE_API sqlite3_stmt *SQLITE_STDCALL sqlite3_next_stmt(sqlite3 *pDb, sqlite3_stmt *pStmt);
  5105. /*
  5106. ** CAPI3REF: Commit And Rollback Notification Callbacks
  5107. ** METHOD: sqlite3
  5108. **
  5109. ** ^The sqlite3_commit_hook() interface registers a callback
  5110. ** function to be invoked whenever a transaction is [COMMIT | committed].
  5111. ** ^Any callback set by a previous call to sqlite3_commit_hook()
  5112. ** for the same database connection is overridden.
  5113. ** ^The sqlite3_rollback_hook() interface registers a callback
  5114. ** function to be invoked whenever a transaction is [ROLLBACK | rolled back].
  5115. ** ^Any callback set by a previous call to sqlite3_rollback_hook()
  5116. ** for the same database connection is overridden.
  5117. ** ^The pArg argument is passed through to the callback.
  5118. ** ^If the callback on a commit hook function returns non-zero,
  5119. ** then the commit is converted into a rollback.
  5120. **
  5121. ** ^The sqlite3_commit_hook(D,C,P) and sqlite3_rollback_hook(D,C,P) functions
  5122. ** return the P argument from the previous call of the same function
  5123. ** on the same [database connection] D, or NULL for
  5124. ** the first call for each function on D.
  5125. **
  5126. ** The commit and rollback hook callbacks are not reentrant.
  5127. ** The callback implementation must not do anything that will modify
  5128. ** the database connection that invoked the callback. Any actions
  5129. ** to modify the database connection must be deferred until after the
  5130. ** completion of the [sqlite3_step()] call that triggered the commit
  5131. ** or rollback hook in the first place.
  5132. ** Note that running any other SQL statements, including SELECT statements,
  5133. ** or merely calling [sqlite3_prepare_v2()] and [sqlite3_step()] will modify
  5134. ** the database connections for the meaning of "modify" in this paragraph.
  5135. **
  5136. ** ^Registering a NULL function disables the callback.
  5137. **
  5138. ** ^When the commit hook callback routine returns zero, the [COMMIT]
  5139. ** operation is allowed to continue normally. ^If the commit hook
  5140. ** returns non-zero, then the [COMMIT] is converted into a [ROLLBACK].
  5141. ** ^The rollback hook is invoked on a rollback that results from a commit
  5142. ** hook returning non-zero, just as it would be with any other rollback.
  5143. **
  5144. ** ^For the purposes of this API, a transaction is said to have been
  5145. ** rolled back if an explicit "ROLLBACK" statement is executed, or
  5146. ** an error or constraint causes an implicit rollback to occur.
  5147. ** ^The rollback callback is not invoked if a transaction is
  5148. ** automatically rolled back because the database connection is closed.
  5149. **
  5150. ** See also the [sqlite3_update_hook()] interface.
  5151. */
  5152. SQLITE_API void *SQLITE_STDCALL sqlite3_commit_hook(sqlite3*, int(*)(void*), void*);
  5153. SQLITE_API void *SQLITE_STDCALL sqlite3_rollback_hook(sqlite3*, void(*)(void *), void*);
  5154. /*
  5155. ** CAPI3REF: Data Change Notification Callbacks
  5156. ** METHOD: sqlite3
  5157. **
  5158. ** ^The sqlite3_update_hook() interface registers a callback function
  5159. ** with the [database connection] identified by the first argument
  5160. ** to be invoked whenever a row is updated, inserted or deleted in
  5161. ** a rowid table.
  5162. ** ^Any callback set by a previous call to this function
  5163. ** for the same database connection is overridden.
  5164. **
  5165. ** ^The second argument is a pointer to the function to invoke when a
  5166. ** row is updated, inserted or deleted in a rowid table.
  5167. ** ^The first argument to the callback is a copy of the third argument
  5168. ** to sqlite3_update_hook().
  5169. ** ^The second callback argument is one of [SQLITE_INSERT], [SQLITE_DELETE],
  5170. ** or [SQLITE_UPDATE], depending on the operation that caused the callback
  5171. ** to be invoked.
  5172. ** ^The third and fourth arguments to the callback contain pointers to the
  5173. ** database and table name containing the affected row.
  5174. ** ^The final callback parameter is the [rowid] of the row.
  5175. ** ^In the case of an update, this is the [rowid] after the update takes place.
  5176. **
  5177. ** ^(The update hook is not invoked when internal system tables are
  5178. ** modified (i.e. sqlite_master and sqlite_sequence).)^
  5179. ** ^The update hook is not invoked when [WITHOUT ROWID] tables are modified.
  5180. **
  5181. ** ^In the current implementation, the update hook
  5182. ** is not invoked when duplication rows are deleted because of an
  5183. ** [ON CONFLICT | ON CONFLICT REPLACE] clause. ^Nor is the update hook
  5184. ** invoked when rows are deleted using the [truncate optimization].
  5185. ** The exceptions defined in this paragraph might change in a future
  5186. ** release of SQLite.
  5187. **
  5188. ** The update hook implementation must not do anything that will modify
  5189. ** the database connection that invoked the update hook. Any actions
  5190. ** to modify the database connection must be deferred until after the
  5191. ** completion of the [sqlite3_step()] call that triggered the update hook.
  5192. ** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
  5193. ** database connections for the meaning of "modify" in this paragraph.
  5194. **
  5195. ** ^The sqlite3_update_hook(D,C,P) function
  5196. ** returns the P argument from the previous call
  5197. ** on the same [database connection] D, or NULL for
  5198. ** the first call on D.
  5199. **
  5200. ** See also the [sqlite3_commit_hook()] and [sqlite3_rollback_hook()]
  5201. ** interfaces.
  5202. */
  5203. SQLITE_API void *SQLITE_STDCALL sqlite3_update_hook(
  5204. sqlite3*,
  5205. void(*)(void *,int ,char const *,char const *,sqlite3_int64),
  5206. void*
  5207. );
  5208. /*
  5209. ** CAPI3REF: Enable Or Disable Shared Pager Cache
  5210. **
  5211. ** ^(This routine enables or disables the sharing of the database cache
  5212. ** and schema data structures between [database connection | connections]
  5213. ** to the same database. Sharing is enabled if the argument is true
  5214. ** and disabled if the argument is false.)^
  5215. **
  5216. ** ^Cache sharing is enabled and disabled for an entire process.
  5217. ** This is a change as of SQLite version 3.5.0. In prior versions of SQLite,
  5218. ** sharing was enabled or disabled for each thread separately.
  5219. **
  5220. ** ^(The cache sharing mode set by this interface effects all subsequent
  5221. ** calls to [sqlite3_open()], [sqlite3_open_v2()], and [sqlite3_open16()].
  5222. ** Existing database connections continue use the sharing mode
  5223. ** that was in effect at the time they were opened.)^
  5224. **
  5225. ** ^(This routine returns [SQLITE_OK] if shared cache was enabled or disabled
  5226. ** successfully. An [error code] is returned otherwise.)^
  5227. **
  5228. ** ^Shared cache is disabled by default. But this might change in
  5229. ** future releases of SQLite. Applications that care about shared
  5230. ** cache setting should set it explicitly.
  5231. **
  5232. ** Note: This method is disabled on MacOS X 10.7 and iOS version 5.0
  5233. ** and will always return SQLITE_MISUSE. On those systems,
  5234. ** shared cache mode should be enabled per-database connection via
  5235. ** [sqlite3_open_v2()] with [SQLITE_OPEN_SHAREDCACHE].
  5236. **
  5237. ** This interface is threadsafe on processors where writing a
  5238. ** 32-bit integer is atomic.
  5239. **
  5240. ** See Also: [SQLite Shared-Cache Mode]
  5241. */
  5242. SQLITE_API int SQLITE_STDCALL sqlite3_enable_shared_cache(int);
  5243. /*
  5244. ** CAPI3REF: Attempt To Free Heap Memory
  5245. **
  5246. ** ^The sqlite3_release_memory() interface attempts to free N bytes
  5247. ** of heap memory by deallocating non-essential memory allocations
  5248. ** held by the database library. Memory used to cache database
  5249. ** pages to improve performance is an example of non-essential memory.
  5250. ** ^sqlite3_release_memory() returns the number of bytes actually freed,
  5251. ** which might be more or less than the amount requested.
  5252. ** ^The sqlite3_release_memory() routine is a no-op returning zero
  5253. ** if SQLite is not compiled with [SQLITE_ENABLE_MEMORY_MANAGEMENT].
  5254. **
  5255. ** See also: [sqlite3_db_release_memory()]
  5256. */
  5257. SQLITE_API int SQLITE_STDCALL sqlite3_release_memory(int);
  5258. /*
  5259. ** CAPI3REF: Free Memory Used By A Database Connection
  5260. ** METHOD: sqlite3
  5261. **
  5262. ** ^The sqlite3_db_release_memory(D) interface attempts to free as much heap
  5263. ** memory as possible from database connection D. Unlike the
  5264. ** [sqlite3_release_memory()] interface, this interface is in effect even
  5265. ** when the [SQLITE_ENABLE_MEMORY_MANAGEMENT] compile-time option is
  5266. ** omitted.
  5267. **
  5268. ** See also: [sqlite3_release_memory()]
  5269. */
  5270. SQLITE_API int SQLITE_STDCALL sqlite3_db_release_memory(sqlite3*);
  5271. /*
  5272. ** CAPI3REF: Impose A Limit On Heap Size
  5273. **
  5274. ** ^The sqlite3_soft_heap_limit64() interface sets and/or queries the
  5275. ** soft limit on the amount of heap memory that may be allocated by SQLite.
  5276. ** ^SQLite strives to keep heap memory utilization below the soft heap
  5277. ** limit by reducing the number of pages held in the page cache
  5278. ** as heap memory usages approaches the limit.
  5279. ** ^The soft heap limit is "soft" because even though SQLite strives to stay
  5280. ** below the limit, it will exceed the limit rather than generate
  5281. ** an [SQLITE_NOMEM] error. In other words, the soft heap limit
  5282. ** is advisory only.
  5283. **
  5284. ** ^The return value from sqlite3_soft_heap_limit64() is the size of
  5285. ** the soft heap limit prior to the call, or negative in the case of an
  5286. ** error. ^If the argument N is negative
  5287. ** then no change is made to the soft heap limit. Hence, the current
  5288. ** size of the soft heap limit can be determined by invoking
  5289. ** sqlite3_soft_heap_limit64() with a negative argument.
  5290. **
  5291. ** ^If the argument N is zero then the soft heap limit is disabled.
  5292. **
  5293. ** ^(The soft heap limit is not enforced in the current implementation
  5294. ** if one or more of following conditions are true:
  5295. **
  5296. ** <ul>
  5297. ** <li> The soft heap limit is set to zero.
  5298. ** <li> Memory accounting is disabled using a combination of the
  5299. ** [sqlite3_config]([SQLITE_CONFIG_MEMSTATUS],...) start-time option and
  5300. ** the [SQLITE_DEFAULT_MEMSTATUS] compile-time option.
  5301. ** <li> An alternative page cache implementation is specified using
  5302. ** [sqlite3_config]([SQLITE_CONFIG_PCACHE2],...).
  5303. ** <li> The page cache allocates from its own memory pool supplied
  5304. ** by [sqlite3_config]([SQLITE_CONFIG_PAGECACHE],...) rather than
  5305. ** from the heap.
  5306. ** </ul>)^
  5307. **
  5308. ** Beginning with SQLite version 3.7.3, the soft heap limit is enforced
  5309. ** regardless of whether or not the [SQLITE_ENABLE_MEMORY_MANAGEMENT]
  5310. ** compile-time option is invoked. With [SQLITE_ENABLE_MEMORY_MANAGEMENT],
  5311. ** the soft heap limit is enforced on every memory allocation. Without
  5312. ** [SQLITE_ENABLE_MEMORY_MANAGEMENT], the soft heap limit is only enforced
  5313. ** when memory is allocated by the page cache. Testing suggests that because
  5314. ** the page cache is the predominate memory user in SQLite, most
  5315. ** applications will achieve adequate soft heap limit enforcement without
  5316. ** the use of [SQLITE_ENABLE_MEMORY_MANAGEMENT].
  5317. **
  5318. ** The circumstances under which SQLite will enforce the soft heap limit may
  5319. ** changes in future releases of SQLite.
  5320. */
  5321. SQLITE_API sqlite3_int64 SQLITE_STDCALL sqlite3_soft_heap_limit64(sqlite3_int64 N);
  5322. /*
  5323. ** CAPI3REF: Deprecated Soft Heap Limit Interface
  5324. ** DEPRECATED
  5325. **
  5326. ** This is a deprecated version of the [sqlite3_soft_heap_limit64()]
  5327. ** interface. This routine is provided for historical compatibility
  5328. ** only. All new applications should use the
  5329. ** [sqlite3_soft_heap_limit64()] interface rather than this one.
  5330. */
  5331. SQLITE_API SQLITE_DEPRECATED void SQLITE_STDCALL sqlite3_soft_heap_limit(int N);
  5332. /*
  5333. ** CAPI3REF: Extract Metadata About A Column Of A Table
  5334. ** METHOD: sqlite3
  5335. **
  5336. ** ^(The sqlite3_table_column_metadata(X,D,T,C,....) routine returns
  5337. ** information about column C of table T in database D
  5338. ** on [database connection] X.)^ ^The sqlite3_table_column_metadata()
  5339. ** interface returns SQLITE_OK and fills in the non-NULL pointers in
  5340. ** the final five arguments with appropriate values if the specified
  5341. ** column exists. ^The sqlite3_table_column_metadata() interface returns
  5342. ** SQLITE_ERROR and if the specified column does not exist.
  5343. ** ^If the column-name parameter to sqlite3_table_column_metadata() is a
  5344. ** NULL pointer, then this routine simply checks for the existance of the
  5345. ** table and returns SQLITE_OK if the table exists and SQLITE_ERROR if it
  5346. ** does not.
  5347. **
  5348. ** ^The column is identified by the second, third and fourth parameters to
  5349. ** this function. ^(The second parameter is either the name of the database
  5350. ** (i.e. "main", "temp", or an attached database) containing the specified
  5351. ** table or NULL.)^ ^If it is NULL, then all attached databases are searched
  5352. ** for the table using the same algorithm used by the database engine to
  5353. ** resolve unqualified table references.
  5354. **
  5355. ** ^The third and fourth parameters to this function are the table and column
  5356. ** name of the desired column, respectively.
  5357. **
  5358. ** ^Metadata is returned by writing to the memory locations passed as the 5th
  5359. ** and subsequent parameters to this function. ^Any of these arguments may be
  5360. ** NULL, in which case the corresponding element of metadata is omitted.
  5361. **
  5362. ** ^(<blockquote>
  5363. ** <table border="1">
  5364. ** <tr><th> Parameter <th> Output<br>Type <th> Description
  5365. **
  5366. ** <tr><td> 5th <td> const char* <td> Data type
  5367. ** <tr><td> 6th <td> const char* <td> Name of default collation sequence
  5368. ** <tr><td> 7th <td> int <td> True if column has a NOT NULL constraint
  5369. ** <tr><td> 8th <td> int <td> True if column is part of the PRIMARY KEY
  5370. ** <tr><td> 9th <td> int <td> True if column is [AUTOINCREMENT]
  5371. ** </table>
  5372. ** </blockquote>)^
  5373. **
  5374. ** ^The memory pointed to by the character pointers returned for the
  5375. ** declaration type and collation sequence is valid until the next
  5376. ** call to any SQLite API function.
  5377. **
  5378. ** ^If the specified table is actually a view, an [error code] is returned.
  5379. **
  5380. ** ^If the specified column is "rowid", "oid" or "_rowid_" and the table
  5381. ** is not a [WITHOUT ROWID] table and an
  5382. ** [INTEGER PRIMARY KEY] column has been explicitly declared, then the output
  5383. ** parameters are set for the explicitly declared column. ^(If there is no
  5384. ** [INTEGER PRIMARY KEY] column, then the outputs
  5385. ** for the [rowid] are set as follows:
  5386. **
  5387. ** <pre>
  5388. ** data type: "INTEGER"
  5389. ** collation sequence: "BINARY"
  5390. ** not null: 0
  5391. ** primary key: 1
  5392. ** auto increment: 0
  5393. ** </pre>)^
  5394. **
  5395. ** ^This function causes all database schemas to be read from disk and
  5396. ** parsed, if that has not already been done, and returns an error if
  5397. ** any errors are encountered while loading the schema.
  5398. */
  5399. SQLITE_API int SQLITE_STDCALL sqlite3_table_column_metadata(
  5400. sqlite3 *db, /* Connection handle */
  5401. const char *zDbName, /* Database name or NULL */
  5402. const char *zTableName, /* Table name */
  5403. const char *zColumnName, /* Column name */
  5404. char const **pzDataType, /* OUTPUT: Declared data type */
  5405. char const **pzCollSeq, /* OUTPUT: Collation sequence name */
  5406. int *pNotNull, /* OUTPUT: True if NOT NULL constraint exists */
  5407. int *pPrimaryKey, /* OUTPUT: True if column part of PK */
  5408. int *pAutoinc /* OUTPUT: True if column is auto-increment */
  5409. );
  5410. /*
  5411. ** CAPI3REF: Load An Extension
  5412. ** METHOD: sqlite3
  5413. **
  5414. ** ^This interface loads an SQLite extension library from the named file.
  5415. **
  5416. ** ^The sqlite3_load_extension() interface attempts to load an
  5417. ** [SQLite extension] library contained in the file zFile. If
  5418. ** the file cannot be loaded directly, attempts are made to load
  5419. ** with various operating-system specific extensions added.
  5420. ** So for example, if "samplelib" cannot be loaded, then names like
  5421. ** "samplelib.so" or "samplelib.dylib" or "samplelib.dll" might
  5422. ** be tried also.
  5423. **
  5424. ** ^The entry point is zProc.
  5425. ** ^(zProc may be 0, in which case SQLite will try to come up with an
  5426. ** entry point name on its own. It first tries "sqlite3_extension_init".
  5427. ** If that does not work, it constructs a name "sqlite3_X_init" where the
  5428. ** X is consists of the lower-case equivalent of all ASCII alphabetic
  5429. ** characters in the filename from the last "/" to the first following
  5430. ** "." and omitting any initial "lib".)^
  5431. ** ^The sqlite3_load_extension() interface returns
  5432. ** [SQLITE_OK] on success and [SQLITE_ERROR] if something goes wrong.
  5433. ** ^If an error occurs and pzErrMsg is not 0, then the
  5434. ** [sqlite3_load_extension()] interface shall attempt to
  5435. ** fill *pzErrMsg with error message text stored in memory
  5436. ** obtained from [sqlite3_malloc()]. The calling function
  5437. ** should free this memory by calling [sqlite3_free()].
  5438. **
  5439. ** ^Extension loading must be enabled using
  5440. ** [sqlite3_enable_load_extension()] prior to calling this API,
  5441. ** otherwise an error will be returned.
  5442. **
  5443. ** See also the [load_extension() SQL function].
  5444. */
  5445. SQLITE_API int SQLITE_STDCALL sqlite3_load_extension(
  5446. sqlite3 *db, /* Load the extension into this database connection */
  5447. const char *zFile, /* Name of the shared library containing extension */
  5448. const char *zProc, /* Entry point. Derived from zFile if 0 */
  5449. char **pzErrMsg /* Put error message here if not 0 */
  5450. );
  5451. /*
  5452. ** CAPI3REF: Enable Or Disable Extension Loading
  5453. ** METHOD: sqlite3
  5454. **
  5455. ** ^So as not to open security holes in older applications that are
  5456. ** unprepared to deal with [extension loading], and as a means of disabling
  5457. ** [extension loading] while evaluating user-entered SQL, the following API
  5458. ** is provided to turn the [sqlite3_load_extension()] mechanism on and off.
  5459. **
  5460. ** ^Extension loading is off by default.
  5461. ** ^Call the sqlite3_enable_load_extension() routine with onoff==1
  5462. ** to turn extension loading on and call it with onoff==0 to turn
  5463. ** it back off again.
  5464. */
  5465. SQLITE_API int SQLITE_STDCALL sqlite3_enable_load_extension(sqlite3 *db, int onoff);
  5466. /*
  5467. ** CAPI3REF: Automatically Load Statically Linked Extensions
  5468. **
  5469. ** ^This interface causes the xEntryPoint() function to be invoked for
  5470. ** each new [database connection] that is created. The idea here is that
  5471. ** xEntryPoint() is the entry point for a statically linked [SQLite extension]
  5472. ** that is to be automatically loaded into all new database connections.
  5473. **
  5474. ** ^(Even though the function prototype shows that xEntryPoint() takes
  5475. ** no arguments and returns void, SQLite invokes xEntryPoint() with three
  5476. ** arguments and expects and integer result as if the signature of the
  5477. ** entry point where as follows:
  5478. **
  5479. ** <blockquote><pre>
  5480. ** &nbsp; int xEntryPoint(
  5481. ** &nbsp; sqlite3 *db,
  5482. ** &nbsp; const char **pzErrMsg,
  5483. ** &nbsp; const struct sqlite3_api_routines *pThunk
  5484. ** &nbsp; );
  5485. ** </pre></blockquote>)^
  5486. **
  5487. ** If the xEntryPoint routine encounters an error, it should make *pzErrMsg
  5488. ** point to an appropriate error message (obtained from [sqlite3_mprintf()])
  5489. ** and return an appropriate [error code]. ^SQLite ensures that *pzErrMsg
  5490. ** is NULL before calling the xEntryPoint(). ^SQLite will invoke
  5491. ** [sqlite3_free()] on *pzErrMsg after xEntryPoint() returns. ^If any
  5492. ** xEntryPoint() returns an error, the [sqlite3_open()], [sqlite3_open16()],
  5493. ** or [sqlite3_open_v2()] call that provoked the xEntryPoint() will fail.
  5494. **
  5495. ** ^Calling sqlite3_auto_extension(X) with an entry point X that is already
  5496. ** on the list of automatic extensions is a harmless no-op. ^No entry point
  5497. ** will be called more than once for each database connection that is opened.
  5498. **
  5499. ** See also: [sqlite3_reset_auto_extension()]
  5500. ** and [sqlite3_cancel_auto_extension()]
  5501. */
  5502. SQLITE_API int SQLITE_STDCALL sqlite3_auto_extension(void (*xEntryPoint)(void));
  5503. /*
  5504. ** CAPI3REF: Cancel Automatic Extension Loading
  5505. **
  5506. ** ^The [sqlite3_cancel_auto_extension(X)] interface unregisters the
  5507. ** initialization routine X that was registered using a prior call to
  5508. ** [sqlite3_auto_extension(X)]. ^The [sqlite3_cancel_auto_extension(X)]
  5509. ** routine returns 1 if initialization routine X was successfully
  5510. ** unregistered and it returns 0 if X was not on the list of initialization
  5511. ** routines.
  5512. */
  5513. SQLITE_API int SQLITE_STDCALL sqlite3_cancel_auto_extension(void (*xEntryPoint)(void));
  5514. /*
  5515. ** CAPI3REF: Reset Automatic Extension Loading
  5516. **
  5517. ** ^This interface disables all automatic extensions previously
  5518. ** registered using [sqlite3_auto_extension()].
  5519. */
  5520. SQLITE_API void SQLITE_STDCALL sqlite3_reset_auto_extension(void);
  5521. /*
  5522. ** The interface to the virtual-table mechanism is currently considered
  5523. ** to be experimental. The interface might change in incompatible ways.
  5524. ** If this is a problem for you, do not use the interface at this time.
  5525. **
  5526. ** When the virtual-table mechanism stabilizes, we will declare the
  5527. ** interface fixed, support it indefinitely, and remove this comment.
  5528. */
  5529. /*
  5530. ** Structures used by the virtual table interface
  5531. */
  5532. typedef struct sqlite3_vtab sqlite3_vtab;
  5533. typedef struct sqlite3_index_info sqlite3_index_info;
  5534. typedef struct sqlite3_vtab_cursor sqlite3_vtab_cursor;
  5535. typedef struct sqlite3_module sqlite3_module;
  5536. /*
  5537. ** CAPI3REF: Virtual Table Object
  5538. ** KEYWORDS: sqlite3_module {virtual table module}
  5539. **
  5540. ** This structure, sometimes called a "virtual table module",
  5541. ** defines the implementation of a [virtual tables].
  5542. ** This structure consists mostly of methods for the module.
  5543. **
  5544. ** ^A virtual table module is created by filling in a persistent
  5545. ** instance of this structure and passing a pointer to that instance
  5546. ** to [sqlite3_create_module()] or [sqlite3_create_module_v2()].
  5547. ** ^The registration remains valid until it is replaced by a different
  5548. ** module or until the [database connection] closes. The content
  5549. ** of this structure must not change while it is registered with
  5550. ** any database connection.
  5551. */
  5552. struct sqlite3_module {
  5553. int iVersion;
  5554. int (*xCreate)(sqlite3*, void *pAux,
  5555. int argc, const char *const*argv,
  5556. sqlite3_vtab **ppVTab, char**);
  5557. int (*xConnect)(sqlite3*, void *pAux,
  5558. int argc, const char *const*argv,
  5559. sqlite3_vtab **ppVTab, char**);
  5560. int (*xBestIndex)(sqlite3_vtab *pVTab, sqlite3_index_info*);
  5561. int (*xDisconnect)(sqlite3_vtab *pVTab);
  5562. int (*xDestroy)(sqlite3_vtab *pVTab);
  5563. int (*xOpen)(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor);
  5564. int (*xClose)(sqlite3_vtab_cursor*);
  5565. int (*xFilter)(sqlite3_vtab_cursor*, int idxNum, const char *idxStr,
  5566. int argc, sqlite3_value **argv);
  5567. int (*xNext)(sqlite3_vtab_cursor*);
  5568. int (*xEof)(sqlite3_vtab_cursor*);
  5569. int (*xColumn)(sqlite3_vtab_cursor*, sqlite3_context*, int);
  5570. int (*xRowid)(sqlite3_vtab_cursor*, sqlite3_int64 *pRowid);
  5571. int (*xUpdate)(sqlite3_vtab *, int, sqlite3_value **, sqlite3_int64 *);
  5572. int (*xBegin)(sqlite3_vtab *pVTab);
  5573. int (*xSync)(sqlite3_vtab *pVTab);
  5574. int (*xCommit)(sqlite3_vtab *pVTab);
  5575. int (*xRollback)(sqlite3_vtab *pVTab);
  5576. int (*xFindFunction)(sqlite3_vtab *pVtab, int nArg, const char *zName,
  5577. void (**pxFunc)(sqlite3_context*,int,sqlite3_value**),
  5578. void **ppArg);
  5579. int (*xRename)(sqlite3_vtab *pVtab, const char *zNew);
  5580. /* The methods above are in version 1 of the sqlite_module object. Those
  5581. ** below are for version 2 and greater. */
  5582. int (*xSavepoint)(sqlite3_vtab *pVTab, int);
  5583. int (*xRelease)(sqlite3_vtab *pVTab, int);
  5584. int (*xRollbackTo)(sqlite3_vtab *pVTab, int);
  5585. };
  5586. /*
  5587. ** CAPI3REF: Virtual Table Indexing Information
  5588. ** KEYWORDS: sqlite3_index_info
  5589. **
  5590. ** The sqlite3_index_info structure and its substructures is used as part
  5591. ** of the [virtual table] interface to
  5592. ** pass information into and receive the reply from the [xBestIndex]
  5593. ** method of a [virtual table module]. The fields under **Inputs** are the
  5594. ** inputs to xBestIndex and are read-only. xBestIndex inserts its
  5595. ** results into the **Outputs** fields.
  5596. **
  5597. ** ^(The aConstraint[] array records WHERE clause constraints of the form:
  5598. **
  5599. ** <blockquote>column OP expr</blockquote>
  5600. **
  5601. ** where OP is =, &lt;, &lt;=, &gt;, or &gt;=.)^ ^(The particular operator is
  5602. ** stored in aConstraint[].op using one of the
  5603. ** [SQLITE_INDEX_CONSTRAINT_EQ | SQLITE_INDEX_CONSTRAINT_ values].)^
  5604. ** ^(The index of the column is stored in
  5605. ** aConstraint[].iColumn.)^ ^(aConstraint[].usable is TRUE if the
  5606. ** expr on the right-hand side can be evaluated (and thus the constraint
  5607. ** is usable) and false if it cannot.)^
  5608. **
  5609. ** ^The optimizer automatically inverts terms of the form "expr OP column"
  5610. ** and makes other simplifications to the WHERE clause in an attempt to
  5611. ** get as many WHERE clause terms into the form shown above as possible.
  5612. ** ^The aConstraint[] array only reports WHERE clause terms that are
  5613. ** relevant to the particular virtual table being queried.
  5614. **
  5615. ** ^Information about the ORDER BY clause is stored in aOrderBy[].
  5616. ** ^Each term of aOrderBy records a column of the ORDER BY clause.
  5617. **
  5618. ** The [xBestIndex] method must fill aConstraintUsage[] with information
  5619. ** about what parameters to pass to xFilter. ^If argvIndex>0 then
  5620. ** the right-hand side of the corresponding aConstraint[] is evaluated
  5621. ** and becomes the argvIndex-th entry in argv. ^(If aConstraintUsage[].omit
  5622. ** is true, then the constraint is assumed to be fully handled by the
  5623. ** virtual table and is not checked again by SQLite.)^
  5624. **
  5625. ** ^The idxNum and idxPtr values are recorded and passed into the
  5626. ** [xFilter] method.
  5627. ** ^[sqlite3_free()] is used to free idxPtr if and only if
  5628. ** needToFreeIdxPtr is true.
  5629. **
  5630. ** ^The orderByConsumed means that output from [xFilter]/[xNext] will occur in
  5631. ** the correct order to satisfy the ORDER BY clause so that no separate
  5632. ** sorting step is required.
  5633. **
  5634. ** ^The estimatedCost value is an estimate of the cost of a particular
  5635. ** strategy. A cost of N indicates that the cost of the strategy is similar
  5636. ** to a linear scan of an SQLite table with N rows. A cost of log(N)
  5637. ** indicates that the expense of the operation is similar to that of a
  5638. ** binary search on a unique indexed field of an SQLite table with N rows.
  5639. **
  5640. ** ^The estimatedRows value is an estimate of the number of rows that
  5641. ** will be returned by the strategy.
  5642. **
  5643. ** IMPORTANT: The estimatedRows field was added to the sqlite3_index_info
  5644. ** structure for SQLite version 3.8.2. If a virtual table extension is
  5645. ** used with an SQLite version earlier than 3.8.2, the results of attempting
  5646. ** to read or write the estimatedRows field are undefined (but are likely
  5647. ** to included crashing the application). The estimatedRows field should
  5648. ** therefore only be used if [sqlite3_libversion_number()] returns a
  5649. ** value greater than or equal to 3008002.
  5650. */
  5651. struct sqlite3_index_info {
  5652. /* Inputs */
  5653. int nConstraint; /* Number of entries in aConstraint */
  5654. struct sqlite3_index_constraint {
  5655. int iColumn; /* Column on left-hand side of constraint */
  5656. unsigned char op; /* Constraint operator */
  5657. unsigned char usable; /* True if this constraint is usable */
  5658. int iTermOffset; /* Used internally - xBestIndex should ignore */
  5659. } *aConstraint; /* Table of WHERE clause constraints */
  5660. int nOrderBy; /* Number of terms in the ORDER BY clause */
  5661. struct sqlite3_index_orderby {
  5662. int iColumn; /* Column number */
  5663. unsigned char desc; /* True for DESC. False for ASC. */
  5664. } *aOrderBy; /* The ORDER BY clause */
  5665. /* Outputs */
  5666. struct sqlite3_index_constraint_usage {
  5667. int argvIndex; /* if >0, constraint is part of argv to xFilter */
  5668. unsigned char omit; /* Do not code a test for this constraint */
  5669. } *aConstraintUsage;
  5670. int idxNum; /* Number used to identify the index */
  5671. char *idxStr; /* String, possibly obtained from sqlite3_malloc */
  5672. int needToFreeIdxStr; /* Free idxStr using sqlite3_free() if true */
  5673. int orderByConsumed; /* True if output is already ordered */
  5674. double estimatedCost; /* Estimated cost of using this index */
  5675. /* Fields below are only available in SQLite 3.8.2 and later */
  5676. sqlite3_int64 estimatedRows; /* Estimated number of rows returned */
  5677. };
  5678. /*
  5679. ** CAPI3REF: Virtual Table Constraint Operator Codes
  5680. **
  5681. ** These macros defined the allowed values for the
  5682. ** [sqlite3_index_info].aConstraint[].op field. Each value represents
  5683. ** an operator that is part of a constraint term in the wHERE clause of
  5684. ** a query that uses a [virtual table].
  5685. */
  5686. #define SQLITE_INDEX_CONSTRAINT_EQ 2
  5687. #define SQLITE_INDEX_CONSTRAINT_GT 4
  5688. #define SQLITE_INDEX_CONSTRAINT_LE 8
  5689. #define SQLITE_INDEX_CONSTRAINT_LT 16
  5690. #define SQLITE_INDEX_CONSTRAINT_GE 32
  5691. #define SQLITE_INDEX_CONSTRAINT_MATCH 64
  5692. /*
  5693. ** CAPI3REF: Register A Virtual Table Implementation
  5694. ** METHOD: sqlite3
  5695. **
  5696. ** ^These routines are used to register a new [virtual table module] name.
  5697. ** ^Module names must be registered before
  5698. ** creating a new [virtual table] using the module and before using a
  5699. ** preexisting [virtual table] for the module.
  5700. **
  5701. ** ^The module name is registered on the [database connection] specified
  5702. ** by the first parameter. ^The name of the module is given by the
  5703. ** second parameter. ^The third parameter is a pointer to
  5704. ** the implementation of the [virtual table module]. ^The fourth
  5705. ** parameter is an arbitrary client data pointer that is passed through
  5706. ** into the [xCreate] and [xConnect] methods of the virtual table module
  5707. ** when a new virtual table is be being created or reinitialized.
  5708. **
  5709. ** ^The sqlite3_create_module_v2() interface has a fifth parameter which
  5710. ** is a pointer to a destructor for the pClientData. ^SQLite will
  5711. ** invoke the destructor function (if it is not NULL) when SQLite
  5712. ** no longer needs the pClientData pointer. ^The destructor will also
  5713. ** be invoked if the call to sqlite3_create_module_v2() fails.
  5714. ** ^The sqlite3_create_module()
  5715. ** interface is equivalent to sqlite3_create_module_v2() with a NULL
  5716. ** destructor.
  5717. */
  5718. SQLITE_API int SQLITE_STDCALL sqlite3_create_module(
  5719. sqlite3 *db, /* SQLite connection to register module with */
  5720. const char *zName, /* Name of the module */
  5721. const sqlite3_module *p, /* Methods for the module */
  5722. void *pClientData /* Client data for xCreate/xConnect */
  5723. );
  5724. SQLITE_API int SQLITE_STDCALL sqlite3_create_module_v2(
  5725. sqlite3 *db, /* SQLite connection to register module with */
  5726. const char *zName, /* Name of the module */
  5727. const sqlite3_module *p, /* Methods for the module */
  5728. void *pClientData, /* Client data for xCreate/xConnect */
  5729. void(*xDestroy)(void*) /* Module destructor function */
  5730. );
  5731. /*
  5732. ** CAPI3REF: Virtual Table Instance Object
  5733. ** KEYWORDS: sqlite3_vtab
  5734. **
  5735. ** Every [virtual table module] implementation uses a subclass
  5736. ** of this object to describe a particular instance
  5737. ** of the [virtual table]. Each subclass will
  5738. ** be tailored to the specific needs of the module implementation.
  5739. ** The purpose of this superclass is to define certain fields that are
  5740. ** common to all module implementations.
  5741. **
  5742. ** ^Virtual tables methods can set an error message by assigning a
  5743. ** string obtained from [sqlite3_mprintf()] to zErrMsg. The method should
  5744. ** take care that any prior string is freed by a call to [sqlite3_free()]
  5745. ** prior to assigning a new string to zErrMsg. ^After the error message
  5746. ** is delivered up to the client application, the string will be automatically
  5747. ** freed by sqlite3_free() and the zErrMsg field will be zeroed.
  5748. */
  5749. struct sqlite3_vtab {
  5750. const sqlite3_module *pModule; /* The module for this virtual table */
  5751. int nRef; /* Number of open cursors */
  5752. char *zErrMsg; /* Error message from sqlite3_mprintf() */
  5753. /* Virtual table implementations will typically add additional fields */
  5754. };
  5755. /*
  5756. ** CAPI3REF: Virtual Table Cursor Object
  5757. ** KEYWORDS: sqlite3_vtab_cursor {virtual table cursor}
  5758. **
  5759. ** Every [virtual table module] implementation uses a subclass of the
  5760. ** following structure to describe cursors that point into the
  5761. ** [virtual table] and are used
  5762. ** to loop through the virtual table. Cursors are created using the
  5763. ** [sqlite3_module.xOpen | xOpen] method of the module and are destroyed
  5764. ** by the [sqlite3_module.xClose | xClose] method. Cursors are used
  5765. ** by the [xFilter], [xNext], [xEof], [xColumn], and [xRowid] methods
  5766. ** of the module. Each module implementation will define
  5767. ** the content of a cursor structure to suit its own needs.
  5768. **
  5769. ** This superclass exists in order to define fields of the cursor that
  5770. ** are common to all implementations.
  5771. */
  5772. struct sqlite3_vtab_cursor {
  5773. sqlite3_vtab *pVtab; /* Virtual table of this cursor */
  5774. /* Virtual table implementations will typically add additional fields */
  5775. };
  5776. /*
  5777. ** CAPI3REF: Declare The Schema Of A Virtual Table
  5778. **
  5779. ** ^The [xCreate] and [xConnect] methods of a
  5780. ** [virtual table module] call this interface
  5781. ** to declare the format (the names and datatypes of the columns) of
  5782. ** the virtual tables they implement.
  5783. */
  5784. SQLITE_API int SQLITE_STDCALL sqlite3_declare_vtab(sqlite3*, const char *zSQL);
  5785. /*
  5786. ** CAPI3REF: Overload A Function For A Virtual Table
  5787. ** METHOD: sqlite3
  5788. **
  5789. ** ^(Virtual tables can provide alternative implementations of functions
  5790. ** using the [xFindFunction] method of the [virtual table module].
  5791. ** But global versions of those functions
  5792. ** must exist in order to be overloaded.)^
  5793. **
  5794. ** ^(This API makes sure a global version of a function with a particular
  5795. ** name and number of parameters exists. If no such function exists
  5796. ** before this API is called, a new function is created.)^ ^The implementation
  5797. ** of the new function always causes an exception to be thrown. So
  5798. ** the new function is not good for anything by itself. Its only
  5799. ** purpose is to be a placeholder function that can be overloaded
  5800. ** by a [virtual table].
  5801. */
  5802. SQLITE_API int SQLITE_STDCALL sqlite3_overload_function(sqlite3*, const char *zFuncName, int nArg);
  5803. /*
  5804. ** The interface to the virtual-table mechanism defined above (back up
  5805. ** to a comment remarkably similar to this one) is currently considered
  5806. ** to be experimental. The interface might change in incompatible ways.
  5807. ** If this is a problem for you, do not use the interface at this time.
  5808. **
  5809. ** When the virtual-table mechanism stabilizes, we will declare the
  5810. ** interface fixed, support it indefinitely, and remove this comment.
  5811. */
  5812. /*
  5813. ** CAPI3REF: A Handle To An Open BLOB
  5814. ** KEYWORDS: {BLOB handle} {BLOB handles}
  5815. **
  5816. ** An instance of this object represents an open BLOB on which
  5817. ** [sqlite3_blob_open | incremental BLOB I/O] can be performed.
  5818. ** ^Objects of this type are created by [sqlite3_blob_open()]
  5819. ** and destroyed by [sqlite3_blob_close()].
  5820. ** ^The [sqlite3_blob_read()] and [sqlite3_blob_write()] interfaces
  5821. ** can be used to read or write small subsections of the BLOB.
  5822. ** ^The [sqlite3_blob_bytes()] interface returns the size of the BLOB in bytes.
  5823. */
  5824. typedef struct sqlite3_blob sqlite3_blob;
  5825. /*
  5826. ** CAPI3REF: Open A BLOB For Incremental I/O
  5827. ** METHOD: sqlite3
  5828. ** CONSTRUCTOR: sqlite3_blob
  5829. **
  5830. ** ^(This interfaces opens a [BLOB handle | handle] to the BLOB located
  5831. ** in row iRow, column zColumn, table zTable in database zDb;
  5832. ** in other words, the same BLOB that would be selected by:
  5833. **
  5834. ** <pre>
  5835. ** SELECT zColumn FROM zDb.zTable WHERE [rowid] = iRow;
  5836. ** </pre>)^
  5837. **
  5838. ** ^(Parameter zDb is not the filename that contains the database, but
  5839. ** rather the symbolic name of the database. For attached databases, this is
  5840. ** the name that appears after the AS keyword in the [ATTACH] statement.
  5841. ** For the main database file, the database name is "main". For TEMP
  5842. ** tables, the database name is "temp".)^
  5843. **
  5844. ** ^If the flags parameter is non-zero, then the BLOB is opened for read
  5845. ** and write access. ^If the flags parameter is zero, the BLOB is opened for
  5846. ** read-only access.
  5847. **
  5848. ** ^(On success, [SQLITE_OK] is returned and the new [BLOB handle] is stored
  5849. ** in *ppBlob. Otherwise an [error code] is returned and, unless the error
  5850. ** code is SQLITE_MISUSE, *ppBlob is set to NULL.)^ ^This means that, provided
  5851. ** the API is not misused, it is always safe to call [sqlite3_blob_close()]
  5852. ** on *ppBlob after this function it returns.
  5853. **
  5854. ** This function fails with SQLITE_ERROR if any of the following are true:
  5855. ** <ul>
  5856. ** <li> ^(Database zDb does not exist)^,
  5857. ** <li> ^(Table zTable does not exist within database zDb)^,
  5858. ** <li> ^(Table zTable is a WITHOUT ROWID table)^,
  5859. ** <li> ^(Column zColumn does not exist)^,
  5860. ** <li> ^(Row iRow is not present in the table)^,
  5861. ** <li> ^(The specified column of row iRow contains a value that is not
  5862. ** a TEXT or BLOB value)^,
  5863. ** <li> ^(Column zColumn is part of an index, PRIMARY KEY or UNIQUE
  5864. ** constraint and the blob is being opened for read/write access)^,
  5865. ** <li> ^([foreign key constraints | Foreign key constraints] are enabled,
  5866. ** column zColumn is part of a [child key] definition and the blob is
  5867. ** being opened for read/write access)^.
  5868. ** </ul>
  5869. **
  5870. ** ^Unless it returns SQLITE_MISUSE, this function sets the
  5871. ** [database connection] error code and message accessible via
  5872. ** [sqlite3_errcode()] and [sqlite3_errmsg()] and related functions.
  5873. **
  5874. **
  5875. ** ^(If the row that a BLOB handle points to is modified by an
  5876. ** [UPDATE], [DELETE], or by [ON CONFLICT] side-effects
  5877. ** then the BLOB handle is marked as "expired".
  5878. ** This is true if any column of the row is changed, even a column
  5879. ** other than the one the BLOB handle is open on.)^
  5880. ** ^Calls to [sqlite3_blob_read()] and [sqlite3_blob_write()] for
  5881. ** an expired BLOB handle fail with a return code of [SQLITE_ABORT].
  5882. ** ^(Changes written into a BLOB prior to the BLOB expiring are not
  5883. ** rolled back by the expiration of the BLOB. Such changes will eventually
  5884. ** commit if the transaction continues to completion.)^
  5885. **
  5886. ** ^Use the [sqlite3_blob_bytes()] interface to determine the size of
  5887. ** the opened blob. ^The size of a blob may not be changed by this
  5888. ** interface. Use the [UPDATE] SQL command to change the size of a
  5889. ** blob.
  5890. **
  5891. ** ^The [sqlite3_bind_zeroblob()] and [sqlite3_result_zeroblob()] interfaces
  5892. ** and the built-in [zeroblob] SQL function may be used to create a
  5893. ** zero-filled blob to read or write using the incremental-blob interface.
  5894. **
  5895. ** To avoid a resource leak, every open [BLOB handle] should eventually
  5896. ** be released by a call to [sqlite3_blob_close()].
  5897. */
  5898. SQLITE_API int SQLITE_STDCALL sqlite3_blob_open(
  5899. sqlite3*,
  5900. const char *zDb,
  5901. const char *zTable,
  5902. const char *zColumn,
  5903. sqlite3_int64 iRow,
  5904. int flags,
  5905. sqlite3_blob **ppBlob
  5906. );
  5907. /*
  5908. ** CAPI3REF: Move a BLOB Handle to a New Row
  5909. ** METHOD: sqlite3_blob
  5910. **
  5911. ** ^This function is used to move an existing blob handle so that it points
  5912. ** to a different row of the same database table. ^The new row is identified
  5913. ** by the rowid value passed as the second argument. Only the row can be
  5914. ** changed. ^The database, table and column on which the blob handle is open
  5915. ** remain the same. Moving an existing blob handle to a new row can be
  5916. ** faster than closing the existing handle and opening a new one.
  5917. **
  5918. ** ^(The new row must meet the same criteria as for [sqlite3_blob_open()] -
  5919. ** it must exist and there must be either a blob or text value stored in
  5920. ** the nominated column.)^ ^If the new row is not present in the table, or if
  5921. ** it does not contain a blob or text value, or if another error occurs, an
  5922. ** SQLite error code is returned and the blob handle is considered aborted.
  5923. ** ^All subsequent calls to [sqlite3_blob_read()], [sqlite3_blob_write()] or
  5924. ** [sqlite3_blob_reopen()] on an aborted blob handle immediately return
  5925. ** SQLITE_ABORT. ^Calling [sqlite3_blob_bytes()] on an aborted blob handle
  5926. ** always returns zero.
  5927. **
  5928. ** ^This function sets the database handle error code and message.
  5929. */
  5930. SQLITE_API SQLITE_EXPERIMENTAL int SQLITE_STDCALL sqlite3_blob_reopen(sqlite3_blob *, sqlite3_int64);
  5931. /*
  5932. ** CAPI3REF: Close A BLOB Handle
  5933. ** DESTRUCTOR: sqlite3_blob
  5934. **
  5935. ** ^This function closes an open [BLOB handle]. ^(The BLOB handle is closed
  5936. ** unconditionally. Even if this routine returns an error code, the
  5937. ** handle is still closed.)^
  5938. **
  5939. ** ^If the blob handle being closed was opened for read-write access, and if
  5940. ** the database is in auto-commit mode and there are no other open read-write
  5941. ** blob handles or active write statements, the current transaction is
  5942. ** committed. ^If an error occurs while committing the transaction, an error
  5943. ** code is returned and the transaction rolled back.
  5944. **
  5945. ** Calling this function with an argument that is not a NULL pointer or an
  5946. ** open blob handle results in undefined behaviour. ^Calling this routine
  5947. ** with a null pointer (such as would be returned by a failed call to
  5948. ** [sqlite3_blob_open()]) is a harmless no-op. ^Otherwise, if this function
  5949. ** is passed a valid open blob handle, the values returned by the
  5950. ** sqlite3_errcode() and sqlite3_errmsg() functions are set before returning.
  5951. */
  5952. SQLITE_API int SQLITE_STDCALL sqlite3_blob_close(sqlite3_blob *);
  5953. /*
  5954. ** CAPI3REF: Return The Size Of An Open BLOB
  5955. ** METHOD: sqlite3_blob
  5956. **
  5957. ** ^Returns the size in bytes of the BLOB accessible via the
  5958. ** successfully opened [BLOB handle] in its only argument. ^The
  5959. ** incremental blob I/O routines can only read or overwriting existing
  5960. ** blob content; they cannot change the size of a blob.
  5961. **
  5962. ** This routine only works on a [BLOB handle] which has been created
  5963. ** by a prior successful call to [sqlite3_blob_open()] and which has not
  5964. ** been closed by [sqlite3_blob_close()]. Passing any other pointer in
  5965. ** to this routine results in undefined and probably undesirable behavior.
  5966. */
  5967. SQLITE_API int SQLITE_STDCALL sqlite3_blob_bytes(sqlite3_blob *);
  5968. /*
  5969. ** CAPI3REF: Read Data From A BLOB Incrementally
  5970. ** METHOD: sqlite3_blob
  5971. **
  5972. ** ^(This function is used to read data from an open [BLOB handle] into a
  5973. ** caller-supplied buffer. N bytes of data are copied into buffer Z
  5974. ** from the open BLOB, starting at offset iOffset.)^
  5975. **
  5976. ** ^If offset iOffset is less than N bytes from the end of the BLOB,
  5977. ** [SQLITE_ERROR] is returned and no data is read. ^If N or iOffset is
  5978. ** less than zero, [SQLITE_ERROR] is returned and no data is read.
  5979. ** ^The size of the blob (and hence the maximum value of N+iOffset)
  5980. ** can be determined using the [sqlite3_blob_bytes()] interface.
  5981. **
  5982. ** ^An attempt to read from an expired [BLOB handle] fails with an
  5983. ** error code of [SQLITE_ABORT].
  5984. **
  5985. ** ^(On success, sqlite3_blob_read() returns SQLITE_OK.
  5986. ** Otherwise, an [error code] or an [extended error code] is returned.)^
  5987. **
  5988. ** This routine only works on a [BLOB handle] which has been created
  5989. ** by a prior successful call to [sqlite3_blob_open()] and which has not
  5990. ** been closed by [sqlite3_blob_close()]. Passing any other pointer in
  5991. ** to this routine results in undefined and probably undesirable behavior.
  5992. **
  5993. ** See also: [sqlite3_blob_write()].
  5994. */
  5995. SQLITE_API int SQLITE_STDCALL sqlite3_blob_read(sqlite3_blob *, void *Z, int N, int iOffset);
  5996. /*
  5997. ** CAPI3REF: Write Data Into A BLOB Incrementally
  5998. ** METHOD: sqlite3_blob
  5999. **
  6000. ** ^(This function is used to write data into an open [BLOB handle] from a
  6001. ** caller-supplied buffer. N bytes of data are copied from the buffer Z
  6002. ** into the open BLOB, starting at offset iOffset.)^
  6003. **
  6004. ** ^(On success, sqlite3_blob_write() returns SQLITE_OK.
  6005. ** Otherwise, an [error code] or an [extended error code] is returned.)^
  6006. ** ^Unless SQLITE_MISUSE is returned, this function sets the
  6007. ** [database connection] error code and message accessible via
  6008. ** [sqlite3_errcode()] and [sqlite3_errmsg()] and related functions.
  6009. **
  6010. ** ^If the [BLOB handle] passed as the first argument was not opened for
  6011. ** writing (the flags parameter to [sqlite3_blob_open()] was zero),
  6012. ** this function returns [SQLITE_READONLY].
  6013. **
  6014. ** This function may only modify the contents of the BLOB; it is
  6015. ** not possible to increase the size of a BLOB using this API.
  6016. ** ^If offset iOffset is less than N bytes from the end of the BLOB,
  6017. ** [SQLITE_ERROR] is returned and no data is written. The size of the
  6018. ** BLOB (and hence the maximum value of N+iOffset) can be determined
  6019. ** using the [sqlite3_blob_bytes()] interface. ^If N or iOffset are less
  6020. ** than zero [SQLITE_ERROR] is returned and no data is written.
  6021. **
  6022. ** ^An attempt to write to an expired [BLOB handle] fails with an
  6023. ** error code of [SQLITE_ABORT]. ^Writes to the BLOB that occurred
  6024. ** before the [BLOB handle] expired are not rolled back by the
  6025. ** expiration of the handle, though of course those changes might
  6026. ** have been overwritten by the statement that expired the BLOB handle
  6027. ** or by other independent statements.
  6028. **
  6029. ** This routine only works on a [BLOB handle] which has been created
  6030. ** by a prior successful call to [sqlite3_blob_open()] and which has not
  6031. ** been closed by [sqlite3_blob_close()]. Passing any other pointer in
  6032. ** to this routine results in undefined and probably undesirable behavior.
  6033. **
  6034. ** See also: [sqlite3_blob_read()].
  6035. */
  6036. SQLITE_API int SQLITE_STDCALL sqlite3_blob_write(sqlite3_blob *, const void *z, int n, int iOffset);
  6037. /*
  6038. ** CAPI3REF: Virtual File System Objects
  6039. **
  6040. ** A virtual filesystem (VFS) is an [sqlite3_vfs] object
  6041. ** that SQLite uses to interact
  6042. ** with the underlying operating system. Most SQLite builds come with a
  6043. ** single default VFS that is appropriate for the host computer.
  6044. ** New VFSes can be registered and existing VFSes can be unregistered.
  6045. ** The following interfaces are provided.
  6046. **
  6047. ** ^The sqlite3_vfs_find() interface returns a pointer to a VFS given its name.
  6048. ** ^Names are case sensitive.
  6049. ** ^Names are zero-terminated UTF-8 strings.
  6050. ** ^If there is no match, a NULL pointer is returned.
  6051. ** ^If zVfsName is NULL then the default VFS is returned.
  6052. **
  6053. ** ^New VFSes are registered with sqlite3_vfs_register().
  6054. ** ^Each new VFS becomes the default VFS if the makeDflt flag is set.
  6055. ** ^The same VFS can be registered multiple times without injury.
  6056. ** ^To make an existing VFS into the default VFS, register it again
  6057. ** with the makeDflt flag set. If two different VFSes with the
  6058. ** same name are registered, the behavior is undefined. If a
  6059. ** VFS is registered with a name that is NULL or an empty string,
  6060. ** then the behavior is undefined.
  6061. **
  6062. ** ^Unregister a VFS with the sqlite3_vfs_unregister() interface.
  6063. ** ^(If the default VFS is unregistered, another VFS is chosen as
  6064. ** the default. The choice for the new VFS is arbitrary.)^
  6065. */
  6066. SQLITE_API sqlite3_vfs *SQLITE_STDCALL sqlite3_vfs_find(const char *zVfsName);
  6067. SQLITE_API int SQLITE_STDCALL sqlite3_vfs_register(sqlite3_vfs*, int makeDflt);
  6068. SQLITE_API int SQLITE_STDCALL sqlite3_vfs_unregister(sqlite3_vfs*);
  6069. /*
  6070. ** CAPI3REF: Mutexes
  6071. **
  6072. ** The SQLite core uses these routines for thread
  6073. ** synchronization. Though they are intended for internal
  6074. ** use by SQLite, code that links against SQLite is
  6075. ** permitted to use any of these routines.
  6076. **
  6077. ** The SQLite source code contains multiple implementations
  6078. ** of these mutex routines. An appropriate implementation
  6079. ** is selected automatically at compile-time. The following
  6080. ** implementations are available in the SQLite core:
  6081. **
  6082. ** <ul>
  6083. ** <li> SQLITE_MUTEX_PTHREADS
  6084. ** <li> SQLITE_MUTEX_W32
  6085. ** <li> SQLITE_MUTEX_NOOP
  6086. ** </ul>
  6087. **
  6088. ** The SQLITE_MUTEX_NOOP implementation is a set of routines
  6089. ** that does no real locking and is appropriate for use in
  6090. ** a single-threaded application. The SQLITE_MUTEX_PTHREADS and
  6091. ** SQLITE_MUTEX_W32 implementations are appropriate for use on Unix
  6092. ** and Windows.
  6093. **
  6094. ** If SQLite is compiled with the SQLITE_MUTEX_APPDEF preprocessor
  6095. ** macro defined (with "-DSQLITE_MUTEX_APPDEF=1"), then no mutex
  6096. ** implementation is included with the library. In this case the
  6097. ** application must supply a custom mutex implementation using the
  6098. ** [SQLITE_CONFIG_MUTEX] option of the sqlite3_config() function
  6099. ** before calling sqlite3_initialize() or any other public sqlite3_
  6100. ** function that calls sqlite3_initialize().
  6101. **
  6102. ** ^The sqlite3_mutex_alloc() routine allocates a new
  6103. ** mutex and returns a pointer to it. ^The sqlite3_mutex_alloc()
  6104. ** routine returns NULL if it is unable to allocate the requested
  6105. ** mutex. The argument to sqlite3_mutex_alloc() must one of these
  6106. ** integer constants:
  6107. **
  6108. ** <ul>
  6109. ** <li> SQLITE_MUTEX_FAST
  6110. ** <li> SQLITE_MUTEX_RECURSIVE
  6111. ** <li> SQLITE_MUTEX_STATIC_MASTER
  6112. ** <li> SQLITE_MUTEX_STATIC_MEM
  6113. ** <li> SQLITE_MUTEX_STATIC_OPEN
  6114. ** <li> SQLITE_MUTEX_STATIC_PRNG
  6115. ** <li> SQLITE_MUTEX_STATIC_LRU
  6116. ** <li> SQLITE_MUTEX_STATIC_PMEM
  6117. ** <li> SQLITE_MUTEX_STATIC_APP1
  6118. ** <li> SQLITE_MUTEX_STATIC_APP2
  6119. ** <li> SQLITE_MUTEX_STATIC_APP3
  6120. ** </ul>
  6121. **
  6122. ** ^The first two constants (SQLITE_MUTEX_FAST and SQLITE_MUTEX_RECURSIVE)
  6123. ** cause sqlite3_mutex_alloc() to create
  6124. ** a new mutex. ^The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
  6125. ** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
  6126. ** The mutex implementation does not need to make a distinction
  6127. ** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
  6128. ** not want to. SQLite will only request a recursive mutex in
  6129. ** cases where it really needs one. If a faster non-recursive mutex
  6130. ** implementation is available on the host platform, the mutex subsystem
  6131. ** might return such a mutex in response to SQLITE_MUTEX_FAST.
  6132. **
  6133. ** ^The other allowed parameters to sqlite3_mutex_alloc() (anything other
  6134. ** than SQLITE_MUTEX_FAST and SQLITE_MUTEX_RECURSIVE) each return
  6135. ** a pointer to a static preexisting mutex. ^Nine static mutexes are
  6136. ** used by the current version of SQLite. Future versions of SQLite
  6137. ** may add additional static mutexes. Static mutexes are for internal
  6138. ** use by SQLite only. Applications that use SQLite mutexes should
  6139. ** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
  6140. ** SQLITE_MUTEX_RECURSIVE.
  6141. **
  6142. ** ^Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
  6143. ** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
  6144. ** returns a different mutex on every call. ^For the static
  6145. ** mutex types, the same mutex is returned on every call that has
  6146. ** the same type number.
  6147. **
  6148. ** ^The sqlite3_mutex_free() routine deallocates a previously
  6149. ** allocated dynamic mutex. Attempting to deallocate a static
  6150. ** mutex results in undefined behavior.
  6151. **
  6152. ** ^The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
  6153. ** to enter a mutex. ^If another thread is already within the mutex,
  6154. ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
  6155. ** SQLITE_BUSY. ^The sqlite3_mutex_try() interface returns [SQLITE_OK]
  6156. ** upon successful entry. ^(Mutexes created using
  6157. ** SQLITE_MUTEX_RECURSIVE can be entered multiple times by the same thread.
  6158. ** In such cases, the
  6159. ** mutex must be exited an equal number of times before another thread
  6160. ** can enter.)^ If the same thread tries to enter any mutex other
  6161. ** than an SQLITE_MUTEX_RECURSIVE more than once, the behavior is undefined.
  6162. **
  6163. ** ^(Some systems (for example, Windows 95) do not support the operation
  6164. ** implemented by sqlite3_mutex_try(). On those systems, sqlite3_mutex_try()
  6165. ** will always return SQLITE_BUSY. The SQLite core only ever uses
  6166. ** sqlite3_mutex_try() as an optimization so this is acceptable
  6167. ** behavior.)^
  6168. **
  6169. ** ^The sqlite3_mutex_leave() routine exits a mutex that was
  6170. ** previously entered by the same thread. The behavior
  6171. ** is undefined if the mutex is not currently entered by the
  6172. ** calling thread or is not currently allocated.
  6173. **
  6174. ** ^If the argument to sqlite3_mutex_enter(), sqlite3_mutex_try(), or
  6175. ** sqlite3_mutex_leave() is a NULL pointer, then all three routines
  6176. ** behave as no-ops.
  6177. **
  6178. ** See also: [sqlite3_mutex_held()] and [sqlite3_mutex_notheld()].
  6179. */
  6180. SQLITE_API sqlite3_mutex *SQLITE_STDCALL sqlite3_mutex_alloc(int);
  6181. SQLITE_API void SQLITE_STDCALL sqlite3_mutex_free(sqlite3_mutex*);
  6182. SQLITE_API void SQLITE_STDCALL sqlite3_mutex_enter(sqlite3_mutex*);
  6183. SQLITE_API int SQLITE_STDCALL sqlite3_mutex_try(sqlite3_mutex*);
  6184. SQLITE_API void SQLITE_STDCALL sqlite3_mutex_leave(sqlite3_mutex*);
  6185. /*
  6186. ** CAPI3REF: Mutex Methods Object
  6187. **
  6188. ** An instance of this structure defines the low-level routines
  6189. ** used to allocate and use mutexes.
  6190. **
  6191. ** Usually, the default mutex implementations provided by SQLite are
  6192. ** sufficient, however the application has the option of substituting a custom
  6193. ** implementation for specialized deployments or systems for which SQLite
  6194. ** does not provide a suitable implementation. In this case, the application
  6195. ** creates and populates an instance of this structure to pass
  6196. ** to sqlite3_config() along with the [SQLITE_CONFIG_MUTEX] option.
  6197. ** Additionally, an instance of this structure can be used as an
  6198. ** output variable when querying the system for the current mutex
  6199. ** implementation, using the [SQLITE_CONFIG_GETMUTEX] option.
  6200. **
  6201. ** ^The xMutexInit method defined by this structure is invoked as
  6202. ** part of system initialization by the sqlite3_initialize() function.
  6203. ** ^The xMutexInit routine is called by SQLite exactly once for each
  6204. ** effective call to [sqlite3_initialize()].
  6205. **
  6206. ** ^The xMutexEnd method defined by this structure is invoked as
  6207. ** part of system shutdown by the sqlite3_shutdown() function. The
  6208. ** implementation of this method is expected to release all outstanding
  6209. ** resources obtained by the mutex methods implementation, especially
  6210. ** those obtained by the xMutexInit method. ^The xMutexEnd()
  6211. ** interface is invoked exactly once for each call to [sqlite3_shutdown()].
  6212. **
  6213. ** ^(The remaining seven methods defined by this structure (xMutexAlloc,
  6214. ** xMutexFree, xMutexEnter, xMutexTry, xMutexLeave, xMutexHeld and
  6215. ** xMutexNotheld) implement the following interfaces (respectively):
  6216. **
  6217. ** <ul>
  6218. ** <li> [sqlite3_mutex_alloc()] </li>
  6219. ** <li> [sqlite3_mutex_free()] </li>
  6220. ** <li> [sqlite3_mutex_enter()] </li>
  6221. ** <li> [sqlite3_mutex_try()] </li>
  6222. ** <li> [sqlite3_mutex_leave()] </li>
  6223. ** <li> [sqlite3_mutex_held()] </li>
  6224. ** <li> [sqlite3_mutex_notheld()] </li>
  6225. ** </ul>)^
  6226. **
  6227. ** The only difference is that the public sqlite3_XXX functions enumerated
  6228. ** above silently ignore any invocations that pass a NULL pointer instead
  6229. ** of a valid mutex handle. The implementations of the methods defined
  6230. ** by this structure are not required to handle this case, the results
  6231. ** of passing a NULL pointer instead of a valid mutex handle are undefined
  6232. ** (i.e. it is acceptable to provide an implementation that segfaults if
  6233. ** it is passed a NULL pointer).
  6234. **
  6235. ** The xMutexInit() method must be threadsafe. It must be harmless to
  6236. ** invoke xMutexInit() multiple times within the same process and without
  6237. ** intervening calls to xMutexEnd(). Second and subsequent calls to
  6238. ** xMutexInit() must be no-ops.
  6239. **
  6240. ** xMutexInit() must not use SQLite memory allocation ([sqlite3_malloc()]
  6241. ** and its associates). Similarly, xMutexAlloc() must not use SQLite memory
  6242. ** allocation for a static mutex. ^However xMutexAlloc() may use SQLite
  6243. ** memory allocation for a fast or recursive mutex.
  6244. **
  6245. ** ^SQLite will invoke the xMutexEnd() method when [sqlite3_shutdown()] is
  6246. ** called, but only if the prior call to xMutexInit returned SQLITE_OK.
  6247. ** If xMutexInit fails in any way, it is expected to clean up after itself
  6248. ** prior to returning.
  6249. */
  6250. typedef struct sqlite3_mutex_methods sqlite3_mutex_methods;
  6251. struct sqlite3_mutex_methods {
  6252. int (*xMutexInit)(void);
  6253. int (*xMutexEnd)(void);
  6254. sqlite3_mutex *(*xMutexAlloc)(int);
  6255. void (*xMutexFree)(sqlite3_mutex *);
  6256. void (*xMutexEnter)(sqlite3_mutex *);
  6257. int (*xMutexTry)(sqlite3_mutex *);
  6258. void (*xMutexLeave)(sqlite3_mutex *);
  6259. int (*xMutexHeld)(sqlite3_mutex *);
  6260. int (*xMutexNotheld)(sqlite3_mutex *);
  6261. };
  6262. /*
  6263. ** CAPI3REF: Mutex Verification Routines
  6264. **
  6265. ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routines
  6266. ** are intended for use inside assert() statements. The SQLite core
  6267. ** never uses these routines except inside an assert() and applications
  6268. ** are advised to follow the lead of the core. The SQLite core only
  6269. ** provides implementations for these routines when it is compiled
  6270. ** with the SQLITE_DEBUG flag. External mutex implementations
  6271. ** are only required to provide these routines if SQLITE_DEBUG is
  6272. ** defined and if NDEBUG is not defined.
  6273. **
  6274. ** These routines should return true if the mutex in their argument
  6275. ** is held or not held, respectively, by the calling thread.
  6276. **
  6277. ** The implementation is not required to provide versions of these
  6278. ** routines that actually work. If the implementation does not provide working
  6279. ** versions of these routines, it should at least provide stubs that always
  6280. ** return true so that one does not get spurious assertion failures.
  6281. **
  6282. ** If the argument to sqlite3_mutex_held() is a NULL pointer then
  6283. ** the routine should return 1. This seems counter-intuitive since
  6284. ** clearly the mutex cannot be held if it does not exist. But
  6285. ** the reason the mutex does not exist is because the build is not
  6286. ** using mutexes. And we do not want the assert() containing the
  6287. ** call to sqlite3_mutex_held() to fail, so a non-zero return is
  6288. ** the appropriate thing to do. The sqlite3_mutex_notheld()
  6289. ** interface should also return 1 when given a NULL pointer.
  6290. */
  6291. #ifndef NDEBUG
  6292. SQLITE_API int SQLITE_STDCALL sqlite3_mutex_held(sqlite3_mutex*);
  6293. SQLITE_API int SQLITE_STDCALL sqlite3_mutex_notheld(sqlite3_mutex*);
  6294. #endif
  6295. /*
  6296. ** CAPI3REF: Mutex Types
  6297. **
  6298. ** The [sqlite3_mutex_alloc()] interface takes a single argument
  6299. ** which is one of these integer constants.
  6300. **
  6301. ** The set of static mutexes may change from one SQLite release to the
  6302. ** next. Applications that override the built-in mutex logic must be
  6303. ** prepared to accommodate additional static mutexes.
  6304. */
  6305. #define SQLITE_MUTEX_FAST 0
  6306. #define SQLITE_MUTEX_RECURSIVE 1
  6307. #define SQLITE_MUTEX_STATIC_MASTER 2
  6308. #define SQLITE_MUTEX_STATIC_MEM 3 /* sqlite3_malloc() */
  6309. #define SQLITE_MUTEX_STATIC_MEM2 4 /* NOT USED */
  6310. #define SQLITE_MUTEX_STATIC_OPEN 4 /* sqlite3BtreeOpen() */
  6311. #define SQLITE_MUTEX_STATIC_PRNG 5 /* sqlite3_random() */
  6312. #define SQLITE_MUTEX_STATIC_LRU 6 /* lru page list */
  6313. #define SQLITE_MUTEX_STATIC_LRU2 7 /* NOT USED */
  6314. #define SQLITE_MUTEX_STATIC_PMEM 7 /* sqlite3PageMalloc() */
  6315. #define SQLITE_MUTEX_STATIC_APP1 8 /* For use by application */
  6316. #define SQLITE_MUTEX_STATIC_APP2 9 /* For use by application */
  6317. #define SQLITE_MUTEX_STATIC_APP3 10 /* For use by application */
  6318. /*
  6319. ** CAPI3REF: Retrieve the mutex for a database connection
  6320. ** METHOD: sqlite3
  6321. **
  6322. ** ^This interface returns a pointer the [sqlite3_mutex] object that
  6323. ** serializes access to the [database connection] given in the argument
  6324. ** when the [threading mode] is Serialized.
  6325. ** ^If the [threading mode] is Single-thread or Multi-thread then this
  6326. ** routine returns a NULL pointer.
  6327. */
  6328. SQLITE_API sqlite3_mutex *SQLITE_STDCALL sqlite3_db_mutex(sqlite3*);
  6329. /*
  6330. ** CAPI3REF: Low-Level Control Of Database Files
  6331. ** METHOD: sqlite3
  6332. **
  6333. ** ^The [sqlite3_file_control()] interface makes a direct call to the
  6334. ** xFileControl method for the [sqlite3_io_methods] object associated
  6335. ** with a particular database identified by the second argument. ^The
  6336. ** name of the database is "main" for the main database or "temp" for the
  6337. ** TEMP database, or the name that appears after the AS keyword for
  6338. ** databases that are added using the [ATTACH] SQL command.
  6339. ** ^A NULL pointer can be used in place of "main" to refer to the
  6340. ** main database file.
  6341. ** ^The third and fourth parameters to this routine
  6342. ** are passed directly through to the second and third parameters of
  6343. ** the xFileControl method. ^The return value of the xFileControl
  6344. ** method becomes the return value of this routine.
  6345. **
  6346. ** ^The SQLITE_FCNTL_FILE_POINTER value for the op parameter causes
  6347. ** a pointer to the underlying [sqlite3_file] object to be written into
  6348. ** the space pointed to by the 4th parameter. ^The SQLITE_FCNTL_FILE_POINTER
  6349. ** case is a short-circuit path which does not actually invoke the
  6350. ** underlying sqlite3_io_methods.xFileControl method.
  6351. **
  6352. ** ^If the second parameter (zDbName) does not match the name of any
  6353. ** open database file, then SQLITE_ERROR is returned. ^This error
  6354. ** code is not remembered and will not be recalled by [sqlite3_errcode()]
  6355. ** or [sqlite3_errmsg()]. The underlying xFileControl method might
  6356. ** also return SQLITE_ERROR. There is no way to distinguish between
  6357. ** an incorrect zDbName and an SQLITE_ERROR return from the underlying
  6358. ** xFileControl method.
  6359. **
  6360. ** See also: [SQLITE_FCNTL_LOCKSTATE]
  6361. */
  6362. SQLITE_API int SQLITE_STDCALL sqlite3_file_control(sqlite3*, const char *zDbName, int op, void*);
  6363. /*
  6364. ** CAPI3REF: Testing Interface
  6365. **
  6366. ** ^The sqlite3_test_control() interface is used to read out internal
  6367. ** state of SQLite and to inject faults into SQLite for testing
  6368. ** purposes. ^The first parameter is an operation code that determines
  6369. ** the number, meaning, and operation of all subsequent parameters.
  6370. **
  6371. ** This interface is not for use by applications. It exists solely
  6372. ** for verifying the correct operation of the SQLite library. Depending
  6373. ** on how the SQLite library is compiled, this interface might not exist.
  6374. **
  6375. ** The details of the operation codes, their meanings, the parameters
  6376. ** they take, and what they do are all subject to change without notice.
  6377. ** Unlike most of the SQLite API, this function is not guaranteed to
  6378. ** operate consistently from one release to the next.
  6379. */
  6380. SQLITE_API int SQLITE_CDECL sqlite3_test_control(int op, ...);
  6381. /*
  6382. ** CAPI3REF: Testing Interface Operation Codes
  6383. **
  6384. ** These constants are the valid operation code parameters used
  6385. ** as the first argument to [sqlite3_test_control()].
  6386. **
  6387. ** These parameters and their meanings are subject to change
  6388. ** without notice. These values are for testing purposes only.
  6389. ** Applications should not use any of these parameters or the
  6390. ** [sqlite3_test_control()] interface.
  6391. */
  6392. #define SQLITE_TESTCTRL_FIRST 5
  6393. #define SQLITE_TESTCTRL_PRNG_SAVE 5
  6394. #define SQLITE_TESTCTRL_PRNG_RESTORE 6
  6395. #define SQLITE_TESTCTRL_PRNG_RESET 7
  6396. #define SQLITE_TESTCTRL_BITVEC_TEST 8
  6397. #define SQLITE_TESTCTRL_FAULT_INSTALL 9
  6398. #define SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS 10
  6399. #define SQLITE_TESTCTRL_PENDING_BYTE 11
  6400. #define SQLITE_TESTCTRL_ASSERT 12
  6401. #define SQLITE_TESTCTRL_ALWAYS 13
  6402. #define SQLITE_TESTCTRL_RESERVE 14
  6403. #define SQLITE_TESTCTRL_OPTIMIZATIONS 15
  6404. #define SQLITE_TESTCTRL_ISKEYWORD 16
  6405. #define SQLITE_TESTCTRL_SCRATCHMALLOC 17
  6406. #define SQLITE_TESTCTRL_LOCALTIME_FAULT 18
  6407. #define SQLITE_TESTCTRL_EXPLAIN_STMT 19 /* NOT USED */
  6408. #define SQLITE_TESTCTRL_NEVER_CORRUPT 20
  6409. #define SQLITE_TESTCTRL_VDBE_COVERAGE 21
  6410. #define SQLITE_TESTCTRL_BYTEORDER 22
  6411. #define SQLITE_TESTCTRL_ISINIT 23
  6412. #define SQLITE_TESTCTRL_SORTER_MMAP 24
  6413. #define SQLITE_TESTCTRL_IMPOSTER 25
  6414. #define SQLITE_TESTCTRL_LAST 25
  6415. /*
  6416. ** CAPI3REF: SQLite Runtime Status
  6417. **
  6418. ** ^These interfaces are used to retrieve runtime status information
  6419. ** about the performance of SQLite, and optionally to reset various
  6420. ** highwater marks. ^The first argument is an integer code for
  6421. ** the specific parameter to measure. ^(Recognized integer codes
  6422. ** are of the form [status parameters | SQLITE_STATUS_...].)^
  6423. ** ^The current value of the parameter is returned into *pCurrent.
  6424. ** ^The highest recorded value is returned in *pHighwater. ^If the
  6425. ** resetFlag is true, then the highest record value is reset after
  6426. ** *pHighwater is written. ^(Some parameters do not record the highest
  6427. ** value. For those parameters
  6428. ** nothing is written into *pHighwater and the resetFlag is ignored.)^
  6429. ** ^(Other parameters record only the highwater mark and not the current
  6430. ** value. For these latter parameters nothing is written into *pCurrent.)^
  6431. **
  6432. ** ^The sqlite3_status() and sqlite3_status64() routines return
  6433. ** SQLITE_OK on success and a non-zero [error code] on failure.
  6434. **
  6435. ** If either the current value or the highwater mark is too large to
  6436. ** be represented by a 32-bit integer, then the values returned by
  6437. ** sqlite3_status() are undefined.
  6438. **
  6439. ** See also: [sqlite3_db_status()]
  6440. */
  6441. SQLITE_API int SQLITE_STDCALL sqlite3_status(int op, int *pCurrent, int *pHighwater, int resetFlag);
  6442. SQLITE_API int SQLITE_STDCALL sqlite3_status64(
  6443. int op,
  6444. sqlite3_int64 *pCurrent,
  6445. sqlite3_int64 *pHighwater,
  6446. int resetFlag
  6447. );
  6448. /*
  6449. ** CAPI3REF: Status Parameters
  6450. ** KEYWORDS: {status parameters}
  6451. **
  6452. ** These integer constants designate various run-time status parameters
  6453. ** that can be returned by [sqlite3_status()].
  6454. **
  6455. ** <dl>
  6456. ** [[SQLITE_STATUS_MEMORY_USED]] ^(<dt>SQLITE_STATUS_MEMORY_USED</dt>
  6457. ** <dd>This parameter is the current amount of memory checked out
  6458. ** using [sqlite3_malloc()], either directly or indirectly. The
  6459. ** figure includes calls made to [sqlite3_malloc()] by the application
  6460. ** and internal memory usage by the SQLite library. Scratch memory
  6461. ** controlled by [SQLITE_CONFIG_SCRATCH] and auxiliary page-cache
  6462. ** memory controlled by [SQLITE_CONFIG_PAGECACHE] is not included in
  6463. ** this parameter. The amount returned is the sum of the allocation
  6464. ** sizes as reported by the xSize method in [sqlite3_mem_methods].</dd>)^
  6465. **
  6466. ** [[SQLITE_STATUS_MALLOC_SIZE]] ^(<dt>SQLITE_STATUS_MALLOC_SIZE</dt>
  6467. ** <dd>This parameter records the largest memory allocation request
  6468. ** handed to [sqlite3_malloc()] or [sqlite3_realloc()] (or their
  6469. ** internal equivalents). Only the value returned in the
  6470. ** *pHighwater parameter to [sqlite3_status()] is of interest.
  6471. ** The value written into the *pCurrent parameter is undefined.</dd>)^
  6472. **
  6473. ** [[SQLITE_STATUS_MALLOC_COUNT]] ^(<dt>SQLITE_STATUS_MALLOC_COUNT</dt>
  6474. ** <dd>This parameter records the number of separate memory allocations
  6475. ** currently checked out.</dd>)^
  6476. **
  6477. ** [[SQLITE_STATUS_PAGECACHE_USED]] ^(<dt>SQLITE_STATUS_PAGECACHE_USED</dt>
  6478. ** <dd>This parameter returns the number of pages used out of the
  6479. ** [pagecache memory allocator] that was configured using
  6480. ** [SQLITE_CONFIG_PAGECACHE]. The
  6481. ** value returned is in pages, not in bytes.</dd>)^
  6482. **
  6483. ** [[SQLITE_STATUS_PAGECACHE_OVERFLOW]]
  6484. ** ^(<dt>SQLITE_STATUS_PAGECACHE_OVERFLOW</dt>
  6485. ** <dd>This parameter returns the number of bytes of page cache
  6486. ** allocation which could not be satisfied by the [SQLITE_CONFIG_PAGECACHE]
  6487. ** buffer and where forced to overflow to [sqlite3_malloc()]. The
  6488. ** returned value includes allocations that overflowed because they
  6489. ** where too large (they were larger than the "sz" parameter to
  6490. ** [SQLITE_CONFIG_PAGECACHE]) and allocations that overflowed because
  6491. ** no space was left in the page cache.</dd>)^
  6492. **
  6493. ** [[SQLITE_STATUS_PAGECACHE_SIZE]] ^(<dt>SQLITE_STATUS_PAGECACHE_SIZE</dt>
  6494. ** <dd>This parameter records the largest memory allocation request
  6495. ** handed to [pagecache memory allocator]. Only the value returned in the
  6496. ** *pHighwater parameter to [sqlite3_status()] is of interest.
  6497. ** The value written into the *pCurrent parameter is undefined.</dd>)^
  6498. **
  6499. ** [[SQLITE_STATUS_SCRATCH_USED]] ^(<dt>SQLITE_STATUS_SCRATCH_USED</dt>
  6500. ** <dd>This parameter returns the number of allocations used out of the
  6501. ** [scratch memory allocator] configured using
  6502. ** [SQLITE_CONFIG_SCRATCH]. The value returned is in allocations, not
  6503. ** in bytes. Since a single thread may only have one scratch allocation
  6504. ** outstanding at time, this parameter also reports the number of threads
  6505. ** using scratch memory at the same time.</dd>)^
  6506. **
  6507. ** [[SQLITE_STATUS_SCRATCH_OVERFLOW]] ^(<dt>SQLITE_STATUS_SCRATCH_OVERFLOW</dt>
  6508. ** <dd>This parameter returns the number of bytes of scratch memory
  6509. ** allocation which could not be satisfied by the [SQLITE_CONFIG_SCRATCH]
  6510. ** buffer and where forced to overflow to [sqlite3_malloc()]. The values
  6511. ** returned include overflows because the requested allocation was too
  6512. ** larger (that is, because the requested allocation was larger than the
  6513. ** "sz" parameter to [SQLITE_CONFIG_SCRATCH]) and because no scratch buffer
  6514. ** slots were available.
  6515. ** </dd>)^
  6516. **
  6517. ** [[SQLITE_STATUS_SCRATCH_SIZE]] ^(<dt>SQLITE_STATUS_SCRATCH_SIZE</dt>
  6518. ** <dd>This parameter records the largest memory allocation request
  6519. ** handed to [scratch memory allocator]. Only the value returned in the
  6520. ** *pHighwater parameter to [sqlite3_status()] is of interest.
  6521. ** The value written into the *pCurrent parameter is undefined.</dd>)^
  6522. **
  6523. ** [[SQLITE_STATUS_PARSER_STACK]] ^(<dt>SQLITE_STATUS_PARSER_STACK</dt>
  6524. ** <dd>This parameter records the deepest parser stack. It is only
  6525. ** meaningful if SQLite is compiled with [YYTRACKMAXSTACKDEPTH].</dd>)^
  6526. ** </dl>
  6527. **
  6528. ** New status parameters may be added from time to time.
  6529. */
  6530. #define SQLITE_STATUS_MEMORY_USED 0
  6531. #define SQLITE_STATUS_PAGECACHE_USED 1
  6532. #define SQLITE_STATUS_PAGECACHE_OVERFLOW 2
  6533. #define SQLITE_STATUS_SCRATCH_USED 3
  6534. #define SQLITE_STATUS_SCRATCH_OVERFLOW 4
  6535. #define SQLITE_STATUS_MALLOC_SIZE 5
  6536. #define SQLITE_STATUS_PARSER_STACK 6
  6537. #define SQLITE_STATUS_PAGECACHE_SIZE 7
  6538. #define SQLITE_STATUS_SCRATCH_SIZE 8
  6539. #define SQLITE_STATUS_MALLOC_COUNT 9
  6540. /*
  6541. ** CAPI3REF: Database Connection Status
  6542. ** METHOD: sqlite3
  6543. **
  6544. ** ^This interface is used to retrieve runtime status information
  6545. ** about a single [database connection]. ^The first argument is the
  6546. ** database connection object to be interrogated. ^The second argument
  6547. ** is an integer constant, taken from the set of
  6548. ** [SQLITE_DBSTATUS options], that
  6549. ** determines the parameter to interrogate. The set of
  6550. ** [SQLITE_DBSTATUS options] is likely
  6551. ** to grow in future releases of SQLite.
  6552. **
  6553. ** ^The current value of the requested parameter is written into *pCur
  6554. ** and the highest instantaneous value is written into *pHiwtr. ^If
  6555. ** the resetFlg is true, then the highest instantaneous value is
  6556. ** reset back down to the current value.
  6557. **
  6558. ** ^The sqlite3_db_status() routine returns SQLITE_OK on success and a
  6559. ** non-zero [error code] on failure.
  6560. **
  6561. ** See also: [sqlite3_status()] and [sqlite3_stmt_status()].
  6562. */
  6563. SQLITE_API int SQLITE_STDCALL sqlite3_db_status(sqlite3*, int op, int *pCur, int *pHiwtr, int resetFlg);
  6564. /*
  6565. ** CAPI3REF: Status Parameters for database connections
  6566. ** KEYWORDS: {SQLITE_DBSTATUS options}
  6567. **
  6568. ** These constants are the available integer "verbs" that can be passed as
  6569. ** the second argument to the [sqlite3_db_status()] interface.
  6570. **
  6571. ** New verbs may be added in future releases of SQLite. Existing verbs
  6572. ** might be discontinued. Applications should check the return code from
  6573. ** [sqlite3_db_status()] to make sure that the call worked.
  6574. ** The [sqlite3_db_status()] interface will return a non-zero error code
  6575. ** if a discontinued or unsupported verb is invoked.
  6576. **
  6577. ** <dl>
  6578. ** [[SQLITE_DBSTATUS_LOOKASIDE_USED]] ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_USED</dt>
  6579. ** <dd>This parameter returns the number of lookaside memory slots currently
  6580. ** checked out.</dd>)^
  6581. **
  6582. ** [[SQLITE_DBSTATUS_LOOKASIDE_HIT]] ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_HIT</dt>
  6583. ** <dd>This parameter returns the number malloc attempts that were
  6584. ** satisfied using lookaside memory. Only the high-water value is meaningful;
  6585. ** the current value is always zero.)^
  6586. **
  6587. ** [[SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE]]
  6588. ** ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE</dt>
  6589. ** <dd>This parameter returns the number malloc attempts that might have
  6590. ** been satisfied using lookaside memory but failed due to the amount of
  6591. ** memory requested being larger than the lookaside slot size.
  6592. ** Only the high-water value is meaningful;
  6593. ** the current value is always zero.)^
  6594. **
  6595. ** [[SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL]]
  6596. ** ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL</dt>
  6597. ** <dd>This parameter returns the number malloc attempts that might have
  6598. ** been satisfied using lookaside memory but failed due to all lookaside
  6599. ** memory already being in use.
  6600. ** Only the high-water value is meaningful;
  6601. ** the current value is always zero.)^
  6602. **
  6603. ** [[SQLITE_DBSTATUS_CACHE_USED]] ^(<dt>SQLITE_DBSTATUS_CACHE_USED</dt>
  6604. ** <dd>This parameter returns the approximate number of bytes of heap
  6605. ** memory used by all pager caches associated with the database connection.)^
  6606. ** ^The highwater mark associated with SQLITE_DBSTATUS_CACHE_USED is always 0.
  6607. **
  6608. ** [[SQLITE_DBSTATUS_SCHEMA_USED]] ^(<dt>SQLITE_DBSTATUS_SCHEMA_USED</dt>
  6609. ** <dd>This parameter returns the approximate number of bytes of heap
  6610. ** memory used to store the schema for all databases associated
  6611. ** with the connection - main, temp, and any [ATTACH]-ed databases.)^
  6612. ** ^The full amount of memory used by the schemas is reported, even if the
  6613. ** schema memory is shared with other database connections due to
  6614. ** [shared cache mode] being enabled.
  6615. ** ^The highwater mark associated with SQLITE_DBSTATUS_SCHEMA_USED is always 0.
  6616. **
  6617. ** [[SQLITE_DBSTATUS_STMT_USED]] ^(<dt>SQLITE_DBSTATUS_STMT_USED</dt>
  6618. ** <dd>This parameter returns the approximate number of bytes of heap
  6619. ** and lookaside memory used by all prepared statements associated with
  6620. ** the database connection.)^
  6621. ** ^The highwater mark associated with SQLITE_DBSTATUS_STMT_USED is always 0.
  6622. ** </dd>
  6623. **
  6624. ** [[SQLITE_DBSTATUS_CACHE_HIT]] ^(<dt>SQLITE_DBSTATUS_CACHE_HIT</dt>
  6625. ** <dd>This parameter returns the number of pager cache hits that have
  6626. ** occurred.)^ ^The highwater mark associated with SQLITE_DBSTATUS_CACHE_HIT
  6627. ** is always 0.
  6628. ** </dd>
  6629. **
  6630. ** [[SQLITE_DBSTATUS_CACHE_MISS]] ^(<dt>SQLITE_DBSTATUS_CACHE_MISS</dt>
  6631. ** <dd>This parameter returns the number of pager cache misses that have
  6632. ** occurred.)^ ^The highwater mark associated with SQLITE_DBSTATUS_CACHE_MISS
  6633. ** is always 0.
  6634. ** </dd>
  6635. **
  6636. ** [[SQLITE_DBSTATUS_CACHE_WRITE]] ^(<dt>SQLITE_DBSTATUS_CACHE_WRITE</dt>
  6637. ** <dd>This parameter returns the number of dirty cache entries that have
  6638. ** been written to disk. Specifically, the number of pages written to the
  6639. ** wal file in wal mode databases, or the number of pages written to the
  6640. ** database file in rollback mode databases. Any pages written as part of
  6641. ** transaction rollback or database recovery operations are not included.
  6642. ** If an IO or other error occurs while writing a page to disk, the effect
  6643. ** on subsequent SQLITE_DBSTATUS_CACHE_WRITE requests is undefined.)^ ^The
  6644. ** highwater mark associated with SQLITE_DBSTATUS_CACHE_WRITE is always 0.
  6645. ** </dd>
  6646. **
  6647. ** [[SQLITE_DBSTATUS_DEFERRED_FKS]] ^(<dt>SQLITE_DBSTATUS_DEFERRED_FKS</dt>
  6648. ** <dd>This parameter returns zero for the current value if and only if
  6649. ** all foreign key constraints (deferred or immediate) have been
  6650. ** resolved.)^ ^The highwater mark is always 0.
  6651. ** </dd>
  6652. ** </dl>
  6653. */
  6654. #define SQLITE_DBSTATUS_LOOKASIDE_USED 0
  6655. #define SQLITE_DBSTATUS_CACHE_USED 1
  6656. #define SQLITE_DBSTATUS_SCHEMA_USED 2
  6657. #define SQLITE_DBSTATUS_STMT_USED 3
  6658. #define SQLITE_DBSTATUS_LOOKASIDE_HIT 4
  6659. #define SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE 5
  6660. #define SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL 6
  6661. #define SQLITE_DBSTATUS_CACHE_HIT 7
  6662. #define SQLITE_DBSTATUS_CACHE_MISS 8
  6663. #define SQLITE_DBSTATUS_CACHE_WRITE 9
  6664. #define SQLITE_DBSTATUS_DEFERRED_FKS 10
  6665. #define SQLITE_DBSTATUS_MAX 10 /* Largest defined DBSTATUS */
  6666. /*
  6667. ** CAPI3REF: Prepared Statement Status
  6668. ** METHOD: sqlite3_stmt
  6669. **
  6670. ** ^(Each prepared statement maintains various
  6671. ** [SQLITE_STMTSTATUS counters] that measure the number
  6672. ** of times it has performed specific operations.)^ These counters can
  6673. ** be used to monitor the performance characteristics of the prepared
  6674. ** statements. For example, if the number of table steps greatly exceeds
  6675. ** the number of table searches or result rows, that would tend to indicate
  6676. ** that the prepared statement is using a full table scan rather than
  6677. ** an index.
  6678. **
  6679. ** ^(This interface is used to retrieve and reset counter values from
  6680. ** a [prepared statement]. The first argument is the prepared statement
  6681. ** object to be interrogated. The second argument
  6682. ** is an integer code for a specific [SQLITE_STMTSTATUS counter]
  6683. ** to be interrogated.)^
  6684. ** ^The current value of the requested counter is returned.
  6685. ** ^If the resetFlg is true, then the counter is reset to zero after this
  6686. ** interface call returns.
  6687. **
  6688. ** See also: [sqlite3_status()] and [sqlite3_db_status()].
  6689. */
  6690. SQLITE_API int SQLITE_STDCALL sqlite3_stmt_status(sqlite3_stmt*, int op,int resetFlg);
  6691. /*
  6692. ** CAPI3REF: Status Parameters for prepared statements
  6693. ** KEYWORDS: {SQLITE_STMTSTATUS counter} {SQLITE_STMTSTATUS counters}
  6694. **
  6695. ** These preprocessor macros define integer codes that name counter
  6696. ** values associated with the [sqlite3_stmt_status()] interface.
  6697. ** The meanings of the various counters are as follows:
  6698. **
  6699. ** <dl>
  6700. ** [[SQLITE_STMTSTATUS_FULLSCAN_STEP]] <dt>SQLITE_STMTSTATUS_FULLSCAN_STEP</dt>
  6701. ** <dd>^This is the number of times that SQLite has stepped forward in
  6702. ** a table as part of a full table scan. Large numbers for this counter
  6703. ** may indicate opportunities for performance improvement through
  6704. ** careful use of indices.</dd>
  6705. **
  6706. ** [[SQLITE_STMTSTATUS_SORT]] <dt>SQLITE_STMTSTATUS_SORT</dt>
  6707. ** <dd>^This is the number of sort operations that have occurred.
  6708. ** A non-zero value in this counter may indicate an opportunity to
  6709. ** improvement performance through careful use of indices.</dd>
  6710. **
  6711. ** [[SQLITE_STMTSTATUS_AUTOINDEX]] <dt>SQLITE_STMTSTATUS_AUTOINDEX</dt>
  6712. ** <dd>^This is the number of rows inserted into transient indices that
  6713. ** were created automatically in order to help joins run faster.
  6714. ** A non-zero value in this counter may indicate an opportunity to
  6715. ** improvement performance by adding permanent indices that do not
  6716. ** need to be reinitialized each time the statement is run.</dd>
  6717. **
  6718. ** [[SQLITE_STMTSTATUS_VM_STEP]] <dt>SQLITE_STMTSTATUS_VM_STEP</dt>
  6719. ** <dd>^This is the number of virtual machine operations executed
  6720. ** by the prepared statement if that number is less than or equal
  6721. ** to 2147483647. The number of virtual machine operations can be
  6722. ** used as a proxy for the total work done by the prepared statement.
  6723. ** If the number of virtual machine operations exceeds 2147483647
  6724. ** then the value returned by this statement status code is undefined.
  6725. ** </dd>
  6726. ** </dl>
  6727. */
  6728. #define SQLITE_STMTSTATUS_FULLSCAN_STEP 1
  6729. #define SQLITE_STMTSTATUS_SORT 2
  6730. #define SQLITE_STMTSTATUS_AUTOINDEX 3
  6731. #define SQLITE_STMTSTATUS_VM_STEP 4
  6732. /*
  6733. ** CAPI3REF: Custom Page Cache Object
  6734. **
  6735. ** The sqlite3_pcache type is opaque. It is implemented by
  6736. ** the pluggable module. The SQLite core has no knowledge of
  6737. ** its size or internal structure and never deals with the
  6738. ** sqlite3_pcache object except by holding and passing pointers
  6739. ** to the object.
  6740. **
  6741. ** See [sqlite3_pcache_methods2] for additional information.
  6742. */
  6743. typedef struct sqlite3_pcache sqlite3_pcache;
  6744. /*
  6745. ** CAPI3REF: Custom Page Cache Object
  6746. **
  6747. ** The sqlite3_pcache_page object represents a single page in the
  6748. ** page cache. The page cache will allocate instances of this
  6749. ** object. Various methods of the page cache use pointers to instances
  6750. ** of this object as parameters or as their return value.
  6751. **
  6752. ** See [sqlite3_pcache_methods2] for additional information.
  6753. */
  6754. typedef struct sqlite3_pcache_page sqlite3_pcache_page;
  6755. struct sqlite3_pcache_page {
  6756. void *pBuf; /* The content of the page */
  6757. void *pExtra; /* Extra information associated with the page */
  6758. };
  6759. /*
  6760. ** CAPI3REF: Application Defined Page Cache.
  6761. ** KEYWORDS: {page cache}
  6762. **
  6763. ** ^(The [sqlite3_config]([SQLITE_CONFIG_PCACHE2], ...) interface can
  6764. ** register an alternative page cache implementation by passing in an
  6765. ** instance of the sqlite3_pcache_methods2 structure.)^
  6766. ** In many applications, most of the heap memory allocated by
  6767. ** SQLite is used for the page cache.
  6768. ** By implementing a
  6769. ** custom page cache using this API, an application can better control
  6770. ** the amount of memory consumed by SQLite, the way in which
  6771. ** that memory is allocated and released, and the policies used to
  6772. ** determine exactly which parts of a database file are cached and for
  6773. ** how long.
  6774. **
  6775. ** The alternative page cache mechanism is an
  6776. ** extreme measure that is only needed by the most demanding applications.
  6777. ** The built-in page cache is recommended for most uses.
  6778. **
  6779. ** ^(The contents of the sqlite3_pcache_methods2 structure are copied to an
  6780. ** internal buffer by SQLite within the call to [sqlite3_config]. Hence
  6781. ** the application may discard the parameter after the call to
  6782. ** [sqlite3_config()] returns.)^
  6783. **
  6784. ** [[the xInit() page cache method]]
  6785. ** ^(The xInit() method is called once for each effective
  6786. ** call to [sqlite3_initialize()])^
  6787. ** (usually only once during the lifetime of the process). ^(The xInit()
  6788. ** method is passed a copy of the sqlite3_pcache_methods2.pArg value.)^
  6789. ** The intent of the xInit() method is to set up global data structures
  6790. ** required by the custom page cache implementation.
  6791. ** ^(If the xInit() method is NULL, then the
  6792. ** built-in default page cache is used instead of the application defined
  6793. ** page cache.)^
  6794. **
  6795. ** [[the xShutdown() page cache method]]
  6796. ** ^The xShutdown() method is called by [sqlite3_shutdown()].
  6797. ** It can be used to clean up
  6798. ** any outstanding resources before process shutdown, if required.
  6799. ** ^The xShutdown() method may be NULL.
  6800. **
  6801. ** ^SQLite automatically serializes calls to the xInit method,
  6802. ** so the xInit method need not be threadsafe. ^The
  6803. ** xShutdown method is only called from [sqlite3_shutdown()] so it does
  6804. ** not need to be threadsafe either. All other methods must be threadsafe
  6805. ** in multithreaded applications.
  6806. **
  6807. ** ^SQLite will never invoke xInit() more than once without an intervening
  6808. ** call to xShutdown().
  6809. **
  6810. ** [[the xCreate() page cache methods]]
  6811. ** ^SQLite invokes the xCreate() method to construct a new cache instance.
  6812. ** SQLite will typically create one cache instance for each open database file,
  6813. ** though this is not guaranteed. ^The
  6814. ** first parameter, szPage, is the size in bytes of the pages that must
  6815. ** be allocated by the cache. ^szPage will always a power of two. ^The
  6816. ** second parameter szExtra is a number of bytes of extra storage
  6817. ** associated with each page cache entry. ^The szExtra parameter will
  6818. ** a number less than 250. SQLite will use the
  6819. ** extra szExtra bytes on each page to store metadata about the underlying
  6820. ** database page on disk. The value passed into szExtra depends
  6821. ** on the SQLite version, the target platform, and how SQLite was compiled.
  6822. ** ^The third argument to xCreate(), bPurgeable, is true if the cache being
  6823. ** created will be used to cache database pages of a file stored on disk, or
  6824. ** false if it is used for an in-memory database. The cache implementation
  6825. ** does not have to do anything special based with the value of bPurgeable;
  6826. ** it is purely advisory. ^On a cache where bPurgeable is false, SQLite will
  6827. ** never invoke xUnpin() except to deliberately delete a page.
  6828. ** ^In other words, calls to xUnpin() on a cache with bPurgeable set to
  6829. ** false will always have the "discard" flag set to true.
  6830. ** ^Hence, a cache created with bPurgeable false will
  6831. ** never contain any unpinned pages.
  6832. **
  6833. ** [[the xCachesize() page cache method]]
  6834. ** ^(The xCachesize() method may be called at any time by SQLite to set the
  6835. ** suggested maximum cache-size (number of pages stored by) the cache
  6836. ** instance passed as the first argument. This is the value configured using
  6837. ** the SQLite "[PRAGMA cache_size]" command.)^ As with the bPurgeable
  6838. ** parameter, the implementation is not required to do anything with this
  6839. ** value; it is advisory only.
  6840. **
  6841. ** [[the xPagecount() page cache methods]]
  6842. ** The xPagecount() method must return the number of pages currently
  6843. ** stored in the cache, both pinned and unpinned.
  6844. **
  6845. ** [[the xFetch() page cache methods]]
  6846. ** The xFetch() method locates a page in the cache and returns a pointer to
  6847. ** an sqlite3_pcache_page object associated with that page, or a NULL pointer.
  6848. ** The pBuf element of the returned sqlite3_pcache_page object will be a
  6849. ** pointer to a buffer of szPage bytes used to store the content of a
  6850. ** single database page. The pExtra element of sqlite3_pcache_page will be
  6851. ** a pointer to the szExtra bytes of extra storage that SQLite has requested
  6852. ** for each entry in the page cache.
  6853. **
  6854. ** The page to be fetched is determined by the key. ^The minimum key value
  6855. ** is 1. After it has been retrieved using xFetch, the page is considered
  6856. ** to be "pinned".
  6857. **
  6858. ** If the requested page is already in the page cache, then the page cache
  6859. ** implementation must return a pointer to the page buffer with its content
  6860. ** intact. If the requested page is not already in the cache, then the
  6861. ** cache implementation should use the value of the createFlag
  6862. ** parameter to help it determined what action to take:
  6863. **
  6864. ** <table border=1 width=85% align=center>
  6865. ** <tr><th> createFlag <th> Behavior when page is not already in cache
  6866. ** <tr><td> 0 <td> Do not allocate a new page. Return NULL.
  6867. ** <tr><td> 1 <td> Allocate a new page if it easy and convenient to do so.
  6868. ** Otherwise return NULL.
  6869. ** <tr><td> 2 <td> Make every effort to allocate a new page. Only return
  6870. ** NULL if allocating a new page is effectively impossible.
  6871. ** </table>
  6872. **
  6873. ** ^(SQLite will normally invoke xFetch() with a createFlag of 0 or 1. SQLite
  6874. ** will only use a createFlag of 2 after a prior call with a createFlag of 1
  6875. ** failed.)^ In between the to xFetch() calls, SQLite may
  6876. ** attempt to unpin one or more cache pages by spilling the content of
  6877. ** pinned pages to disk and synching the operating system disk cache.
  6878. **
  6879. ** [[the xUnpin() page cache method]]
  6880. ** ^xUnpin() is called by SQLite with a pointer to a currently pinned page
  6881. ** as its second argument. If the third parameter, discard, is non-zero,
  6882. ** then the page must be evicted from the cache.
  6883. ** ^If the discard parameter is
  6884. ** zero, then the page may be discarded or retained at the discretion of
  6885. ** page cache implementation. ^The page cache implementation
  6886. ** may choose to evict unpinned pages at any time.
  6887. **
  6888. ** The cache must not perform any reference counting. A single
  6889. ** call to xUnpin() unpins the page regardless of the number of prior calls
  6890. ** to xFetch().
  6891. **
  6892. ** [[the xRekey() page cache methods]]
  6893. ** The xRekey() method is used to change the key value associated with the
  6894. ** page passed as the second argument. If the cache
  6895. ** previously contains an entry associated with newKey, it must be
  6896. ** discarded. ^Any prior cache entry associated with newKey is guaranteed not
  6897. ** to be pinned.
  6898. **
  6899. ** When SQLite calls the xTruncate() method, the cache must discard all
  6900. ** existing cache entries with page numbers (keys) greater than or equal
  6901. ** to the value of the iLimit parameter passed to xTruncate(). If any
  6902. ** of these pages are pinned, they are implicitly unpinned, meaning that
  6903. ** they can be safely discarded.
  6904. **
  6905. ** [[the xDestroy() page cache method]]
  6906. ** ^The xDestroy() method is used to delete a cache allocated by xCreate().
  6907. ** All resources associated with the specified cache should be freed. ^After
  6908. ** calling the xDestroy() method, SQLite considers the [sqlite3_pcache*]
  6909. ** handle invalid, and will not use it with any other sqlite3_pcache_methods2
  6910. ** functions.
  6911. **
  6912. ** [[the xShrink() page cache method]]
  6913. ** ^SQLite invokes the xShrink() method when it wants the page cache to
  6914. ** free up as much of heap memory as possible. The page cache implementation
  6915. ** is not obligated to free any memory, but well-behaved implementations should
  6916. ** do their best.
  6917. */
  6918. typedef struct sqlite3_pcache_methods2 sqlite3_pcache_methods2;
  6919. struct sqlite3_pcache_methods2 {
  6920. int iVersion;
  6921. void *pArg;
  6922. int (*xInit)(void*);
  6923. void (*xShutdown)(void*);
  6924. sqlite3_pcache *(*xCreate)(int szPage, int szExtra, int bPurgeable);
  6925. void (*xCachesize)(sqlite3_pcache*, int nCachesize);
  6926. int (*xPagecount)(sqlite3_pcache*);
  6927. sqlite3_pcache_page *(*xFetch)(sqlite3_pcache*, unsigned key, int createFlag);
  6928. void (*xUnpin)(sqlite3_pcache*, sqlite3_pcache_page*, int discard);
  6929. void (*xRekey)(sqlite3_pcache*, sqlite3_pcache_page*,
  6930. unsigned oldKey, unsigned newKey);
  6931. void (*xTruncate)(sqlite3_pcache*, unsigned iLimit);
  6932. void (*xDestroy)(sqlite3_pcache*);
  6933. void (*xShrink)(sqlite3_pcache*);
  6934. };
  6935. /*
  6936. ** This is the obsolete pcache_methods object that has now been replaced
  6937. ** by sqlite3_pcache_methods2. This object is not used by SQLite. It is
  6938. ** retained in the header file for backwards compatibility only.
  6939. */
  6940. typedef struct sqlite3_pcache_methods sqlite3_pcache_methods;
  6941. struct sqlite3_pcache_methods {
  6942. void *pArg;
  6943. int (*xInit)(void*);
  6944. void (*xShutdown)(void*);
  6945. sqlite3_pcache *(*xCreate)(int szPage, int bPurgeable);
  6946. void (*xCachesize)(sqlite3_pcache*, int nCachesize);
  6947. int (*xPagecount)(sqlite3_pcache*);
  6948. void *(*xFetch)(sqlite3_pcache*, unsigned key, int createFlag);
  6949. void (*xUnpin)(sqlite3_pcache*, void*, int discard);
  6950. void (*xRekey)(sqlite3_pcache*, void*, unsigned oldKey, unsigned newKey);
  6951. void (*xTruncate)(sqlite3_pcache*, unsigned iLimit);
  6952. void (*xDestroy)(sqlite3_pcache*);
  6953. };
  6954. /*
  6955. ** CAPI3REF: Online Backup Object
  6956. **
  6957. ** The sqlite3_backup object records state information about an ongoing
  6958. ** online backup operation. ^The sqlite3_backup object is created by
  6959. ** a call to [sqlite3_backup_init()] and is destroyed by a call to
  6960. ** [sqlite3_backup_finish()].
  6961. **
  6962. ** See Also: [Using the SQLite Online Backup API]
  6963. */
  6964. typedef struct sqlite3_backup sqlite3_backup;
  6965. /*
  6966. ** CAPI3REF: Online Backup API.
  6967. **
  6968. ** The backup API copies the content of one database into another.
  6969. ** It is useful either for creating backups of databases or
  6970. ** for copying in-memory databases to or from persistent files.
  6971. **
  6972. ** See Also: [Using the SQLite Online Backup API]
  6973. **
  6974. ** ^SQLite holds a write transaction open on the destination database file
  6975. ** for the duration of the backup operation.
  6976. ** ^The source database is read-locked only while it is being read;
  6977. ** it is not locked continuously for the entire backup operation.
  6978. ** ^Thus, the backup may be performed on a live source database without
  6979. ** preventing other database connections from
  6980. ** reading or writing to the source database while the backup is underway.
  6981. **
  6982. ** ^(To perform a backup operation:
  6983. ** <ol>
  6984. ** <li><b>sqlite3_backup_init()</b> is called once to initialize the
  6985. ** backup,
  6986. ** <li><b>sqlite3_backup_step()</b> is called one or more times to transfer
  6987. ** the data between the two databases, and finally
  6988. ** <li><b>sqlite3_backup_finish()</b> is called to release all resources
  6989. ** associated with the backup operation.
  6990. ** </ol>)^
  6991. ** There should be exactly one call to sqlite3_backup_finish() for each
  6992. ** successful call to sqlite3_backup_init().
  6993. **
  6994. ** [[sqlite3_backup_init()]] <b>sqlite3_backup_init()</b>
  6995. **
  6996. ** ^The D and N arguments to sqlite3_backup_init(D,N,S,M) are the
  6997. ** [database connection] associated with the destination database
  6998. ** and the database name, respectively.
  6999. ** ^The database name is "main" for the main database, "temp" for the
  7000. ** temporary database, or the name specified after the AS keyword in
  7001. ** an [ATTACH] statement for an attached database.
  7002. ** ^The S and M arguments passed to
  7003. ** sqlite3_backup_init(D,N,S,M) identify the [database connection]
  7004. ** and database name of the source database, respectively.
  7005. ** ^The source and destination [database connections] (parameters S and D)
  7006. ** must be different or else sqlite3_backup_init(D,N,S,M) will fail with
  7007. ** an error.
  7008. **
  7009. ** ^A call to sqlite3_backup_init() will fail, returning SQLITE_ERROR, if
  7010. ** there is already a read or read-write transaction open on the
  7011. ** destination database.
  7012. **
  7013. ** ^If an error occurs within sqlite3_backup_init(D,N,S,M), then NULL is
  7014. ** returned and an error code and error message are stored in the
  7015. ** destination [database connection] D.
  7016. ** ^The error code and message for the failed call to sqlite3_backup_init()
  7017. ** can be retrieved using the [sqlite3_errcode()], [sqlite3_errmsg()], and/or
  7018. ** [sqlite3_errmsg16()] functions.
  7019. ** ^A successful call to sqlite3_backup_init() returns a pointer to an
  7020. ** [sqlite3_backup] object.
  7021. ** ^The [sqlite3_backup] object may be used with the sqlite3_backup_step() and
  7022. ** sqlite3_backup_finish() functions to perform the specified backup
  7023. ** operation.
  7024. **
  7025. ** [[sqlite3_backup_step()]] <b>sqlite3_backup_step()</b>
  7026. **
  7027. ** ^Function sqlite3_backup_step(B,N) will copy up to N pages between
  7028. ** the source and destination databases specified by [sqlite3_backup] object B.
  7029. ** ^If N is negative, all remaining source pages are copied.
  7030. ** ^If sqlite3_backup_step(B,N) successfully copies N pages and there
  7031. ** are still more pages to be copied, then the function returns [SQLITE_OK].
  7032. ** ^If sqlite3_backup_step(B,N) successfully finishes copying all pages
  7033. ** from source to destination, then it returns [SQLITE_DONE].
  7034. ** ^If an error occurs while running sqlite3_backup_step(B,N),
  7035. ** then an [error code] is returned. ^As well as [SQLITE_OK] and
  7036. ** [SQLITE_DONE], a call to sqlite3_backup_step() may return [SQLITE_READONLY],
  7037. ** [SQLITE_NOMEM], [SQLITE_BUSY], [SQLITE_LOCKED], or an
  7038. ** [SQLITE_IOERR_ACCESS | SQLITE_IOERR_XXX] extended error code.
  7039. **
  7040. ** ^(The sqlite3_backup_step() might return [SQLITE_READONLY] if
  7041. ** <ol>
  7042. ** <li> the destination database was opened read-only, or
  7043. ** <li> the destination database is using write-ahead-log journaling
  7044. ** and the destination and source page sizes differ, or
  7045. ** <li> the destination database is an in-memory database and the
  7046. ** destination and source page sizes differ.
  7047. ** </ol>)^
  7048. **
  7049. ** ^If sqlite3_backup_step() cannot obtain a required file-system lock, then
  7050. ** the [sqlite3_busy_handler | busy-handler function]
  7051. ** is invoked (if one is specified). ^If the
  7052. ** busy-handler returns non-zero before the lock is available, then
  7053. ** [SQLITE_BUSY] is returned to the caller. ^In this case the call to
  7054. ** sqlite3_backup_step() can be retried later. ^If the source
  7055. ** [database connection]
  7056. ** is being used to write to the source database when sqlite3_backup_step()
  7057. ** is called, then [SQLITE_LOCKED] is returned immediately. ^Again, in this
  7058. ** case the call to sqlite3_backup_step() can be retried later on. ^(If
  7059. ** [SQLITE_IOERR_ACCESS | SQLITE_IOERR_XXX], [SQLITE_NOMEM], or
  7060. ** [SQLITE_READONLY] is returned, then
  7061. ** there is no point in retrying the call to sqlite3_backup_step(). These
  7062. ** errors are considered fatal.)^ The application must accept
  7063. ** that the backup operation has failed and pass the backup operation handle
  7064. ** to the sqlite3_backup_finish() to release associated resources.
  7065. **
  7066. ** ^The first call to sqlite3_backup_step() obtains an exclusive lock
  7067. ** on the destination file. ^The exclusive lock is not released until either
  7068. ** sqlite3_backup_finish() is called or the backup operation is complete
  7069. ** and sqlite3_backup_step() returns [SQLITE_DONE]. ^Every call to
  7070. ** sqlite3_backup_step() obtains a [shared lock] on the source database that
  7071. ** lasts for the duration of the sqlite3_backup_step() call.
  7072. ** ^Because the source database is not locked between calls to
  7073. ** sqlite3_backup_step(), the source database may be modified mid-way
  7074. ** through the backup process. ^If the source database is modified by an
  7075. ** external process or via a database connection other than the one being
  7076. ** used by the backup operation, then the backup will be automatically
  7077. ** restarted by the next call to sqlite3_backup_step(). ^If the source
  7078. ** database is modified by the using the same database connection as is used
  7079. ** by the backup operation, then the backup database is automatically
  7080. ** updated at the same time.
  7081. **
  7082. ** [[sqlite3_backup_finish()]] <b>sqlite3_backup_finish()</b>
  7083. **
  7084. ** When sqlite3_backup_step() has returned [SQLITE_DONE], or when the
  7085. ** application wishes to abandon the backup operation, the application
  7086. ** should destroy the [sqlite3_backup] by passing it to sqlite3_backup_finish().
  7087. ** ^The sqlite3_backup_finish() interfaces releases all
  7088. ** resources associated with the [sqlite3_backup] object.
  7089. ** ^If sqlite3_backup_step() has not yet returned [SQLITE_DONE], then any
  7090. ** active write-transaction on the destination database is rolled back.
  7091. ** The [sqlite3_backup] object is invalid
  7092. ** and may not be used following a call to sqlite3_backup_finish().
  7093. **
  7094. ** ^The value returned by sqlite3_backup_finish is [SQLITE_OK] if no
  7095. ** sqlite3_backup_step() errors occurred, regardless or whether or not
  7096. ** sqlite3_backup_step() completed.
  7097. ** ^If an out-of-memory condition or IO error occurred during any prior
  7098. ** sqlite3_backup_step() call on the same [sqlite3_backup] object, then
  7099. ** sqlite3_backup_finish() returns the corresponding [error code].
  7100. **
  7101. ** ^A return of [SQLITE_BUSY] or [SQLITE_LOCKED] from sqlite3_backup_step()
  7102. ** is not a permanent error and does not affect the return value of
  7103. ** sqlite3_backup_finish().
  7104. **
  7105. ** [[sqlite3_backup_remaining()]] [[sqlite3_backup_pagecount()]]
  7106. ** <b>sqlite3_backup_remaining() and sqlite3_backup_pagecount()</b>
  7107. **
  7108. ** ^The sqlite3_backup_remaining() routine returns the number of pages still
  7109. ** to be backed up at the conclusion of the most recent sqlite3_backup_step().
  7110. ** ^The sqlite3_backup_pagecount() routine returns the total number of pages
  7111. ** in the source database at the conclusion of the most recent
  7112. ** sqlite3_backup_step().
  7113. ** ^(The values returned by these functions are only updated by
  7114. ** sqlite3_backup_step(). If the source database is modified in a way that
  7115. ** changes the size of the source database or the number of pages remaining,
  7116. ** those changes are not reflected in the output of sqlite3_backup_pagecount()
  7117. ** and sqlite3_backup_remaining() until after the next
  7118. ** sqlite3_backup_step().)^
  7119. **
  7120. ** <b>Concurrent Usage of Database Handles</b>
  7121. **
  7122. ** ^The source [database connection] may be used by the application for other
  7123. ** purposes while a backup operation is underway or being initialized.
  7124. ** ^If SQLite is compiled and configured to support threadsafe database
  7125. ** connections, then the source database connection may be used concurrently
  7126. ** from within other threads.
  7127. **
  7128. ** However, the application must guarantee that the destination
  7129. ** [database connection] is not passed to any other API (by any thread) after
  7130. ** sqlite3_backup_init() is called and before the corresponding call to
  7131. ** sqlite3_backup_finish(). SQLite does not currently check to see
  7132. ** if the application incorrectly accesses the destination [database connection]
  7133. ** and so no error code is reported, but the operations may malfunction
  7134. ** nevertheless. Use of the destination database connection while a
  7135. ** backup is in progress might also also cause a mutex deadlock.
  7136. **
  7137. ** If running in [shared cache mode], the application must
  7138. ** guarantee that the shared cache used by the destination database
  7139. ** is not accessed while the backup is running. In practice this means
  7140. ** that the application must guarantee that the disk file being
  7141. ** backed up to is not accessed by any connection within the process,
  7142. ** not just the specific connection that was passed to sqlite3_backup_init().
  7143. **
  7144. ** The [sqlite3_backup] object itself is partially threadsafe. Multiple
  7145. ** threads may safely make multiple concurrent calls to sqlite3_backup_step().
  7146. ** However, the sqlite3_backup_remaining() and sqlite3_backup_pagecount()
  7147. ** APIs are not strictly speaking threadsafe. If they are invoked at the
  7148. ** same time as another thread is invoking sqlite3_backup_step() it is
  7149. ** possible that they return invalid values.
  7150. */
  7151. SQLITE_API sqlite3_backup *SQLITE_STDCALL sqlite3_backup_init(
  7152. sqlite3 *pDest, /* Destination database handle */
  7153. const char *zDestName, /* Destination database name */
  7154. sqlite3 *pSource, /* Source database handle */
  7155. const char *zSourceName /* Source database name */
  7156. );
  7157. SQLITE_API int SQLITE_STDCALL sqlite3_backup_step(sqlite3_backup *p, int nPage);
  7158. SQLITE_API int SQLITE_STDCALL sqlite3_backup_finish(sqlite3_backup *p);
  7159. SQLITE_API int SQLITE_STDCALL sqlite3_backup_remaining(sqlite3_backup *p);
  7160. SQLITE_API int SQLITE_STDCALL sqlite3_backup_pagecount(sqlite3_backup *p);
  7161. /*
  7162. ** CAPI3REF: Unlock Notification
  7163. ** METHOD: sqlite3
  7164. **
  7165. ** ^When running in shared-cache mode, a database operation may fail with
  7166. ** an [SQLITE_LOCKED] error if the required locks on the shared-cache or
  7167. ** individual tables within the shared-cache cannot be obtained. See
  7168. ** [SQLite Shared-Cache Mode] for a description of shared-cache locking.
  7169. ** ^This API may be used to register a callback that SQLite will invoke
  7170. ** when the connection currently holding the required lock relinquishes it.
  7171. ** ^This API is only available if the library was compiled with the
  7172. ** [SQLITE_ENABLE_UNLOCK_NOTIFY] C-preprocessor symbol defined.
  7173. **
  7174. ** See Also: [Using the SQLite Unlock Notification Feature].
  7175. **
  7176. ** ^Shared-cache locks are released when a database connection concludes
  7177. ** its current transaction, either by committing it or rolling it back.
  7178. **
  7179. ** ^When a connection (known as the blocked connection) fails to obtain a
  7180. ** shared-cache lock and SQLITE_LOCKED is returned to the caller, the
  7181. ** identity of the database connection (the blocking connection) that
  7182. ** has locked the required resource is stored internally. ^After an
  7183. ** application receives an SQLITE_LOCKED error, it may call the
  7184. ** sqlite3_unlock_notify() method with the blocked connection handle as
  7185. ** the first argument to register for a callback that will be invoked
  7186. ** when the blocking connections current transaction is concluded. ^The
  7187. ** callback is invoked from within the [sqlite3_step] or [sqlite3_close]
  7188. ** call that concludes the blocking connections transaction.
  7189. **
  7190. ** ^(If sqlite3_unlock_notify() is called in a multi-threaded application,
  7191. ** there is a chance that the blocking connection will have already
  7192. ** concluded its transaction by the time sqlite3_unlock_notify() is invoked.
  7193. ** If this happens, then the specified callback is invoked immediately,
  7194. ** from within the call to sqlite3_unlock_notify().)^
  7195. **
  7196. ** ^If the blocked connection is attempting to obtain a write-lock on a
  7197. ** shared-cache table, and more than one other connection currently holds
  7198. ** a read-lock on the same table, then SQLite arbitrarily selects one of
  7199. ** the other connections to use as the blocking connection.
  7200. **
  7201. ** ^(There may be at most one unlock-notify callback registered by a
  7202. ** blocked connection. If sqlite3_unlock_notify() is called when the
  7203. ** blocked connection already has a registered unlock-notify callback,
  7204. ** then the new callback replaces the old.)^ ^If sqlite3_unlock_notify() is
  7205. ** called with a NULL pointer as its second argument, then any existing
  7206. ** unlock-notify callback is canceled. ^The blocked connections
  7207. ** unlock-notify callback may also be canceled by closing the blocked
  7208. ** connection using [sqlite3_close()].
  7209. **
  7210. ** The unlock-notify callback is not reentrant. If an application invokes
  7211. ** any sqlite3_xxx API functions from within an unlock-notify callback, a
  7212. ** crash or deadlock may be the result.
  7213. **
  7214. ** ^Unless deadlock is detected (see below), sqlite3_unlock_notify() always
  7215. ** returns SQLITE_OK.
  7216. **
  7217. ** <b>Callback Invocation Details</b>
  7218. **
  7219. ** When an unlock-notify callback is registered, the application provides a
  7220. ** single void* pointer that is passed to the callback when it is invoked.
  7221. ** However, the signature of the callback function allows SQLite to pass
  7222. ** it an array of void* context pointers. The first argument passed to
  7223. ** an unlock-notify callback is a pointer to an array of void* pointers,
  7224. ** and the second is the number of entries in the array.
  7225. **
  7226. ** When a blocking connections transaction is concluded, there may be
  7227. ** more than one blocked connection that has registered for an unlock-notify
  7228. ** callback. ^If two or more such blocked connections have specified the
  7229. ** same callback function, then instead of invoking the callback function
  7230. ** multiple times, it is invoked once with the set of void* context pointers
  7231. ** specified by the blocked connections bundled together into an array.
  7232. ** This gives the application an opportunity to prioritize any actions
  7233. ** related to the set of unblocked database connections.
  7234. **
  7235. ** <b>Deadlock Detection</b>
  7236. **
  7237. ** Assuming that after registering for an unlock-notify callback a
  7238. ** database waits for the callback to be issued before taking any further
  7239. ** action (a reasonable assumption), then using this API may cause the
  7240. ** application to deadlock. For example, if connection X is waiting for
  7241. ** connection Y's transaction to be concluded, and similarly connection
  7242. ** Y is waiting on connection X's transaction, then neither connection
  7243. ** will proceed and the system may remain deadlocked indefinitely.
  7244. **
  7245. ** To avoid this scenario, the sqlite3_unlock_notify() performs deadlock
  7246. ** detection. ^If a given call to sqlite3_unlock_notify() would put the
  7247. ** system in a deadlocked state, then SQLITE_LOCKED is returned and no
  7248. ** unlock-notify callback is registered. The system is said to be in
  7249. ** a deadlocked state if connection A has registered for an unlock-notify
  7250. ** callback on the conclusion of connection B's transaction, and connection
  7251. ** B has itself registered for an unlock-notify callback when connection
  7252. ** A's transaction is concluded. ^Indirect deadlock is also detected, so
  7253. ** the system is also considered to be deadlocked if connection B has
  7254. ** registered for an unlock-notify callback on the conclusion of connection
  7255. ** C's transaction, where connection C is waiting on connection A. ^Any
  7256. ** number of levels of indirection are allowed.
  7257. **
  7258. ** <b>The "DROP TABLE" Exception</b>
  7259. **
  7260. ** When a call to [sqlite3_step()] returns SQLITE_LOCKED, it is almost
  7261. ** always appropriate to call sqlite3_unlock_notify(). There is however,
  7262. ** one exception. When executing a "DROP TABLE" or "DROP INDEX" statement,
  7263. ** SQLite checks if there are any currently executing SELECT statements
  7264. ** that belong to the same connection. If there are, SQLITE_LOCKED is
  7265. ** returned. In this case there is no "blocking connection", so invoking
  7266. ** sqlite3_unlock_notify() results in the unlock-notify callback being
  7267. ** invoked immediately. If the application then re-attempts the "DROP TABLE"
  7268. ** or "DROP INDEX" query, an infinite loop might be the result.
  7269. **
  7270. ** One way around this problem is to check the extended error code returned
  7271. ** by an sqlite3_step() call. ^(If there is a blocking connection, then the
  7272. ** extended error code is set to SQLITE_LOCKED_SHAREDCACHE. Otherwise, in
  7273. ** the special "DROP TABLE/INDEX" case, the extended error code is just
  7274. ** SQLITE_LOCKED.)^
  7275. */
  7276. SQLITE_API int SQLITE_STDCALL sqlite3_unlock_notify(
  7277. sqlite3 *pBlocked, /* Waiting connection */
  7278. void (*xNotify)(void **apArg, int nArg), /* Callback function to invoke */
  7279. void *pNotifyArg /* Argument to pass to xNotify */
  7280. );
  7281. /*
  7282. ** CAPI3REF: String Comparison
  7283. **
  7284. ** ^The [sqlite3_stricmp()] and [sqlite3_strnicmp()] APIs allow applications
  7285. ** and extensions to compare the contents of two buffers containing UTF-8
  7286. ** strings in a case-independent fashion, using the same definition of "case
  7287. ** independence" that SQLite uses internally when comparing identifiers.
  7288. */
  7289. SQLITE_API int SQLITE_STDCALL sqlite3_stricmp(const char *, const char *);
  7290. SQLITE_API int SQLITE_STDCALL sqlite3_strnicmp(const char *, const char *, int);
  7291. /*
  7292. ** CAPI3REF: String Globbing
  7293. *
  7294. ** ^The [sqlite3_strglob(P,X)] interface returns zero if string X matches
  7295. ** the glob pattern P, and it returns non-zero if string X does not match
  7296. ** the glob pattern P. ^The definition of glob pattern matching used in
  7297. ** [sqlite3_strglob(P,X)] is the same as for the "X GLOB P" operator in the
  7298. ** SQL dialect used by SQLite. ^The sqlite3_strglob(P,X) function is case
  7299. ** sensitive.
  7300. **
  7301. ** Note that this routine returns zero on a match and non-zero if the strings
  7302. ** do not match, the same as [sqlite3_stricmp()] and [sqlite3_strnicmp()].
  7303. */
  7304. SQLITE_API int SQLITE_STDCALL sqlite3_strglob(const char *zGlob, const char *zStr);
  7305. /*
  7306. ** CAPI3REF: Error Logging Interface
  7307. **
  7308. ** ^The [sqlite3_log()] interface writes a message into the [error log]
  7309. ** established by the [SQLITE_CONFIG_LOG] option to [sqlite3_config()].
  7310. ** ^If logging is enabled, the zFormat string and subsequent arguments are
  7311. ** used with [sqlite3_snprintf()] to generate the final output string.
  7312. **
  7313. ** The sqlite3_log() interface is intended for use by extensions such as
  7314. ** virtual tables, collating functions, and SQL functions. While there is
  7315. ** nothing to prevent an application from calling sqlite3_log(), doing so
  7316. ** is considered bad form.
  7317. **
  7318. ** The zFormat string must not be NULL.
  7319. **
  7320. ** To avoid deadlocks and other threading problems, the sqlite3_log() routine
  7321. ** will not use dynamically allocated memory. The log message is stored in
  7322. ** a fixed-length buffer on the stack. If the log message is longer than
  7323. ** a few hundred characters, it will be truncated to the length of the
  7324. ** buffer.
  7325. */
  7326. SQLITE_API void SQLITE_CDECL sqlite3_log(int iErrCode, const char *zFormat, ...);
  7327. /*
  7328. ** CAPI3REF: Write-Ahead Log Commit Hook
  7329. ** METHOD: sqlite3
  7330. **
  7331. ** ^The [sqlite3_wal_hook()] function is used to register a callback that
  7332. ** is invoked each time data is committed to a database in wal mode.
  7333. **
  7334. ** ^(The callback is invoked by SQLite after the commit has taken place and
  7335. ** the associated write-lock on the database released)^, so the implementation
  7336. ** may read, write or [checkpoint] the database as required.
  7337. **
  7338. ** ^The first parameter passed to the callback function when it is invoked
  7339. ** is a copy of the third parameter passed to sqlite3_wal_hook() when
  7340. ** registering the callback. ^The second is a copy of the database handle.
  7341. ** ^The third parameter is the name of the database that was written to -
  7342. ** either "main" or the name of an [ATTACH]-ed database. ^The fourth parameter
  7343. ** is the number of pages currently in the write-ahead log file,
  7344. ** including those that were just committed.
  7345. **
  7346. ** The callback function should normally return [SQLITE_OK]. ^If an error
  7347. ** code is returned, that error will propagate back up through the
  7348. ** SQLite code base to cause the statement that provoked the callback
  7349. ** to report an error, though the commit will have still occurred. If the
  7350. ** callback returns [SQLITE_ROW] or [SQLITE_DONE], or if it returns a value
  7351. ** that does not correspond to any valid SQLite error code, the results
  7352. ** are undefined.
  7353. **
  7354. ** A single database handle may have at most a single write-ahead log callback
  7355. ** registered at one time. ^Calling [sqlite3_wal_hook()] replaces any
  7356. ** previously registered write-ahead log callback. ^Note that the
  7357. ** [sqlite3_wal_autocheckpoint()] interface and the
  7358. ** [wal_autocheckpoint pragma] both invoke [sqlite3_wal_hook()] and will
  7359. ** those overwrite any prior [sqlite3_wal_hook()] settings.
  7360. */
  7361. SQLITE_API void *SQLITE_STDCALL sqlite3_wal_hook(
  7362. sqlite3*,
  7363. int(*)(void *,sqlite3*,const char*,int),
  7364. void*
  7365. );
  7366. /*
  7367. ** CAPI3REF: Configure an auto-checkpoint
  7368. ** METHOD: sqlite3
  7369. **
  7370. ** ^The [sqlite3_wal_autocheckpoint(D,N)] is a wrapper around
  7371. ** [sqlite3_wal_hook()] that causes any database on [database connection] D
  7372. ** to automatically [checkpoint]
  7373. ** after committing a transaction if there are N or
  7374. ** more frames in the [write-ahead log] file. ^Passing zero or
  7375. ** a negative value as the nFrame parameter disables automatic
  7376. ** checkpoints entirely.
  7377. **
  7378. ** ^The callback registered by this function replaces any existing callback
  7379. ** registered using [sqlite3_wal_hook()]. ^Likewise, registering a callback
  7380. ** using [sqlite3_wal_hook()] disables the automatic checkpoint mechanism
  7381. ** configured by this function.
  7382. **
  7383. ** ^The [wal_autocheckpoint pragma] can be used to invoke this interface
  7384. ** from SQL.
  7385. **
  7386. ** ^Checkpoints initiated by this mechanism are
  7387. ** [sqlite3_wal_checkpoint_v2|PASSIVE].
  7388. **
  7389. ** ^Every new [database connection] defaults to having the auto-checkpoint
  7390. ** enabled with a threshold of 1000 or [SQLITE_DEFAULT_WAL_AUTOCHECKPOINT]
  7391. ** pages. The use of this interface
  7392. ** is only necessary if the default setting is found to be suboptimal
  7393. ** for a particular application.
  7394. */
  7395. SQLITE_API int SQLITE_STDCALL sqlite3_wal_autocheckpoint(sqlite3 *db, int N);
  7396. /*
  7397. ** CAPI3REF: Checkpoint a database
  7398. ** METHOD: sqlite3
  7399. **
  7400. ** ^(The sqlite3_wal_checkpoint(D,X) is equivalent to
  7401. ** [sqlite3_wal_checkpoint_v2](D,X,[SQLITE_CHECKPOINT_PASSIVE],0,0).)^
  7402. **
  7403. ** In brief, sqlite3_wal_checkpoint(D,X) causes the content in the
  7404. ** [write-ahead log] for database X on [database connection] D to be
  7405. ** transferred into the database file and for the write-ahead log to
  7406. ** be reset. See the [checkpointing] documentation for addition
  7407. ** information.
  7408. **
  7409. ** This interface used to be the only way to cause a checkpoint to
  7410. ** occur. But then the newer and more powerful [sqlite3_wal_checkpoint_v2()]
  7411. ** interface was added. This interface is retained for backwards
  7412. ** compatibility and as a convenience for applications that need to manually
  7413. ** start a callback but which do not need the full power (and corresponding
  7414. ** complication) of [sqlite3_wal_checkpoint_v2()].
  7415. */
  7416. SQLITE_API int SQLITE_STDCALL sqlite3_wal_checkpoint(sqlite3 *db, const char *zDb);
  7417. /*
  7418. ** CAPI3REF: Checkpoint a database
  7419. ** METHOD: sqlite3
  7420. **
  7421. ** ^(The sqlite3_wal_checkpoint_v2(D,X,M,L,C) interface runs a checkpoint
  7422. ** operation on database X of [database connection] D in mode M. Status
  7423. ** information is written back into integers pointed to by L and C.)^
  7424. ** ^(The M parameter must be a valid [checkpoint mode]:)^
  7425. **
  7426. ** <dl>
  7427. ** <dt>SQLITE_CHECKPOINT_PASSIVE<dd>
  7428. ** ^Checkpoint as many frames as possible without waiting for any database
  7429. ** readers or writers to finish, then sync the database file if all frames
  7430. ** in the log were checkpointed. ^The [busy-handler callback]
  7431. ** is never invoked in the SQLITE_CHECKPOINT_PASSIVE mode.
  7432. ** ^On the other hand, passive mode might leave the checkpoint unfinished
  7433. ** if there are concurrent readers or writers.
  7434. **
  7435. ** <dt>SQLITE_CHECKPOINT_FULL<dd>
  7436. ** ^This mode blocks (it invokes the
  7437. ** [sqlite3_busy_handler|busy-handler callback]) until there is no
  7438. ** database writer and all readers are reading from the most recent database
  7439. ** snapshot. ^It then checkpoints all frames in the log file and syncs the
  7440. ** database file. ^This mode blocks new database writers while it is pending,
  7441. ** but new database readers are allowed to continue unimpeded.
  7442. **
  7443. ** <dt>SQLITE_CHECKPOINT_RESTART<dd>
  7444. ** ^This mode works the same way as SQLITE_CHECKPOINT_FULL with the addition
  7445. ** that after checkpointing the log file it blocks (calls the
  7446. ** [busy-handler callback])
  7447. ** until all readers are reading from the database file only. ^This ensures
  7448. ** that the next writer will restart the log file from the beginning.
  7449. ** ^Like SQLITE_CHECKPOINT_FULL, this mode blocks new
  7450. ** database writer attempts while it is pending, but does not impede readers.
  7451. **
  7452. ** <dt>SQLITE_CHECKPOINT_TRUNCATE<dd>
  7453. ** ^This mode works the same way as SQLITE_CHECKPOINT_RESTART with the
  7454. ** addition that it also truncates the log file to zero bytes just prior
  7455. ** to a successful return.
  7456. ** </dl>
  7457. **
  7458. ** ^If pnLog is not NULL, then *pnLog is set to the total number of frames in
  7459. ** the log file or to -1 if the checkpoint could not run because
  7460. ** of an error or because the database is not in [WAL mode]. ^If pnCkpt is not
  7461. ** NULL,then *pnCkpt is set to the total number of checkpointed frames in the
  7462. ** log file (including any that were already checkpointed before the function
  7463. ** was called) or to -1 if the checkpoint could not run due to an error or
  7464. ** because the database is not in WAL mode. ^Note that upon successful
  7465. ** completion of an SQLITE_CHECKPOINT_TRUNCATE, the log file will have been
  7466. ** truncated to zero bytes and so both *pnLog and *pnCkpt will be set to zero.
  7467. **
  7468. ** ^All calls obtain an exclusive "checkpoint" lock on the database file. ^If
  7469. ** any other process is running a checkpoint operation at the same time, the
  7470. ** lock cannot be obtained and SQLITE_BUSY is returned. ^Even if there is a
  7471. ** busy-handler configured, it will not be invoked in this case.
  7472. **
  7473. ** ^The SQLITE_CHECKPOINT_FULL, RESTART and TRUNCATE modes also obtain the
  7474. ** exclusive "writer" lock on the database file. ^If the writer lock cannot be
  7475. ** obtained immediately, and a busy-handler is configured, it is invoked and
  7476. ** the writer lock retried until either the busy-handler returns 0 or the lock
  7477. ** is successfully obtained. ^The busy-handler is also invoked while waiting for
  7478. ** database readers as described above. ^If the busy-handler returns 0 before
  7479. ** the writer lock is obtained or while waiting for database readers, the
  7480. ** checkpoint operation proceeds from that point in the same way as
  7481. ** SQLITE_CHECKPOINT_PASSIVE - checkpointing as many frames as possible
  7482. ** without blocking any further. ^SQLITE_BUSY is returned in this case.
  7483. **
  7484. ** ^If parameter zDb is NULL or points to a zero length string, then the
  7485. ** specified operation is attempted on all WAL databases [attached] to
  7486. ** [database connection] db. In this case the
  7487. ** values written to output parameters *pnLog and *pnCkpt are undefined. ^If
  7488. ** an SQLITE_BUSY error is encountered when processing one or more of the
  7489. ** attached WAL databases, the operation is still attempted on any remaining
  7490. ** attached databases and SQLITE_BUSY is returned at the end. ^If any other
  7491. ** error occurs while processing an attached database, processing is abandoned
  7492. ** and the error code is returned to the caller immediately. ^If no error
  7493. ** (SQLITE_BUSY or otherwise) is encountered while processing the attached
  7494. ** databases, SQLITE_OK is returned.
  7495. **
  7496. ** ^If database zDb is the name of an attached database that is not in WAL
  7497. ** mode, SQLITE_OK is returned and both *pnLog and *pnCkpt set to -1. ^If
  7498. ** zDb is not NULL (or a zero length string) and is not the name of any
  7499. ** attached database, SQLITE_ERROR is returned to the caller.
  7500. **
  7501. ** ^Unless it returns SQLITE_MISUSE,
  7502. ** the sqlite3_wal_checkpoint_v2() interface
  7503. ** sets the error information that is queried by
  7504. ** [sqlite3_errcode()] and [sqlite3_errmsg()].
  7505. **
  7506. ** ^The [PRAGMA wal_checkpoint] command can be used to invoke this interface
  7507. ** from SQL.
  7508. */
  7509. SQLITE_API int SQLITE_STDCALL sqlite3_wal_checkpoint_v2(
  7510. sqlite3 *db, /* Database handle */
  7511. const char *zDb, /* Name of attached database (or NULL) */
  7512. int eMode, /* SQLITE_CHECKPOINT_* value */
  7513. int *pnLog, /* OUT: Size of WAL log in frames */
  7514. int *pnCkpt /* OUT: Total number of frames checkpointed */
  7515. );
  7516. /*
  7517. ** CAPI3REF: Checkpoint Mode Values
  7518. ** KEYWORDS: {checkpoint mode}
  7519. **
  7520. ** These constants define all valid values for the "checkpoint mode" passed
  7521. ** as the third parameter to the [sqlite3_wal_checkpoint_v2()] interface.
  7522. ** See the [sqlite3_wal_checkpoint_v2()] documentation for details on the
  7523. ** meaning of each of these checkpoint modes.
  7524. */
  7525. #define SQLITE_CHECKPOINT_PASSIVE 0 /* Do as much as possible w/o blocking */
  7526. #define SQLITE_CHECKPOINT_FULL 1 /* Wait for writers, then checkpoint */
  7527. #define SQLITE_CHECKPOINT_RESTART 2 /* Like FULL but wait for for readers */
  7528. #define SQLITE_CHECKPOINT_TRUNCATE 3 /* Like RESTART but also truncate WAL */
  7529. /*
  7530. ** CAPI3REF: Virtual Table Interface Configuration
  7531. **
  7532. ** This function may be called by either the [xConnect] or [xCreate] method
  7533. ** of a [virtual table] implementation to configure
  7534. ** various facets of the virtual table interface.
  7535. **
  7536. ** If this interface is invoked outside the context of an xConnect or
  7537. ** xCreate virtual table method then the behavior is undefined.
  7538. **
  7539. ** At present, there is only one option that may be configured using
  7540. ** this function. (See [SQLITE_VTAB_CONSTRAINT_SUPPORT].) Further options
  7541. ** may be added in the future.
  7542. */
  7543. SQLITE_API int SQLITE_CDECL sqlite3_vtab_config(sqlite3*, int op, ...);
  7544. /*
  7545. ** CAPI3REF: Virtual Table Configuration Options
  7546. **
  7547. ** These macros define the various options to the
  7548. ** [sqlite3_vtab_config()] interface that [virtual table] implementations
  7549. ** can use to customize and optimize their behavior.
  7550. **
  7551. ** <dl>
  7552. ** <dt>SQLITE_VTAB_CONSTRAINT_SUPPORT
  7553. ** <dd>Calls of the form
  7554. ** [sqlite3_vtab_config](db,SQLITE_VTAB_CONSTRAINT_SUPPORT,X) are supported,
  7555. ** where X is an integer. If X is zero, then the [virtual table] whose
  7556. ** [xCreate] or [xConnect] method invoked [sqlite3_vtab_config()] does not
  7557. ** support constraints. In this configuration (which is the default) if
  7558. ** a call to the [xUpdate] method returns [SQLITE_CONSTRAINT], then the entire
  7559. ** statement is rolled back as if [ON CONFLICT | OR ABORT] had been
  7560. ** specified as part of the users SQL statement, regardless of the actual
  7561. ** ON CONFLICT mode specified.
  7562. **
  7563. ** If X is non-zero, then the virtual table implementation guarantees
  7564. ** that if [xUpdate] returns [SQLITE_CONSTRAINT], it will do so before
  7565. ** any modifications to internal or persistent data structures have been made.
  7566. ** If the [ON CONFLICT] mode is ABORT, FAIL, IGNORE or ROLLBACK, SQLite
  7567. ** is able to roll back a statement or database transaction, and abandon
  7568. ** or continue processing the current SQL statement as appropriate.
  7569. ** If the ON CONFLICT mode is REPLACE and the [xUpdate] method returns
  7570. ** [SQLITE_CONSTRAINT], SQLite handles this as if the ON CONFLICT mode
  7571. ** had been ABORT.
  7572. **
  7573. ** Virtual table implementations that are required to handle OR REPLACE
  7574. ** must do so within the [xUpdate] method. If a call to the
  7575. ** [sqlite3_vtab_on_conflict()] function indicates that the current ON
  7576. ** CONFLICT policy is REPLACE, the virtual table implementation should
  7577. ** silently replace the appropriate rows within the xUpdate callback and
  7578. ** return SQLITE_OK. Or, if this is not possible, it may return
  7579. ** SQLITE_CONSTRAINT, in which case SQLite falls back to OR ABORT
  7580. ** constraint handling.
  7581. ** </dl>
  7582. */
  7583. #define SQLITE_VTAB_CONSTRAINT_SUPPORT 1
  7584. /*
  7585. ** CAPI3REF: Determine The Virtual Table Conflict Policy
  7586. **
  7587. ** This function may only be called from within a call to the [xUpdate] method
  7588. ** of a [virtual table] implementation for an INSERT or UPDATE operation. ^The
  7589. ** value returned is one of [SQLITE_ROLLBACK], [SQLITE_IGNORE], [SQLITE_FAIL],
  7590. ** [SQLITE_ABORT], or [SQLITE_REPLACE], according to the [ON CONFLICT] mode
  7591. ** of the SQL statement that triggered the call to the [xUpdate] method of the
  7592. ** [virtual table].
  7593. */
  7594. SQLITE_API int SQLITE_STDCALL sqlite3_vtab_on_conflict(sqlite3 *);
  7595. /*
  7596. ** CAPI3REF: Conflict resolution modes
  7597. ** KEYWORDS: {conflict resolution mode}
  7598. **
  7599. ** These constants are returned by [sqlite3_vtab_on_conflict()] to
  7600. ** inform a [virtual table] implementation what the [ON CONFLICT] mode
  7601. ** is for the SQL statement being evaluated.
  7602. **
  7603. ** Note that the [SQLITE_IGNORE] constant is also used as a potential
  7604. ** return value from the [sqlite3_set_authorizer()] callback and that
  7605. ** [SQLITE_ABORT] is also a [result code].
  7606. */
  7607. #define SQLITE_ROLLBACK 1
  7608. /* #define SQLITE_IGNORE 2 // Also used by sqlite3_authorizer() callback */
  7609. #define SQLITE_FAIL 3
  7610. /* #define SQLITE_ABORT 4 // Also an error code */
  7611. #define SQLITE_REPLACE 5
  7612. /*
  7613. ** CAPI3REF: Prepared Statement Scan Status Opcodes
  7614. ** KEYWORDS: {scanstatus options}
  7615. **
  7616. ** The following constants can be used for the T parameter to the
  7617. ** [sqlite3_stmt_scanstatus(S,X,T,V)] interface. Each constant designates a
  7618. ** different metric for sqlite3_stmt_scanstatus() to return.
  7619. **
  7620. ** When the value returned to V is a string, space to hold that string is
  7621. ** managed by the prepared statement S and will be automatically freed when
  7622. ** S is finalized.
  7623. **
  7624. ** <dl>
  7625. ** [[SQLITE_SCANSTAT_NLOOP]] <dt>SQLITE_SCANSTAT_NLOOP</dt>
  7626. ** <dd>^The [sqlite3_int64] variable pointed to by the T parameter will be
  7627. ** set to the total number of times that the X-th loop has run.</dd>
  7628. **
  7629. ** [[SQLITE_SCANSTAT_NVISIT]] <dt>SQLITE_SCANSTAT_NVISIT</dt>
  7630. ** <dd>^The [sqlite3_int64] variable pointed to by the T parameter will be set
  7631. ** to the total number of rows examined by all iterations of the X-th loop.</dd>
  7632. **
  7633. ** [[SQLITE_SCANSTAT_EST]] <dt>SQLITE_SCANSTAT_EST</dt>
  7634. ** <dd>^The "double" variable pointed to by the T parameter will be set to the
  7635. ** query planner's estimate for the average number of rows output from each
  7636. ** iteration of the X-th loop. If the query planner's estimates was accurate,
  7637. ** then this value will approximate the quotient NVISIT/NLOOP and the
  7638. ** product of this value for all prior loops with the same SELECTID will
  7639. ** be the NLOOP value for the current loop.
  7640. **
  7641. ** [[SQLITE_SCANSTAT_NAME]] <dt>SQLITE_SCANSTAT_NAME</dt>
  7642. ** <dd>^The "const char *" variable pointed to by the T parameter will be set
  7643. ** to a zero-terminated UTF-8 string containing the name of the index or table
  7644. ** used for the X-th loop.
  7645. **
  7646. ** [[SQLITE_SCANSTAT_EXPLAIN]] <dt>SQLITE_SCANSTAT_EXPLAIN</dt>
  7647. ** <dd>^The "const char *" variable pointed to by the T parameter will be set
  7648. ** to a zero-terminated UTF-8 string containing the [EXPLAIN QUERY PLAN]
  7649. ** description for the X-th loop.
  7650. **
  7651. ** [[SQLITE_SCANSTAT_SELECTID]] <dt>SQLITE_SCANSTAT_SELECT</dt>
  7652. ** <dd>^The "int" variable pointed to by the T parameter will be set to the
  7653. ** "select-id" for the X-th loop. The select-id identifies which query or
  7654. ** subquery the loop is part of. The main query has a select-id of zero.
  7655. ** The select-id is the same value as is output in the first column
  7656. ** of an [EXPLAIN QUERY PLAN] query.
  7657. ** </dl>
  7658. */
  7659. #define SQLITE_SCANSTAT_NLOOP 0
  7660. #define SQLITE_SCANSTAT_NVISIT 1
  7661. #define SQLITE_SCANSTAT_EST 2
  7662. #define SQLITE_SCANSTAT_NAME 3
  7663. #define SQLITE_SCANSTAT_EXPLAIN 4
  7664. #define SQLITE_SCANSTAT_SELECTID 5
  7665. /*
  7666. ** CAPI3REF: Prepared Statement Scan Status
  7667. ** METHOD: sqlite3_stmt
  7668. **
  7669. ** This interface returns information about the predicted and measured
  7670. ** performance for pStmt. Advanced applications can use this
  7671. ** interface to compare the predicted and the measured performance and
  7672. ** issue warnings and/or rerun [ANALYZE] if discrepancies are found.
  7673. **
  7674. ** Since this interface is expected to be rarely used, it is only
  7675. ** available if SQLite is compiled using the [SQLITE_ENABLE_STMT_SCANSTATUS]
  7676. ** compile-time option.
  7677. **
  7678. ** The "iScanStatusOp" parameter determines which status information to return.
  7679. ** The "iScanStatusOp" must be one of the [scanstatus options] or the behavior
  7680. ** of this interface is undefined.
  7681. ** ^The requested measurement is written into a variable pointed to by
  7682. ** the "pOut" parameter.
  7683. ** Parameter "idx" identifies the specific loop to retrieve statistics for.
  7684. ** Loops are numbered starting from zero. ^If idx is out of range - less than
  7685. ** zero or greater than or equal to the total number of loops used to implement
  7686. ** the statement - a non-zero value is returned and the variable that pOut
  7687. ** points to is unchanged.
  7688. **
  7689. ** ^Statistics might not be available for all loops in all statements. ^In cases
  7690. ** where there exist loops with no available statistics, this function behaves
  7691. ** as if the loop did not exist - it returns non-zero and leave the variable
  7692. ** that pOut points to unchanged.
  7693. **
  7694. ** See also: [sqlite3_stmt_scanstatus_reset()]
  7695. */
  7696. SQLITE_API SQLITE_EXPERIMENTAL int SQLITE_STDCALL sqlite3_stmt_scanstatus(
  7697. sqlite3_stmt *pStmt, /* Prepared statement for which info desired */
  7698. int idx, /* Index of loop to report on */
  7699. int iScanStatusOp, /* Information desired. SQLITE_SCANSTAT_* */
  7700. void *pOut /* Result written here */
  7701. );
  7702. /*
  7703. ** CAPI3REF: Zero Scan-Status Counters
  7704. ** METHOD: sqlite3_stmt
  7705. **
  7706. ** ^Zero all [sqlite3_stmt_scanstatus()] related event counters.
  7707. **
  7708. ** This API is only available if the library is built with pre-processor
  7709. ** symbol [SQLITE_ENABLE_STMT_SCANSTATUS] defined.
  7710. */
  7711. SQLITE_API SQLITE_EXPERIMENTAL void SQLITE_STDCALL sqlite3_stmt_scanstatus_reset(sqlite3_stmt*);
  7712. /*
  7713. ** Undo the hack that converts floating point types to integer for
  7714. ** builds on processors without floating point support.
  7715. */
  7716. #ifdef SQLITE_OMIT_FLOATING_POINT
  7717. # undef double
  7718. #endif
  7719. #if 0
  7720. } /* End of the 'extern "C"' block */
  7721. #endif
  7722. #endif /* _SQLITE3_H_ */
  7723. /*
  7724. ** 2010 August 30
  7725. **
  7726. ** The author disclaims copyright to this source code. In place of
  7727. ** a legal notice, here is a blessing:
  7728. **
  7729. ** May you do good and not evil.
  7730. ** May you find forgiveness for yourself and forgive others.
  7731. ** May you share freely, never taking more than you give.
  7732. **
  7733. *************************************************************************
  7734. */
  7735. #ifndef _SQLITE3RTREE_H_
  7736. #define _SQLITE3RTREE_H_
  7737. #if 0
  7738. extern "C" {
  7739. #endif
  7740. typedef struct sqlite3_rtree_geometry sqlite3_rtree_geometry;
  7741. typedef struct sqlite3_rtree_query_info sqlite3_rtree_query_info;
  7742. /* The double-precision datatype used by RTree depends on the
  7743. ** SQLITE_RTREE_INT_ONLY compile-time option.
  7744. */
  7745. #ifdef SQLITE_RTREE_INT_ONLY
  7746. typedef sqlite3_int64 sqlite3_rtree_dbl;
  7747. #else
  7748. typedef double sqlite3_rtree_dbl;
  7749. #endif
  7750. /*
  7751. ** Register a geometry callback named zGeom that can be used as part of an
  7752. ** R-Tree geometry query as follows:
  7753. **
  7754. ** SELECT ... FROM <rtree> WHERE <rtree col> MATCH $zGeom(... params ...)
  7755. */
  7756. SQLITE_API int SQLITE_STDCALL sqlite3_rtree_geometry_callback(
  7757. sqlite3 *db,
  7758. const char *zGeom,
  7759. int (*xGeom)(sqlite3_rtree_geometry*, int, sqlite3_rtree_dbl*,int*),
  7760. void *pContext
  7761. );
  7762. /*
  7763. ** A pointer to a structure of the following type is passed as the first
  7764. ** argument to callbacks registered using rtree_geometry_callback().
  7765. */
  7766. struct sqlite3_rtree_geometry {
  7767. void *pContext; /* Copy of pContext passed to s_r_g_c() */
  7768. int nParam; /* Size of array aParam[] */
  7769. sqlite3_rtree_dbl *aParam; /* Parameters passed to SQL geom function */
  7770. void *pUser; /* Callback implementation user data */
  7771. void (*xDelUser)(void *); /* Called by SQLite to clean up pUser */
  7772. };
  7773. /*
  7774. ** Register a 2nd-generation geometry callback named zScore that can be
  7775. ** used as part of an R-Tree geometry query as follows:
  7776. **
  7777. ** SELECT ... FROM <rtree> WHERE <rtree col> MATCH $zQueryFunc(... params ...)
  7778. */
  7779. SQLITE_API int SQLITE_STDCALL sqlite3_rtree_query_callback(
  7780. sqlite3 *db,
  7781. const char *zQueryFunc,
  7782. int (*xQueryFunc)(sqlite3_rtree_query_info*),
  7783. void *pContext,
  7784. void (*xDestructor)(void*)
  7785. );
  7786. /*
  7787. ** A pointer to a structure of the following type is passed as the
  7788. ** argument to scored geometry callback registered using
  7789. ** sqlite3_rtree_query_callback().
  7790. **
  7791. ** Note that the first 5 fields of this structure are identical to
  7792. ** sqlite3_rtree_geometry. This structure is a subclass of
  7793. ** sqlite3_rtree_geometry.
  7794. */
  7795. struct sqlite3_rtree_query_info {
  7796. void *pContext; /* pContext from when function registered */
  7797. int nParam; /* Number of function parameters */
  7798. sqlite3_rtree_dbl *aParam; /* value of function parameters */
  7799. void *pUser; /* callback can use this, if desired */
  7800. void (*xDelUser)(void*); /* function to free pUser */
  7801. sqlite3_rtree_dbl *aCoord; /* Coordinates of node or entry to check */
  7802. unsigned int *anQueue; /* Number of pending entries in the queue */
  7803. int nCoord; /* Number of coordinates */
  7804. int iLevel; /* Level of current node or entry */
  7805. int mxLevel; /* The largest iLevel value in the tree */
  7806. sqlite3_int64 iRowid; /* Rowid for current entry */
  7807. sqlite3_rtree_dbl rParentScore; /* Score of parent node */
  7808. int eParentWithin; /* Visibility of parent node */
  7809. int eWithin; /* OUT: Visiblity */
  7810. sqlite3_rtree_dbl rScore; /* OUT: Write the score here */
  7811. };
  7812. /*
  7813. ** Allowed values for sqlite3_rtree_query.eWithin and .eParentWithin.
  7814. */
  7815. #define NOT_WITHIN 0 /* Object completely outside of query region */
  7816. #define PARTLY_WITHIN 1 /* Object partially overlaps query region */
  7817. #define FULLY_WITHIN 2 /* Object fully contained within query region */
  7818. #if 0
  7819. } /* end of the 'extern "C"' block */
  7820. #endif
  7821. #endif /* ifndef _SQLITE3RTREE_H_ */
  7822. /************** End of sqlite3.h *********************************************/
  7823. /************** Continuing where we left off in sqliteInt.h ******************/
  7824. /*
  7825. ** Include the configuration header output by 'configure' if we're using the
  7826. ** autoconf-based build
  7827. */
  7828. #ifdef _HAVE_SQLITE_CONFIG_H
  7829. #include "config.h"
  7830. #endif
  7831. /************** Include sqliteLimit.h in the middle of sqliteInt.h ***********/
  7832. /************** Begin file sqliteLimit.h *************************************/
  7833. /*
  7834. ** 2007 May 7
  7835. **
  7836. ** The author disclaims copyright to this source code. In place of
  7837. ** a legal notice, here is a blessing:
  7838. **
  7839. ** May you do good and not evil.
  7840. ** May you find forgiveness for yourself and forgive others.
  7841. ** May you share freely, never taking more than you give.
  7842. **
  7843. *************************************************************************
  7844. **
  7845. ** This file defines various limits of what SQLite can process.
  7846. */
  7847. /*
  7848. ** The maximum length of a TEXT or BLOB in bytes. This also
  7849. ** limits the size of a row in a table or index.
  7850. **
  7851. ** The hard limit is the ability of a 32-bit signed integer
  7852. ** to count the size: 2^31-1 or 2147483647.
  7853. */
  7854. #ifndef SQLITE_MAX_LENGTH
  7855. # define SQLITE_MAX_LENGTH 1000000000
  7856. #endif
  7857. /*
  7858. ** This is the maximum number of
  7859. **
  7860. ** * Columns in a table
  7861. ** * Columns in an index
  7862. ** * Columns in a view
  7863. ** * Terms in the SET clause of an UPDATE statement
  7864. ** * Terms in the result set of a SELECT statement
  7865. ** * Terms in the GROUP BY or ORDER BY clauses of a SELECT statement.
  7866. ** * Terms in the VALUES clause of an INSERT statement
  7867. **
  7868. ** The hard upper limit here is 32676. Most database people will
  7869. ** tell you that in a well-normalized database, you usually should
  7870. ** not have more than a dozen or so columns in any table. And if
  7871. ** that is the case, there is no point in having more than a few
  7872. ** dozen values in any of the other situations described above.
  7873. */
  7874. #ifndef SQLITE_MAX_COLUMN
  7875. # define SQLITE_MAX_COLUMN 2000
  7876. #endif
  7877. /*
  7878. ** The maximum length of a single SQL statement in bytes.
  7879. **
  7880. ** It used to be the case that setting this value to zero would
  7881. ** turn the limit off. That is no longer true. It is not possible
  7882. ** to turn this limit off.
  7883. */
  7884. #ifndef SQLITE_MAX_SQL_LENGTH
  7885. # define SQLITE_MAX_SQL_LENGTH 1000000000
  7886. #endif
  7887. /*
  7888. ** The maximum depth of an expression tree. This is limited to
  7889. ** some extent by SQLITE_MAX_SQL_LENGTH. But sometime you might
  7890. ** want to place more severe limits on the complexity of an
  7891. ** expression.
  7892. **
  7893. ** A value of 0 used to mean that the limit was not enforced.
  7894. ** But that is no longer true. The limit is now strictly enforced
  7895. ** at all times.
  7896. */
  7897. #ifndef SQLITE_MAX_EXPR_DEPTH
  7898. # define SQLITE_MAX_EXPR_DEPTH 1000
  7899. #endif
  7900. /*
  7901. ** The maximum number of terms in a compound SELECT statement.
  7902. ** The code generator for compound SELECT statements does one
  7903. ** level of recursion for each term. A stack overflow can result
  7904. ** if the number of terms is too large. In practice, most SQL
  7905. ** never has more than 3 or 4 terms. Use a value of 0 to disable
  7906. ** any limit on the number of terms in a compount SELECT.
  7907. */
  7908. #ifndef SQLITE_MAX_COMPOUND_SELECT
  7909. # define SQLITE_MAX_COMPOUND_SELECT 500
  7910. #endif
  7911. /*
  7912. ** The maximum number of opcodes in a VDBE program.
  7913. ** Not currently enforced.
  7914. */
  7915. #ifndef SQLITE_MAX_VDBE_OP
  7916. # define SQLITE_MAX_VDBE_OP 25000
  7917. #endif
  7918. /*
  7919. ** The maximum number of arguments to an SQL function.
  7920. */
  7921. #ifndef SQLITE_MAX_FUNCTION_ARG
  7922. # define SQLITE_MAX_FUNCTION_ARG 127
  7923. #endif
  7924. /*
  7925. ** The suggested maximum number of in-memory pages to use for
  7926. ** the main database table and for temporary tables.
  7927. **
  7928. ** IMPLEMENTATION-OF: R-31093-59126 The default suggested cache size
  7929. ** is 2000 pages.
  7930. ** IMPLEMENTATION-OF: R-48205-43578 The default suggested cache size can be
  7931. ** altered using the SQLITE_DEFAULT_CACHE_SIZE compile-time options.
  7932. */
  7933. #ifndef SQLITE_DEFAULT_CACHE_SIZE
  7934. # define SQLITE_DEFAULT_CACHE_SIZE 2000
  7935. #endif
  7936. /*
  7937. ** The default number of frames to accumulate in the log file before
  7938. ** checkpointing the database in WAL mode.
  7939. */
  7940. #ifndef SQLITE_DEFAULT_WAL_AUTOCHECKPOINT
  7941. # define SQLITE_DEFAULT_WAL_AUTOCHECKPOINT 1000
  7942. #endif
  7943. /*
  7944. ** The maximum number of attached databases. This must be between 0
  7945. ** and 62. The upper bound on 62 is because a 64-bit integer bitmap
  7946. ** is used internally to track attached databases.
  7947. */
  7948. #ifndef SQLITE_MAX_ATTACHED
  7949. # define SQLITE_MAX_ATTACHED 10
  7950. #endif
  7951. /*
  7952. ** The maximum value of a ?nnn wildcard that the parser will accept.
  7953. */
  7954. #ifndef SQLITE_MAX_VARIABLE_NUMBER
  7955. # define SQLITE_MAX_VARIABLE_NUMBER 999
  7956. #endif
  7957. /* Maximum page size. The upper bound on this value is 65536. This a limit
  7958. ** imposed by the use of 16-bit offsets within each page.
  7959. **
  7960. ** Earlier versions of SQLite allowed the user to change this value at
  7961. ** compile time. This is no longer permitted, on the grounds that it creates
  7962. ** a library that is technically incompatible with an SQLite library
  7963. ** compiled with a different limit. If a process operating on a database
  7964. ** with a page-size of 65536 bytes crashes, then an instance of SQLite
  7965. ** compiled with the default page-size limit will not be able to rollback
  7966. ** the aborted transaction. This could lead to database corruption.
  7967. */
  7968. #ifdef SQLITE_MAX_PAGE_SIZE
  7969. # undef SQLITE_MAX_PAGE_SIZE
  7970. #endif
  7971. #define SQLITE_MAX_PAGE_SIZE 65536
  7972. /*
  7973. ** The default size of a database page.
  7974. */
  7975. #ifndef SQLITE_DEFAULT_PAGE_SIZE
  7976. # define SQLITE_DEFAULT_PAGE_SIZE 1024
  7977. #endif
  7978. #if SQLITE_DEFAULT_PAGE_SIZE>SQLITE_MAX_PAGE_SIZE
  7979. # undef SQLITE_DEFAULT_PAGE_SIZE
  7980. # define SQLITE_DEFAULT_PAGE_SIZE SQLITE_MAX_PAGE_SIZE
  7981. #endif
  7982. /*
  7983. ** Ordinarily, if no value is explicitly provided, SQLite creates databases
  7984. ** with page size SQLITE_DEFAULT_PAGE_SIZE. However, based on certain
  7985. ** device characteristics (sector-size and atomic write() support),
  7986. ** SQLite may choose a larger value. This constant is the maximum value
  7987. ** SQLite will choose on its own.
  7988. */
  7989. #ifndef SQLITE_MAX_DEFAULT_PAGE_SIZE
  7990. # define SQLITE_MAX_DEFAULT_PAGE_SIZE 8192
  7991. #endif
  7992. #if SQLITE_MAX_DEFAULT_PAGE_SIZE>SQLITE_MAX_PAGE_SIZE
  7993. # undef SQLITE_MAX_DEFAULT_PAGE_SIZE
  7994. # define SQLITE_MAX_DEFAULT_PAGE_SIZE SQLITE_MAX_PAGE_SIZE
  7995. #endif
  7996. /*
  7997. ** Maximum number of pages in one database file.
  7998. **
  7999. ** This is really just the default value for the max_page_count pragma.
  8000. ** This value can be lowered (or raised) at run-time using that the
  8001. ** max_page_count macro.
  8002. */
  8003. #ifndef SQLITE_MAX_PAGE_COUNT
  8004. # define SQLITE_MAX_PAGE_COUNT 1073741823
  8005. #endif
  8006. /*
  8007. ** Maximum length (in bytes) of the pattern in a LIKE or GLOB
  8008. ** operator.
  8009. */
  8010. #ifndef SQLITE_MAX_LIKE_PATTERN_LENGTH
  8011. # define SQLITE_MAX_LIKE_PATTERN_LENGTH 50000
  8012. #endif
  8013. /*
  8014. ** Maximum depth of recursion for triggers.
  8015. **
  8016. ** A value of 1 means that a trigger program will not be able to itself
  8017. ** fire any triggers. A value of 0 means that no trigger programs at all
  8018. ** may be executed.
  8019. */
  8020. #ifndef SQLITE_MAX_TRIGGER_DEPTH
  8021. # define SQLITE_MAX_TRIGGER_DEPTH 1000
  8022. #endif
  8023. /************** End of sqliteLimit.h *****************************************/
  8024. /************** Continuing where we left off in sqliteInt.h ******************/
  8025. /* Disable nuisance warnings on Borland compilers */
  8026. #if defined(__BORLANDC__)
  8027. #pragma warn -rch /* unreachable code */
  8028. #pragma warn -ccc /* Condition is always true or false */
  8029. #pragma warn -aus /* Assigned value is never used */
  8030. #pragma warn -csu /* Comparing signed and unsigned */
  8031. #pragma warn -spa /* Suspicious pointer arithmetic */
  8032. #endif
  8033. /*
  8034. ** Include standard header files as necessary
  8035. */
  8036. #ifdef HAVE_STDINT_H
  8037. #include <stdint.h>
  8038. #endif
  8039. #ifdef HAVE_INTTYPES_H
  8040. #include <inttypes.h>
  8041. #endif
  8042. /*
  8043. ** The following macros are used to cast pointers to integers and
  8044. ** integers to pointers. The way you do this varies from one compiler
  8045. ** to the next, so we have developed the following set of #if statements
  8046. ** to generate appropriate macros for a wide range of compilers.
  8047. **
  8048. ** The correct "ANSI" way to do this is to use the intptr_t type.
  8049. ** Unfortunately, that typedef is not available on all compilers, or
  8050. ** if it is available, it requires an #include of specific headers
  8051. ** that vary from one machine to the next.
  8052. **
  8053. ** Ticket #3860: The llvm-gcc-4.2 compiler from Apple chokes on
  8054. ** the ((void*)&((char*)0)[X]) construct. But MSVC chokes on ((void*)(X)).
  8055. ** So we have to define the macros in different ways depending on the
  8056. ** compiler.
  8057. */
  8058. #if defined(__PTRDIFF_TYPE__) /* This case should work for GCC */
  8059. # define SQLITE_INT_TO_PTR(X) ((void*)(__PTRDIFF_TYPE__)(X))
  8060. # define SQLITE_PTR_TO_INT(X) ((int)(__PTRDIFF_TYPE__)(X))
  8061. #elif !defined(__GNUC__) /* Works for compilers other than LLVM */
  8062. # define SQLITE_INT_TO_PTR(X) ((void*)&((char*)0)[X])
  8063. # define SQLITE_PTR_TO_INT(X) ((int)(((char*)X)-(char*)0))
  8064. #elif defined(HAVE_STDINT_H) /* Use this case if we have ANSI headers */
  8065. # define SQLITE_INT_TO_PTR(X) ((void*)(intptr_t)(X))
  8066. # define SQLITE_PTR_TO_INT(X) ((int)(intptr_t)(X))
  8067. #else /* Generates a warning - but it always works */
  8068. # define SQLITE_INT_TO_PTR(X) ((void*)(X))
  8069. # define SQLITE_PTR_TO_INT(X) ((int)(X))
  8070. #endif
  8071. /*
  8072. ** A macro to hint to the compiler that a function should not be
  8073. ** inlined.
  8074. */
  8075. #if defined(__GNUC__)
  8076. # define SQLITE_NOINLINE __attribute__((noinline))
  8077. #elif defined(_MSC_VER) && _MSC_VER>=1310
  8078. # define SQLITE_NOINLINE __declspec(noinline)
  8079. #else
  8080. # define SQLITE_NOINLINE
  8081. #endif
  8082. /*
  8083. ** The SQLITE_THREADSAFE macro must be defined as 0, 1, or 2.
  8084. ** 0 means mutexes are permanently disable and the library is never
  8085. ** threadsafe. 1 means the library is serialized which is the highest
  8086. ** level of threadsafety. 2 means the library is multithreaded - multiple
  8087. ** threads can use SQLite as long as no two threads try to use the same
  8088. ** database connection at the same time.
  8089. **
  8090. ** Older versions of SQLite used an optional THREADSAFE macro.
  8091. ** We support that for legacy.
  8092. */
  8093. #if !defined(SQLITE_THREADSAFE)
  8094. # if defined(THREADSAFE)
  8095. # define SQLITE_THREADSAFE THREADSAFE
  8096. # else
  8097. # define SQLITE_THREADSAFE 1 /* IMP: R-07272-22309 */
  8098. # endif
  8099. #endif
  8100. /*
  8101. ** Powersafe overwrite is on by default. But can be turned off using
  8102. ** the -DSQLITE_POWERSAFE_OVERWRITE=0 command-line option.
  8103. */
  8104. #ifndef SQLITE_POWERSAFE_OVERWRITE
  8105. # define SQLITE_POWERSAFE_OVERWRITE 1
  8106. #endif
  8107. /*
  8108. ** EVIDENCE-OF: R-25715-37072 Memory allocation statistics are enabled by
  8109. ** default unless SQLite is compiled with SQLITE_DEFAULT_MEMSTATUS=0 in
  8110. ** which case memory allocation statistics are disabled by default.
  8111. */
  8112. #if !defined(SQLITE_DEFAULT_MEMSTATUS)
  8113. # define SQLITE_DEFAULT_MEMSTATUS 1
  8114. #endif
  8115. /*
  8116. ** Exactly one of the following macros must be defined in order to
  8117. ** specify which memory allocation subsystem to use.
  8118. **
  8119. ** SQLITE_SYSTEM_MALLOC // Use normal system malloc()
  8120. ** SQLITE_WIN32_MALLOC // Use Win32 native heap API
  8121. ** SQLITE_ZERO_MALLOC // Use a stub allocator that always fails
  8122. ** SQLITE_MEMDEBUG // Debugging version of system malloc()
  8123. **
  8124. ** On Windows, if the SQLITE_WIN32_MALLOC_VALIDATE macro is defined and the
  8125. ** assert() macro is enabled, each call into the Win32 native heap subsystem
  8126. ** will cause HeapValidate to be called. If heap validation should fail, an
  8127. ** assertion will be triggered.
  8128. **
  8129. ** If none of the above are defined, then set SQLITE_SYSTEM_MALLOC as
  8130. ** the default.
  8131. */
  8132. #if defined(SQLITE_SYSTEM_MALLOC) \
  8133. + defined(SQLITE_WIN32_MALLOC) \
  8134. + defined(SQLITE_ZERO_MALLOC) \
  8135. + defined(SQLITE_MEMDEBUG)>1
  8136. # error "Two or more of the following compile-time configuration options\
  8137. are defined but at most one is allowed:\
  8138. SQLITE_SYSTEM_MALLOC, SQLITE_WIN32_MALLOC, SQLITE_MEMDEBUG,\
  8139. SQLITE_ZERO_MALLOC"
  8140. #endif
  8141. #if defined(SQLITE_SYSTEM_MALLOC) \
  8142. + defined(SQLITE_WIN32_MALLOC) \
  8143. + defined(SQLITE_ZERO_MALLOC) \
  8144. + defined(SQLITE_MEMDEBUG)==0
  8145. # define SQLITE_SYSTEM_MALLOC 1
  8146. #endif
  8147. /*
  8148. ** If SQLITE_MALLOC_SOFT_LIMIT is not zero, then try to keep the
  8149. ** sizes of memory allocations below this value where possible.
  8150. */
  8151. #if !defined(SQLITE_MALLOC_SOFT_LIMIT)
  8152. # define SQLITE_MALLOC_SOFT_LIMIT 1024
  8153. #endif
  8154. /*
  8155. ** We need to define _XOPEN_SOURCE as follows in order to enable
  8156. ** recursive mutexes on most Unix systems and fchmod() on OpenBSD.
  8157. ** But _XOPEN_SOURCE define causes problems for Mac OS X, so omit
  8158. ** it.
  8159. */
  8160. #if !defined(_XOPEN_SOURCE) && !defined(__DARWIN__) && !defined(__APPLE__)
  8161. # define _XOPEN_SOURCE 600
  8162. #endif
  8163. /*
  8164. ** NDEBUG and SQLITE_DEBUG are opposites. It should always be true that
  8165. ** defined(NDEBUG)==!defined(SQLITE_DEBUG). If this is not currently true,
  8166. ** make it true by defining or undefining NDEBUG.
  8167. **
  8168. ** Setting NDEBUG makes the code smaller and faster by disabling the
  8169. ** assert() statements in the code. So we want the default action
  8170. ** to be for NDEBUG to be set and NDEBUG to be undefined only if SQLITE_DEBUG
  8171. ** is set. Thus NDEBUG becomes an opt-in rather than an opt-out
  8172. ** feature.
  8173. */
  8174. #if !defined(NDEBUG) && !defined(SQLITE_DEBUG)
  8175. # define NDEBUG 1
  8176. #endif
  8177. #if defined(NDEBUG) && defined(SQLITE_DEBUG)
  8178. # undef NDEBUG
  8179. #endif
  8180. /*
  8181. ** Enable SQLITE_ENABLE_EXPLAIN_COMMENTS if SQLITE_DEBUG is turned on.
  8182. */
  8183. #if !defined(SQLITE_ENABLE_EXPLAIN_COMMENTS) && defined(SQLITE_DEBUG)
  8184. # define SQLITE_ENABLE_EXPLAIN_COMMENTS 1
  8185. #endif
  8186. /*
  8187. ** The testcase() macro is used to aid in coverage testing. When
  8188. ** doing coverage testing, the condition inside the argument to
  8189. ** testcase() must be evaluated both true and false in order to
  8190. ** get full branch coverage. The testcase() macro is inserted
  8191. ** to help ensure adequate test coverage in places where simple
  8192. ** condition/decision coverage is inadequate. For example, testcase()
  8193. ** can be used to make sure boundary values are tested. For
  8194. ** bitmask tests, testcase() can be used to make sure each bit
  8195. ** is significant and used at least once. On switch statements
  8196. ** where multiple cases go to the same block of code, testcase()
  8197. ** can insure that all cases are evaluated.
  8198. **
  8199. */
  8200. #ifdef SQLITE_COVERAGE_TEST
  8201. SQLITE_PRIVATE void sqlite3Coverage(int);
  8202. # define testcase(X) if( X ){ sqlite3Coverage(__LINE__); }
  8203. #else
  8204. # define testcase(X)
  8205. #endif
  8206. /*
  8207. ** The TESTONLY macro is used to enclose variable declarations or
  8208. ** other bits of code that are needed to support the arguments
  8209. ** within testcase() and assert() macros.
  8210. */
  8211. #if !defined(NDEBUG) || defined(SQLITE_COVERAGE_TEST)
  8212. # define TESTONLY(X) X
  8213. #else
  8214. # define TESTONLY(X)
  8215. #endif
  8216. /*
  8217. ** Sometimes we need a small amount of code such as a variable initialization
  8218. ** to setup for a later assert() statement. We do not want this code to
  8219. ** appear when assert() is disabled. The following macro is therefore
  8220. ** used to contain that setup code. The "VVA" acronym stands for
  8221. ** "Verification, Validation, and Accreditation". In other words, the
  8222. ** code within VVA_ONLY() will only run during verification processes.
  8223. */
  8224. #ifndef NDEBUG
  8225. # define VVA_ONLY(X) X
  8226. #else
  8227. # define VVA_ONLY(X)
  8228. #endif
  8229. /*
  8230. ** The ALWAYS and NEVER macros surround boolean expressions which
  8231. ** are intended to always be true or false, respectively. Such
  8232. ** expressions could be omitted from the code completely. But they
  8233. ** are included in a few cases in order to enhance the resilience
  8234. ** of SQLite to unexpected behavior - to make the code "self-healing"
  8235. ** or "ductile" rather than being "brittle" and crashing at the first
  8236. ** hint of unplanned behavior.
  8237. **
  8238. ** In other words, ALWAYS and NEVER are added for defensive code.
  8239. **
  8240. ** When doing coverage testing ALWAYS and NEVER are hard-coded to
  8241. ** be true and false so that the unreachable code they specify will
  8242. ** not be counted as untested code.
  8243. */
  8244. #if defined(SQLITE_COVERAGE_TEST)
  8245. # define ALWAYS(X) (1)
  8246. # define NEVER(X) (0)
  8247. #elif !defined(NDEBUG)
  8248. # define ALWAYS(X) ((X)?1:(assert(0),0))
  8249. # define NEVER(X) ((X)?(assert(0),1):0)
  8250. #else
  8251. # define ALWAYS(X) (X)
  8252. # define NEVER(X) (X)
  8253. #endif
  8254. /*
  8255. ** Declarations used for tracing the operating system interfaces.
  8256. */
  8257. #if defined(SQLITE_FORCE_OS_TRACE) || defined(SQLITE_TEST) || \
  8258. (defined(SQLITE_DEBUG) && SQLITE_OS_WIN)
  8259. extern int sqlite3OSTrace;
  8260. # define OSTRACE(X) if( sqlite3OSTrace ) sqlite3DebugPrintf X
  8261. # define SQLITE_HAVE_OS_TRACE
  8262. #else
  8263. # define OSTRACE(X)
  8264. # undef SQLITE_HAVE_OS_TRACE
  8265. #endif
  8266. /*
  8267. ** Is the sqlite3ErrName() function needed in the build? Currently,
  8268. ** it is needed by "mutex_w32.c" (when debugging), "os_win.c" (when
  8269. ** OSTRACE is enabled), and by several "test*.c" files (which are
  8270. ** compiled using SQLITE_TEST).
  8271. */
  8272. #if defined(SQLITE_HAVE_OS_TRACE) || defined(SQLITE_TEST) || \
  8273. (defined(SQLITE_DEBUG) && SQLITE_OS_WIN)
  8274. # define SQLITE_NEED_ERR_NAME
  8275. #else
  8276. # undef SQLITE_NEED_ERR_NAME
  8277. #endif
  8278. /*
  8279. ** Return true (non-zero) if the input is an integer that is too large
  8280. ** to fit in 32-bits. This macro is used inside of various testcase()
  8281. ** macros to verify that we have tested SQLite for large-file support.
  8282. */
  8283. #define IS_BIG_INT(X) (((X)&~(i64)0xffffffff)!=0)
  8284. /*
  8285. ** The macro unlikely() is a hint that surrounds a boolean
  8286. ** expression that is usually false. Macro likely() surrounds
  8287. ** a boolean expression that is usually true. These hints could,
  8288. ** in theory, be used by the compiler to generate better code, but
  8289. ** currently they are just comments for human readers.
  8290. */
  8291. #define likely(X) (X)
  8292. #define unlikely(X) (X)
  8293. /************** Include hash.h in the middle of sqliteInt.h ******************/
  8294. /************** Begin file hash.h ********************************************/
  8295. /*
  8296. ** 2001 September 22
  8297. **
  8298. ** The author disclaims copyright to this source code. In place of
  8299. ** a legal notice, here is a blessing:
  8300. **
  8301. ** May you do good and not evil.
  8302. ** May you find forgiveness for yourself and forgive others.
  8303. ** May you share freely, never taking more than you give.
  8304. **
  8305. *************************************************************************
  8306. ** This is the header file for the generic hash-table implementation
  8307. ** used in SQLite.
  8308. */
  8309. #ifndef _SQLITE_HASH_H_
  8310. #define _SQLITE_HASH_H_
  8311. /* Forward declarations of structures. */
  8312. typedef struct Hash Hash;
  8313. typedef struct HashElem HashElem;
  8314. /* A complete hash table is an instance of the following structure.
  8315. ** The internals of this structure are intended to be opaque -- client
  8316. ** code should not attempt to access or modify the fields of this structure
  8317. ** directly. Change this structure only by using the routines below.
  8318. ** However, some of the "procedures" and "functions" for modifying and
  8319. ** accessing this structure are really macros, so we can't really make
  8320. ** this structure opaque.
  8321. **
  8322. ** All elements of the hash table are on a single doubly-linked list.
  8323. ** Hash.first points to the head of this list.
  8324. **
  8325. ** There are Hash.htsize buckets. Each bucket points to a spot in
  8326. ** the global doubly-linked list. The contents of the bucket are the
  8327. ** element pointed to plus the next _ht.count-1 elements in the list.
  8328. **
  8329. ** Hash.htsize and Hash.ht may be zero. In that case lookup is done
  8330. ** by a linear search of the global list. For small tables, the
  8331. ** Hash.ht table is never allocated because if there are few elements
  8332. ** in the table, it is faster to do a linear search than to manage
  8333. ** the hash table.
  8334. */
  8335. struct Hash {
  8336. unsigned int htsize; /* Number of buckets in the hash table */
  8337. unsigned int count; /* Number of entries in this table */
  8338. HashElem *first; /* The first element of the array */
  8339. struct _ht { /* the hash table */
  8340. int count; /* Number of entries with this hash */
  8341. HashElem *chain; /* Pointer to first entry with this hash */
  8342. } *ht;
  8343. };
  8344. /* Each element in the hash table is an instance of the following
  8345. ** structure. All elements are stored on a single doubly-linked list.
  8346. **
  8347. ** Again, this structure is intended to be opaque, but it can't really
  8348. ** be opaque because it is used by macros.
  8349. */
  8350. struct HashElem {
  8351. HashElem *next, *prev; /* Next and previous elements in the table */
  8352. void *data; /* Data associated with this element */
  8353. const char *pKey; /* Key associated with this element */
  8354. };
  8355. /*
  8356. ** Access routines. To delete, insert a NULL pointer.
  8357. */
  8358. SQLITE_PRIVATE void sqlite3HashInit(Hash*);
  8359. SQLITE_PRIVATE void *sqlite3HashInsert(Hash*, const char *pKey, void *pData);
  8360. SQLITE_PRIVATE void *sqlite3HashFind(const Hash*, const char *pKey);
  8361. SQLITE_PRIVATE void sqlite3HashClear(Hash*);
  8362. /*
  8363. ** Macros for looping over all elements of a hash table. The idiom is
  8364. ** like this:
  8365. **
  8366. ** Hash h;
  8367. ** HashElem *p;
  8368. ** ...
  8369. ** for(p=sqliteHashFirst(&h); p; p=sqliteHashNext(p)){
  8370. ** SomeStructure *pData = sqliteHashData(p);
  8371. ** // do something with pData
  8372. ** }
  8373. */
  8374. #define sqliteHashFirst(H) ((H)->first)
  8375. #define sqliteHashNext(E) ((E)->next)
  8376. #define sqliteHashData(E) ((E)->data)
  8377. /* #define sqliteHashKey(E) ((E)->pKey) // NOT USED */
  8378. /* #define sqliteHashKeysize(E) ((E)->nKey) // NOT USED */
  8379. /*
  8380. ** Number of entries in a hash table
  8381. */
  8382. /* #define sqliteHashCount(H) ((H)->count) // NOT USED */
  8383. #endif /* _SQLITE_HASH_H_ */
  8384. /************** End of hash.h ************************************************/
  8385. /************** Continuing where we left off in sqliteInt.h ******************/
  8386. /************** Include parse.h in the middle of sqliteInt.h *****************/
  8387. /************** Begin file parse.h *******************************************/
  8388. #define TK_SEMI 1
  8389. #define TK_EXPLAIN 2
  8390. #define TK_QUERY 3
  8391. #define TK_PLAN 4
  8392. #define TK_BEGIN 5
  8393. #define TK_TRANSACTION 6
  8394. #define TK_DEFERRED 7
  8395. #define TK_IMMEDIATE 8
  8396. #define TK_EXCLUSIVE 9
  8397. #define TK_COMMIT 10
  8398. #define TK_END 11
  8399. #define TK_ROLLBACK 12
  8400. #define TK_SAVEPOINT 13
  8401. #define TK_RELEASE 14
  8402. #define TK_TO 15
  8403. #define TK_TABLE 16
  8404. #define TK_CREATE 17
  8405. #define TK_IF 18
  8406. #define TK_NOT 19
  8407. #define TK_EXISTS 20
  8408. #define TK_TEMP 21
  8409. #define TK_LP 22
  8410. #define TK_RP 23
  8411. #define TK_AS 24
  8412. #define TK_WITHOUT 25
  8413. #define TK_COMMA 26
  8414. #define TK_ID 27
  8415. #define TK_INDEXED 28
  8416. #define TK_ABORT 29
  8417. #define TK_ACTION 30
  8418. #define TK_AFTER 31
  8419. #define TK_ANALYZE 32
  8420. #define TK_ASC 33
  8421. #define TK_ATTACH 34
  8422. #define TK_BEFORE 35
  8423. #define TK_BY 36
  8424. #define TK_CASCADE 37
  8425. #define TK_CAST 38
  8426. #define TK_COLUMNKW 39
  8427. #define TK_CONFLICT 40
  8428. #define TK_DATABASE 41
  8429. #define TK_DESC 42
  8430. #define TK_DETACH 43
  8431. #define TK_EACH 44
  8432. #define TK_FAIL 45
  8433. #define TK_FOR 46
  8434. #define TK_IGNORE 47
  8435. #define TK_INITIALLY 48
  8436. #define TK_INSTEAD 49
  8437. #define TK_LIKE_KW 50
  8438. #define TK_MATCH 51
  8439. #define TK_NO 52
  8440. #define TK_KEY 53
  8441. #define TK_OF 54
  8442. #define TK_OFFSET 55
  8443. #define TK_PRAGMA 56
  8444. #define TK_RAISE 57
  8445. #define TK_RECURSIVE 58
  8446. #define TK_REPLACE 59
  8447. #define TK_RESTRICT 60
  8448. #define TK_ROW 61
  8449. #define TK_TRIGGER 62
  8450. #define TK_VACUUM 63
  8451. #define TK_VIEW 64
  8452. #define TK_VIRTUAL 65
  8453. #define TK_WITH 66
  8454. #define TK_REINDEX 67
  8455. #define TK_RENAME 68
  8456. #define TK_CTIME_KW 69
  8457. #define TK_ANY 70
  8458. #define TK_OR 71
  8459. #define TK_AND 72
  8460. #define TK_IS 73
  8461. #define TK_BETWEEN 74
  8462. #define TK_IN 75
  8463. #define TK_ISNULL 76
  8464. #define TK_NOTNULL 77
  8465. #define TK_NE 78
  8466. #define TK_EQ 79
  8467. #define TK_GT 80
  8468. #define TK_LE 81
  8469. #define TK_LT 82
  8470. #define TK_GE 83
  8471. #define TK_ESCAPE 84
  8472. #define TK_BITAND 85
  8473. #define TK_BITOR 86
  8474. #define TK_LSHIFT 87
  8475. #define TK_RSHIFT 88
  8476. #define TK_PLUS 89
  8477. #define TK_MINUS 90
  8478. #define TK_STAR 91
  8479. #define TK_SLASH 92
  8480. #define TK_REM 93
  8481. #define TK_CONCAT 94
  8482. #define TK_COLLATE 95
  8483. #define TK_BITNOT 96
  8484. #define TK_STRING 97
  8485. #define TK_JOIN_KW 98
  8486. #define TK_CONSTRAINT 99
  8487. #define TK_DEFAULT 100
  8488. #define TK_NULL 101
  8489. #define TK_PRIMARY 102
  8490. #define TK_UNIQUE 103
  8491. #define TK_CHECK 104
  8492. #define TK_REFERENCES 105
  8493. #define TK_AUTOINCR 106
  8494. #define TK_ON 107
  8495. #define TK_INSERT 108
  8496. #define TK_DELETE 109
  8497. #define TK_UPDATE 110
  8498. #define TK_SET 111
  8499. #define TK_DEFERRABLE 112
  8500. #define TK_FOREIGN 113
  8501. #define TK_DROP 114
  8502. #define TK_UNION 115
  8503. #define TK_ALL 116
  8504. #define TK_EXCEPT 117
  8505. #define TK_INTERSECT 118
  8506. #define TK_SELECT 119
  8507. #define TK_VALUES 120
  8508. #define TK_DISTINCT 121
  8509. #define TK_DOT 122
  8510. #define TK_FROM 123
  8511. #define TK_JOIN 124
  8512. #define TK_USING 125
  8513. #define TK_ORDER 126
  8514. #define TK_GROUP 127
  8515. #define TK_HAVING 128
  8516. #define TK_LIMIT 129
  8517. #define TK_WHERE 130
  8518. #define TK_INTO 131
  8519. #define TK_INTEGER 132
  8520. #define TK_FLOAT 133
  8521. #define TK_BLOB 134
  8522. #define TK_VARIABLE 135
  8523. #define TK_CASE 136
  8524. #define TK_WHEN 137
  8525. #define TK_THEN 138
  8526. #define TK_ELSE 139
  8527. #define TK_INDEX 140
  8528. #define TK_ALTER 141
  8529. #define TK_ADD 142
  8530. #define TK_TO_TEXT 143
  8531. #define TK_TO_BLOB 144
  8532. #define TK_TO_NUMERIC 145
  8533. #define TK_TO_INT 146
  8534. #define TK_TO_REAL 147
  8535. #define TK_ISNOT 148
  8536. #define TK_END_OF_FILE 149
  8537. #define TK_ILLEGAL 150
  8538. #define TK_SPACE 151
  8539. #define TK_UNCLOSED_STRING 152
  8540. #define TK_FUNCTION 153
  8541. #define TK_COLUMN 154
  8542. #define TK_AGG_FUNCTION 155
  8543. #define TK_AGG_COLUMN 156
  8544. #define TK_UMINUS 157
  8545. #define TK_UPLUS 158
  8546. #define TK_REGISTER 159
  8547. /************** End of parse.h ***********************************************/
  8548. /************** Continuing where we left off in sqliteInt.h ******************/
  8549. #include <stdio.h>
  8550. #include <stdlib.h>
  8551. #include <string.h>
  8552. #include <assert.h>
  8553. #include <stddef.h>
  8554. /*
  8555. ** If compiling for a processor that lacks floating point support,
  8556. ** substitute integer for floating-point
  8557. */
  8558. #ifdef SQLITE_OMIT_FLOATING_POINT
  8559. # define double sqlite_int64
  8560. # define float sqlite_int64
  8561. # define LONGDOUBLE_TYPE sqlite_int64
  8562. # ifndef SQLITE_BIG_DBL
  8563. # define SQLITE_BIG_DBL (((sqlite3_int64)1)<<50)
  8564. # endif
  8565. # define SQLITE_OMIT_DATETIME_FUNCS 1
  8566. # define SQLITE_OMIT_TRACE 1
  8567. # undef SQLITE_MIXED_ENDIAN_64BIT_FLOAT
  8568. # undef SQLITE_HAVE_ISNAN
  8569. #endif
  8570. #ifndef SQLITE_BIG_DBL
  8571. # define SQLITE_BIG_DBL (1e99)
  8572. #endif
  8573. /*
  8574. ** OMIT_TEMPDB is set to 1 if SQLITE_OMIT_TEMPDB is defined, or 0
  8575. ** afterward. Having this macro allows us to cause the C compiler
  8576. ** to omit code used by TEMP tables without messy #ifndef statements.
  8577. */
  8578. #ifdef SQLITE_OMIT_TEMPDB
  8579. #define OMIT_TEMPDB 1
  8580. #else
  8581. #define OMIT_TEMPDB 0
  8582. #endif
  8583. /*
  8584. ** The "file format" number is an integer that is incremented whenever
  8585. ** the VDBE-level file format changes. The following macros define the
  8586. ** the default file format for new databases and the maximum file format
  8587. ** that the library can read.
  8588. */
  8589. #define SQLITE_MAX_FILE_FORMAT 4
  8590. #ifndef SQLITE_DEFAULT_FILE_FORMAT
  8591. # define SQLITE_DEFAULT_FILE_FORMAT 4
  8592. #endif
  8593. /*
  8594. ** Determine whether triggers are recursive by default. This can be
  8595. ** changed at run-time using a pragma.
  8596. */
  8597. #ifndef SQLITE_DEFAULT_RECURSIVE_TRIGGERS
  8598. # define SQLITE_DEFAULT_RECURSIVE_TRIGGERS 0
  8599. #endif
  8600. /*
  8601. ** Provide a default value for SQLITE_TEMP_STORE in case it is not specified
  8602. ** on the command-line
  8603. */
  8604. #ifndef SQLITE_TEMP_STORE
  8605. # define SQLITE_TEMP_STORE 1
  8606. # define SQLITE_TEMP_STORE_xc 1 /* Exclude from ctime.c */
  8607. #endif
  8608. /*
  8609. ** If no value has been provided for SQLITE_MAX_WORKER_THREADS, or if
  8610. ** SQLITE_TEMP_STORE is set to 3 (never use temporary files), set it
  8611. ** to zero.
  8612. */
  8613. #if SQLITE_TEMP_STORE==3 || SQLITE_THREADSAFE==0
  8614. # undef SQLITE_MAX_WORKER_THREADS
  8615. # define SQLITE_MAX_WORKER_THREADS 0
  8616. #endif
  8617. #ifndef SQLITE_MAX_WORKER_THREADS
  8618. # define SQLITE_MAX_WORKER_THREADS 8
  8619. #endif
  8620. #ifndef SQLITE_DEFAULT_WORKER_THREADS
  8621. # define SQLITE_DEFAULT_WORKER_THREADS 0
  8622. #endif
  8623. #if SQLITE_DEFAULT_WORKER_THREADS>SQLITE_MAX_WORKER_THREADS
  8624. # undef SQLITE_MAX_WORKER_THREADS
  8625. # define SQLITE_MAX_WORKER_THREADS SQLITE_DEFAULT_WORKER_THREADS
  8626. #endif
  8627. /*
  8628. ** GCC does not define the offsetof() macro so we'll have to do it
  8629. ** ourselves.
  8630. */
  8631. #ifndef offsetof
  8632. #define offsetof(STRUCTURE,FIELD) ((int)((char*)&((STRUCTURE*)0)->FIELD))
  8633. #endif
  8634. /*
  8635. ** Macros to compute minimum and maximum of two numbers.
  8636. */
  8637. #define MIN(A,B) ((A)<(B)?(A):(B))
  8638. #define MAX(A,B) ((A)>(B)?(A):(B))
  8639. /*
  8640. ** Swap two objects of type TYPE.
  8641. */
  8642. #define SWAP(TYPE,A,B) {TYPE t=A; A=B; B=t;}
  8643. /*
  8644. ** Check to see if this machine uses EBCDIC. (Yes, believe it or
  8645. ** not, there are still machines out there that use EBCDIC.)
  8646. */
  8647. #if 'A' == '\301'
  8648. # define SQLITE_EBCDIC 1
  8649. #else
  8650. # define SQLITE_ASCII 1
  8651. #endif
  8652. /*
  8653. ** Integers of known sizes. These typedefs might change for architectures
  8654. ** where the sizes very. Preprocessor macros are available so that the
  8655. ** types can be conveniently redefined at compile-type. Like this:
  8656. **
  8657. ** cc '-DUINTPTR_TYPE=long long int' ...
  8658. */
  8659. #ifndef UINT32_TYPE
  8660. # ifdef HAVE_UINT32_T
  8661. # define UINT32_TYPE uint32_t
  8662. # else
  8663. # define UINT32_TYPE unsigned int
  8664. # endif
  8665. #endif
  8666. #ifndef UINT16_TYPE
  8667. # ifdef HAVE_UINT16_T
  8668. # define UINT16_TYPE uint16_t
  8669. # else
  8670. # define UINT16_TYPE unsigned short int
  8671. # endif
  8672. #endif
  8673. #ifndef INT16_TYPE
  8674. # ifdef HAVE_INT16_T
  8675. # define INT16_TYPE int16_t
  8676. # else
  8677. # define INT16_TYPE short int
  8678. # endif
  8679. #endif
  8680. #ifndef UINT8_TYPE
  8681. # ifdef HAVE_UINT8_T
  8682. # define UINT8_TYPE uint8_t
  8683. # else
  8684. # define UINT8_TYPE unsigned char
  8685. # endif
  8686. #endif
  8687. #ifndef INT8_TYPE
  8688. # ifdef HAVE_INT8_T
  8689. # define INT8_TYPE int8_t
  8690. # else
  8691. # define INT8_TYPE signed char
  8692. # endif
  8693. #endif
  8694. #ifndef LONGDOUBLE_TYPE
  8695. # define LONGDOUBLE_TYPE long double
  8696. #endif
  8697. typedef sqlite_int64 i64; /* 8-byte signed integer */
  8698. typedef sqlite_uint64 u64; /* 8-byte unsigned integer */
  8699. typedef UINT32_TYPE u32; /* 4-byte unsigned integer */
  8700. typedef UINT16_TYPE u16; /* 2-byte unsigned integer */
  8701. typedef INT16_TYPE i16; /* 2-byte signed integer */
  8702. typedef UINT8_TYPE u8; /* 1-byte unsigned integer */
  8703. typedef INT8_TYPE i8; /* 1-byte signed integer */
  8704. /*
  8705. ** SQLITE_MAX_U32 is a u64 constant that is the maximum u64 value
  8706. ** that can be stored in a u32 without loss of data. The value
  8707. ** is 0x00000000ffffffff. But because of quirks of some compilers, we
  8708. ** have to specify the value in the less intuitive manner shown:
  8709. */
  8710. #define SQLITE_MAX_U32 ((((u64)1)<<32)-1)
  8711. /*
  8712. ** The datatype used to store estimates of the number of rows in a
  8713. ** table or index. This is an unsigned integer type. For 99.9% of
  8714. ** the world, a 32-bit integer is sufficient. But a 64-bit integer
  8715. ** can be used at compile-time if desired.
  8716. */
  8717. #ifdef SQLITE_64BIT_STATS
  8718. typedef u64 tRowcnt; /* 64-bit only if requested at compile-time */
  8719. #else
  8720. typedef u32 tRowcnt; /* 32-bit is the default */
  8721. #endif
  8722. /*
  8723. ** Estimated quantities used for query planning are stored as 16-bit
  8724. ** logarithms. For quantity X, the value stored is 10*log2(X). This
  8725. ** gives a possible range of values of approximately 1.0e986 to 1e-986.
  8726. ** But the allowed values are "grainy". Not every value is representable.
  8727. ** For example, quantities 16 and 17 are both represented by a LogEst
  8728. ** of 40. However, since LogEst quantities are suppose to be estimates,
  8729. ** not exact values, this imprecision is not a problem.
  8730. **
  8731. ** "LogEst" is short for "Logarithmic Estimate".
  8732. **
  8733. ** Examples:
  8734. ** 1 -> 0 20 -> 43 10000 -> 132
  8735. ** 2 -> 10 25 -> 46 25000 -> 146
  8736. ** 3 -> 16 100 -> 66 1000000 -> 199
  8737. ** 4 -> 20 1000 -> 99 1048576 -> 200
  8738. ** 10 -> 33 1024 -> 100 4294967296 -> 320
  8739. **
  8740. ** The LogEst can be negative to indicate fractional values.
  8741. ** Examples:
  8742. **
  8743. ** 0.5 -> -10 0.1 -> -33 0.0625 -> -40
  8744. */
  8745. typedef INT16_TYPE LogEst;
  8746. /*
  8747. ** Set the SQLITE_PTRSIZE macro to the number of bytes in a pointer
  8748. */
  8749. #ifndef SQLITE_PTRSIZE
  8750. # if defined(__SIZEOF_POINTER__)
  8751. # define SQLITE_PTRSIZE __SIZEOF_POINTER__
  8752. # elif defined(i386) || defined(__i386__) || defined(_M_IX86) || \
  8753. defined(_M_ARM) || defined(__arm__) || defined(__x86)
  8754. # define SQLITE_PTRSIZE 4
  8755. # else
  8756. # define SQLITE_PTRSIZE 8
  8757. # endif
  8758. #endif
  8759. /*
  8760. ** Macros to determine whether the machine is big or little endian,
  8761. ** and whether or not that determination is run-time or compile-time.
  8762. **
  8763. ** For best performance, an attempt is made to guess at the byte-order
  8764. ** using C-preprocessor macros. If that is unsuccessful, or if
  8765. ** -DSQLITE_RUNTIME_BYTEORDER=1 is set, then byte-order is determined
  8766. ** at run-time.
  8767. */
  8768. #ifdef SQLITE_AMALGAMATION
  8769. SQLITE_PRIVATE const int sqlite3one = 1;
  8770. #else
  8771. SQLITE_PRIVATE const int sqlite3one;
  8772. #endif
  8773. #if (defined(i386) || defined(__i386__) || defined(_M_IX86) || \
  8774. defined(__x86_64) || defined(__x86_64__) || defined(_M_X64) || \
  8775. defined(_M_AMD64) || defined(_M_ARM) || defined(__x86) || \
  8776. defined(__arm__)) && !defined(SQLITE_RUNTIME_BYTEORDER)
  8777. # define SQLITE_BYTEORDER 1234
  8778. # define SQLITE_BIGENDIAN 0
  8779. # define SQLITE_LITTLEENDIAN 1
  8780. # define SQLITE_UTF16NATIVE SQLITE_UTF16LE
  8781. #endif
  8782. #if (defined(sparc) || defined(__ppc__)) \
  8783. && !defined(SQLITE_RUNTIME_BYTEORDER)
  8784. # define SQLITE_BYTEORDER 4321
  8785. # define SQLITE_BIGENDIAN 1
  8786. # define SQLITE_LITTLEENDIAN 0
  8787. # define SQLITE_UTF16NATIVE SQLITE_UTF16BE
  8788. #endif
  8789. #if !defined(SQLITE_BYTEORDER)
  8790. # define SQLITE_BYTEORDER 0 /* 0 means "unknown at compile-time" */
  8791. # define SQLITE_BIGENDIAN (*(char *)(&sqlite3one)==0)
  8792. # define SQLITE_LITTLEENDIAN (*(char *)(&sqlite3one)==1)
  8793. # define SQLITE_UTF16NATIVE (SQLITE_BIGENDIAN?SQLITE_UTF16BE:SQLITE_UTF16LE)
  8794. #endif
  8795. /*
  8796. ** Constants for the largest and smallest possible 64-bit signed integers.
  8797. ** These macros are designed to work correctly on both 32-bit and 64-bit
  8798. ** compilers.
  8799. */
  8800. #define LARGEST_INT64 (0xffffffff|(((i64)0x7fffffff)<<32))
  8801. #define SMALLEST_INT64 (((i64)-1) - LARGEST_INT64)
  8802. /*
  8803. ** Round up a number to the next larger multiple of 8. This is used
  8804. ** to force 8-byte alignment on 64-bit architectures.
  8805. */
  8806. #define ROUND8(x) (((x)+7)&~7)
  8807. /*
  8808. ** Round down to the nearest multiple of 8
  8809. */
  8810. #define ROUNDDOWN8(x) ((x)&~7)
  8811. /*
  8812. ** Assert that the pointer X is aligned to an 8-byte boundary. This
  8813. ** macro is used only within assert() to verify that the code gets
  8814. ** all alignment restrictions correct.
  8815. **
  8816. ** Except, if SQLITE_4_BYTE_ALIGNED_MALLOC is defined, then the
  8817. ** underlying malloc() implementation might return us 4-byte aligned
  8818. ** pointers. In that case, only verify 4-byte alignment.
  8819. */
  8820. #ifdef SQLITE_4_BYTE_ALIGNED_MALLOC
  8821. # define EIGHT_BYTE_ALIGNMENT(X) ((((char*)(X) - (char*)0)&3)==0)
  8822. #else
  8823. # define EIGHT_BYTE_ALIGNMENT(X) ((((char*)(X) - (char*)0)&7)==0)
  8824. #endif
  8825. /*
  8826. ** Disable MMAP on platforms where it is known to not work
  8827. */
  8828. #if defined(__OpenBSD__) || defined(__QNXNTO__)
  8829. # undef SQLITE_MAX_MMAP_SIZE
  8830. # define SQLITE_MAX_MMAP_SIZE 0
  8831. #endif
  8832. /*
  8833. ** Default maximum size of memory used by memory-mapped I/O in the VFS
  8834. */
  8835. #ifdef __APPLE__
  8836. # include <TargetConditionals.h>
  8837. # if TARGET_OS_IPHONE
  8838. # undef SQLITE_MAX_MMAP_SIZE
  8839. # define SQLITE_MAX_MMAP_SIZE 0
  8840. # endif
  8841. #endif
  8842. #ifndef SQLITE_MAX_MMAP_SIZE
  8843. # if defined(__linux__) \
  8844. || defined(_WIN32) \
  8845. || (defined(__APPLE__) && defined(__MACH__)) \
  8846. || defined(__sun)
  8847. # define SQLITE_MAX_MMAP_SIZE 0x7fff0000 /* 2147418112 */
  8848. # else
  8849. # define SQLITE_MAX_MMAP_SIZE 0
  8850. # endif
  8851. # define SQLITE_MAX_MMAP_SIZE_xc 1 /* exclude from ctime.c */
  8852. #endif
  8853. /*
  8854. ** The default MMAP_SIZE is zero on all platforms. Or, even if a larger
  8855. ** default MMAP_SIZE is specified at compile-time, make sure that it does
  8856. ** not exceed the maximum mmap size.
  8857. */
  8858. #ifndef SQLITE_DEFAULT_MMAP_SIZE
  8859. # define SQLITE_DEFAULT_MMAP_SIZE 0
  8860. # define SQLITE_DEFAULT_MMAP_SIZE_xc 1 /* Exclude from ctime.c */
  8861. #endif
  8862. #if SQLITE_DEFAULT_MMAP_SIZE>SQLITE_MAX_MMAP_SIZE
  8863. # undef SQLITE_DEFAULT_MMAP_SIZE
  8864. # define SQLITE_DEFAULT_MMAP_SIZE SQLITE_MAX_MMAP_SIZE
  8865. #endif
  8866. /*
  8867. ** Only one of SQLITE_ENABLE_STAT3 or SQLITE_ENABLE_STAT4 can be defined.
  8868. ** Priority is given to SQLITE_ENABLE_STAT4. If either are defined, also
  8869. ** define SQLITE_ENABLE_STAT3_OR_STAT4
  8870. */
  8871. #ifdef SQLITE_ENABLE_STAT4
  8872. # undef SQLITE_ENABLE_STAT3
  8873. # define SQLITE_ENABLE_STAT3_OR_STAT4 1
  8874. #elif SQLITE_ENABLE_STAT3
  8875. # define SQLITE_ENABLE_STAT3_OR_STAT4 1
  8876. #elif SQLITE_ENABLE_STAT3_OR_STAT4
  8877. # undef SQLITE_ENABLE_STAT3_OR_STAT4
  8878. #endif
  8879. /*
  8880. ** SELECTTRACE_ENABLED will be either 1 or 0 depending on whether or not
  8881. ** the Select query generator tracing logic is turned on.
  8882. */
  8883. #if defined(SQLITE_DEBUG) || defined(SQLITE_ENABLE_SELECTTRACE)
  8884. # define SELECTTRACE_ENABLED 1
  8885. #else
  8886. # define SELECTTRACE_ENABLED 0
  8887. #endif
  8888. /*
  8889. ** An instance of the following structure is used to store the busy-handler
  8890. ** callback for a given sqlite handle.
  8891. **
  8892. ** The sqlite.busyHandler member of the sqlite struct contains the busy
  8893. ** callback for the database handle. Each pager opened via the sqlite
  8894. ** handle is passed a pointer to sqlite.busyHandler. The busy-handler
  8895. ** callback is currently invoked only from within pager.c.
  8896. */
  8897. typedef struct BusyHandler BusyHandler;
  8898. struct BusyHandler {
  8899. int (*xFunc)(void *,int); /* The busy callback */
  8900. void *pArg; /* First arg to busy callback */
  8901. int nBusy; /* Incremented with each busy call */
  8902. };
  8903. /*
  8904. ** Name of the master database table. The master database table
  8905. ** is a special table that holds the names and attributes of all
  8906. ** user tables and indices.
  8907. */
  8908. #define MASTER_NAME "sqlite_master"
  8909. #define TEMP_MASTER_NAME "sqlite_temp_master"
  8910. /*
  8911. ** The root-page of the master database table.
  8912. */
  8913. #define MASTER_ROOT 1
  8914. /*
  8915. ** The name of the schema table.
  8916. */
  8917. #define SCHEMA_TABLE(x) ((!OMIT_TEMPDB)&&(x==1)?TEMP_MASTER_NAME:MASTER_NAME)
  8918. /*
  8919. ** A convenience macro that returns the number of elements in
  8920. ** an array.
  8921. */
  8922. #define ArraySize(X) ((int)(sizeof(X)/sizeof(X[0])))
  8923. /*
  8924. ** Determine if the argument is a power of two
  8925. */
  8926. #define IsPowerOfTwo(X) (((X)&((X)-1))==0)
  8927. /*
  8928. ** The following value as a destructor means to use sqlite3DbFree().
  8929. ** The sqlite3DbFree() routine requires two parameters instead of the
  8930. ** one parameter that destructors normally want. So we have to introduce
  8931. ** this magic value that the code knows to handle differently. Any
  8932. ** pointer will work here as long as it is distinct from SQLITE_STATIC
  8933. ** and SQLITE_TRANSIENT.
  8934. */
  8935. #define SQLITE_DYNAMIC ((sqlite3_destructor_type)sqlite3MallocSize)
  8936. /*
  8937. ** When SQLITE_OMIT_WSD is defined, it means that the target platform does
  8938. ** not support Writable Static Data (WSD) such as global and static variables.
  8939. ** All variables must either be on the stack or dynamically allocated from
  8940. ** the heap. When WSD is unsupported, the variable declarations scattered
  8941. ** throughout the SQLite code must become constants instead. The SQLITE_WSD
  8942. ** macro is used for this purpose. And instead of referencing the variable
  8943. ** directly, we use its constant as a key to lookup the run-time allocated
  8944. ** buffer that holds real variable. The constant is also the initializer
  8945. ** for the run-time allocated buffer.
  8946. **
  8947. ** In the usual case where WSD is supported, the SQLITE_WSD and GLOBAL
  8948. ** macros become no-ops and have zero performance impact.
  8949. */
  8950. #ifdef SQLITE_OMIT_WSD
  8951. #define SQLITE_WSD const
  8952. #define GLOBAL(t,v) (*(t*)sqlite3_wsd_find((void*)&(v), sizeof(v)))
  8953. #define sqlite3GlobalConfig GLOBAL(struct Sqlite3Config, sqlite3Config)
  8954. SQLITE_API int SQLITE_STDCALL sqlite3_wsd_init(int N, int J);
  8955. SQLITE_API void *SQLITE_STDCALL sqlite3_wsd_find(void *K, int L);
  8956. #else
  8957. #define SQLITE_WSD
  8958. #define GLOBAL(t,v) v
  8959. #define sqlite3GlobalConfig sqlite3Config
  8960. #endif
  8961. /*
  8962. ** The following macros are used to suppress compiler warnings and to
  8963. ** make it clear to human readers when a function parameter is deliberately
  8964. ** left unused within the body of a function. This usually happens when
  8965. ** a function is called via a function pointer. For example the
  8966. ** implementation of an SQL aggregate step callback may not use the
  8967. ** parameter indicating the number of arguments passed to the aggregate,
  8968. ** if it knows that this is enforced elsewhere.
  8969. **
  8970. ** When a function parameter is not used at all within the body of a function,
  8971. ** it is generally named "NotUsed" or "NotUsed2" to make things even clearer.
  8972. ** However, these macros may also be used to suppress warnings related to
  8973. ** parameters that may or may not be used depending on compilation options.
  8974. ** For example those parameters only used in assert() statements. In these
  8975. ** cases the parameters are named as per the usual conventions.
  8976. */
  8977. #define UNUSED_PARAMETER(x) (void)(x)
  8978. #define UNUSED_PARAMETER2(x,y) UNUSED_PARAMETER(x),UNUSED_PARAMETER(y)
  8979. /*
  8980. ** Forward references to structures
  8981. */
  8982. typedef struct AggInfo AggInfo;
  8983. typedef struct AuthContext AuthContext;
  8984. typedef struct AutoincInfo AutoincInfo;
  8985. typedef struct Bitvec Bitvec;
  8986. typedef struct CollSeq CollSeq;
  8987. typedef struct Column Column;
  8988. typedef struct Db Db;
  8989. typedef struct Schema Schema;
  8990. typedef struct Expr Expr;
  8991. typedef struct ExprList ExprList;
  8992. typedef struct ExprSpan ExprSpan;
  8993. typedef struct FKey FKey;
  8994. typedef struct FuncDestructor FuncDestructor;
  8995. typedef struct FuncDef FuncDef;
  8996. typedef struct FuncDefHash FuncDefHash;
  8997. typedef struct IdList IdList;
  8998. typedef struct Index Index;
  8999. typedef struct IndexSample IndexSample;
  9000. typedef struct KeyClass KeyClass;
  9001. typedef struct KeyInfo KeyInfo;
  9002. typedef struct Lookaside Lookaside;
  9003. typedef struct LookasideSlot LookasideSlot;
  9004. typedef struct Module Module;
  9005. typedef struct NameContext NameContext;
  9006. typedef struct Parse Parse;
  9007. typedef struct PrintfArguments PrintfArguments;
  9008. typedef struct RowSet RowSet;
  9009. typedef struct Savepoint Savepoint;
  9010. typedef struct Select Select;
  9011. typedef struct SQLiteThread SQLiteThread;
  9012. typedef struct SelectDest SelectDest;
  9013. typedef struct SrcList SrcList;
  9014. typedef struct StrAccum StrAccum;
  9015. typedef struct Table Table;
  9016. typedef struct TableLock TableLock;
  9017. typedef struct Token Token;
  9018. typedef struct TreeView TreeView;
  9019. typedef struct Trigger Trigger;
  9020. typedef struct TriggerPrg TriggerPrg;
  9021. typedef struct TriggerStep TriggerStep;
  9022. typedef struct UnpackedRecord UnpackedRecord;
  9023. typedef struct VTable VTable;
  9024. typedef struct VtabCtx VtabCtx;
  9025. typedef struct Walker Walker;
  9026. typedef struct WhereInfo WhereInfo;
  9027. typedef struct With With;
  9028. /*
  9029. ** Defer sourcing vdbe.h and btree.h until after the "u8" and
  9030. ** "BusyHandler" typedefs. vdbe.h also requires a few of the opaque
  9031. ** pointer types (i.e. FuncDef) defined above.
  9032. */
  9033. /************** Include btree.h in the middle of sqliteInt.h *****************/
  9034. /************** Begin file btree.h *******************************************/
  9035. /*
  9036. ** 2001 September 15
  9037. **
  9038. ** The author disclaims copyright to this source code. In place of
  9039. ** a legal notice, here is a blessing:
  9040. **
  9041. ** May you do good and not evil.
  9042. ** May you find forgiveness for yourself and forgive others.
  9043. ** May you share freely, never taking more than you give.
  9044. **
  9045. *************************************************************************
  9046. ** This header file defines the interface that the sqlite B-Tree file
  9047. ** subsystem. See comments in the source code for a detailed description
  9048. ** of what each interface routine does.
  9049. */
  9050. #ifndef _BTREE_H_
  9051. #define _BTREE_H_
  9052. /* TODO: This definition is just included so other modules compile. It
  9053. ** needs to be revisited.
  9054. */
  9055. #define SQLITE_N_BTREE_META 16
  9056. /*
  9057. ** If defined as non-zero, auto-vacuum is enabled by default. Otherwise
  9058. ** it must be turned on for each database using "PRAGMA auto_vacuum = 1".
  9059. */
  9060. #ifndef SQLITE_DEFAULT_AUTOVACUUM
  9061. #define SQLITE_DEFAULT_AUTOVACUUM 0
  9062. #endif
  9063. #define BTREE_AUTOVACUUM_NONE 0 /* Do not do auto-vacuum */
  9064. #define BTREE_AUTOVACUUM_FULL 1 /* Do full auto-vacuum */
  9065. #define BTREE_AUTOVACUUM_INCR 2 /* Incremental vacuum */
  9066. /*
  9067. ** Forward declarations of structure
  9068. */
  9069. typedef struct Btree Btree;
  9070. typedef struct BtCursor BtCursor;
  9071. typedef struct BtShared BtShared;
  9072. SQLITE_PRIVATE int sqlite3BtreeOpen(
  9073. sqlite3_vfs *pVfs, /* VFS to use with this b-tree */
  9074. const char *zFilename, /* Name of database file to open */
  9075. sqlite3 *db, /* Associated database connection */
  9076. Btree **ppBtree, /* Return open Btree* here */
  9077. int flags, /* Flags */
  9078. int vfsFlags /* Flags passed through to VFS open */
  9079. );
  9080. /* The flags parameter to sqlite3BtreeOpen can be the bitwise or of the
  9081. ** following values.
  9082. **
  9083. ** NOTE: These values must match the corresponding PAGER_ values in
  9084. ** pager.h.
  9085. */
  9086. #define BTREE_OMIT_JOURNAL 1 /* Do not create or use a rollback journal */
  9087. #define BTREE_MEMORY 2 /* This is an in-memory DB */
  9088. #define BTREE_SINGLE 4 /* The file contains at most 1 b-tree */
  9089. #define BTREE_UNORDERED 8 /* Use of a hash implementation is OK */
  9090. SQLITE_PRIVATE int sqlite3BtreeClose(Btree*);
  9091. SQLITE_PRIVATE int sqlite3BtreeSetCacheSize(Btree*,int);
  9092. #if SQLITE_MAX_MMAP_SIZE>0
  9093. SQLITE_PRIVATE int sqlite3BtreeSetMmapLimit(Btree*,sqlite3_int64);
  9094. #endif
  9095. SQLITE_PRIVATE int sqlite3BtreeSetPagerFlags(Btree*,unsigned);
  9096. SQLITE_PRIVATE int sqlite3BtreeSyncDisabled(Btree*);
  9097. SQLITE_PRIVATE int sqlite3BtreeSetPageSize(Btree *p, int nPagesize, int nReserve, int eFix);
  9098. SQLITE_PRIVATE int sqlite3BtreeGetPageSize(Btree*);
  9099. SQLITE_PRIVATE int sqlite3BtreeMaxPageCount(Btree*,int);
  9100. SQLITE_PRIVATE u32 sqlite3BtreeLastPage(Btree*);
  9101. SQLITE_PRIVATE int sqlite3BtreeSecureDelete(Btree*,int);
  9102. SQLITE_PRIVATE int sqlite3BtreeGetOptimalReserve(Btree*);
  9103. SQLITE_PRIVATE int sqlite3BtreeGetReserveNoMutex(Btree *p);
  9104. SQLITE_PRIVATE int sqlite3BtreeSetAutoVacuum(Btree *, int);
  9105. SQLITE_PRIVATE int sqlite3BtreeGetAutoVacuum(Btree *);
  9106. SQLITE_PRIVATE int sqlite3BtreeBeginTrans(Btree*,int);
  9107. SQLITE_PRIVATE int sqlite3BtreeCommitPhaseOne(Btree*, const char *zMaster);
  9108. SQLITE_PRIVATE int sqlite3BtreeCommitPhaseTwo(Btree*, int);
  9109. SQLITE_PRIVATE int sqlite3BtreeCommit(Btree*);
  9110. SQLITE_PRIVATE int sqlite3BtreeRollback(Btree*,int,int);
  9111. SQLITE_PRIVATE int sqlite3BtreeBeginStmt(Btree*,int);
  9112. SQLITE_PRIVATE int sqlite3BtreeCreateTable(Btree*, int*, int flags);
  9113. SQLITE_PRIVATE int sqlite3BtreeIsInTrans(Btree*);
  9114. SQLITE_PRIVATE int sqlite3BtreeIsInReadTrans(Btree*);
  9115. SQLITE_PRIVATE int sqlite3BtreeIsInBackup(Btree*);
  9116. SQLITE_PRIVATE void *sqlite3BtreeSchema(Btree *, int, void(*)(void *));
  9117. SQLITE_PRIVATE int sqlite3BtreeSchemaLocked(Btree *pBtree);
  9118. SQLITE_PRIVATE int sqlite3BtreeLockTable(Btree *pBtree, int iTab, u8 isWriteLock);
  9119. SQLITE_PRIVATE int sqlite3BtreeSavepoint(Btree *, int, int);
  9120. SQLITE_PRIVATE const char *sqlite3BtreeGetFilename(Btree *);
  9121. SQLITE_PRIVATE const char *sqlite3BtreeGetJournalname(Btree *);
  9122. SQLITE_PRIVATE int sqlite3BtreeCopyFile(Btree *, Btree *);
  9123. SQLITE_PRIVATE int sqlite3BtreeIncrVacuum(Btree *);
  9124. /* The flags parameter to sqlite3BtreeCreateTable can be the bitwise OR
  9125. ** of the flags shown below.
  9126. **
  9127. ** Every SQLite table must have either BTREE_INTKEY or BTREE_BLOBKEY set.
  9128. ** With BTREE_INTKEY, the table key is a 64-bit integer and arbitrary data
  9129. ** is stored in the leaves. (BTREE_INTKEY is used for SQL tables.) With
  9130. ** BTREE_BLOBKEY, the key is an arbitrary BLOB and no content is stored
  9131. ** anywhere - the key is the content. (BTREE_BLOBKEY is used for SQL
  9132. ** indices.)
  9133. */
  9134. #define BTREE_INTKEY 1 /* Table has only 64-bit signed integer keys */
  9135. #define BTREE_BLOBKEY 2 /* Table has keys only - no data */
  9136. SQLITE_PRIVATE int sqlite3BtreeDropTable(Btree*, int, int*);
  9137. SQLITE_PRIVATE int sqlite3BtreeClearTable(Btree*, int, int*);
  9138. SQLITE_PRIVATE int sqlite3BtreeClearTableOfCursor(BtCursor*);
  9139. SQLITE_PRIVATE int sqlite3BtreeTripAllCursors(Btree*, int, int);
  9140. SQLITE_PRIVATE void sqlite3BtreeGetMeta(Btree *pBtree, int idx, u32 *pValue);
  9141. SQLITE_PRIVATE int sqlite3BtreeUpdateMeta(Btree*, int idx, u32 value);
  9142. SQLITE_PRIVATE int sqlite3BtreeNewDb(Btree *p);
  9143. /*
  9144. ** The second parameter to sqlite3BtreeGetMeta or sqlite3BtreeUpdateMeta
  9145. ** should be one of the following values. The integer values are assigned
  9146. ** to constants so that the offset of the corresponding field in an
  9147. ** SQLite database header may be found using the following formula:
  9148. **
  9149. ** offset = 36 + (idx * 4)
  9150. **
  9151. ** For example, the free-page-count field is located at byte offset 36 of
  9152. ** the database file header. The incr-vacuum-flag field is located at
  9153. ** byte offset 64 (== 36+4*7).
  9154. **
  9155. ** The BTREE_DATA_VERSION value is not really a value stored in the header.
  9156. ** It is a read-only number computed by the pager. But we merge it with
  9157. ** the header value access routines since its access pattern is the same.
  9158. ** Call it a "virtual meta value".
  9159. */
  9160. #define BTREE_FREE_PAGE_COUNT 0
  9161. #define BTREE_SCHEMA_VERSION 1
  9162. #define BTREE_FILE_FORMAT 2
  9163. #define BTREE_DEFAULT_CACHE_SIZE 3
  9164. #define BTREE_LARGEST_ROOT_PAGE 4
  9165. #define BTREE_TEXT_ENCODING 5
  9166. #define BTREE_USER_VERSION 6
  9167. #define BTREE_INCR_VACUUM 7
  9168. #define BTREE_APPLICATION_ID 8
  9169. #define BTREE_DATA_VERSION 15 /* A virtual meta-value */
  9170. /*
  9171. ** Values that may be OR'd together to form the second argument of an
  9172. ** sqlite3BtreeCursorHints() call.
  9173. **
  9174. ** The BTREE_BULKLOAD flag is set on index cursors when the index is going
  9175. ** to be filled with content that is already in sorted order.
  9176. **
  9177. ** The BTREE_SEEK_EQ flag is set on cursors that will get OP_SeekGE or
  9178. ** OP_SeekLE opcodes for a range search, but where the range of entries
  9179. ** selected will all have the same key. In other words, the cursor will
  9180. ** be used only for equality key searches.
  9181. **
  9182. */
  9183. #define BTREE_BULKLOAD 0x00000001 /* Used to full index in sorted order */
  9184. #define BTREE_SEEK_EQ 0x00000002 /* EQ seeks only - no range seeks */
  9185. SQLITE_PRIVATE int sqlite3BtreeCursor(
  9186. Btree*, /* BTree containing table to open */
  9187. int iTable, /* Index of root page */
  9188. int wrFlag, /* 1 for writing. 0 for read-only */
  9189. struct KeyInfo*, /* First argument to compare function */
  9190. BtCursor *pCursor /* Space to write cursor structure */
  9191. );
  9192. SQLITE_PRIVATE int sqlite3BtreeCursorSize(void);
  9193. SQLITE_PRIVATE void sqlite3BtreeCursorZero(BtCursor*);
  9194. SQLITE_PRIVATE int sqlite3BtreeCloseCursor(BtCursor*);
  9195. SQLITE_PRIVATE int sqlite3BtreeMovetoUnpacked(
  9196. BtCursor*,
  9197. UnpackedRecord *pUnKey,
  9198. i64 intKey,
  9199. int bias,
  9200. int *pRes
  9201. );
  9202. SQLITE_PRIVATE int sqlite3BtreeCursorHasMoved(BtCursor*);
  9203. SQLITE_PRIVATE int sqlite3BtreeCursorRestore(BtCursor*, int*);
  9204. SQLITE_PRIVATE int sqlite3BtreeDelete(BtCursor*);
  9205. SQLITE_PRIVATE int sqlite3BtreeInsert(BtCursor*, const void *pKey, i64 nKey,
  9206. const void *pData, int nData,
  9207. int nZero, int bias, int seekResult);
  9208. SQLITE_PRIVATE int sqlite3BtreeFirst(BtCursor*, int *pRes);
  9209. SQLITE_PRIVATE int sqlite3BtreeLast(BtCursor*, int *pRes);
  9210. SQLITE_PRIVATE int sqlite3BtreeNext(BtCursor*, int *pRes);
  9211. SQLITE_PRIVATE int sqlite3BtreeEof(BtCursor*);
  9212. SQLITE_PRIVATE int sqlite3BtreePrevious(BtCursor*, int *pRes);
  9213. SQLITE_PRIVATE int sqlite3BtreeKeySize(BtCursor*, i64 *pSize);
  9214. SQLITE_PRIVATE int sqlite3BtreeKey(BtCursor*, u32 offset, u32 amt, void*);
  9215. SQLITE_PRIVATE const void *sqlite3BtreeKeyFetch(BtCursor*, u32 *pAmt);
  9216. SQLITE_PRIVATE const void *sqlite3BtreeDataFetch(BtCursor*, u32 *pAmt);
  9217. SQLITE_PRIVATE int sqlite3BtreeDataSize(BtCursor*, u32 *pSize);
  9218. SQLITE_PRIVATE int sqlite3BtreeData(BtCursor*, u32 offset, u32 amt, void*);
  9219. SQLITE_PRIVATE char *sqlite3BtreeIntegrityCheck(Btree*, int *aRoot, int nRoot, int, int*);
  9220. SQLITE_PRIVATE struct Pager *sqlite3BtreePager(Btree*);
  9221. SQLITE_PRIVATE int sqlite3BtreePutData(BtCursor*, u32 offset, u32 amt, void*);
  9222. SQLITE_PRIVATE void sqlite3BtreeIncrblobCursor(BtCursor *);
  9223. SQLITE_PRIVATE void sqlite3BtreeClearCursor(BtCursor *);
  9224. SQLITE_PRIVATE int sqlite3BtreeSetVersion(Btree *pBt, int iVersion);
  9225. SQLITE_PRIVATE void sqlite3BtreeCursorHints(BtCursor *, unsigned int mask);
  9226. #ifdef SQLITE_DEBUG
  9227. SQLITE_PRIVATE int sqlite3BtreeCursorHasHint(BtCursor*, unsigned int mask);
  9228. #endif
  9229. SQLITE_PRIVATE int sqlite3BtreeIsReadonly(Btree *pBt);
  9230. SQLITE_PRIVATE int sqlite3HeaderSizeBtree(void);
  9231. #ifndef NDEBUG
  9232. SQLITE_PRIVATE int sqlite3BtreeCursorIsValid(BtCursor*);
  9233. #endif
  9234. #ifndef SQLITE_OMIT_BTREECOUNT
  9235. SQLITE_PRIVATE int sqlite3BtreeCount(BtCursor *, i64 *);
  9236. #endif
  9237. #ifdef SQLITE_TEST
  9238. SQLITE_PRIVATE int sqlite3BtreeCursorInfo(BtCursor*, int*, int);
  9239. SQLITE_PRIVATE void sqlite3BtreeCursorList(Btree*);
  9240. #endif
  9241. #ifndef SQLITE_OMIT_WAL
  9242. SQLITE_PRIVATE int sqlite3BtreeCheckpoint(Btree*, int, int *, int *);
  9243. #endif
  9244. /*
  9245. ** If we are not using shared cache, then there is no need to
  9246. ** use mutexes to access the BtShared structures. So make the
  9247. ** Enter and Leave procedures no-ops.
  9248. */
  9249. #ifndef SQLITE_OMIT_SHARED_CACHE
  9250. SQLITE_PRIVATE void sqlite3BtreeEnter(Btree*);
  9251. SQLITE_PRIVATE void sqlite3BtreeEnterAll(sqlite3*);
  9252. #else
  9253. # define sqlite3BtreeEnter(X)
  9254. # define sqlite3BtreeEnterAll(X)
  9255. #endif
  9256. #if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE
  9257. SQLITE_PRIVATE int sqlite3BtreeSharable(Btree*);
  9258. SQLITE_PRIVATE void sqlite3BtreeLeave(Btree*);
  9259. SQLITE_PRIVATE void sqlite3BtreeEnterCursor(BtCursor*);
  9260. SQLITE_PRIVATE void sqlite3BtreeLeaveCursor(BtCursor*);
  9261. SQLITE_PRIVATE void sqlite3BtreeLeaveAll(sqlite3*);
  9262. #ifndef NDEBUG
  9263. /* These routines are used inside assert() statements only. */
  9264. SQLITE_PRIVATE int sqlite3BtreeHoldsMutex(Btree*);
  9265. SQLITE_PRIVATE int sqlite3BtreeHoldsAllMutexes(sqlite3*);
  9266. SQLITE_PRIVATE int sqlite3SchemaMutexHeld(sqlite3*,int,Schema*);
  9267. #endif
  9268. #else
  9269. # define sqlite3BtreeSharable(X) 0
  9270. # define sqlite3BtreeLeave(X)
  9271. # define sqlite3BtreeEnterCursor(X)
  9272. # define sqlite3BtreeLeaveCursor(X)
  9273. # define sqlite3BtreeLeaveAll(X)
  9274. # define sqlite3BtreeHoldsMutex(X) 1
  9275. # define sqlite3BtreeHoldsAllMutexes(X) 1
  9276. # define sqlite3SchemaMutexHeld(X,Y,Z) 1
  9277. #endif
  9278. #endif /* _BTREE_H_ */
  9279. /************** End of btree.h ***********************************************/
  9280. /************** Continuing where we left off in sqliteInt.h ******************/
  9281. /************** Include vdbe.h in the middle of sqliteInt.h ******************/
  9282. /************** Begin file vdbe.h ********************************************/
  9283. /*
  9284. ** 2001 September 15
  9285. **
  9286. ** The author disclaims copyright to this source code. In place of
  9287. ** a legal notice, here is a blessing:
  9288. **
  9289. ** May you do good and not evil.
  9290. ** May you find forgiveness for yourself and forgive others.
  9291. ** May you share freely, never taking more than you give.
  9292. **
  9293. *************************************************************************
  9294. ** Header file for the Virtual DataBase Engine (VDBE)
  9295. **
  9296. ** This header defines the interface to the virtual database engine
  9297. ** or VDBE. The VDBE implements an abstract machine that runs a
  9298. ** simple program to access and modify the underlying database.
  9299. */
  9300. #ifndef _SQLITE_VDBE_H_
  9301. #define _SQLITE_VDBE_H_
  9302. /* #include <stdio.h> */
  9303. /*
  9304. ** A single VDBE is an opaque structure named "Vdbe". Only routines
  9305. ** in the source file sqliteVdbe.c are allowed to see the insides
  9306. ** of this structure.
  9307. */
  9308. typedef struct Vdbe Vdbe;
  9309. /*
  9310. ** The names of the following types declared in vdbeInt.h are required
  9311. ** for the VdbeOp definition.
  9312. */
  9313. typedef struct Mem Mem;
  9314. typedef struct SubProgram SubProgram;
  9315. /*
  9316. ** A single instruction of the virtual machine has an opcode
  9317. ** and as many as three operands. The instruction is recorded
  9318. ** as an instance of the following structure:
  9319. */
  9320. struct VdbeOp {
  9321. u8 opcode; /* What operation to perform */
  9322. signed char p4type; /* One of the P4_xxx constants for p4 */
  9323. u8 opflags; /* Mask of the OPFLG_* flags in opcodes.h */
  9324. u8 p5; /* Fifth parameter is an unsigned character */
  9325. int p1; /* First operand */
  9326. int p2; /* Second parameter (often the jump destination) */
  9327. int p3; /* The third parameter */
  9328. union { /* fourth parameter */
  9329. int i; /* Integer value if p4type==P4_INT32 */
  9330. void *p; /* Generic pointer */
  9331. char *z; /* Pointer to data for string (char array) types */
  9332. i64 *pI64; /* Used when p4type is P4_INT64 */
  9333. double *pReal; /* Used when p4type is P4_REAL */
  9334. FuncDef *pFunc; /* Used when p4type is P4_FUNCDEF */
  9335. CollSeq *pColl; /* Used when p4type is P4_COLLSEQ */
  9336. Mem *pMem; /* Used when p4type is P4_MEM */
  9337. VTable *pVtab; /* Used when p4type is P4_VTAB */
  9338. KeyInfo *pKeyInfo; /* Used when p4type is P4_KEYINFO */
  9339. int *ai; /* Used when p4type is P4_INTARRAY */
  9340. SubProgram *pProgram; /* Used when p4type is P4_SUBPROGRAM */
  9341. int (*xAdvance)(BtCursor *, int *);
  9342. } p4;
  9343. #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
  9344. char *zComment; /* Comment to improve readability */
  9345. #endif
  9346. #ifdef VDBE_PROFILE
  9347. u32 cnt; /* Number of times this instruction was executed */
  9348. u64 cycles; /* Total time spent executing this instruction */
  9349. #endif
  9350. #ifdef SQLITE_VDBE_COVERAGE
  9351. int iSrcLine; /* Source-code line that generated this opcode */
  9352. #endif
  9353. };
  9354. typedef struct VdbeOp VdbeOp;
  9355. /*
  9356. ** A sub-routine used to implement a trigger program.
  9357. */
  9358. struct SubProgram {
  9359. VdbeOp *aOp; /* Array of opcodes for sub-program */
  9360. int nOp; /* Elements in aOp[] */
  9361. int nMem; /* Number of memory cells required */
  9362. int nCsr; /* Number of cursors required */
  9363. int nOnce; /* Number of OP_Once instructions */
  9364. void *token; /* id that may be used to recursive triggers */
  9365. SubProgram *pNext; /* Next sub-program already visited */
  9366. };
  9367. /*
  9368. ** A smaller version of VdbeOp used for the VdbeAddOpList() function because
  9369. ** it takes up less space.
  9370. */
  9371. struct VdbeOpList {
  9372. u8 opcode; /* What operation to perform */
  9373. signed char p1; /* First operand */
  9374. signed char p2; /* Second parameter (often the jump destination) */
  9375. signed char p3; /* Third parameter */
  9376. };
  9377. typedef struct VdbeOpList VdbeOpList;
  9378. /*
  9379. ** Allowed values of VdbeOp.p4type
  9380. */
  9381. #define P4_NOTUSED 0 /* The P4 parameter is not used */
  9382. #define P4_DYNAMIC (-1) /* Pointer to a string obtained from sqliteMalloc() */
  9383. #define P4_STATIC (-2) /* Pointer to a static string */
  9384. #define P4_COLLSEQ (-4) /* P4 is a pointer to a CollSeq structure */
  9385. #define P4_FUNCDEF (-5) /* P4 is a pointer to a FuncDef structure */
  9386. #define P4_KEYINFO (-6) /* P4 is a pointer to a KeyInfo structure */
  9387. #define P4_MEM (-8) /* P4 is a pointer to a Mem* structure */
  9388. #define P4_TRANSIENT 0 /* P4 is a pointer to a transient string */
  9389. #define P4_VTAB (-10) /* P4 is a pointer to an sqlite3_vtab structure */
  9390. #define P4_MPRINTF (-11) /* P4 is a string obtained from sqlite3_mprintf() */
  9391. #define P4_REAL (-12) /* P4 is a 64-bit floating point value */
  9392. #define P4_INT64 (-13) /* P4 is a 64-bit signed integer */
  9393. #define P4_INT32 (-14) /* P4 is a 32-bit signed integer */
  9394. #define P4_INTARRAY (-15) /* P4 is a vector of 32-bit integers */
  9395. #define P4_SUBPROGRAM (-18) /* P4 is a pointer to a SubProgram structure */
  9396. #define P4_ADVANCE (-19) /* P4 is a pointer to BtreeNext() or BtreePrev() */
  9397. /* Error message codes for OP_Halt */
  9398. #define P5_ConstraintNotNull 1
  9399. #define P5_ConstraintUnique 2
  9400. #define P5_ConstraintCheck 3
  9401. #define P5_ConstraintFK 4
  9402. /*
  9403. ** The Vdbe.aColName array contains 5n Mem structures, where n is the
  9404. ** number of columns of data returned by the statement.
  9405. */
  9406. #define COLNAME_NAME 0
  9407. #define COLNAME_DECLTYPE 1
  9408. #define COLNAME_DATABASE 2
  9409. #define COLNAME_TABLE 3
  9410. #define COLNAME_COLUMN 4
  9411. #ifdef SQLITE_ENABLE_COLUMN_METADATA
  9412. # define COLNAME_N 5 /* Number of COLNAME_xxx symbols */
  9413. #else
  9414. # ifdef SQLITE_OMIT_DECLTYPE
  9415. # define COLNAME_N 1 /* Store only the name */
  9416. # else
  9417. # define COLNAME_N 2 /* Store the name and decltype */
  9418. # endif
  9419. #endif
  9420. /*
  9421. ** The following macro converts a relative address in the p2 field
  9422. ** of a VdbeOp structure into a negative number so that
  9423. ** sqlite3VdbeAddOpList() knows that the address is relative. Calling
  9424. ** the macro again restores the address.
  9425. */
  9426. #define ADDR(X) (-1-(X))
  9427. /*
  9428. ** The makefile scans the vdbe.c source file and creates the "opcodes.h"
  9429. ** header file that defines a number for each opcode used by the VDBE.
  9430. */
  9431. /************** Include opcodes.h in the middle of vdbe.h ********************/
  9432. /************** Begin file opcodes.h *****************************************/
  9433. /* Automatically generated. Do not edit */
  9434. /* See the mkopcodeh.awk script for details */
  9435. #define OP_Function 1 /* synopsis: r[P3]=func(r[P2@P5]) */
  9436. #define OP_Savepoint 2
  9437. #define OP_AutoCommit 3
  9438. #define OP_Transaction 4
  9439. #define OP_SorterNext 5
  9440. #define OP_PrevIfOpen 6
  9441. #define OP_NextIfOpen 7
  9442. #define OP_Prev 8
  9443. #define OP_Next 9
  9444. #define OP_AggStep 10 /* synopsis: accum=r[P3] step(r[P2@P5]) */
  9445. #define OP_Checkpoint 11
  9446. #define OP_JournalMode 12
  9447. #define OP_Vacuum 13
  9448. #define OP_VFilter 14 /* synopsis: iplan=r[P3] zplan='P4' */
  9449. #define OP_VUpdate 15 /* synopsis: data=r[P3@P2] */
  9450. #define OP_Goto 16
  9451. #define OP_Gosub 17
  9452. #define OP_Return 18
  9453. #define OP_Not 19 /* same as TK_NOT, synopsis: r[P2]= !r[P1] */
  9454. #define OP_InitCoroutine 20
  9455. #define OP_EndCoroutine 21
  9456. #define OP_Yield 22
  9457. #define OP_HaltIfNull 23 /* synopsis: if r[P3]=null halt */
  9458. #define OP_Halt 24
  9459. #define OP_Integer 25 /* synopsis: r[P2]=P1 */
  9460. #define OP_Int64 26 /* synopsis: r[P2]=P4 */
  9461. #define OP_String 27 /* synopsis: r[P2]='P4' (len=P1) */
  9462. #define OP_Null 28 /* synopsis: r[P2..P3]=NULL */
  9463. #define OP_SoftNull 29 /* synopsis: r[P1]=NULL */
  9464. #define OP_Blob 30 /* synopsis: r[P2]=P4 (len=P1) */
  9465. #define OP_Variable 31 /* synopsis: r[P2]=parameter(P1,P4) */
  9466. #define OP_Move 32 /* synopsis: r[P2@P3]=r[P1@P3] */
  9467. #define OP_Copy 33 /* synopsis: r[P2@P3+1]=r[P1@P3+1] */
  9468. #define OP_SCopy 34 /* synopsis: r[P2]=r[P1] */
  9469. #define OP_ResultRow 35 /* synopsis: output=r[P1@P2] */
  9470. #define OP_CollSeq 36
  9471. #define OP_AddImm 37 /* synopsis: r[P1]=r[P1]+P2 */
  9472. #define OP_MustBeInt 38
  9473. #define OP_RealAffinity 39
  9474. #define OP_Cast 40 /* synopsis: affinity(r[P1]) */
  9475. #define OP_Permutation 41
  9476. #define OP_Compare 42 /* synopsis: r[P1@P3] <-> r[P2@P3] */
  9477. #define OP_Jump 43
  9478. #define OP_Once 44
  9479. #define OP_If 45
  9480. #define OP_IfNot 46
  9481. #define OP_Column 47 /* synopsis: r[P3]=PX */
  9482. #define OP_Affinity 48 /* synopsis: affinity(r[P1@P2]) */
  9483. #define OP_MakeRecord 49 /* synopsis: r[P3]=mkrec(r[P1@P2]) */
  9484. #define OP_Count 50 /* synopsis: r[P2]=count() */
  9485. #define OP_ReadCookie 51
  9486. #define OP_SetCookie 52
  9487. #define OP_ReopenIdx 53 /* synopsis: root=P2 iDb=P3 */
  9488. #define OP_OpenRead 54 /* synopsis: root=P2 iDb=P3 */
  9489. #define OP_OpenWrite 55 /* synopsis: root=P2 iDb=P3 */
  9490. #define OP_OpenAutoindex 56 /* synopsis: nColumn=P2 */
  9491. #define OP_OpenEphemeral 57 /* synopsis: nColumn=P2 */
  9492. #define OP_SorterOpen 58
  9493. #define OP_SequenceTest 59 /* synopsis: if( cursor[P1].ctr++ ) pc = P2 */
  9494. #define OP_OpenPseudo 60 /* synopsis: P3 columns in r[P2] */
  9495. #define OP_Close 61
  9496. #define OP_SeekLT 62 /* synopsis: key=r[P3@P4] */
  9497. #define OP_SeekLE 63 /* synopsis: key=r[P3@P4] */
  9498. #define OP_SeekGE 64 /* synopsis: key=r[P3@P4] */
  9499. #define OP_SeekGT 65 /* synopsis: key=r[P3@P4] */
  9500. #define OP_Seek 66 /* synopsis: intkey=r[P2] */
  9501. #define OP_NoConflict 67 /* synopsis: key=r[P3@P4] */
  9502. #define OP_NotFound 68 /* synopsis: key=r[P3@P4] */
  9503. #define OP_Found 69 /* synopsis: key=r[P3@P4] */
  9504. #define OP_NotExists 70 /* synopsis: intkey=r[P3] */
  9505. #define OP_Or 71 /* same as TK_OR, synopsis: r[P3]=(r[P1] || r[P2]) */
  9506. #define OP_And 72 /* same as TK_AND, synopsis: r[P3]=(r[P1] && r[P2]) */
  9507. #define OP_Sequence 73 /* synopsis: r[P2]=cursor[P1].ctr++ */
  9508. #define OP_NewRowid 74 /* synopsis: r[P2]=rowid */
  9509. #define OP_Insert 75 /* synopsis: intkey=r[P3] data=r[P2] */
  9510. #define OP_IsNull 76 /* same as TK_ISNULL, synopsis: if r[P1]==NULL goto P2 */
  9511. #define OP_NotNull 77 /* same as TK_NOTNULL, synopsis: if r[P1]!=NULL goto P2 */
  9512. #define OP_Ne 78 /* same as TK_NE, synopsis: if r[P1]!=r[P3] goto P2 */
  9513. #define OP_Eq 79 /* same as TK_EQ, synopsis: if r[P1]==r[P3] goto P2 */
  9514. #define OP_Gt 80 /* same as TK_GT, synopsis: if r[P1]>r[P3] goto P2 */
  9515. #define OP_Le 81 /* same as TK_LE, synopsis: if r[P1]<=r[P3] goto P2 */
  9516. #define OP_Lt 82 /* same as TK_LT, synopsis: if r[P1]<r[P3] goto P2 */
  9517. #define OP_Ge 83 /* same as TK_GE, synopsis: if r[P1]>=r[P3] goto P2 */
  9518. #define OP_InsertInt 84 /* synopsis: intkey=P3 data=r[P2] */
  9519. #define OP_BitAnd 85 /* same as TK_BITAND, synopsis: r[P3]=r[P1]&r[P2] */
  9520. #define OP_BitOr 86 /* same as TK_BITOR, synopsis: r[P3]=r[P1]|r[P2] */
  9521. #define OP_ShiftLeft 87 /* same as TK_LSHIFT, synopsis: r[P3]=r[P2]<<r[P1] */
  9522. #define OP_ShiftRight 88 /* same as TK_RSHIFT, synopsis: r[P3]=r[P2]>>r[P1] */
  9523. #define OP_Add 89 /* same as TK_PLUS, synopsis: r[P3]=r[P1]+r[P2] */
  9524. #define OP_Subtract 90 /* same as TK_MINUS, synopsis: r[P3]=r[P2]-r[P1] */
  9525. #define OP_Multiply 91 /* same as TK_STAR, synopsis: r[P3]=r[P1]*r[P2] */
  9526. #define OP_Divide 92 /* same as TK_SLASH, synopsis: r[P3]=r[P2]/r[P1] */
  9527. #define OP_Remainder 93 /* same as TK_REM, synopsis: r[P3]=r[P2]%r[P1] */
  9528. #define OP_Concat 94 /* same as TK_CONCAT, synopsis: r[P3]=r[P2]+r[P1] */
  9529. #define OP_Delete 95
  9530. #define OP_BitNot 96 /* same as TK_BITNOT, synopsis: r[P1]= ~r[P1] */
  9531. #define OP_String8 97 /* same as TK_STRING, synopsis: r[P2]='P4' */
  9532. #define OP_ResetCount 98
  9533. #define OP_SorterCompare 99 /* synopsis: if key(P1)!=trim(r[P3],P4) goto P2 */
  9534. #define OP_SorterData 100 /* synopsis: r[P2]=data */
  9535. #define OP_RowKey 101 /* synopsis: r[P2]=key */
  9536. #define OP_RowData 102 /* synopsis: r[P2]=data */
  9537. #define OP_Rowid 103 /* synopsis: r[P2]=rowid */
  9538. #define OP_NullRow 104
  9539. #define OP_Last 105
  9540. #define OP_SorterSort 106
  9541. #define OP_Sort 107
  9542. #define OP_Rewind 108
  9543. #define OP_SorterInsert 109
  9544. #define OP_IdxInsert 110 /* synopsis: key=r[P2] */
  9545. #define OP_IdxDelete 111 /* synopsis: key=r[P2@P3] */
  9546. #define OP_IdxRowid 112 /* synopsis: r[P2]=rowid */
  9547. #define OP_IdxLE 113 /* synopsis: key=r[P3@P4] */
  9548. #define OP_IdxGT 114 /* synopsis: key=r[P3@P4] */
  9549. #define OP_IdxLT 115 /* synopsis: key=r[P3@P4] */
  9550. #define OP_IdxGE 116 /* synopsis: key=r[P3@P4] */
  9551. #define OP_Destroy 117
  9552. #define OP_Clear 118
  9553. #define OP_ResetSorter 119
  9554. #define OP_CreateIndex 120 /* synopsis: r[P2]=root iDb=P1 */
  9555. #define OP_CreateTable 121 /* synopsis: r[P2]=root iDb=P1 */
  9556. #define OP_ParseSchema 122
  9557. #define OP_LoadAnalysis 123
  9558. #define OP_DropTable 124
  9559. #define OP_DropIndex 125
  9560. #define OP_DropTrigger 126
  9561. #define OP_IntegrityCk 127
  9562. #define OP_RowSetAdd 128 /* synopsis: rowset(P1)=r[P2] */
  9563. #define OP_RowSetRead 129 /* synopsis: r[P3]=rowset(P1) */
  9564. #define OP_RowSetTest 130 /* synopsis: if r[P3] in rowset(P1) goto P2 */
  9565. #define OP_Program 131
  9566. #define OP_Param 132
  9567. #define OP_Real 133 /* same as TK_FLOAT, synopsis: r[P2]=P4 */
  9568. #define OP_FkCounter 134 /* synopsis: fkctr[P1]+=P2 */
  9569. #define OP_FkIfZero 135 /* synopsis: if fkctr[P1]==0 goto P2 */
  9570. #define OP_MemMax 136 /* synopsis: r[P1]=max(r[P1],r[P2]) */
  9571. #define OP_IfPos 137 /* synopsis: if r[P1]>0 goto P2 */
  9572. #define OP_IfNeg 138 /* synopsis: r[P1]+=P3, if r[P1]<0 goto P2 */
  9573. #define OP_IfNotZero 139 /* synopsis: if r[P1]!=0 then r[P1]+=P3, goto P2 */
  9574. #define OP_DecrJumpZero 140 /* synopsis: if (--r[P1])==0 goto P2 */
  9575. #define OP_JumpZeroIncr 141 /* synopsis: if (r[P1]++)==0 ) goto P2 */
  9576. #define OP_AggFinal 142 /* synopsis: accum=r[P1] N=P2 */
  9577. #define OP_IncrVacuum 143
  9578. #define OP_Expire 144
  9579. #define OP_TableLock 145 /* synopsis: iDb=P1 root=P2 write=P3 */
  9580. #define OP_VBegin 146
  9581. #define OP_VCreate 147
  9582. #define OP_VDestroy 148
  9583. #define OP_VOpen 149
  9584. #define OP_VColumn 150 /* synopsis: r[P3]=vcolumn(P2) */
  9585. #define OP_VNext 151
  9586. #define OP_VRename 152
  9587. #define OP_Pagecount 153
  9588. #define OP_MaxPgcnt 154
  9589. #define OP_Init 155 /* synopsis: Start at P2 */
  9590. #define OP_Noop 156
  9591. #define OP_Explain 157
  9592. /* Properties such as "out2" or "jump" that are specified in
  9593. ** comments following the "case" for each opcode in the vdbe.c
  9594. ** are encoded into bitvectors as follows:
  9595. */
  9596. #define OPFLG_JUMP 0x0001 /* jump: P2 holds jmp target */
  9597. #define OPFLG_IN1 0x0002 /* in1: P1 is an input */
  9598. #define OPFLG_IN2 0x0004 /* in2: P2 is an input */
  9599. #define OPFLG_IN3 0x0008 /* in3: P3 is an input */
  9600. #define OPFLG_OUT2 0x0010 /* out2: P2 is an output */
  9601. #define OPFLG_OUT3 0x0020 /* out3: P3 is an output */
  9602. #define OPFLG_INITIALIZER {\
  9603. /* 0 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x01, 0x01,\
  9604. /* 8 */ 0x01, 0x01, 0x00, 0x00, 0x10, 0x00, 0x01, 0x00,\
  9605. /* 16 */ 0x01, 0x01, 0x02, 0x12, 0x01, 0x02, 0x03, 0x08,\
  9606. /* 24 */ 0x00, 0x10, 0x10, 0x10, 0x10, 0x00, 0x10, 0x10,\
  9607. /* 32 */ 0x00, 0x00, 0x10, 0x00, 0x00, 0x02, 0x03, 0x02,\
  9608. /* 40 */ 0x02, 0x00, 0x00, 0x01, 0x01, 0x03, 0x03, 0x00,\
  9609. /* 48 */ 0x00, 0x00, 0x10, 0x10, 0x08, 0x00, 0x00, 0x00,\
  9610. /* 56 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x09, 0x09,\
  9611. /* 64 */ 0x09, 0x09, 0x04, 0x09, 0x09, 0x09, 0x09, 0x26,\
  9612. /* 72 */ 0x26, 0x10, 0x10, 0x00, 0x03, 0x03, 0x0b, 0x0b,\
  9613. /* 80 */ 0x0b, 0x0b, 0x0b, 0x0b, 0x00, 0x26, 0x26, 0x26,\
  9614. /* 88 */ 0x26, 0x26, 0x26, 0x26, 0x26, 0x26, 0x26, 0x00,\
  9615. /* 96 */ 0x12, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10,\
  9616. /* 104 */ 0x00, 0x01, 0x01, 0x01, 0x01, 0x04, 0x04, 0x00,\
  9617. /* 112 */ 0x10, 0x01, 0x01, 0x01, 0x01, 0x10, 0x00, 0x00,\
  9618. /* 120 */ 0x10, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\
  9619. /* 128 */ 0x06, 0x23, 0x0b, 0x01, 0x10, 0x10, 0x00, 0x01,\
  9620. /* 136 */ 0x04, 0x03, 0x03, 0x03, 0x03, 0x03, 0x00, 0x01,\
  9621. /* 144 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01,\
  9622. /* 152 */ 0x00, 0x10, 0x10, 0x01, 0x00, 0x00,}
  9623. /************** End of opcodes.h *********************************************/
  9624. /************** Continuing where we left off in vdbe.h ***********************/
  9625. /*
  9626. ** Prototypes for the VDBE interface. See comments on the implementation
  9627. ** for a description of what each of these routines does.
  9628. */
  9629. SQLITE_PRIVATE Vdbe *sqlite3VdbeCreate(Parse*);
  9630. SQLITE_PRIVATE int sqlite3VdbeAddOp0(Vdbe*,int);
  9631. SQLITE_PRIVATE int sqlite3VdbeAddOp1(Vdbe*,int,int);
  9632. SQLITE_PRIVATE int sqlite3VdbeAddOp2(Vdbe*,int,int,int);
  9633. SQLITE_PRIVATE int sqlite3VdbeAddOp3(Vdbe*,int,int,int,int);
  9634. SQLITE_PRIVATE int sqlite3VdbeAddOp4(Vdbe*,int,int,int,int,const char *zP4,int);
  9635. SQLITE_PRIVATE int sqlite3VdbeAddOp4Int(Vdbe*,int,int,int,int,int);
  9636. SQLITE_PRIVATE int sqlite3VdbeAddOpList(Vdbe*, int nOp, VdbeOpList const *aOp, int iLineno);
  9637. SQLITE_PRIVATE void sqlite3VdbeAddParseSchemaOp(Vdbe*,int,char*);
  9638. SQLITE_PRIVATE void sqlite3VdbeChangeP1(Vdbe*, u32 addr, int P1);
  9639. SQLITE_PRIVATE void sqlite3VdbeChangeP2(Vdbe*, u32 addr, int P2);
  9640. SQLITE_PRIVATE void sqlite3VdbeChangeP3(Vdbe*, u32 addr, int P3);
  9641. SQLITE_PRIVATE void sqlite3VdbeChangeP5(Vdbe*, u8 P5);
  9642. SQLITE_PRIVATE void sqlite3VdbeJumpHere(Vdbe*, int addr);
  9643. SQLITE_PRIVATE void sqlite3VdbeChangeToNoop(Vdbe*, int addr);
  9644. SQLITE_PRIVATE int sqlite3VdbeDeletePriorOpcode(Vdbe*, u8 op);
  9645. SQLITE_PRIVATE void sqlite3VdbeChangeP4(Vdbe*, int addr, const char *zP4, int N);
  9646. SQLITE_PRIVATE void sqlite3VdbeSetP4KeyInfo(Parse*, Index*);
  9647. SQLITE_PRIVATE void sqlite3VdbeUsesBtree(Vdbe*, int);
  9648. SQLITE_PRIVATE VdbeOp *sqlite3VdbeGetOp(Vdbe*, int);
  9649. SQLITE_PRIVATE int sqlite3VdbeMakeLabel(Vdbe*);
  9650. SQLITE_PRIVATE void sqlite3VdbeRunOnlyOnce(Vdbe*);
  9651. SQLITE_PRIVATE void sqlite3VdbeDelete(Vdbe*);
  9652. SQLITE_PRIVATE void sqlite3VdbeClearObject(sqlite3*,Vdbe*);
  9653. SQLITE_PRIVATE void sqlite3VdbeMakeReady(Vdbe*,Parse*);
  9654. SQLITE_PRIVATE int sqlite3VdbeFinalize(Vdbe*);
  9655. SQLITE_PRIVATE void sqlite3VdbeResolveLabel(Vdbe*, int);
  9656. SQLITE_PRIVATE int sqlite3VdbeCurrentAddr(Vdbe*);
  9657. #ifdef SQLITE_DEBUG
  9658. SQLITE_PRIVATE int sqlite3VdbeAssertMayAbort(Vdbe *, int);
  9659. #endif
  9660. SQLITE_PRIVATE void sqlite3VdbeResetStepResult(Vdbe*);
  9661. SQLITE_PRIVATE void sqlite3VdbeRewind(Vdbe*);
  9662. SQLITE_PRIVATE int sqlite3VdbeReset(Vdbe*);
  9663. SQLITE_PRIVATE void sqlite3VdbeSetNumCols(Vdbe*,int);
  9664. SQLITE_PRIVATE int sqlite3VdbeSetColName(Vdbe*, int, int, const char *, void(*)(void*));
  9665. SQLITE_PRIVATE void sqlite3VdbeCountChanges(Vdbe*);
  9666. SQLITE_PRIVATE sqlite3 *sqlite3VdbeDb(Vdbe*);
  9667. SQLITE_PRIVATE void sqlite3VdbeSetSql(Vdbe*, const char *z, int n, int);
  9668. SQLITE_PRIVATE void sqlite3VdbeSwap(Vdbe*,Vdbe*);
  9669. SQLITE_PRIVATE VdbeOp *sqlite3VdbeTakeOpArray(Vdbe*, int*, int*);
  9670. SQLITE_PRIVATE sqlite3_value *sqlite3VdbeGetBoundValue(Vdbe*, int, u8);
  9671. SQLITE_PRIVATE void sqlite3VdbeSetVarmask(Vdbe*, int);
  9672. #ifndef SQLITE_OMIT_TRACE
  9673. SQLITE_PRIVATE char *sqlite3VdbeExpandSql(Vdbe*, const char*);
  9674. #endif
  9675. SQLITE_PRIVATE int sqlite3MemCompare(const Mem*, const Mem*, const CollSeq*);
  9676. SQLITE_PRIVATE void sqlite3VdbeRecordUnpack(KeyInfo*,int,const void*,UnpackedRecord*);
  9677. SQLITE_PRIVATE int sqlite3VdbeRecordCompare(int,const void*,UnpackedRecord*);
  9678. SQLITE_PRIVATE int sqlite3VdbeRecordCompareWithSkip(int, const void *, UnpackedRecord *, int);
  9679. SQLITE_PRIVATE UnpackedRecord *sqlite3VdbeAllocUnpackedRecord(KeyInfo *, char *, int, char **);
  9680. typedef int (*RecordCompare)(int,const void*,UnpackedRecord*);
  9681. SQLITE_PRIVATE RecordCompare sqlite3VdbeFindCompare(UnpackedRecord*);
  9682. #ifndef SQLITE_OMIT_TRIGGER
  9683. SQLITE_PRIVATE void sqlite3VdbeLinkSubProgram(Vdbe *, SubProgram *);
  9684. #endif
  9685. /* Use SQLITE_ENABLE_COMMENTS to enable generation of extra comments on
  9686. ** each VDBE opcode.
  9687. **
  9688. ** Use the SQLITE_ENABLE_MODULE_COMMENTS macro to see some extra no-op
  9689. ** comments in VDBE programs that show key decision points in the code
  9690. ** generator.
  9691. */
  9692. #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
  9693. SQLITE_PRIVATE void sqlite3VdbeComment(Vdbe*, const char*, ...);
  9694. # define VdbeComment(X) sqlite3VdbeComment X
  9695. SQLITE_PRIVATE void sqlite3VdbeNoopComment(Vdbe*, const char*, ...);
  9696. # define VdbeNoopComment(X) sqlite3VdbeNoopComment X
  9697. # ifdef SQLITE_ENABLE_MODULE_COMMENTS
  9698. # define VdbeModuleComment(X) sqlite3VdbeNoopComment X
  9699. # else
  9700. # define VdbeModuleComment(X)
  9701. # endif
  9702. #else
  9703. # define VdbeComment(X)
  9704. # define VdbeNoopComment(X)
  9705. # define VdbeModuleComment(X)
  9706. #endif
  9707. /*
  9708. ** The VdbeCoverage macros are used to set a coverage testing point
  9709. ** for VDBE branch instructions. The coverage testing points are line
  9710. ** numbers in the sqlite3.c source file. VDBE branch coverage testing
  9711. ** only works with an amalagmation build. That's ok since a VDBE branch
  9712. ** coverage build designed for testing the test suite only. No application
  9713. ** should ever ship with VDBE branch coverage measuring turned on.
  9714. **
  9715. ** VdbeCoverage(v) // Mark the previously coded instruction
  9716. ** // as a branch
  9717. **
  9718. ** VdbeCoverageIf(v, conditional) // Mark previous if conditional true
  9719. **
  9720. ** VdbeCoverageAlwaysTaken(v) // Previous branch is always taken
  9721. **
  9722. ** VdbeCoverageNeverTaken(v) // Previous branch is never taken
  9723. **
  9724. ** Every VDBE branch operation must be tagged with one of the macros above.
  9725. ** If not, then when "make test" is run with -DSQLITE_VDBE_COVERAGE and
  9726. ** -DSQLITE_DEBUG then an ALWAYS() will fail in the vdbeTakeBranch()
  9727. ** routine in vdbe.c, alerting the developer to the missed tag.
  9728. */
  9729. #ifdef SQLITE_VDBE_COVERAGE
  9730. SQLITE_PRIVATE void sqlite3VdbeSetLineNumber(Vdbe*,int);
  9731. # define VdbeCoverage(v) sqlite3VdbeSetLineNumber(v,__LINE__)
  9732. # define VdbeCoverageIf(v,x) if(x)sqlite3VdbeSetLineNumber(v,__LINE__)
  9733. # define VdbeCoverageAlwaysTaken(v) sqlite3VdbeSetLineNumber(v,2);
  9734. # define VdbeCoverageNeverTaken(v) sqlite3VdbeSetLineNumber(v,1);
  9735. # define VDBE_OFFSET_LINENO(x) (__LINE__+x)
  9736. #else
  9737. # define VdbeCoverage(v)
  9738. # define VdbeCoverageIf(v,x)
  9739. # define VdbeCoverageAlwaysTaken(v)
  9740. # define VdbeCoverageNeverTaken(v)
  9741. # define VDBE_OFFSET_LINENO(x) 0
  9742. #endif
  9743. #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
  9744. SQLITE_PRIVATE void sqlite3VdbeScanStatus(Vdbe*, int, int, int, LogEst, const char*);
  9745. #else
  9746. # define sqlite3VdbeScanStatus(a,b,c,d,e)
  9747. #endif
  9748. #endif
  9749. /************** End of vdbe.h ************************************************/
  9750. /************** Continuing where we left off in sqliteInt.h ******************/
  9751. /************** Include pager.h in the middle of sqliteInt.h *****************/
  9752. /************** Begin file pager.h *******************************************/
  9753. /*
  9754. ** 2001 September 15
  9755. **
  9756. ** The author disclaims copyright to this source code. In place of
  9757. ** a legal notice, here is a blessing:
  9758. **
  9759. ** May you do good and not evil.
  9760. ** May you find forgiveness for yourself and forgive others.
  9761. ** May you share freely, never taking more than you give.
  9762. **
  9763. *************************************************************************
  9764. ** This header file defines the interface that the sqlite page cache
  9765. ** subsystem. The page cache subsystem reads and writes a file a page
  9766. ** at a time and provides a journal for rollback.
  9767. */
  9768. #ifndef _PAGER_H_
  9769. #define _PAGER_H_
  9770. /*
  9771. ** Default maximum size for persistent journal files. A negative
  9772. ** value means no limit. This value may be overridden using the
  9773. ** sqlite3PagerJournalSizeLimit() API. See also "PRAGMA journal_size_limit".
  9774. */
  9775. #ifndef SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT
  9776. #define SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT -1
  9777. #endif
  9778. /*
  9779. ** The type used to represent a page number. The first page in a file
  9780. ** is called page 1. 0 is used to represent "not a page".
  9781. */
  9782. typedef u32 Pgno;
  9783. /*
  9784. ** Each open file is managed by a separate instance of the "Pager" structure.
  9785. */
  9786. typedef struct Pager Pager;
  9787. /*
  9788. ** Handle type for pages.
  9789. */
  9790. typedef struct PgHdr DbPage;
  9791. /*
  9792. ** Page number PAGER_MJ_PGNO is never used in an SQLite database (it is
  9793. ** reserved for working around a windows/posix incompatibility). It is
  9794. ** used in the journal to signify that the remainder of the journal file
  9795. ** is devoted to storing a master journal name - there are no more pages to
  9796. ** roll back. See comments for function writeMasterJournal() in pager.c
  9797. ** for details.
  9798. */
  9799. #define PAGER_MJ_PGNO(x) ((Pgno)((PENDING_BYTE/((x)->pageSize))+1))
  9800. /*
  9801. ** Allowed values for the flags parameter to sqlite3PagerOpen().
  9802. **
  9803. ** NOTE: These values must match the corresponding BTREE_ values in btree.h.
  9804. */
  9805. #define PAGER_OMIT_JOURNAL 0x0001 /* Do not use a rollback journal */
  9806. #define PAGER_MEMORY 0x0002 /* In-memory database */
  9807. /*
  9808. ** Valid values for the second argument to sqlite3PagerLockingMode().
  9809. */
  9810. #define PAGER_LOCKINGMODE_QUERY -1
  9811. #define PAGER_LOCKINGMODE_NORMAL 0
  9812. #define PAGER_LOCKINGMODE_EXCLUSIVE 1
  9813. /*
  9814. ** Numeric constants that encode the journalmode.
  9815. */
  9816. #define PAGER_JOURNALMODE_QUERY (-1) /* Query the value of journalmode */
  9817. #define PAGER_JOURNALMODE_DELETE 0 /* Commit by deleting journal file */
  9818. #define PAGER_JOURNALMODE_PERSIST 1 /* Commit by zeroing journal header */
  9819. #define PAGER_JOURNALMODE_OFF 2 /* Journal omitted. */
  9820. #define PAGER_JOURNALMODE_TRUNCATE 3 /* Commit by truncating journal */
  9821. #define PAGER_JOURNALMODE_MEMORY 4 /* In-memory journal file */
  9822. #define PAGER_JOURNALMODE_WAL 5 /* Use write-ahead logging */
  9823. /*
  9824. ** Flags that make up the mask passed to sqlite3PagerAcquire().
  9825. */
  9826. #define PAGER_GET_NOCONTENT 0x01 /* Do not load data from disk */
  9827. #define PAGER_GET_READONLY 0x02 /* Read-only page is acceptable */
  9828. /*
  9829. ** Flags for sqlite3PagerSetFlags()
  9830. */
  9831. #define PAGER_SYNCHRONOUS_OFF 0x01 /* PRAGMA synchronous=OFF */
  9832. #define PAGER_SYNCHRONOUS_NORMAL 0x02 /* PRAGMA synchronous=NORMAL */
  9833. #define PAGER_SYNCHRONOUS_FULL 0x03 /* PRAGMA synchronous=FULL */
  9834. #define PAGER_SYNCHRONOUS_MASK 0x03 /* Mask for three values above */
  9835. #define PAGER_FULLFSYNC 0x04 /* PRAGMA fullfsync=ON */
  9836. #define PAGER_CKPT_FULLFSYNC 0x08 /* PRAGMA checkpoint_fullfsync=ON */
  9837. #define PAGER_CACHESPILL 0x10 /* PRAGMA cache_spill=ON */
  9838. #define PAGER_FLAGS_MASK 0x1c /* All above except SYNCHRONOUS */
  9839. /*
  9840. ** The remainder of this file contains the declarations of the functions
  9841. ** that make up the Pager sub-system API. See source code comments for
  9842. ** a detailed description of each routine.
  9843. */
  9844. /* Open and close a Pager connection. */
  9845. SQLITE_PRIVATE int sqlite3PagerOpen(
  9846. sqlite3_vfs*,
  9847. Pager **ppPager,
  9848. const char*,
  9849. int,
  9850. int,
  9851. int,
  9852. void(*)(DbPage*)
  9853. );
  9854. SQLITE_PRIVATE int sqlite3PagerClose(Pager *pPager);
  9855. SQLITE_PRIVATE int sqlite3PagerReadFileheader(Pager*, int, unsigned char*);
  9856. /* Functions used to configure a Pager object. */
  9857. SQLITE_PRIVATE void sqlite3PagerSetBusyhandler(Pager*, int(*)(void *), void *);
  9858. SQLITE_PRIVATE int sqlite3PagerSetPagesize(Pager*, u32*, int);
  9859. SQLITE_PRIVATE int sqlite3PagerMaxPageCount(Pager*, int);
  9860. SQLITE_PRIVATE void sqlite3PagerSetCachesize(Pager*, int);
  9861. SQLITE_PRIVATE void sqlite3PagerSetMmapLimit(Pager *, sqlite3_int64);
  9862. SQLITE_PRIVATE void sqlite3PagerShrink(Pager*);
  9863. SQLITE_PRIVATE void sqlite3PagerSetFlags(Pager*,unsigned);
  9864. SQLITE_PRIVATE int sqlite3PagerLockingMode(Pager *, int);
  9865. SQLITE_PRIVATE int sqlite3PagerSetJournalMode(Pager *, int);
  9866. SQLITE_PRIVATE int sqlite3PagerGetJournalMode(Pager*);
  9867. SQLITE_PRIVATE int sqlite3PagerOkToChangeJournalMode(Pager*);
  9868. SQLITE_PRIVATE i64 sqlite3PagerJournalSizeLimit(Pager *, i64);
  9869. SQLITE_PRIVATE sqlite3_backup **sqlite3PagerBackupPtr(Pager*);
  9870. /* Functions used to obtain and release page references. */
  9871. SQLITE_PRIVATE int sqlite3PagerAcquire(Pager *pPager, Pgno pgno, DbPage **ppPage, int clrFlag);
  9872. #define sqlite3PagerGet(A,B,C) sqlite3PagerAcquire(A,B,C,0)
  9873. SQLITE_PRIVATE DbPage *sqlite3PagerLookup(Pager *pPager, Pgno pgno);
  9874. SQLITE_PRIVATE void sqlite3PagerRef(DbPage*);
  9875. SQLITE_PRIVATE void sqlite3PagerUnref(DbPage*);
  9876. SQLITE_PRIVATE void sqlite3PagerUnrefNotNull(DbPage*);
  9877. /* Operations on page references. */
  9878. SQLITE_PRIVATE int sqlite3PagerWrite(DbPage*);
  9879. SQLITE_PRIVATE void sqlite3PagerDontWrite(DbPage*);
  9880. SQLITE_PRIVATE int sqlite3PagerMovepage(Pager*,DbPage*,Pgno,int);
  9881. SQLITE_PRIVATE int sqlite3PagerPageRefcount(DbPage*);
  9882. SQLITE_PRIVATE void *sqlite3PagerGetData(DbPage *);
  9883. SQLITE_PRIVATE void *sqlite3PagerGetExtra(DbPage *);
  9884. /* Functions used to manage pager transactions and savepoints. */
  9885. SQLITE_PRIVATE void sqlite3PagerPagecount(Pager*, int*);
  9886. SQLITE_PRIVATE int sqlite3PagerBegin(Pager*, int exFlag, int);
  9887. SQLITE_PRIVATE int sqlite3PagerCommitPhaseOne(Pager*,const char *zMaster, int);
  9888. SQLITE_PRIVATE int sqlite3PagerExclusiveLock(Pager*);
  9889. SQLITE_PRIVATE int sqlite3PagerSync(Pager *pPager, const char *zMaster);
  9890. SQLITE_PRIVATE int sqlite3PagerCommitPhaseTwo(Pager*);
  9891. SQLITE_PRIVATE int sqlite3PagerRollback(Pager*);
  9892. SQLITE_PRIVATE int sqlite3PagerOpenSavepoint(Pager *pPager, int n);
  9893. SQLITE_PRIVATE int sqlite3PagerSavepoint(Pager *pPager, int op, int iSavepoint);
  9894. SQLITE_PRIVATE int sqlite3PagerSharedLock(Pager *pPager);
  9895. #ifndef SQLITE_OMIT_WAL
  9896. SQLITE_PRIVATE int sqlite3PagerCheckpoint(Pager *pPager, int, int*, int*);
  9897. SQLITE_PRIVATE int sqlite3PagerWalSupported(Pager *pPager);
  9898. SQLITE_PRIVATE int sqlite3PagerWalCallback(Pager *pPager);
  9899. SQLITE_PRIVATE int sqlite3PagerOpenWal(Pager *pPager, int *pisOpen);
  9900. SQLITE_PRIVATE int sqlite3PagerCloseWal(Pager *pPager);
  9901. #endif
  9902. #ifdef SQLITE_ENABLE_ZIPVFS
  9903. SQLITE_PRIVATE int sqlite3PagerWalFramesize(Pager *pPager);
  9904. #endif
  9905. /* Functions used to query pager state and configuration. */
  9906. SQLITE_PRIVATE u8 sqlite3PagerIsreadonly(Pager*);
  9907. SQLITE_PRIVATE u32 sqlite3PagerDataVersion(Pager*);
  9908. SQLITE_PRIVATE int sqlite3PagerRefcount(Pager*);
  9909. SQLITE_PRIVATE int sqlite3PagerMemUsed(Pager*);
  9910. SQLITE_PRIVATE const char *sqlite3PagerFilename(Pager*, int);
  9911. SQLITE_PRIVATE const sqlite3_vfs *sqlite3PagerVfs(Pager*);
  9912. SQLITE_PRIVATE sqlite3_file *sqlite3PagerFile(Pager*);
  9913. SQLITE_PRIVATE const char *sqlite3PagerJournalname(Pager*);
  9914. SQLITE_PRIVATE int sqlite3PagerNosync(Pager*);
  9915. SQLITE_PRIVATE void *sqlite3PagerTempSpace(Pager*);
  9916. SQLITE_PRIVATE int sqlite3PagerIsMemdb(Pager*);
  9917. SQLITE_PRIVATE void sqlite3PagerCacheStat(Pager *, int, int, int *);
  9918. SQLITE_PRIVATE void sqlite3PagerClearCache(Pager *);
  9919. SQLITE_PRIVATE int sqlite3SectorSize(sqlite3_file *);
  9920. /* Functions used to truncate the database file. */
  9921. SQLITE_PRIVATE void sqlite3PagerTruncateImage(Pager*,Pgno);
  9922. SQLITE_PRIVATE void sqlite3PagerRekey(DbPage*, Pgno, u16);
  9923. #if defined(SQLITE_HAS_CODEC) && !defined(SQLITE_OMIT_WAL)
  9924. SQLITE_PRIVATE void *sqlite3PagerCodec(DbPage *);
  9925. #endif
  9926. /* Functions to support testing and debugging. */
  9927. #if !defined(NDEBUG) || defined(SQLITE_TEST)
  9928. SQLITE_PRIVATE Pgno sqlite3PagerPagenumber(DbPage*);
  9929. SQLITE_PRIVATE int sqlite3PagerIswriteable(DbPage*);
  9930. #endif
  9931. #ifdef SQLITE_TEST
  9932. SQLITE_PRIVATE int *sqlite3PagerStats(Pager*);
  9933. SQLITE_PRIVATE void sqlite3PagerRefdump(Pager*);
  9934. void disable_simulated_io_errors(void);
  9935. void enable_simulated_io_errors(void);
  9936. #else
  9937. # define disable_simulated_io_errors()
  9938. # define enable_simulated_io_errors()
  9939. #endif
  9940. #endif /* _PAGER_H_ */
  9941. /************** End of pager.h ***********************************************/
  9942. /************** Continuing where we left off in sqliteInt.h ******************/
  9943. /************** Include pcache.h in the middle of sqliteInt.h ****************/
  9944. /************** Begin file pcache.h ******************************************/
  9945. /*
  9946. ** 2008 August 05
  9947. **
  9948. ** The author disclaims copyright to this source code. In place of
  9949. ** a legal notice, here is a blessing:
  9950. **
  9951. ** May you do good and not evil.
  9952. ** May you find forgiveness for yourself and forgive others.
  9953. ** May you share freely, never taking more than you give.
  9954. **
  9955. *************************************************************************
  9956. ** This header file defines the interface that the sqlite page cache
  9957. ** subsystem.
  9958. */
  9959. #ifndef _PCACHE_H_
  9960. typedef struct PgHdr PgHdr;
  9961. typedef struct PCache PCache;
  9962. /*
  9963. ** Every page in the cache is controlled by an instance of the following
  9964. ** structure.
  9965. */
  9966. struct PgHdr {
  9967. sqlite3_pcache_page *pPage; /* Pcache object page handle */
  9968. void *pData; /* Page data */
  9969. void *pExtra; /* Extra content */
  9970. PgHdr *pDirty; /* Transient list of dirty pages */
  9971. Pager *pPager; /* The pager this page is part of */
  9972. Pgno pgno; /* Page number for this page */
  9973. #ifdef SQLITE_CHECK_PAGES
  9974. u32 pageHash; /* Hash of page content */
  9975. #endif
  9976. u16 flags; /* PGHDR flags defined below */
  9977. /**********************************************************************
  9978. ** Elements above are public. All that follows is private to pcache.c
  9979. ** and should not be accessed by other modules.
  9980. */
  9981. i16 nRef; /* Number of users of this page */
  9982. PCache *pCache; /* Cache that owns this page */
  9983. PgHdr *pDirtyNext; /* Next element in list of dirty pages */
  9984. PgHdr *pDirtyPrev; /* Previous element in list of dirty pages */
  9985. };
  9986. /* Bit values for PgHdr.flags */
  9987. #define PGHDR_DIRTY 0x002 /* Page has changed */
  9988. #define PGHDR_NEED_SYNC 0x004 /* Fsync the rollback journal before
  9989. ** writing this page to the database */
  9990. #define PGHDR_NEED_READ 0x008 /* Content is unread */
  9991. #define PGHDR_REUSE_UNLIKELY 0x010 /* A hint that reuse is unlikely */
  9992. #define PGHDR_DONT_WRITE 0x020 /* Do not write content to disk */
  9993. #define PGHDR_MMAP 0x040 /* This is an mmap page object */
  9994. /* Initialize and shutdown the page cache subsystem */
  9995. SQLITE_PRIVATE int sqlite3PcacheInitialize(void);
  9996. SQLITE_PRIVATE void sqlite3PcacheShutdown(void);
  9997. /* Page cache buffer management:
  9998. ** These routines implement SQLITE_CONFIG_PAGECACHE.
  9999. */
  10000. SQLITE_PRIVATE void sqlite3PCacheBufferSetup(void *, int sz, int n);
  10001. /* Create a new pager cache.
  10002. ** Under memory stress, invoke xStress to try to make pages clean.
  10003. ** Only clean and unpinned pages can be reclaimed.
  10004. */
  10005. SQLITE_PRIVATE int sqlite3PcacheOpen(
  10006. int szPage, /* Size of every page */
  10007. int szExtra, /* Extra space associated with each page */
  10008. int bPurgeable, /* True if pages are on backing store */
  10009. int (*xStress)(void*, PgHdr*), /* Call to try to make pages clean */
  10010. void *pStress, /* Argument to xStress */
  10011. PCache *pToInit /* Preallocated space for the PCache */
  10012. );
  10013. /* Modify the page-size after the cache has been created. */
  10014. SQLITE_PRIVATE int sqlite3PcacheSetPageSize(PCache *, int);
  10015. /* Return the size in bytes of a PCache object. Used to preallocate
  10016. ** storage space.
  10017. */
  10018. SQLITE_PRIVATE int sqlite3PcacheSize(void);
  10019. /* One release per successful fetch. Page is pinned until released.
  10020. ** Reference counted.
  10021. */
  10022. SQLITE_PRIVATE sqlite3_pcache_page *sqlite3PcacheFetch(PCache*, Pgno, int createFlag);
  10023. SQLITE_PRIVATE int sqlite3PcacheFetchStress(PCache*, Pgno, sqlite3_pcache_page**);
  10024. SQLITE_PRIVATE PgHdr *sqlite3PcacheFetchFinish(PCache*, Pgno, sqlite3_pcache_page *pPage);
  10025. SQLITE_PRIVATE void sqlite3PcacheRelease(PgHdr*);
  10026. SQLITE_PRIVATE void sqlite3PcacheDrop(PgHdr*); /* Remove page from cache */
  10027. SQLITE_PRIVATE void sqlite3PcacheMakeDirty(PgHdr*); /* Make sure page is marked dirty */
  10028. SQLITE_PRIVATE void sqlite3PcacheMakeClean(PgHdr*); /* Mark a single page as clean */
  10029. SQLITE_PRIVATE void sqlite3PcacheCleanAll(PCache*); /* Mark all dirty list pages as clean */
  10030. /* Change a page number. Used by incr-vacuum. */
  10031. SQLITE_PRIVATE void sqlite3PcacheMove(PgHdr*, Pgno);
  10032. /* Remove all pages with pgno>x. Reset the cache if x==0 */
  10033. SQLITE_PRIVATE void sqlite3PcacheTruncate(PCache*, Pgno x);
  10034. /* Get a list of all dirty pages in the cache, sorted by page number */
  10035. SQLITE_PRIVATE PgHdr *sqlite3PcacheDirtyList(PCache*);
  10036. /* Reset and close the cache object */
  10037. SQLITE_PRIVATE void sqlite3PcacheClose(PCache*);
  10038. /* Clear flags from pages of the page cache */
  10039. SQLITE_PRIVATE void sqlite3PcacheClearSyncFlags(PCache *);
  10040. /* Discard the contents of the cache */
  10041. SQLITE_PRIVATE void sqlite3PcacheClear(PCache*);
  10042. /* Return the total number of outstanding page references */
  10043. SQLITE_PRIVATE int sqlite3PcacheRefCount(PCache*);
  10044. /* Increment the reference count of an existing page */
  10045. SQLITE_PRIVATE void sqlite3PcacheRef(PgHdr*);
  10046. SQLITE_PRIVATE int sqlite3PcachePageRefcount(PgHdr*);
  10047. /* Return the total number of pages stored in the cache */
  10048. SQLITE_PRIVATE int sqlite3PcachePagecount(PCache*);
  10049. #if defined(SQLITE_CHECK_PAGES) || defined(SQLITE_DEBUG)
  10050. /* Iterate through all dirty pages currently stored in the cache. This
  10051. ** interface is only available if SQLITE_CHECK_PAGES is defined when the
  10052. ** library is built.
  10053. */
  10054. SQLITE_PRIVATE void sqlite3PcacheIterateDirty(PCache *pCache, void (*xIter)(PgHdr *));
  10055. #endif
  10056. /* Set and get the suggested cache-size for the specified pager-cache.
  10057. **
  10058. ** If no global maximum is configured, then the system attempts to limit
  10059. ** the total number of pages cached by purgeable pager-caches to the sum
  10060. ** of the suggested cache-sizes.
  10061. */
  10062. SQLITE_PRIVATE void sqlite3PcacheSetCachesize(PCache *, int);
  10063. #ifdef SQLITE_TEST
  10064. SQLITE_PRIVATE int sqlite3PcacheGetCachesize(PCache *);
  10065. #endif
  10066. /* Free up as much memory as possible from the page cache */
  10067. SQLITE_PRIVATE void sqlite3PcacheShrink(PCache*);
  10068. #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
  10069. /* Try to return memory used by the pcache module to the main memory heap */
  10070. SQLITE_PRIVATE int sqlite3PcacheReleaseMemory(int);
  10071. #endif
  10072. #ifdef SQLITE_TEST
  10073. SQLITE_PRIVATE void sqlite3PcacheStats(int*,int*,int*,int*);
  10074. #endif
  10075. SQLITE_PRIVATE void sqlite3PCacheSetDefault(void);
  10076. /* Return the header size */
  10077. SQLITE_PRIVATE int sqlite3HeaderSizePcache(void);
  10078. SQLITE_PRIVATE int sqlite3HeaderSizePcache1(void);
  10079. #endif /* _PCACHE_H_ */
  10080. /************** End of pcache.h **********************************************/
  10081. /************** Continuing where we left off in sqliteInt.h ******************/
  10082. /************** Include os.h in the middle of sqliteInt.h ********************/
  10083. /************** Begin file os.h **********************************************/
  10084. /*
  10085. ** 2001 September 16
  10086. **
  10087. ** The author disclaims copyright to this source code. In place of
  10088. ** a legal notice, here is a blessing:
  10089. **
  10090. ** May you do good and not evil.
  10091. ** May you find forgiveness for yourself and forgive others.
  10092. ** May you share freely, never taking more than you give.
  10093. **
  10094. ******************************************************************************
  10095. **
  10096. ** This header file (together with is companion C source-code file
  10097. ** "os.c") attempt to abstract the underlying operating system so that
  10098. ** the SQLite library will work on both POSIX and windows systems.
  10099. **
  10100. ** This header file is #include-ed by sqliteInt.h and thus ends up
  10101. ** being included by every source file.
  10102. */
  10103. #ifndef _SQLITE_OS_H_
  10104. #define _SQLITE_OS_H_
  10105. /*
  10106. ** Attempt to automatically detect the operating system and setup the
  10107. ** necessary pre-processor macros for it.
  10108. */
  10109. /************** Include os_setup.h in the middle of os.h *********************/
  10110. /************** Begin file os_setup.h ****************************************/
  10111. /*
  10112. ** 2013 November 25
  10113. **
  10114. ** The author disclaims copyright to this source code. In place of
  10115. ** a legal notice, here is a blessing:
  10116. **
  10117. ** May you do good and not evil.
  10118. ** May you find forgiveness for yourself and forgive others.
  10119. ** May you share freely, never taking more than you give.
  10120. **
  10121. ******************************************************************************
  10122. **
  10123. ** This file contains pre-processor directives related to operating system
  10124. ** detection and/or setup.
  10125. */
  10126. #ifndef _OS_SETUP_H_
  10127. #define _OS_SETUP_H_
  10128. /*
  10129. ** Figure out if we are dealing with Unix, Windows, or some other operating
  10130. ** system.
  10131. **
  10132. ** After the following block of preprocess macros, all of SQLITE_OS_UNIX,
  10133. ** SQLITE_OS_WIN, and SQLITE_OS_OTHER will defined to either 1 or 0. One of
  10134. ** the three will be 1. The other two will be 0.
  10135. */
  10136. #if defined(SQLITE_OS_OTHER)
  10137. # if SQLITE_OS_OTHER==1
  10138. # undef SQLITE_OS_UNIX
  10139. # define SQLITE_OS_UNIX 0
  10140. # undef SQLITE_OS_WIN
  10141. # define SQLITE_OS_WIN 0
  10142. # else
  10143. # undef SQLITE_OS_OTHER
  10144. # endif
  10145. #endif
  10146. #if !defined(SQLITE_OS_UNIX) && !defined(SQLITE_OS_OTHER)
  10147. # define SQLITE_OS_OTHER 0
  10148. # ifndef SQLITE_OS_WIN
  10149. # if defined(_WIN32) || defined(WIN32) || defined(__CYGWIN__) || \
  10150. defined(__MINGW32__) || defined(__BORLANDC__)
  10151. # define SQLITE_OS_WIN 1
  10152. # define SQLITE_OS_UNIX 0
  10153. # else
  10154. # define SQLITE_OS_WIN 0
  10155. # define SQLITE_OS_UNIX 1
  10156. # endif
  10157. # else
  10158. # define SQLITE_OS_UNIX 0
  10159. # endif
  10160. #else
  10161. # ifndef SQLITE_OS_WIN
  10162. # define SQLITE_OS_WIN 0
  10163. # endif
  10164. #endif
  10165. #endif /* _OS_SETUP_H_ */
  10166. /************** End of os_setup.h ********************************************/
  10167. /************** Continuing where we left off in os.h *************************/
  10168. /* If the SET_FULLSYNC macro is not defined above, then make it
  10169. ** a no-op
  10170. */
  10171. #ifndef SET_FULLSYNC
  10172. # define SET_FULLSYNC(x,y)
  10173. #endif
  10174. /*
  10175. ** The default size of a disk sector
  10176. */
  10177. #ifndef SQLITE_DEFAULT_SECTOR_SIZE
  10178. # define SQLITE_DEFAULT_SECTOR_SIZE 4096
  10179. #endif
  10180. /*
  10181. ** Temporary files are named starting with this prefix followed by 16 random
  10182. ** alphanumeric characters, and no file extension. They are stored in the
  10183. ** OS's standard temporary file directory, and are deleted prior to exit.
  10184. ** If sqlite is being embedded in another program, you may wish to change the
  10185. ** prefix to reflect your program's name, so that if your program exits
  10186. ** prematurely, old temporary files can be easily identified. This can be done
  10187. ** using -DSQLITE_TEMP_FILE_PREFIX=myprefix_ on the compiler command line.
  10188. **
  10189. ** 2006-10-31: The default prefix used to be "sqlite_". But then
  10190. ** Mcafee started using SQLite in their anti-virus product and it
  10191. ** started putting files with the "sqlite" name in the c:/temp folder.
  10192. ** This annoyed many windows users. Those users would then do a
  10193. ** Google search for "sqlite", find the telephone numbers of the
  10194. ** developers and call to wake them up at night and complain.
  10195. ** For this reason, the default name prefix is changed to be "sqlite"
  10196. ** spelled backwards. So the temp files are still identified, but
  10197. ** anybody smart enough to figure out the code is also likely smart
  10198. ** enough to know that calling the developer will not help get rid
  10199. ** of the file.
  10200. */
  10201. #ifndef SQLITE_TEMP_FILE_PREFIX
  10202. # define SQLITE_TEMP_FILE_PREFIX "etilqs_"
  10203. #endif
  10204. /*
  10205. ** The following values may be passed as the second argument to
  10206. ** sqlite3OsLock(). The various locks exhibit the following semantics:
  10207. **
  10208. ** SHARED: Any number of processes may hold a SHARED lock simultaneously.
  10209. ** RESERVED: A single process may hold a RESERVED lock on a file at
  10210. ** any time. Other processes may hold and obtain new SHARED locks.
  10211. ** PENDING: A single process may hold a PENDING lock on a file at
  10212. ** any one time. Existing SHARED locks may persist, but no new
  10213. ** SHARED locks may be obtained by other processes.
  10214. ** EXCLUSIVE: An EXCLUSIVE lock precludes all other locks.
  10215. **
  10216. ** PENDING_LOCK may not be passed directly to sqlite3OsLock(). Instead, a
  10217. ** process that requests an EXCLUSIVE lock may actually obtain a PENDING
  10218. ** lock. This can be upgraded to an EXCLUSIVE lock by a subsequent call to
  10219. ** sqlite3OsLock().
  10220. */
  10221. #define NO_LOCK 0
  10222. #define SHARED_LOCK 1
  10223. #define RESERVED_LOCK 2
  10224. #define PENDING_LOCK 3
  10225. #define EXCLUSIVE_LOCK 4
  10226. /*
  10227. ** File Locking Notes: (Mostly about windows but also some info for Unix)
  10228. **
  10229. ** We cannot use LockFileEx() or UnlockFileEx() on Win95/98/ME because
  10230. ** those functions are not available. So we use only LockFile() and
  10231. ** UnlockFile().
  10232. **
  10233. ** LockFile() prevents not just writing but also reading by other processes.
  10234. ** A SHARED_LOCK is obtained by locking a single randomly-chosen
  10235. ** byte out of a specific range of bytes. The lock byte is obtained at
  10236. ** random so two separate readers can probably access the file at the
  10237. ** same time, unless they are unlucky and choose the same lock byte.
  10238. ** An EXCLUSIVE_LOCK is obtained by locking all bytes in the range.
  10239. ** There can only be one writer. A RESERVED_LOCK is obtained by locking
  10240. ** a single byte of the file that is designated as the reserved lock byte.
  10241. ** A PENDING_LOCK is obtained by locking a designated byte different from
  10242. ** the RESERVED_LOCK byte.
  10243. **
  10244. ** On WinNT/2K/XP systems, LockFileEx() and UnlockFileEx() are available,
  10245. ** which means we can use reader/writer locks. When reader/writer locks
  10246. ** are used, the lock is placed on the same range of bytes that is used
  10247. ** for probabilistic locking in Win95/98/ME. Hence, the locking scheme
  10248. ** will support two or more Win95 readers or two or more WinNT readers.
  10249. ** But a single Win95 reader will lock out all WinNT readers and a single
  10250. ** WinNT reader will lock out all other Win95 readers.
  10251. **
  10252. ** The following #defines specify the range of bytes used for locking.
  10253. ** SHARED_SIZE is the number of bytes available in the pool from which
  10254. ** a random byte is selected for a shared lock. The pool of bytes for
  10255. ** shared locks begins at SHARED_FIRST.
  10256. **
  10257. ** The same locking strategy and
  10258. ** byte ranges are used for Unix. This leaves open the possibility of having
  10259. ** clients on win95, winNT, and unix all talking to the same shared file
  10260. ** and all locking correctly. To do so would require that samba (or whatever
  10261. ** tool is being used for file sharing) implements locks correctly between
  10262. ** windows and unix. I'm guessing that isn't likely to happen, but by
  10263. ** using the same locking range we are at least open to the possibility.
  10264. **
  10265. ** Locking in windows is manditory. For this reason, we cannot store
  10266. ** actual data in the bytes used for locking. The pager never allocates
  10267. ** the pages involved in locking therefore. SHARED_SIZE is selected so
  10268. ** that all locks will fit on a single page even at the minimum page size.
  10269. ** PENDING_BYTE defines the beginning of the locks. By default PENDING_BYTE
  10270. ** is set high so that we don't have to allocate an unused page except
  10271. ** for very large databases. But one should test the page skipping logic
  10272. ** by setting PENDING_BYTE low and running the entire regression suite.
  10273. **
  10274. ** Changing the value of PENDING_BYTE results in a subtly incompatible
  10275. ** file format. Depending on how it is changed, you might not notice
  10276. ** the incompatibility right away, even running a full regression test.
  10277. ** The default location of PENDING_BYTE is the first byte past the
  10278. ** 1GB boundary.
  10279. **
  10280. */
  10281. #ifdef SQLITE_OMIT_WSD
  10282. # define PENDING_BYTE (0x40000000)
  10283. #else
  10284. # define PENDING_BYTE sqlite3PendingByte
  10285. #endif
  10286. #define RESERVED_BYTE (PENDING_BYTE+1)
  10287. #define SHARED_FIRST (PENDING_BYTE+2)
  10288. #define SHARED_SIZE 510
  10289. /*
  10290. ** Wrapper around OS specific sqlite3_os_init() function.
  10291. */
  10292. SQLITE_PRIVATE int sqlite3OsInit(void);
  10293. /*
  10294. ** Functions for accessing sqlite3_file methods
  10295. */
  10296. SQLITE_PRIVATE int sqlite3OsClose(sqlite3_file*);
  10297. SQLITE_PRIVATE int sqlite3OsRead(sqlite3_file*, void*, int amt, i64 offset);
  10298. SQLITE_PRIVATE int sqlite3OsWrite(sqlite3_file*, const void*, int amt, i64 offset);
  10299. SQLITE_PRIVATE int sqlite3OsTruncate(sqlite3_file*, i64 size);
  10300. SQLITE_PRIVATE int sqlite3OsSync(sqlite3_file*, int);
  10301. SQLITE_PRIVATE int sqlite3OsFileSize(sqlite3_file*, i64 *pSize);
  10302. SQLITE_PRIVATE int sqlite3OsLock(sqlite3_file*, int);
  10303. SQLITE_PRIVATE int sqlite3OsUnlock(sqlite3_file*, int);
  10304. SQLITE_PRIVATE int sqlite3OsCheckReservedLock(sqlite3_file *id, int *pResOut);
  10305. SQLITE_PRIVATE int sqlite3OsFileControl(sqlite3_file*,int,void*);
  10306. SQLITE_PRIVATE void sqlite3OsFileControlHint(sqlite3_file*,int,void*);
  10307. #define SQLITE_FCNTL_DB_UNCHANGED 0xca093fa0
  10308. SQLITE_PRIVATE int sqlite3OsSectorSize(sqlite3_file *id);
  10309. SQLITE_PRIVATE int sqlite3OsDeviceCharacteristics(sqlite3_file *id);
  10310. SQLITE_PRIVATE int sqlite3OsShmMap(sqlite3_file *,int,int,int,void volatile **);
  10311. SQLITE_PRIVATE int sqlite3OsShmLock(sqlite3_file *id, int, int, int);
  10312. SQLITE_PRIVATE void sqlite3OsShmBarrier(sqlite3_file *id);
  10313. SQLITE_PRIVATE int sqlite3OsShmUnmap(sqlite3_file *id, int);
  10314. SQLITE_PRIVATE int sqlite3OsFetch(sqlite3_file *id, i64, int, void **);
  10315. SQLITE_PRIVATE int sqlite3OsUnfetch(sqlite3_file *, i64, void *);
  10316. /*
  10317. ** Functions for accessing sqlite3_vfs methods
  10318. */
  10319. SQLITE_PRIVATE int sqlite3OsOpen(sqlite3_vfs *, const char *, sqlite3_file*, int, int *);
  10320. SQLITE_PRIVATE int sqlite3OsDelete(sqlite3_vfs *, const char *, int);
  10321. SQLITE_PRIVATE int sqlite3OsAccess(sqlite3_vfs *, const char *, int, int *pResOut);
  10322. SQLITE_PRIVATE int sqlite3OsFullPathname(sqlite3_vfs *, const char *, int, char *);
  10323. #ifndef SQLITE_OMIT_LOAD_EXTENSION
  10324. SQLITE_PRIVATE void *sqlite3OsDlOpen(sqlite3_vfs *, const char *);
  10325. SQLITE_PRIVATE void sqlite3OsDlError(sqlite3_vfs *, int, char *);
  10326. SQLITE_PRIVATE void (*sqlite3OsDlSym(sqlite3_vfs *, void *, const char *))(void);
  10327. SQLITE_PRIVATE void sqlite3OsDlClose(sqlite3_vfs *, void *);
  10328. #endif /* SQLITE_OMIT_LOAD_EXTENSION */
  10329. SQLITE_PRIVATE int sqlite3OsRandomness(sqlite3_vfs *, int, char *);
  10330. SQLITE_PRIVATE int sqlite3OsSleep(sqlite3_vfs *, int);
  10331. SQLITE_PRIVATE int sqlite3OsCurrentTimeInt64(sqlite3_vfs *, sqlite3_int64*);
  10332. /*
  10333. ** Convenience functions for opening and closing files using
  10334. ** sqlite3_malloc() to obtain space for the file-handle structure.
  10335. */
  10336. SQLITE_PRIVATE int sqlite3OsOpenMalloc(sqlite3_vfs *, const char *, sqlite3_file **, int,int*);
  10337. SQLITE_PRIVATE int sqlite3OsCloseFree(sqlite3_file *);
  10338. #endif /* _SQLITE_OS_H_ */
  10339. /************** End of os.h **************************************************/
  10340. /************** Continuing where we left off in sqliteInt.h ******************/
  10341. /************** Include mutex.h in the middle of sqliteInt.h *****************/
  10342. /************** Begin file mutex.h *******************************************/
  10343. /*
  10344. ** 2007 August 28
  10345. **
  10346. ** The author disclaims copyright to this source code. In place of
  10347. ** a legal notice, here is a blessing:
  10348. **
  10349. ** May you do good and not evil.
  10350. ** May you find forgiveness for yourself and forgive others.
  10351. ** May you share freely, never taking more than you give.
  10352. **
  10353. *************************************************************************
  10354. **
  10355. ** This file contains the common header for all mutex implementations.
  10356. ** The sqliteInt.h header #includes this file so that it is available
  10357. ** to all source files. We break it out in an effort to keep the code
  10358. ** better organized.
  10359. **
  10360. ** NOTE: source files should *not* #include this header file directly.
  10361. ** Source files should #include the sqliteInt.h file and let that file
  10362. ** include this one indirectly.
  10363. */
  10364. /*
  10365. ** Figure out what version of the code to use. The choices are
  10366. **
  10367. ** SQLITE_MUTEX_OMIT No mutex logic. Not even stubs. The
  10368. ** mutexes implementation cannot be overridden
  10369. ** at start-time.
  10370. **
  10371. ** SQLITE_MUTEX_NOOP For single-threaded applications. No
  10372. ** mutual exclusion is provided. But this
  10373. ** implementation can be overridden at
  10374. ** start-time.
  10375. **
  10376. ** SQLITE_MUTEX_PTHREADS For multi-threaded applications on Unix.
  10377. **
  10378. ** SQLITE_MUTEX_W32 For multi-threaded applications on Win32.
  10379. */
  10380. #if !SQLITE_THREADSAFE
  10381. # define SQLITE_MUTEX_OMIT
  10382. #endif
  10383. #if SQLITE_THREADSAFE && !defined(SQLITE_MUTEX_NOOP)
  10384. # if SQLITE_OS_UNIX
  10385. # define SQLITE_MUTEX_PTHREADS
  10386. # elif SQLITE_OS_WIN
  10387. # define SQLITE_MUTEX_W32
  10388. # else
  10389. # define SQLITE_MUTEX_NOOP
  10390. # endif
  10391. #endif
  10392. #ifdef SQLITE_MUTEX_OMIT
  10393. /*
  10394. ** If this is a no-op implementation, implement everything as macros.
  10395. */
  10396. #define sqlite3_mutex_alloc(X) ((sqlite3_mutex*)8)
  10397. #define sqlite3_mutex_free(X)
  10398. #define sqlite3_mutex_enter(X)
  10399. #define sqlite3_mutex_try(X) SQLITE_OK
  10400. #define sqlite3_mutex_leave(X)
  10401. #define sqlite3_mutex_held(X) ((void)(X),1)
  10402. #define sqlite3_mutex_notheld(X) ((void)(X),1)
  10403. #define sqlite3MutexAlloc(X) ((sqlite3_mutex*)8)
  10404. #define sqlite3MutexInit() SQLITE_OK
  10405. #define sqlite3MutexEnd()
  10406. #define MUTEX_LOGIC(X)
  10407. #else
  10408. #define MUTEX_LOGIC(X) X
  10409. #endif /* defined(SQLITE_MUTEX_OMIT) */
  10410. /************** End of mutex.h ***********************************************/
  10411. /************** Continuing where we left off in sqliteInt.h ******************/
  10412. /*
  10413. ** Each database file to be accessed by the system is an instance
  10414. ** of the following structure. There are normally two of these structures
  10415. ** in the sqlite.aDb[] array. aDb[0] is the main database file and
  10416. ** aDb[1] is the database file used to hold temporary tables. Additional
  10417. ** databases may be attached.
  10418. */
  10419. struct Db {
  10420. char *zName; /* Name of this database */
  10421. Btree *pBt; /* The B*Tree structure for this database file */
  10422. u8 safety_level; /* How aggressive at syncing data to disk */
  10423. Schema *pSchema; /* Pointer to database schema (possibly shared) */
  10424. };
  10425. /*
  10426. ** An instance of the following structure stores a database schema.
  10427. **
  10428. ** Most Schema objects are associated with a Btree. The exception is
  10429. ** the Schema for the TEMP databaes (sqlite3.aDb[1]) which is free-standing.
  10430. ** In shared cache mode, a single Schema object can be shared by multiple
  10431. ** Btrees that refer to the same underlying BtShared object.
  10432. **
  10433. ** Schema objects are automatically deallocated when the last Btree that
  10434. ** references them is destroyed. The TEMP Schema is manually freed by
  10435. ** sqlite3_close().
  10436. *
  10437. ** A thread must be holding a mutex on the corresponding Btree in order
  10438. ** to access Schema content. This implies that the thread must also be
  10439. ** holding a mutex on the sqlite3 connection pointer that owns the Btree.
  10440. ** For a TEMP Schema, only the connection mutex is required.
  10441. */
  10442. struct Schema {
  10443. int schema_cookie; /* Database schema version number for this file */
  10444. int iGeneration; /* Generation counter. Incremented with each change */
  10445. Hash tblHash; /* All tables indexed by name */
  10446. Hash idxHash; /* All (named) indices indexed by name */
  10447. Hash trigHash; /* All triggers indexed by name */
  10448. Hash fkeyHash; /* All foreign keys by referenced table name */
  10449. Table *pSeqTab; /* The sqlite_sequence table used by AUTOINCREMENT */
  10450. u8 file_format; /* Schema format version for this file */
  10451. u8 enc; /* Text encoding used by this database */
  10452. u16 schemaFlags; /* Flags associated with this schema */
  10453. int cache_size; /* Number of pages to use in the cache */
  10454. };
  10455. /*
  10456. ** These macros can be used to test, set, or clear bits in the
  10457. ** Db.pSchema->flags field.
  10458. */
  10459. #define DbHasProperty(D,I,P) (((D)->aDb[I].pSchema->schemaFlags&(P))==(P))
  10460. #define DbHasAnyProperty(D,I,P) (((D)->aDb[I].pSchema->schemaFlags&(P))!=0)
  10461. #define DbSetProperty(D,I,P) (D)->aDb[I].pSchema->schemaFlags|=(P)
  10462. #define DbClearProperty(D,I,P) (D)->aDb[I].pSchema->schemaFlags&=~(P)
  10463. /*
  10464. ** Allowed values for the DB.pSchema->flags field.
  10465. **
  10466. ** The DB_SchemaLoaded flag is set after the database schema has been
  10467. ** read into internal hash tables.
  10468. **
  10469. ** DB_UnresetViews means that one or more views have column names that
  10470. ** have been filled out. If the schema changes, these column names might
  10471. ** changes and so the view will need to be reset.
  10472. */
  10473. #define DB_SchemaLoaded 0x0001 /* The schema has been loaded */
  10474. #define DB_UnresetViews 0x0002 /* Some views have defined column names */
  10475. #define DB_Empty 0x0004 /* The file is empty (length 0 bytes) */
  10476. /*
  10477. ** The number of different kinds of things that can be limited
  10478. ** using the sqlite3_limit() interface.
  10479. */
  10480. #define SQLITE_N_LIMIT (SQLITE_LIMIT_WORKER_THREADS+1)
  10481. /*
  10482. ** Lookaside malloc is a set of fixed-size buffers that can be used
  10483. ** to satisfy small transient memory allocation requests for objects
  10484. ** associated with a particular database connection. The use of
  10485. ** lookaside malloc provides a significant performance enhancement
  10486. ** (approx 10%) by avoiding numerous malloc/free requests while parsing
  10487. ** SQL statements.
  10488. **
  10489. ** The Lookaside structure holds configuration information about the
  10490. ** lookaside malloc subsystem. Each available memory allocation in
  10491. ** the lookaside subsystem is stored on a linked list of LookasideSlot
  10492. ** objects.
  10493. **
  10494. ** Lookaside allocations are only allowed for objects that are associated
  10495. ** with a particular database connection. Hence, schema information cannot
  10496. ** be stored in lookaside because in shared cache mode the schema information
  10497. ** is shared by multiple database connections. Therefore, while parsing
  10498. ** schema information, the Lookaside.bEnabled flag is cleared so that
  10499. ** lookaside allocations are not used to construct the schema objects.
  10500. */
  10501. struct Lookaside {
  10502. u16 sz; /* Size of each buffer in bytes */
  10503. u8 bEnabled; /* False to disable new lookaside allocations */
  10504. u8 bMalloced; /* True if pStart obtained from sqlite3_malloc() */
  10505. int nOut; /* Number of buffers currently checked out */
  10506. int mxOut; /* Highwater mark for nOut */
  10507. int anStat[3]; /* 0: hits. 1: size misses. 2: full misses */
  10508. LookasideSlot *pFree; /* List of available buffers */
  10509. void *pStart; /* First byte of available memory space */
  10510. void *pEnd; /* First byte past end of available space */
  10511. };
  10512. struct LookasideSlot {
  10513. LookasideSlot *pNext; /* Next buffer in the list of free buffers */
  10514. };
  10515. /*
  10516. ** A hash table for function definitions.
  10517. **
  10518. ** Hash each FuncDef structure into one of the FuncDefHash.a[] slots.
  10519. ** Collisions are on the FuncDef.pHash chain.
  10520. */
  10521. struct FuncDefHash {
  10522. FuncDef *a[23]; /* Hash table for functions */
  10523. };
  10524. #ifdef SQLITE_USER_AUTHENTICATION
  10525. /*
  10526. ** Information held in the "sqlite3" database connection object and used
  10527. ** to manage user authentication.
  10528. */
  10529. typedef struct sqlite3_userauth sqlite3_userauth;
  10530. struct sqlite3_userauth {
  10531. u8 authLevel; /* Current authentication level */
  10532. int nAuthPW; /* Size of the zAuthPW in bytes */
  10533. char *zAuthPW; /* Password used to authenticate */
  10534. char *zAuthUser; /* User name used to authenticate */
  10535. };
  10536. /* Allowed values for sqlite3_userauth.authLevel */
  10537. #define UAUTH_Unknown 0 /* Authentication not yet checked */
  10538. #define UAUTH_Fail 1 /* User authentication failed */
  10539. #define UAUTH_User 2 /* Authenticated as a normal user */
  10540. #define UAUTH_Admin 3 /* Authenticated as an administrator */
  10541. /* Functions used only by user authorization logic */
  10542. SQLITE_PRIVATE int sqlite3UserAuthTable(const char*);
  10543. SQLITE_PRIVATE int sqlite3UserAuthCheckLogin(sqlite3*,const char*,u8*);
  10544. SQLITE_PRIVATE void sqlite3UserAuthInit(sqlite3*);
  10545. SQLITE_PRIVATE void sqlite3CryptFunc(sqlite3_context*,int,sqlite3_value**);
  10546. #endif /* SQLITE_USER_AUTHENTICATION */
  10547. /*
  10548. ** typedef for the authorization callback function.
  10549. */
  10550. #ifdef SQLITE_USER_AUTHENTICATION
  10551. typedef int (*sqlite3_xauth)(void*,int,const char*,const char*,const char*,
  10552. const char*, const char*);
  10553. #else
  10554. typedef int (*sqlite3_xauth)(void*,int,const char*,const char*,const char*,
  10555. const char*);
  10556. #endif
  10557. /*
  10558. ** Each database connection is an instance of the following structure.
  10559. */
  10560. struct sqlite3 {
  10561. sqlite3_vfs *pVfs; /* OS Interface */
  10562. struct Vdbe *pVdbe; /* List of active virtual machines */
  10563. CollSeq *pDfltColl; /* The default collating sequence (BINARY) */
  10564. sqlite3_mutex *mutex; /* Connection mutex */
  10565. Db *aDb; /* All backends */
  10566. int nDb; /* Number of backends currently in use */
  10567. int flags; /* Miscellaneous flags. See below */
  10568. i64 lastRowid; /* ROWID of most recent insert (see above) */
  10569. i64 szMmap; /* Default mmap_size setting */
  10570. unsigned int openFlags; /* Flags passed to sqlite3_vfs.xOpen() */
  10571. int errCode; /* Most recent error code (SQLITE_*) */
  10572. int errMask; /* & result codes with this before returning */
  10573. u16 dbOptFlags; /* Flags to enable/disable optimizations */
  10574. u8 enc; /* Text encoding */
  10575. u8 autoCommit; /* The auto-commit flag. */
  10576. u8 temp_store; /* 1: file 2: memory 0: default */
  10577. u8 mallocFailed; /* True if we have seen a malloc failure */
  10578. u8 dfltLockMode; /* Default locking-mode for attached dbs */
  10579. signed char nextAutovac; /* Autovac setting after VACUUM if >=0 */
  10580. u8 suppressErr; /* Do not issue error messages if true */
  10581. u8 vtabOnConflict; /* Value to return for s3_vtab_on_conflict() */
  10582. u8 isTransactionSavepoint; /* True if the outermost savepoint is a TS */
  10583. int nextPagesize; /* Pagesize after VACUUM if >0 */
  10584. u32 magic; /* Magic number for detect library misuse */
  10585. int nChange; /* Value returned by sqlite3_changes() */
  10586. int nTotalChange; /* Value returned by sqlite3_total_changes() */
  10587. int aLimit[SQLITE_N_LIMIT]; /* Limits */
  10588. int nMaxSorterMmap; /* Maximum size of regions mapped by sorter */
  10589. struct sqlite3InitInfo { /* Information used during initialization */
  10590. int newTnum; /* Rootpage of table being initialized */
  10591. u8 iDb; /* Which db file is being initialized */
  10592. u8 busy; /* TRUE if currently initializing */
  10593. u8 orphanTrigger; /* Last statement is orphaned TEMP trigger */
  10594. u8 imposterTable; /* Building an imposter table */
  10595. } init;
  10596. int nVdbeActive; /* Number of VDBEs currently running */
  10597. int nVdbeRead; /* Number of active VDBEs that read or write */
  10598. int nVdbeWrite; /* Number of active VDBEs that read and write */
  10599. int nVdbeExec; /* Number of nested calls to VdbeExec() */
  10600. int nVDestroy; /* Number of active OP_VDestroy operations */
  10601. int nExtension; /* Number of loaded extensions */
  10602. void **aExtension; /* Array of shared library handles */
  10603. void (*xTrace)(void*,const char*); /* Trace function */
  10604. void *pTraceArg; /* Argument to the trace function */
  10605. void (*xProfile)(void*,const char*,u64); /* Profiling function */
  10606. void *pProfileArg; /* Argument to profile function */
  10607. void *pCommitArg; /* Argument to xCommitCallback() */
  10608. int (*xCommitCallback)(void*); /* Invoked at every commit. */
  10609. void *pRollbackArg; /* Argument to xRollbackCallback() */
  10610. void (*xRollbackCallback)(void*); /* Invoked at every commit. */
  10611. void *pUpdateArg;
  10612. void (*xUpdateCallback)(void*,int, const char*,const char*,sqlite_int64);
  10613. #ifndef SQLITE_OMIT_WAL
  10614. int (*xWalCallback)(void *, sqlite3 *, const char *, int);
  10615. void *pWalArg;
  10616. #endif
  10617. void(*xCollNeeded)(void*,sqlite3*,int eTextRep,const char*);
  10618. void(*xCollNeeded16)(void*,sqlite3*,int eTextRep,const void*);
  10619. void *pCollNeededArg;
  10620. sqlite3_value *pErr; /* Most recent error message */
  10621. union {
  10622. volatile int isInterrupted; /* True if sqlite3_interrupt has been called */
  10623. double notUsed1; /* Spacer */
  10624. } u1;
  10625. Lookaside lookaside; /* Lookaside malloc configuration */
  10626. #ifndef SQLITE_OMIT_AUTHORIZATION
  10627. sqlite3_xauth xAuth; /* Access authorization function */
  10628. void *pAuthArg; /* 1st argument to the access auth function */
  10629. #endif
  10630. #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
  10631. int (*xProgress)(void *); /* The progress callback */
  10632. void *pProgressArg; /* Argument to the progress callback */
  10633. unsigned nProgressOps; /* Number of opcodes for progress callback */
  10634. #endif
  10635. #ifndef SQLITE_OMIT_VIRTUALTABLE
  10636. int nVTrans; /* Allocated size of aVTrans */
  10637. Hash aModule; /* populated by sqlite3_create_module() */
  10638. VtabCtx *pVtabCtx; /* Context for active vtab connect/create */
  10639. VTable **aVTrans; /* Virtual tables with open transactions */
  10640. VTable *pDisconnect; /* Disconnect these in next sqlite3_prepare() */
  10641. #endif
  10642. FuncDefHash aFunc; /* Hash table of connection functions */
  10643. Hash aCollSeq; /* All collating sequences */
  10644. BusyHandler busyHandler; /* Busy callback */
  10645. Db aDbStatic[2]; /* Static space for the 2 default backends */
  10646. Savepoint *pSavepoint; /* List of active savepoints */
  10647. int busyTimeout; /* Busy handler timeout, in msec */
  10648. int nSavepoint; /* Number of non-transaction savepoints */
  10649. int nStatement; /* Number of nested statement-transactions */
  10650. i64 nDeferredCons; /* Net deferred constraints this transaction. */
  10651. i64 nDeferredImmCons; /* Net deferred immediate constraints */
  10652. int *pnBytesFreed; /* If not NULL, increment this in DbFree() */
  10653. #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
  10654. /* The following variables are all protected by the STATIC_MASTER
  10655. ** mutex, not by sqlite3.mutex. They are used by code in notify.c.
  10656. **
  10657. ** When X.pUnlockConnection==Y, that means that X is waiting for Y to
  10658. ** unlock so that it can proceed.
  10659. **
  10660. ** When X.pBlockingConnection==Y, that means that something that X tried
  10661. ** tried to do recently failed with an SQLITE_LOCKED error due to locks
  10662. ** held by Y.
  10663. */
  10664. sqlite3 *pBlockingConnection; /* Connection that caused SQLITE_LOCKED */
  10665. sqlite3 *pUnlockConnection; /* Connection to watch for unlock */
  10666. void *pUnlockArg; /* Argument to xUnlockNotify */
  10667. void (*xUnlockNotify)(void **, int); /* Unlock notify callback */
  10668. sqlite3 *pNextBlocked; /* Next in list of all blocked connections */
  10669. #endif
  10670. #ifdef SQLITE_USER_AUTHENTICATION
  10671. sqlite3_userauth auth; /* User authentication information */
  10672. #endif
  10673. };
  10674. /*
  10675. ** A macro to discover the encoding of a database.
  10676. */
  10677. #define SCHEMA_ENC(db) ((db)->aDb[0].pSchema->enc)
  10678. #define ENC(db) ((db)->enc)
  10679. /*
  10680. ** Possible values for the sqlite3.flags.
  10681. */
  10682. #define SQLITE_VdbeTrace 0x00000001 /* True to trace VDBE execution */
  10683. #define SQLITE_InternChanges 0x00000002 /* Uncommitted Hash table changes */
  10684. #define SQLITE_FullFSync 0x00000004 /* Use full fsync on the backend */
  10685. #define SQLITE_CkptFullFSync 0x00000008 /* Use full fsync for checkpoint */
  10686. #define SQLITE_CacheSpill 0x00000010 /* OK to spill pager cache */
  10687. #define SQLITE_FullColNames 0x00000020 /* Show full column names on SELECT */
  10688. #define SQLITE_ShortColNames 0x00000040 /* Show short columns names */
  10689. #define SQLITE_CountRows 0x00000080 /* Count rows changed by INSERT, */
  10690. /* DELETE, or UPDATE and return */
  10691. /* the count using a callback. */
  10692. #define SQLITE_NullCallback 0x00000100 /* Invoke the callback once if the */
  10693. /* result set is empty */
  10694. #define SQLITE_SqlTrace 0x00000200 /* Debug print SQL as it executes */
  10695. #define SQLITE_VdbeListing 0x00000400 /* Debug listings of VDBE programs */
  10696. #define SQLITE_WriteSchema 0x00000800 /* OK to update SQLITE_MASTER */
  10697. #define SQLITE_VdbeAddopTrace 0x00001000 /* Trace sqlite3VdbeAddOp() calls */
  10698. #define SQLITE_IgnoreChecks 0x00002000 /* Do not enforce check constraints */
  10699. #define SQLITE_ReadUncommitted 0x0004000 /* For shared-cache mode */
  10700. #define SQLITE_LegacyFileFmt 0x00008000 /* Create new databases in format 1 */
  10701. #define SQLITE_RecoveryMode 0x00010000 /* Ignore schema errors */
  10702. #define SQLITE_ReverseOrder 0x00020000 /* Reverse unordered SELECTs */
  10703. #define SQLITE_RecTriggers 0x00040000 /* Enable recursive triggers */
  10704. #define SQLITE_ForeignKeys 0x00080000 /* Enforce foreign key constraints */
  10705. #define SQLITE_AutoIndex 0x00100000 /* Enable automatic indexes */
  10706. #define SQLITE_PreferBuiltin 0x00200000 /* Preference to built-in funcs */
  10707. #define SQLITE_LoadExtension 0x00400000 /* Enable load_extension */
  10708. #define SQLITE_EnableTrigger 0x00800000 /* True to enable triggers */
  10709. #define SQLITE_DeferFKs 0x01000000 /* Defer all FK constraints */
  10710. #define SQLITE_QueryOnly 0x02000000 /* Disable database changes */
  10711. #define SQLITE_VdbeEQP 0x04000000 /* Debug EXPLAIN QUERY PLAN */
  10712. #define SQLITE_Vacuum 0x08000000 /* Currently in a VACUUM */
  10713. /*
  10714. ** Bits of the sqlite3.dbOptFlags field that are used by the
  10715. ** sqlite3_test_control(SQLITE_TESTCTRL_OPTIMIZATIONS,...) interface to
  10716. ** selectively disable various optimizations.
  10717. */
  10718. #define SQLITE_QueryFlattener 0x0001 /* Query flattening */
  10719. #define SQLITE_ColumnCache 0x0002 /* Column cache */
  10720. #define SQLITE_GroupByOrder 0x0004 /* GROUPBY cover of ORDERBY */
  10721. #define SQLITE_FactorOutConst 0x0008 /* Constant factoring */
  10722. /* not used 0x0010 // Was: SQLITE_IdxRealAsInt */
  10723. #define SQLITE_DistinctOpt 0x0020 /* DISTINCT using indexes */
  10724. #define SQLITE_CoverIdxScan 0x0040 /* Covering index scans */
  10725. #define SQLITE_OrderByIdxJoin 0x0080 /* ORDER BY of joins via index */
  10726. #define SQLITE_SubqCoroutine 0x0100 /* Evaluate subqueries as coroutines */
  10727. #define SQLITE_Transitive 0x0200 /* Transitive constraints */
  10728. #define SQLITE_OmitNoopJoin 0x0400 /* Omit unused tables in joins */
  10729. #define SQLITE_Stat34 0x0800 /* Use STAT3 or STAT4 data */
  10730. #define SQLITE_AllOpts 0xffff /* All optimizations */
  10731. /*
  10732. ** Macros for testing whether or not optimizations are enabled or disabled.
  10733. */
  10734. #ifndef SQLITE_OMIT_BUILTIN_TEST
  10735. #define OptimizationDisabled(db, mask) (((db)->dbOptFlags&(mask))!=0)
  10736. #define OptimizationEnabled(db, mask) (((db)->dbOptFlags&(mask))==0)
  10737. #else
  10738. #define OptimizationDisabled(db, mask) 0
  10739. #define OptimizationEnabled(db, mask) 1
  10740. #endif
  10741. /*
  10742. ** Return true if it OK to factor constant expressions into the initialization
  10743. ** code. The argument is a Parse object for the code generator.
  10744. */
  10745. #define ConstFactorOk(P) ((P)->okConstFactor)
  10746. /*
  10747. ** Possible values for the sqlite.magic field.
  10748. ** The numbers are obtained at random and have no special meaning, other
  10749. ** than being distinct from one another.
  10750. */
  10751. #define SQLITE_MAGIC_OPEN 0xa029a697 /* Database is open */
  10752. #define SQLITE_MAGIC_CLOSED 0x9f3c2d33 /* Database is closed */
  10753. #define SQLITE_MAGIC_SICK 0x4b771290 /* Error and awaiting close */
  10754. #define SQLITE_MAGIC_BUSY 0xf03b7906 /* Database currently in use */
  10755. #define SQLITE_MAGIC_ERROR 0xb5357930 /* An SQLITE_MISUSE error occurred */
  10756. #define SQLITE_MAGIC_ZOMBIE 0x64cffc7f /* Close with last statement close */
  10757. /*
  10758. ** Each SQL function is defined by an instance of the following
  10759. ** structure. A pointer to this structure is stored in the sqlite.aFunc
  10760. ** hash table. When multiple functions have the same name, the hash table
  10761. ** points to a linked list of these structures.
  10762. */
  10763. struct FuncDef {
  10764. i16 nArg; /* Number of arguments. -1 means unlimited */
  10765. u16 funcFlags; /* Some combination of SQLITE_FUNC_* */
  10766. void *pUserData; /* User data parameter */
  10767. FuncDef *pNext; /* Next function with same name */
  10768. void (*xFunc)(sqlite3_context*,int,sqlite3_value**); /* Regular function */
  10769. void (*xStep)(sqlite3_context*,int,sqlite3_value**); /* Aggregate step */
  10770. void (*xFinalize)(sqlite3_context*); /* Aggregate finalizer */
  10771. char *zName; /* SQL name of the function. */
  10772. FuncDef *pHash; /* Next with a different name but the same hash */
  10773. FuncDestructor *pDestructor; /* Reference counted destructor function */
  10774. };
  10775. /*
  10776. ** This structure encapsulates a user-function destructor callback (as
  10777. ** configured using create_function_v2()) and a reference counter. When
  10778. ** create_function_v2() is called to create a function with a destructor,
  10779. ** a single object of this type is allocated. FuncDestructor.nRef is set to
  10780. ** the number of FuncDef objects created (either 1 or 3, depending on whether
  10781. ** or not the specified encoding is SQLITE_ANY). The FuncDef.pDestructor
  10782. ** member of each of the new FuncDef objects is set to point to the allocated
  10783. ** FuncDestructor.
  10784. **
  10785. ** Thereafter, when one of the FuncDef objects is deleted, the reference
  10786. ** count on this object is decremented. When it reaches 0, the destructor
  10787. ** is invoked and the FuncDestructor structure freed.
  10788. */
  10789. struct FuncDestructor {
  10790. int nRef;
  10791. void (*xDestroy)(void *);
  10792. void *pUserData;
  10793. };
  10794. /*
  10795. ** Possible values for FuncDef.flags. Note that the _LENGTH and _TYPEOF
  10796. ** values must correspond to OPFLAG_LENGTHARG and OPFLAG_TYPEOFARG. There
  10797. ** are assert() statements in the code to verify this.
  10798. */
  10799. #define SQLITE_FUNC_ENCMASK 0x003 /* SQLITE_UTF8, SQLITE_UTF16BE or UTF16LE */
  10800. #define SQLITE_FUNC_LIKE 0x004 /* Candidate for the LIKE optimization */
  10801. #define SQLITE_FUNC_CASE 0x008 /* Case-sensitive LIKE-type function */
  10802. #define SQLITE_FUNC_EPHEM 0x010 /* Ephemeral. Delete with VDBE */
  10803. #define SQLITE_FUNC_NEEDCOLL 0x020 /* sqlite3GetFuncCollSeq() might be called */
  10804. #define SQLITE_FUNC_LENGTH 0x040 /* Built-in length() function */
  10805. #define SQLITE_FUNC_TYPEOF 0x080 /* Built-in typeof() function */
  10806. #define SQLITE_FUNC_COUNT 0x100 /* Built-in count(*) aggregate */
  10807. #define SQLITE_FUNC_COALESCE 0x200 /* Built-in coalesce() or ifnull() */
  10808. #define SQLITE_FUNC_UNLIKELY 0x400 /* Built-in unlikely() function */
  10809. #define SQLITE_FUNC_CONSTANT 0x800 /* Constant inputs give a constant output */
  10810. #define SQLITE_FUNC_MINMAX 0x1000 /* True for min() and max() aggregates */
  10811. /*
  10812. ** The following three macros, FUNCTION(), LIKEFUNC() and AGGREGATE() are
  10813. ** used to create the initializers for the FuncDef structures.
  10814. **
  10815. ** FUNCTION(zName, nArg, iArg, bNC, xFunc)
  10816. ** Used to create a scalar function definition of a function zName
  10817. ** implemented by C function xFunc that accepts nArg arguments. The
  10818. ** value passed as iArg is cast to a (void*) and made available
  10819. ** as the user-data (sqlite3_user_data()) for the function. If
  10820. ** argument bNC is true, then the SQLITE_FUNC_NEEDCOLL flag is set.
  10821. **
  10822. ** VFUNCTION(zName, nArg, iArg, bNC, xFunc)
  10823. ** Like FUNCTION except it omits the SQLITE_FUNC_CONSTANT flag.
  10824. **
  10825. ** AGGREGATE(zName, nArg, iArg, bNC, xStep, xFinal)
  10826. ** Used to create an aggregate function definition implemented by
  10827. ** the C functions xStep and xFinal. The first four parameters
  10828. ** are interpreted in the same way as the first 4 parameters to
  10829. ** FUNCTION().
  10830. **
  10831. ** LIKEFUNC(zName, nArg, pArg, flags)
  10832. ** Used to create a scalar function definition of a function zName
  10833. ** that accepts nArg arguments and is implemented by a call to C
  10834. ** function likeFunc. Argument pArg is cast to a (void *) and made
  10835. ** available as the function user-data (sqlite3_user_data()). The
  10836. ** FuncDef.flags variable is set to the value passed as the flags
  10837. ** parameter.
  10838. */
  10839. #define FUNCTION(zName, nArg, iArg, bNC, xFunc) \
  10840. {nArg, SQLITE_FUNC_CONSTANT|SQLITE_UTF8|(bNC*SQLITE_FUNC_NEEDCOLL), \
  10841. SQLITE_INT_TO_PTR(iArg), 0, xFunc, 0, 0, #zName, 0, 0}
  10842. #define VFUNCTION(zName, nArg, iArg, bNC, xFunc) \
  10843. {nArg, SQLITE_UTF8|(bNC*SQLITE_FUNC_NEEDCOLL), \
  10844. SQLITE_INT_TO_PTR(iArg), 0, xFunc, 0, 0, #zName, 0, 0}
  10845. #define FUNCTION2(zName, nArg, iArg, bNC, xFunc, extraFlags) \
  10846. {nArg,SQLITE_FUNC_CONSTANT|SQLITE_UTF8|(bNC*SQLITE_FUNC_NEEDCOLL)|extraFlags,\
  10847. SQLITE_INT_TO_PTR(iArg), 0, xFunc, 0, 0, #zName, 0, 0}
  10848. #define STR_FUNCTION(zName, nArg, pArg, bNC, xFunc) \
  10849. {nArg, SQLITE_FUNC_CONSTANT|SQLITE_UTF8|(bNC*SQLITE_FUNC_NEEDCOLL), \
  10850. pArg, 0, xFunc, 0, 0, #zName, 0, 0}
  10851. #define LIKEFUNC(zName, nArg, arg, flags) \
  10852. {nArg, SQLITE_FUNC_CONSTANT|SQLITE_UTF8|flags, \
  10853. (void *)arg, 0, likeFunc, 0, 0, #zName, 0, 0}
  10854. #define AGGREGATE(zName, nArg, arg, nc, xStep, xFinal) \
  10855. {nArg, SQLITE_UTF8|(nc*SQLITE_FUNC_NEEDCOLL), \
  10856. SQLITE_INT_TO_PTR(arg), 0, 0, xStep,xFinal,#zName,0,0}
  10857. #define AGGREGATE2(zName, nArg, arg, nc, xStep, xFinal, extraFlags) \
  10858. {nArg, SQLITE_UTF8|(nc*SQLITE_FUNC_NEEDCOLL)|extraFlags, \
  10859. SQLITE_INT_TO_PTR(arg), 0, 0, xStep,xFinal,#zName,0,0}
  10860. /*
  10861. ** All current savepoints are stored in a linked list starting at
  10862. ** sqlite3.pSavepoint. The first element in the list is the most recently
  10863. ** opened savepoint. Savepoints are added to the list by the vdbe
  10864. ** OP_Savepoint instruction.
  10865. */
  10866. struct Savepoint {
  10867. char *zName; /* Savepoint name (nul-terminated) */
  10868. i64 nDeferredCons; /* Number of deferred fk violations */
  10869. i64 nDeferredImmCons; /* Number of deferred imm fk. */
  10870. Savepoint *pNext; /* Parent savepoint (if any) */
  10871. };
  10872. /*
  10873. ** The following are used as the second parameter to sqlite3Savepoint(),
  10874. ** and as the P1 argument to the OP_Savepoint instruction.
  10875. */
  10876. #define SAVEPOINT_BEGIN 0
  10877. #define SAVEPOINT_RELEASE 1
  10878. #define SAVEPOINT_ROLLBACK 2
  10879. /*
  10880. ** Each SQLite module (virtual table definition) is defined by an
  10881. ** instance of the following structure, stored in the sqlite3.aModule
  10882. ** hash table.
  10883. */
  10884. struct Module {
  10885. const sqlite3_module *pModule; /* Callback pointers */
  10886. const char *zName; /* Name passed to create_module() */
  10887. void *pAux; /* pAux passed to create_module() */
  10888. void (*xDestroy)(void *); /* Module destructor function */
  10889. };
  10890. /*
  10891. ** information about each column of an SQL table is held in an instance
  10892. ** of this structure.
  10893. */
  10894. struct Column {
  10895. char *zName; /* Name of this column */
  10896. Expr *pDflt; /* Default value of this column */
  10897. char *zDflt; /* Original text of the default value */
  10898. char *zType; /* Data type for this column */
  10899. char *zColl; /* Collating sequence. If NULL, use the default */
  10900. u8 notNull; /* An OE_ code for handling a NOT NULL constraint */
  10901. char affinity; /* One of the SQLITE_AFF_... values */
  10902. u8 szEst; /* Estimated size of this column. INT==1 */
  10903. u8 colFlags; /* Boolean properties. See COLFLAG_ defines below */
  10904. };
  10905. /* Allowed values for Column.colFlags:
  10906. */
  10907. #define COLFLAG_PRIMKEY 0x0001 /* Column is part of the primary key */
  10908. #define COLFLAG_HIDDEN 0x0002 /* A hidden column in a virtual table */
  10909. /*
  10910. ** A "Collating Sequence" is defined by an instance of the following
  10911. ** structure. Conceptually, a collating sequence consists of a name and
  10912. ** a comparison routine that defines the order of that sequence.
  10913. **
  10914. ** If CollSeq.xCmp is NULL, it means that the
  10915. ** collating sequence is undefined. Indices built on an undefined
  10916. ** collating sequence may not be read or written.
  10917. */
  10918. struct CollSeq {
  10919. char *zName; /* Name of the collating sequence, UTF-8 encoded */
  10920. u8 enc; /* Text encoding handled by xCmp() */
  10921. void *pUser; /* First argument to xCmp() */
  10922. int (*xCmp)(void*,int, const void*, int, const void*);
  10923. void (*xDel)(void*); /* Destructor for pUser */
  10924. };
  10925. /*
  10926. ** A sort order can be either ASC or DESC.
  10927. */
  10928. #define SQLITE_SO_ASC 0 /* Sort in ascending order */
  10929. #define SQLITE_SO_DESC 1 /* Sort in ascending order */
  10930. /*
  10931. ** Column affinity types.
  10932. **
  10933. ** These used to have mnemonic name like 'i' for SQLITE_AFF_INTEGER and
  10934. ** 't' for SQLITE_AFF_TEXT. But we can save a little space and improve
  10935. ** the speed a little by numbering the values consecutively.
  10936. **
  10937. ** But rather than start with 0 or 1, we begin with 'A'. That way,
  10938. ** when multiple affinity types are concatenated into a string and
  10939. ** used as the P4 operand, they will be more readable.
  10940. **
  10941. ** Note also that the numeric types are grouped together so that testing
  10942. ** for a numeric type is a single comparison. And the NONE type is first.
  10943. */
  10944. #define SQLITE_AFF_NONE 'A'
  10945. #define SQLITE_AFF_TEXT 'B'
  10946. #define SQLITE_AFF_NUMERIC 'C'
  10947. #define SQLITE_AFF_INTEGER 'D'
  10948. #define SQLITE_AFF_REAL 'E'
  10949. #define sqlite3IsNumericAffinity(X) ((X)>=SQLITE_AFF_NUMERIC)
  10950. /*
  10951. ** The SQLITE_AFF_MASK values masks off the significant bits of an
  10952. ** affinity value.
  10953. */
  10954. #define SQLITE_AFF_MASK 0x47
  10955. /*
  10956. ** Additional bit values that can be ORed with an affinity without
  10957. ** changing the affinity.
  10958. **
  10959. ** The SQLITE_NOTNULL flag is a combination of NULLEQ and JUMPIFNULL.
  10960. ** It causes an assert() to fire if either operand to a comparison
  10961. ** operator is NULL. It is added to certain comparison operators to
  10962. ** prove that the operands are always NOT NULL.
  10963. */
  10964. #define SQLITE_JUMPIFNULL 0x10 /* jumps if either operand is NULL */
  10965. #define SQLITE_STOREP2 0x20 /* Store result in reg[P2] rather than jump */
  10966. #define SQLITE_NULLEQ 0x80 /* NULL=NULL */
  10967. #define SQLITE_NOTNULL 0x90 /* Assert that operands are never NULL */
  10968. /*
  10969. ** An object of this type is created for each virtual table present in
  10970. ** the database schema.
  10971. **
  10972. ** If the database schema is shared, then there is one instance of this
  10973. ** structure for each database connection (sqlite3*) that uses the shared
  10974. ** schema. This is because each database connection requires its own unique
  10975. ** instance of the sqlite3_vtab* handle used to access the virtual table
  10976. ** implementation. sqlite3_vtab* handles can not be shared between
  10977. ** database connections, even when the rest of the in-memory database
  10978. ** schema is shared, as the implementation often stores the database
  10979. ** connection handle passed to it via the xConnect() or xCreate() method
  10980. ** during initialization internally. This database connection handle may
  10981. ** then be used by the virtual table implementation to access real tables
  10982. ** within the database. So that they appear as part of the callers
  10983. ** transaction, these accesses need to be made via the same database
  10984. ** connection as that used to execute SQL operations on the virtual table.
  10985. **
  10986. ** All VTable objects that correspond to a single table in a shared
  10987. ** database schema are initially stored in a linked-list pointed to by
  10988. ** the Table.pVTable member variable of the corresponding Table object.
  10989. ** When an sqlite3_prepare() operation is required to access the virtual
  10990. ** table, it searches the list for the VTable that corresponds to the
  10991. ** database connection doing the preparing so as to use the correct
  10992. ** sqlite3_vtab* handle in the compiled query.
  10993. **
  10994. ** When an in-memory Table object is deleted (for example when the
  10995. ** schema is being reloaded for some reason), the VTable objects are not
  10996. ** deleted and the sqlite3_vtab* handles are not xDisconnect()ed
  10997. ** immediately. Instead, they are moved from the Table.pVTable list to
  10998. ** another linked list headed by the sqlite3.pDisconnect member of the
  10999. ** corresponding sqlite3 structure. They are then deleted/xDisconnected
  11000. ** next time a statement is prepared using said sqlite3*. This is done
  11001. ** to avoid deadlock issues involving multiple sqlite3.mutex mutexes.
  11002. ** Refer to comments above function sqlite3VtabUnlockList() for an
  11003. ** explanation as to why it is safe to add an entry to an sqlite3.pDisconnect
  11004. ** list without holding the corresponding sqlite3.mutex mutex.
  11005. **
  11006. ** The memory for objects of this type is always allocated by
  11007. ** sqlite3DbMalloc(), using the connection handle stored in VTable.db as
  11008. ** the first argument.
  11009. */
  11010. struct VTable {
  11011. sqlite3 *db; /* Database connection associated with this table */
  11012. Module *pMod; /* Pointer to module implementation */
  11013. sqlite3_vtab *pVtab; /* Pointer to vtab instance */
  11014. int nRef; /* Number of pointers to this structure */
  11015. u8 bConstraint; /* True if constraints are supported */
  11016. int iSavepoint; /* Depth of the SAVEPOINT stack */
  11017. VTable *pNext; /* Next in linked list (see above) */
  11018. };
  11019. /*
  11020. ** The schema for each SQL table and view is represented in memory
  11021. ** by an instance of the following structure.
  11022. */
  11023. struct Table {
  11024. char *zName; /* Name of the table or view */
  11025. Column *aCol; /* Information about each column */
  11026. Index *pIndex; /* List of SQL indexes on this table. */
  11027. Select *pSelect; /* NULL for tables. Points to definition if a view. */
  11028. FKey *pFKey; /* Linked list of all foreign keys in this table */
  11029. char *zColAff; /* String defining the affinity of each column */
  11030. #ifndef SQLITE_OMIT_CHECK
  11031. ExprList *pCheck; /* All CHECK constraints */
  11032. #endif
  11033. int tnum; /* Root BTree page for this table */
  11034. i16 iPKey; /* If not negative, use aCol[iPKey] as the rowid */
  11035. i16 nCol; /* Number of columns in this table */
  11036. u16 nRef; /* Number of pointers to this Table */
  11037. LogEst nRowLogEst; /* Estimated rows in table - from sqlite_stat1 table */
  11038. LogEst szTabRow; /* Estimated size of each table row in bytes */
  11039. #ifdef SQLITE_ENABLE_COSTMULT
  11040. LogEst costMult; /* Cost multiplier for using this table */
  11041. #endif
  11042. u8 tabFlags; /* Mask of TF_* values */
  11043. u8 keyConf; /* What to do in case of uniqueness conflict on iPKey */
  11044. #ifndef SQLITE_OMIT_ALTERTABLE
  11045. int addColOffset; /* Offset in CREATE TABLE stmt to add a new column */
  11046. #endif
  11047. #ifndef SQLITE_OMIT_VIRTUALTABLE
  11048. int nModuleArg; /* Number of arguments to the module */
  11049. char **azModuleArg; /* Text of all module args. [0] is module name */
  11050. VTable *pVTable; /* List of VTable objects. */
  11051. #endif
  11052. Trigger *pTrigger; /* List of triggers stored in pSchema */
  11053. Schema *pSchema; /* Schema that contains this table */
  11054. Table *pNextZombie; /* Next on the Parse.pZombieTab list */
  11055. };
  11056. /*
  11057. ** Allowed values for Table.tabFlags.
  11058. **
  11059. ** TF_OOOHidden applies to virtual tables that have hidden columns that are
  11060. ** followed by non-hidden columns. Example: "CREATE VIRTUAL TABLE x USING
  11061. ** vtab1(a HIDDEN, b);". Since "b" is a non-hidden column but "a" is hidden,
  11062. ** the TF_OOOHidden attribute would apply in this case. Such tables require
  11063. ** special handling during INSERT processing.
  11064. */
  11065. #define TF_Readonly 0x01 /* Read-only system table */
  11066. #define TF_Ephemeral 0x02 /* An ephemeral table */
  11067. #define TF_HasPrimaryKey 0x04 /* Table has a primary key */
  11068. #define TF_Autoincrement 0x08 /* Integer primary key is autoincrement */
  11069. #define TF_Virtual 0x10 /* Is a virtual table */
  11070. #define TF_WithoutRowid 0x20 /* No rowid used. PRIMARY KEY is the key */
  11071. #define TF_OOOHidden 0x40 /* Out-of-Order hidden columns */
  11072. /*
  11073. ** Test to see whether or not a table is a virtual table. This is
  11074. ** done as a macro so that it will be optimized out when virtual
  11075. ** table support is omitted from the build.
  11076. */
  11077. #ifndef SQLITE_OMIT_VIRTUALTABLE
  11078. # define IsVirtual(X) (((X)->tabFlags & TF_Virtual)!=0)
  11079. # define IsHiddenColumn(X) (((X)->colFlags & COLFLAG_HIDDEN)!=0)
  11080. #else
  11081. # define IsVirtual(X) 0
  11082. # define IsHiddenColumn(X) 0
  11083. #endif
  11084. /* Does the table have a rowid */
  11085. #define HasRowid(X) (((X)->tabFlags & TF_WithoutRowid)==0)
  11086. /*
  11087. ** Each foreign key constraint is an instance of the following structure.
  11088. **
  11089. ** A foreign key is associated with two tables. The "from" table is
  11090. ** the table that contains the REFERENCES clause that creates the foreign
  11091. ** key. The "to" table is the table that is named in the REFERENCES clause.
  11092. ** Consider this example:
  11093. **
  11094. ** CREATE TABLE ex1(
  11095. ** a INTEGER PRIMARY KEY,
  11096. ** b INTEGER CONSTRAINT fk1 REFERENCES ex2(x)
  11097. ** );
  11098. **
  11099. ** For foreign key "fk1", the from-table is "ex1" and the to-table is "ex2".
  11100. ** Equivalent names:
  11101. **
  11102. ** from-table == child-table
  11103. ** to-table == parent-table
  11104. **
  11105. ** Each REFERENCES clause generates an instance of the following structure
  11106. ** which is attached to the from-table. The to-table need not exist when
  11107. ** the from-table is created. The existence of the to-table is not checked.
  11108. **
  11109. ** The list of all parents for child Table X is held at X.pFKey.
  11110. **
  11111. ** A list of all children for a table named Z (which might not even exist)
  11112. ** is held in Schema.fkeyHash with a hash key of Z.
  11113. */
  11114. struct FKey {
  11115. Table *pFrom; /* Table containing the REFERENCES clause (aka: Child) */
  11116. FKey *pNextFrom; /* Next FKey with the same in pFrom. Next parent of pFrom */
  11117. char *zTo; /* Name of table that the key points to (aka: Parent) */
  11118. FKey *pNextTo; /* Next with the same zTo. Next child of zTo. */
  11119. FKey *pPrevTo; /* Previous with the same zTo */
  11120. int nCol; /* Number of columns in this key */
  11121. /* EV: R-30323-21917 */
  11122. u8 isDeferred; /* True if constraint checking is deferred till COMMIT */
  11123. u8 aAction[2]; /* ON DELETE and ON UPDATE actions, respectively */
  11124. Trigger *apTrigger[2];/* Triggers for aAction[] actions */
  11125. struct sColMap { /* Mapping of columns in pFrom to columns in zTo */
  11126. int iFrom; /* Index of column in pFrom */
  11127. char *zCol; /* Name of column in zTo. If NULL use PRIMARY KEY */
  11128. } aCol[1]; /* One entry for each of nCol columns */
  11129. };
  11130. /*
  11131. ** SQLite supports many different ways to resolve a constraint
  11132. ** error. ROLLBACK processing means that a constraint violation
  11133. ** causes the operation in process to fail and for the current transaction
  11134. ** to be rolled back. ABORT processing means the operation in process
  11135. ** fails and any prior changes from that one operation are backed out,
  11136. ** but the transaction is not rolled back. FAIL processing means that
  11137. ** the operation in progress stops and returns an error code. But prior
  11138. ** changes due to the same operation are not backed out and no rollback
  11139. ** occurs. IGNORE means that the particular row that caused the constraint
  11140. ** error is not inserted or updated. Processing continues and no error
  11141. ** is returned. REPLACE means that preexisting database rows that caused
  11142. ** a UNIQUE constraint violation are removed so that the new insert or
  11143. ** update can proceed. Processing continues and no error is reported.
  11144. **
  11145. ** RESTRICT, SETNULL, and CASCADE actions apply only to foreign keys.
  11146. ** RESTRICT is the same as ABORT for IMMEDIATE foreign keys and the
  11147. ** same as ROLLBACK for DEFERRED keys. SETNULL means that the foreign
  11148. ** key is set to NULL. CASCADE means that a DELETE or UPDATE of the
  11149. ** referenced table row is propagated into the row that holds the
  11150. ** foreign key.
  11151. **
  11152. ** The following symbolic values are used to record which type
  11153. ** of action to take.
  11154. */
  11155. #define OE_None 0 /* There is no constraint to check */
  11156. #define OE_Rollback 1 /* Fail the operation and rollback the transaction */
  11157. #define OE_Abort 2 /* Back out changes but do no rollback transaction */
  11158. #define OE_Fail 3 /* Stop the operation but leave all prior changes */
  11159. #define OE_Ignore 4 /* Ignore the error. Do not do the INSERT or UPDATE */
  11160. #define OE_Replace 5 /* Delete existing record, then do INSERT or UPDATE */
  11161. #define OE_Restrict 6 /* OE_Abort for IMMEDIATE, OE_Rollback for DEFERRED */
  11162. #define OE_SetNull 7 /* Set the foreign key value to NULL */
  11163. #define OE_SetDflt 8 /* Set the foreign key value to its default */
  11164. #define OE_Cascade 9 /* Cascade the changes */
  11165. #define OE_Default 10 /* Do whatever the default action is */
  11166. /*
  11167. ** An instance of the following structure is passed as the first
  11168. ** argument to sqlite3VdbeKeyCompare and is used to control the
  11169. ** comparison of the two index keys.
  11170. **
  11171. ** Note that aSortOrder[] and aColl[] have nField+1 slots. There
  11172. ** are nField slots for the columns of an index then one extra slot
  11173. ** for the rowid at the end.
  11174. */
  11175. struct KeyInfo {
  11176. u32 nRef; /* Number of references to this KeyInfo object */
  11177. u8 enc; /* Text encoding - one of the SQLITE_UTF* values */
  11178. u16 nField; /* Number of key columns in the index */
  11179. u16 nXField; /* Number of columns beyond the key columns */
  11180. sqlite3 *db; /* The database connection */
  11181. u8 *aSortOrder; /* Sort order for each column. */
  11182. CollSeq *aColl[1]; /* Collating sequence for each term of the key */
  11183. };
  11184. /*
  11185. ** An instance of the following structure holds information about a
  11186. ** single index record that has already been parsed out into individual
  11187. ** values.
  11188. **
  11189. ** A record is an object that contains one or more fields of data.
  11190. ** Records are used to store the content of a table row and to store
  11191. ** the key of an index. A blob encoding of a record is created by
  11192. ** the OP_MakeRecord opcode of the VDBE and is disassembled by the
  11193. ** OP_Column opcode.
  11194. **
  11195. ** This structure holds a record that has already been disassembled
  11196. ** into its constituent fields.
  11197. **
  11198. ** The r1 and r2 member variables are only used by the optimized comparison
  11199. ** functions vdbeRecordCompareInt() and vdbeRecordCompareString().
  11200. */
  11201. struct UnpackedRecord {
  11202. KeyInfo *pKeyInfo; /* Collation and sort-order information */
  11203. u16 nField; /* Number of entries in apMem[] */
  11204. i8 default_rc; /* Comparison result if keys are equal */
  11205. u8 errCode; /* Error detected by xRecordCompare (CORRUPT or NOMEM) */
  11206. Mem *aMem; /* Values */
  11207. int r1; /* Value to return if (lhs > rhs) */
  11208. int r2; /* Value to return if (rhs < lhs) */
  11209. };
  11210. /*
  11211. ** Each SQL index is represented in memory by an
  11212. ** instance of the following structure.
  11213. **
  11214. ** The columns of the table that are to be indexed are described
  11215. ** by the aiColumn[] field of this structure. For example, suppose
  11216. ** we have the following table and index:
  11217. **
  11218. ** CREATE TABLE Ex1(c1 int, c2 int, c3 text);
  11219. ** CREATE INDEX Ex2 ON Ex1(c3,c1);
  11220. **
  11221. ** In the Table structure describing Ex1, nCol==3 because there are
  11222. ** three columns in the table. In the Index structure describing
  11223. ** Ex2, nColumn==2 since 2 of the 3 columns of Ex1 are indexed.
  11224. ** The value of aiColumn is {2, 0}. aiColumn[0]==2 because the
  11225. ** first column to be indexed (c3) has an index of 2 in Ex1.aCol[].
  11226. ** The second column to be indexed (c1) has an index of 0 in
  11227. ** Ex1.aCol[], hence Ex2.aiColumn[1]==0.
  11228. **
  11229. ** The Index.onError field determines whether or not the indexed columns
  11230. ** must be unique and what to do if they are not. When Index.onError=OE_None,
  11231. ** it means this is not a unique index. Otherwise it is a unique index
  11232. ** and the value of Index.onError indicate the which conflict resolution
  11233. ** algorithm to employ whenever an attempt is made to insert a non-unique
  11234. ** element.
  11235. */
  11236. struct Index {
  11237. char *zName; /* Name of this index */
  11238. i16 *aiColumn; /* Which columns are used by this index. 1st is 0 */
  11239. LogEst *aiRowLogEst; /* From ANALYZE: Est. rows selected by each column */
  11240. Table *pTable; /* The SQL table being indexed */
  11241. char *zColAff; /* String defining the affinity of each column */
  11242. Index *pNext; /* The next index associated with the same table */
  11243. Schema *pSchema; /* Schema containing this index */
  11244. u8 *aSortOrder; /* for each column: True==DESC, False==ASC */
  11245. char **azColl; /* Array of collation sequence names for index */
  11246. Expr *pPartIdxWhere; /* WHERE clause for partial indices */
  11247. int tnum; /* DB Page containing root of this index */
  11248. LogEst szIdxRow; /* Estimated average row size in bytes */
  11249. u16 nKeyCol; /* Number of columns forming the key */
  11250. u16 nColumn; /* Number of columns stored in the index */
  11251. u8 onError; /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */
  11252. unsigned idxType:2; /* 1==UNIQUE, 2==PRIMARY KEY, 0==CREATE INDEX */
  11253. unsigned bUnordered:1; /* Use this index for == or IN queries only */
  11254. unsigned uniqNotNull:1; /* True if UNIQUE and NOT NULL for all columns */
  11255. unsigned isResized:1; /* True if resizeIndexObject() has been called */
  11256. unsigned isCovering:1; /* True if this is a covering index */
  11257. unsigned noSkipScan:1; /* Do not try to use skip-scan if true */
  11258. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  11259. int nSample; /* Number of elements in aSample[] */
  11260. int nSampleCol; /* Size of IndexSample.anEq[] and so on */
  11261. tRowcnt *aAvgEq; /* Average nEq values for keys not in aSample */
  11262. IndexSample *aSample; /* Samples of the left-most key */
  11263. tRowcnt *aiRowEst; /* Non-logarithmic stat1 data for this index */
  11264. tRowcnt nRowEst0; /* Non-logarithmic number of rows in the index */
  11265. #endif
  11266. };
  11267. /*
  11268. ** Allowed values for Index.idxType
  11269. */
  11270. #define SQLITE_IDXTYPE_APPDEF 0 /* Created using CREATE INDEX */
  11271. #define SQLITE_IDXTYPE_UNIQUE 1 /* Implements a UNIQUE constraint */
  11272. #define SQLITE_IDXTYPE_PRIMARYKEY 2 /* Is the PRIMARY KEY for the table */
  11273. /* Return true if index X is a PRIMARY KEY index */
  11274. #define IsPrimaryKeyIndex(X) ((X)->idxType==SQLITE_IDXTYPE_PRIMARYKEY)
  11275. /* Return true if index X is a UNIQUE index */
  11276. #define IsUniqueIndex(X) ((X)->onError!=OE_None)
  11277. /*
  11278. ** Each sample stored in the sqlite_stat3 table is represented in memory
  11279. ** using a structure of this type. See documentation at the top of the
  11280. ** analyze.c source file for additional information.
  11281. */
  11282. struct IndexSample {
  11283. void *p; /* Pointer to sampled record */
  11284. int n; /* Size of record in bytes */
  11285. tRowcnt *anEq; /* Est. number of rows where the key equals this sample */
  11286. tRowcnt *anLt; /* Est. number of rows where key is less than this sample */
  11287. tRowcnt *anDLt; /* Est. number of distinct keys less than this sample */
  11288. };
  11289. /*
  11290. ** Each token coming out of the lexer is an instance of
  11291. ** this structure. Tokens are also used as part of an expression.
  11292. **
  11293. ** Note if Token.z==0 then Token.dyn and Token.n are undefined and
  11294. ** may contain random values. Do not make any assumptions about Token.dyn
  11295. ** and Token.n when Token.z==0.
  11296. */
  11297. struct Token {
  11298. const char *z; /* Text of the token. Not NULL-terminated! */
  11299. unsigned int n; /* Number of characters in this token */
  11300. };
  11301. /*
  11302. ** An instance of this structure contains information needed to generate
  11303. ** code for a SELECT that contains aggregate functions.
  11304. **
  11305. ** If Expr.op==TK_AGG_COLUMN or TK_AGG_FUNCTION then Expr.pAggInfo is a
  11306. ** pointer to this structure. The Expr.iColumn field is the index in
  11307. ** AggInfo.aCol[] or AggInfo.aFunc[] of information needed to generate
  11308. ** code for that node.
  11309. **
  11310. ** AggInfo.pGroupBy and AggInfo.aFunc.pExpr point to fields within the
  11311. ** original Select structure that describes the SELECT statement. These
  11312. ** fields do not need to be freed when deallocating the AggInfo structure.
  11313. */
  11314. struct AggInfo {
  11315. u8 directMode; /* Direct rendering mode means take data directly
  11316. ** from source tables rather than from accumulators */
  11317. u8 useSortingIdx; /* In direct mode, reference the sorting index rather
  11318. ** than the source table */
  11319. int sortingIdx; /* Cursor number of the sorting index */
  11320. int sortingIdxPTab; /* Cursor number of pseudo-table */
  11321. int nSortingColumn; /* Number of columns in the sorting index */
  11322. int mnReg, mxReg; /* Range of registers allocated for aCol and aFunc */
  11323. ExprList *pGroupBy; /* The group by clause */
  11324. struct AggInfo_col { /* For each column used in source tables */
  11325. Table *pTab; /* Source table */
  11326. int iTable; /* Cursor number of the source table */
  11327. int iColumn; /* Column number within the source table */
  11328. int iSorterColumn; /* Column number in the sorting index */
  11329. int iMem; /* Memory location that acts as accumulator */
  11330. Expr *pExpr; /* The original expression */
  11331. } *aCol;
  11332. int nColumn; /* Number of used entries in aCol[] */
  11333. int nAccumulator; /* Number of columns that show through to the output.
  11334. ** Additional columns are used only as parameters to
  11335. ** aggregate functions */
  11336. struct AggInfo_func { /* For each aggregate function */
  11337. Expr *pExpr; /* Expression encoding the function */
  11338. FuncDef *pFunc; /* The aggregate function implementation */
  11339. int iMem; /* Memory location that acts as accumulator */
  11340. int iDistinct; /* Ephemeral table used to enforce DISTINCT */
  11341. } *aFunc;
  11342. int nFunc; /* Number of entries in aFunc[] */
  11343. };
  11344. /*
  11345. ** The datatype ynVar is a signed integer, either 16-bit or 32-bit.
  11346. ** Usually it is 16-bits. But if SQLITE_MAX_VARIABLE_NUMBER is greater
  11347. ** than 32767 we have to make it 32-bit. 16-bit is preferred because
  11348. ** it uses less memory in the Expr object, which is a big memory user
  11349. ** in systems with lots of prepared statements. And few applications
  11350. ** need more than about 10 or 20 variables. But some extreme users want
  11351. ** to have prepared statements with over 32767 variables, and for them
  11352. ** the option is available (at compile-time).
  11353. */
  11354. #if SQLITE_MAX_VARIABLE_NUMBER<=32767
  11355. typedef i16 ynVar;
  11356. #else
  11357. typedef int ynVar;
  11358. #endif
  11359. /*
  11360. ** Each node of an expression in the parse tree is an instance
  11361. ** of this structure.
  11362. **
  11363. ** Expr.op is the opcode. The integer parser token codes are reused
  11364. ** as opcodes here. For example, the parser defines TK_GE to be an integer
  11365. ** code representing the ">=" operator. This same integer code is reused
  11366. ** to represent the greater-than-or-equal-to operator in the expression
  11367. ** tree.
  11368. **
  11369. ** If the expression is an SQL literal (TK_INTEGER, TK_FLOAT, TK_BLOB,
  11370. ** or TK_STRING), then Expr.token contains the text of the SQL literal. If
  11371. ** the expression is a variable (TK_VARIABLE), then Expr.token contains the
  11372. ** variable name. Finally, if the expression is an SQL function (TK_FUNCTION),
  11373. ** then Expr.token contains the name of the function.
  11374. **
  11375. ** Expr.pRight and Expr.pLeft are the left and right subexpressions of a
  11376. ** binary operator. Either or both may be NULL.
  11377. **
  11378. ** Expr.x.pList is a list of arguments if the expression is an SQL function,
  11379. ** a CASE expression or an IN expression of the form "<lhs> IN (<y>, <z>...)".
  11380. ** Expr.x.pSelect is used if the expression is a sub-select or an expression of
  11381. ** the form "<lhs> IN (SELECT ...)". If the EP_xIsSelect bit is set in the
  11382. ** Expr.flags mask, then Expr.x.pSelect is valid. Otherwise, Expr.x.pList is
  11383. ** valid.
  11384. **
  11385. ** An expression of the form ID or ID.ID refers to a column in a table.
  11386. ** For such expressions, Expr.op is set to TK_COLUMN and Expr.iTable is
  11387. ** the integer cursor number of a VDBE cursor pointing to that table and
  11388. ** Expr.iColumn is the column number for the specific column. If the
  11389. ** expression is used as a result in an aggregate SELECT, then the
  11390. ** value is also stored in the Expr.iAgg column in the aggregate so that
  11391. ** it can be accessed after all aggregates are computed.
  11392. **
  11393. ** If the expression is an unbound variable marker (a question mark
  11394. ** character '?' in the original SQL) then the Expr.iTable holds the index
  11395. ** number for that variable.
  11396. **
  11397. ** If the expression is a subquery then Expr.iColumn holds an integer
  11398. ** register number containing the result of the subquery. If the
  11399. ** subquery gives a constant result, then iTable is -1. If the subquery
  11400. ** gives a different answer at different times during statement processing
  11401. ** then iTable is the address of a subroutine that computes the subquery.
  11402. **
  11403. ** If the Expr is of type OP_Column, and the table it is selecting from
  11404. ** is a disk table or the "old.*" pseudo-table, then pTab points to the
  11405. ** corresponding table definition.
  11406. **
  11407. ** ALLOCATION NOTES:
  11408. **
  11409. ** Expr objects can use a lot of memory space in database schema. To
  11410. ** help reduce memory requirements, sometimes an Expr object will be
  11411. ** truncated. And to reduce the number of memory allocations, sometimes
  11412. ** two or more Expr objects will be stored in a single memory allocation,
  11413. ** together with Expr.zToken strings.
  11414. **
  11415. ** If the EP_Reduced and EP_TokenOnly flags are set when
  11416. ** an Expr object is truncated. When EP_Reduced is set, then all
  11417. ** the child Expr objects in the Expr.pLeft and Expr.pRight subtrees
  11418. ** are contained within the same memory allocation. Note, however, that
  11419. ** the subtrees in Expr.x.pList or Expr.x.pSelect are always separately
  11420. ** allocated, regardless of whether or not EP_Reduced is set.
  11421. */
  11422. struct Expr {
  11423. u8 op; /* Operation performed by this node */
  11424. char affinity; /* The affinity of the column or 0 if not a column */
  11425. u32 flags; /* Various flags. EP_* See below */
  11426. union {
  11427. char *zToken; /* Token value. Zero terminated and dequoted */
  11428. int iValue; /* Non-negative integer value if EP_IntValue */
  11429. } u;
  11430. /* If the EP_TokenOnly flag is set in the Expr.flags mask, then no
  11431. ** space is allocated for the fields below this point. An attempt to
  11432. ** access them will result in a segfault or malfunction.
  11433. *********************************************************************/
  11434. Expr *pLeft; /* Left subnode */
  11435. Expr *pRight; /* Right subnode */
  11436. union {
  11437. ExprList *pList; /* op = IN, EXISTS, SELECT, CASE, FUNCTION, BETWEEN */
  11438. Select *pSelect; /* EP_xIsSelect and op = IN, EXISTS, SELECT */
  11439. } x;
  11440. /* If the EP_Reduced flag is set in the Expr.flags mask, then no
  11441. ** space is allocated for the fields below this point. An attempt to
  11442. ** access them will result in a segfault or malfunction.
  11443. *********************************************************************/
  11444. #if SQLITE_MAX_EXPR_DEPTH>0
  11445. int nHeight; /* Height of the tree headed by this node */
  11446. #endif
  11447. int iTable; /* TK_COLUMN: cursor number of table holding column
  11448. ** TK_REGISTER: register number
  11449. ** TK_TRIGGER: 1 -> new, 0 -> old
  11450. ** EP_Unlikely: 134217728 times likelihood */
  11451. ynVar iColumn; /* TK_COLUMN: column index. -1 for rowid.
  11452. ** TK_VARIABLE: variable number (always >= 1). */
  11453. i16 iAgg; /* Which entry in pAggInfo->aCol[] or ->aFunc[] */
  11454. i16 iRightJoinTable; /* If EP_FromJoin, the right table of the join */
  11455. u8 op2; /* TK_REGISTER: original value of Expr.op
  11456. ** TK_COLUMN: the value of p5 for OP_Column
  11457. ** TK_AGG_FUNCTION: nesting depth */
  11458. AggInfo *pAggInfo; /* Used by TK_AGG_COLUMN and TK_AGG_FUNCTION */
  11459. Table *pTab; /* Table for TK_COLUMN expressions. */
  11460. };
  11461. /*
  11462. ** The following are the meanings of bits in the Expr.flags field.
  11463. */
  11464. #define EP_FromJoin 0x000001 /* Originates in ON/USING clause of outer join */
  11465. #define EP_Agg 0x000002 /* Contains one or more aggregate functions */
  11466. #define EP_Resolved 0x000004 /* IDs have been resolved to COLUMNs */
  11467. #define EP_Error 0x000008 /* Expression contains one or more errors */
  11468. #define EP_Distinct 0x000010 /* Aggregate function with DISTINCT keyword */
  11469. #define EP_VarSelect 0x000020 /* pSelect is correlated, not constant */
  11470. #define EP_DblQuoted 0x000040 /* token.z was originally in "..." */
  11471. #define EP_InfixFunc 0x000080 /* True for an infix function: LIKE, GLOB, etc */
  11472. #define EP_Collate 0x000100 /* Tree contains a TK_COLLATE operator */
  11473. #define EP_Generic 0x000200 /* Ignore COLLATE or affinity on this tree */
  11474. #define EP_IntValue 0x000400 /* Integer value contained in u.iValue */
  11475. #define EP_xIsSelect 0x000800 /* x.pSelect is valid (otherwise x.pList is) */
  11476. #define EP_Skip 0x001000 /* COLLATE, AS, or UNLIKELY */
  11477. #define EP_Reduced 0x002000 /* Expr struct EXPR_REDUCEDSIZE bytes only */
  11478. #define EP_TokenOnly 0x004000 /* Expr struct EXPR_TOKENONLYSIZE bytes only */
  11479. #define EP_Static 0x008000 /* Held in memory not obtained from malloc() */
  11480. #define EP_MemToken 0x010000 /* Need to sqlite3DbFree() Expr.zToken */
  11481. #define EP_NoReduce 0x020000 /* Cannot EXPRDUP_REDUCE this Expr */
  11482. #define EP_Unlikely 0x040000 /* unlikely() or likelihood() function */
  11483. #define EP_ConstFunc 0x080000 /* Node is a SQLITE_FUNC_CONSTANT function */
  11484. #define EP_CanBeNull 0x100000 /* Can be null despite NOT NULL constraint */
  11485. #define EP_Subquery 0x200000 /* Tree contains a TK_SELECT operator */
  11486. /*
  11487. ** Combinations of two or more EP_* flags
  11488. */
  11489. #define EP_Propagate (EP_Collate|EP_Subquery) /* Propagate these bits up tree */
  11490. /*
  11491. ** These macros can be used to test, set, or clear bits in the
  11492. ** Expr.flags field.
  11493. */
  11494. #define ExprHasProperty(E,P) (((E)->flags&(P))!=0)
  11495. #define ExprHasAllProperty(E,P) (((E)->flags&(P))==(P))
  11496. #define ExprSetProperty(E,P) (E)->flags|=(P)
  11497. #define ExprClearProperty(E,P) (E)->flags&=~(P)
  11498. /* The ExprSetVVAProperty() macro is used for Verification, Validation,
  11499. ** and Accreditation only. It works like ExprSetProperty() during VVA
  11500. ** processes but is a no-op for delivery.
  11501. */
  11502. #ifdef SQLITE_DEBUG
  11503. # define ExprSetVVAProperty(E,P) (E)->flags|=(P)
  11504. #else
  11505. # define ExprSetVVAProperty(E,P)
  11506. #endif
  11507. /*
  11508. ** Macros to determine the number of bytes required by a normal Expr
  11509. ** struct, an Expr struct with the EP_Reduced flag set in Expr.flags
  11510. ** and an Expr struct with the EP_TokenOnly flag set.
  11511. */
  11512. #define EXPR_FULLSIZE sizeof(Expr) /* Full size */
  11513. #define EXPR_REDUCEDSIZE offsetof(Expr,iTable) /* Common features */
  11514. #define EXPR_TOKENONLYSIZE offsetof(Expr,pLeft) /* Fewer features */
  11515. /*
  11516. ** Flags passed to the sqlite3ExprDup() function. See the header comment
  11517. ** above sqlite3ExprDup() for details.
  11518. */
  11519. #define EXPRDUP_REDUCE 0x0001 /* Used reduced-size Expr nodes */
  11520. /*
  11521. ** A list of expressions. Each expression may optionally have a
  11522. ** name. An expr/name combination can be used in several ways, such
  11523. ** as the list of "expr AS ID" fields following a "SELECT" or in the
  11524. ** list of "ID = expr" items in an UPDATE. A list of expressions can
  11525. ** also be used as the argument to a function, in which case the a.zName
  11526. ** field is not used.
  11527. **
  11528. ** By default the Expr.zSpan field holds a human-readable description of
  11529. ** the expression that is used in the generation of error messages and
  11530. ** column labels. In this case, Expr.zSpan is typically the text of a
  11531. ** column expression as it exists in a SELECT statement. However, if
  11532. ** the bSpanIsTab flag is set, then zSpan is overloaded to mean the name
  11533. ** of the result column in the form: DATABASE.TABLE.COLUMN. This later
  11534. ** form is used for name resolution with nested FROM clauses.
  11535. */
  11536. struct ExprList {
  11537. int nExpr; /* Number of expressions on the list */
  11538. struct ExprList_item { /* For each expression in the list */
  11539. Expr *pExpr; /* The list of expressions */
  11540. char *zName; /* Token associated with this expression */
  11541. char *zSpan; /* Original text of the expression */
  11542. u8 sortOrder; /* 1 for DESC or 0 for ASC */
  11543. unsigned done :1; /* A flag to indicate when processing is finished */
  11544. unsigned bSpanIsTab :1; /* zSpan holds DB.TABLE.COLUMN */
  11545. unsigned reusable :1; /* Constant expression is reusable */
  11546. union {
  11547. struct {
  11548. u16 iOrderByCol; /* For ORDER BY, column number in result set */
  11549. u16 iAlias; /* Index into Parse.aAlias[] for zName */
  11550. } x;
  11551. int iConstExprReg; /* Register in which Expr value is cached */
  11552. } u;
  11553. } *a; /* Alloc a power of two greater or equal to nExpr */
  11554. };
  11555. /*
  11556. ** An instance of this structure is used by the parser to record both
  11557. ** the parse tree for an expression and the span of input text for an
  11558. ** expression.
  11559. */
  11560. struct ExprSpan {
  11561. Expr *pExpr; /* The expression parse tree */
  11562. const char *zStart; /* First character of input text */
  11563. const char *zEnd; /* One character past the end of input text */
  11564. };
  11565. /*
  11566. ** An instance of this structure can hold a simple list of identifiers,
  11567. ** such as the list "a,b,c" in the following statements:
  11568. **
  11569. ** INSERT INTO t(a,b,c) VALUES ...;
  11570. ** CREATE INDEX idx ON t(a,b,c);
  11571. ** CREATE TRIGGER trig BEFORE UPDATE ON t(a,b,c) ...;
  11572. **
  11573. ** The IdList.a.idx field is used when the IdList represents the list of
  11574. ** column names after a table name in an INSERT statement. In the statement
  11575. **
  11576. ** INSERT INTO t(a,b,c) ...
  11577. **
  11578. ** If "a" is the k-th column of table "t", then IdList.a[0].idx==k.
  11579. */
  11580. struct IdList {
  11581. struct IdList_item {
  11582. char *zName; /* Name of the identifier */
  11583. int idx; /* Index in some Table.aCol[] of a column named zName */
  11584. } *a;
  11585. int nId; /* Number of identifiers on the list */
  11586. };
  11587. /*
  11588. ** The bitmask datatype defined below is used for various optimizations.
  11589. **
  11590. ** Changing this from a 64-bit to a 32-bit type limits the number of
  11591. ** tables in a join to 32 instead of 64. But it also reduces the size
  11592. ** of the library by 738 bytes on ix86.
  11593. */
  11594. typedef u64 Bitmask;
  11595. /*
  11596. ** The number of bits in a Bitmask. "BMS" means "BitMask Size".
  11597. */
  11598. #define BMS ((int)(sizeof(Bitmask)*8))
  11599. /*
  11600. ** A bit in a Bitmask
  11601. */
  11602. #define MASKBIT(n) (((Bitmask)1)<<(n))
  11603. #define MASKBIT32(n) (((unsigned int)1)<<(n))
  11604. /*
  11605. ** The following structure describes the FROM clause of a SELECT statement.
  11606. ** Each table or subquery in the FROM clause is a separate element of
  11607. ** the SrcList.a[] array.
  11608. **
  11609. ** With the addition of multiple database support, the following structure
  11610. ** can also be used to describe a particular table such as the table that
  11611. ** is modified by an INSERT, DELETE, or UPDATE statement. In standard SQL,
  11612. ** such a table must be a simple name: ID. But in SQLite, the table can
  11613. ** now be identified by a database name, a dot, then the table name: ID.ID.
  11614. **
  11615. ** The jointype starts out showing the join type between the current table
  11616. ** and the next table on the list. The parser builds the list this way.
  11617. ** But sqlite3SrcListShiftJoinType() later shifts the jointypes so that each
  11618. ** jointype expresses the join between the table and the previous table.
  11619. **
  11620. ** In the colUsed field, the high-order bit (bit 63) is set if the table
  11621. ** contains more than 63 columns and the 64-th or later column is used.
  11622. */
  11623. struct SrcList {
  11624. int nSrc; /* Number of tables or subqueries in the FROM clause */
  11625. u32 nAlloc; /* Number of entries allocated in a[] below */
  11626. struct SrcList_item {
  11627. Schema *pSchema; /* Schema to which this item is fixed */
  11628. char *zDatabase; /* Name of database holding this table */
  11629. char *zName; /* Name of the table */
  11630. char *zAlias; /* The "B" part of a "A AS B" phrase. zName is the "A" */
  11631. Table *pTab; /* An SQL table corresponding to zName */
  11632. Select *pSelect; /* A SELECT statement used in place of a table name */
  11633. int addrFillSub; /* Address of subroutine to manifest a subquery */
  11634. int regReturn; /* Register holding return address of addrFillSub */
  11635. int regResult; /* Registers holding results of a co-routine */
  11636. u8 jointype; /* Type of join between this able and the previous */
  11637. unsigned notIndexed :1; /* True if there is a NOT INDEXED clause */
  11638. unsigned isCorrelated :1; /* True if sub-query is correlated */
  11639. unsigned viaCoroutine :1; /* Implemented as a co-routine */
  11640. unsigned isRecursive :1; /* True for recursive reference in WITH */
  11641. #ifndef SQLITE_OMIT_EXPLAIN
  11642. u8 iSelectId; /* If pSelect!=0, the id of the sub-select in EQP */
  11643. #endif
  11644. int iCursor; /* The VDBE cursor number used to access this table */
  11645. Expr *pOn; /* The ON clause of a join */
  11646. IdList *pUsing; /* The USING clause of a join */
  11647. Bitmask colUsed; /* Bit N (1<<N) set if column N of pTab is used */
  11648. char *zIndex; /* Identifier from "INDEXED BY <zIndex>" clause */
  11649. Index *pIndex; /* Index structure corresponding to zIndex, if any */
  11650. } a[1]; /* One entry for each identifier on the list */
  11651. };
  11652. /*
  11653. ** Permitted values of the SrcList.a.jointype field
  11654. */
  11655. #define JT_INNER 0x0001 /* Any kind of inner or cross join */
  11656. #define JT_CROSS 0x0002 /* Explicit use of the CROSS keyword */
  11657. #define JT_NATURAL 0x0004 /* True for a "natural" join */
  11658. #define JT_LEFT 0x0008 /* Left outer join */
  11659. #define JT_RIGHT 0x0010 /* Right outer join */
  11660. #define JT_OUTER 0x0020 /* The "OUTER" keyword is present */
  11661. #define JT_ERROR 0x0040 /* unknown or unsupported join type */
  11662. /*
  11663. ** Flags appropriate for the wctrlFlags parameter of sqlite3WhereBegin()
  11664. ** and the WhereInfo.wctrlFlags member.
  11665. */
  11666. #define WHERE_ORDERBY_NORMAL 0x0000 /* No-op */
  11667. #define WHERE_ORDERBY_MIN 0x0001 /* ORDER BY processing for min() func */
  11668. #define WHERE_ORDERBY_MAX 0x0002 /* ORDER BY processing for max() func */
  11669. #define WHERE_ONEPASS_DESIRED 0x0004 /* Want to do one-pass UPDATE/DELETE */
  11670. #define WHERE_DUPLICATES_OK 0x0008 /* Ok to return a row more than once */
  11671. #define WHERE_OMIT_OPEN_CLOSE 0x0010 /* Table cursors are already open */
  11672. #define WHERE_FORCE_TABLE 0x0020 /* Do not use an index-only search */
  11673. #define WHERE_ONETABLE_ONLY 0x0040 /* Only code the 1st table in pTabList */
  11674. #define WHERE_NO_AUTOINDEX 0x0080 /* Disallow automatic indexes */
  11675. #define WHERE_GROUPBY 0x0100 /* pOrderBy is really a GROUP BY */
  11676. #define WHERE_DISTINCTBY 0x0200 /* pOrderby is really a DISTINCT clause */
  11677. #define WHERE_WANT_DISTINCT 0x0400 /* All output needs to be distinct */
  11678. #define WHERE_SORTBYGROUP 0x0800 /* Support sqlite3WhereIsSorted() */
  11679. #define WHERE_REOPEN_IDX 0x1000 /* Try to use OP_ReopenIdx */
  11680. /* Allowed return values from sqlite3WhereIsDistinct()
  11681. */
  11682. #define WHERE_DISTINCT_NOOP 0 /* DISTINCT keyword not used */
  11683. #define WHERE_DISTINCT_UNIQUE 1 /* No duplicates */
  11684. #define WHERE_DISTINCT_ORDERED 2 /* All duplicates are adjacent */
  11685. #define WHERE_DISTINCT_UNORDERED 3 /* Duplicates are scattered */
  11686. /*
  11687. ** A NameContext defines a context in which to resolve table and column
  11688. ** names. The context consists of a list of tables (the pSrcList) field and
  11689. ** a list of named expression (pEList). The named expression list may
  11690. ** be NULL. The pSrc corresponds to the FROM clause of a SELECT or
  11691. ** to the table being operated on by INSERT, UPDATE, or DELETE. The
  11692. ** pEList corresponds to the result set of a SELECT and is NULL for
  11693. ** other statements.
  11694. **
  11695. ** NameContexts can be nested. When resolving names, the inner-most
  11696. ** context is searched first. If no match is found, the next outer
  11697. ** context is checked. If there is still no match, the next context
  11698. ** is checked. This process continues until either a match is found
  11699. ** or all contexts are check. When a match is found, the nRef member of
  11700. ** the context containing the match is incremented.
  11701. **
  11702. ** Each subquery gets a new NameContext. The pNext field points to the
  11703. ** NameContext in the parent query. Thus the process of scanning the
  11704. ** NameContext list corresponds to searching through successively outer
  11705. ** subqueries looking for a match.
  11706. */
  11707. struct NameContext {
  11708. Parse *pParse; /* The parser */
  11709. SrcList *pSrcList; /* One or more tables used to resolve names */
  11710. ExprList *pEList; /* Optional list of result-set columns */
  11711. AggInfo *pAggInfo; /* Information about aggregates at this level */
  11712. NameContext *pNext; /* Next outer name context. NULL for outermost */
  11713. int nRef; /* Number of names resolved by this context */
  11714. int nErr; /* Number of errors encountered while resolving names */
  11715. u16 ncFlags; /* Zero or more NC_* flags defined below */
  11716. };
  11717. /*
  11718. ** Allowed values for the NameContext, ncFlags field.
  11719. **
  11720. ** Note: NC_MinMaxAgg must have the same value as SF_MinMaxAgg and
  11721. ** SQLITE_FUNC_MINMAX.
  11722. **
  11723. */
  11724. #define NC_AllowAgg 0x0001 /* Aggregate functions are allowed here */
  11725. #define NC_HasAgg 0x0002 /* One or more aggregate functions seen */
  11726. #define NC_IsCheck 0x0004 /* True if resolving names in a CHECK constraint */
  11727. #define NC_InAggFunc 0x0008 /* True if analyzing arguments to an agg func */
  11728. #define NC_PartIdx 0x0010 /* True if resolving a partial index WHERE */
  11729. #define NC_MinMaxAgg 0x1000 /* min/max aggregates seen. See note above */
  11730. /*
  11731. ** An instance of the following structure contains all information
  11732. ** needed to generate code for a single SELECT statement.
  11733. **
  11734. ** nLimit is set to -1 if there is no LIMIT clause. nOffset is set to 0.
  11735. ** If there is a LIMIT clause, the parser sets nLimit to the value of the
  11736. ** limit and nOffset to the value of the offset (or 0 if there is not
  11737. ** offset). But later on, nLimit and nOffset become the memory locations
  11738. ** in the VDBE that record the limit and offset counters.
  11739. **
  11740. ** addrOpenEphm[] entries contain the address of OP_OpenEphemeral opcodes.
  11741. ** These addresses must be stored so that we can go back and fill in
  11742. ** the P4_KEYINFO and P2 parameters later. Neither the KeyInfo nor
  11743. ** the number of columns in P2 can be computed at the same time
  11744. ** as the OP_OpenEphm instruction is coded because not
  11745. ** enough information about the compound query is known at that point.
  11746. ** The KeyInfo for addrOpenTran[0] and [1] contains collating sequences
  11747. ** for the result set. The KeyInfo for addrOpenEphm[2] contains collating
  11748. ** sequences for the ORDER BY clause.
  11749. */
  11750. struct Select {
  11751. ExprList *pEList; /* The fields of the result */
  11752. u8 op; /* One of: TK_UNION TK_ALL TK_INTERSECT TK_EXCEPT */
  11753. u16 selFlags; /* Various SF_* values */
  11754. int iLimit, iOffset; /* Memory registers holding LIMIT & OFFSET counters */
  11755. #if SELECTTRACE_ENABLED
  11756. char zSelName[12]; /* Symbolic name of this SELECT use for debugging */
  11757. #endif
  11758. int addrOpenEphm[2]; /* OP_OpenEphem opcodes related to this select */
  11759. u64 nSelectRow; /* Estimated number of result rows */
  11760. SrcList *pSrc; /* The FROM clause */
  11761. Expr *pWhere; /* The WHERE clause */
  11762. ExprList *pGroupBy; /* The GROUP BY clause */
  11763. Expr *pHaving; /* The HAVING clause */
  11764. ExprList *pOrderBy; /* The ORDER BY clause */
  11765. Select *pPrior; /* Prior select in a compound select statement */
  11766. Select *pNext; /* Next select to the left in a compound */
  11767. Expr *pLimit; /* LIMIT expression. NULL means not used. */
  11768. Expr *pOffset; /* OFFSET expression. NULL means not used. */
  11769. With *pWith; /* WITH clause attached to this select. Or NULL. */
  11770. };
  11771. /*
  11772. ** Allowed values for Select.selFlags. The "SF" prefix stands for
  11773. ** "Select Flag".
  11774. */
  11775. #define SF_Distinct 0x0001 /* Output should be DISTINCT */
  11776. #define SF_Resolved 0x0002 /* Identifiers have been resolved */
  11777. #define SF_Aggregate 0x0004 /* Contains aggregate functions */
  11778. #define SF_UsesEphemeral 0x0008 /* Uses the OpenEphemeral opcode */
  11779. #define SF_Expanded 0x0010 /* sqlite3SelectExpand() called on this */
  11780. #define SF_HasTypeInfo 0x0020 /* FROM subqueries have Table metadata */
  11781. #define SF_Compound 0x0040 /* Part of a compound query */
  11782. #define SF_Values 0x0080 /* Synthesized from VALUES clause */
  11783. #define SF_MultiValue 0x0100 /* Single VALUES term with multiple rows */
  11784. #define SF_NestedFrom 0x0200 /* Part of a parenthesized FROM clause */
  11785. #define SF_MaybeConvert 0x0400 /* Need convertCompoundSelectToSubquery() */
  11786. #define SF_Recursive 0x0800 /* The recursive part of a recursive CTE */
  11787. #define SF_MinMaxAgg 0x1000 /* Aggregate containing min() or max() */
  11788. #define SF_Converted 0x2000 /* By convertCompoundSelectToSubquery() */
  11789. /*
  11790. ** The results of a SELECT can be distributed in several ways, as defined
  11791. ** by one of the following macros. The "SRT" prefix means "SELECT Result
  11792. ** Type".
  11793. **
  11794. ** SRT_Union Store results as a key in a temporary index
  11795. ** identified by pDest->iSDParm.
  11796. **
  11797. ** SRT_Except Remove results from the temporary index pDest->iSDParm.
  11798. **
  11799. ** SRT_Exists Store a 1 in memory cell pDest->iSDParm if the result
  11800. ** set is not empty.
  11801. **
  11802. ** SRT_Discard Throw the results away. This is used by SELECT
  11803. ** statements within triggers whose only purpose is
  11804. ** the side-effects of functions.
  11805. **
  11806. ** All of the above are free to ignore their ORDER BY clause. Those that
  11807. ** follow must honor the ORDER BY clause.
  11808. **
  11809. ** SRT_Output Generate a row of output (using the OP_ResultRow
  11810. ** opcode) for each row in the result set.
  11811. **
  11812. ** SRT_Mem Only valid if the result is a single column.
  11813. ** Store the first column of the first result row
  11814. ** in register pDest->iSDParm then abandon the rest
  11815. ** of the query. This destination implies "LIMIT 1".
  11816. **
  11817. ** SRT_Set The result must be a single column. Store each
  11818. ** row of result as the key in table pDest->iSDParm.
  11819. ** Apply the affinity pDest->affSdst before storing
  11820. ** results. Used to implement "IN (SELECT ...)".
  11821. **
  11822. ** SRT_EphemTab Create an temporary table pDest->iSDParm and store
  11823. ** the result there. The cursor is left open after
  11824. ** returning. This is like SRT_Table except that
  11825. ** this destination uses OP_OpenEphemeral to create
  11826. ** the table first.
  11827. **
  11828. ** SRT_Coroutine Generate a co-routine that returns a new row of
  11829. ** results each time it is invoked. The entry point
  11830. ** of the co-routine is stored in register pDest->iSDParm
  11831. ** and the result row is stored in pDest->nDest registers
  11832. ** starting with pDest->iSdst.
  11833. **
  11834. ** SRT_Table Store results in temporary table pDest->iSDParm.
  11835. ** SRT_Fifo This is like SRT_EphemTab except that the table
  11836. ** is assumed to already be open. SRT_Fifo has
  11837. ** the additional property of being able to ignore
  11838. ** the ORDER BY clause.
  11839. **
  11840. ** SRT_DistFifo Store results in a temporary table pDest->iSDParm.
  11841. ** But also use temporary table pDest->iSDParm+1 as
  11842. ** a record of all prior results and ignore any duplicate
  11843. ** rows. Name means: "Distinct Fifo".
  11844. **
  11845. ** SRT_Queue Store results in priority queue pDest->iSDParm (really
  11846. ** an index). Append a sequence number so that all entries
  11847. ** are distinct.
  11848. **
  11849. ** SRT_DistQueue Store results in priority queue pDest->iSDParm only if
  11850. ** the same record has never been stored before. The
  11851. ** index at pDest->iSDParm+1 hold all prior stores.
  11852. */
  11853. #define SRT_Union 1 /* Store result as keys in an index */
  11854. #define SRT_Except 2 /* Remove result from a UNION index */
  11855. #define SRT_Exists 3 /* Store 1 if the result is not empty */
  11856. #define SRT_Discard 4 /* Do not save the results anywhere */
  11857. #define SRT_Fifo 5 /* Store result as data with an automatic rowid */
  11858. #define SRT_DistFifo 6 /* Like SRT_Fifo, but unique results only */
  11859. #define SRT_Queue 7 /* Store result in an queue */
  11860. #define SRT_DistQueue 8 /* Like SRT_Queue, but unique results only */
  11861. /* The ORDER BY clause is ignored for all of the above */
  11862. #define IgnorableOrderby(X) ((X->eDest)<=SRT_DistQueue)
  11863. #define SRT_Output 9 /* Output each row of result */
  11864. #define SRT_Mem 10 /* Store result in a memory cell */
  11865. #define SRT_Set 11 /* Store results as keys in an index */
  11866. #define SRT_EphemTab 12 /* Create transient tab and store like SRT_Table */
  11867. #define SRT_Coroutine 13 /* Generate a single row of result */
  11868. #define SRT_Table 14 /* Store result as data with an automatic rowid */
  11869. /*
  11870. ** An instance of this object describes where to put of the results of
  11871. ** a SELECT statement.
  11872. */
  11873. struct SelectDest {
  11874. u8 eDest; /* How to dispose of the results. On of SRT_* above. */
  11875. char affSdst; /* Affinity used when eDest==SRT_Set */
  11876. int iSDParm; /* A parameter used by the eDest disposal method */
  11877. int iSdst; /* Base register where results are written */
  11878. int nSdst; /* Number of registers allocated */
  11879. ExprList *pOrderBy; /* Key columns for SRT_Queue and SRT_DistQueue */
  11880. };
  11881. /*
  11882. ** During code generation of statements that do inserts into AUTOINCREMENT
  11883. ** tables, the following information is attached to the Table.u.autoInc.p
  11884. ** pointer of each autoincrement table to record some side information that
  11885. ** the code generator needs. We have to keep per-table autoincrement
  11886. ** information in case inserts are down within triggers. Triggers do not
  11887. ** normally coordinate their activities, but we do need to coordinate the
  11888. ** loading and saving of autoincrement information.
  11889. */
  11890. struct AutoincInfo {
  11891. AutoincInfo *pNext; /* Next info block in a list of them all */
  11892. Table *pTab; /* Table this info block refers to */
  11893. int iDb; /* Index in sqlite3.aDb[] of database holding pTab */
  11894. int regCtr; /* Memory register holding the rowid counter */
  11895. };
  11896. /*
  11897. ** Size of the column cache
  11898. */
  11899. #ifndef SQLITE_N_COLCACHE
  11900. # define SQLITE_N_COLCACHE 10
  11901. #endif
  11902. /*
  11903. ** At least one instance of the following structure is created for each
  11904. ** trigger that may be fired while parsing an INSERT, UPDATE or DELETE
  11905. ** statement. All such objects are stored in the linked list headed at
  11906. ** Parse.pTriggerPrg and deleted once statement compilation has been
  11907. ** completed.
  11908. **
  11909. ** A Vdbe sub-program that implements the body and WHEN clause of trigger
  11910. ** TriggerPrg.pTrigger, assuming a default ON CONFLICT clause of
  11911. ** TriggerPrg.orconf, is stored in the TriggerPrg.pProgram variable.
  11912. ** The Parse.pTriggerPrg list never contains two entries with the same
  11913. ** values for both pTrigger and orconf.
  11914. **
  11915. ** The TriggerPrg.aColmask[0] variable is set to a mask of old.* columns
  11916. ** accessed (or set to 0 for triggers fired as a result of INSERT
  11917. ** statements). Similarly, the TriggerPrg.aColmask[1] variable is set to
  11918. ** a mask of new.* columns used by the program.
  11919. */
  11920. struct TriggerPrg {
  11921. Trigger *pTrigger; /* Trigger this program was coded from */
  11922. TriggerPrg *pNext; /* Next entry in Parse.pTriggerPrg list */
  11923. SubProgram *pProgram; /* Program implementing pTrigger/orconf */
  11924. int orconf; /* Default ON CONFLICT policy */
  11925. u32 aColmask[2]; /* Masks of old.*, new.* columns accessed */
  11926. };
  11927. /*
  11928. ** The yDbMask datatype for the bitmask of all attached databases.
  11929. */
  11930. #if SQLITE_MAX_ATTACHED>30
  11931. typedef unsigned char yDbMask[(SQLITE_MAX_ATTACHED+9)/8];
  11932. # define DbMaskTest(M,I) (((M)[(I)/8]&(1<<((I)&7)))!=0)
  11933. # define DbMaskZero(M) memset((M),0,sizeof(M))
  11934. # define DbMaskSet(M,I) (M)[(I)/8]|=(1<<((I)&7))
  11935. # define DbMaskAllZero(M) sqlite3DbMaskAllZero(M)
  11936. # define DbMaskNonZero(M) (sqlite3DbMaskAllZero(M)==0)
  11937. #else
  11938. typedef unsigned int yDbMask;
  11939. # define DbMaskTest(M,I) (((M)&(((yDbMask)1)<<(I)))!=0)
  11940. # define DbMaskZero(M) (M)=0
  11941. # define DbMaskSet(M,I) (M)|=(((yDbMask)1)<<(I))
  11942. # define DbMaskAllZero(M) (M)==0
  11943. # define DbMaskNonZero(M) (M)!=0
  11944. #endif
  11945. /*
  11946. ** An SQL parser context. A copy of this structure is passed through
  11947. ** the parser and down into all the parser action routine in order to
  11948. ** carry around information that is global to the entire parse.
  11949. **
  11950. ** The structure is divided into two parts. When the parser and code
  11951. ** generate call themselves recursively, the first part of the structure
  11952. ** is constant but the second part is reset at the beginning and end of
  11953. ** each recursion.
  11954. **
  11955. ** The nTableLock and aTableLock variables are only used if the shared-cache
  11956. ** feature is enabled (if sqlite3Tsd()->useSharedData is true). They are
  11957. ** used to store the set of table-locks required by the statement being
  11958. ** compiled. Function sqlite3TableLock() is used to add entries to the
  11959. ** list.
  11960. */
  11961. struct Parse {
  11962. sqlite3 *db; /* The main database structure */
  11963. char *zErrMsg; /* An error message */
  11964. Vdbe *pVdbe; /* An engine for executing database bytecode */
  11965. int rc; /* Return code from execution */
  11966. u8 colNamesSet; /* TRUE after OP_ColumnName has been issued to pVdbe */
  11967. u8 checkSchema; /* Causes schema cookie check after an error */
  11968. u8 nested; /* Number of nested calls to the parser/code generator */
  11969. u8 nTempReg; /* Number of temporary registers in aTempReg[] */
  11970. u8 isMultiWrite; /* True if statement may modify/insert multiple rows */
  11971. u8 mayAbort; /* True if statement may throw an ABORT exception */
  11972. u8 hasCompound; /* Need to invoke convertCompoundSelectToSubquery() */
  11973. u8 okConstFactor; /* OK to factor out constants */
  11974. int aTempReg[8]; /* Holding area for temporary registers */
  11975. int nRangeReg; /* Size of the temporary register block */
  11976. int iRangeReg; /* First register in temporary register block */
  11977. int nErr; /* Number of errors seen */
  11978. int nTab; /* Number of previously allocated VDBE cursors */
  11979. int nMem; /* Number of memory cells used so far */
  11980. int nSet; /* Number of sets used so far */
  11981. int nOnce; /* Number of OP_Once instructions so far */
  11982. int nOpAlloc; /* Number of slots allocated for Vdbe.aOp[] */
  11983. int iFixedOp; /* Never back out opcodes iFixedOp-1 or earlier */
  11984. int ckBase; /* Base register of data during check constraints */
  11985. int iPartIdxTab; /* Table corresponding to a partial index */
  11986. int iCacheLevel; /* ColCache valid when aColCache[].iLevel<=iCacheLevel */
  11987. int iCacheCnt; /* Counter used to generate aColCache[].lru values */
  11988. int nLabel; /* Number of labels used */
  11989. int *aLabel; /* Space to hold the labels */
  11990. struct yColCache {
  11991. int iTable; /* Table cursor number */
  11992. i16 iColumn; /* Table column number */
  11993. u8 tempReg; /* iReg is a temp register that needs to be freed */
  11994. int iLevel; /* Nesting level */
  11995. int iReg; /* Reg with value of this column. 0 means none. */
  11996. int lru; /* Least recently used entry has the smallest value */
  11997. } aColCache[SQLITE_N_COLCACHE]; /* One for each column cache entry */
  11998. ExprList *pConstExpr;/* Constant expressions */
  11999. Token constraintName;/* Name of the constraint currently being parsed */
  12000. yDbMask writeMask; /* Start a write transaction on these databases */
  12001. yDbMask cookieMask; /* Bitmask of schema verified databases */
  12002. int cookieValue[SQLITE_MAX_ATTACHED+2]; /* Values of cookies to verify */
  12003. int regRowid; /* Register holding rowid of CREATE TABLE entry */
  12004. int regRoot; /* Register holding root page number for new objects */
  12005. int nMaxArg; /* Max args passed to user function by sub-program */
  12006. #if SELECTTRACE_ENABLED
  12007. int nSelect; /* Number of SELECT statements seen */
  12008. int nSelectIndent; /* How far to indent SELECTTRACE() output */
  12009. #endif
  12010. #ifndef SQLITE_OMIT_SHARED_CACHE
  12011. int nTableLock; /* Number of locks in aTableLock */
  12012. TableLock *aTableLock; /* Required table locks for shared-cache mode */
  12013. #endif
  12014. AutoincInfo *pAinc; /* Information about AUTOINCREMENT counters */
  12015. /* Information used while coding trigger programs. */
  12016. Parse *pToplevel; /* Parse structure for main program (or NULL) */
  12017. Table *pTriggerTab; /* Table triggers are being coded for */
  12018. int addrCrTab; /* Address of OP_CreateTable opcode on CREATE TABLE */
  12019. int addrSkipPK; /* Address of instruction to skip PRIMARY KEY index */
  12020. u32 nQueryLoop; /* Est number of iterations of a query (10*log2(N)) */
  12021. u32 oldmask; /* Mask of old.* columns referenced */
  12022. u32 newmask; /* Mask of new.* columns referenced */
  12023. u8 eTriggerOp; /* TK_UPDATE, TK_INSERT or TK_DELETE */
  12024. u8 eOrconf; /* Default ON CONFLICT policy for trigger steps */
  12025. u8 disableTriggers; /* True to disable triggers */
  12026. /************************************************************************
  12027. ** Above is constant between recursions. Below is reset before and after
  12028. ** each recursion. The boundary between these two regions is determined
  12029. ** using offsetof(Parse,nVar) so the nVar field must be the first field
  12030. ** in the recursive region.
  12031. ************************************************************************/
  12032. int nVar; /* Number of '?' variables seen in the SQL so far */
  12033. int nzVar; /* Number of available slots in azVar[] */
  12034. u8 iPkSortOrder; /* ASC or DESC for INTEGER PRIMARY KEY */
  12035. u8 bFreeWith; /* True if pWith should be freed with parser */
  12036. u8 explain; /* True if the EXPLAIN flag is found on the query */
  12037. #ifndef SQLITE_OMIT_VIRTUALTABLE
  12038. u8 declareVtab; /* True if inside sqlite3_declare_vtab() */
  12039. int nVtabLock; /* Number of virtual tables to lock */
  12040. #endif
  12041. int nAlias; /* Number of aliased result set columns */
  12042. int nHeight; /* Expression tree height of current sub-select */
  12043. #ifndef SQLITE_OMIT_EXPLAIN
  12044. int iSelectId; /* ID of current select for EXPLAIN output */
  12045. int iNextSelectId; /* Next available select ID for EXPLAIN output */
  12046. #endif
  12047. char **azVar; /* Pointers to names of parameters */
  12048. Vdbe *pReprepare; /* VM being reprepared (sqlite3Reprepare()) */
  12049. const char *zTail; /* All SQL text past the last semicolon parsed */
  12050. Table *pNewTable; /* A table being constructed by CREATE TABLE */
  12051. Trigger *pNewTrigger; /* Trigger under construct by a CREATE TRIGGER */
  12052. const char *zAuthContext; /* The 6th parameter to db->xAuth callbacks */
  12053. Token sNameToken; /* Token with unqualified schema object name */
  12054. Token sLastToken; /* The last token parsed */
  12055. #ifndef SQLITE_OMIT_VIRTUALTABLE
  12056. Token sArg; /* Complete text of a module argument */
  12057. Table **apVtabLock; /* Pointer to virtual tables needing locking */
  12058. #endif
  12059. Table *pZombieTab; /* List of Table objects to delete after code gen */
  12060. TriggerPrg *pTriggerPrg; /* Linked list of coded triggers */
  12061. With *pWith; /* Current WITH clause, or NULL */
  12062. };
  12063. /*
  12064. ** Return true if currently inside an sqlite3_declare_vtab() call.
  12065. */
  12066. #ifdef SQLITE_OMIT_VIRTUALTABLE
  12067. #define IN_DECLARE_VTAB 0
  12068. #else
  12069. #define IN_DECLARE_VTAB (pParse->declareVtab)
  12070. #endif
  12071. /*
  12072. ** An instance of the following structure can be declared on a stack and used
  12073. ** to save the Parse.zAuthContext value so that it can be restored later.
  12074. */
  12075. struct AuthContext {
  12076. const char *zAuthContext; /* Put saved Parse.zAuthContext here */
  12077. Parse *pParse; /* The Parse structure */
  12078. };
  12079. /*
  12080. ** Bitfield flags for P5 value in various opcodes.
  12081. */
  12082. #define OPFLAG_NCHANGE 0x01 /* Set to update db->nChange */
  12083. #define OPFLAG_EPHEM 0x01 /* OP_Column: Ephemeral output is ok */
  12084. #define OPFLAG_LASTROWID 0x02 /* Set to update db->lastRowid */
  12085. #define OPFLAG_ISUPDATE 0x04 /* This OP_Insert is an sql UPDATE */
  12086. #define OPFLAG_APPEND 0x08 /* This is likely to be an append */
  12087. #define OPFLAG_USESEEKRESULT 0x10 /* Try to avoid a seek in BtreeInsert() */
  12088. #define OPFLAG_LENGTHARG 0x40 /* OP_Column only used for length() */
  12089. #define OPFLAG_TYPEOFARG 0x80 /* OP_Column only used for typeof() */
  12090. #define OPFLAG_BULKCSR 0x01 /* OP_Open** used to open bulk cursor */
  12091. #define OPFLAG_SEEKEQ 0x02 /* OP_Open** cursor uses EQ seek only */
  12092. #define OPFLAG_P2ISREG 0x04 /* P2 to OP_Open** is a register number */
  12093. #define OPFLAG_PERMUTE 0x01 /* OP_Compare: use the permutation */
  12094. /*
  12095. * Each trigger present in the database schema is stored as an instance of
  12096. * struct Trigger.
  12097. *
  12098. * Pointers to instances of struct Trigger are stored in two ways.
  12099. * 1. In the "trigHash" hash table (part of the sqlite3* that represents the
  12100. * database). This allows Trigger structures to be retrieved by name.
  12101. * 2. All triggers associated with a single table form a linked list, using the
  12102. * pNext member of struct Trigger. A pointer to the first element of the
  12103. * linked list is stored as the "pTrigger" member of the associated
  12104. * struct Table.
  12105. *
  12106. * The "step_list" member points to the first element of a linked list
  12107. * containing the SQL statements specified as the trigger program.
  12108. */
  12109. struct Trigger {
  12110. char *zName; /* The name of the trigger */
  12111. char *table; /* The table or view to which the trigger applies */
  12112. u8 op; /* One of TK_DELETE, TK_UPDATE, TK_INSERT */
  12113. u8 tr_tm; /* One of TRIGGER_BEFORE, TRIGGER_AFTER */
  12114. Expr *pWhen; /* The WHEN clause of the expression (may be NULL) */
  12115. IdList *pColumns; /* If this is an UPDATE OF <column-list> trigger,
  12116. the <column-list> is stored here */
  12117. Schema *pSchema; /* Schema containing the trigger */
  12118. Schema *pTabSchema; /* Schema containing the table */
  12119. TriggerStep *step_list; /* Link list of trigger program steps */
  12120. Trigger *pNext; /* Next trigger associated with the table */
  12121. };
  12122. /*
  12123. ** A trigger is either a BEFORE or an AFTER trigger. The following constants
  12124. ** determine which.
  12125. **
  12126. ** If there are multiple triggers, you might of some BEFORE and some AFTER.
  12127. ** In that cases, the constants below can be ORed together.
  12128. */
  12129. #define TRIGGER_BEFORE 1
  12130. #define TRIGGER_AFTER 2
  12131. /*
  12132. * An instance of struct TriggerStep is used to store a single SQL statement
  12133. * that is a part of a trigger-program.
  12134. *
  12135. * Instances of struct TriggerStep are stored in a singly linked list (linked
  12136. * using the "pNext" member) referenced by the "step_list" member of the
  12137. * associated struct Trigger instance. The first element of the linked list is
  12138. * the first step of the trigger-program.
  12139. *
  12140. * The "op" member indicates whether this is a "DELETE", "INSERT", "UPDATE" or
  12141. * "SELECT" statement. The meanings of the other members is determined by the
  12142. * value of "op" as follows:
  12143. *
  12144. * (op == TK_INSERT)
  12145. * orconf -> stores the ON CONFLICT algorithm
  12146. * pSelect -> If this is an INSERT INTO ... SELECT ... statement, then
  12147. * this stores a pointer to the SELECT statement. Otherwise NULL.
  12148. * zTarget -> Dequoted name of the table to insert into.
  12149. * pExprList -> If this is an INSERT INTO ... VALUES ... statement, then
  12150. * this stores values to be inserted. Otherwise NULL.
  12151. * pIdList -> If this is an INSERT INTO ... (<column-names>) VALUES ...
  12152. * statement, then this stores the column-names to be
  12153. * inserted into.
  12154. *
  12155. * (op == TK_DELETE)
  12156. * zTarget -> Dequoted name of the table to delete from.
  12157. * pWhere -> The WHERE clause of the DELETE statement if one is specified.
  12158. * Otherwise NULL.
  12159. *
  12160. * (op == TK_UPDATE)
  12161. * zTarget -> Dequoted name of the table to update.
  12162. * pWhere -> The WHERE clause of the UPDATE statement if one is specified.
  12163. * Otherwise NULL.
  12164. * pExprList -> A list of the columns to update and the expressions to update
  12165. * them to. See sqlite3Update() documentation of "pChanges"
  12166. * argument.
  12167. *
  12168. */
  12169. struct TriggerStep {
  12170. u8 op; /* One of TK_DELETE, TK_UPDATE, TK_INSERT, TK_SELECT */
  12171. u8 orconf; /* OE_Rollback etc. */
  12172. Trigger *pTrig; /* The trigger that this step is a part of */
  12173. Select *pSelect; /* SELECT statement or RHS of INSERT INTO SELECT ... */
  12174. char *zTarget; /* Target table for DELETE, UPDATE, INSERT */
  12175. Expr *pWhere; /* The WHERE clause for DELETE or UPDATE steps */
  12176. ExprList *pExprList; /* SET clause for UPDATE. */
  12177. IdList *pIdList; /* Column names for INSERT */
  12178. TriggerStep *pNext; /* Next in the link-list */
  12179. TriggerStep *pLast; /* Last element in link-list. Valid for 1st elem only */
  12180. };
  12181. /*
  12182. ** The following structure contains information used by the sqliteFix...
  12183. ** routines as they walk the parse tree to make database references
  12184. ** explicit.
  12185. */
  12186. typedef struct DbFixer DbFixer;
  12187. struct DbFixer {
  12188. Parse *pParse; /* The parsing context. Error messages written here */
  12189. Schema *pSchema; /* Fix items to this schema */
  12190. int bVarOnly; /* Check for variable references only */
  12191. const char *zDb; /* Make sure all objects are contained in this database */
  12192. const char *zType; /* Type of the container - used for error messages */
  12193. const Token *pName; /* Name of the container - used for error messages */
  12194. };
  12195. /*
  12196. ** An objected used to accumulate the text of a string where we
  12197. ** do not necessarily know how big the string will be in the end.
  12198. */
  12199. struct StrAccum {
  12200. sqlite3 *db; /* Optional database for lookaside. Can be NULL */
  12201. char *zBase; /* A base allocation. Not from malloc. */
  12202. char *zText; /* The string collected so far */
  12203. int nChar; /* Length of the string so far */
  12204. int nAlloc; /* Amount of space allocated in zText */
  12205. int mxAlloc; /* Maximum allowed allocation. 0 for no malloc usage */
  12206. u8 accError; /* STRACCUM_NOMEM or STRACCUM_TOOBIG */
  12207. };
  12208. #define STRACCUM_NOMEM 1
  12209. #define STRACCUM_TOOBIG 2
  12210. /*
  12211. ** A pointer to this structure is used to communicate information
  12212. ** from sqlite3Init and OP_ParseSchema into the sqlite3InitCallback.
  12213. */
  12214. typedef struct {
  12215. sqlite3 *db; /* The database being initialized */
  12216. char **pzErrMsg; /* Error message stored here */
  12217. int iDb; /* 0 for main database. 1 for TEMP, 2.. for ATTACHed */
  12218. int rc; /* Result code stored here */
  12219. } InitData;
  12220. /*
  12221. ** Structure containing global configuration data for the SQLite library.
  12222. **
  12223. ** This structure also contains some state information.
  12224. */
  12225. struct Sqlite3Config {
  12226. int bMemstat; /* True to enable memory status */
  12227. int bCoreMutex; /* True to enable core mutexing */
  12228. int bFullMutex; /* True to enable full mutexing */
  12229. int bOpenUri; /* True to interpret filenames as URIs */
  12230. int bUseCis; /* Use covering indices for full-scans */
  12231. int mxStrlen; /* Maximum string length */
  12232. int neverCorrupt; /* Database is always well-formed */
  12233. int szLookaside; /* Default lookaside buffer size */
  12234. int nLookaside; /* Default lookaside buffer count */
  12235. sqlite3_mem_methods m; /* Low-level memory allocation interface */
  12236. sqlite3_mutex_methods mutex; /* Low-level mutex interface */
  12237. sqlite3_pcache_methods2 pcache2; /* Low-level page-cache interface */
  12238. void *pHeap; /* Heap storage space */
  12239. int nHeap; /* Size of pHeap[] */
  12240. int mnReq, mxReq; /* Min and max heap requests sizes */
  12241. sqlite3_int64 szMmap; /* mmap() space per open file */
  12242. sqlite3_int64 mxMmap; /* Maximum value for szMmap */
  12243. void *pScratch; /* Scratch memory */
  12244. int szScratch; /* Size of each scratch buffer */
  12245. int nScratch; /* Number of scratch buffers */
  12246. void *pPage; /* Page cache memory */
  12247. int szPage; /* Size of each page in pPage[] */
  12248. int nPage; /* Number of pages in pPage[] */
  12249. int mxParserStack; /* maximum depth of the parser stack */
  12250. int sharedCacheEnabled; /* true if shared-cache mode enabled */
  12251. u32 szPma; /* Maximum Sorter PMA size */
  12252. /* The above might be initialized to non-zero. The following need to always
  12253. ** initially be zero, however. */
  12254. int isInit; /* True after initialization has finished */
  12255. int inProgress; /* True while initialization in progress */
  12256. int isMutexInit; /* True after mutexes are initialized */
  12257. int isMallocInit; /* True after malloc is initialized */
  12258. int isPCacheInit; /* True after malloc is initialized */
  12259. int nRefInitMutex; /* Number of users of pInitMutex */
  12260. sqlite3_mutex *pInitMutex; /* Mutex used by sqlite3_initialize() */
  12261. void (*xLog)(void*,int,const char*); /* Function for logging */
  12262. void *pLogArg; /* First argument to xLog() */
  12263. #ifdef SQLITE_ENABLE_SQLLOG
  12264. void(*xSqllog)(void*,sqlite3*,const char*, int);
  12265. void *pSqllogArg;
  12266. #endif
  12267. #ifdef SQLITE_VDBE_COVERAGE
  12268. /* The following callback (if not NULL) is invoked on every VDBE branch
  12269. ** operation. Set the callback using SQLITE_TESTCTRL_VDBE_COVERAGE.
  12270. */
  12271. void (*xVdbeBranch)(void*,int iSrcLine,u8 eThis,u8 eMx); /* Callback */
  12272. void *pVdbeBranchArg; /* 1st argument */
  12273. #endif
  12274. #ifndef SQLITE_OMIT_BUILTIN_TEST
  12275. int (*xTestCallback)(int); /* Invoked by sqlite3FaultSim() */
  12276. #endif
  12277. int bLocaltimeFault; /* True to fail localtime() calls */
  12278. };
  12279. /*
  12280. ** This macro is used inside of assert() statements to indicate that
  12281. ** the assert is only valid on a well-formed database. Instead of:
  12282. **
  12283. ** assert( X );
  12284. **
  12285. ** One writes:
  12286. **
  12287. ** assert( X || CORRUPT_DB );
  12288. **
  12289. ** CORRUPT_DB is true during normal operation. CORRUPT_DB does not indicate
  12290. ** that the database is definitely corrupt, only that it might be corrupt.
  12291. ** For most test cases, CORRUPT_DB is set to false using a special
  12292. ** sqlite3_test_control(). This enables assert() statements to prove
  12293. ** things that are always true for well-formed databases.
  12294. */
  12295. #define CORRUPT_DB (sqlite3Config.neverCorrupt==0)
  12296. /*
  12297. ** Context pointer passed down through the tree-walk.
  12298. */
  12299. struct Walker {
  12300. int (*xExprCallback)(Walker*, Expr*); /* Callback for expressions */
  12301. int (*xSelectCallback)(Walker*,Select*); /* Callback for SELECTs */
  12302. void (*xSelectCallback2)(Walker*,Select*);/* Second callback for SELECTs */
  12303. Parse *pParse; /* Parser context. */
  12304. int walkerDepth; /* Number of subqueries */
  12305. u8 eCode; /* A small processing code */
  12306. union { /* Extra data for callback */
  12307. NameContext *pNC; /* Naming context */
  12308. int n; /* A counter */
  12309. int iCur; /* A cursor number */
  12310. SrcList *pSrcList; /* FROM clause */
  12311. struct SrcCount *pSrcCount; /* Counting column references */
  12312. } u;
  12313. };
  12314. /* Forward declarations */
  12315. SQLITE_PRIVATE int sqlite3WalkExpr(Walker*, Expr*);
  12316. SQLITE_PRIVATE int sqlite3WalkExprList(Walker*, ExprList*);
  12317. SQLITE_PRIVATE int sqlite3WalkSelect(Walker*, Select*);
  12318. SQLITE_PRIVATE int sqlite3WalkSelectExpr(Walker*, Select*);
  12319. SQLITE_PRIVATE int sqlite3WalkSelectFrom(Walker*, Select*);
  12320. /*
  12321. ** Return code from the parse-tree walking primitives and their
  12322. ** callbacks.
  12323. */
  12324. #define WRC_Continue 0 /* Continue down into children */
  12325. #define WRC_Prune 1 /* Omit children but continue walking siblings */
  12326. #define WRC_Abort 2 /* Abandon the tree walk */
  12327. /*
  12328. ** An instance of this structure represents a set of one or more CTEs
  12329. ** (common table expressions) created by a single WITH clause.
  12330. */
  12331. struct With {
  12332. int nCte; /* Number of CTEs in the WITH clause */
  12333. With *pOuter; /* Containing WITH clause, or NULL */
  12334. struct Cte { /* For each CTE in the WITH clause.... */
  12335. char *zName; /* Name of this CTE */
  12336. ExprList *pCols; /* List of explicit column names, or NULL */
  12337. Select *pSelect; /* The definition of this CTE */
  12338. const char *zErr; /* Error message for circular references */
  12339. } a[1];
  12340. };
  12341. #ifdef SQLITE_DEBUG
  12342. /*
  12343. ** An instance of the TreeView object is used for printing the content of
  12344. ** data structures on sqlite3DebugPrintf() using a tree-like view.
  12345. */
  12346. struct TreeView {
  12347. int iLevel; /* Which level of the tree we are on */
  12348. u8 bLine[100]; /* Draw vertical in column i if bLine[i] is true */
  12349. };
  12350. #endif /* SQLITE_DEBUG */
  12351. /*
  12352. ** Assuming zIn points to the first byte of a UTF-8 character,
  12353. ** advance zIn to point to the first byte of the next UTF-8 character.
  12354. */
  12355. #define SQLITE_SKIP_UTF8(zIn) { \
  12356. if( (*(zIn++))>=0xc0 ){ \
  12357. while( (*zIn & 0xc0)==0x80 ){ zIn++; } \
  12358. } \
  12359. }
  12360. /*
  12361. ** The SQLITE_*_BKPT macros are substitutes for the error codes with
  12362. ** the same name but without the _BKPT suffix. These macros invoke
  12363. ** routines that report the line-number on which the error originated
  12364. ** using sqlite3_log(). The routines also provide a convenient place
  12365. ** to set a debugger breakpoint.
  12366. */
  12367. SQLITE_PRIVATE int sqlite3CorruptError(int);
  12368. SQLITE_PRIVATE int sqlite3MisuseError(int);
  12369. SQLITE_PRIVATE int sqlite3CantopenError(int);
  12370. #define SQLITE_CORRUPT_BKPT sqlite3CorruptError(__LINE__)
  12371. #define SQLITE_MISUSE_BKPT sqlite3MisuseError(__LINE__)
  12372. #define SQLITE_CANTOPEN_BKPT sqlite3CantopenError(__LINE__)
  12373. /*
  12374. ** FTS4 is really an extension for FTS3. It is enabled using the
  12375. ** SQLITE_ENABLE_FTS3 macro. But to avoid confusion we also call
  12376. ** the SQLITE_ENABLE_FTS4 macro to serve as an alias for SQLITE_ENABLE_FTS3.
  12377. */
  12378. #if defined(SQLITE_ENABLE_FTS4) && !defined(SQLITE_ENABLE_FTS3)
  12379. # define SQLITE_ENABLE_FTS3 1
  12380. #endif
  12381. /*
  12382. ** The ctype.h header is needed for non-ASCII systems. It is also
  12383. ** needed by FTS3 when FTS3 is included in the amalgamation.
  12384. */
  12385. #if !defined(SQLITE_ASCII) || \
  12386. (defined(SQLITE_ENABLE_FTS3) && defined(SQLITE_AMALGAMATION))
  12387. # include <ctype.h>
  12388. #endif
  12389. /*
  12390. ** The following macros mimic the standard library functions toupper(),
  12391. ** isspace(), isalnum(), isdigit() and isxdigit(), respectively. The
  12392. ** sqlite versions only work for ASCII characters, regardless of locale.
  12393. */
  12394. #ifdef SQLITE_ASCII
  12395. # define sqlite3Toupper(x) ((x)&~(sqlite3CtypeMap[(unsigned char)(x)]&0x20))
  12396. # define sqlite3Isspace(x) (sqlite3CtypeMap[(unsigned char)(x)]&0x01)
  12397. # define sqlite3Isalnum(x) (sqlite3CtypeMap[(unsigned char)(x)]&0x06)
  12398. # define sqlite3Isalpha(x) (sqlite3CtypeMap[(unsigned char)(x)]&0x02)
  12399. # define sqlite3Isdigit(x) (sqlite3CtypeMap[(unsigned char)(x)]&0x04)
  12400. # define sqlite3Isxdigit(x) (sqlite3CtypeMap[(unsigned char)(x)]&0x08)
  12401. # define sqlite3Tolower(x) (sqlite3UpperToLower[(unsigned char)(x)])
  12402. #else
  12403. # define sqlite3Toupper(x) toupper((unsigned char)(x))
  12404. # define sqlite3Isspace(x) isspace((unsigned char)(x))
  12405. # define sqlite3Isalnum(x) isalnum((unsigned char)(x))
  12406. # define sqlite3Isalpha(x) isalpha((unsigned char)(x))
  12407. # define sqlite3Isdigit(x) isdigit((unsigned char)(x))
  12408. # define sqlite3Isxdigit(x) isxdigit((unsigned char)(x))
  12409. # define sqlite3Tolower(x) tolower((unsigned char)(x))
  12410. #endif
  12411. SQLITE_PRIVATE int sqlite3IsIdChar(u8);
  12412. /*
  12413. ** Internal function prototypes
  12414. */
  12415. #define sqlite3StrICmp sqlite3_stricmp
  12416. SQLITE_PRIVATE int sqlite3Strlen30(const char*);
  12417. #define sqlite3StrNICmp sqlite3_strnicmp
  12418. SQLITE_PRIVATE int sqlite3MallocInit(void);
  12419. SQLITE_PRIVATE void sqlite3MallocEnd(void);
  12420. SQLITE_PRIVATE void *sqlite3Malloc(u64);
  12421. SQLITE_PRIVATE void *sqlite3MallocZero(u64);
  12422. SQLITE_PRIVATE void *sqlite3DbMallocZero(sqlite3*, u64);
  12423. SQLITE_PRIVATE void *sqlite3DbMallocRaw(sqlite3*, u64);
  12424. SQLITE_PRIVATE char *sqlite3DbStrDup(sqlite3*,const char*);
  12425. SQLITE_PRIVATE char *sqlite3DbStrNDup(sqlite3*,const char*, u64);
  12426. SQLITE_PRIVATE void *sqlite3Realloc(void*, u64);
  12427. SQLITE_PRIVATE void *sqlite3DbReallocOrFree(sqlite3 *, void *, u64);
  12428. SQLITE_PRIVATE void *sqlite3DbRealloc(sqlite3 *, void *, u64);
  12429. SQLITE_PRIVATE void sqlite3DbFree(sqlite3*, void*);
  12430. SQLITE_PRIVATE int sqlite3MallocSize(void*);
  12431. SQLITE_PRIVATE int sqlite3DbMallocSize(sqlite3*, void*);
  12432. SQLITE_PRIVATE void *sqlite3ScratchMalloc(int);
  12433. SQLITE_PRIVATE void sqlite3ScratchFree(void*);
  12434. SQLITE_PRIVATE void *sqlite3PageMalloc(int);
  12435. SQLITE_PRIVATE void sqlite3PageFree(void*);
  12436. SQLITE_PRIVATE void sqlite3MemSetDefault(void);
  12437. SQLITE_PRIVATE void sqlite3BenignMallocHooks(void (*)(void), void (*)(void));
  12438. SQLITE_PRIVATE int sqlite3HeapNearlyFull(void);
  12439. /*
  12440. ** On systems with ample stack space and that support alloca(), make
  12441. ** use of alloca() to obtain space for large automatic objects. By default,
  12442. ** obtain space from malloc().
  12443. **
  12444. ** The alloca() routine never returns NULL. This will cause code paths
  12445. ** that deal with sqlite3StackAlloc() failures to be unreachable.
  12446. */
  12447. #ifdef SQLITE_USE_ALLOCA
  12448. # define sqlite3StackAllocRaw(D,N) alloca(N)
  12449. # define sqlite3StackAllocZero(D,N) memset(alloca(N), 0, N)
  12450. # define sqlite3StackFree(D,P)
  12451. #else
  12452. # define sqlite3StackAllocRaw(D,N) sqlite3DbMallocRaw(D,N)
  12453. # define sqlite3StackAllocZero(D,N) sqlite3DbMallocZero(D,N)
  12454. # define sqlite3StackFree(D,P) sqlite3DbFree(D,P)
  12455. #endif
  12456. #ifdef SQLITE_ENABLE_MEMSYS3
  12457. SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys3(void);
  12458. #endif
  12459. #ifdef SQLITE_ENABLE_MEMSYS5
  12460. SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys5(void);
  12461. #endif
  12462. #ifndef SQLITE_MUTEX_OMIT
  12463. SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void);
  12464. SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3NoopMutex(void);
  12465. SQLITE_PRIVATE sqlite3_mutex *sqlite3MutexAlloc(int);
  12466. SQLITE_PRIVATE int sqlite3MutexInit(void);
  12467. SQLITE_PRIVATE int sqlite3MutexEnd(void);
  12468. #endif
  12469. SQLITE_PRIVATE sqlite3_int64 sqlite3StatusValue(int);
  12470. SQLITE_PRIVATE void sqlite3StatusUp(int, int);
  12471. SQLITE_PRIVATE void sqlite3StatusDown(int, int);
  12472. SQLITE_PRIVATE void sqlite3StatusSet(int, int);
  12473. /* Access to mutexes used by sqlite3_status() */
  12474. SQLITE_PRIVATE sqlite3_mutex *sqlite3Pcache1Mutex(void);
  12475. SQLITE_PRIVATE sqlite3_mutex *sqlite3MallocMutex(void);
  12476. #ifndef SQLITE_OMIT_FLOATING_POINT
  12477. SQLITE_PRIVATE int sqlite3IsNaN(double);
  12478. #else
  12479. # define sqlite3IsNaN(X) 0
  12480. #endif
  12481. /*
  12482. ** An instance of the following structure holds information about SQL
  12483. ** functions arguments that are the parameters to the printf() function.
  12484. */
  12485. struct PrintfArguments {
  12486. int nArg; /* Total number of arguments */
  12487. int nUsed; /* Number of arguments used so far */
  12488. sqlite3_value **apArg; /* The argument values */
  12489. };
  12490. #define SQLITE_PRINTF_INTERNAL 0x01
  12491. #define SQLITE_PRINTF_SQLFUNC 0x02
  12492. SQLITE_PRIVATE void sqlite3VXPrintf(StrAccum*, u32, const char*, va_list);
  12493. SQLITE_PRIVATE void sqlite3XPrintf(StrAccum*, u32, const char*, ...);
  12494. SQLITE_PRIVATE char *sqlite3MPrintf(sqlite3*,const char*, ...);
  12495. SQLITE_PRIVATE char *sqlite3VMPrintf(sqlite3*,const char*, va_list);
  12496. SQLITE_PRIVATE char *sqlite3MAppendf(sqlite3*,char*,const char*,...);
  12497. #if defined(SQLITE_DEBUG) || defined(SQLITE_HAVE_OS_TRACE)
  12498. SQLITE_PRIVATE void sqlite3DebugPrintf(const char*, ...);
  12499. #endif
  12500. #if defined(SQLITE_TEST)
  12501. SQLITE_PRIVATE void *sqlite3TestTextToPtr(const char*);
  12502. #endif
  12503. #if defined(SQLITE_DEBUG)
  12504. SQLITE_PRIVATE TreeView *sqlite3TreeViewPush(TreeView*,u8);
  12505. SQLITE_PRIVATE void sqlite3TreeViewPop(TreeView*);
  12506. SQLITE_PRIVATE void sqlite3TreeViewLine(TreeView*, const char*, ...);
  12507. SQLITE_PRIVATE void sqlite3TreeViewItem(TreeView*, const char*, u8);
  12508. SQLITE_PRIVATE void sqlite3TreeViewExpr(TreeView*, const Expr*, u8);
  12509. SQLITE_PRIVATE void sqlite3TreeViewExprList(TreeView*, const ExprList*, u8, const char*);
  12510. SQLITE_PRIVATE void sqlite3TreeViewSelect(TreeView*, const Select*, u8);
  12511. #endif
  12512. SQLITE_PRIVATE void sqlite3SetString(char **, sqlite3*, const char*, ...);
  12513. SQLITE_PRIVATE void sqlite3ErrorMsg(Parse*, const char*, ...);
  12514. SQLITE_PRIVATE int sqlite3Dequote(char*);
  12515. SQLITE_PRIVATE int sqlite3KeywordCode(const unsigned char*, int);
  12516. SQLITE_PRIVATE int sqlite3RunParser(Parse*, const char*, char **);
  12517. SQLITE_PRIVATE void sqlite3FinishCoding(Parse*);
  12518. SQLITE_PRIVATE int sqlite3GetTempReg(Parse*);
  12519. SQLITE_PRIVATE void sqlite3ReleaseTempReg(Parse*,int);
  12520. SQLITE_PRIVATE int sqlite3GetTempRange(Parse*,int);
  12521. SQLITE_PRIVATE void sqlite3ReleaseTempRange(Parse*,int,int);
  12522. SQLITE_PRIVATE void sqlite3ClearTempRegCache(Parse*);
  12523. SQLITE_PRIVATE Expr *sqlite3ExprAlloc(sqlite3*,int,const Token*,int);
  12524. SQLITE_PRIVATE Expr *sqlite3Expr(sqlite3*,int,const char*);
  12525. SQLITE_PRIVATE void sqlite3ExprAttachSubtrees(sqlite3*,Expr*,Expr*,Expr*);
  12526. SQLITE_PRIVATE Expr *sqlite3PExpr(Parse*, int, Expr*, Expr*, const Token*);
  12527. SQLITE_PRIVATE Expr *sqlite3ExprAnd(sqlite3*,Expr*, Expr*);
  12528. SQLITE_PRIVATE Expr *sqlite3ExprFunction(Parse*,ExprList*, Token*);
  12529. SQLITE_PRIVATE void sqlite3ExprAssignVarNumber(Parse*, Expr*);
  12530. SQLITE_PRIVATE void sqlite3ExprDelete(sqlite3*, Expr*);
  12531. SQLITE_PRIVATE ExprList *sqlite3ExprListAppend(Parse*,ExprList*,Expr*);
  12532. SQLITE_PRIVATE void sqlite3ExprListSetName(Parse*,ExprList*,Token*,int);
  12533. SQLITE_PRIVATE void sqlite3ExprListSetSpan(Parse*,ExprList*,ExprSpan*);
  12534. SQLITE_PRIVATE void sqlite3ExprListDelete(sqlite3*, ExprList*);
  12535. SQLITE_PRIVATE u32 sqlite3ExprListFlags(const ExprList*);
  12536. SQLITE_PRIVATE int sqlite3Init(sqlite3*, char**);
  12537. SQLITE_PRIVATE int sqlite3InitCallback(void*, int, char**, char**);
  12538. SQLITE_PRIVATE void sqlite3Pragma(Parse*,Token*,Token*,Token*,int);
  12539. SQLITE_PRIVATE void sqlite3ResetAllSchemasOfConnection(sqlite3*);
  12540. SQLITE_PRIVATE void sqlite3ResetOneSchema(sqlite3*,int);
  12541. SQLITE_PRIVATE void sqlite3CollapseDatabaseArray(sqlite3*);
  12542. SQLITE_PRIVATE void sqlite3BeginParse(Parse*,int);
  12543. SQLITE_PRIVATE void sqlite3CommitInternalChanges(sqlite3*);
  12544. SQLITE_PRIVATE Table *sqlite3ResultSetOfSelect(Parse*,Select*);
  12545. SQLITE_PRIVATE void sqlite3OpenMasterTable(Parse *, int);
  12546. SQLITE_PRIVATE Index *sqlite3PrimaryKeyIndex(Table*);
  12547. SQLITE_PRIVATE i16 sqlite3ColumnOfIndex(Index*, i16);
  12548. SQLITE_PRIVATE void sqlite3StartTable(Parse*,Token*,Token*,int,int,int,int);
  12549. SQLITE_PRIVATE void sqlite3AddColumn(Parse*,Token*);
  12550. SQLITE_PRIVATE void sqlite3AddNotNull(Parse*, int);
  12551. SQLITE_PRIVATE void sqlite3AddPrimaryKey(Parse*, ExprList*, int, int, int);
  12552. SQLITE_PRIVATE void sqlite3AddCheckConstraint(Parse*, Expr*);
  12553. SQLITE_PRIVATE void sqlite3AddColumnType(Parse*,Token*);
  12554. SQLITE_PRIVATE void sqlite3AddDefaultValue(Parse*,ExprSpan*);
  12555. SQLITE_PRIVATE void sqlite3AddCollateType(Parse*, Token*);
  12556. SQLITE_PRIVATE void sqlite3EndTable(Parse*,Token*,Token*,u8,Select*);
  12557. SQLITE_PRIVATE int sqlite3ParseUri(const char*,const char*,unsigned int*,
  12558. sqlite3_vfs**,char**,char **);
  12559. SQLITE_PRIVATE Btree *sqlite3DbNameToBtree(sqlite3*,const char*);
  12560. SQLITE_PRIVATE int sqlite3CodeOnce(Parse *);
  12561. #ifdef SQLITE_OMIT_BUILTIN_TEST
  12562. # define sqlite3FaultSim(X) SQLITE_OK
  12563. #else
  12564. SQLITE_PRIVATE int sqlite3FaultSim(int);
  12565. #endif
  12566. SQLITE_PRIVATE Bitvec *sqlite3BitvecCreate(u32);
  12567. SQLITE_PRIVATE int sqlite3BitvecTest(Bitvec*, u32);
  12568. SQLITE_PRIVATE int sqlite3BitvecSet(Bitvec*, u32);
  12569. SQLITE_PRIVATE void sqlite3BitvecClear(Bitvec*, u32, void*);
  12570. SQLITE_PRIVATE void sqlite3BitvecDestroy(Bitvec*);
  12571. SQLITE_PRIVATE u32 sqlite3BitvecSize(Bitvec*);
  12572. SQLITE_PRIVATE int sqlite3BitvecBuiltinTest(int,int*);
  12573. SQLITE_PRIVATE RowSet *sqlite3RowSetInit(sqlite3*, void*, unsigned int);
  12574. SQLITE_PRIVATE void sqlite3RowSetClear(RowSet*);
  12575. SQLITE_PRIVATE void sqlite3RowSetInsert(RowSet*, i64);
  12576. SQLITE_PRIVATE int sqlite3RowSetTest(RowSet*, int iBatch, i64);
  12577. SQLITE_PRIVATE int sqlite3RowSetNext(RowSet*, i64*);
  12578. SQLITE_PRIVATE void sqlite3CreateView(Parse*,Token*,Token*,Token*,Select*,int,int);
  12579. #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
  12580. SQLITE_PRIVATE int sqlite3ViewGetColumnNames(Parse*,Table*);
  12581. #else
  12582. # define sqlite3ViewGetColumnNames(A,B) 0
  12583. #endif
  12584. #if SQLITE_MAX_ATTACHED>30
  12585. SQLITE_PRIVATE int sqlite3DbMaskAllZero(yDbMask);
  12586. #endif
  12587. SQLITE_PRIVATE void sqlite3DropTable(Parse*, SrcList*, int, int);
  12588. SQLITE_PRIVATE void sqlite3CodeDropTable(Parse*, Table*, int, int);
  12589. SQLITE_PRIVATE void sqlite3DeleteTable(sqlite3*, Table*);
  12590. #ifndef SQLITE_OMIT_AUTOINCREMENT
  12591. SQLITE_PRIVATE void sqlite3AutoincrementBegin(Parse *pParse);
  12592. SQLITE_PRIVATE void sqlite3AutoincrementEnd(Parse *pParse);
  12593. #else
  12594. # define sqlite3AutoincrementBegin(X)
  12595. # define sqlite3AutoincrementEnd(X)
  12596. #endif
  12597. SQLITE_PRIVATE void sqlite3Insert(Parse*, SrcList*, Select*, IdList*, int);
  12598. SQLITE_PRIVATE void *sqlite3ArrayAllocate(sqlite3*,void*,int,int*,int*);
  12599. SQLITE_PRIVATE IdList *sqlite3IdListAppend(sqlite3*, IdList*, Token*);
  12600. SQLITE_PRIVATE int sqlite3IdListIndex(IdList*,const char*);
  12601. SQLITE_PRIVATE SrcList *sqlite3SrcListEnlarge(sqlite3*, SrcList*, int, int);
  12602. SQLITE_PRIVATE SrcList *sqlite3SrcListAppend(sqlite3*, SrcList*, Token*, Token*);
  12603. SQLITE_PRIVATE SrcList *sqlite3SrcListAppendFromTerm(Parse*, SrcList*, Token*, Token*,
  12604. Token*, Select*, Expr*, IdList*);
  12605. SQLITE_PRIVATE void sqlite3SrcListIndexedBy(Parse *, SrcList *, Token *);
  12606. SQLITE_PRIVATE int sqlite3IndexedByLookup(Parse *, struct SrcList_item *);
  12607. SQLITE_PRIVATE void sqlite3SrcListShiftJoinType(SrcList*);
  12608. SQLITE_PRIVATE void sqlite3SrcListAssignCursors(Parse*, SrcList*);
  12609. SQLITE_PRIVATE void sqlite3IdListDelete(sqlite3*, IdList*);
  12610. SQLITE_PRIVATE void sqlite3SrcListDelete(sqlite3*, SrcList*);
  12611. SQLITE_PRIVATE Index *sqlite3AllocateIndexObject(sqlite3*,i16,int,char**);
  12612. SQLITE_PRIVATE Index *sqlite3CreateIndex(Parse*,Token*,Token*,SrcList*,ExprList*,int,Token*,
  12613. Expr*, int, int);
  12614. SQLITE_PRIVATE void sqlite3DropIndex(Parse*, SrcList*, int);
  12615. SQLITE_PRIVATE int sqlite3Select(Parse*, Select*, SelectDest*);
  12616. SQLITE_PRIVATE Select *sqlite3SelectNew(Parse*,ExprList*,SrcList*,Expr*,ExprList*,
  12617. Expr*,ExprList*,u16,Expr*,Expr*);
  12618. SQLITE_PRIVATE void sqlite3SelectDelete(sqlite3*, Select*);
  12619. SQLITE_PRIVATE Table *sqlite3SrcListLookup(Parse*, SrcList*);
  12620. SQLITE_PRIVATE int sqlite3IsReadOnly(Parse*, Table*, int);
  12621. SQLITE_PRIVATE void sqlite3OpenTable(Parse*, int iCur, int iDb, Table*, int);
  12622. #if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)
  12623. SQLITE_PRIVATE Expr *sqlite3LimitWhere(Parse*,SrcList*,Expr*,ExprList*,Expr*,Expr*,char*);
  12624. #endif
  12625. SQLITE_PRIVATE void sqlite3DeleteFrom(Parse*, SrcList*, Expr*);
  12626. SQLITE_PRIVATE void sqlite3Update(Parse*, SrcList*, ExprList*, Expr*, int);
  12627. SQLITE_PRIVATE WhereInfo *sqlite3WhereBegin(Parse*,SrcList*,Expr*,ExprList*,ExprList*,u16,int);
  12628. SQLITE_PRIVATE void sqlite3WhereEnd(WhereInfo*);
  12629. SQLITE_PRIVATE u64 sqlite3WhereOutputRowCount(WhereInfo*);
  12630. SQLITE_PRIVATE int sqlite3WhereIsDistinct(WhereInfo*);
  12631. SQLITE_PRIVATE int sqlite3WhereIsOrdered(WhereInfo*);
  12632. SQLITE_PRIVATE int sqlite3WhereIsSorted(WhereInfo*);
  12633. SQLITE_PRIVATE int sqlite3WhereContinueLabel(WhereInfo*);
  12634. SQLITE_PRIVATE int sqlite3WhereBreakLabel(WhereInfo*);
  12635. SQLITE_PRIVATE int sqlite3WhereOkOnePass(WhereInfo*, int*);
  12636. SQLITE_PRIVATE int sqlite3ExprCodeGetColumn(Parse*, Table*, int, int, int, u8);
  12637. SQLITE_PRIVATE void sqlite3ExprCodeGetColumnOfTable(Vdbe*, Table*, int, int, int);
  12638. SQLITE_PRIVATE void sqlite3ExprCodeMove(Parse*, int, int, int);
  12639. SQLITE_PRIVATE void sqlite3ExprCacheStore(Parse*, int, int, int);
  12640. SQLITE_PRIVATE void sqlite3ExprCachePush(Parse*);
  12641. SQLITE_PRIVATE void sqlite3ExprCachePop(Parse*);
  12642. SQLITE_PRIVATE void sqlite3ExprCacheRemove(Parse*, int, int);
  12643. SQLITE_PRIVATE void sqlite3ExprCacheClear(Parse*);
  12644. SQLITE_PRIVATE void sqlite3ExprCacheAffinityChange(Parse*, int, int);
  12645. SQLITE_PRIVATE void sqlite3ExprCode(Parse*, Expr*, int);
  12646. SQLITE_PRIVATE void sqlite3ExprCodeFactorable(Parse*, Expr*, int);
  12647. SQLITE_PRIVATE void sqlite3ExprCodeAtInit(Parse*, Expr*, int, u8);
  12648. SQLITE_PRIVATE int sqlite3ExprCodeTemp(Parse*, Expr*, int*);
  12649. SQLITE_PRIVATE int sqlite3ExprCodeTarget(Parse*, Expr*, int);
  12650. SQLITE_PRIVATE void sqlite3ExprCodeAndCache(Parse*, Expr*, int);
  12651. SQLITE_PRIVATE int sqlite3ExprCodeExprList(Parse*, ExprList*, int, u8);
  12652. #define SQLITE_ECEL_DUP 0x01 /* Deep, not shallow copies */
  12653. #define SQLITE_ECEL_FACTOR 0x02 /* Factor out constant terms */
  12654. SQLITE_PRIVATE void sqlite3ExprIfTrue(Parse*, Expr*, int, int);
  12655. SQLITE_PRIVATE void sqlite3ExprIfFalse(Parse*, Expr*, int, int);
  12656. SQLITE_PRIVATE Table *sqlite3FindTable(sqlite3*,const char*, const char*);
  12657. SQLITE_PRIVATE Table *sqlite3LocateTable(Parse*,int isView,const char*, const char*);
  12658. SQLITE_PRIVATE Table *sqlite3LocateTableItem(Parse*,int isView,struct SrcList_item *);
  12659. SQLITE_PRIVATE Index *sqlite3FindIndex(sqlite3*,const char*, const char*);
  12660. SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTable(sqlite3*,int,const char*);
  12661. SQLITE_PRIVATE void sqlite3UnlinkAndDeleteIndex(sqlite3*,int,const char*);
  12662. SQLITE_PRIVATE void sqlite3Vacuum(Parse*);
  12663. SQLITE_PRIVATE int sqlite3RunVacuum(char**, sqlite3*);
  12664. SQLITE_PRIVATE char *sqlite3NameFromToken(sqlite3*, Token*);
  12665. SQLITE_PRIVATE int sqlite3ExprCompare(Expr*, Expr*, int);
  12666. SQLITE_PRIVATE int sqlite3ExprListCompare(ExprList*, ExprList*, int);
  12667. SQLITE_PRIVATE int sqlite3ExprImpliesExpr(Expr*, Expr*, int);
  12668. SQLITE_PRIVATE void sqlite3ExprAnalyzeAggregates(NameContext*, Expr*);
  12669. SQLITE_PRIVATE void sqlite3ExprAnalyzeAggList(NameContext*,ExprList*);
  12670. SQLITE_PRIVATE int sqlite3FunctionUsesThisSrc(Expr*, SrcList*);
  12671. SQLITE_PRIVATE Vdbe *sqlite3GetVdbe(Parse*);
  12672. SQLITE_PRIVATE void sqlite3PrngSaveState(void);
  12673. SQLITE_PRIVATE void sqlite3PrngRestoreState(void);
  12674. SQLITE_PRIVATE void sqlite3RollbackAll(sqlite3*,int);
  12675. SQLITE_PRIVATE void sqlite3CodeVerifySchema(Parse*, int);
  12676. SQLITE_PRIVATE void sqlite3CodeVerifyNamedSchema(Parse*, const char *zDb);
  12677. SQLITE_PRIVATE void sqlite3BeginTransaction(Parse*, int);
  12678. SQLITE_PRIVATE void sqlite3CommitTransaction(Parse*);
  12679. SQLITE_PRIVATE void sqlite3RollbackTransaction(Parse*);
  12680. SQLITE_PRIVATE void sqlite3Savepoint(Parse*, int, Token*);
  12681. SQLITE_PRIVATE void sqlite3CloseSavepoints(sqlite3 *);
  12682. SQLITE_PRIVATE void sqlite3LeaveMutexAndCloseZombie(sqlite3*);
  12683. SQLITE_PRIVATE int sqlite3ExprIsConstant(Expr*);
  12684. SQLITE_PRIVATE int sqlite3ExprIsConstantNotJoin(Expr*);
  12685. SQLITE_PRIVATE int sqlite3ExprIsConstantOrFunction(Expr*, u8);
  12686. SQLITE_PRIVATE int sqlite3ExprIsTableConstant(Expr*,int);
  12687. SQLITE_PRIVATE int sqlite3ExprIsInteger(Expr*, int*);
  12688. SQLITE_PRIVATE int sqlite3ExprCanBeNull(const Expr*);
  12689. SQLITE_PRIVATE int sqlite3ExprNeedsNoAffinityChange(const Expr*, char);
  12690. SQLITE_PRIVATE int sqlite3IsRowid(const char*);
  12691. SQLITE_PRIVATE void sqlite3GenerateRowDelete(Parse*,Table*,Trigger*,int,int,int,i16,u8,u8,u8);
  12692. SQLITE_PRIVATE void sqlite3GenerateRowIndexDelete(Parse*, Table*, int, int, int*);
  12693. SQLITE_PRIVATE int sqlite3GenerateIndexKey(Parse*, Index*, int, int, int, int*,Index*,int);
  12694. SQLITE_PRIVATE void sqlite3ResolvePartIdxLabel(Parse*,int);
  12695. SQLITE_PRIVATE void sqlite3GenerateConstraintChecks(Parse*,Table*,int*,int,int,int,int,
  12696. u8,u8,int,int*);
  12697. SQLITE_PRIVATE void sqlite3CompleteInsertion(Parse*,Table*,int,int,int,int*,int,int,int);
  12698. SQLITE_PRIVATE int sqlite3OpenTableAndIndices(Parse*, Table*, int, int, u8*, int*, int*);
  12699. SQLITE_PRIVATE void sqlite3BeginWriteOperation(Parse*, int, int);
  12700. SQLITE_PRIVATE void sqlite3MultiWrite(Parse*);
  12701. SQLITE_PRIVATE void sqlite3MayAbort(Parse*);
  12702. SQLITE_PRIVATE void sqlite3HaltConstraint(Parse*, int, int, char*, i8, u8);
  12703. SQLITE_PRIVATE void sqlite3UniqueConstraint(Parse*, int, Index*);
  12704. SQLITE_PRIVATE void sqlite3RowidConstraint(Parse*, int, Table*);
  12705. SQLITE_PRIVATE Expr *sqlite3ExprDup(sqlite3*,Expr*,int);
  12706. SQLITE_PRIVATE ExprList *sqlite3ExprListDup(sqlite3*,ExprList*,int);
  12707. SQLITE_PRIVATE SrcList *sqlite3SrcListDup(sqlite3*,SrcList*,int);
  12708. SQLITE_PRIVATE IdList *sqlite3IdListDup(sqlite3*,IdList*);
  12709. SQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3*,Select*,int);
  12710. #if SELECTTRACE_ENABLED
  12711. SQLITE_PRIVATE void sqlite3SelectSetName(Select*,const char*);
  12712. #else
  12713. # define sqlite3SelectSetName(A,B)
  12714. #endif
  12715. SQLITE_PRIVATE void sqlite3FuncDefInsert(FuncDefHash*, FuncDef*);
  12716. SQLITE_PRIVATE FuncDef *sqlite3FindFunction(sqlite3*,const char*,int,int,u8,u8);
  12717. SQLITE_PRIVATE void sqlite3RegisterBuiltinFunctions(sqlite3*);
  12718. SQLITE_PRIVATE void sqlite3RegisterDateTimeFunctions(void);
  12719. SQLITE_PRIVATE void sqlite3RegisterGlobalFunctions(void);
  12720. SQLITE_PRIVATE int sqlite3SafetyCheckOk(sqlite3*);
  12721. SQLITE_PRIVATE int sqlite3SafetyCheckSickOrOk(sqlite3*);
  12722. SQLITE_PRIVATE void sqlite3ChangeCookie(Parse*, int);
  12723. #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
  12724. SQLITE_PRIVATE void sqlite3MaterializeView(Parse*, Table*, Expr*, int);
  12725. #endif
  12726. #ifndef SQLITE_OMIT_TRIGGER
  12727. SQLITE_PRIVATE void sqlite3BeginTrigger(Parse*, Token*,Token*,int,int,IdList*,SrcList*,
  12728. Expr*,int, int);
  12729. SQLITE_PRIVATE void sqlite3FinishTrigger(Parse*, TriggerStep*, Token*);
  12730. SQLITE_PRIVATE void sqlite3DropTrigger(Parse*, SrcList*, int);
  12731. SQLITE_PRIVATE void sqlite3DropTriggerPtr(Parse*, Trigger*);
  12732. SQLITE_PRIVATE Trigger *sqlite3TriggersExist(Parse *, Table*, int, ExprList*, int *pMask);
  12733. SQLITE_PRIVATE Trigger *sqlite3TriggerList(Parse *, Table *);
  12734. SQLITE_PRIVATE void sqlite3CodeRowTrigger(Parse*, Trigger *, int, ExprList*, int, Table *,
  12735. int, int, int);
  12736. SQLITE_PRIVATE void sqlite3CodeRowTriggerDirect(Parse *, Trigger *, Table *, int, int, int);
  12737. void sqliteViewTriggers(Parse*, Table*, Expr*, int, ExprList*);
  12738. SQLITE_PRIVATE void sqlite3DeleteTriggerStep(sqlite3*, TriggerStep*);
  12739. SQLITE_PRIVATE TriggerStep *sqlite3TriggerSelectStep(sqlite3*,Select*);
  12740. SQLITE_PRIVATE TriggerStep *sqlite3TriggerInsertStep(sqlite3*,Token*, IdList*,
  12741. Select*,u8);
  12742. SQLITE_PRIVATE TriggerStep *sqlite3TriggerUpdateStep(sqlite3*,Token*,ExprList*, Expr*, u8);
  12743. SQLITE_PRIVATE TriggerStep *sqlite3TriggerDeleteStep(sqlite3*,Token*, Expr*);
  12744. SQLITE_PRIVATE void sqlite3DeleteTrigger(sqlite3*, Trigger*);
  12745. SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTrigger(sqlite3*,int,const char*);
  12746. SQLITE_PRIVATE u32 sqlite3TriggerColmask(Parse*,Trigger*,ExprList*,int,int,Table*,int);
  12747. # define sqlite3ParseToplevel(p) ((p)->pToplevel ? (p)->pToplevel : (p))
  12748. #else
  12749. # define sqlite3TriggersExist(B,C,D,E,F) 0
  12750. # define sqlite3DeleteTrigger(A,B)
  12751. # define sqlite3DropTriggerPtr(A,B)
  12752. # define sqlite3UnlinkAndDeleteTrigger(A,B,C)
  12753. # define sqlite3CodeRowTrigger(A,B,C,D,E,F,G,H,I)
  12754. # define sqlite3CodeRowTriggerDirect(A,B,C,D,E,F)
  12755. # define sqlite3TriggerList(X, Y) 0
  12756. # define sqlite3ParseToplevel(p) p
  12757. # define sqlite3TriggerColmask(A,B,C,D,E,F,G) 0
  12758. #endif
  12759. SQLITE_PRIVATE int sqlite3JoinType(Parse*, Token*, Token*, Token*);
  12760. SQLITE_PRIVATE void sqlite3CreateForeignKey(Parse*, ExprList*, Token*, ExprList*, int);
  12761. SQLITE_PRIVATE void sqlite3DeferForeignKey(Parse*, int);
  12762. #ifndef SQLITE_OMIT_AUTHORIZATION
  12763. SQLITE_PRIVATE void sqlite3AuthRead(Parse*,Expr*,Schema*,SrcList*);
  12764. SQLITE_PRIVATE int sqlite3AuthCheck(Parse*,int, const char*, const char*, const char*);
  12765. SQLITE_PRIVATE void sqlite3AuthContextPush(Parse*, AuthContext*, const char*);
  12766. SQLITE_PRIVATE void sqlite3AuthContextPop(AuthContext*);
  12767. SQLITE_PRIVATE int sqlite3AuthReadCol(Parse*, const char *, const char *, int);
  12768. #else
  12769. # define sqlite3AuthRead(a,b,c,d)
  12770. # define sqlite3AuthCheck(a,b,c,d,e) SQLITE_OK
  12771. # define sqlite3AuthContextPush(a,b,c)
  12772. # define sqlite3AuthContextPop(a) ((void)(a))
  12773. #endif
  12774. SQLITE_PRIVATE void sqlite3Attach(Parse*, Expr*, Expr*, Expr*);
  12775. SQLITE_PRIVATE void sqlite3Detach(Parse*, Expr*);
  12776. SQLITE_PRIVATE void sqlite3FixInit(DbFixer*, Parse*, int, const char*, const Token*);
  12777. SQLITE_PRIVATE int sqlite3FixSrcList(DbFixer*, SrcList*);
  12778. SQLITE_PRIVATE int sqlite3FixSelect(DbFixer*, Select*);
  12779. SQLITE_PRIVATE int sqlite3FixExpr(DbFixer*, Expr*);
  12780. SQLITE_PRIVATE int sqlite3FixExprList(DbFixer*, ExprList*);
  12781. SQLITE_PRIVATE int sqlite3FixTriggerStep(DbFixer*, TriggerStep*);
  12782. SQLITE_PRIVATE int sqlite3AtoF(const char *z, double*, int, u8);
  12783. SQLITE_PRIVATE int sqlite3GetInt32(const char *, int*);
  12784. SQLITE_PRIVATE int sqlite3Atoi(const char*);
  12785. SQLITE_PRIVATE int sqlite3Utf16ByteLen(const void *pData, int nChar);
  12786. SQLITE_PRIVATE int sqlite3Utf8CharLen(const char *pData, int nByte);
  12787. SQLITE_PRIVATE u32 sqlite3Utf8Read(const u8**);
  12788. SQLITE_PRIVATE LogEst sqlite3LogEst(u64);
  12789. SQLITE_PRIVATE LogEst sqlite3LogEstAdd(LogEst,LogEst);
  12790. #ifndef SQLITE_OMIT_VIRTUALTABLE
  12791. SQLITE_PRIVATE LogEst sqlite3LogEstFromDouble(double);
  12792. #endif
  12793. SQLITE_PRIVATE u64 sqlite3LogEstToInt(LogEst);
  12794. /*
  12795. ** Routines to read and write variable-length integers. These used to
  12796. ** be defined locally, but now we use the varint routines in the util.c
  12797. ** file.
  12798. */
  12799. SQLITE_PRIVATE int sqlite3PutVarint(unsigned char*, u64);
  12800. SQLITE_PRIVATE u8 sqlite3GetVarint(const unsigned char *, u64 *);
  12801. SQLITE_PRIVATE u8 sqlite3GetVarint32(const unsigned char *, u32 *);
  12802. SQLITE_PRIVATE int sqlite3VarintLen(u64 v);
  12803. /*
  12804. ** The common case is for a varint to be a single byte. They following
  12805. ** macros handle the common case without a procedure call, but then call
  12806. ** the procedure for larger varints.
  12807. */
  12808. #define getVarint32(A,B) \
  12809. (u8)((*(A)<(u8)0x80)?((B)=(u32)*(A)),1:sqlite3GetVarint32((A),(u32 *)&(B)))
  12810. #define putVarint32(A,B) \
  12811. (u8)(((u32)(B)<(u32)0x80)?(*(A)=(unsigned char)(B)),1:\
  12812. sqlite3PutVarint((A),(B)))
  12813. #define getVarint sqlite3GetVarint
  12814. #define putVarint sqlite3PutVarint
  12815. SQLITE_PRIVATE const char *sqlite3IndexAffinityStr(Vdbe *, Index *);
  12816. SQLITE_PRIVATE void sqlite3TableAffinity(Vdbe*, Table*, int);
  12817. SQLITE_PRIVATE char sqlite3CompareAffinity(Expr *pExpr, char aff2);
  12818. SQLITE_PRIVATE int sqlite3IndexAffinityOk(Expr *pExpr, char idx_affinity);
  12819. SQLITE_PRIVATE char sqlite3ExprAffinity(Expr *pExpr);
  12820. SQLITE_PRIVATE int sqlite3Atoi64(const char*, i64*, int, u8);
  12821. SQLITE_PRIVATE int sqlite3DecOrHexToI64(const char*, i64*);
  12822. SQLITE_PRIVATE void sqlite3ErrorWithMsg(sqlite3*, int, const char*,...);
  12823. SQLITE_PRIVATE void sqlite3Error(sqlite3*,int);
  12824. SQLITE_PRIVATE void *sqlite3HexToBlob(sqlite3*, const char *z, int n);
  12825. SQLITE_PRIVATE u8 sqlite3HexToInt(int h);
  12826. SQLITE_PRIVATE int sqlite3TwoPartName(Parse *, Token *, Token *, Token **);
  12827. #if defined(SQLITE_NEED_ERR_NAME)
  12828. SQLITE_PRIVATE const char *sqlite3ErrName(int);
  12829. #endif
  12830. SQLITE_PRIVATE const char *sqlite3ErrStr(int);
  12831. SQLITE_PRIVATE int sqlite3ReadSchema(Parse *pParse);
  12832. SQLITE_PRIVATE CollSeq *sqlite3FindCollSeq(sqlite3*,u8 enc, const char*,int);
  12833. SQLITE_PRIVATE CollSeq *sqlite3LocateCollSeq(Parse *pParse, const char*zName);
  12834. SQLITE_PRIVATE CollSeq *sqlite3ExprCollSeq(Parse *pParse, Expr *pExpr);
  12835. SQLITE_PRIVATE Expr *sqlite3ExprAddCollateToken(Parse *pParse, Expr*, const Token*, int);
  12836. SQLITE_PRIVATE Expr *sqlite3ExprAddCollateString(Parse*,Expr*,const char*);
  12837. SQLITE_PRIVATE Expr *sqlite3ExprSkipCollate(Expr*);
  12838. SQLITE_PRIVATE int sqlite3CheckCollSeq(Parse *, CollSeq *);
  12839. SQLITE_PRIVATE int sqlite3CheckObjectName(Parse *, const char *);
  12840. SQLITE_PRIVATE void sqlite3VdbeSetChanges(sqlite3 *, int);
  12841. SQLITE_PRIVATE int sqlite3AddInt64(i64*,i64);
  12842. SQLITE_PRIVATE int sqlite3SubInt64(i64*,i64);
  12843. SQLITE_PRIVATE int sqlite3MulInt64(i64*,i64);
  12844. SQLITE_PRIVATE int sqlite3AbsInt32(int);
  12845. #ifdef SQLITE_ENABLE_8_3_NAMES
  12846. SQLITE_PRIVATE void sqlite3FileSuffix3(const char*, char*);
  12847. #else
  12848. # define sqlite3FileSuffix3(X,Y)
  12849. #endif
  12850. SQLITE_PRIVATE u8 sqlite3GetBoolean(const char *z,u8);
  12851. SQLITE_PRIVATE const void *sqlite3ValueText(sqlite3_value*, u8);
  12852. SQLITE_PRIVATE int sqlite3ValueBytes(sqlite3_value*, u8);
  12853. SQLITE_PRIVATE void sqlite3ValueSetStr(sqlite3_value*, int, const void *,u8,
  12854. void(*)(void*));
  12855. SQLITE_PRIVATE void sqlite3ValueSetNull(sqlite3_value*);
  12856. SQLITE_PRIVATE void sqlite3ValueFree(sqlite3_value*);
  12857. SQLITE_PRIVATE sqlite3_value *sqlite3ValueNew(sqlite3 *);
  12858. SQLITE_PRIVATE char *sqlite3Utf16to8(sqlite3 *, const void*, int, u8);
  12859. SQLITE_PRIVATE int sqlite3ValueFromExpr(sqlite3 *, Expr *, u8, u8, sqlite3_value **);
  12860. SQLITE_PRIVATE void sqlite3ValueApplyAffinity(sqlite3_value *, u8, u8);
  12861. #ifndef SQLITE_AMALGAMATION
  12862. SQLITE_PRIVATE const unsigned char sqlite3OpcodeProperty[];
  12863. SQLITE_PRIVATE const unsigned char sqlite3UpperToLower[];
  12864. SQLITE_PRIVATE const unsigned char sqlite3CtypeMap[];
  12865. SQLITE_PRIVATE const Token sqlite3IntTokens[];
  12866. SQLITE_PRIVATE SQLITE_WSD struct Sqlite3Config sqlite3Config;
  12867. SQLITE_PRIVATE SQLITE_WSD FuncDefHash sqlite3GlobalFunctions;
  12868. #ifndef SQLITE_OMIT_WSD
  12869. SQLITE_PRIVATE int sqlite3PendingByte;
  12870. #endif
  12871. #endif
  12872. SQLITE_PRIVATE void sqlite3RootPageMoved(sqlite3*, int, int, int);
  12873. SQLITE_PRIVATE void sqlite3Reindex(Parse*, Token*, Token*);
  12874. SQLITE_PRIVATE void sqlite3AlterFunctions(void);
  12875. SQLITE_PRIVATE void sqlite3AlterRenameTable(Parse*, SrcList*, Token*);
  12876. SQLITE_PRIVATE int sqlite3GetToken(const unsigned char *, int *);
  12877. SQLITE_PRIVATE void sqlite3NestedParse(Parse*, const char*, ...);
  12878. SQLITE_PRIVATE void sqlite3ExpirePreparedStatements(sqlite3*);
  12879. SQLITE_PRIVATE int sqlite3CodeSubselect(Parse *, Expr *, int, int);
  12880. SQLITE_PRIVATE void sqlite3SelectPrep(Parse*, Select*, NameContext*);
  12881. SQLITE_PRIVATE int sqlite3MatchSpanName(const char*, const char*, const char*, const char*);
  12882. SQLITE_PRIVATE int sqlite3ResolveExprNames(NameContext*, Expr*);
  12883. SQLITE_PRIVATE void sqlite3ResolveSelectNames(Parse*, Select*, NameContext*);
  12884. SQLITE_PRIVATE void sqlite3ResolveSelfReference(Parse*,Table*,int,Expr*,ExprList*);
  12885. SQLITE_PRIVATE int sqlite3ResolveOrderGroupBy(Parse*, Select*, ExprList*, const char*);
  12886. SQLITE_PRIVATE void sqlite3ColumnDefault(Vdbe *, Table *, int, int);
  12887. SQLITE_PRIVATE void sqlite3AlterFinishAddColumn(Parse *, Token *);
  12888. SQLITE_PRIVATE void sqlite3AlterBeginAddColumn(Parse *, SrcList *);
  12889. SQLITE_PRIVATE CollSeq *sqlite3GetCollSeq(Parse*, u8, CollSeq *, const char*);
  12890. SQLITE_PRIVATE char sqlite3AffinityType(const char*, u8*);
  12891. SQLITE_PRIVATE void sqlite3Analyze(Parse*, Token*, Token*);
  12892. SQLITE_PRIVATE int sqlite3InvokeBusyHandler(BusyHandler*);
  12893. SQLITE_PRIVATE int sqlite3FindDb(sqlite3*, Token*);
  12894. SQLITE_PRIVATE int sqlite3FindDbName(sqlite3 *, const char *);
  12895. SQLITE_PRIVATE int sqlite3AnalysisLoad(sqlite3*,int iDB);
  12896. SQLITE_PRIVATE void sqlite3DeleteIndexSamples(sqlite3*,Index*);
  12897. SQLITE_PRIVATE void sqlite3DefaultRowEst(Index*);
  12898. SQLITE_PRIVATE void sqlite3RegisterLikeFunctions(sqlite3*, int);
  12899. SQLITE_PRIVATE int sqlite3IsLikeFunction(sqlite3*,Expr*,int*,char*);
  12900. SQLITE_PRIVATE void sqlite3MinimumFileFormat(Parse*, int, int);
  12901. SQLITE_PRIVATE void sqlite3SchemaClear(void *);
  12902. SQLITE_PRIVATE Schema *sqlite3SchemaGet(sqlite3 *, Btree *);
  12903. SQLITE_PRIVATE int sqlite3SchemaToIndex(sqlite3 *db, Schema *);
  12904. SQLITE_PRIVATE KeyInfo *sqlite3KeyInfoAlloc(sqlite3*,int,int);
  12905. SQLITE_PRIVATE void sqlite3KeyInfoUnref(KeyInfo*);
  12906. SQLITE_PRIVATE KeyInfo *sqlite3KeyInfoRef(KeyInfo*);
  12907. SQLITE_PRIVATE KeyInfo *sqlite3KeyInfoOfIndex(Parse*, Index*);
  12908. #ifdef SQLITE_DEBUG
  12909. SQLITE_PRIVATE int sqlite3KeyInfoIsWriteable(KeyInfo*);
  12910. #endif
  12911. SQLITE_PRIVATE int sqlite3CreateFunc(sqlite3 *, const char *, int, int, void *,
  12912. void (*)(sqlite3_context*,int,sqlite3_value **),
  12913. void (*)(sqlite3_context*,int,sqlite3_value **), void (*)(sqlite3_context*),
  12914. FuncDestructor *pDestructor
  12915. );
  12916. SQLITE_PRIVATE int sqlite3ApiExit(sqlite3 *db, int);
  12917. SQLITE_PRIVATE int sqlite3OpenTempDatabase(Parse *);
  12918. SQLITE_PRIVATE void sqlite3StrAccumInit(StrAccum*, sqlite3*, char*, int, int);
  12919. SQLITE_PRIVATE void sqlite3StrAccumAppend(StrAccum*,const char*,int);
  12920. SQLITE_PRIVATE void sqlite3StrAccumAppendAll(StrAccum*,const char*);
  12921. SQLITE_PRIVATE void sqlite3AppendChar(StrAccum*,int,char);
  12922. SQLITE_PRIVATE char *sqlite3StrAccumFinish(StrAccum*);
  12923. SQLITE_PRIVATE void sqlite3StrAccumReset(StrAccum*);
  12924. SQLITE_PRIVATE void sqlite3SelectDestInit(SelectDest*,int,int);
  12925. SQLITE_PRIVATE Expr *sqlite3CreateColumnExpr(sqlite3 *, SrcList *, int, int);
  12926. SQLITE_PRIVATE void sqlite3BackupRestart(sqlite3_backup *);
  12927. SQLITE_PRIVATE void sqlite3BackupUpdate(sqlite3_backup *, Pgno, const u8 *);
  12928. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  12929. SQLITE_PRIVATE void sqlite3AnalyzeFunctions(void);
  12930. SQLITE_PRIVATE int sqlite3Stat4ProbeSetValue(Parse*,Index*,UnpackedRecord**,Expr*,u8,int,int*);
  12931. SQLITE_PRIVATE int sqlite3Stat4ValueFromExpr(Parse*, Expr*, u8, sqlite3_value**);
  12932. SQLITE_PRIVATE void sqlite3Stat4ProbeFree(UnpackedRecord*);
  12933. SQLITE_PRIVATE int sqlite3Stat4Column(sqlite3*, const void*, int, int, sqlite3_value**);
  12934. #endif
  12935. /*
  12936. ** The interface to the LEMON-generated parser
  12937. */
  12938. SQLITE_PRIVATE void *sqlite3ParserAlloc(void*(*)(u64));
  12939. SQLITE_PRIVATE void sqlite3ParserFree(void*, void(*)(void*));
  12940. SQLITE_PRIVATE void sqlite3Parser(void*, int, Token, Parse*);
  12941. #ifdef YYTRACKMAXSTACKDEPTH
  12942. SQLITE_PRIVATE int sqlite3ParserStackPeak(void*);
  12943. #endif
  12944. SQLITE_PRIVATE void sqlite3AutoLoadExtensions(sqlite3*);
  12945. #ifndef SQLITE_OMIT_LOAD_EXTENSION
  12946. SQLITE_PRIVATE void sqlite3CloseExtensions(sqlite3*);
  12947. #else
  12948. # define sqlite3CloseExtensions(X)
  12949. #endif
  12950. #ifndef SQLITE_OMIT_SHARED_CACHE
  12951. SQLITE_PRIVATE void sqlite3TableLock(Parse *, int, int, u8, const char *);
  12952. #else
  12953. #define sqlite3TableLock(v,w,x,y,z)
  12954. #endif
  12955. #ifdef SQLITE_TEST
  12956. SQLITE_PRIVATE int sqlite3Utf8To8(unsigned char*);
  12957. #endif
  12958. #ifdef SQLITE_OMIT_VIRTUALTABLE
  12959. # define sqlite3VtabClear(Y)
  12960. # define sqlite3VtabSync(X,Y) SQLITE_OK
  12961. # define sqlite3VtabRollback(X)
  12962. # define sqlite3VtabCommit(X)
  12963. # define sqlite3VtabInSync(db) 0
  12964. # define sqlite3VtabLock(X)
  12965. # define sqlite3VtabUnlock(X)
  12966. # define sqlite3VtabUnlockList(X)
  12967. # define sqlite3VtabSavepoint(X, Y, Z) SQLITE_OK
  12968. # define sqlite3GetVTable(X,Y) ((VTable*)0)
  12969. #else
  12970. SQLITE_PRIVATE void sqlite3VtabClear(sqlite3 *db, Table*);
  12971. SQLITE_PRIVATE void sqlite3VtabDisconnect(sqlite3 *db, Table *p);
  12972. SQLITE_PRIVATE int sqlite3VtabSync(sqlite3 *db, Vdbe*);
  12973. SQLITE_PRIVATE int sqlite3VtabRollback(sqlite3 *db);
  12974. SQLITE_PRIVATE int sqlite3VtabCommit(sqlite3 *db);
  12975. SQLITE_PRIVATE void sqlite3VtabLock(VTable *);
  12976. SQLITE_PRIVATE void sqlite3VtabUnlock(VTable *);
  12977. SQLITE_PRIVATE void sqlite3VtabUnlockList(sqlite3*);
  12978. SQLITE_PRIVATE int sqlite3VtabSavepoint(sqlite3 *, int, int);
  12979. SQLITE_PRIVATE void sqlite3VtabImportErrmsg(Vdbe*, sqlite3_vtab*);
  12980. SQLITE_PRIVATE VTable *sqlite3GetVTable(sqlite3*, Table*);
  12981. # define sqlite3VtabInSync(db) ((db)->nVTrans>0 && (db)->aVTrans==0)
  12982. #endif
  12983. SQLITE_PRIVATE void sqlite3VtabMakeWritable(Parse*,Table*);
  12984. SQLITE_PRIVATE void sqlite3VtabBeginParse(Parse*, Token*, Token*, Token*, int);
  12985. SQLITE_PRIVATE void sqlite3VtabFinishParse(Parse*, Token*);
  12986. SQLITE_PRIVATE void sqlite3VtabArgInit(Parse*);
  12987. SQLITE_PRIVATE void sqlite3VtabArgExtend(Parse*, Token*);
  12988. SQLITE_PRIVATE int sqlite3VtabCallCreate(sqlite3*, int, const char *, char **);
  12989. SQLITE_PRIVATE int sqlite3VtabCallConnect(Parse*, Table*);
  12990. SQLITE_PRIVATE int sqlite3VtabCallDestroy(sqlite3*, int, const char *);
  12991. SQLITE_PRIVATE int sqlite3VtabBegin(sqlite3 *, VTable *);
  12992. SQLITE_PRIVATE FuncDef *sqlite3VtabOverloadFunction(sqlite3 *,FuncDef*, int nArg, Expr*);
  12993. SQLITE_PRIVATE void sqlite3InvalidFunction(sqlite3_context*,int,sqlite3_value**);
  12994. SQLITE_PRIVATE sqlite3_int64 sqlite3StmtCurrentTime(sqlite3_context*);
  12995. SQLITE_PRIVATE int sqlite3VdbeParameterIndex(Vdbe*, const char*, int);
  12996. SQLITE_PRIVATE int sqlite3TransferBindings(sqlite3_stmt *, sqlite3_stmt *);
  12997. SQLITE_PRIVATE void sqlite3ParserReset(Parse*);
  12998. SQLITE_PRIVATE int sqlite3Reprepare(Vdbe*);
  12999. SQLITE_PRIVATE void sqlite3ExprListCheckLength(Parse*, ExprList*, const char*);
  13000. SQLITE_PRIVATE CollSeq *sqlite3BinaryCompareCollSeq(Parse *, Expr *, Expr *);
  13001. SQLITE_PRIVATE int sqlite3TempInMemory(const sqlite3*);
  13002. SQLITE_PRIVATE const char *sqlite3JournalModename(int);
  13003. #ifndef SQLITE_OMIT_WAL
  13004. SQLITE_PRIVATE int sqlite3Checkpoint(sqlite3*, int, int, int*, int*);
  13005. SQLITE_PRIVATE int sqlite3WalDefaultHook(void*,sqlite3*,const char*,int);
  13006. #endif
  13007. #ifndef SQLITE_OMIT_CTE
  13008. SQLITE_PRIVATE With *sqlite3WithAdd(Parse*,With*,Token*,ExprList*,Select*);
  13009. SQLITE_PRIVATE void sqlite3WithDelete(sqlite3*,With*);
  13010. SQLITE_PRIVATE void sqlite3WithPush(Parse*, With*, u8);
  13011. #else
  13012. #define sqlite3WithPush(x,y,z)
  13013. #define sqlite3WithDelete(x,y)
  13014. #endif
  13015. /* Declarations for functions in fkey.c. All of these are replaced by
  13016. ** no-op macros if OMIT_FOREIGN_KEY is defined. In this case no foreign
  13017. ** key functionality is available. If OMIT_TRIGGER is defined but
  13018. ** OMIT_FOREIGN_KEY is not, only some of the functions are no-oped. In
  13019. ** this case foreign keys are parsed, but no other functionality is
  13020. ** provided (enforcement of FK constraints requires the triggers sub-system).
  13021. */
  13022. #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
  13023. SQLITE_PRIVATE void sqlite3FkCheck(Parse*, Table*, int, int, int*, int);
  13024. SQLITE_PRIVATE void sqlite3FkDropTable(Parse*, SrcList *, Table*);
  13025. SQLITE_PRIVATE void sqlite3FkActions(Parse*, Table*, ExprList*, int, int*, int);
  13026. SQLITE_PRIVATE int sqlite3FkRequired(Parse*, Table*, int*, int);
  13027. SQLITE_PRIVATE u32 sqlite3FkOldmask(Parse*, Table*);
  13028. SQLITE_PRIVATE FKey *sqlite3FkReferences(Table *);
  13029. #else
  13030. #define sqlite3FkActions(a,b,c,d,e,f)
  13031. #define sqlite3FkCheck(a,b,c,d,e,f)
  13032. #define sqlite3FkDropTable(a,b,c)
  13033. #define sqlite3FkOldmask(a,b) 0
  13034. #define sqlite3FkRequired(a,b,c,d) 0
  13035. #endif
  13036. #ifndef SQLITE_OMIT_FOREIGN_KEY
  13037. SQLITE_PRIVATE void sqlite3FkDelete(sqlite3 *, Table*);
  13038. SQLITE_PRIVATE int sqlite3FkLocateIndex(Parse*,Table*,FKey*,Index**,int**);
  13039. #else
  13040. #define sqlite3FkDelete(a,b)
  13041. #define sqlite3FkLocateIndex(a,b,c,d,e)
  13042. #endif
  13043. /*
  13044. ** Available fault injectors. Should be numbered beginning with 0.
  13045. */
  13046. #define SQLITE_FAULTINJECTOR_MALLOC 0
  13047. #define SQLITE_FAULTINJECTOR_COUNT 1
  13048. /*
  13049. ** The interface to the code in fault.c used for identifying "benign"
  13050. ** malloc failures. This is only present if SQLITE_OMIT_BUILTIN_TEST
  13051. ** is not defined.
  13052. */
  13053. #ifndef SQLITE_OMIT_BUILTIN_TEST
  13054. SQLITE_PRIVATE void sqlite3BeginBenignMalloc(void);
  13055. SQLITE_PRIVATE void sqlite3EndBenignMalloc(void);
  13056. #else
  13057. #define sqlite3BeginBenignMalloc()
  13058. #define sqlite3EndBenignMalloc()
  13059. #endif
  13060. /*
  13061. ** Allowed return values from sqlite3FindInIndex()
  13062. */
  13063. #define IN_INDEX_ROWID 1 /* Search the rowid of the table */
  13064. #define IN_INDEX_EPH 2 /* Search an ephemeral b-tree */
  13065. #define IN_INDEX_INDEX_ASC 3 /* Existing index ASCENDING */
  13066. #define IN_INDEX_INDEX_DESC 4 /* Existing index DESCENDING */
  13067. #define IN_INDEX_NOOP 5 /* No table available. Use comparisons */
  13068. /*
  13069. ** Allowed flags for the 3rd parameter to sqlite3FindInIndex().
  13070. */
  13071. #define IN_INDEX_NOOP_OK 0x0001 /* OK to return IN_INDEX_NOOP */
  13072. #define IN_INDEX_MEMBERSHIP 0x0002 /* IN operator used for membership test */
  13073. #define IN_INDEX_LOOP 0x0004 /* IN operator used as a loop */
  13074. SQLITE_PRIVATE int sqlite3FindInIndex(Parse *, Expr *, u32, int*);
  13075. #ifdef SQLITE_ENABLE_ATOMIC_WRITE
  13076. SQLITE_PRIVATE int sqlite3JournalOpen(sqlite3_vfs *, const char *, sqlite3_file *, int, int);
  13077. SQLITE_PRIVATE int sqlite3JournalSize(sqlite3_vfs *);
  13078. SQLITE_PRIVATE int sqlite3JournalCreate(sqlite3_file *);
  13079. SQLITE_PRIVATE int sqlite3JournalExists(sqlite3_file *p);
  13080. #else
  13081. #define sqlite3JournalSize(pVfs) ((pVfs)->szOsFile)
  13082. #define sqlite3JournalExists(p) 1
  13083. #endif
  13084. SQLITE_PRIVATE void sqlite3MemJournalOpen(sqlite3_file *);
  13085. SQLITE_PRIVATE int sqlite3MemJournalSize(void);
  13086. SQLITE_PRIVATE int sqlite3IsMemJournal(sqlite3_file *);
  13087. SQLITE_PRIVATE void sqlite3ExprSetHeightAndFlags(Parse *pParse, Expr *p);
  13088. #if SQLITE_MAX_EXPR_DEPTH>0
  13089. SQLITE_PRIVATE int sqlite3SelectExprHeight(Select *);
  13090. SQLITE_PRIVATE int sqlite3ExprCheckHeight(Parse*, int);
  13091. #else
  13092. #define sqlite3SelectExprHeight(x) 0
  13093. #define sqlite3ExprCheckHeight(x,y)
  13094. #endif
  13095. SQLITE_PRIVATE u32 sqlite3Get4byte(const u8*);
  13096. SQLITE_PRIVATE void sqlite3Put4byte(u8*, u32);
  13097. #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
  13098. SQLITE_PRIVATE void sqlite3ConnectionBlocked(sqlite3 *, sqlite3 *);
  13099. SQLITE_PRIVATE void sqlite3ConnectionUnlocked(sqlite3 *db);
  13100. SQLITE_PRIVATE void sqlite3ConnectionClosed(sqlite3 *db);
  13101. #else
  13102. #define sqlite3ConnectionBlocked(x,y)
  13103. #define sqlite3ConnectionUnlocked(x)
  13104. #define sqlite3ConnectionClosed(x)
  13105. #endif
  13106. #ifdef SQLITE_DEBUG
  13107. SQLITE_PRIVATE void sqlite3ParserTrace(FILE*, char *);
  13108. #endif
  13109. /*
  13110. ** If the SQLITE_ENABLE IOTRACE exists then the global variable
  13111. ** sqlite3IoTrace is a pointer to a printf-like routine used to
  13112. ** print I/O tracing messages.
  13113. */
  13114. #ifdef SQLITE_ENABLE_IOTRACE
  13115. # define IOTRACE(A) if( sqlite3IoTrace ){ sqlite3IoTrace A; }
  13116. SQLITE_PRIVATE void sqlite3VdbeIOTraceSql(Vdbe*);
  13117. SQLITE_API SQLITE_EXTERN void (SQLITE_CDECL *sqlite3IoTrace)(const char*,...);
  13118. #else
  13119. # define IOTRACE(A)
  13120. # define sqlite3VdbeIOTraceSql(X)
  13121. #endif
  13122. /*
  13123. ** These routines are available for the mem2.c debugging memory allocator
  13124. ** only. They are used to verify that different "types" of memory
  13125. ** allocations are properly tracked by the system.
  13126. **
  13127. ** sqlite3MemdebugSetType() sets the "type" of an allocation to one of
  13128. ** the MEMTYPE_* macros defined below. The type must be a bitmask with
  13129. ** a single bit set.
  13130. **
  13131. ** sqlite3MemdebugHasType() returns true if any of the bits in its second
  13132. ** argument match the type set by the previous sqlite3MemdebugSetType().
  13133. ** sqlite3MemdebugHasType() is intended for use inside assert() statements.
  13134. **
  13135. ** sqlite3MemdebugNoType() returns true if none of the bits in its second
  13136. ** argument match the type set by the previous sqlite3MemdebugSetType().
  13137. **
  13138. ** Perhaps the most important point is the difference between MEMTYPE_HEAP
  13139. ** and MEMTYPE_LOOKASIDE. If an allocation is MEMTYPE_LOOKASIDE, that means
  13140. ** it might have been allocated by lookaside, except the allocation was
  13141. ** too large or lookaside was already full. It is important to verify
  13142. ** that allocations that might have been satisfied by lookaside are not
  13143. ** passed back to non-lookaside free() routines. Asserts such as the
  13144. ** example above are placed on the non-lookaside free() routines to verify
  13145. ** this constraint.
  13146. **
  13147. ** All of this is no-op for a production build. It only comes into
  13148. ** play when the SQLITE_MEMDEBUG compile-time option is used.
  13149. */
  13150. #ifdef SQLITE_MEMDEBUG
  13151. SQLITE_PRIVATE void sqlite3MemdebugSetType(void*,u8);
  13152. SQLITE_PRIVATE int sqlite3MemdebugHasType(void*,u8);
  13153. SQLITE_PRIVATE int sqlite3MemdebugNoType(void*,u8);
  13154. #else
  13155. # define sqlite3MemdebugSetType(X,Y) /* no-op */
  13156. # define sqlite3MemdebugHasType(X,Y) 1
  13157. # define sqlite3MemdebugNoType(X,Y) 1
  13158. #endif
  13159. #define MEMTYPE_HEAP 0x01 /* General heap allocations */
  13160. #define MEMTYPE_LOOKASIDE 0x02 /* Heap that might have been lookaside */
  13161. #define MEMTYPE_SCRATCH 0x04 /* Scratch allocations */
  13162. #define MEMTYPE_PCACHE 0x08 /* Page cache allocations */
  13163. /*
  13164. ** Threading interface
  13165. */
  13166. #if SQLITE_MAX_WORKER_THREADS>0
  13167. SQLITE_PRIVATE int sqlite3ThreadCreate(SQLiteThread**,void*(*)(void*),void*);
  13168. SQLITE_PRIVATE int sqlite3ThreadJoin(SQLiteThread*, void**);
  13169. #endif
  13170. #endif /* _SQLITEINT_H_ */
  13171. /************** End of sqliteInt.h *******************************************/
  13172. /************** Begin file global.c ******************************************/
  13173. /*
  13174. ** 2008 June 13
  13175. **
  13176. ** The author disclaims copyright to this source code. In place of
  13177. ** a legal notice, here is a blessing:
  13178. **
  13179. ** May you do good and not evil.
  13180. ** May you find forgiveness for yourself and forgive others.
  13181. ** May you share freely, never taking more than you give.
  13182. **
  13183. *************************************************************************
  13184. **
  13185. ** This file contains definitions of global variables and constants.
  13186. */
  13187. /* An array to map all upper-case characters into their corresponding
  13188. ** lower-case character.
  13189. **
  13190. ** SQLite only considers US-ASCII (or EBCDIC) characters. We do not
  13191. ** handle case conversions for the UTF character set since the tables
  13192. ** involved are nearly as big or bigger than SQLite itself.
  13193. */
  13194. SQLITE_PRIVATE const unsigned char sqlite3UpperToLower[] = {
  13195. #ifdef SQLITE_ASCII
  13196. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17,
  13197. 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35,
  13198. 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53,
  13199. 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 97, 98, 99,100,101,102,103,
  13200. 104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119,120,121,
  13201. 122, 91, 92, 93, 94, 95, 96, 97, 98, 99,100,101,102,103,104,105,106,107,
  13202. 108,109,110,111,112,113,114,115,116,117,118,119,120,121,122,123,124,125,
  13203. 126,127,128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,
  13204. 144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,160,161,
  13205. 162,163,164,165,166,167,168,169,170,171,172,173,174,175,176,177,178,179,
  13206. 180,181,182,183,184,185,186,187,188,189,190,191,192,193,194,195,196,197,
  13207. 198,199,200,201,202,203,204,205,206,207,208,209,210,211,212,213,214,215,
  13208. 216,217,218,219,220,221,222,223,224,225,226,227,228,229,230,231,232,233,
  13209. 234,235,236,237,238,239,240,241,242,243,244,245,246,247,248,249,250,251,
  13210. 252,253,254,255
  13211. #endif
  13212. #ifdef SQLITE_EBCDIC
  13213. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, /* 0x */
  13214. 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, /* 1x */
  13215. 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, /* 2x */
  13216. 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, /* 3x */
  13217. 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, /* 4x */
  13218. 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, /* 5x */
  13219. 96, 97, 98, 99,100,101,102,103,104,105,106,107,108,109,110,111, /* 6x */
  13220. 112,113,114,115,116,117,118,119,120,121,122,123,124,125,126,127, /* 7x */
  13221. 128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143, /* 8x */
  13222. 144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159, /* 9x */
  13223. 160,161,162,163,164,165,166,167,168,169,170,171,140,141,142,175, /* Ax */
  13224. 176,177,178,179,180,181,182,183,184,185,186,187,188,189,190,191, /* Bx */
  13225. 192,129,130,131,132,133,134,135,136,137,202,203,204,205,206,207, /* Cx */
  13226. 208,145,146,147,148,149,150,151,152,153,218,219,220,221,222,223, /* Dx */
  13227. 224,225,162,163,164,165,166,167,168,169,234,235,236,237,238,239, /* Ex */
  13228. 240,241,242,243,244,245,246,247,248,249,250,251,252,253,254,255, /* Fx */
  13229. #endif
  13230. };
  13231. /*
  13232. ** The following 256 byte lookup table is used to support SQLites built-in
  13233. ** equivalents to the following standard library functions:
  13234. **
  13235. ** isspace() 0x01
  13236. ** isalpha() 0x02
  13237. ** isdigit() 0x04
  13238. ** isalnum() 0x06
  13239. ** isxdigit() 0x08
  13240. ** toupper() 0x20
  13241. ** SQLite identifier character 0x40
  13242. **
  13243. ** Bit 0x20 is set if the mapped character requires translation to upper
  13244. ** case. i.e. if the character is a lower-case ASCII character.
  13245. ** If x is a lower-case ASCII character, then its upper-case equivalent
  13246. ** is (x - 0x20). Therefore toupper() can be implemented as:
  13247. **
  13248. ** (x & ~(map[x]&0x20))
  13249. **
  13250. ** Standard function tolower() is implemented using the sqlite3UpperToLower[]
  13251. ** array. tolower() is used more often than toupper() by SQLite.
  13252. **
  13253. ** Bit 0x40 is set if the character non-alphanumeric and can be used in an
  13254. ** SQLite identifier. Identifiers are alphanumerics, "_", "$", and any
  13255. ** non-ASCII UTF character. Hence the test for whether or not a character is
  13256. ** part of an identifier is 0x46.
  13257. **
  13258. ** SQLite's versions are identical to the standard versions assuming a
  13259. ** locale of "C". They are implemented as macros in sqliteInt.h.
  13260. */
  13261. #ifdef SQLITE_ASCII
  13262. SQLITE_PRIVATE const unsigned char sqlite3CtypeMap[256] = {
  13263. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 00..07 ........ */
  13264. 0x00, 0x01, 0x01, 0x01, 0x01, 0x01, 0x00, 0x00, /* 08..0f ........ */
  13265. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 10..17 ........ */
  13266. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 18..1f ........ */
  13267. 0x01, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00, /* 20..27 !"#$%&' */
  13268. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 28..2f ()*+,-./ */
  13269. 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, /* 30..37 01234567 */
  13270. 0x0c, 0x0c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 38..3f 89:;<=>? */
  13271. 0x00, 0x0a, 0x0a, 0x0a, 0x0a, 0x0a, 0x0a, 0x02, /* 40..47 @ABCDEFG */
  13272. 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, /* 48..4f HIJKLMNO */
  13273. 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, /* 50..57 PQRSTUVW */
  13274. 0x02, 0x02, 0x02, 0x00, 0x00, 0x00, 0x00, 0x40, /* 58..5f XYZ[\]^_ */
  13275. 0x00, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x22, /* 60..67 `abcdefg */
  13276. 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, /* 68..6f hijklmno */
  13277. 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, /* 70..77 pqrstuvw */
  13278. 0x22, 0x22, 0x22, 0x00, 0x00, 0x00, 0x00, 0x00, /* 78..7f xyz{|}~. */
  13279. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* 80..87 ........ */
  13280. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* 88..8f ........ */
  13281. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* 90..97 ........ */
  13282. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* 98..9f ........ */
  13283. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* a0..a7 ........ */
  13284. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* a8..af ........ */
  13285. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* b0..b7 ........ */
  13286. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* b8..bf ........ */
  13287. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* c0..c7 ........ */
  13288. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* c8..cf ........ */
  13289. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* d0..d7 ........ */
  13290. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* d8..df ........ */
  13291. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* e0..e7 ........ */
  13292. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* e8..ef ........ */
  13293. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* f0..f7 ........ */
  13294. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40 /* f8..ff ........ */
  13295. };
  13296. #endif
  13297. /* EVIDENCE-OF: R-02982-34736 In order to maintain full backwards
  13298. ** compatibility for legacy applications, the URI filename capability is
  13299. ** disabled by default.
  13300. **
  13301. ** EVIDENCE-OF: R-38799-08373 URI filenames can be enabled or disabled
  13302. ** using the SQLITE_USE_URI=1 or SQLITE_USE_URI=0 compile-time options.
  13303. **
  13304. ** EVIDENCE-OF: R-43642-56306 By default, URI handling is globally
  13305. ** disabled. The default value may be changed by compiling with the
  13306. ** SQLITE_USE_URI symbol defined.
  13307. */
  13308. #ifndef SQLITE_USE_URI
  13309. # define SQLITE_USE_URI 0
  13310. #endif
  13311. /* EVIDENCE-OF: R-38720-18127 The default setting is determined by the
  13312. ** SQLITE_ALLOW_COVERING_INDEX_SCAN compile-time option, or is "on" if
  13313. ** that compile-time option is omitted.
  13314. */
  13315. #ifndef SQLITE_ALLOW_COVERING_INDEX_SCAN
  13316. # define SQLITE_ALLOW_COVERING_INDEX_SCAN 1
  13317. #endif
  13318. /* The minimum PMA size is set to this value multiplied by the database
  13319. ** page size in bytes.
  13320. */
  13321. #ifndef SQLITE_SORTER_PMASZ
  13322. # define SQLITE_SORTER_PMASZ 250
  13323. #endif
  13324. /*
  13325. ** The following singleton contains the global configuration for
  13326. ** the SQLite library.
  13327. */
  13328. SQLITE_PRIVATE SQLITE_WSD struct Sqlite3Config sqlite3Config = {
  13329. SQLITE_DEFAULT_MEMSTATUS, /* bMemstat */
  13330. 1, /* bCoreMutex */
  13331. SQLITE_THREADSAFE==1, /* bFullMutex */
  13332. SQLITE_USE_URI, /* bOpenUri */
  13333. SQLITE_ALLOW_COVERING_INDEX_SCAN, /* bUseCis */
  13334. 0x7ffffffe, /* mxStrlen */
  13335. 0, /* neverCorrupt */
  13336. 128, /* szLookaside */
  13337. 500, /* nLookaside */
  13338. {0,0,0,0,0,0,0,0}, /* m */
  13339. {0,0,0,0,0,0,0,0,0}, /* mutex */
  13340. {0,0,0,0,0,0,0,0,0,0,0,0,0},/* pcache2 */
  13341. (void*)0, /* pHeap */
  13342. 0, /* nHeap */
  13343. 0, 0, /* mnHeap, mxHeap */
  13344. SQLITE_DEFAULT_MMAP_SIZE, /* szMmap */
  13345. SQLITE_MAX_MMAP_SIZE, /* mxMmap */
  13346. (void*)0, /* pScratch */
  13347. 0, /* szScratch */
  13348. 0, /* nScratch */
  13349. (void*)0, /* pPage */
  13350. 0, /* szPage */
  13351. 0, /* nPage */
  13352. 0, /* mxParserStack */
  13353. 0, /* sharedCacheEnabled */
  13354. SQLITE_SORTER_PMASZ, /* szPma */
  13355. /* All the rest should always be initialized to zero */
  13356. 0, /* isInit */
  13357. 0, /* inProgress */
  13358. 0, /* isMutexInit */
  13359. 0, /* isMallocInit */
  13360. 0, /* isPCacheInit */
  13361. 0, /* nRefInitMutex */
  13362. 0, /* pInitMutex */
  13363. 0, /* xLog */
  13364. 0, /* pLogArg */
  13365. #ifdef SQLITE_ENABLE_SQLLOG
  13366. 0, /* xSqllog */
  13367. 0, /* pSqllogArg */
  13368. #endif
  13369. #ifdef SQLITE_VDBE_COVERAGE
  13370. 0, /* xVdbeBranch */
  13371. 0, /* pVbeBranchArg */
  13372. #endif
  13373. #ifndef SQLITE_OMIT_BUILTIN_TEST
  13374. 0, /* xTestCallback */
  13375. #endif
  13376. 0 /* bLocaltimeFault */
  13377. };
  13378. /*
  13379. ** Hash table for global functions - functions common to all
  13380. ** database connections. After initialization, this table is
  13381. ** read-only.
  13382. */
  13383. SQLITE_PRIVATE SQLITE_WSD FuncDefHash sqlite3GlobalFunctions;
  13384. /*
  13385. ** Constant tokens for values 0 and 1.
  13386. */
  13387. SQLITE_PRIVATE const Token sqlite3IntTokens[] = {
  13388. { "0", 1 },
  13389. { "1", 1 }
  13390. };
  13391. /*
  13392. ** The value of the "pending" byte must be 0x40000000 (1 byte past the
  13393. ** 1-gibabyte boundary) in a compatible database. SQLite never uses
  13394. ** the database page that contains the pending byte. It never attempts
  13395. ** to read or write that page. The pending byte page is set assign
  13396. ** for use by the VFS layers as space for managing file locks.
  13397. **
  13398. ** During testing, it is often desirable to move the pending byte to
  13399. ** a different position in the file. This allows code that has to
  13400. ** deal with the pending byte to run on files that are much smaller
  13401. ** than 1 GiB. The sqlite3_test_control() interface can be used to
  13402. ** move the pending byte.
  13403. **
  13404. ** IMPORTANT: Changing the pending byte to any value other than
  13405. ** 0x40000000 results in an incompatible database file format!
  13406. ** Changing the pending byte during operation will result in undefined
  13407. ** and incorrect behavior.
  13408. */
  13409. #ifndef SQLITE_OMIT_WSD
  13410. SQLITE_PRIVATE int sqlite3PendingByte = 0x40000000;
  13411. #endif
  13412. /*
  13413. ** Properties of opcodes. The OPFLG_INITIALIZER macro is
  13414. ** created by mkopcodeh.awk during compilation. Data is obtained
  13415. ** from the comments following the "case OP_xxxx:" statements in
  13416. ** the vdbe.c file.
  13417. */
  13418. SQLITE_PRIVATE const unsigned char sqlite3OpcodeProperty[] = OPFLG_INITIALIZER;
  13419. /************** End of global.c **********************************************/
  13420. /************** Begin file ctime.c *******************************************/
  13421. /*
  13422. ** 2010 February 23
  13423. **
  13424. ** The author disclaims copyright to this source code. In place of
  13425. ** a legal notice, here is a blessing:
  13426. **
  13427. ** May you do good and not evil.
  13428. ** May you find forgiveness for yourself and forgive others.
  13429. ** May you share freely, never taking more than you give.
  13430. **
  13431. *************************************************************************
  13432. **
  13433. ** This file implements routines used to report what compile-time options
  13434. ** SQLite was built with.
  13435. */
  13436. #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
  13437. /*
  13438. ** An array of names of all compile-time options. This array should
  13439. ** be sorted A-Z.
  13440. **
  13441. ** This array looks large, but in a typical installation actually uses
  13442. ** only a handful of compile-time options, so most times this array is usually
  13443. ** rather short and uses little memory space.
  13444. */
  13445. static const char * const azCompileOpt[] = {
  13446. /* These macros are provided to "stringify" the value of the define
  13447. ** for those options in which the value is meaningful. */
  13448. #define CTIMEOPT_VAL_(opt) #opt
  13449. #define CTIMEOPT_VAL(opt) CTIMEOPT_VAL_(opt)
  13450. #if SQLITE_32BIT_ROWID
  13451. "32BIT_ROWID",
  13452. #endif
  13453. #if SQLITE_4_BYTE_ALIGNED_MALLOC
  13454. "4_BYTE_ALIGNED_MALLOC",
  13455. #endif
  13456. #if SQLITE_CASE_SENSITIVE_LIKE
  13457. "CASE_SENSITIVE_LIKE",
  13458. #endif
  13459. #if SQLITE_CHECK_PAGES
  13460. "CHECK_PAGES",
  13461. #endif
  13462. #if SQLITE_COVERAGE_TEST
  13463. "COVERAGE_TEST",
  13464. #endif
  13465. #if SQLITE_DEBUG
  13466. "DEBUG",
  13467. #endif
  13468. #if SQLITE_DEFAULT_LOCKING_MODE
  13469. "DEFAULT_LOCKING_MODE=" CTIMEOPT_VAL(SQLITE_DEFAULT_LOCKING_MODE),
  13470. #endif
  13471. #if defined(SQLITE_DEFAULT_MMAP_SIZE) && !defined(SQLITE_DEFAULT_MMAP_SIZE_xc)
  13472. "DEFAULT_MMAP_SIZE=" CTIMEOPT_VAL(SQLITE_DEFAULT_MMAP_SIZE),
  13473. #endif
  13474. #if SQLITE_DISABLE_DIRSYNC
  13475. "DISABLE_DIRSYNC",
  13476. #endif
  13477. #if SQLITE_DISABLE_LFS
  13478. "DISABLE_LFS",
  13479. #endif
  13480. #if SQLITE_ENABLE_API_ARMOR
  13481. "ENABLE_API_ARMOR",
  13482. #endif
  13483. #if SQLITE_ENABLE_ATOMIC_WRITE
  13484. "ENABLE_ATOMIC_WRITE",
  13485. #endif
  13486. #if SQLITE_ENABLE_CEROD
  13487. "ENABLE_CEROD",
  13488. #endif
  13489. #if SQLITE_ENABLE_COLUMN_METADATA
  13490. "ENABLE_COLUMN_METADATA",
  13491. #endif
  13492. #if SQLITE_ENABLE_DBSTAT_VTAB
  13493. "ENABLE_DBSTAT_VTAB",
  13494. #endif
  13495. #if SQLITE_ENABLE_EXPENSIVE_ASSERT
  13496. "ENABLE_EXPENSIVE_ASSERT",
  13497. #endif
  13498. #if SQLITE_ENABLE_FTS1
  13499. "ENABLE_FTS1",
  13500. #endif
  13501. #if SQLITE_ENABLE_FTS2
  13502. "ENABLE_FTS2",
  13503. #endif
  13504. #if SQLITE_ENABLE_FTS3
  13505. "ENABLE_FTS3",
  13506. #endif
  13507. #if SQLITE_ENABLE_FTS3_PARENTHESIS
  13508. "ENABLE_FTS3_PARENTHESIS",
  13509. #endif
  13510. #if SQLITE_ENABLE_FTS4
  13511. "ENABLE_FTS4",
  13512. #endif
  13513. #if SQLITE_ENABLE_ICU
  13514. "ENABLE_ICU",
  13515. #endif
  13516. #if SQLITE_ENABLE_IOTRACE
  13517. "ENABLE_IOTRACE",
  13518. #endif
  13519. #if SQLITE_ENABLE_LOAD_EXTENSION
  13520. "ENABLE_LOAD_EXTENSION",
  13521. #endif
  13522. #if SQLITE_ENABLE_LOCKING_STYLE
  13523. "ENABLE_LOCKING_STYLE=" CTIMEOPT_VAL(SQLITE_ENABLE_LOCKING_STYLE),
  13524. #endif
  13525. #if SQLITE_ENABLE_MEMORY_MANAGEMENT
  13526. "ENABLE_MEMORY_MANAGEMENT",
  13527. #endif
  13528. #if SQLITE_ENABLE_MEMSYS3
  13529. "ENABLE_MEMSYS3",
  13530. #endif
  13531. #if SQLITE_ENABLE_MEMSYS5
  13532. "ENABLE_MEMSYS5",
  13533. #endif
  13534. #if SQLITE_ENABLE_OVERSIZE_CELL_CHECK
  13535. "ENABLE_OVERSIZE_CELL_CHECK",
  13536. #endif
  13537. #if SQLITE_ENABLE_RTREE
  13538. "ENABLE_RTREE",
  13539. #endif
  13540. #if defined(SQLITE_ENABLE_STAT4)
  13541. "ENABLE_STAT4",
  13542. #elif defined(SQLITE_ENABLE_STAT3)
  13543. "ENABLE_STAT3",
  13544. #endif
  13545. #if SQLITE_ENABLE_UNLOCK_NOTIFY
  13546. "ENABLE_UNLOCK_NOTIFY",
  13547. #endif
  13548. #if SQLITE_ENABLE_UPDATE_DELETE_LIMIT
  13549. "ENABLE_UPDATE_DELETE_LIMIT",
  13550. #endif
  13551. #if SQLITE_HAS_CODEC
  13552. "HAS_CODEC",
  13553. #endif
  13554. #if HAVE_ISNAN || SQLITE_HAVE_ISNAN
  13555. "HAVE_ISNAN",
  13556. #endif
  13557. #if SQLITE_HOMEGROWN_RECURSIVE_MUTEX
  13558. "HOMEGROWN_RECURSIVE_MUTEX",
  13559. #endif
  13560. #if SQLITE_IGNORE_AFP_LOCK_ERRORS
  13561. "IGNORE_AFP_LOCK_ERRORS",
  13562. #endif
  13563. #if SQLITE_IGNORE_FLOCK_LOCK_ERRORS
  13564. "IGNORE_FLOCK_LOCK_ERRORS",
  13565. #endif
  13566. #ifdef SQLITE_INT64_TYPE
  13567. "INT64_TYPE",
  13568. #endif
  13569. #if SQLITE_LOCK_TRACE
  13570. "LOCK_TRACE",
  13571. #endif
  13572. #if defined(SQLITE_MAX_MMAP_SIZE) && !defined(SQLITE_MAX_MMAP_SIZE_xc)
  13573. "MAX_MMAP_SIZE=" CTIMEOPT_VAL(SQLITE_MAX_MMAP_SIZE),
  13574. #endif
  13575. #ifdef SQLITE_MAX_SCHEMA_RETRY
  13576. "MAX_SCHEMA_RETRY=" CTIMEOPT_VAL(SQLITE_MAX_SCHEMA_RETRY),
  13577. #endif
  13578. #if SQLITE_MEMDEBUG
  13579. "MEMDEBUG",
  13580. #endif
  13581. #if SQLITE_MIXED_ENDIAN_64BIT_FLOAT
  13582. "MIXED_ENDIAN_64BIT_FLOAT",
  13583. #endif
  13584. #if SQLITE_NO_SYNC
  13585. "NO_SYNC",
  13586. #endif
  13587. #if SQLITE_OMIT_ALTERTABLE
  13588. "OMIT_ALTERTABLE",
  13589. #endif
  13590. #if SQLITE_OMIT_ANALYZE
  13591. "OMIT_ANALYZE",
  13592. #endif
  13593. #if SQLITE_OMIT_ATTACH
  13594. "OMIT_ATTACH",
  13595. #endif
  13596. #if SQLITE_OMIT_AUTHORIZATION
  13597. "OMIT_AUTHORIZATION",
  13598. #endif
  13599. #if SQLITE_OMIT_AUTOINCREMENT
  13600. "OMIT_AUTOINCREMENT",
  13601. #endif
  13602. #if SQLITE_OMIT_AUTOINIT
  13603. "OMIT_AUTOINIT",
  13604. #endif
  13605. #if SQLITE_OMIT_AUTOMATIC_INDEX
  13606. "OMIT_AUTOMATIC_INDEX",
  13607. #endif
  13608. #if SQLITE_OMIT_AUTORESET
  13609. "OMIT_AUTORESET",
  13610. #endif
  13611. #if SQLITE_OMIT_AUTOVACUUM
  13612. "OMIT_AUTOVACUUM",
  13613. #endif
  13614. #if SQLITE_OMIT_BETWEEN_OPTIMIZATION
  13615. "OMIT_BETWEEN_OPTIMIZATION",
  13616. #endif
  13617. #if SQLITE_OMIT_BLOB_LITERAL
  13618. "OMIT_BLOB_LITERAL",
  13619. #endif
  13620. #if SQLITE_OMIT_BTREECOUNT
  13621. "OMIT_BTREECOUNT",
  13622. #endif
  13623. #if SQLITE_OMIT_BUILTIN_TEST
  13624. "OMIT_BUILTIN_TEST",
  13625. #endif
  13626. #if SQLITE_OMIT_CAST
  13627. "OMIT_CAST",
  13628. #endif
  13629. #if SQLITE_OMIT_CHECK
  13630. "OMIT_CHECK",
  13631. #endif
  13632. #if SQLITE_OMIT_COMPLETE
  13633. "OMIT_COMPLETE",
  13634. #endif
  13635. #if SQLITE_OMIT_COMPOUND_SELECT
  13636. "OMIT_COMPOUND_SELECT",
  13637. #endif
  13638. #if SQLITE_OMIT_CTE
  13639. "OMIT_CTE",
  13640. #endif
  13641. #if SQLITE_OMIT_DATETIME_FUNCS
  13642. "OMIT_DATETIME_FUNCS",
  13643. #endif
  13644. #if SQLITE_OMIT_DECLTYPE
  13645. "OMIT_DECLTYPE",
  13646. #endif
  13647. #if SQLITE_OMIT_DEPRECATED
  13648. "OMIT_DEPRECATED",
  13649. #endif
  13650. #if SQLITE_OMIT_DISKIO
  13651. "OMIT_DISKIO",
  13652. #endif
  13653. #if SQLITE_OMIT_EXPLAIN
  13654. "OMIT_EXPLAIN",
  13655. #endif
  13656. #if SQLITE_OMIT_FLAG_PRAGMAS
  13657. "OMIT_FLAG_PRAGMAS",
  13658. #endif
  13659. #if SQLITE_OMIT_FLOATING_POINT
  13660. "OMIT_FLOATING_POINT",
  13661. #endif
  13662. #if SQLITE_OMIT_FOREIGN_KEY
  13663. "OMIT_FOREIGN_KEY",
  13664. #endif
  13665. #if SQLITE_OMIT_GET_TABLE
  13666. "OMIT_GET_TABLE",
  13667. #endif
  13668. #if SQLITE_OMIT_INCRBLOB
  13669. "OMIT_INCRBLOB",
  13670. #endif
  13671. #if SQLITE_OMIT_INTEGRITY_CHECK
  13672. "OMIT_INTEGRITY_CHECK",
  13673. #endif
  13674. #if SQLITE_OMIT_LIKE_OPTIMIZATION
  13675. "OMIT_LIKE_OPTIMIZATION",
  13676. #endif
  13677. #if SQLITE_OMIT_LOAD_EXTENSION
  13678. "OMIT_LOAD_EXTENSION",
  13679. #endif
  13680. #if SQLITE_OMIT_LOCALTIME
  13681. "OMIT_LOCALTIME",
  13682. #endif
  13683. #if SQLITE_OMIT_LOOKASIDE
  13684. "OMIT_LOOKASIDE",
  13685. #endif
  13686. #if SQLITE_OMIT_MEMORYDB
  13687. "OMIT_MEMORYDB",
  13688. #endif
  13689. #if SQLITE_OMIT_OR_OPTIMIZATION
  13690. "OMIT_OR_OPTIMIZATION",
  13691. #endif
  13692. #if SQLITE_OMIT_PAGER_PRAGMAS
  13693. "OMIT_PAGER_PRAGMAS",
  13694. #endif
  13695. #if SQLITE_OMIT_PRAGMA
  13696. "OMIT_PRAGMA",
  13697. #endif
  13698. #if SQLITE_OMIT_PROGRESS_CALLBACK
  13699. "OMIT_PROGRESS_CALLBACK",
  13700. #endif
  13701. #if SQLITE_OMIT_QUICKBALANCE
  13702. "OMIT_QUICKBALANCE",
  13703. #endif
  13704. #if SQLITE_OMIT_REINDEX
  13705. "OMIT_REINDEX",
  13706. #endif
  13707. #if SQLITE_OMIT_SCHEMA_PRAGMAS
  13708. "OMIT_SCHEMA_PRAGMAS",
  13709. #endif
  13710. #if SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS
  13711. "OMIT_SCHEMA_VERSION_PRAGMAS",
  13712. #endif
  13713. #if SQLITE_OMIT_SHARED_CACHE
  13714. "OMIT_SHARED_CACHE",
  13715. #endif
  13716. #if SQLITE_OMIT_SUBQUERY
  13717. "OMIT_SUBQUERY",
  13718. #endif
  13719. #if SQLITE_OMIT_TCL_VARIABLE
  13720. "OMIT_TCL_VARIABLE",
  13721. #endif
  13722. #if SQLITE_OMIT_TEMPDB
  13723. "OMIT_TEMPDB",
  13724. #endif
  13725. #if SQLITE_OMIT_TRACE
  13726. "OMIT_TRACE",
  13727. #endif
  13728. #if SQLITE_OMIT_TRIGGER
  13729. "OMIT_TRIGGER",
  13730. #endif
  13731. #if SQLITE_OMIT_TRUNCATE_OPTIMIZATION
  13732. "OMIT_TRUNCATE_OPTIMIZATION",
  13733. #endif
  13734. #if SQLITE_OMIT_UTF16
  13735. "OMIT_UTF16",
  13736. #endif
  13737. #if SQLITE_OMIT_VACUUM
  13738. "OMIT_VACUUM",
  13739. #endif
  13740. #if SQLITE_OMIT_VIEW
  13741. "OMIT_VIEW",
  13742. #endif
  13743. #if SQLITE_OMIT_VIRTUALTABLE
  13744. "OMIT_VIRTUALTABLE",
  13745. #endif
  13746. #if SQLITE_OMIT_WAL
  13747. "OMIT_WAL",
  13748. #endif
  13749. #if SQLITE_OMIT_WSD
  13750. "OMIT_WSD",
  13751. #endif
  13752. #if SQLITE_OMIT_XFER_OPT
  13753. "OMIT_XFER_OPT",
  13754. #endif
  13755. #if SQLITE_PERFORMANCE_TRACE
  13756. "PERFORMANCE_TRACE",
  13757. #endif
  13758. #if SQLITE_PROXY_DEBUG
  13759. "PROXY_DEBUG",
  13760. #endif
  13761. #if SQLITE_RTREE_INT_ONLY
  13762. "RTREE_INT_ONLY",
  13763. #endif
  13764. #if SQLITE_SECURE_DELETE
  13765. "SECURE_DELETE",
  13766. #endif
  13767. #if SQLITE_SMALL_STACK
  13768. "SMALL_STACK",
  13769. #endif
  13770. #if SQLITE_SOUNDEX
  13771. "SOUNDEX",
  13772. #endif
  13773. #if SQLITE_SYSTEM_MALLOC
  13774. "SYSTEM_MALLOC",
  13775. #endif
  13776. #if SQLITE_TCL
  13777. "TCL",
  13778. #endif
  13779. #if defined(SQLITE_TEMP_STORE) && !defined(SQLITE_TEMP_STORE_xc)
  13780. "TEMP_STORE=" CTIMEOPT_VAL(SQLITE_TEMP_STORE),
  13781. #endif
  13782. #if SQLITE_TEST
  13783. "TEST",
  13784. #endif
  13785. #if defined(SQLITE_THREADSAFE)
  13786. "THREADSAFE=" CTIMEOPT_VAL(SQLITE_THREADSAFE),
  13787. #endif
  13788. #if SQLITE_USE_ALLOCA
  13789. "USE_ALLOCA",
  13790. #endif
  13791. #if SQLITE_USER_AUTHENTICATION
  13792. "USER_AUTHENTICATION",
  13793. #endif
  13794. #if SQLITE_WIN32_MALLOC
  13795. "WIN32_MALLOC",
  13796. #endif
  13797. #if SQLITE_ZERO_MALLOC
  13798. "ZERO_MALLOC"
  13799. #endif
  13800. };
  13801. /*
  13802. ** Given the name of a compile-time option, return true if that option
  13803. ** was used and false if not.
  13804. **
  13805. ** The name can optionally begin with "SQLITE_" but the "SQLITE_" prefix
  13806. ** is not required for a match.
  13807. */
  13808. SQLITE_API int SQLITE_STDCALL sqlite3_compileoption_used(const char *zOptName){
  13809. int i, n;
  13810. #if SQLITE_ENABLE_API_ARMOR
  13811. if( zOptName==0 ){
  13812. (void)SQLITE_MISUSE_BKPT;
  13813. return 0;
  13814. }
  13815. #endif
  13816. if( sqlite3StrNICmp(zOptName, "SQLITE_", 7)==0 ) zOptName += 7;
  13817. n = sqlite3Strlen30(zOptName);
  13818. /* Since ArraySize(azCompileOpt) is normally in single digits, a
  13819. ** linear search is adequate. No need for a binary search. */
  13820. for(i=0; i<ArraySize(azCompileOpt); i++){
  13821. if( sqlite3StrNICmp(zOptName, azCompileOpt[i], n)==0
  13822. && sqlite3IsIdChar((unsigned char)azCompileOpt[i][n])==0
  13823. ){
  13824. return 1;
  13825. }
  13826. }
  13827. return 0;
  13828. }
  13829. /*
  13830. ** Return the N-th compile-time option string. If N is out of range,
  13831. ** return a NULL pointer.
  13832. */
  13833. SQLITE_API const char *SQLITE_STDCALL sqlite3_compileoption_get(int N){
  13834. if( N>=0 && N<ArraySize(azCompileOpt) ){
  13835. return azCompileOpt[N];
  13836. }
  13837. return 0;
  13838. }
  13839. #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
  13840. /************** End of ctime.c ***********************************************/
  13841. /************** Begin file status.c ******************************************/
  13842. /*
  13843. ** 2008 June 18
  13844. **
  13845. ** The author disclaims copyright to this source code. In place of
  13846. ** a legal notice, here is a blessing:
  13847. **
  13848. ** May you do good and not evil.
  13849. ** May you find forgiveness for yourself and forgive others.
  13850. ** May you share freely, never taking more than you give.
  13851. **
  13852. *************************************************************************
  13853. **
  13854. ** This module implements the sqlite3_status() interface and related
  13855. ** functionality.
  13856. */
  13857. /************** Include vdbeInt.h in the middle of status.c ******************/
  13858. /************** Begin file vdbeInt.h *****************************************/
  13859. /*
  13860. ** 2003 September 6
  13861. **
  13862. ** The author disclaims copyright to this source code. In place of
  13863. ** a legal notice, here is a blessing:
  13864. **
  13865. ** May you do good and not evil.
  13866. ** May you find forgiveness for yourself and forgive others.
  13867. ** May you share freely, never taking more than you give.
  13868. **
  13869. *************************************************************************
  13870. ** This is the header file for information that is private to the
  13871. ** VDBE. This information used to all be at the top of the single
  13872. ** source code file "vdbe.c". When that file became too big (over
  13873. ** 6000 lines long) it was split up into several smaller files and
  13874. ** this header information was factored out.
  13875. */
  13876. #ifndef _VDBEINT_H_
  13877. #define _VDBEINT_H_
  13878. /*
  13879. ** The maximum number of times that a statement will try to reparse
  13880. ** itself before giving up and returning SQLITE_SCHEMA.
  13881. */
  13882. #ifndef SQLITE_MAX_SCHEMA_RETRY
  13883. # define SQLITE_MAX_SCHEMA_RETRY 50
  13884. #endif
  13885. /*
  13886. ** SQL is translated into a sequence of instructions to be
  13887. ** executed by a virtual machine. Each instruction is an instance
  13888. ** of the following structure.
  13889. */
  13890. typedef struct VdbeOp Op;
  13891. /*
  13892. ** Boolean values
  13893. */
  13894. typedef unsigned Bool;
  13895. /* Opaque type used by code in vdbesort.c */
  13896. typedef struct VdbeSorter VdbeSorter;
  13897. /* Opaque type used by the explainer */
  13898. typedef struct Explain Explain;
  13899. /* Elements of the linked list at Vdbe.pAuxData */
  13900. typedef struct AuxData AuxData;
  13901. /*
  13902. ** A cursor is a pointer into a single BTree within a database file.
  13903. ** The cursor can seek to a BTree entry with a particular key, or
  13904. ** loop over all entries of the Btree. You can also insert new BTree
  13905. ** entries or retrieve the key or data from the entry that the cursor
  13906. ** is currently pointing to.
  13907. **
  13908. ** Cursors can also point to virtual tables, sorters, or "pseudo-tables".
  13909. ** A pseudo-table is a single-row table implemented by registers.
  13910. **
  13911. ** Every cursor that the virtual machine has open is represented by an
  13912. ** instance of the following structure.
  13913. */
  13914. struct VdbeCursor {
  13915. BtCursor *pCursor; /* The cursor structure of the backend */
  13916. Btree *pBt; /* Separate file holding temporary table */
  13917. KeyInfo *pKeyInfo; /* Info about index keys needed by index cursors */
  13918. int seekResult; /* Result of previous sqlite3BtreeMoveto() */
  13919. int pseudoTableReg; /* Register holding pseudotable content. */
  13920. i16 nField; /* Number of fields in the header */
  13921. u16 nHdrParsed; /* Number of header fields parsed so far */
  13922. #ifdef SQLITE_DEBUG
  13923. u8 seekOp; /* Most recent seek operation on this cursor */
  13924. #endif
  13925. i8 iDb; /* Index of cursor database in db->aDb[] (or -1) */
  13926. u8 nullRow; /* True if pointing to a row with no data */
  13927. u8 deferredMoveto; /* A call to sqlite3BtreeMoveto() is needed */
  13928. Bool isEphemeral:1; /* True for an ephemeral table */
  13929. Bool useRandomRowid:1;/* Generate new record numbers semi-randomly */
  13930. Bool isTable:1; /* True if a table requiring integer keys */
  13931. Bool isOrdered:1; /* True if the underlying table is BTREE_UNORDERED */
  13932. Pgno pgnoRoot; /* Root page of the open btree cursor */
  13933. sqlite3_vtab_cursor *pVtabCursor; /* The cursor for a virtual table */
  13934. i64 seqCount; /* Sequence counter */
  13935. i64 movetoTarget; /* Argument to the deferred sqlite3BtreeMoveto() */
  13936. VdbeSorter *pSorter; /* Sorter object for OP_SorterOpen cursors */
  13937. /* Cached information about the header for the data record that the
  13938. ** cursor is currently pointing to. Only valid if cacheStatus matches
  13939. ** Vdbe.cacheCtr. Vdbe.cacheCtr will never take on the value of
  13940. ** CACHE_STALE and so setting cacheStatus=CACHE_STALE guarantees that
  13941. ** the cache is out of date.
  13942. **
  13943. ** aRow might point to (ephemeral) data for the current row, or it might
  13944. ** be NULL.
  13945. */
  13946. u32 cacheStatus; /* Cache is valid if this matches Vdbe.cacheCtr */
  13947. u32 payloadSize; /* Total number of bytes in the record */
  13948. u32 szRow; /* Byte available in aRow */
  13949. u32 iHdrOffset; /* Offset to next unparsed byte of the header */
  13950. const u8 *aRow; /* Data for the current row, if all on one page */
  13951. u32 *aOffset; /* Pointer to aType[nField] */
  13952. u32 aType[1]; /* Type values for all entries in the record */
  13953. /* 2*nField extra array elements allocated for aType[], beyond the one
  13954. ** static element declared in the structure. nField total array slots for
  13955. ** aType[] and nField+1 array slots for aOffset[] */
  13956. };
  13957. typedef struct VdbeCursor VdbeCursor;
  13958. /*
  13959. ** When a sub-program is executed (OP_Program), a structure of this type
  13960. ** is allocated to store the current value of the program counter, as
  13961. ** well as the current memory cell array and various other frame specific
  13962. ** values stored in the Vdbe struct. When the sub-program is finished,
  13963. ** these values are copied back to the Vdbe from the VdbeFrame structure,
  13964. ** restoring the state of the VM to as it was before the sub-program
  13965. ** began executing.
  13966. **
  13967. ** The memory for a VdbeFrame object is allocated and managed by a memory
  13968. ** cell in the parent (calling) frame. When the memory cell is deleted or
  13969. ** overwritten, the VdbeFrame object is not freed immediately. Instead, it
  13970. ** is linked into the Vdbe.pDelFrame list. The contents of the Vdbe.pDelFrame
  13971. ** list is deleted when the VM is reset in VdbeHalt(). The reason for doing
  13972. ** this instead of deleting the VdbeFrame immediately is to avoid recursive
  13973. ** calls to sqlite3VdbeMemRelease() when the memory cells belonging to the
  13974. ** child frame are released.
  13975. **
  13976. ** The currently executing frame is stored in Vdbe.pFrame. Vdbe.pFrame is
  13977. ** set to NULL if the currently executing frame is the main program.
  13978. */
  13979. typedef struct VdbeFrame VdbeFrame;
  13980. struct VdbeFrame {
  13981. Vdbe *v; /* VM this frame belongs to */
  13982. VdbeFrame *pParent; /* Parent of this frame, or NULL if parent is main */
  13983. Op *aOp; /* Program instructions for parent frame */
  13984. i64 *anExec; /* Event counters from parent frame */
  13985. Mem *aMem; /* Array of memory cells for parent frame */
  13986. u8 *aOnceFlag; /* Array of OP_Once flags for parent frame */
  13987. VdbeCursor **apCsr; /* Array of Vdbe cursors for parent frame */
  13988. void *token; /* Copy of SubProgram.token */
  13989. i64 lastRowid; /* Last insert rowid (sqlite3.lastRowid) */
  13990. int nCursor; /* Number of entries in apCsr */
  13991. int pc; /* Program Counter in parent (calling) frame */
  13992. int nOp; /* Size of aOp array */
  13993. int nMem; /* Number of entries in aMem */
  13994. int nOnceFlag; /* Number of entries in aOnceFlag */
  13995. int nChildMem; /* Number of memory cells for child frame */
  13996. int nChildCsr; /* Number of cursors for child frame */
  13997. int nChange; /* Statement changes (Vdbe.nChange) */
  13998. int nDbChange; /* Value of db->nChange */
  13999. };
  14000. #define VdbeFrameMem(p) ((Mem *)&((u8 *)p)[ROUND8(sizeof(VdbeFrame))])
  14001. /*
  14002. ** A value for VdbeCursor.cacheValid that means the cache is always invalid.
  14003. */
  14004. #define CACHE_STALE 0
  14005. /*
  14006. ** Internally, the vdbe manipulates nearly all SQL values as Mem
  14007. ** structures. Each Mem struct may cache multiple representations (string,
  14008. ** integer etc.) of the same value.
  14009. */
  14010. struct Mem {
  14011. union MemValue {
  14012. double r; /* Real value used when MEM_Real is set in flags */
  14013. i64 i; /* Integer value used when MEM_Int is set in flags */
  14014. int nZero; /* Used when bit MEM_Zero is set in flags */
  14015. FuncDef *pDef; /* Used only when flags==MEM_Agg */
  14016. RowSet *pRowSet; /* Used only when flags==MEM_RowSet */
  14017. VdbeFrame *pFrame; /* Used when flags==MEM_Frame */
  14018. } u;
  14019. u16 flags; /* Some combination of MEM_Null, MEM_Str, MEM_Dyn, etc. */
  14020. u8 enc; /* SQLITE_UTF8, SQLITE_UTF16BE, SQLITE_UTF16LE */
  14021. int n; /* Number of characters in string value, excluding '\0' */
  14022. char *z; /* String or BLOB value */
  14023. /* ShallowCopy only needs to copy the information above */
  14024. char *zMalloc; /* Space to hold MEM_Str or MEM_Blob if szMalloc>0 */
  14025. int szMalloc; /* Size of the zMalloc allocation */
  14026. u32 uTemp; /* Transient storage for serial_type in OP_MakeRecord */
  14027. sqlite3 *db; /* The associated database connection */
  14028. void (*xDel)(void*);/* Destructor for Mem.z - only valid if MEM_Dyn */
  14029. #ifdef SQLITE_DEBUG
  14030. Mem *pScopyFrom; /* This Mem is a shallow copy of pScopyFrom */
  14031. void *pFiller; /* So that sizeof(Mem) is a multiple of 8 */
  14032. #endif
  14033. };
  14034. /* One or more of the following flags are set to indicate the validOK
  14035. ** representations of the value stored in the Mem struct.
  14036. **
  14037. ** If the MEM_Null flag is set, then the value is an SQL NULL value.
  14038. ** No other flags may be set in this case.
  14039. **
  14040. ** If the MEM_Str flag is set then Mem.z points at a string representation.
  14041. ** Usually this is encoded in the same unicode encoding as the main
  14042. ** database (see below for exceptions). If the MEM_Term flag is also
  14043. ** set, then the string is nul terminated. The MEM_Int and MEM_Real
  14044. ** flags may coexist with the MEM_Str flag.
  14045. */
  14046. #define MEM_Null 0x0001 /* Value is NULL */
  14047. #define MEM_Str 0x0002 /* Value is a string */
  14048. #define MEM_Int 0x0004 /* Value is an integer */
  14049. #define MEM_Real 0x0008 /* Value is a real number */
  14050. #define MEM_Blob 0x0010 /* Value is a BLOB */
  14051. #define MEM_AffMask 0x001f /* Mask of affinity bits */
  14052. #define MEM_RowSet 0x0020 /* Value is a RowSet object */
  14053. #define MEM_Frame 0x0040 /* Value is a VdbeFrame object */
  14054. #define MEM_Undefined 0x0080 /* Value is undefined */
  14055. #define MEM_Cleared 0x0100 /* NULL set by OP_Null, not from data */
  14056. #define MEM_TypeMask 0x01ff /* Mask of type bits */
  14057. /* Whenever Mem contains a valid string or blob representation, one of
  14058. ** the following flags must be set to determine the memory management
  14059. ** policy for Mem.z. The MEM_Term flag tells us whether or not the
  14060. ** string is \000 or \u0000 terminated
  14061. */
  14062. #define MEM_Term 0x0200 /* String rep is nul terminated */
  14063. #define MEM_Dyn 0x0400 /* Need to call Mem.xDel() on Mem.z */
  14064. #define MEM_Static 0x0800 /* Mem.z points to a static string */
  14065. #define MEM_Ephem 0x1000 /* Mem.z points to an ephemeral string */
  14066. #define MEM_Agg 0x2000 /* Mem.z points to an agg function context */
  14067. #define MEM_Zero 0x4000 /* Mem.i contains count of 0s appended to blob */
  14068. #ifdef SQLITE_OMIT_INCRBLOB
  14069. #undef MEM_Zero
  14070. #define MEM_Zero 0x0000
  14071. #endif
  14072. /*
  14073. ** Clear any existing type flags from a Mem and replace them with f
  14074. */
  14075. #define MemSetTypeFlag(p, f) \
  14076. ((p)->flags = ((p)->flags&~(MEM_TypeMask|MEM_Zero))|f)
  14077. /*
  14078. ** Return true if a memory cell is not marked as invalid. This macro
  14079. ** is for use inside assert() statements only.
  14080. */
  14081. #ifdef SQLITE_DEBUG
  14082. #define memIsValid(M) ((M)->flags & MEM_Undefined)==0
  14083. #endif
  14084. /*
  14085. ** Each auxiliary data pointer stored by a user defined function
  14086. ** implementation calling sqlite3_set_auxdata() is stored in an instance
  14087. ** of this structure. All such structures associated with a single VM
  14088. ** are stored in a linked list headed at Vdbe.pAuxData. All are destroyed
  14089. ** when the VM is halted (if not before).
  14090. */
  14091. struct AuxData {
  14092. int iOp; /* Instruction number of OP_Function opcode */
  14093. int iArg; /* Index of function argument. */
  14094. void *pAux; /* Aux data pointer */
  14095. void (*xDelete)(void *); /* Destructor for the aux data */
  14096. AuxData *pNext; /* Next element in list */
  14097. };
  14098. /*
  14099. ** The "context" argument for an installable function. A pointer to an
  14100. ** instance of this structure is the first argument to the routines used
  14101. ** implement the SQL functions.
  14102. **
  14103. ** There is a typedef for this structure in sqlite.h. So all routines,
  14104. ** even the public interface to SQLite, can use a pointer to this structure.
  14105. ** But this file is the only place where the internal details of this
  14106. ** structure are known.
  14107. **
  14108. ** This structure is defined inside of vdbeInt.h because it uses substructures
  14109. ** (Mem) which are only defined there.
  14110. */
  14111. struct sqlite3_context {
  14112. Mem *pOut; /* The return value is stored here */
  14113. FuncDef *pFunc; /* Pointer to function information */
  14114. Mem *pMem; /* Memory cell used to store aggregate context */
  14115. Vdbe *pVdbe; /* The VM that owns this context */
  14116. int iOp; /* Instruction number of OP_Function */
  14117. int isError; /* Error code returned by the function. */
  14118. u8 skipFlag; /* Skip accumulator loading if true */
  14119. u8 fErrorOrAux; /* isError!=0 or pVdbe->pAuxData modified */
  14120. };
  14121. /*
  14122. ** An Explain object accumulates indented output which is helpful
  14123. ** in describing recursive data structures.
  14124. */
  14125. struct Explain {
  14126. Vdbe *pVdbe; /* Attach the explanation to this Vdbe */
  14127. StrAccum str; /* The string being accumulated */
  14128. int nIndent; /* Number of elements in aIndent */
  14129. u16 aIndent[100]; /* Levels of indentation */
  14130. char zBase[100]; /* Initial space */
  14131. };
  14132. /* A bitfield type for use inside of structures. Always follow with :N where
  14133. ** N is the number of bits.
  14134. */
  14135. typedef unsigned bft; /* Bit Field Type */
  14136. typedef struct ScanStatus ScanStatus;
  14137. struct ScanStatus {
  14138. int addrExplain; /* OP_Explain for loop */
  14139. int addrLoop; /* Address of "loops" counter */
  14140. int addrVisit; /* Address of "rows visited" counter */
  14141. int iSelectID; /* The "Select-ID" for this loop */
  14142. LogEst nEst; /* Estimated output rows per loop */
  14143. char *zName; /* Name of table or index */
  14144. };
  14145. /*
  14146. ** An instance of the virtual machine. This structure contains the complete
  14147. ** state of the virtual machine.
  14148. **
  14149. ** The "sqlite3_stmt" structure pointer that is returned by sqlite3_prepare()
  14150. ** is really a pointer to an instance of this structure.
  14151. */
  14152. struct Vdbe {
  14153. sqlite3 *db; /* The database connection that owns this statement */
  14154. Op *aOp; /* Space to hold the virtual machine's program */
  14155. Mem *aMem; /* The memory locations */
  14156. Mem **apArg; /* Arguments to currently executing user function */
  14157. Mem *aColName; /* Column names to return */
  14158. Mem *pResultSet; /* Pointer to an array of results */
  14159. Parse *pParse; /* Parsing context used to create this Vdbe */
  14160. int nMem; /* Number of memory locations currently allocated */
  14161. int nOp; /* Number of instructions in the program */
  14162. int nCursor; /* Number of slots in apCsr[] */
  14163. u32 magic; /* Magic number for sanity checking */
  14164. char *zErrMsg; /* Error message written here */
  14165. Vdbe *pPrev,*pNext; /* Linked list of VDBEs with the same Vdbe.db */
  14166. VdbeCursor **apCsr; /* One element of this array for each open cursor */
  14167. Mem *aVar; /* Values for the OP_Variable opcode. */
  14168. char **azVar; /* Name of variables */
  14169. ynVar nVar; /* Number of entries in aVar[] */
  14170. ynVar nzVar; /* Number of entries in azVar[] */
  14171. u32 cacheCtr; /* VdbeCursor row cache generation counter */
  14172. int pc; /* The program counter */
  14173. int rc; /* Value to return */
  14174. #ifdef SQLITE_DEBUG
  14175. int rcApp; /* errcode set by sqlite3_result_error_code() */
  14176. #endif
  14177. u16 nResColumn; /* Number of columns in one row of the result set */
  14178. u8 errorAction; /* Recovery action to do in case of an error */
  14179. u8 minWriteFileFormat; /* Minimum file format for writable database files */
  14180. bft explain:2; /* True if EXPLAIN present on SQL command */
  14181. bft changeCntOn:1; /* True to update the change-counter */
  14182. bft expired:1; /* True if the VM needs to be recompiled */
  14183. bft runOnlyOnce:1; /* Automatically expire on reset */
  14184. bft usesStmtJournal:1; /* True if uses a statement journal */
  14185. bft readOnly:1; /* True for statements that do not write */
  14186. bft bIsReader:1; /* True for statements that read */
  14187. bft isPrepareV2:1; /* True if prepared with prepare_v2() */
  14188. bft doingRerun:1; /* True if rerunning after an auto-reprepare */
  14189. int nChange; /* Number of db changes made since last reset */
  14190. yDbMask btreeMask; /* Bitmask of db->aDb[] entries referenced */
  14191. yDbMask lockMask; /* Subset of btreeMask that requires a lock */
  14192. int iStatement; /* Statement number (or 0 if has not opened stmt) */
  14193. u32 aCounter[5]; /* Counters used by sqlite3_stmt_status() */
  14194. #ifndef SQLITE_OMIT_TRACE
  14195. i64 startTime; /* Time when query started - used for profiling */
  14196. #endif
  14197. i64 iCurrentTime; /* Value of julianday('now') for this statement */
  14198. i64 nFkConstraint; /* Number of imm. FK constraints this VM */
  14199. i64 nStmtDefCons; /* Number of def. constraints when stmt started */
  14200. i64 nStmtDefImmCons; /* Number of def. imm constraints when stmt started */
  14201. char *zSql; /* Text of the SQL statement that generated this */
  14202. void *pFree; /* Free this when deleting the vdbe */
  14203. VdbeFrame *pFrame; /* Parent frame */
  14204. VdbeFrame *pDelFrame; /* List of frame objects to free on VM reset */
  14205. int nFrame; /* Number of frames in pFrame list */
  14206. u32 expmask; /* Binding to these vars invalidates VM */
  14207. SubProgram *pProgram; /* Linked list of all sub-programs used by VM */
  14208. int nOnceFlag; /* Size of array aOnceFlag[] */
  14209. u8 *aOnceFlag; /* Flags for OP_Once */
  14210. AuxData *pAuxData; /* Linked list of auxdata allocations */
  14211. #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
  14212. i64 *anExec; /* Number of times each op has been executed */
  14213. int nScan; /* Entries in aScan[] */
  14214. ScanStatus *aScan; /* Scan definitions for sqlite3_stmt_scanstatus() */
  14215. #endif
  14216. };
  14217. /*
  14218. ** The following are allowed values for Vdbe.magic
  14219. */
  14220. #define VDBE_MAGIC_INIT 0x26bceaa5 /* Building a VDBE program */
  14221. #define VDBE_MAGIC_RUN 0xbdf20da3 /* VDBE is ready to execute */
  14222. #define VDBE_MAGIC_HALT 0x519c2973 /* VDBE has completed execution */
  14223. #define VDBE_MAGIC_DEAD 0xb606c3c8 /* The VDBE has been deallocated */
  14224. /*
  14225. ** Function prototypes
  14226. */
  14227. SQLITE_PRIVATE void sqlite3VdbeFreeCursor(Vdbe *, VdbeCursor*);
  14228. void sqliteVdbePopStack(Vdbe*,int);
  14229. SQLITE_PRIVATE int sqlite3VdbeCursorMoveto(VdbeCursor*);
  14230. SQLITE_PRIVATE int sqlite3VdbeCursorRestore(VdbeCursor*);
  14231. #if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE)
  14232. SQLITE_PRIVATE void sqlite3VdbePrintOp(FILE*, int, Op*);
  14233. #endif
  14234. SQLITE_PRIVATE u32 sqlite3VdbeSerialTypeLen(u32);
  14235. SQLITE_PRIVATE u32 sqlite3VdbeSerialType(Mem*, int);
  14236. SQLITE_PRIVATE u32 sqlite3VdbeSerialPut(unsigned char*, Mem*, u32);
  14237. SQLITE_PRIVATE u32 sqlite3VdbeSerialGet(const unsigned char*, u32, Mem*);
  14238. SQLITE_PRIVATE void sqlite3VdbeDeleteAuxData(Vdbe*, int, int);
  14239. int sqlite2BtreeKeyCompare(BtCursor *, const void *, int, int, int *);
  14240. SQLITE_PRIVATE int sqlite3VdbeIdxKeyCompare(sqlite3*,VdbeCursor*,UnpackedRecord*,int*);
  14241. SQLITE_PRIVATE int sqlite3VdbeIdxRowid(sqlite3*, BtCursor*, i64*);
  14242. SQLITE_PRIVATE int sqlite3VdbeExec(Vdbe*);
  14243. SQLITE_PRIVATE int sqlite3VdbeList(Vdbe*);
  14244. SQLITE_PRIVATE int sqlite3VdbeHalt(Vdbe*);
  14245. SQLITE_PRIVATE int sqlite3VdbeChangeEncoding(Mem *, int);
  14246. SQLITE_PRIVATE int sqlite3VdbeMemTooBig(Mem*);
  14247. SQLITE_PRIVATE int sqlite3VdbeMemCopy(Mem*, const Mem*);
  14248. SQLITE_PRIVATE void sqlite3VdbeMemShallowCopy(Mem*, const Mem*, int);
  14249. SQLITE_PRIVATE void sqlite3VdbeMemMove(Mem*, Mem*);
  14250. SQLITE_PRIVATE int sqlite3VdbeMemNulTerminate(Mem*);
  14251. SQLITE_PRIVATE int sqlite3VdbeMemSetStr(Mem*, const char*, int, u8, void(*)(void*));
  14252. SQLITE_PRIVATE void sqlite3VdbeMemSetInt64(Mem*, i64);
  14253. #ifdef SQLITE_OMIT_FLOATING_POINT
  14254. # define sqlite3VdbeMemSetDouble sqlite3VdbeMemSetInt64
  14255. #else
  14256. SQLITE_PRIVATE void sqlite3VdbeMemSetDouble(Mem*, double);
  14257. #endif
  14258. SQLITE_PRIVATE void sqlite3VdbeMemInit(Mem*,sqlite3*,u16);
  14259. SQLITE_PRIVATE void sqlite3VdbeMemSetNull(Mem*);
  14260. SQLITE_PRIVATE void sqlite3VdbeMemSetZeroBlob(Mem*,int);
  14261. SQLITE_PRIVATE void sqlite3VdbeMemSetRowSet(Mem*);
  14262. SQLITE_PRIVATE int sqlite3VdbeMemMakeWriteable(Mem*);
  14263. SQLITE_PRIVATE int sqlite3VdbeMemStringify(Mem*, u8, u8);
  14264. SQLITE_PRIVATE i64 sqlite3VdbeIntValue(Mem*);
  14265. SQLITE_PRIVATE int sqlite3VdbeMemIntegerify(Mem*);
  14266. SQLITE_PRIVATE double sqlite3VdbeRealValue(Mem*);
  14267. SQLITE_PRIVATE void sqlite3VdbeIntegerAffinity(Mem*);
  14268. SQLITE_PRIVATE int sqlite3VdbeMemRealify(Mem*);
  14269. SQLITE_PRIVATE int sqlite3VdbeMemNumerify(Mem*);
  14270. SQLITE_PRIVATE void sqlite3VdbeMemCast(Mem*,u8,u8);
  14271. SQLITE_PRIVATE int sqlite3VdbeMemFromBtree(BtCursor*,u32,u32,int,Mem*);
  14272. SQLITE_PRIVATE void sqlite3VdbeMemRelease(Mem *p);
  14273. #define VdbeMemDynamic(X) \
  14274. (((X)->flags&(MEM_Agg|MEM_Dyn|MEM_RowSet|MEM_Frame))!=0)
  14275. SQLITE_PRIVATE int sqlite3VdbeMemFinalize(Mem*, FuncDef*);
  14276. SQLITE_PRIVATE const char *sqlite3OpcodeName(int);
  14277. SQLITE_PRIVATE int sqlite3VdbeMemGrow(Mem *pMem, int n, int preserve);
  14278. SQLITE_PRIVATE int sqlite3VdbeMemClearAndResize(Mem *pMem, int n);
  14279. SQLITE_PRIVATE int sqlite3VdbeCloseStatement(Vdbe *, int);
  14280. SQLITE_PRIVATE void sqlite3VdbeFrameDelete(VdbeFrame*);
  14281. SQLITE_PRIVATE int sqlite3VdbeFrameRestore(VdbeFrame *);
  14282. SQLITE_PRIVATE int sqlite3VdbeTransferError(Vdbe *p);
  14283. SQLITE_PRIVATE int sqlite3VdbeSorterInit(sqlite3 *, int, VdbeCursor *);
  14284. SQLITE_PRIVATE void sqlite3VdbeSorterReset(sqlite3 *, VdbeSorter *);
  14285. SQLITE_PRIVATE void sqlite3VdbeSorterClose(sqlite3 *, VdbeCursor *);
  14286. SQLITE_PRIVATE int sqlite3VdbeSorterRowkey(const VdbeCursor *, Mem *);
  14287. SQLITE_PRIVATE int sqlite3VdbeSorterNext(sqlite3 *, const VdbeCursor *, int *);
  14288. SQLITE_PRIVATE int sqlite3VdbeSorterRewind(const VdbeCursor *, int *);
  14289. SQLITE_PRIVATE int sqlite3VdbeSorterWrite(const VdbeCursor *, Mem *);
  14290. SQLITE_PRIVATE int sqlite3VdbeSorterCompare(const VdbeCursor *, Mem *, int, int *);
  14291. #if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE>0
  14292. SQLITE_PRIVATE void sqlite3VdbeEnter(Vdbe*);
  14293. SQLITE_PRIVATE void sqlite3VdbeLeave(Vdbe*);
  14294. #else
  14295. # define sqlite3VdbeEnter(X)
  14296. # define sqlite3VdbeLeave(X)
  14297. #endif
  14298. #ifdef SQLITE_DEBUG
  14299. SQLITE_PRIVATE void sqlite3VdbeMemAboutToChange(Vdbe*,Mem*);
  14300. SQLITE_PRIVATE int sqlite3VdbeCheckMemInvariants(Mem*);
  14301. #endif
  14302. #ifndef SQLITE_OMIT_FOREIGN_KEY
  14303. SQLITE_PRIVATE int sqlite3VdbeCheckFk(Vdbe *, int);
  14304. #else
  14305. # define sqlite3VdbeCheckFk(p,i) 0
  14306. #endif
  14307. SQLITE_PRIVATE int sqlite3VdbeMemTranslate(Mem*, u8);
  14308. #ifdef SQLITE_DEBUG
  14309. SQLITE_PRIVATE void sqlite3VdbePrintSql(Vdbe*);
  14310. SQLITE_PRIVATE void sqlite3VdbeMemPrettyPrint(Mem *pMem, char *zBuf);
  14311. #endif
  14312. SQLITE_PRIVATE int sqlite3VdbeMemHandleBom(Mem *pMem);
  14313. #ifndef SQLITE_OMIT_INCRBLOB
  14314. SQLITE_PRIVATE int sqlite3VdbeMemExpandBlob(Mem *);
  14315. #define ExpandBlob(P) (((P)->flags&MEM_Zero)?sqlite3VdbeMemExpandBlob(P):0)
  14316. #else
  14317. #define sqlite3VdbeMemExpandBlob(x) SQLITE_OK
  14318. #define ExpandBlob(P) SQLITE_OK
  14319. #endif
  14320. #endif /* !defined(_VDBEINT_H_) */
  14321. /************** End of vdbeInt.h *********************************************/
  14322. /************** Continuing where we left off in status.c *********************/
  14323. /*
  14324. ** Variables in which to record status information.
  14325. */
  14326. typedef struct sqlite3StatType sqlite3StatType;
  14327. static SQLITE_WSD struct sqlite3StatType {
  14328. #if SQLITE_PTRSIZE>4
  14329. sqlite3_int64 nowValue[10]; /* Current value */
  14330. sqlite3_int64 mxValue[10]; /* Maximum value */
  14331. #else
  14332. u32 nowValue[10]; /* Current value */
  14333. u32 mxValue[10]; /* Maximum value */
  14334. #endif
  14335. } sqlite3Stat = { {0,}, {0,} };
  14336. /*
  14337. ** Elements of sqlite3Stat[] are protected by either the memory allocator
  14338. ** mutex, or by the pcache1 mutex. The following array determines which.
  14339. */
  14340. static const char statMutex[] = {
  14341. 0, /* SQLITE_STATUS_MEMORY_USED */
  14342. 1, /* SQLITE_STATUS_PAGECACHE_USED */
  14343. 1, /* SQLITE_STATUS_PAGECACHE_OVERFLOW */
  14344. 0, /* SQLITE_STATUS_SCRATCH_USED */
  14345. 0, /* SQLITE_STATUS_SCRATCH_OVERFLOW */
  14346. 0, /* SQLITE_STATUS_MALLOC_SIZE */
  14347. 0, /* SQLITE_STATUS_PARSER_STACK */
  14348. 1, /* SQLITE_STATUS_PAGECACHE_SIZE */
  14349. 0, /* SQLITE_STATUS_SCRATCH_SIZE */
  14350. 0, /* SQLITE_STATUS_MALLOC_COUNT */
  14351. };
  14352. /* The "wsdStat" macro will resolve to the status information
  14353. ** state vector. If writable static data is unsupported on the target,
  14354. ** we have to locate the state vector at run-time. In the more common
  14355. ** case where writable static data is supported, wsdStat can refer directly
  14356. ** to the "sqlite3Stat" state vector declared above.
  14357. */
  14358. #ifdef SQLITE_OMIT_WSD
  14359. # define wsdStatInit sqlite3StatType *x = &GLOBAL(sqlite3StatType,sqlite3Stat)
  14360. # define wsdStat x[0]
  14361. #else
  14362. # define wsdStatInit
  14363. # define wsdStat sqlite3Stat
  14364. #endif
  14365. /*
  14366. ** Return the current value of a status parameter. The caller must
  14367. ** be holding the appropriate mutex.
  14368. */
  14369. SQLITE_PRIVATE sqlite3_int64 sqlite3StatusValue(int op){
  14370. wsdStatInit;
  14371. assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
  14372. assert( op>=0 && op<ArraySize(statMutex) );
  14373. assert( sqlite3_mutex_held(statMutex[op] ? sqlite3Pcache1Mutex()
  14374. : sqlite3MallocMutex()) );
  14375. return wsdStat.nowValue[op];
  14376. }
  14377. /*
  14378. ** Add N to the value of a status record. The caller must hold the
  14379. ** appropriate mutex. (Locking is checked by assert()).
  14380. **
  14381. ** The StatusUp() routine can accept positive or negative values for N.
  14382. ** The value of N is added to the current status value and the high-water
  14383. ** mark is adjusted if necessary.
  14384. **
  14385. ** The StatusDown() routine lowers the current value by N. The highwater
  14386. ** mark is unchanged. N must be non-negative for StatusDown().
  14387. */
  14388. SQLITE_PRIVATE void sqlite3StatusUp(int op, int N){
  14389. wsdStatInit;
  14390. assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
  14391. assert( op>=0 && op<ArraySize(statMutex) );
  14392. assert( sqlite3_mutex_held(statMutex[op] ? sqlite3Pcache1Mutex()
  14393. : sqlite3MallocMutex()) );
  14394. wsdStat.nowValue[op] += N;
  14395. if( wsdStat.nowValue[op]>wsdStat.mxValue[op] ){
  14396. wsdStat.mxValue[op] = wsdStat.nowValue[op];
  14397. }
  14398. }
  14399. SQLITE_PRIVATE void sqlite3StatusDown(int op, int N){
  14400. wsdStatInit;
  14401. assert( N>=0 );
  14402. assert( op>=0 && op<ArraySize(statMutex) );
  14403. assert( sqlite3_mutex_held(statMutex[op] ? sqlite3Pcache1Mutex()
  14404. : sqlite3MallocMutex()) );
  14405. assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
  14406. wsdStat.nowValue[op] -= N;
  14407. }
  14408. /*
  14409. ** Set the value of a status to X. The highwater mark is adjusted if
  14410. ** necessary. The caller must hold the appropriate mutex.
  14411. */
  14412. SQLITE_PRIVATE void sqlite3StatusSet(int op, int X){
  14413. wsdStatInit;
  14414. assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
  14415. assert( op>=0 && op<ArraySize(statMutex) );
  14416. assert( sqlite3_mutex_held(statMutex[op] ? sqlite3Pcache1Mutex()
  14417. : sqlite3MallocMutex()) );
  14418. wsdStat.nowValue[op] = X;
  14419. if( wsdStat.nowValue[op]>wsdStat.mxValue[op] ){
  14420. wsdStat.mxValue[op] = wsdStat.nowValue[op];
  14421. }
  14422. }
  14423. /*
  14424. ** Query status information.
  14425. */
  14426. SQLITE_API int SQLITE_STDCALL sqlite3_status64(
  14427. int op,
  14428. sqlite3_int64 *pCurrent,
  14429. sqlite3_int64 *pHighwater,
  14430. int resetFlag
  14431. ){
  14432. sqlite3_mutex *pMutex;
  14433. wsdStatInit;
  14434. if( op<0 || op>=ArraySize(wsdStat.nowValue) ){
  14435. return SQLITE_MISUSE_BKPT;
  14436. }
  14437. #ifdef SQLITE_ENABLE_API_ARMOR
  14438. if( pCurrent==0 || pHighwater==0 ) return SQLITE_MISUSE_BKPT;
  14439. #endif
  14440. pMutex = statMutex[op] ? sqlite3Pcache1Mutex() : sqlite3MallocMutex();
  14441. sqlite3_mutex_enter(pMutex);
  14442. *pCurrent = wsdStat.nowValue[op];
  14443. *pHighwater = wsdStat.mxValue[op];
  14444. if( resetFlag ){
  14445. wsdStat.mxValue[op] = wsdStat.nowValue[op];
  14446. }
  14447. sqlite3_mutex_leave(pMutex);
  14448. (void)pMutex; /* Prevent warning when SQLITE_THREADSAFE=0 */
  14449. return SQLITE_OK;
  14450. }
  14451. SQLITE_API int SQLITE_STDCALL sqlite3_status(int op, int *pCurrent, int *pHighwater, int resetFlag){
  14452. sqlite3_int64 iCur, iHwtr;
  14453. int rc;
  14454. #ifdef SQLITE_ENABLE_API_ARMOR
  14455. if( pCurrent==0 || pHighwater==0 ) return SQLITE_MISUSE_BKPT;
  14456. #endif
  14457. rc = sqlite3_status64(op, &iCur, &iHwtr, resetFlag);
  14458. if( rc==0 ){
  14459. *pCurrent = (int)iCur;
  14460. *pHighwater = (int)iHwtr;
  14461. }
  14462. return rc;
  14463. }
  14464. /*
  14465. ** Query status information for a single database connection
  14466. */
  14467. SQLITE_API int SQLITE_STDCALL sqlite3_db_status(
  14468. sqlite3 *db, /* The database connection whose status is desired */
  14469. int op, /* Status verb */
  14470. int *pCurrent, /* Write current value here */
  14471. int *pHighwater, /* Write high-water mark here */
  14472. int resetFlag /* Reset high-water mark if true */
  14473. ){
  14474. int rc = SQLITE_OK; /* Return code */
  14475. #ifdef SQLITE_ENABLE_API_ARMOR
  14476. if( !sqlite3SafetyCheckOk(db) || pCurrent==0|| pHighwater==0 ){
  14477. return SQLITE_MISUSE_BKPT;
  14478. }
  14479. #endif
  14480. sqlite3_mutex_enter(db->mutex);
  14481. switch( op ){
  14482. case SQLITE_DBSTATUS_LOOKASIDE_USED: {
  14483. *pCurrent = db->lookaside.nOut;
  14484. *pHighwater = db->lookaside.mxOut;
  14485. if( resetFlag ){
  14486. db->lookaside.mxOut = db->lookaside.nOut;
  14487. }
  14488. break;
  14489. }
  14490. case SQLITE_DBSTATUS_LOOKASIDE_HIT:
  14491. case SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE:
  14492. case SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL: {
  14493. testcase( op==SQLITE_DBSTATUS_LOOKASIDE_HIT );
  14494. testcase( op==SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE );
  14495. testcase( op==SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL );
  14496. assert( (op-SQLITE_DBSTATUS_LOOKASIDE_HIT)>=0 );
  14497. assert( (op-SQLITE_DBSTATUS_LOOKASIDE_HIT)<3 );
  14498. *pCurrent = 0;
  14499. *pHighwater = db->lookaside.anStat[op - SQLITE_DBSTATUS_LOOKASIDE_HIT];
  14500. if( resetFlag ){
  14501. db->lookaside.anStat[op - SQLITE_DBSTATUS_LOOKASIDE_HIT] = 0;
  14502. }
  14503. break;
  14504. }
  14505. /*
  14506. ** Return an approximation for the amount of memory currently used
  14507. ** by all pagers associated with the given database connection. The
  14508. ** highwater mark is meaningless and is returned as zero.
  14509. */
  14510. case SQLITE_DBSTATUS_CACHE_USED: {
  14511. int totalUsed = 0;
  14512. int i;
  14513. sqlite3BtreeEnterAll(db);
  14514. for(i=0; i<db->nDb; i++){
  14515. Btree *pBt = db->aDb[i].pBt;
  14516. if( pBt ){
  14517. Pager *pPager = sqlite3BtreePager(pBt);
  14518. totalUsed += sqlite3PagerMemUsed(pPager);
  14519. }
  14520. }
  14521. sqlite3BtreeLeaveAll(db);
  14522. *pCurrent = totalUsed;
  14523. *pHighwater = 0;
  14524. break;
  14525. }
  14526. /*
  14527. ** *pCurrent gets an accurate estimate of the amount of memory used
  14528. ** to store the schema for all databases (main, temp, and any ATTACHed
  14529. ** databases. *pHighwater is set to zero.
  14530. */
  14531. case SQLITE_DBSTATUS_SCHEMA_USED: {
  14532. int i; /* Used to iterate through schemas */
  14533. int nByte = 0; /* Used to accumulate return value */
  14534. sqlite3BtreeEnterAll(db);
  14535. db->pnBytesFreed = &nByte;
  14536. for(i=0; i<db->nDb; i++){
  14537. Schema *pSchema = db->aDb[i].pSchema;
  14538. if( ALWAYS(pSchema!=0) ){
  14539. HashElem *p;
  14540. nByte += sqlite3GlobalConfig.m.xRoundup(sizeof(HashElem)) * (
  14541. pSchema->tblHash.count
  14542. + pSchema->trigHash.count
  14543. + pSchema->idxHash.count
  14544. + pSchema->fkeyHash.count
  14545. );
  14546. nByte += sqlite3MallocSize(pSchema->tblHash.ht);
  14547. nByte += sqlite3MallocSize(pSchema->trigHash.ht);
  14548. nByte += sqlite3MallocSize(pSchema->idxHash.ht);
  14549. nByte += sqlite3MallocSize(pSchema->fkeyHash.ht);
  14550. for(p=sqliteHashFirst(&pSchema->trigHash); p; p=sqliteHashNext(p)){
  14551. sqlite3DeleteTrigger(db, (Trigger*)sqliteHashData(p));
  14552. }
  14553. for(p=sqliteHashFirst(&pSchema->tblHash); p; p=sqliteHashNext(p)){
  14554. sqlite3DeleteTable(db, (Table *)sqliteHashData(p));
  14555. }
  14556. }
  14557. }
  14558. db->pnBytesFreed = 0;
  14559. sqlite3BtreeLeaveAll(db);
  14560. *pHighwater = 0;
  14561. *pCurrent = nByte;
  14562. break;
  14563. }
  14564. /*
  14565. ** *pCurrent gets an accurate estimate of the amount of memory used
  14566. ** to store all prepared statements.
  14567. ** *pHighwater is set to zero.
  14568. */
  14569. case SQLITE_DBSTATUS_STMT_USED: {
  14570. struct Vdbe *pVdbe; /* Used to iterate through VMs */
  14571. int nByte = 0; /* Used to accumulate return value */
  14572. db->pnBytesFreed = &nByte;
  14573. for(pVdbe=db->pVdbe; pVdbe; pVdbe=pVdbe->pNext){
  14574. sqlite3VdbeClearObject(db, pVdbe);
  14575. sqlite3DbFree(db, pVdbe);
  14576. }
  14577. db->pnBytesFreed = 0;
  14578. *pHighwater = 0; /* IMP: R-64479-57858 */
  14579. *pCurrent = nByte;
  14580. break;
  14581. }
  14582. /*
  14583. ** Set *pCurrent to the total cache hits or misses encountered by all
  14584. ** pagers the database handle is connected to. *pHighwater is always set
  14585. ** to zero.
  14586. */
  14587. case SQLITE_DBSTATUS_CACHE_HIT:
  14588. case SQLITE_DBSTATUS_CACHE_MISS:
  14589. case SQLITE_DBSTATUS_CACHE_WRITE:{
  14590. int i;
  14591. int nRet = 0;
  14592. assert( SQLITE_DBSTATUS_CACHE_MISS==SQLITE_DBSTATUS_CACHE_HIT+1 );
  14593. assert( SQLITE_DBSTATUS_CACHE_WRITE==SQLITE_DBSTATUS_CACHE_HIT+2 );
  14594. for(i=0; i<db->nDb; i++){
  14595. if( db->aDb[i].pBt ){
  14596. Pager *pPager = sqlite3BtreePager(db->aDb[i].pBt);
  14597. sqlite3PagerCacheStat(pPager, op, resetFlag, &nRet);
  14598. }
  14599. }
  14600. *pHighwater = 0; /* IMP: R-42420-56072 */
  14601. /* IMP: R-54100-20147 */
  14602. /* IMP: R-29431-39229 */
  14603. *pCurrent = nRet;
  14604. break;
  14605. }
  14606. /* Set *pCurrent to non-zero if there are unresolved deferred foreign
  14607. ** key constraints. Set *pCurrent to zero if all foreign key constraints
  14608. ** have been satisfied. The *pHighwater is always set to zero.
  14609. */
  14610. case SQLITE_DBSTATUS_DEFERRED_FKS: {
  14611. *pHighwater = 0; /* IMP: R-11967-56545 */
  14612. *pCurrent = db->nDeferredImmCons>0 || db->nDeferredCons>0;
  14613. break;
  14614. }
  14615. default: {
  14616. rc = SQLITE_ERROR;
  14617. }
  14618. }
  14619. sqlite3_mutex_leave(db->mutex);
  14620. return rc;
  14621. }
  14622. /************** End of status.c **********************************************/
  14623. /************** Begin file date.c ********************************************/
  14624. /*
  14625. ** 2003 October 31
  14626. **
  14627. ** The author disclaims copyright to this source code. In place of
  14628. ** a legal notice, here is a blessing:
  14629. **
  14630. ** May you do good and not evil.
  14631. ** May you find forgiveness for yourself and forgive others.
  14632. ** May you share freely, never taking more than you give.
  14633. **
  14634. *************************************************************************
  14635. ** This file contains the C functions that implement date and time
  14636. ** functions for SQLite.
  14637. **
  14638. ** There is only one exported symbol in this file - the function
  14639. ** sqlite3RegisterDateTimeFunctions() found at the bottom of the file.
  14640. ** All other code has file scope.
  14641. **
  14642. ** SQLite processes all times and dates as julian day numbers. The
  14643. ** dates and times are stored as the number of days since noon
  14644. ** in Greenwich on November 24, 4714 B.C. according to the Gregorian
  14645. ** calendar system.
  14646. **
  14647. ** 1970-01-01 00:00:00 is JD 2440587.5
  14648. ** 2000-01-01 00:00:00 is JD 2451544.5
  14649. **
  14650. ** This implementation requires years to be expressed as a 4-digit number
  14651. ** which means that only dates between 0000-01-01 and 9999-12-31 can
  14652. ** be represented, even though julian day numbers allow a much wider
  14653. ** range of dates.
  14654. **
  14655. ** The Gregorian calendar system is used for all dates and times,
  14656. ** even those that predate the Gregorian calendar. Historians usually
  14657. ** use the julian calendar for dates prior to 1582-10-15 and for some
  14658. ** dates afterwards, depending on locale. Beware of this difference.
  14659. **
  14660. ** The conversion algorithms are implemented based on descriptions
  14661. ** in the following text:
  14662. **
  14663. ** Jean Meeus
  14664. ** Astronomical Algorithms, 2nd Edition, 1998
  14665. ** ISBM 0-943396-61-1
  14666. ** Willmann-Bell, Inc
  14667. ** Richmond, Virginia (USA)
  14668. */
  14669. /* #include <stdlib.h> */
  14670. /* #include <assert.h> */
  14671. #include <time.h>
  14672. #ifndef SQLITE_OMIT_DATETIME_FUNCS
  14673. /*
  14674. ** A structure for holding a single date and time.
  14675. */
  14676. typedef struct DateTime DateTime;
  14677. struct DateTime {
  14678. sqlite3_int64 iJD; /* The julian day number times 86400000 */
  14679. int Y, M, D; /* Year, month, and day */
  14680. int h, m; /* Hour and minutes */
  14681. int tz; /* Timezone offset in minutes */
  14682. double s; /* Seconds */
  14683. char validYMD; /* True (1) if Y,M,D are valid */
  14684. char validHMS; /* True (1) if h,m,s are valid */
  14685. char validJD; /* True (1) if iJD is valid */
  14686. char validTZ; /* True (1) if tz is valid */
  14687. };
  14688. /*
  14689. ** Convert zDate into one or more integers. Additional arguments
  14690. ** come in groups of 5 as follows:
  14691. **
  14692. ** N number of digits in the integer
  14693. ** min minimum allowed value of the integer
  14694. ** max maximum allowed value of the integer
  14695. ** nextC first character after the integer
  14696. ** pVal where to write the integers value.
  14697. **
  14698. ** Conversions continue until one with nextC==0 is encountered.
  14699. ** The function returns the number of successful conversions.
  14700. */
  14701. static int getDigits(const char *zDate, ...){
  14702. va_list ap;
  14703. int val;
  14704. int N;
  14705. int min;
  14706. int max;
  14707. int nextC;
  14708. int *pVal;
  14709. int cnt = 0;
  14710. va_start(ap, zDate);
  14711. do{
  14712. N = va_arg(ap, int);
  14713. min = va_arg(ap, int);
  14714. max = va_arg(ap, int);
  14715. nextC = va_arg(ap, int);
  14716. pVal = va_arg(ap, int*);
  14717. val = 0;
  14718. while( N-- ){
  14719. if( !sqlite3Isdigit(*zDate) ){
  14720. goto end_getDigits;
  14721. }
  14722. val = val*10 + *zDate - '0';
  14723. zDate++;
  14724. }
  14725. if( val<min || val>max || (nextC!=0 && nextC!=*zDate) ){
  14726. goto end_getDigits;
  14727. }
  14728. *pVal = val;
  14729. zDate++;
  14730. cnt++;
  14731. }while( nextC );
  14732. end_getDigits:
  14733. va_end(ap);
  14734. return cnt;
  14735. }
  14736. /*
  14737. ** Parse a timezone extension on the end of a date-time.
  14738. ** The extension is of the form:
  14739. **
  14740. ** (+/-)HH:MM
  14741. **
  14742. ** Or the "zulu" notation:
  14743. **
  14744. ** Z
  14745. **
  14746. ** If the parse is successful, write the number of minutes
  14747. ** of change in p->tz and return 0. If a parser error occurs,
  14748. ** return non-zero.
  14749. **
  14750. ** A missing specifier is not considered an error.
  14751. */
  14752. static int parseTimezone(const char *zDate, DateTime *p){
  14753. int sgn = 0;
  14754. int nHr, nMn;
  14755. int c;
  14756. while( sqlite3Isspace(*zDate) ){ zDate++; }
  14757. p->tz = 0;
  14758. c = *zDate;
  14759. if( c=='-' ){
  14760. sgn = -1;
  14761. }else if( c=='+' ){
  14762. sgn = +1;
  14763. }else if( c=='Z' || c=='z' ){
  14764. zDate++;
  14765. goto zulu_time;
  14766. }else{
  14767. return c!=0;
  14768. }
  14769. zDate++;
  14770. if( getDigits(zDate, 2, 0, 14, ':', &nHr, 2, 0, 59, 0, &nMn)!=2 ){
  14771. return 1;
  14772. }
  14773. zDate += 5;
  14774. p->tz = sgn*(nMn + nHr*60);
  14775. zulu_time:
  14776. while( sqlite3Isspace(*zDate) ){ zDate++; }
  14777. return *zDate!=0;
  14778. }
  14779. /*
  14780. ** Parse times of the form HH:MM or HH:MM:SS or HH:MM:SS.FFFF.
  14781. ** The HH, MM, and SS must each be exactly 2 digits. The
  14782. ** fractional seconds FFFF can be one or more digits.
  14783. **
  14784. ** Return 1 if there is a parsing error and 0 on success.
  14785. */
  14786. static int parseHhMmSs(const char *zDate, DateTime *p){
  14787. int h, m, s;
  14788. double ms = 0.0;
  14789. if( getDigits(zDate, 2, 0, 24, ':', &h, 2, 0, 59, 0, &m)!=2 ){
  14790. return 1;
  14791. }
  14792. zDate += 5;
  14793. if( *zDate==':' ){
  14794. zDate++;
  14795. if( getDigits(zDate, 2, 0, 59, 0, &s)!=1 ){
  14796. return 1;
  14797. }
  14798. zDate += 2;
  14799. if( *zDate=='.' && sqlite3Isdigit(zDate[1]) ){
  14800. double rScale = 1.0;
  14801. zDate++;
  14802. while( sqlite3Isdigit(*zDate) ){
  14803. ms = ms*10.0 + *zDate - '0';
  14804. rScale *= 10.0;
  14805. zDate++;
  14806. }
  14807. ms /= rScale;
  14808. }
  14809. }else{
  14810. s = 0;
  14811. }
  14812. p->validJD = 0;
  14813. p->validHMS = 1;
  14814. p->h = h;
  14815. p->m = m;
  14816. p->s = s + ms;
  14817. if( parseTimezone(zDate, p) ) return 1;
  14818. p->validTZ = (p->tz!=0)?1:0;
  14819. return 0;
  14820. }
  14821. /*
  14822. ** Convert from YYYY-MM-DD HH:MM:SS to julian day. We always assume
  14823. ** that the YYYY-MM-DD is according to the Gregorian calendar.
  14824. **
  14825. ** Reference: Meeus page 61
  14826. */
  14827. static void computeJD(DateTime *p){
  14828. int Y, M, D, A, B, X1, X2;
  14829. if( p->validJD ) return;
  14830. if( p->validYMD ){
  14831. Y = p->Y;
  14832. M = p->M;
  14833. D = p->D;
  14834. }else{
  14835. Y = 2000; /* If no YMD specified, assume 2000-Jan-01 */
  14836. M = 1;
  14837. D = 1;
  14838. }
  14839. if( M<=2 ){
  14840. Y--;
  14841. M += 12;
  14842. }
  14843. A = Y/100;
  14844. B = 2 - A + (A/4);
  14845. X1 = 36525*(Y+4716)/100;
  14846. X2 = 306001*(M+1)/10000;
  14847. p->iJD = (sqlite3_int64)((X1 + X2 + D + B - 1524.5 ) * 86400000);
  14848. p->validJD = 1;
  14849. if( p->validHMS ){
  14850. p->iJD += p->h*3600000 + p->m*60000 + (sqlite3_int64)(p->s*1000);
  14851. if( p->validTZ ){
  14852. p->iJD -= p->tz*60000;
  14853. p->validYMD = 0;
  14854. p->validHMS = 0;
  14855. p->validTZ = 0;
  14856. }
  14857. }
  14858. }
  14859. /*
  14860. ** Parse dates of the form
  14861. **
  14862. ** YYYY-MM-DD HH:MM:SS.FFF
  14863. ** YYYY-MM-DD HH:MM:SS
  14864. ** YYYY-MM-DD HH:MM
  14865. ** YYYY-MM-DD
  14866. **
  14867. ** Write the result into the DateTime structure and return 0
  14868. ** on success and 1 if the input string is not a well-formed
  14869. ** date.
  14870. */
  14871. static int parseYyyyMmDd(const char *zDate, DateTime *p){
  14872. int Y, M, D, neg;
  14873. if( zDate[0]=='-' ){
  14874. zDate++;
  14875. neg = 1;
  14876. }else{
  14877. neg = 0;
  14878. }
  14879. if( getDigits(zDate,4,0,9999,'-',&Y,2,1,12,'-',&M,2,1,31,0,&D)!=3 ){
  14880. return 1;
  14881. }
  14882. zDate += 10;
  14883. while( sqlite3Isspace(*zDate) || 'T'==*(u8*)zDate ){ zDate++; }
  14884. if( parseHhMmSs(zDate, p)==0 ){
  14885. /* We got the time */
  14886. }else if( *zDate==0 ){
  14887. p->validHMS = 0;
  14888. }else{
  14889. return 1;
  14890. }
  14891. p->validJD = 0;
  14892. p->validYMD = 1;
  14893. p->Y = neg ? -Y : Y;
  14894. p->M = M;
  14895. p->D = D;
  14896. if( p->validTZ ){
  14897. computeJD(p);
  14898. }
  14899. return 0;
  14900. }
  14901. /*
  14902. ** Set the time to the current time reported by the VFS.
  14903. **
  14904. ** Return the number of errors.
  14905. */
  14906. static int setDateTimeToCurrent(sqlite3_context *context, DateTime *p){
  14907. p->iJD = sqlite3StmtCurrentTime(context);
  14908. if( p->iJD>0 ){
  14909. p->validJD = 1;
  14910. return 0;
  14911. }else{
  14912. return 1;
  14913. }
  14914. }
  14915. /*
  14916. ** Attempt to parse the given string into a julian day number. Return
  14917. ** the number of errors.
  14918. **
  14919. ** The following are acceptable forms for the input string:
  14920. **
  14921. ** YYYY-MM-DD HH:MM:SS.FFF +/-HH:MM
  14922. ** DDDD.DD
  14923. ** now
  14924. **
  14925. ** In the first form, the +/-HH:MM is always optional. The fractional
  14926. ** seconds extension (the ".FFF") is optional. The seconds portion
  14927. ** (":SS.FFF") is option. The year and date can be omitted as long
  14928. ** as there is a time string. The time string can be omitted as long
  14929. ** as there is a year and date.
  14930. */
  14931. static int parseDateOrTime(
  14932. sqlite3_context *context,
  14933. const char *zDate,
  14934. DateTime *p
  14935. ){
  14936. double r;
  14937. if( parseYyyyMmDd(zDate,p)==0 ){
  14938. return 0;
  14939. }else if( parseHhMmSs(zDate, p)==0 ){
  14940. return 0;
  14941. }else if( sqlite3StrICmp(zDate,"now")==0){
  14942. return setDateTimeToCurrent(context, p);
  14943. }else if( sqlite3AtoF(zDate, &r, sqlite3Strlen30(zDate), SQLITE_UTF8) ){
  14944. p->iJD = (sqlite3_int64)(r*86400000.0 + 0.5);
  14945. p->validJD = 1;
  14946. return 0;
  14947. }
  14948. return 1;
  14949. }
  14950. /*
  14951. ** Compute the Year, Month, and Day from the julian day number.
  14952. */
  14953. static void computeYMD(DateTime *p){
  14954. int Z, A, B, C, D, E, X1;
  14955. if( p->validYMD ) return;
  14956. if( !p->validJD ){
  14957. p->Y = 2000;
  14958. p->M = 1;
  14959. p->D = 1;
  14960. }else{
  14961. Z = (int)((p->iJD + 43200000)/86400000);
  14962. A = (int)((Z - 1867216.25)/36524.25);
  14963. A = Z + 1 + A - (A/4);
  14964. B = A + 1524;
  14965. C = (int)((B - 122.1)/365.25);
  14966. D = (36525*C)/100;
  14967. E = (int)((B-D)/30.6001);
  14968. X1 = (int)(30.6001*E);
  14969. p->D = B - D - X1;
  14970. p->M = E<14 ? E-1 : E-13;
  14971. p->Y = p->M>2 ? C - 4716 : C - 4715;
  14972. }
  14973. p->validYMD = 1;
  14974. }
  14975. /*
  14976. ** Compute the Hour, Minute, and Seconds from the julian day number.
  14977. */
  14978. static void computeHMS(DateTime *p){
  14979. int s;
  14980. if( p->validHMS ) return;
  14981. computeJD(p);
  14982. s = (int)((p->iJD + 43200000) % 86400000);
  14983. p->s = s/1000.0;
  14984. s = (int)p->s;
  14985. p->s -= s;
  14986. p->h = s/3600;
  14987. s -= p->h*3600;
  14988. p->m = s/60;
  14989. p->s += s - p->m*60;
  14990. p->validHMS = 1;
  14991. }
  14992. /*
  14993. ** Compute both YMD and HMS
  14994. */
  14995. static void computeYMD_HMS(DateTime *p){
  14996. computeYMD(p);
  14997. computeHMS(p);
  14998. }
  14999. /*
  15000. ** Clear the YMD and HMS and the TZ
  15001. */
  15002. static void clearYMD_HMS_TZ(DateTime *p){
  15003. p->validYMD = 0;
  15004. p->validHMS = 0;
  15005. p->validTZ = 0;
  15006. }
  15007. /*
  15008. ** On recent Windows platforms, the localtime_s() function is available
  15009. ** as part of the "Secure CRT". It is essentially equivalent to
  15010. ** localtime_r() available under most POSIX platforms, except that the
  15011. ** order of the parameters is reversed.
  15012. **
  15013. ** See http://msdn.microsoft.com/en-us/library/a442x3ye(VS.80).aspx.
  15014. **
  15015. ** If the user has not indicated to use localtime_r() or localtime_s()
  15016. ** already, check for an MSVC build environment that provides
  15017. ** localtime_s().
  15018. */
  15019. #if !HAVE_LOCALTIME_R && !HAVE_LOCALTIME_S \
  15020. && defined(_MSC_VER) && defined(_CRT_INSECURE_DEPRECATE)
  15021. #undef HAVE_LOCALTIME_S
  15022. #define HAVE_LOCALTIME_S 1
  15023. #endif
  15024. #ifndef SQLITE_OMIT_LOCALTIME
  15025. /*
  15026. ** The following routine implements the rough equivalent of localtime_r()
  15027. ** using whatever operating-system specific localtime facility that
  15028. ** is available. This routine returns 0 on success and
  15029. ** non-zero on any kind of error.
  15030. **
  15031. ** If the sqlite3GlobalConfig.bLocaltimeFault variable is true then this
  15032. ** routine will always fail.
  15033. **
  15034. ** EVIDENCE-OF: R-62172-00036 In this implementation, the standard C
  15035. ** library function localtime_r() is used to assist in the calculation of
  15036. ** local time.
  15037. */
  15038. static int osLocaltime(time_t *t, struct tm *pTm){
  15039. int rc;
  15040. #if !HAVE_LOCALTIME_R && !HAVE_LOCALTIME_S
  15041. struct tm *pX;
  15042. #if SQLITE_THREADSAFE>0
  15043. sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
  15044. #endif
  15045. sqlite3_mutex_enter(mutex);
  15046. pX = localtime(t);
  15047. #ifndef SQLITE_OMIT_BUILTIN_TEST
  15048. if( sqlite3GlobalConfig.bLocaltimeFault ) pX = 0;
  15049. #endif
  15050. if( pX ) *pTm = *pX;
  15051. sqlite3_mutex_leave(mutex);
  15052. rc = pX==0;
  15053. #else
  15054. #ifndef SQLITE_OMIT_BUILTIN_TEST
  15055. if( sqlite3GlobalConfig.bLocaltimeFault ) return 1;
  15056. #endif
  15057. #if HAVE_LOCALTIME_R
  15058. rc = localtime_r(t, pTm)==0;
  15059. #else
  15060. rc = localtime_s(pTm, t);
  15061. #endif /* HAVE_LOCALTIME_R */
  15062. #endif /* HAVE_LOCALTIME_R || HAVE_LOCALTIME_S */
  15063. return rc;
  15064. }
  15065. #endif /* SQLITE_OMIT_LOCALTIME */
  15066. #ifndef SQLITE_OMIT_LOCALTIME
  15067. /*
  15068. ** Compute the difference (in milliseconds) between localtime and UTC
  15069. ** (a.k.a. GMT) for the time value p where p is in UTC. If no error occurs,
  15070. ** return this value and set *pRc to SQLITE_OK.
  15071. **
  15072. ** Or, if an error does occur, set *pRc to SQLITE_ERROR. The returned value
  15073. ** is undefined in this case.
  15074. */
  15075. static sqlite3_int64 localtimeOffset(
  15076. DateTime *p, /* Date at which to calculate offset */
  15077. sqlite3_context *pCtx, /* Write error here if one occurs */
  15078. int *pRc /* OUT: Error code. SQLITE_OK or ERROR */
  15079. ){
  15080. DateTime x, y;
  15081. time_t t;
  15082. struct tm sLocal;
  15083. /* Initialize the contents of sLocal to avoid a compiler warning. */
  15084. memset(&sLocal, 0, sizeof(sLocal));
  15085. x = *p;
  15086. computeYMD_HMS(&x);
  15087. if( x.Y<1971 || x.Y>=2038 ){
  15088. /* EVIDENCE-OF: R-55269-29598 The localtime_r() C function normally only
  15089. ** works for years between 1970 and 2037. For dates outside this range,
  15090. ** SQLite attempts to map the year into an equivalent year within this
  15091. ** range, do the calculation, then map the year back.
  15092. */
  15093. x.Y = 2000;
  15094. x.M = 1;
  15095. x.D = 1;
  15096. x.h = 0;
  15097. x.m = 0;
  15098. x.s = 0.0;
  15099. } else {
  15100. int s = (int)(x.s + 0.5);
  15101. x.s = s;
  15102. }
  15103. x.tz = 0;
  15104. x.validJD = 0;
  15105. computeJD(&x);
  15106. t = (time_t)(x.iJD/1000 - 21086676*(i64)10000);
  15107. if( osLocaltime(&t, &sLocal) ){
  15108. sqlite3_result_error(pCtx, "local time unavailable", -1);
  15109. *pRc = SQLITE_ERROR;
  15110. return 0;
  15111. }
  15112. y.Y = sLocal.tm_year + 1900;
  15113. y.M = sLocal.tm_mon + 1;
  15114. y.D = sLocal.tm_mday;
  15115. y.h = sLocal.tm_hour;
  15116. y.m = sLocal.tm_min;
  15117. y.s = sLocal.tm_sec;
  15118. y.validYMD = 1;
  15119. y.validHMS = 1;
  15120. y.validJD = 0;
  15121. y.validTZ = 0;
  15122. computeJD(&y);
  15123. *pRc = SQLITE_OK;
  15124. return y.iJD - x.iJD;
  15125. }
  15126. #endif /* SQLITE_OMIT_LOCALTIME */
  15127. /*
  15128. ** Process a modifier to a date-time stamp. The modifiers are
  15129. ** as follows:
  15130. **
  15131. ** NNN days
  15132. ** NNN hours
  15133. ** NNN minutes
  15134. ** NNN.NNNN seconds
  15135. ** NNN months
  15136. ** NNN years
  15137. ** start of month
  15138. ** start of year
  15139. ** start of week
  15140. ** start of day
  15141. ** weekday N
  15142. ** unixepoch
  15143. ** localtime
  15144. ** utc
  15145. **
  15146. ** Return 0 on success and 1 if there is any kind of error. If the error
  15147. ** is in a system call (i.e. localtime()), then an error message is written
  15148. ** to context pCtx. If the error is an unrecognized modifier, no error is
  15149. ** written to pCtx.
  15150. */
  15151. static int parseModifier(sqlite3_context *pCtx, const char *zMod, DateTime *p){
  15152. int rc = 1;
  15153. int n;
  15154. double r;
  15155. char *z, zBuf[30];
  15156. z = zBuf;
  15157. for(n=0; n<ArraySize(zBuf)-1 && zMod[n]; n++){
  15158. z[n] = (char)sqlite3UpperToLower[(u8)zMod[n]];
  15159. }
  15160. z[n] = 0;
  15161. switch( z[0] ){
  15162. #ifndef SQLITE_OMIT_LOCALTIME
  15163. case 'l': {
  15164. /* localtime
  15165. **
  15166. ** Assuming the current time value is UTC (a.k.a. GMT), shift it to
  15167. ** show local time.
  15168. */
  15169. if( strcmp(z, "localtime")==0 ){
  15170. computeJD(p);
  15171. p->iJD += localtimeOffset(p, pCtx, &rc);
  15172. clearYMD_HMS_TZ(p);
  15173. }
  15174. break;
  15175. }
  15176. #endif
  15177. case 'u': {
  15178. /*
  15179. ** unixepoch
  15180. **
  15181. ** Treat the current value of p->iJD as the number of
  15182. ** seconds since 1970. Convert to a real julian day number.
  15183. */
  15184. if( strcmp(z, "unixepoch")==0 && p->validJD ){
  15185. p->iJD = (p->iJD + 43200)/86400 + 21086676*(i64)10000000;
  15186. clearYMD_HMS_TZ(p);
  15187. rc = 0;
  15188. }
  15189. #ifndef SQLITE_OMIT_LOCALTIME
  15190. else if( strcmp(z, "utc")==0 ){
  15191. sqlite3_int64 c1;
  15192. computeJD(p);
  15193. c1 = localtimeOffset(p, pCtx, &rc);
  15194. if( rc==SQLITE_OK ){
  15195. p->iJD -= c1;
  15196. clearYMD_HMS_TZ(p);
  15197. p->iJD += c1 - localtimeOffset(p, pCtx, &rc);
  15198. }
  15199. }
  15200. #endif
  15201. break;
  15202. }
  15203. case 'w': {
  15204. /*
  15205. ** weekday N
  15206. **
  15207. ** Move the date to the same time on the next occurrence of
  15208. ** weekday N where 0==Sunday, 1==Monday, and so forth. If the
  15209. ** date is already on the appropriate weekday, this is a no-op.
  15210. */
  15211. if( strncmp(z, "weekday ", 8)==0
  15212. && sqlite3AtoF(&z[8], &r, sqlite3Strlen30(&z[8]), SQLITE_UTF8)
  15213. && (n=(int)r)==r && n>=0 && r<7 ){
  15214. sqlite3_int64 Z;
  15215. computeYMD_HMS(p);
  15216. p->validTZ = 0;
  15217. p->validJD = 0;
  15218. computeJD(p);
  15219. Z = ((p->iJD + 129600000)/86400000) % 7;
  15220. if( Z>n ) Z -= 7;
  15221. p->iJD += (n - Z)*86400000;
  15222. clearYMD_HMS_TZ(p);
  15223. rc = 0;
  15224. }
  15225. break;
  15226. }
  15227. case 's': {
  15228. /*
  15229. ** start of TTTTT
  15230. **
  15231. ** Move the date backwards to the beginning of the current day,
  15232. ** or month or year.
  15233. */
  15234. if( strncmp(z, "start of ", 9)!=0 ) break;
  15235. z += 9;
  15236. computeYMD(p);
  15237. p->validHMS = 1;
  15238. p->h = p->m = 0;
  15239. p->s = 0.0;
  15240. p->validTZ = 0;
  15241. p->validJD = 0;
  15242. if( strcmp(z,"month")==0 ){
  15243. p->D = 1;
  15244. rc = 0;
  15245. }else if( strcmp(z,"year")==0 ){
  15246. computeYMD(p);
  15247. p->M = 1;
  15248. p->D = 1;
  15249. rc = 0;
  15250. }else if( strcmp(z,"day")==0 ){
  15251. rc = 0;
  15252. }
  15253. break;
  15254. }
  15255. case '+':
  15256. case '-':
  15257. case '0':
  15258. case '1':
  15259. case '2':
  15260. case '3':
  15261. case '4':
  15262. case '5':
  15263. case '6':
  15264. case '7':
  15265. case '8':
  15266. case '9': {
  15267. double rRounder;
  15268. for(n=1; z[n] && z[n]!=':' && !sqlite3Isspace(z[n]); n++){}
  15269. if( !sqlite3AtoF(z, &r, n, SQLITE_UTF8) ){
  15270. rc = 1;
  15271. break;
  15272. }
  15273. if( z[n]==':' ){
  15274. /* A modifier of the form (+|-)HH:MM:SS.FFF adds (or subtracts) the
  15275. ** specified number of hours, minutes, seconds, and fractional seconds
  15276. ** to the time. The ".FFF" may be omitted. The ":SS.FFF" may be
  15277. ** omitted.
  15278. */
  15279. const char *z2 = z;
  15280. DateTime tx;
  15281. sqlite3_int64 day;
  15282. if( !sqlite3Isdigit(*z2) ) z2++;
  15283. memset(&tx, 0, sizeof(tx));
  15284. if( parseHhMmSs(z2, &tx) ) break;
  15285. computeJD(&tx);
  15286. tx.iJD -= 43200000;
  15287. day = tx.iJD/86400000;
  15288. tx.iJD -= day*86400000;
  15289. if( z[0]=='-' ) tx.iJD = -tx.iJD;
  15290. computeJD(p);
  15291. clearYMD_HMS_TZ(p);
  15292. p->iJD += tx.iJD;
  15293. rc = 0;
  15294. break;
  15295. }
  15296. z += n;
  15297. while( sqlite3Isspace(*z) ) z++;
  15298. n = sqlite3Strlen30(z);
  15299. if( n>10 || n<3 ) break;
  15300. if( z[n-1]=='s' ){ z[n-1] = 0; n--; }
  15301. computeJD(p);
  15302. rc = 0;
  15303. rRounder = r<0 ? -0.5 : +0.5;
  15304. if( n==3 && strcmp(z,"day")==0 ){
  15305. p->iJD += (sqlite3_int64)(r*86400000.0 + rRounder);
  15306. }else if( n==4 && strcmp(z,"hour")==0 ){
  15307. p->iJD += (sqlite3_int64)(r*(86400000.0/24.0) + rRounder);
  15308. }else if( n==6 && strcmp(z,"minute")==0 ){
  15309. p->iJD += (sqlite3_int64)(r*(86400000.0/(24.0*60.0)) + rRounder);
  15310. }else if( n==6 && strcmp(z,"second")==0 ){
  15311. p->iJD += (sqlite3_int64)(r*(86400000.0/(24.0*60.0*60.0)) + rRounder);
  15312. }else if( n==5 && strcmp(z,"month")==0 ){
  15313. int x, y;
  15314. computeYMD_HMS(p);
  15315. p->M += (int)r;
  15316. x = p->M>0 ? (p->M-1)/12 : (p->M-12)/12;
  15317. p->Y += x;
  15318. p->M -= x*12;
  15319. p->validJD = 0;
  15320. computeJD(p);
  15321. y = (int)r;
  15322. if( y!=r ){
  15323. p->iJD += (sqlite3_int64)((r - y)*30.0*86400000.0 + rRounder);
  15324. }
  15325. }else if( n==4 && strcmp(z,"year")==0 ){
  15326. int y = (int)r;
  15327. computeYMD_HMS(p);
  15328. p->Y += y;
  15329. p->validJD = 0;
  15330. computeJD(p);
  15331. if( y!=r ){
  15332. p->iJD += (sqlite3_int64)((r - y)*365.0*86400000.0 + rRounder);
  15333. }
  15334. }else{
  15335. rc = 1;
  15336. }
  15337. clearYMD_HMS_TZ(p);
  15338. break;
  15339. }
  15340. default: {
  15341. break;
  15342. }
  15343. }
  15344. return rc;
  15345. }
  15346. /*
  15347. ** Process time function arguments. argv[0] is a date-time stamp.
  15348. ** argv[1] and following are modifiers. Parse them all and write
  15349. ** the resulting time into the DateTime structure p. Return 0
  15350. ** on success and 1 if there are any errors.
  15351. **
  15352. ** If there are zero parameters (if even argv[0] is undefined)
  15353. ** then assume a default value of "now" for argv[0].
  15354. */
  15355. static int isDate(
  15356. sqlite3_context *context,
  15357. int argc,
  15358. sqlite3_value **argv,
  15359. DateTime *p
  15360. ){
  15361. int i;
  15362. const unsigned char *z;
  15363. int eType;
  15364. memset(p, 0, sizeof(*p));
  15365. if( argc==0 ){
  15366. return setDateTimeToCurrent(context, p);
  15367. }
  15368. if( (eType = sqlite3_value_type(argv[0]))==SQLITE_FLOAT
  15369. || eType==SQLITE_INTEGER ){
  15370. p->iJD = (sqlite3_int64)(sqlite3_value_double(argv[0])*86400000.0 + 0.5);
  15371. p->validJD = 1;
  15372. }else{
  15373. z = sqlite3_value_text(argv[0]);
  15374. if( !z || parseDateOrTime(context, (char*)z, p) ){
  15375. return 1;
  15376. }
  15377. }
  15378. for(i=1; i<argc; i++){
  15379. z = sqlite3_value_text(argv[i]);
  15380. if( z==0 || parseModifier(context, (char*)z, p) ) return 1;
  15381. }
  15382. return 0;
  15383. }
  15384. /*
  15385. ** The following routines implement the various date and time functions
  15386. ** of SQLite.
  15387. */
  15388. /*
  15389. ** julianday( TIMESTRING, MOD, MOD, ...)
  15390. **
  15391. ** Return the julian day number of the date specified in the arguments
  15392. */
  15393. static void juliandayFunc(
  15394. sqlite3_context *context,
  15395. int argc,
  15396. sqlite3_value **argv
  15397. ){
  15398. DateTime x;
  15399. if( isDate(context, argc, argv, &x)==0 ){
  15400. computeJD(&x);
  15401. sqlite3_result_double(context, x.iJD/86400000.0);
  15402. }
  15403. }
  15404. /*
  15405. ** datetime( TIMESTRING, MOD, MOD, ...)
  15406. **
  15407. ** Return YYYY-MM-DD HH:MM:SS
  15408. */
  15409. static void datetimeFunc(
  15410. sqlite3_context *context,
  15411. int argc,
  15412. sqlite3_value **argv
  15413. ){
  15414. DateTime x;
  15415. if( isDate(context, argc, argv, &x)==0 ){
  15416. char zBuf[100];
  15417. computeYMD_HMS(&x);
  15418. sqlite3_snprintf(sizeof(zBuf), zBuf, "%04d-%02d-%02d %02d:%02d:%02d",
  15419. x.Y, x.M, x.D, x.h, x.m, (int)(x.s));
  15420. sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
  15421. }
  15422. }
  15423. /*
  15424. ** time( TIMESTRING, MOD, MOD, ...)
  15425. **
  15426. ** Return HH:MM:SS
  15427. */
  15428. static void timeFunc(
  15429. sqlite3_context *context,
  15430. int argc,
  15431. sqlite3_value **argv
  15432. ){
  15433. DateTime x;
  15434. if( isDate(context, argc, argv, &x)==0 ){
  15435. char zBuf[100];
  15436. computeHMS(&x);
  15437. sqlite3_snprintf(sizeof(zBuf), zBuf, "%02d:%02d:%02d", x.h, x.m, (int)x.s);
  15438. sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
  15439. }
  15440. }
  15441. /*
  15442. ** date( TIMESTRING, MOD, MOD, ...)
  15443. **
  15444. ** Return YYYY-MM-DD
  15445. */
  15446. static void dateFunc(
  15447. sqlite3_context *context,
  15448. int argc,
  15449. sqlite3_value **argv
  15450. ){
  15451. DateTime x;
  15452. if( isDate(context, argc, argv, &x)==0 ){
  15453. char zBuf[100];
  15454. computeYMD(&x);
  15455. sqlite3_snprintf(sizeof(zBuf), zBuf, "%04d-%02d-%02d", x.Y, x.M, x.D);
  15456. sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
  15457. }
  15458. }
  15459. /*
  15460. ** strftime( FORMAT, TIMESTRING, MOD, MOD, ...)
  15461. **
  15462. ** Return a string described by FORMAT. Conversions as follows:
  15463. **
  15464. ** %d day of month
  15465. ** %f ** fractional seconds SS.SSS
  15466. ** %H hour 00-24
  15467. ** %j day of year 000-366
  15468. ** %J ** julian day number
  15469. ** %m month 01-12
  15470. ** %M minute 00-59
  15471. ** %s seconds since 1970-01-01
  15472. ** %S seconds 00-59
  15473. ** %w day of week 0-6 sunday==0
  15474. ** %W week of year 00-53
  15475. ** %Y year 0000-9999
  15476. ** %% %
  15477. */
  15478. static void strftimeFunc(
  15479. sqlite3_context *context,
  15480. int argc,
  15481. sqlite3_value **argv
  15482. ){
  15483. DateTime x;
  15484. u64 n;
  15485. size_t i,j;
  15486. char *z;
  15487. sqlite3 *db;
  15488. const char *zFmt;
  15489. char zBuf[100];
  15490. if( argc==0 ) return;
  15491. zFmt = (const char*)sqlite3_value_text(argv[0]);
  15492. if( zFmt==0 || isDate(context, argc-1, argv+1, &x) ) return;
  15493. db = sqlite3_context_db_handle(context);
  15494. for(i=0, n=1; zFmt[i]; i++, n++){
  15495. if( zFmt[i]=='%' ){
  15496. switch( zFmt[i+1] ){
  15497. case 'd':
  15498. case 'H':
  15499. case 'm':
  15500. case 'M':
  15501. case 'S':
  15502. case 'W':
  15503. n++;
  15504. /* fall thru */
  15505. case 'w':
  15506. case '%':
  15507. break;
  15508. case 'f':
  15509. n += 8;
  15510. break;
  15511. case 'j':
  15512. n += 3;
  15513. break;
  15514. case 'Y':
  15515. n += 8;
  15516. break;
  15517. case 's':
  15518. case 'J':
  15519. n += 50;
  15520. break;
  15521. default:
  15522. return; /* ERROR. return a NULL */
  15523. }
  15524. i++;
  15525. }
  15526. }
  15527. testcase( n==sizeof(zBuf)-1 );
  15528. testcase( n==sizeof(zBuf) );
  15529. testcase( n==(u64)db->aLimit[SQLITE_LIMIT_LENGTH]+1 );
  15530. testcase( n==(u64)db->aLimit[SQLITE_LIMIT_LENGTH] );
  15531. if( n<sizeof(zBuf) ){
  15532. z = zBuf;
  15533. }else if( n>(u64)db->aLimit[SQLITE_LIMIT_LENGTH] ){
  15534. sqlite3_result_error_toobig(context);
  15535. return;
  15536. }else{
  15537. z = sqlite3DbMallocRaw(db, (int)n);
  15538. if( z==0 ){
  15539. sqlite3_result_error_nomem(context);
  15540. return;
  15541. }
  15542. }
  15543. computeJD(&x);
  15544. computeYMD_HMS(&x);
  15545. for(i=j=0; zFmt[i]; i++){
  15546. if( zFmt[i]!='%' ){
  15547. z[j++] = zFmt[i];
  15548. }else{
  15549. i++;
  15550. switch( zFmt[i] ){
  15551. case 'd': sqlite3_snprintf(3, &z[j],"%02d",x.D); j+=2; break;
  15552. case 'f': {
  15553. double s = x.s;
  15554. if( s>59.999 ) s = 59.999;
  15555. sqlite3_snprintf(7, &z[j],"%06.3f", s);
  15556. j += sqlite3Strlen30(&z[j]);
  15557. break;
  15558. }
  15559. case 'H': sqlite3_snprintf(3, &z[j],"%02d",x.h); j+=2; break;
  15560. case 'W': /* Fall thru */
  15561. case 'j': {
  15562. int nDay; /* Number of days since 1st day of year */
  15563. DateTime y = x;
  15564. y.validJD = 0;
  15565. y.M = 1;
  15566. y.D = 1;
  15567. computeJD(&y);
  15568. nDay = (int)((x.iJD-y.iJD+43200000)/86400000);
  15569. if( zFmt[i]=='W' ){
  15570. int wd; /* 0=Monday, 1=Tuesday, ... 6=Sunday */
  15571. wd = (int)(((x.iJD+43200000)/86400000)%7);
  15572. sqlite3_snprintf(3, &z[j],"%02d",(nDay+7-wd)/7);
  15573. j += 2;
  15574. }else{
  15575. sqlite3_snprintf(4, &z[j],"%03d",nDay+1);
  15576. j += 3;
  15577. }
  15578. break;
  15579. }
  15580. case 'J': {
  15581. sqlite3_snprintf(20, &z[j],"%.16g",x.iJD/86400000.0);
  15582. j+=sqlite3Strlen30(&z[j]);
  15583. break;
  15584. }
  15585. case 'm': sqlite3_snprintf(3, &z[j],"%02d",x.M); j+=2; break;
  15586. case 'M': sqlite3_snprintf(3, &z[j],"%02d",x.m); j+=2; break;
  15587. case 's': {
  15588. sqlite3_snprintf(30,&z[j],"%lld",
  15589. (i64)(x.iJD/1000 - 21086676*(i64)10000));
  15590. j += sqlite3Strlen30(&z[j]);
  15591. break;
  15592. }
  15593. case 'S': sqlite3_snprintf(3,&z[j],"%02d",(int)x.s); j+=2; break;
  15594. case 'w': {
  15595. z[j++] = (char)(((x.iJD+129600000)/86400000) % 7) + '0';
  15596. break;
  15597. }
  15598. case 'Y': {
  15599. sqlite3_snprintf(5,&z[j],"%04d",x.Y); j+=sqlite3Strlen30(&z[j]);
  15600. break;
  15601. }
  15602. default: z[j++] = '%'; break;
  15603. }
  15604. }
  15605. }
  15606. z[j] = 0;
  15607. sqlite3_result_text(context, z, -1,
  15608. z==zBuf ? SQLITE_TRANSIENT : SQLITE_DYNAMIC);
  15609. }
  15610. /*
  15611. ** current_time()
  15612. **
  15613. ** This function returns the same value as time('now').
  15614. */
  15615. static void ctimeFunc(
  15616. sqlite3_context *context,
  15617. int NotUsed,
  15618. sqlite3_value **NotUsed2
  15619. ){
  15620. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  15621. timeFunc(context, 0, 0);
  15622. }
  15623. /*
  15624. ** current_date()
  15625. **
  15626. ** This function returns the same value as date('now').
  15627. */
  15628. static void cdateFunc(
  15629. sqlite3_context *context,
  15630. int NotUsed,
  15631. sqlite3_value **NotUsed2
  15632. ){
  15633. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  15634. dateFunc(context, 0, 0);
  15635. }
  15636. /*
  15637. ** current_timestamp()
  15638. **
  15639. ** This function returns the same value as datetime('now').
  15640. */
  15641. static void ctimestampFunc(
  15642. sqlite3_context *context,
  15643. int NotUsed,
  15644. sqlite3_value **NotUsed2
  15645. ){
  15646. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  15647. datetimeFunc(context, 0, 0);
  15648. }
  15649. #endif /* !defined(SQLITE_OMIT_DATETIME_FUNCS) */
  15650. #ifdef SQLITE_OMIT_DATETIME_FUNCS
  15651. /*
  15652. ** If the library is compiled to omit the full-scale date and time
  15653. ** handling (to get a smaller binary), the following minimal version
  15654. ** of the functions current_time(), current_date() and current_timestamp()
  15655. ** are included instead. This is to support column declarations that
  15656. ** include "DEFAULT CURRENT_TIME" etc.
  15657. **
  15658. ** This function uses the C-library functions time(), gmtime()
  15659. ** and strftime(). The format string to pass to strftime() is supplied
  15660. ** as the user-data for the function.
  15661. */
  15662. static void currentTimeFunc(
  15663. sqlite3_context *context,
  15664. int argc,
  15665. sqlite3_value **argv
  15666. ){
  15667. time_t t;
  15668. char *zFormat = (char *)sqlite3_user_data(context);
  15669. sqlite3 *db;
  15670. sqlite3_int64 iT;
  15671. struct tm *pTm;
  15672. struct tm sNow;
  15673. char zBuf[20];
  15674. UNUSED_PARAMETER(argc);
  15675. UNUSED_PARAMETER(argv);
  15676. iT = sqlite3StmtCurrentTime(context);
  15677. if( iT<=0 ) return;
  15678. t = iT/1000 - 10000*(sqlite3_int64)21086676;
  15679. #if HAVE_GMTIME_R
  15680. pTm = gmtime_r(&t, &sNow);
  15681. #else
  15682. sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
  15683. pTm = gmtime(&t);
  15684. if( pTm ) memcpy(&sNow, pTm, sizeof(sNow));
  15685. sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
  15686. #endif
  15687. if( pTm ){
  15688. strftime(zBuf, 20, zFormat, &sNow);
  15689. sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
  15690. }
  15691. }
  15692. #endif
  15693. /*
  15694. ** This function registered all of the above C functions as SQL
  15695. ** functions. This should be the only routine in this file with
  15696. ** external linkage.
  15697. */
  15698. SQLITE_PRIVATE void sqlite3RegisterDateTimeFunctions(void){
  15699. static SQLITE_WSD FuncDef aDateTimeFuncs[] = {
  15700. #ifndef SQLITE_OMIT_DATETIME_FUNCS
  15701. FUNCTION(julianday, -1, 0, 0, juliandayFunc ),
  15702. FUNCTION(date, -1, 0, 0, dateFunc ),
  15703. FUNCTION(time, -1, 0, 0, timeFunc ),
  15704. FUNCTION(datetime, -1, 0, 0, datetimeFunc ),
  15705. FUNCTION(strftime, -1, 0, 0, strftimeFunc ),
  15706. FUNCTION(current_time, 0, 0, 0, ctimeFunc ),
  15707. FUNCTION(current_timestamp, 0, 0, 0, ctimestampFunc),
  15708. FUNCTION(current_date, 0, 0, 0, cdateFunc ),
  15709. #else
  15710. STR_FUNCTION(current_time, 0, "%H:%M:%S", 0, currentTimeFunc),
  15711. STR_FUNCTION(current_date, 0, "%Y-%m-%d", 0, currentTimeFunc),
  15712. STR_FUNCTION(current_timestamp, 0, "%Y-%m-%d %H:%M:%S", 0, currentTimeFunc),
  15713. #endif
  15714. };
  15715. int i;
  15716. FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
  15717. FuncDef *aFunc = (FuncDef*)&GLOBAL(FuncDef, aDateTimeFuncs);
  15718. for(i=0; i<ArraySize(aDateTimeFuncs); i++){
  15719. sqlite3FuncDefInsert(pHash, &aFunc[i]);
  15720. }
  15721. }
  15722. /************** End of date.c ************************************************/
  15723. /************** Begin file os.c **********************************************/
  15724. /*
  15725. ** 2005 November 29
  15726. **
  15727. ** The author disclaims copyright to this source code. In place of
  15728. ** a legal notice, here is a blessing:
  15729. **
  15730. ** May you do good and not evil.
  15731. ** May you find forgiveness for yourself and forgive others.
  15732. ** May you share freely, never taking more than you give.
  15733. **
  15734. ******************************************************************************
  15735. **
  15736. ** This file contains OS interface code that is common to all
  15737. ** architectures.
  15738. */
  15739. #define _SQLITE_OS_C_ 1
  15740. #undef _SQLITE_OS_C_
  15741. /*
  15742. ** The default SQLite sqlite3_vfs implementations do not allocate
  15743. ** memory (actually, os_unix.c allocates a small amount of memory
  15744. ** from within OsOpen()), but some third-party implementations may.
  15745. ** So we test the effects of a malloc() failing and the sqlite3OsXXX()
  15746. ** function returning SQLITE_IOERR_NOMEM using the DO_OS_MALLOC_TEST macro.
  15747. **
  15748. ** The following functions are instrumented for malloc() failure
  15749. ** testing:
  15750. **
  15751. ** sqlite3OsRead()
  15752. ** sqlite3OsWrite()
  15753. ** sqlite3OsSync()
  15754. ** sqlite3OsFileSize()
  15755. ** sqlite3OsLock()
  15756. ** sqlite3OsCheckReservedLock()
  15757. ** sqlite3OsFileControl()
  15758. ** sqlite3OsShmMap()
  15759. ** sqlite3OsOpen()
  15760. ** sqlite3OsDelete()
  15761. ** sqlite3OsAccess()
  15762. ** sqlite3OsFullPathname()
  15763. **
  15764. */
  15765. #if defined(SQLITE_TEST)
  15766. SQLITE_API int sqlite3_memdebug_vfs_oom_test = 1;
  15767. #define DO_OS_MALLOC_TEST(x) \
  15768. if (sqlite3_memdebug_vfs_oom_test && (!x || !sqlite3IsMemJournal(x))) { \
  15769. void *pTstAlloc = sqlite3Malloc(10); \
  15770. if (!pTstAlloc) return SQLITE_IOERR_NOMEM; \
  15771. sqlite3_free(pTstAlloc); \
  15772. }
  15773. #else
  15774. #define DO_OS_MALLOC_TEST(x)
  15775. #endif
  15776. /*
  15777. ** The following routines are convenience wrappers around methods
  15778. ** of the sqlite3_file object. This is mostly just syntactic sugar. All
  15779. ** of this would be completely automatic if SQLite were coded using
  15780. ** C++ instead of plain old C.
  15781. */
  15782. SQLITE_PRIVATE int sqlite3OsClose(sqlite3_file *pId){
  15783. int rc = SQLITE_OK;
  15784. if( pId->pMethods ){
  15785. rc = pId->pMethods->xClose(pId);
  15786. pId->pMethods = 0;
  15787. }
  15788. return rc;
  15789. }
  15790. SQLITE_PRIVATE int sqlite3OsRead(sqlite3_file *id, void *pBuf, int amt, i64 offset){
  15791. DO_OS_MALLOC_TEST(id);
  15792. return id->pMethods->xRead(id, pBuf, amt, offset);
  15793. }
  15794. SQLITE_PRIVATE int sqlite3OsWrite(sqlite3_file *id, const void *pBuf, int amt, i64 offset){
  15795. DO_OS_MALLOC_TEST(id);
  15796. return id->pMethods->xWrite(id, pBuf, amt, offset);
  15797. }
  15798. SQLITE_PRIVATE int sqlite3OsTruncate(sqlite3_file *id, i64 size){
  15799. return id->pMethods->xTruncate(id, size);
  15800. }
  15801. SQLITE_PRIVATE int sqlite3OsSync(sqlite3_file *id, int flags){
  15802. DO_OS_MALLOC_TEST(id);
  15803. return id->pMethods->xSync(id, flags);
  15804. }
  15805. SQLITE_PRIVATE int sqlite3OsFileSize(sqlite3_file *id, i64 *pSize){
  15806. DO_OS_MALLOC_TEST(id);
  15807. return id->pMethods->xFileSize(id, pSize);
  15808. }
  15809. SQLITE_PRIVATE int sqlite3OsLock(sqlite3_file *id, int lockType){
  15810. DO_OS_MALLOC_TEST(id);
  15811. return id->pMethods->xLock(id, lockType);
  15812. }
  15813. SQLITE_PRIVATE int sqlite3OsUnlock(sqlite3_file *id, int lockType){
  15814. return id->pMethods->xUnlock(id, lockType);
  15815. }
  15816. SQLITE_PRIVATE int sqlite3OsCheckReservedLock(sqlite3_file *id, int *pResOut){
  15817. DO_OS_MALLOC_TEST(id);
  15818. return id->pMethods->xCheckReservedLock(id, pResOut);
  15819. }
  15820. /*
  15821. ** Use sqlite3OsFileControl() when we are doing something that might fail
  15822. ** and we need to know about the failures. Use sqlite3OsFileControlHint()
  15823. ** when simply tossing information over the wall to the VFS and we do not
  15824. ** really care if the VFS receives and understands the information since it
  15825. ** is only a hint and can be safely ignored. The sqlite3OsFileControlHint()
  15826. ** routine has no return value since the return value would be meaningless.
  15827. */
  15828. SQLITE_PRIVATE int sqlite3OsFileControl(sqlite3_file *id, int op, void *pArg){
  15829. #ifdef SQLITE_TEST
  15830. if( op!=SQLITE_FCNTL_COMMIT_PHASETWO ){
  15831. /* Faults are not injected into COMMIT_PHASETWO because, assuming SQLite
  15832. ** is using a regular VFS, it is called after the corresponding
  15833. ** transaction has been committed. Injecting a fault at this point
  15834. ** confuses the test scripts - the COMMIT comand returns SQLITE_NOMEM
  15835. ** but the transaction is committed anyway.
  15836. **
  15837. ** The core must call OsFileControl() though, not OsFileControlHint(),
  15838. ** as if a custom VFS (e.g. zipvfs) returns an error here, it probably
  15839. ** means the commit really has failed and an error should be returned
  15840. ** to the user. */
  15841. DO_OS_MALLOC_TEST(id);
  15842. }
  15843. #endif
  15844. return id->pMethods->xFileControl(id, op, pArg);
  15845. }
  15846. SQLITE_PRIVATE void sqlite3OsFileControlHint(sqlite3_file *id, int op, void *pArg){
  15847. (void)id->pMethods->xFileControl(id, op, pArg);
  15848. }
  15849. SQLITE_PRIVATE int sqlite3OsSectorSize(sqlite3_file *id){
  15850. int (*xSectorSize)(sqlite3_file*) = id->pMethods->xSectorSize;
  15851. return (xSectorSize ? xSectorSize(id) : SQLITE_DEFAULT_SECTOR_SIZE);
  15852. }
  15853. SQLITE_PRIVATE int sqlite3OsDeviceCharacteristics(sqlite3_file *id){
  15854. return id->pMethods->xDeviceCharacteristics(id);
  15855. }
  15856. SQLITE_PRIVATE int sqlite3OsShmLock(sqlite3_file *id, int offset, int n, int flags){
  15857. return id->pMethods->xShmLock(id, offset, n, flags);
  15858. }
  15859. SQLITE_PRIVATE void sqlite3OsShmBarrier(sqlite3_file *id){
  15860. id->pMethods->xShmBarrier(id);
  15861. }
  15862. SQLITE_PRIVATE int sqlite3OsShmUnmap(sqlite3_file *id, int deleteFlag){
  15863. return id->pMethods->xShmUnmap(id, deleteFlag);
  15864. }
  15865. SQLITE_PRIVATE int sqlite3OsShmMap(
  15866. sqlite3_file *id, /* Database file handle */
  15867. int iPage,
  15868. int pgsz,
  15869. int bExtend, /* True to extend file if necessary */
  15870. void volatile **pp /* OUT: Pointer to mapping */
  15871. ){
  15872. DO_OS_MALLOC_TEST(id);
  15873. return id->pMethods->xShmMap(id, iPage, pgsz, bExtend, pp);
  15874. }
  15875. #if SQLITE_MAX_MMAP_SIZE>0
  15876. /* The real implementation of xFetch and xUnfetch */
  15877. SQLITE_PRIVATE int sqlite3OsFetch(sqlite3_file *id, i64 iOff, int iAmt, void **pp){
  15878. DO_OS_MALLOC_TEST(id);
  15879. return id->pMethods->xFetch(id, iOff, iAmt, pp);
  15880. }
  15881. SQLITE_PRIVATE int sqlite3OsUnfetch(sqlite3_file *id, i64 iOff, void *p){
  15882. return id->pMethods->xUnfetch(id, iOff, p);
  15883. }
  15884. #else
  15885. /* No-op stubs to use when memory-mapped I/O is disabled */
  15886. SQLITE_PRIVATE int sqlite3OsFetch(sqlite3_file *id, i64 iOff, int iAmt, void **pp){
  15887. *pp = 0;
  15888. return SQLITE_OK;
  15889. }
  15890. SQLITE_PRIVATE int sqlite3OsUnfetch(sqlite3_file *id, i64 iOff, void *p){
  15891. return SQLITE_OK;
  15892. }
  15893. #endif
  15894. /*
  15895. ** The next group of routines are convenience wrappers around the
  15896. ** VFS methods.
  15897. */
  15898. SQLITE_PRIVATE int sqlite3OsOpen(
  15899. sqlite3_vfs *pVfs,
  15900. const char *zPath,
  15901. sqlite3_file *pFile,
  15902. int flags,
  15903. int *pFlagsOut
  15904. ){
  15905. int rc;
  15906. DO_OS_MALLOC_TEST(0);
  15907. /* 0x87f7f is a mask of SQLITE_OPEN_ flags that are valid to be passed
  15908. ** down into the VFS layer. Some SQLITE_OPEN_ flags (for example,
  15909. ** SQLITE_OPEN_FULLMUTEX or SQLITE_OPEN_SHAREDCACHE) are blocked before
  15910. ** reaching the VFS. */
  15911. rc = pVfs->xOpen(pVfs, zPath, pFile, flags & 0x87f7f, pFlagsOut);
  15912. assert( rc==SQLITE_OK || pFile->pMethods==0 );
  15913. return rc;
  15914. }
  15915. SQLITE_PRIVATE int sqlite3OsDelete(sqlite3_vfs *pVfs, const char *zPath, int dirSync){
  15916. DO_OS_MALLOC_TEST(0);
  15917. assert( dirSync==0 || dirSync==1 );
  15918. return pVfs->xDelete(pVfs, zPath, dirSync);
  15919. }
  15920. SQLITE_PRIVATE int sqlite3OsAccess(
  15921. sqlite3_vfs *pVfs,
  15922. const char *zPath,
  15923. int flags,
  15924. int *pResOut
  15925. ){
  15926. DO_OS_MALLOC_TEST(0);
  15927. return pVfs->xAccess(pVfs, zPath, flags, pResOut);
  15928. }
  15929. SQLITE_PRIVATE int sqlite3OsFullPathname(
  15930. sqlite3_vfs *pVfs,
  15931. const char *zPath,
  15932. int nPathOut,
  15933. char *zPathOut
  15934. ){
  15935. DO_OS_MALLOC_TEST(0);
  15936. zPathOut[0] = 0;
  15937. return pVfs->xFullPathname(pVfs, zPath, nPathOut, zPathOut);
  15938. }
  15939. #ifndef SQLITE_OMIT_LOAD_EXTENSION
  15940. SQLITE_PRIVATE void *sqlite3OsDlOpen(sqlite3_vfs *pVfs, const char *zPath){
  15941. return pVfs->xDlOpen(pVfs, zPath);
  15942. }
  15943. SQLITE_PRIVATE void sqlite3OsDlError(sqlite3_vfs *pVfs, int nByte, char *zBufOut){
  15944. pVfs->xDlError(pVfs, nByte, zBufOut);
  15945. }
  15946. SQLITE_PRIVATE void (*sqlite3OsDlSym(sqlite3_vfs *pVfs, void *pHdle, const char *zSym))(void){
  15947. return pVfs->xDlSym(pVfs, pHdle, zSym);
  15948. }
  15949. SQLITE_PRIVATE void sqlite3OsDlClose(sqlite3_vfs *pVfs, void *pHandle){
  15950. pVfs->xDlClose(pVfs, pHandle);
  15951. }
  15952. #endif /* SQLITE_OMIT_LOAD_EXTENSION */
  15953. SQLITE_PRIVATE int sqlite3OsRandomness(sqlite3_vfs *pVfs, int nByte, char *zBufOut){
  15954. return pVfs->xRandomness(pVfs, nByte, zBufOut);
  15955. }
  15956. SQLITE_PRIVATE int sqlite3OsSleep(sqlite3_vfs *pVfs, int nMicro){
  15957. return pVfs->xSleep(pVfs, nMicro);
  15958. }
  15959. SQLITE_PRIVATE int sqlite3OsCurrentTimeInt64(sqlite3_vfs *pVfs, sqlite3_int64 *pTimeOut){
  15960. int rc;
  15961. /* IMPLEMENTATION-OF: R-49045-42493 SQLite will use the xCurrentTimeInt64()
  15962. ** method to get the current date and time if that method is available
  15963. ** (if iVersion is 2 or greater and the function pointer is not NULL) and
  15964. ** will fall back to xCurrentTime() if xCurrentTimeInt64() is
  15965. ** unavailable.
  15966. */
  15967. if( pVfs->iVersion>=2 && pVfs->xCurrentTimeInt64 ){
  15968. rc = pVfs->xCurrentTimeInt64(pVfs, pTimeOut);
  15969. }else{
  15970. double r;
  15971. rc = pVfs->xCurrentTime(pVfs, &r);
  15972. *pTimeOut = (sqlite3_int64)(r*86400000.0);
  15973. }
  15974. return rc;
  15975. }
  15976. SQLITE_PRIVATE int sqlite3OsOpenMalloc(
  15977. sqlite3_vfs *pVfs,
  15978. const char *zFile,
  15979. sqlite3_file **ppFile,
  15980. int flags,
  15981. int *pOutFlags
  15982. ){
  15983. int rc = SQLITE_NOMEM;
  15984. sqlite3_file *pFile;
  15985. pFile = (sqlite3_file *)sqlite3MallocZero(pVfs->szOsFile);
  15986. if( pFile ){
  15987. rc = sqlite3OsOpen(pVfs, zFile, pFile, flags, pOutFlags);
  15988. if( rc!=SQLITE_OK ){
  15989. sqlite3_free(pFile);
  15990. }else{
  15991. *ppFile = pFile;
  15992. }
  15993. }
  15994. return rc;
  15995. }
  15996. SQLITE_PRIVATE int sqlite3OsCloseFree(sqlite3_file *pFile){
  15997. int rc = SQLITE_OK;
  15998. assert( pFile );
  15999. rc = sqlite3OsClose(pFile);
  16000. sqlite3_free(pFile);
  16001. return rc;
  16002. }
  16003. /*
  16004. ** This function is a wrapper around the OS specific implementation of
  16005. ** sqlite3_os_init(). The purpose of the wrapper is to provide the
  16006. ** ability to simulate a malloc failure, so that the handling of an
  16007. ** error in sqlite3_os_init() by the upper layers can be tested.
  16008. */
  16009. SQLITE_PRIVATE int sqlite3OsInit(void){
  16010. void *p = sqlite3_malloc(10);
  16011. if( p==0 ) return SQLITE_NOMEM;
  16012. sqlite3_free(p);
  16013. return sqlite3_os_init();
  16014. }
  16015. /*
  16016. ** The list of all registered VFS implementations.
  16017. */
  16018. static sqlite3_vfs * SQLITE_WSD vfsList = 0;
  16019. #define vfsList GLOBAL(sqlite3_vfs *, vfsList)
  16020. /*
  16021. ** Locate a VFS by name. If no name is given, simply return the
  16022. ** first VFS on the list.
  16023. */
  16024. SQLITE_API sqlite3_vfs *SQLITE_STDCALL sqlite3_vfs_find(const char *zVfs){
  16025. sqlite3_vfs *pVfs = 0;
  16026. #if SQLITE_THREADSAFE
  16027. sqlite3_mutex *mutex;
  16028. #endif
  16029. #ifndef SQLITE_OMIT_AUTOINIT
  16030. int rc = sqlite3_initialize();
  16031. if( rc ) return 0;
  16032. #endif
  16033. #if SQLITE_THREADSAFE
  16034. mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
  16035. #endif
  16036. sqlite3_mutex_enter(mutex);
  16037. for(pVfs = vfsList; pVfs; pVfs=pVfs->pNext){
  16038. if( zVfs==0 ) break;
  16039. if( strcmp(zVfs, pVfs->zName)==0 ) break;
  16040. }
  16041. sqlite3_mutex_leave(mutex);
  16042. return pVfs;
  16043. }
  16044. /*
  16045. ** Unlink a VFS from the linked list
  16046. */
  16047. static void vfsUnlink(sqlite3_vfs *pVfs){
  16048. assert( sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER)) );
  16049. if( pVfs==0 ){
  16050. /* No-op */
  16051. }else if( vfsList==pVfs ){
  16052. vfsList = pVfs->pNext;
  16053. }else if( vfsList ){
  16054. sqlite3_vfs *p = vfsList;
  16055. while( p->pNext && p->pNext!=pVfs ){
  16056. p = p->pNext;
  16057. }
  16058. if( p->pNext==pVfs ){
  16059. p->pNext = pVfs->pNext;
  16060. }
  16061. }
  16062. }
  16063. /*
  16064. ** Register a VFS with the system. It is harmless to register the same
  16065. ** VFS multiple times. The new VFS becomes the default if makeDflt is
  16066. ** true.
  16067. */
  16068. SQLITE_API int SQLITE_STDCALL sqlite3_vfs_register(sqlite3_vfs *pVfs, int makeDflt){
  16069. MUTEX_LOGIC(sqlite3_mutex *mutex;)
  16070. #ifndef SQLITE_OMIT_AUTOINIT
  16071. int rc = sqlite3_initialize();
  16072. if( rc ) return rc;
  16073. #endif
  16074. #ifdef SQLITE_ENABLE_API_ARMOR
  16075. if( pVfs==0 ) return SQLITE_MISUSE_BKPT;
  16076. #endif
  16077. MUTEX_LOGIC( mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); )
  16078. sqlite3_mutex_enter(mutex);
  16079. vfsUnlink(pVfs);
  16080. if( makeDflt || vfsList==0 ){
  16081. pVfs->pNext = vfsList;
  16082. vfsList = pVfs;
  16083. }else{
  16084. pVfs->pNext = vfsList->pNext;
  16085. vfsList->pNext = pVfs;
  16086. }
  16087. assert(vfsList);
  16088. sqlite3_mutex_leave(mutex);
  16089. return SQLITE_OK;
  16090. }
  16091. /*
  16092. ** Unregister a VFS so that it is no longer accessible.
  16093. */
  16094. SQLITE_API int SQLITE_STDCALL sqlite3_vfs_unregister(sqlite3_vfs *pVfs){
  16095. #if SQLITE_THREADSAFE
  16096. sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
  16097. #endif
  16098. sqlite3_mutex_enter(mutex);
  16099. vfsUnlink(pVfs);
  16100. sqlite3_mutex_leave(mutex);
  16101. return SQLITE_OK;
  16102. }
  16103. /************** End of os.c **************************************************/
  16104. /************** Begin file fault.c *******************************************/
  16105. /*
  16106. ** 2008 Jan 22
  16107. **
  16108. ** The author disclaims copyright to this source code. In place of
  16109. ** a legal notice, here is a blessing:
  16110. **
  16111. ** May you do good and not evil.
  16112. ** May you find forgiveness for yourself and forgive others.
  16113. ** May you share freely, never taking more than you give.
  16114. **
  16115. *************************************************************************
  16116. **
  16117. ** This file contains code to support the concept of "benign"
  16118. ** malloc failures (when the xMalloc() or xRealloc() method of the
  16119. ** sqlite3_mem_methods structure fails to allocate a block of memory
  16120. ** and returns 0).
  16121. **
  16122. ** Most malloc failures are non-benign. After they occur, SQLite
  16123. ** abandons the current operation and returns an error code (usually
  16124. ** SQLITE_NOMEM) to the user. However, sometimes a fault is not necessarily
  16125. ** fatal. For example, if a malloc fails while resizing a hash table, this
  16126. ** is completely recoverable simply by not carrying out the resize. The
  16127. ** hash table will continue to function normally. So a malloc failure
  16128. ** during a hash table resize is a benign fault.
  16129. */
  16130. #ifndef SQLITE_OMIT_BUILTIN_TEST
  16131. /*
  16132. ** Global variables.
  16133. */
  16134. typedef struct BenignMallocHooks BenignMallocHooks;
  16135. static SQLITE_WSD struct BenignMallocHooks {
  16136. void (*xBenignBegin)(void);
  16137. void (*xBenignEnd)(void);
  16138. } sqlite3Hooks = { 0, 0 };
  16139. /* The "wsdHooks" macro will resolve to the appropriate BenignMallocHooks
  16140. ** structure. If writable static data is unsupported on the target,
  16141. ** we have to locate the state vector at run-time. In the more common
  16142. ** case where writable static data is supported, wsdHooks can refer directly
  16143. ** to the "sqlite3Hooks" state vector declared above.
  16144. */
  16145. #ifdef SQLITE_OMIT_WSD
  16146. # define wsdHooksInit \
  16147. BenignMallocHooks *x = &GLOBAL(BenignMallocHooks,sqlite3Hooks)
  16148. # define wsdHooks x[0]
  16149. #else
  16150. # define wsdHooksInit
  16151. # define wsdHooks sqlite3Hooks
  16152. #endif
  16153. /*
  16154. ** Register hooks to call when sqlite3BeginBenignMalloc() and
  16155. ** sqlite3EndBenignMalloc() are called, respectively.
  16156. */
  16157. SQLITE_PRIVATE void sqlite3BenignMallocHooks(
  16158. void (*xBenignBegin)(void),
  16159. void (*xBenignEnd)(void)
  16160. ){
  16161. wsdHooksInit;
  16162. wsdHooks.xBenignBegin = xBenignBegin;
  16163. wsdHooks.xBenignEnd = xBenignEnd;
  16164. }
  16165. /*
  16166. ** This (sqlite3EndBenignMalloc()) is called by SQLite code to indicate that
  16167. ** subsequent malloc failures are benign. A call to sqlite3EndBenignMalloc()
  16168. ** indicates that subsequent malloc failures are non-benign.
  16169. */
  16170. SQLITE_PRIVATE void sqlite3BeginBenignMalloc(void){
  16171. wsdHooksInit;
  16172. if( wsdHooks.xBenignBegin ){
  16173. wsdHooks.xBenignBegin();
  16174. }
  16175. }
  16176. SQLITE_PRIVATE void sqlite3EndBenignMalloc(void){
  16177. wsdHooksInit;
  16178. if( wsdHooks.xBenignEnd ){
  16179. wsdHooks.xBenignEnd();
  16180. }
  16181. }
  16182. #endif /* #ifndef SQLITE_OMIT_BUILTIN_TEST */
  16183. /************** End of fault.c ***********************************************/
  16184. /************** Begin file mem0.c ********************************************/
  16185. /*
  16186. ** 2008 October 28
  16187. **
  16188. ** The author disclaims copyright to this source code. In place of
  16189. ** a legal notice, here is a blessing:
  16190. **
  16191. ** May you do good and not evil.
  16192. ** May you find forgiveness for yourself and forgive others.
  16193. ** May you share freely, never taking more than you give.
  16194. **
  16195. *************************************************************************
  16196. **
  16197. ** This file contains a no-op memory allocation drivers for use when
  16198. ** SQLITE_ZERO_MALLOC is defined. The allocation drivers implemented
  16199. ** here always fail. SQLite will not operate with these drivers. These
  16200. ** are merely placeholders. Real drivers must be substituted using
  16201. ** sqlite3_config() before SQLite will operate.
  16202. */
  16203. /*
  16204. ** This version of the memory allocator is the default. It is
  16205. ** used when no other memory allocator is specified using compile-time
  16206. ** macros.
  16207. */
  16208. #ifdef SQLITE_ZERO_MALLOC
  16209. /*
  16210. ** No-op versions of all memory allocation routines
  16211. */
  16212. static void *sqlite3MemMalloc(int nByte){ return 0; }
  16213. static void sqlite3MemFree(void *pPrior){ return; }
  16214. static void *sqlite3MemRealloc(void *pPrior, int nByte){ return 0; }
  16215. static int sqlite3MemSize(void *pPrior){ return 0; }
  16216. static int sqlite3MemRoundup(int n){ return n; }
  16217. static int sqlite3MemInit(void *NotUsed){ return SQLITE_OK; }
  16218. static void sqlite3MemShutdown(void *NotUsed){ return; }
  16219. /*
  16220. ** This routine is the only routine in this file with external linkage.
  16221. **
  16222. ** Populate the low-level memory allocation function pointers in
  16223. ** sqlite3GlobalConfig.m with pointers to the routines in this file.
  16224. */
  16225. SQLITE_PRIVATE void sqlite3MemSetDefault(void){
  16226. static const sqlite3_mem_methods defaultMethods = {
  16227. sqlite3MemMalloc,
  16228. sqlite3MemFree,
  16229. sqlite3MemRealloc,
  16230. sqlite3MemSize,
  16231. sqlite3MemRoundup,
  16232. sqlite3MemInit,
  16233. sqlite3MemShutdown,
  16234. 0
  16235. };
  16236. sqlite3_config(SQLITE_CONFIG_MALLOC, &defaultMethods);
  16237. }
  16238. #endif /* SQLITE_ZERO_MALLOC */
  16239. /************** End of mem0.c ************************************************/
  16240. /************** Begin file mem1.c ********************************************/
  16241. /*
  16242. ** 2007 August 14
  16243. **
  16244. ** The author disclaims copyright to this source code. In place of
  16245. ** a legal notice, here is a blessing:
  16246. **
  16247. ** May you do good and not evil.
  16248. ** May you find forgiveness for yourself and forgive others.
  16249. ** May you share freely, never taking more than you give.
  16250. **
  16251. *************************************************************************
  16252. **
  16253. ** This file contains low-level memory allocation drivers for when
  16254. ** SQLite will use the standard C-library malloc/realloc/free interface
  16255. ** to obtain the memory it needs.
  16256. **
  16257. ** This file contains implementations of the low-level memory allocation
  16258. ** routines specified in the sqlite3_mem_methods object. The content of
  16259. ** this file is only used if SQLITE_SYSTEM_MALLOC is defined. The
  16260. ** SQLITE_SYSTEM_MALLOC macro is defined automatically if neither the
  16261. ** SQLITE_MEMDEBUG nor the SQLITE_WIN32_MALLOC macros are defined. The
  16262. ** default configuration is to use memory allocation routines in this
  16263. ** file.
  16264. **
  16265. ** C-preprocessor macro summary:
  16266. **
  16267. ** HAVE_MALLOC_USABLE_SIZE The configure script sets this symbol if
  16268. ** the malloc_usable_size() interface exists
  16269. ** on the target platform. Or, this symbol
  16270. ** can be set manually, if desired.
  16271. ** If an equivalent interface exists by
  16272. ** a different name, using a separate -D
  16273. ** option to rename it.
  16274. **
  16275. ** SQLITE_WITHOUT_ZONEMALLOC Some older macs lack support for the zone
  16276. ** memory allocator. Set this symbol to enable
  16277. ** building on older macs.
  16278. **
  16279. ** SQLITE_WITHOUT_MSIZE Set this symbol to disable the use of
  16280. ** _msize() on windows systems. This might
  16281. ** be necessary when compiling for Delphi,
  16282. ** for example.
  16283. */
  16284. /*
  16285. ** This version of the memory allocator is the default. It is
  16286. ** used when no other memory allocator is specified using compile-time
  16287. ** macros.
  16288. */
  16289. #ifdef SQLITE_SYSTEM_MALLOC
  16290. #if defined(__APPLE__) && !defined(SQLITE_WITHOUT_ZONEMALLOC)
  16291. /*
  16292. ** Use the zone allocator available on apple products unless the
  16293. ** SQLITE_WITHOUT_ZONEMALLOC symbol is defined.
  16294. */
  16295. #include <sys/sysctl.h>
  16296. #include <malloc/malloc.h>
  16297. #include <libkern/OSAtomic.h>
  16298. static malloc_zone_t* _sqliteZone_;
  16299. #define SQLITE_MALLOC(x) malloc_zone_malloc(_sqliteZone_, (x))
  16300. #define SQLITE_FREE(x) malloc_zone_free(_sqliteZone_, (x));
  16301. #define SQLITE_REALLOC(x,y) malloc_zone_realloc(_sqliteZone_, (x), (y))
  16302. #define SQLITE_MALLOCSIZE(x) \
  16303. (_sqliteZone_ ? _sqliteZone_->size(_sqliteZone_,x) : malloc_size(x))
  16304. #else /* if not __APPLE__ */
  16305. /*
  16306. ** Use standard C library malloc and free on non-Apple systems.
  16307. ** Also used by Apple systems if SQLITE_WITHOUT_ZONEMALLOC is defined.
  16308. */
  16309. #define SQLITE_MALLOC(x) malloc(x)
  16310. #define SQLITE_FREE(x) free(x)
  16311. #define SQLITE_REALLOC(x,y) realloc((x),(y))
  16312. /*
  16313. ** The malloc.h header file is needed for malloc_usable_size() function
  16314. ** on some systems (e.g. Linux).
  16315. */
  16316. #if HAVE_MALLOC_H && HAVE_MALLOC_USABLE_SIZE
  16317. # define SQLITE_USE_MALLOC_H 1
  16318. # define SQLITE_USE_MALLOC_USABLE_SIZE 1
  16319. /*
  16320. ** The MSVCRT has malloc_usable_size(), but it is called _msize(). The
  16321. ** use of _msize() is automatic, but can be disabled by compiling with
  16322. ** -DSQLITE_WITHOUT_MSIZE. Using the _msize() function also requires
  16323. ** the malloc.h header file.
  16324. */
  16325. #elif defined(_MSC_VER) && !defined(SQLITE_WITHOUT_MSIZE)
  16326. # define SQLITE_USE_MALLOC_H
  16327. # define SQLITE_USE_MSIZE
  16328. #endif
  16329. /*
  16330. ** Include the malloc.h header file, if necessary. Also set define macro
  16331. ** SQLITE_MALLOCSIZE to the appropriate function name, which is _msize()
  16332. ** for MSVC and malloc_usable_size() for most other systems (e.g. Linux).
  16333. ** The memory size function can always be overridden manually by defining
  16334. ** the macro SQLITE_MALLOCSIZE to the desired function name.
  16335. */
  16336. #if defined(SQLITE_USE_MALLOC_H)
  16337. # include <malloc.h>
  16338. # if defined(SQLITE_USE_MALLOC_USABLE_SIZE)
  16339. # if !defined(SQLITE_MALLOCSIZE)
  16340. # define SQLITE_MALLOCSIZE(x) malloc_usable_size(x)
  16341. # endif
  16342. # elif defined(SQLITE_USE_MSIZE)
  16343. # if !defined(SQLITE_MALLOCSIZE)
  16344. # define SQLITE_MALLOCSIZE _msize
  16345. # endif
  16346. # endif
  16347. #endif /* defined(SQLITE_USE_MALLOC_H) */
  16348. #endif /* __APPLE__ or not __APPLE__ */
  16349. /*
  16350. ** Like malloc(), but remember the size of the allocation
  16351. ** so that we can find it later using sqlite3MemSize().
  16352. **
  16353. ** For this low-level routine, we are guaranteed that nByte>0 because
  16354. ** cases of nByte<=0 will be intercepted and dealt with by higher level
  16355. ** routines.
  16356. */
  16357. static void *sqlite3MemMalloc(int nByte){
  16358. #ifdef SQLITE_MALLOCSIZE
  16359. void *p = SQLITE_MALLOC( nByte );
  16360. if( p==0 ){
  16361. testcase( sqlite3GlobalConfig.xLog!=0 );
  16362. sqlite3_log(SQLITE_NOMEM, "failed to allocate %u bytes of memory", nByte);
  16363. }
  16364. return p;
  16365. #else
  16366. sqlite3_int64 *p;
  16367. assert( nByte>0 );
  16368. nByte = ROUND8(nByte);
  16369. p = SQLITE_MALLOC( nByte+8 );
  16370. if( p ){
  16371. p[0] = nByte;
  16372. p++;
  16373. }else{
  16374. testcase( sqlite3GlobalConfig.xLog!=0 );
  16375. sqlite3_log(SQLITE_NOMEM, "failed to allocate %u bytes of memory", nByte);
  16376. }
  16377. return (void *)p;
  16378. #endif
  16379. }
  16380. /*
  16381. ** Like free() but works for allocations obtained from sqlite3MemMalloc()
  16382. ** or sqlite3MemRealloc().
  16383. **
  16384. ** For this low-level routine, we already know that pPrior!=0 since
  16385. ** cases where pPrior==0 will have been intecepted and dealt with
  16386. ** by higher-level routines.
  16387. */
  16388. static void sqlite3MemFree(void *pPrior){
  16389. #ifdef SQLITE_MALLOCSIZE
  16390. SQLITE_FREE(pPrior);
  16391. #else
  16392. sqlite3_int64 *p = (sqlite3_int64*)pPrior;
  16393. assert( pPrior!=0 );
  16394. p--;
  16395. SQLITE_FREE(p);
  16396. #endif
  16397. }
  16398. /*
  16399. ** Report the allocated size of a prior return from xMalloc()
  16400. ** or xRealloc().
  16401. */
  16402. static int sqlite3MemSize(void *pPrior){
  16403. #ifdef SQLITE_MALLOCSIZE
  16404. return pPrior ? (int)SQLITE_MALLOCSIZE(pPrior) : 0;
  16405. #else
  16406. sqlite3_int64 *p;
  16407. if( pPrior==0 ) return 0;
  16408. p = (sqlite3_int64*)pPrior;
  16409. p--;
  16410. return (int)p[0];
  16411. #endif
  16412. }
  16413. /*
  16414. ** Like realloc(). Resize an allocation previously obtained from
  16415. ** sqlite3MemMalloc().
  16416. **
  16417. ** For this low-level interface, we know that pPrior!=0. Cases where
  16418. ** pPrior==0 while have been intercepted by higher-level routine and
  16419. ** redirected to xMalloc. Similarly, we know that nByte>0 because
  16420. ** cases where nByte<=0 will have been intercepted by higher-level
  16421. ** routines and redirected to xFree.
  16422. */
  16423. static void *sqlite3MemRealloc(void *pPrior, int nByte){
  16424. #ifdef SQLITE_MALLOCSIZE
  16425. void *p = SQLITE_REALLOC(pPrior, nByte);
  16426. if( p==0 ){
  16427. testcase( sqlite3GlobalConfig.xLog!=0 );
  16428. sqlite3_log(SQLITE_NOMEM,
  16429. "failed memory resize %u to %u bytes",
  16430. SQLITE_MALLOCSIZE(pPrior), nByte);
  16431. }
  16432. return p;
  16433. #else
  16434. sqlite3_int64 *p = (sqlite3_int64*)pPrior;
  16435. assert( pPrior!=0 && nByte>0 );
  16436. assert( nByte==ROUND8(nByte) ); /* EV: R-46199-30249 */
  16437. p--;
  16438. p = SQLITE_REALLOC(p, nByte+8 );
  16439. if( p ){
  16440. p[0] = nByte;
  16441. p++;
  16442. }else{
  16443. testcase( sqlite3GlobalConfig.xLog!=0 );
  16444. sqlite3_log(SQLITE_NOMEM,
  16445. "failed memory resize %u to %u bytes",
  16446. sqlite3MemSize(pPrior), nByte);
  16447. }
  16448. return (void*)p;
  16449. #endif
  16450. }
  16451. /*
  16452. ** Round up a request size to the next valid allocation size.
  16453. */
  16454. static int sqlite3MemRoundup(int n){
  16455. return ROUND8(n);
  16456. }
  16457. /*
  16458. ** Initialize this module.
  16459. */
  16460. static int sqlite3MemInit(void *NotUsed){
  16461. #if defined(__APPLE__) && !defined(SQLITE_WITHOUT_ZONEMALLOC)
  16462. int cpuCount;
  16463. size_t len;
  16464. if( _sqliteZone_ ){
  16465. return SQLITE_OK;
  16466. }
  16467. len = sizeof(cpuCount);
  16468. /* One usually wants to use hw.acctivecpu for MT decisions, but not here */
  16469. sysctlbyname("hw.ncpu", &cpuCount, &len, NULL, 0);
  16470. if( cpuCount>1 ){
  16471. /* defer MT decisions to system malloc */
  16472. _sqliteZone_ = malloc_default_zone();
  16473. }else{
  16474. /* only 1 core, use our own zone to contention over global locks,
  16475. ** e.g. we have our own dedicated locks */
  16476. bool success;
  16477. malloc_zone_t* newzone = malloc_create_zone(4096, 0);
  16478. malloc_set_zone_name(newzone, "Sqlite_Heap");
  16479. do{
  16480. success = OSAtomicCompareAndSwapPtrBarrier(NULL, newzone,
  16481. (void * volatile *)&_sqliteZone_);
  16482. }while(!_sqliteZone_);
  16483. if( !success ){
  16484. /* somebody registered a zone first */
  16485. malloc_destroy_zone(newzone);
  16486. }
  16487. }
  16488. #endif
  16489. UNUSED_PARAMETER(NotUsed);
  16490. return SQLITE_OK;
  16491. }
  16492. /*
  16493. ** Deinitialize this module.
  16494. */
  16495. static void sqlite3MemShutdown(void *NotUsed){
  16496. UNUSED_PARAMETER(NotUsed);
  16497. return;
  16498. }
  16499. /*
  16500. ** This routine is the only routine in this file with external linkage.
  16501. **
  16502. ** Populate the low-level memory allocation function pointers in
  16503. ** sqlite3GlobalConfig.m with pointers to the routines in this file.
  16504. */
  16505. SQLITE_PRIVATE void sqlite3MemSetDefault(void){
  16506. static const sqlite3_mem_methods defaultMethods = {
  16507. sqlite3MemMalloc,
  16508. sqlite3MemFree,
  16509. sqlite3MemRealloc,
  16510. sqlite3MemSize,
  16511. sqlite3MemRoundup,
  16512. sqlite3MemInit,
  16513. sqlite3MemShutdown,
  16514. 0
  16515. };
  16516. sqlite3_config(SQLITE_CONFIG_MALLOC, &defaultMethods);
  16517. }
  16518. #endif /* SQLITE_SYSTEM_MALLOC */
  16519. /************** End of mem1.c ************************************************/
  16520. /************** Begin file mem2.c ********************************************/
  16521. /*
  16522. ** 2007 August 15
  16523. **
  16524. ** The author disclaims copyright to this source code. In place of
  16525. ** a legal notice, here is a blessing:
  16526. **
  16527. ** May you do good and not evil.
  16528. ** May you find forgiveness for yourself and forgive others.
  16529. ** May you share freely, never taking more than you give.
  16530. **
  16531. *************************************************************************
  16532. **
  16533. ** This file contains low-level memory allocation drivers for when
  16534. ** SQLite will use the standard C-library malloc/realloc/free interface
  16535. ** to obtain the memory it needs while adding lots of additional debugging
  16536. ** information to each allocation in order to help detect and fix memory
  16537. ** leaks and memory usage errors.
  16538. **
  16539. ** This file contains implementations of the low-level memory allocation
  16540. ** routines specified in the sqlite3_mem_methods object.
  16541. */
  16542. /*
  16543. ** This version of the memory allocator is used only if the
  16544. ** SQLITE_MEMDEBUG macro is defined
  16545. */
  16546. #ifdef SQLITE_MEMDEBUG
  16547. /*
  16548. ** The backtrace functionality is only available with GLIBC
  16549. */
  16550. #ifdef __GLIBC__
  16551. extern int backtrace(void**,int);
  16552. extern void backtrace_symbols_fd(void*const*,int,int);
  16553. #else
  16554. # define backtrace(A,B) 1
  16555. # define backtrace_symbols_fd(A,B,C)
  16556. #endif
  16557. /* #include <stdio.h> */
  16558. /*
  16559. ** Each memory allocation looks like this:
  16560. **
  16561. ** ------------------------------------------------------------------------
  16562. ** | Title | backtrace pointers | MemBlockHdr | allocation | EndGuard |
  16563. ** ------------------------------------------------------------------------
  16564. **
  16565. ** The application code sees only a pointer to the allocation. We have
  16566. ** to back up from the allocation pointer to find the MemBlockHdr. The
  16567. ** MemBlockHdr tells us the size of the allocation and the number of
  16568. ** backtrace pointers. There is also a guard word at the end of the
  16569. ** MemBlockHdr.
  16570. */
  16571. struct MemBlockHdr {
  16572. i64 iSize; /* Size of this allocation */
  16573. struct MemBlockHdr *pNext, *pPrev; /* Linked list of all unfreed memory */
  16574. char nBacktrace; /* Number of backtraces on this alloc */
  16575. char nBacktraceSlots; /* Available backtrace slots */
  16576. u8 nTitle; /* Bytes of title; includes '\0' */
  16577. u8 eType; /* Allocation type code */
  16578. int iForeGuard; /* Guard word for sanity */
  16579. };
  16580. /*
  16581. ** Guard words
  16582. */
  16583. #define FOREGUARD 0x80F5E153
  16584. #define REARGUARD 0xE4676B53
  16585. /*
  16586. ** Number of malloc size increments to track.
  16587. */
  16588. #define NCSIZE 1000
  16589. /*
  16590. ** All of the static variables used by this module are collected
  16591. ** into a single structure named "mem". This is to keep the
  16592. ** static variables organized and to reduce namespace pollution
  16593. ** when this module is combined with other in the amalgamation.
  16594. */
  16595. static struct {
  16596. /*
  16597. ** Mutex to control access to the memory allocation subsystem.
  16598. */
  16599. sqlite3_mutex *mutex;
  16600. /*
  16601. ** Head and tail of a linked list of all outstanding allocations
  16602. */
  16603. struct MemBlockHdr *pFirst;
  16604. struct MemBlockHdr *pLast;
  16605. /*
  16606. ** The number of levels of backtrace to save in new allocations.
  16607. */
  16608. int nBacktrace;
  16609. void (*xBacktrace)(int, int, void **);
  16610. /*
  16611. ** Title text to insert in front of each block
  16612. */
  16613. int nTitle; /* Bytes of zTitle to save. Includes '\0' and padding */
  16614. char zTitle[100]; /* The title text */
  16615. /*
  16616. ** sqlite3MallocDisallow() increments the following counter.
  16617. ** sqlite3MallocAllow() decrements it.
  16618. */
  16619. int disallow; /* Do not allow memory allocation */
  16620. /*
  16621. ** Gather statistics on the sizes of memory allocations.
  16622. ** nAlloc[i] is the number of allocation attempts of i*8
  16623. ** bytes. i==NCSIZE is the number of allocation attempts for
  16624. ** sizes more than NCSIZE*8 bytes.
  16625. */
  16626. int nAlloc[NCSIZE]; /* Total number of allocations */
  16627. int nCurrent[NCSIZE]; /* Current number of allocations */
  16628. int mxCurrent[NCSIZE]; /* Highwater mark for nCurrent */
  16629. } mem;
  16630. /*
  16631. ** Adjust memory usage statistics
  16632. */
  16633. static void adjustStats(int iSize, int increment){
  16634. int i = ROUND8(iSize)/8;
  16635. if( i>NCSIZE-1 ){
  16636. i = NCSIZE - 1;
  16637. }
  16638. if( increment>0 ){
  16639. mem.nAlloc[i]++;
  16640. mem.nCurrent[i]++;
  16641. if( mem.nCurrent[i]>mem.mxCurrent[i] ){
  16642. mem.mxCurrent[i] = mem.nCurrent[i];
  16643. }
  16644. }else{
  16645. mem.nCurrent[i]--;
  16646. assert( mem.nCurrent[i]>=0 );
  16647. }
  16648. }
  16649. /*
  16650. ** Given an allocation, find the MemBlockHdr for that allocation.
  16651. **
  16652. ** This routine checks the guards at either end of the allocation and
  16653. ** if they are incorrect it asserts.
  16654. */
  16655. static struct MemBlockHdr *sqlite3MemsysGetHeader(void *pAllocation){
  16656. struct MemBlockHdr *p;
  16657. int *pInt;
  16658. u8 *pU8;
  16659. int nReserve;
  16660. p = (struct MemBlockHdr*)pAllocation;
  16661. p--;
  16662. assert( p->iForeGuard==(int)FOREGUARD );
  16663. nReserve = ROUND8(p->iSize);
  16664. pInt = (int*)pAllocation;
  16665. pU8 = (u8*)pAllocation;
  16666. assert( pInt[nReserve/sizeof(int)]==(int)REARGUARD );
  16667. /* This checks any of the "extra" bytes allocated due
  16668. ** to rounding up to an 8 byte boundary to ensure
  16669. ** they haven't been overwritten.
  16670. */
  16671. while( nReserve-- > p->iSize ) assert( pU8[nReserve]==0x65 );
  16672. return p;
  16673. }
  16674. /*
  16675. ** Return the number of bytes currently allocated at address p.
  16676. */
  16677. static int sqlite3MemSize(void *p){
  16678. struct MemBlockHdr *pHdr;
  16679. if( !p ){
  16680. return 0;
  16681. }
  16682. pHdr = sqlite3MemsysGetHeader(p);
  16683. return (int)pHdr->iSize;
  16684. }
  16685. /*
  16686. ** Initialize the memory allocation subsystem.
  16687. */
  16688. static int sqlite3MemInit(void *NotUsed){
  16689. UNUSED_PARAMETER(NotUsed);
  16690. assert( (sizeof(struct MemBlockHdr)&7) == 0 );
  16691. if( !sqlite3GlobalConfig.bMemstat ){
  16692. /* If memory status is enabled, then the malloc.c wrapper will already
  16693. ** hold the STATIC_MEM mutex when the routines here are invoked. */
  16694. mem.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
  16695. }
  16696. return SQLITE_OK;
  16697. }
  16698. /*
  16699. ** Deinitialize the memory allocation subsystem.
  16700. */
  16701. static void sqlite3MemShutdown(void *NotUsed){
  16702. UNUSED_PARAMETER(NotUsed);
  16703. mem.mutex = 0;
  16704. }
  16705. /*
  16706. ** Round up a request size to the next valid allocation size.
  16707. */
  16708. static int sqlite3MemRoundup(int n){
  16709. return ROUND8(n);
  16710. }
  16711. /*
  16712. ** Fill a buffer with pseudo-random bytes. This is used to preset
  16713. ** the content of a new memory allocation to unpredictable values and
  16714. ** to clear the content of a freed allocation to unpredictable values.
  16715. */
  16716. static void randomFill(char *pBuf, int nByte){
  16717. unsigned int x, y, r;
  16718. x = SQLITE_PTR_TO_INT(pBuf);
  16719. y = nByte | 1;
  16720. while( nByte >= 4 ){
  16721. x = (x>>1) ^ (-(int)(x&1) & 0xd0000001);
  16722. y = y*1103515245 + 12345;
  16723. r = x ^ y;
  16724. *(int*)pBuf = r;
  16725. pBuf += 4;
  16726. nByte -= 4;
  16727. }
  16728. while( nByte-- > 0 ){
  16729. x = (x>>1) ^ (-(int)(x&1) & 0xd0000001);
  16730. y = y*1103515245 + 12345;
  16731. r = x ^ y;
  16732. *(pBuf++) = r & 0xff;
  16733. }
  16734. }
  16735. /*
  16736. ** Allocate nByte bytes of memory.
  16737. */
  16738. static void *sqlite3MemMalloc(int nByte){
  16739. struct MemBlockHdr *pHdr;
  16740. void **pBt;
  16741. char *z;
  16742. int *pInt;
  16743. void *p = 0;
  16744. int totalSize;
  16745. int nReserve;
  16746. sqlite3_mutex_enter(mem.mutex);
  16747. assert( mem.disallow==0 );
  16748. nReserve = ROUND8(nByte);
  16749. totalSize = nReserve + sizeof(*pHdr) + sizeof(int) +
  16750. mem.nBacktrace*sizeof(void*) + mem.nTitle;
  16751. p = malloc(totalSize);
  16752. if( p ){
  16753. z = p;
  16754. pBt = (void**)&z[mem.nTitle];
  16755. pHdr = (struct MemBlockHdr*)&pBt[mem.nBacktrace];
  16756. pHdr->pNext = 0;
  16757. pHdr->pPrev = mem.pLast;
  16758. if( mem.pLast ){
  16759. mem.pLast->pNext = pHdr;
  16760. }else{
  16761. mem.pFirst = pHdr;
  16762. }
  16763. mem.pLast = pHdr;
  16764. pHdr->iForeGuard = FOREGUARD;
  16765. pHdr->eType = MEMTYPE_HEAP;
  16766. pHdr->nBacktraceSlots = mem.nBacktrace;
  16767. pHdr->nTitle = mem.nTitle;
  16768. if( mem.nBacktrace ){
  16769. void *aAddr[40];
  16770. pHdr->nBacktrace = backtrace(aAddr, mem.nBacktrace+1)-1;
  16771. memcpy(pBt, &aAddr[1], pHdr->nBacktrace*sizeof(void*));
  16772. assert(pBt[0]);
  16773. if( mem.xBacktrace ){
  16774. mem.xBacktrace(nByte, pHdr->nBacktrace-1, &aAddr[1]);
  16775. }
  16776. }else{
  16777. pHdr->nBacktrace = 0;
  16778. }
  16779. if( mem.nTitle ){
  16780. memcpy(z, mem.zTitle, mem.nTitle);
  16781. }
  16782. pHdr->iSize = nByte;
  16783. adjustStats(nByte, +1);
  16784. pInt = (int*)&pHdr[1];
  16785. pInt[nReserve/sizeof(int)] = REARGUARD;
  16786. randomFill((char*)pInt, nByte);
  16787. memset(((char*)pInt)+nByte, 0x65, nReserve-nByte);
  16788. p = (void*)pInt;
  16789. }
  16790. sqlite3_mutex_leave(mem.mutex);
  16791. return p;
  16792. }
  16793. /*
  16794. ** Free memory.
  16795. */
  16796. static void sqlite3MemFree(void *pPrior){
  16797. struct MemBlockHdr *pHdr;
  16798. void **pBt;
  16799. char *z;
  16800. assert( sqlite3GlobalConfig.bMemstat || sqlite3GlobalConfig.bCoreMutex==0
  16801. || mem.mutex!=0 );
  16802. pHdr = sqlite3MemsysGetHeader(pPrior);
  16803. pBt = (void**)pHdr;
  16804. pBt -= pHdr->nBacktraceSlots;
  16805. sqlite3_mutex_enter(mem.mutex);
  16806. if( pHdr->pPrev ){
  16807. assert( pHdr->pPrev->pNext==pHdr );
  16808. pHdr->pPrev->pNext = pHdr->pNext;
  16809. }else{
  16810. assert( mem.pFirst==pHdr );
  16811. mem.pFirst = pHdr->pNext;
  16812. }
  16813. if( pHdr->pNext ){
  16814. assert( pHdr->pNext->pPrev==pHdr );
  16815. pHdr->pNext->pPrev = pHdr->pPrev;
  16816. }else{
  16817. assert( mem.pLast==pHdr );
  16818. mem.pLast = pHdr->pPrev;
  16819. }
  16820. z = (char*)pBt;
  16821. z -= pHdr->nTitle;
  16822. adjustStats((int)pHdr->iSize, -1);
  16823. randomFill(z, sizeof(void*)*pHdr->nBacktraceSlots + sizeof(*pHdr) +
  16824. (int)pHdr->iSize + sizeof(int) + pHdr->nTitle);
  16825. free(z);
  16826. sqlite3_mutex_leave(mem.mutex);
  16827. }
  16828. /*
  16829. ** Change the size of an existing memory allocation.
  16830. **
  16831. ** For this debugging implementation, we *always* make a copy of the
  16832. ** allocation into a new place in memory. In this way, if the
  16833. ** higher level code is using pointer to the old allocation, it is
  16834. ** much more likely to break and we are much more liking to find
  16835. ** the error.
  16836. */
  16837. static void *sqlite3MemRealloc(void *pPrior, int nByte){
  16838. struct MemBlockHdr *pOldHdr;
  16839. void *pNew;
  16840. assert( mem.disallow==0 );
  16841. assert( (nByte & 7)==0 ); /* EV: R-46199-30249 */
  16842. pOldHdr = sqlite3MemsysGetHeader(pPrior);
  16843. pNew = sqlite3MemMalloc(nByte);
  16844. if( pNew ){
  16845. memcpy(pNew, pPrior, (int)(nByte<pOldHdr->iSize ? nByte : pOldHdr->iSize));
  16846. if( nByte>pOldHdr->iSize ){
  16847. randomFill(&((char*)pNew)[pOldHdr->iSize], nByte - (int)pOldHdr->iSize);
  16848. }
  16849. sqlite3MemFree(pPrior);
  16850. }
  16851. return pNew;
  16852. }
  16853. /*
  16854. ** Populate the low-level memory allocation function pointers in
  16855. ** sqlite3GlobalConfig.m with pointers to the routines in this file.
  16856. */
  16857. SQLITE_PRIVATE void sqlite3MemSetDefault(void){
  16858. static const sqlite3_mem_methods defaultMethods = {
  16859. sqlite3MemMalloc,
  16860. sqlite3MemFree,
  16861. sqlite3MemRealloc,
  16862. sqlite3MemSize,
  16863. sqlite3MemRoundup,
  16864. sqlite3MemInit,
  16865. sqlite3MemShutdown,
  16866. 0
  16867. };
  16868. sqlite3_config(SQLITE_CONFIG_MALLOC, &defaultMethods);
  16869. }
  16870. /*
  16871. ** Set the "type" of an allocation.
  16872. */
  16873. SQLITE_PRIVATE void sqlite3MemdebugSetType(void *p, u8 eType){
  16874. if( p && sqlite3GlobalConfig.m.xMalloc==sqlite3MemMalloc ){
  16875. struct MemBlockHdr *pHdr;
  16876. pHdr = sqlite3MemsysGetHeader(p);
  16877. assert( pHdr->iForeGuard==FOREGUARD );
  16878. pHdr->eType = eType;
  16879. }
  16880. }
  16881. /*
  16882. ** Return TRUE if the mask of type in eType matches the type of the
  16883. ** allocation p. Also return true if p==NULL.
  16884. **
  16885. ** This routine is designed for use within an assert() statement, to
  16886. ** verify the type of an allocation. For example:
  16887. **
  16888. ** assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) );
  16889. */
  16890. SQLITE_PRIVATE int sqlite3MemdebugHasType(void *p, u8 eType){
  16891. int rc = 1;
  16892. if( p && sqlite3GlobalConfig.m.xMalloc==sqlite3MemMalloc ){
  16893. struct MemBlockHdr *pHdr;
  16894. pHdr = sqlite3MemsysGetHeader(p);
  16895. assert( pHdr->iForeGuard==FOREGUARD ); /* Allocation is valid */
  16896. if( (pHdr->eType&eType)==0 ){
  16897. rc = 0;
  16898. }
  16899. }
  16900. return rc;
  16901. }
  16902. /*
  16903. ** Return TRUE if the mask of type in eType matches no bits of the type of the
  16904. ** allocation p. Also return true if p==NULL.
  16905. **
  16906. ** This routine is designed for use within an assert() statement, to
  16907. ** verify the type of an allocation. For example:
  16908. **
  16909. ** assert( sqlite3MemdebugNoType(p, MEMTYPE_LOOKASIDE) );
  16910. */
  16911. SQLITE_PRIVATE int sqlite3MemdebugNoType(void *p, u8 eType){
  16912. int rc = 1;
  16913. if( p && sqlite3GlobalConfig.m.xMalloc==sqlite3MemMalloc ){
  16914. struct MemBlockHdr *pHdr;
  16915. pHdr = sqlite3MemsysGetHeader(p);
  16916. assert( pHdr->iForeGuard==FOREGUARD ); /* Allocation is valid */
  16917. if( (pHdr->eType&eType)!=0 ){
  16918. rc = 0;
  16919. }
  16920. }
  16921. return rc;
  16922. }
  16923. /*
  16924. ** Set the number of backtrace levels kept for each allocation.
  16925. ** A value of zero turns off backtracing. The number is always rounded
  16926. ** up to a multiple of 2.
  16927. */
  16928. SQLITE_PRIVATE void sqlite3MemdebugBacktrace(int depth){
  16929. if( depth<0 ){ depth = 0; }
  16930. if( depth>20 ){ depth = 20; }
  16931. depth = (depth+1)&0xfe;
  16932. mem.nBacktrace = depth;
  16933. }
  16934. SQLITE_PRIVATE void sqlite3MemdebugBacktraceCallback(void (*xBacktrace)(int, int, void **)){
  16935. mem.xBacktrace = xBacktrace;
  16936. }
  16937. /*
  16938. ** Set the title string for subsequent allocations.
  16939. */
  16940. SQLITE_PRIVATE void sqlite3MemdebugSettitle(const char *zTitle){
  16941. unsigned int n = sqlite3Strlen30(zTitle) + 1;
  16942. sqlite3_mutex_enter(mem.mutex);
  16943. if( n>=sizeof(mem.zTitle) ) n = sizeof(mem.zTitle)-1;
  16944. memcpy(mem.zTitle, zTitle, n);
  16945. mem.zTitle[n] = 0;
  16946. mem.nTitle = ROUND8(n);
  16947. sqlite3_mutex_leave(mem.mutex);
  16948. }
  16949. SQLITE_PRIVATE void sqlite3MemdebugSync(){
  16950. struct MemBlockHdr *pHdr;
  16951. for(pHdr=mem.pFirst; pHdr; pHdr=pHdr->pNext){
  16952. void **pBt = (void**)pHdr;
  16953. pBt -= pHdr->nBacktraceSlots;
  16954. mem.xBacktrace((int)pHdr->iSize, pHdr->nBacktrace-1, &pBt[1]);
  16955. }
  16956. }
  16957. /*
  16958. ** Open the file indicated and write a log of all unfreed memory
  16959. ** allocations into that log.
  16960. */
  16961. SQLITE_PRIVATE void sqlite3MemdebugDump(const char *zFilename){
  16962. FILE *out;
  16963. struct MemBlockHdr *pHdr;
  16964. void **pBt;
  16965. int i;
  16966. out = fopen(zFilename, "w");
  16967. if( out==0 ){
  16968. fprintf(stderr, "** Unable to output memory debug output log: %s **\n",
  16969. zFilename);
  16970. return;
  16971. }
  16972. for(pHdr=mem.pFirst; pHdr; pHdr=pHdr->pNext){
  16973. char *z = (char*)pHdr;
  16974. z -= pHdr->nBacktraceSlots*sizeof(void*) + pHdr->nTitle;
  16975. fprintf(out, "**** %lld bytes at %p from %s ****\n",
  16976. pHdr->iSize, &pHdr[1], pHdr->nTitle ? z : "???");
  16977. if( pHdr->nBacktrace ){
  16978. fflush(out);
  16979. pBt = (void**)pHdr;
  16980. pBt -= pHdr->nBacktraceSlots;
  16981. backtrace_symbols_fd(pBt, pHdr->nBacktrace, fileno(out));
  16982. fprintf(out, "\n");
  16983. }
  16984. }
  16985. fprintf(out, "COUNTS:\n");
  16986. for(i=0; i<NCSIZE-1; i++){
  16987. if( mem.nAlloc[i] ){
  16988. fprintf(out, " %5d: %10d %10d %10d\n",
  16989. i*8, mem.nAlloc[i], mem.nCurrent[i], mem.mxCurrent[i]);
  16990. }
  16991. }
  16992. if( mem.nAlloc[NCSIZE-1] ){
  16993. fprintf(out, " %5d: %10d %10d %10d\n",
  16994. NCSIZE*8-8, mem.nAlloc[NCSIZE-1],
  16995. mem.nCurrent[NCSIZE-1], mem.mxCurrent[NCSIZE-1]);
  16996. }
  16997. fclose(out);
  16998. }
  16999. /*
  17000. ** Return the number of times sqlite3MemMalloc() has been called.
  17001. */
  17002. SQLITE_PRIVATE int sqlite3MemdebugMallocCount(){
  17003. int i;
  17004. int nTotal = 0;
  17005. for(i=0; i<NCSIZE; i++){
  17006. nTotal += mem.nAlloc[i];
  17007. }
  17008. return nTotal;
  17009. }
  17010. #endif /* SQLITE_MEMDEBUG */
  17011. /************** End of mem2.c ************************************************/
  17012. /************** Begin file mem3.c ********************************************/
  17013. /*
  17014. ** 2007 October 14
  17015. **
  17016. ** The author disclaims copyright to this source code. In place of
  17017. ** a legal notice, here is a blessing:
  17018. **
  17019. ** May you do good and not evil.
  17020. ** May you find forgiveness for yourself and forgive others.
  17021. ** May you share freely, never taking more than you give.
  17022. **
  17023. *************************************************************************
  17024. ** This file contains the C functions that implement a memory
  17025. ** allocation subsystem for use by SQLite.
  17026. **
  17027. ** This version of the memory allocation subsystem omits all
  17028. ** use of malloc(). The SQLite user supplies a block of memory
  17029. ** before calling sqlite3_initialize() from which allocations
  17030. ** are made and returned by the xMalloc() and xRealloc()
  17031. ** implementations. Once sqlite3_initialize() has been called,
  17032. ** the amount of memory available to SQLite is fixed and cannot
  17033. ** be changed.
  17034. **
  17035. ** This version of the memory allocation subsystem is included
  17036. ** in the build only if SQLITE_ENABLE_MEMSYS3 is defined.
  17037. */
  17038. /*
  17039. ** This version of the memory allocator is only built into the library
  17040. ** SQLITE_ENABLE_MEMSYS3 is defined. Defining this symbol does not
  17041. ** mean that the library will use a memory-pool by default, just that
  17042. ** it is available. The mempool allocator is activated by calling
  17043. ** sqlite3_config().
  17044. */
  17045. #ifdef SQLITE_ENABLE_MEMSYS3
  17046. /*
  17047. ** Maximum size (in Mem3Blocks) of a "small" chunk.
  17048. */
  17049. #define MX_SMALL 10
  17050. /*
  17051. ** Number of freelist hash slots
  17052. */
  17053. #define N_HASH 61
  17054. /*
  17055. ** A memory allocation (also called a "chunk") consists of two or
  17056. ** more blocks where each block is 8 bytes. The first 8 bytes are
  17057. ** a header that is not returned to the user.
  17058. **
  17059. ** A chunk is two or more blocks that is either checked out or
  17060. ** free. The first block has format u.hdr. u.hdr.size4x is 4 times the
  17061. ** size of the allocation in blocks if the allocation is free.
  17062. ** The u.hdr.size4x&1 bit is true if the chunk is checked out and
  17063. ** false if the chunk is on the freelist. The u.hdr.size4x&2 bit
  17064. ** is true if the previous chunk is checked out and false if the
  17065. ** previous chunk is free. The u.hdr.prevSize field is the size of
  17066. ** the previous chunk in blocks if the previous chunk is on the
  17067. ** freelist. If the previous chunk is checked out, then
  17068. ** u.hdr.prevSize can be part of the data for that chunk and should
  17069. ** not be read or written.
  17070. **
  17071. ** We often identify a chunk by its index in mem3.aPool[]. When
  17072. ** this is done, the chunk index refers to the second block of
  17073. ** the chunk. In this way, the first chunk has an index of 1.
  17074. ** A chunk index of 0 means "no such chunk" and is the equivalent
  17075. ** of a NULL pointer.
  17076. **
  17077. ** The second block of free chunks is of the form u.list. The
  17078. ** two fields form a double-linked list of chunks of related sizes.
  17079. ** Pointers to the head of the list are stored in mem3.aiSmall[]
  17080. ** for smaller chunks and mem3.aiHash[] for larger chunks.
  17081. **
  17082. ** The second block of a chunk is user data if the chunk is checked
  17083. ** out. If a chunk is checked out, the user data may extend into
  17084. ** the u.hdr.prevSize value of the following chunk.
  17085. */
  17086. typedef struct Mem3Block Mem3Block;
  17087. struct Mem3Block {
  17088. union {
  17089. struct {
  17090. u32 prevSize; /* Size of previous chunk in Mem3Block elements */
  17091. u32 size4x; /* 4x the size of current chunk in Mem3Block elements */
  17092. } hdr;
  17093. struct {
  17094. u32 next; /* Index in mem3.aPool[] of next free chunk */
  17095. u32 prev; /* Index in mem3.aPool[] of previous free chunk */
  17096. } list;
  17097. } u;
  17098. };
  17099. /*
  17100. ** All of the static variables used by this module are collected
  17101. ** into a single structure named "mem3". This is to keep the
  17102. ** static variables organized and to reduce namespace pollution
  17103. ** when this module is combined with other in the amalgamation.
  17104. */
  17105. static SQLITE_WSD struct Mem3Global {
  17106. /*
  17107. ** Memory available for allocation. nPool is the size of the array
  17108. ** (in Mem3Blocks) pointed to by aPool less 2.
  17109. */
  17110. u32 nPool;
  17111. Mem3Block *aPool;
  17112. /*
  17113. ** True if we are evaluating an out-of-memory callback.
  17114. */
  17115. int alarmBusy;
  17116. /*
  17117. ** Mutex to control access to the memory allocation subsystem.
  17118. */
  17119. sqlite3_mutex *mutex;
  17120. /*
  17121. ** The minimum amount of free space that we have seen.
  17122. */
  17123. u32 mnMaster;
  17124. /*
  17125. ** iMaster is the index of the master chunk. Most new allocations
  17126. ** occur off of this chunk. szMaster is the size (in Mem3Blocks)
  17127. ** of the current master. iMaster is 0 if there is not master chunk.
  17128. ** The master chunk is not in either the aiHash[] or aiSmall[].
  17129. */
  17130. u32 iMaster;
  17131. u32 szMaster;
  17132. /*
  17133. ** Array of lists of free blocks according to the block size
  17134. ** for smaller chunks, or a hash on the block size for larger
  17135. ** chunks.
  17136. */
  17137. u32 aiSmall[MX_SMALL-1]; /* For sizes 2 through MX_SMALL, inclusive */
  17138. u32 aiHash[N_HASH]; /* For sizes MX_SMALL+1 and larger */
  17139. } mem3 = { 97535575 };
  17140. #define mem3 GLOBAL(struct Mem3Global, mem3)
  17141. /*
  17142. ** Unlink the chunk at mem3.aPool[i] from list it is currently
  17143. ** on. *pRoot is the list that i is a member of.
  17144. */
  17145. static void memsys3UnlinkFromList(u32 i, u32 *pRoot){
  17146. u32 next = mem3.aPool[i].u.list.next;
  17147. u32 prev = mem3.aPool[i].u.list.prev;
  17148. assert( sqlite3_mutex_held(mem3.mutex) );
  17149. if( prev==0 ){
  17150. *pRoot = next;
  17151. }else{
  17152. mem3.aPool[prev].u.list.next = next;
  17153. }
  17154. if( next ){
  17155. mem3.aPool[next].u.list.prev = prev;
  17156. }
  17157. mem3.aPool[i].u.list.next = 0;
  17158. mem3.aPool[i].u.list.prev = 0;
  17159. }
  17160. /*
  17161. ** Unlink the chunk at index i from
  17162. ** whatever list is currently a member of.
  17163. */
  17164. static void memsys3Unlink(u32 i){
  17165. u32 size, hash;
  17166. assert( sqlite3_mutex_held(mem3.mutex) );
  17167. assert( (mem3.aPool[i-1].u.hdr.size4x & 1)==0 );
  17168. assert( i>=1 );
  17169. size = mem3.aPool[i-1].u.hdr.size4x/4;
  17170. assert( size==mem3.aPool[i+size-1].u.hdr.prevSize );
  17171. assert( size>=2 );
  17172. if( size <= MX_SMALL ){
  17173. memsys3UnlinkFromList(i, &mem3.aiSmall[size-2]);
  17174. }else{
  17175. hash = size % N_HASH;
  17176. memsys3UnlinkFromList(i, &mem3.aiHash[hash]);
  17177. }
  17178. }
  17179. /*
  17180. ** Link the chunk at mem3.aPool[i] so that is on the list rooted
  17181. ** at *pRoot.
  17182. */
  17183. static void memsys3LinkIntoList(u32 i, u32 *pRoot){
  17184. assert( sqlite3_mutex_held(mem3.mutex) );
  17185. mem3.aPool[i].u.list.next = *pRoot;
  17186. mem3.aPool[i].u.list.prev = 0;
  17187. if( *pRoot ){
  17188. mem3.aPool[*pRoot].u.list.prev = i;
  17189. }
  17190. *pRoot = i;
  17191. }
  17192. /*
  17193. ** Link the chunk at index i into either the appropriate
  17194. ** small chunk list, or into the large chunk hash table.
  17195. */
  17196. static void memsys3Link(u32 i){
  17197. u32 size, hash;
  17198. assert( sqlite3_mutex_held(mem3.mutex) );
  17199. assert( i>=1 );
  17200. assert( (mem3.aPool[i-1].u.hdr.size4x & 1)==0 );
  17201. size = mem3.aPool[i-1].u.hdr.size4x/4;
  17202. assert( size==mem3.aPool[i+size-1].u.hdr.prevSize );
  17203. assert( size>=2 );
  17204. if( size <= MX_SMALL ){
  17205. memsys3LinkIntoList(i, &mem3.aiSmall[size-2]);
  17206. }else{
  17207. hash = size % N_HASH;
  17208. memsys3LinkIntoList(i, &mem3.aiHash[hash]);
  17209. }
  17210. }
  17211. /*
  17212. ** If the STATIC_MEM mutex is not already held, obtain it now. The mutex
  17213. ** will already be held (obtained by code in malloc.c) if
  17214. ** sqlite3GlobalConfig.bMemStat is true.
  17215. */
  17216. static void memsys3Enter(void){
  17217. if( sqlite3GlobalConfig.bMemstat==0 && mem3.mutex==0 ){
  17218. mem3.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
  17219. }
  17220. sqlite3_mutex_enter(mem3.mutex);
  17221. }
  17222. static void memsys3Leave(void){
  17223. sqlite3_mutex_leave(mem3.mutex);
  17224. }
  17225. /*
  17226. ** Called when we are unable to satisfy an allocation of nBytes.
  17227. */
  17228. static void memsys3OutOfMemory(int nByte){
  17229. if( !mem3.alarmBusy ){
  17230. mem3.alarmBusy = 1;
  17231. assert( sqlite3_mutex_held(mem3.mutex) );
  17232. sqlite3_mutex_leave(mem3.mutex);
  17233. sqlite3_release_memory(nByte);
  17234. sqlite3_mutex_enter(mem3.mutex);
  17235. mem3.alarmBusy = 0;
  17236. }
  17237. }
  17238. /*
  17239. ** Chunk i is a free chunk that has been unlinked. Adjust its
  17240. ** size parameters for check-out and return a pointer to the
  17241. ** user portion of the chunk.
  17242. */
  17243. static void *memsys3Checkout(u32 i, u32 nBlock){
  17244. u32 x;
  17245. assert( sqlite3_mutex_held(mem3.mutex) );
  17246. assert( i>=1 );
  17247. assert( mem3.aPool[i-1].u.hdr.size4x/4==nBlock );
  17248. assert( mem3.aPool[i+nBlock-1].u.hdr.prevSize==nBlock );
  17249. x = mem3.aPool[i-1].u.hdr.size4x;
  17250. mem3.aPool[i-1].u.hdr.size4x = nBlock*4 | 1 | (x&2);
  17251. mem3.aPool[i+nBlock-1].u.hdr.prevSize = nBlock;
  17252. mem3.aPool[i+nBlock-1].u.hdr.size4x |= 2;
  17253. return &mem3.aPool[i];
  17254. }
  17255. /*
  17256. ** Carve a piece off of the end of the mem3.iMaster free chunk.
  17257. ** Return a pointer to the new allocation. Or, if the master chunk
  17258. ** is not large enough, return 0.
  17259. */
  17260. static void *memsys3FromMaster(u32 nBlock){
  17261. assert( sqlite3_mutex_held(mem3.mutex) );
  17262. assert( mem3.szMaster>=nBlock );
  17263. if( nBlock>=mem3.szMaster-1 ){
  17264. /* Use the entire master */
  17265. void *p = memsys3Checkout(mem3.iMaster, mem3.szMaster);
  17266. mem3.iMaster = 0;
  17267. mem3.szMaster = 0;
  17268. mem3.mnMaster = 0;
  17269. return p;
  17270. }else{
  17271. /* Split the master block. Return the tail. */
  17272. u32 newi, x;
  17273. newi = mem3.iMaster + mem3.szMaster - nBlock;
  17274. assert( newi > mem3.iMaster+1 );
  17275. mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.prevSize = nBlock;
  17276. mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.size4x |= 2;
  17277. mem3.aPool[newi-1].u.hdr.size4x = nBlock*4 + 1;
  17278. mem3.szMaster -= nBlock;
  17279. mem3.aPool[newi-1].u.hdr.prevSize = mem3.szMaster;
  17280. x = mem3.aPool[mem3.iMaster-1].u.hdr.size4x & 2;
  17281. mem3.aPool[mem3.iMaster-1].u.hdr.size4x = mem3.szMaster*4 | x;
  17282. if( mem3.szMaster < mem3.mnMaster ){
  17283. mem3.mnMaster = mem3.szMaster;
  17284. }
  17285. return (void*)&mem3.aPool[newi];
  17286. }
  17287. }
  17288. /*
  17289. ** *pRoot is the head of a list of free chunks of the same size
  17290. ** or same size hash. In other words, *pRoot is an entry in either
  17291. ** mem3.aiSmall[] or mem3.aiHash[].
  17292. **
  17293. ** This routine examines all entries on the given list and tries
  17294. ** to coalesce each entries with adjacent free chunks.
  17295. **
  17296. ** If it sees a chunk that is larger than mem3.iMaster, it replaces
  17297. ** the current mem3.iMaster with the new larger chunk. In order for
  17298. ** this mem3.iMaster replacement to work, the master chunk must be
  17299. ** linked into the hash tables. That is not the normal state of
  17300. ** affairs, of course. The calling routine must link the master
  17301. ** chunk before invoking this routine, then must unlink the (possibly
  17302. ** changed) master chunk once this routine has finished.
  17303. */
  17304. static void memsys3Merge(u32 *pRoot){
  17305. u32 iNext, prev, size, i, x;
  17306. assert( sqlite3_mutex_held(mem3.mutex) );
  17307. for(i=*pRoot; i>0; i=iNext){
  17308. iNext = mem3.aPool[i].u.list.next;
  17309. size = mem3.aPool[i-1].u.hdr.size4x;
  17310. assert( (size&1)==0 );
  17311. if( (size&2)==0 ){
  17312. memsys3UnlinkFromList(i, pRoot);
  17313. assert( i > mem3.aPool[i-1].u.hdr.prevSize );
  17314. prev = i - mem3.aPool[i-1].u.hdr.prevSize;
  17315. if( prev==iNext ){
  17316. iNext = mem3.aPool[prev].u.list.next;
  17317. }
  17318. memsys3Unlink(prev);
  17319. size = i + size/4 - prev;
  17320. x = mem3.aPool[prev-1].u.hdr.size4x & 2;
  17321. mem3.aPool[prev-1].u.hdr.size4x = size*4 | x;
  17322. mem3.aPool[prev+size-1].u.hdr.prevSize = size;
  17323. memsys3Link(prev);
  17324. i = prev;
  17325. }else{
  17326. size /= 4;
  17327. }
  17328. if( size>mem3.szMaster ){
  17329. mem3.iMaster = i;
  17330. mem3.szMaster = size;
  17331. }
  17332. }
  17333. }
  17334. /*
  17335. ** Return a block of memory of at least nBytes in size.
  17336. ** Return NULL if unable.
  17337. **
  17338. ** This function assumes that the necessary mutexes, if any, are
  17339. ** already held by the caller. Hence "Unsafe".
  17340. */
  17341. static void *memsys3MallocUnsafe(int nByte){
  17342. u32 i;
  17343. u32 nBlock;
  17344. u32 toFree;
  17345. assert( sqlite3_mutex_held(mem3.mutex) );
  17346. assert( sizeof(Mem3Block)==8 );
  17347. if( nByte<=12 ){
  17348. nBlock = 2;
  17349. }else{
  17350. nBlock = (nByte + 11)/8;
  17351. }
  17352. assert( nBlock>=2 );
  17353. /* STEP 1:
  17354. ** Look for an entry of the correct size in either the small
  17355. ** chunk table or in the large chunk hash table. This is
  17356. ** successful most of the time (about 9 times out of 10).
  17357. */
  17358. if( nBlock <= MX_SMALL ){
  17359. i = mem3.aiSmall[nBlock-2];
  17360. if( i>0 ){
  17361. memsys3UnlinkFromList(i, &mem3.aiSmall[nBlock-2]);
  17362. return memsys3Checkout(i, nBlock);
  17363. }
  17364. }else{
  17365. int hash = nBlock % N_HASH;
  17366. for(i=mem3.aiHash[hash]; i>0; i=mem3.aPool[i].u.list.next){
  17367. if( mem3.aPool[i-1].u.hdr.size4x/4==nBlock ){
  17368. memsys3UnlinkFromList(i, &mem3.aiHash[hash]);
  17369. return memsys3Checkout(i, nBlock);
  17370. }
  17371. }
  17372. }
  17373. /* STEP 2:
  17374. ** Try to satisfy the allocation by carving a piece off of the end
  17375. ** of the master chunk. This step usually works if step 1 fails.
  17376. */
  17377. if( mem3.szMaster>=nBlock ){
  17378. return memsys3FromMaster(nBlock);
  17379. }
  17380. /* STEP 3:
  17381. ** Loop through the entire memory pool. Coalesce adjacent free
  17382. ** chunks. Recompute the master chunk as the largest free chunk.
  17383. ** Then try again to satisfy the allocation by carving a piece off
  17384. ** of the end of the master chunk. This step happens very
  17385. ** rarely (we hope!)
  17386. */
  17387. for(toFree=nBlock*16; toFree<(mem3.nPool*16); toFree *= 2){
  17388. memsys3OutOfMemory(toFree);
  17389. if( mem3.iMaster ){
  17390. memsys3Link(mem3.iMaster);
  17391. mem3.iMaster = 0;
  17392. mem3.szMaster = 0;
  17393. }
  17394. for(i=0; i<N_HASH; i++){
  17395. memsys3Merge(&mem3.aiHash[i]);
  17396. }
  17397. for(i=0; i<MX_SMALL-1; i++){
  17398. memsys3Merge(&mem3.aiSmall[i]);
  17399. }
  17400. if( mem3.szMaster ){
  17401. memsys3Unlink(mem3.iMaster);
  17402. if( mem3.szMaster>=nBlock ){
  17403. return memsys3FromMaster(nBlock);
  17404. }
  17405. }
  17406. }
  17407. /* If none of the above worked, then we fail. */
  17408. return 0;
  17409. }
  17410. /*
  17411. ** Free an outstanding memory allocation.
  17412. **
  17413. ** This function assumes that the necessary mutexes, if any, are
  17414. ** already held by the caller. Hence "Unsafe".
  17415. */
  17416. static void memsys3FreeUnsafe(void *pOld){
  17417. Mem3Block *p = (Mem3Block*)pOld;
  17418. int i;
  17419. u32 size, x;
  17420. assert( sqlite3_mutex_held(mem3.mutex) );
  17421. assert( p>mem3.aPool && p<&mem3.aPool[mem3.nPool] );
  17422. i = p - mem3.aPool;
  17423. assert( (mem3.aPool[i-1].u.hdr.size4x&1)==1 );
  17424. size = mem3.aPool[i-1].u.hdr.size4x/4;
  17425. assert( i+size<=mem3.nPool+1 );
  17426. mem3.aPool[i-1].u.hdr.size4x &= ~1;
  17427. mem3.aPool[i+size-1].u.hdr.prevSize = size;
  17428. mem3.aPool[i+size-1].u.hdr.size4x &= ~2;
  17429. memsys3Link(i);
  17430. /* Try to expand the master using the newly freed chunk */
  17431. if( mem3.iMaster ){
  17432. while( (mem3.aPool[mem3.iMaster-1].u.hdr.size4x&2)==0 ){
  17433. size = mem3.aPool[mem3.iMaster-1].u.hdr.prevSize;
  17434. mem3.iMaster -= size;
  17435. mem3.szMaster += size;
  17436. memsys3Unlink(mem3.iMaster);
  17437. x = mem3.aPool[mem3.iMaster-1].u.hdr.size4x & 2;
  17438. mem3.aPool[mem3.iMaster-1].u.hdr.size4x = mem3.szMaster*4 | x;
  17439. mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.prevSize = mem3.szMaster;
  17440. }
  17441. x = mem3.aPool[mem3.iMaster-1].u.hdr.size4x & 2;
  17442. while( (mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.size4x&1)==0 ){
  17443. memsys3Unlink(mem3.iMaster+mem3.szMaster);
  17444. mem3.szMaster += mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.size4x/4;
  17445. mem3.aPool[mem3.iMaster-1].u.hdr.size4x = mem3.szMaster*4 | x;
  17446. mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.prevSize = mem3.szMaster;
  17447. }
  17448. }
  17449. }
  17450. /*
  17451. ** Return the size of an outstanding allocation, in bytes. The
  17452. ** size returned omits the 8-byte header overhead. This only
  17453. ** works for chunks that are currently checked out.
  17454. */
  17455. static int memsys3Size(void *p){
  17456. Mem3Block *pBlock;
  17457. if( p==0 ) return 0;
  17458. pBlock = (Mem3Block*)p;
  17459. assert( (pBlock[-1].u.hdr.size4x&1)!=0 );
  17460. return (pBlock[-1].u.hdr.size4x&~3)*2 - 4;
  17461. }
  17462. /*
  17463. ** Round up a request size to the next valid allocation size.
  17464. */
  17465. static int memsys3Roundup(int n){
  17466. if( n<=12 ){
  17467. return 12;
  17468. }else{
  17469. return ((n+11)&~7) - 4;
  17470. }
  17471. }
  17472. /*
  17473. ** Allocate nBytes of memory.
  17474. */
  17475. static void *memsys3Malloc(int nBytes){
  17476. sqlite3_int64 *p;
  17477. assert( nBytes>0 ); /* malloc.c filters out 0 byte requests */
  17478. memsys3Enter();
  17479. p = memsys3MallocUnsafe(nBytes);
  17480. memsys3Leave();
  17481. return (void*)p;
  17482. }
  17483. /*
  17484. ** Free memory.
  17485. */
  17486. static void memsys3Free(void *pPrior){
  17487. assert( pPrior );
  17488. memsys3Enter();
  17489. memsys3FreeUnsafe(pPrior);
  17490. memsys3Leave();
  17491. }
  17492. /*
  17493. ** Change the size of an existing memory allocation
  17494. */
  17495. static void *memsys3Realloc(void *pPrior, int nBytes){
  17496. int nOld;
  17497. void *p;
  17498. if( pPrior==0 ){
  17499. return sqlite3_malloc(nBytes);
  17500. }
  17501. if( nBytes<=0 ){
  17502. sqlite3_free(pPrior);
  17503. return 0;
  17504. }
  17505. nOld = memsys3Size(pPrior);
  17506. if( nBytes<=nOld && nBytes>=nOld-128 ){
  17507. return pPrior;
  17508. }
  17509. memsys3Enter();
  17510. p = memsys3MallocUnsafe(nBytes);
  17511. if( p ){
  17512. if( nOld<nBytes ){
  17513. memcpy(p, pPrior, nOld);
  17514. }else{
  17515. memcpy(p, pPrior, nBytes);
  17516. }
  17517. memsys3FreeUnsafe(pPrior);
  17518. }
  17519. memsys3Leave();
  17520. return p;
  17521. }
  17522. /*
  17523. ** Initialize this module.
  17524. */
  17525. static int memsys3Init(void *NotUsed){
  17526. UNUSED_PARAMETER(NotUsed);
  17527. if( !sqlite3GlobalConfig.pHeap ){
  17528. return SQLITE_ERROR;
  17529. }
  17530. /* Store a pointer to the memory block in global structure mem3. */
  17531. assert( sizeof(Mem3Block)==8 );
  17532. mem3.aPool = (Mem3Block *)sqlite3GlobalConfig.pHeap;
  17533. mem3.nPool = (sqlite3GlobalConfig.nHeap / sizeof(Mem3Block)) - 2;
  17534. /* Initialize the master block. */
  17535. mem3.szMaster = mem3.nPool;
  17536. mem3.mnMaster = mem3.szMaster;
  17537. mem3.iMaster = 1;
  17538. mem3.aPool[0].u.hdr.size4x = (mem3.szMaster<<2) + 2;
  17539. mem3.aPool[mem3.nPool].u.hdr.prevSize = mem3.nPool;
  17540. mem3.aPool[mem3.nPool].u.hdr.size4x = 1;
  17541. return SQLITE_OK;
  17542. }
  17543. /*
  17544. ** Deinitialize this module.
  17545. */
  17546. static void memsys3Shutdown(void *NotUsed){
  17547. UNUSED_PARAMETER(NotUsed);
  17548. mem3.mutex = 0;
  17549. return;
  17550. }
  17551. /*
  17552. ** Open the file indicated and write a log of all unfreed memory
  17553. ** allocations into that log.
  17554. */
  17555. SQLITE_PRIVATE void sqlite3Memsys3Dump(const char *zFilename){
  17556. #ifdef SQLITE_DEBUG
  17557. FILE *out;
  17558. u32 i, j;
  17559. u32 size;
  17560. if( zFilename==0 || zFilename[0]==0 ){
  17561. out = stdout;
  17562. }else{
  17563. out = fopen(zFilename, "w");
  17564. if( out==0 ){
  17565. fprintf(stderr, "** Unable to output memory debug output log: %s **\n",
  17566. zFilename);
  17567. return;
  17568. }
  17569. }
  17570. memsys3Enter();
  17571. fprintf(out, "CHUNKS:\n");
  17572. for(i=1; i<=mem3.nPool; i+=size/4){
  17573. size = mem3.aPool[i-1].u.hdr.size4x;
  17574. if( size/4<=1 ){
  17575. fprintf(out, "%p size error\n", &mem3.aPool[i]);
  17576. assert( 0 );
  17577. break;
  17578. }
  17579. if( (size&1)==0 && mem3.aPool[i+size/4-1].u.hdr.prevSize!=size/4 ){
  17580. fprintf(out, "%p tail size does not match\n", &mem3.aPool[i]);
  17581. assert( 0 );
  17582. break;
  17583. }
  17584. if( ((mem3.aPool[i+size/4-1].u.hdr.size4x&2)>>1)!=(size&1) ){
  17585. fprintf(out, "%p tail checkout bit is incorrect\n", &mem3.aPool[i]);
  17586. assert( 0 );
  17587. break;
  17588. }
  17589. if( size&1 ){
  17590. fprintf(out, "%p %6d bytes checked out\n", &mem3.aPool[i], (size/4)*8-8);
  17591. }else{
  17592. fprintf(out, "%p %6d bytes free%s\n", &mem3.aPool[i], (size/4)*8-8,
  17593. i==mem3.iMaster ? " **master**" : "");
  17594. }
  17595. }
  17596. for(i=0; i<MX_SMALL-1; i++){
  17597. if( mem3.aiSmall[i]==0 ) continue;
  17598. fprintf(out, "small(%2d):", i);
  17599. for(j = mem3.aiSmall[i]; j>0; j=mem3.aPool[j].u.list.next){
  17600. fprintf(out, " %p(%d)", &mem3.aPool[j],
  17601. (mem3.aPool[j-1].u.hdr.size4x/4)*8-8);
  17602. }
  17603. fprintf(out, "\n");
  17604. }
  17605. for(i=0; i<N_HASH; i++){
  17606. if( mem3.aiHash[i]==0 ) continue;
  17607. fprintf(out, "hash(%2d):", i);
  17608. for(j = mem3.aiHash[i]; j>0; j=mem3.aPool[j].u.list.next){
  17609. fprintf(out, " %p(%d)", &mem3.aPool[j],
  17610. (mem3.aPool[j-1].u.hdr.size4x/4)*8-8);
  17611. }
  17612. fprintf(out, "\n");
  17613. }
  17614. fprintf(out, "master=%d\n", mem3.iMaster);
  17615. fprintf(out, "nowUsed=%d\n", mem3.nPool*8 - mem3.szMaster*8);
  17616. fprintf(out, "mxUsed=%d\n", mem3.nPool*8 - mem3.mnMaster*8);
  17617. sqlite3_mutex_leave(mem3.mutex);
  17618. if( out==stdout ){
  17619. fflush(stdout);
  17620. }else{
  17621. fclose(out);
  17622. }
  17623. #else
  17624. UNUSED_PARAMETER(zFilename);
  17625. #endif
  17626. }
  17627. /*
  17628. ** This routine is the only routine in this file with external
  17629. ** linkage.
  17630. **
  17631. ** Populate the low-level memory allocation function pointers in
  17632. ** sqlite3GlobalConfig.m with pointers to the routines in this file. The
  17633. ** arguments specify the block of memory to manage.
  17634. **
  17635. ** This routine is only called by sqlite3_config(), and therefore
  17636. ** is not required to be threadsafe (it is not).
  17637. */
  17638. SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys3(void){
  17639. static const sqlite3_mem_methods mempoolMethods = {
  17640. memsys3Malloc,
  17641. memsys3Free,
  17642. memsys3Realloc,
  17643. memsys3Size,
  17644. memsys3Roundup,
  17645. memsys3Init,
  17646. memsys3Shutdown,
  17647. 0
  17648. };
  17649. return &mempoolMethods;
  17650. }
  17651. #endif /* SQLITE_ENABLE_MEMSYS3 */
  17652. /************** End of mem3.c ************************************************/
  17653. /************** Begin file mem5.c ********************************************/
  17654. /*
  17655. ** 2007 October 14
  17656. **
  17657. ** The author disclaims copyright to this source code. In place of
  17658. ** a legal notice, here is a blessing:
  17659. **
  17660. ** May you do good and not evil.
  17661. ** May you find forgiveness for yourself and forgive others.
  17662. ** May you share freely, never taking more than you give.
  17663. **
  17664. *************************************************************************
  17665. ** This file contains the C functions that implement a memory
  17666. ** allocation subsystem for use by SQLite.
  17667. **
  17668. ** This version of the memory allocation subsystem omits all
  17669. ** use of malloc(). The application gives SQLite a block of memory
  17670. ** before calling sqlite3_initialize() from which allocations
  17671. ** are made and returned by the xMalloc() and xRealloc()
  17672. ** implementations. Once sqlite3_initialize() has been called,
  17673. ** the amount of memory available to SQLite is fixed and cannot
  17674. ** be changed.
  17675. **
  17676. ** This version of the memory allocation subsystem is included
  17677. ** in the build only if SQLITE_ENABLE_MEMSYS5 is defined.
  17678. **
  17679. ** This memory allocator uses the following algorithm:
  17680. **
  17681. ** 1. All memory allocations sizes are rounded up to a power of 2.
  17682. **
  17683. ** 2. If two adjacent free blocks are the halves of a larger block,
  17684. ** then the two blocks are coalesced into the single larger block.
  17685. **
  17686. ** 3. New memory is allocated from the first available free block.
  17687. **
  17688. ** This algorithm is described in: J. M. Robson. "Bounds for Some Functions
  17689. ** Concerning Dynamic Storage Allocation". Journal of the Association for
  17690. ** Computing Machinery, Volume 21, Number 8, July 1974, pages 491-499.
  17691. **
  17692. ** Let n be the size of the largest allocation divided by the minimum
  17693. ** allocation size (after rounding all sizes up to a power of 2.) Let M
  17694. ** be the maximum amount of memory ever outstanding at one time. Let
  17695. ** N be the total amount of memory available for allocation. Robson
  17696. ** proved that this memory allocator will never breakdown due to
  17697. ** fragmentation as long as the following constraint holds:
  17698. **
  17699. ** N >= M*(1 + log2(n)/2) - n + 1
  17700. **
  17701. ** The sqlite3_status() logic tracks the maximum values of n and M so
  17702. ** that an application can, at any time, verify this constraint.
  17703. */
  17704. /*
  17705. ** This version of the memory allocator is used only when
  17706. ** SQLITE_ENABLE_MEMSYS5 is defined.
  17707. */
  17708. #ifdef SQLITE_ENABLE_MEMSYS5
  17709. /*
  17710. ** A minimum allocation is an instance of the following structure.
  17711. ** Larger allocations are an array of these structures where the
  17712. ** size of the array is a power of 2.
  17713. **
  17714. ** The size of this object must be a power of two. That fact is
  17715. ** verified in memsys5Init().
  17716. */
  17717. typedef struct Mem5Link Mem5Link;
  17718. struct Mem5Link {
  17719. int next; /* Index of next free chunk */
  17720. int prev; /* Index of previous free chunk */
  17721. };
  17722. /*
  17723. ** Maximum size of any allocation is ((1<<LOGMAX)*mem5.szAtom). Since
  17724. ** mem5.szAtom is always at least 8 and 32-bit integers are used,
  17725. ** it is not actually possible to reach this limit.
  17726. */
  17727. #define LOGMAX 30
  17728. /*
  17729. ** Masks used for mem5.aCtrl[] elements.
  17730. */
  17731. #define CTRL_LOGSIZE 0x1f /* Log2 Size of this block */
  17732. #define CTRL_FREE 0x20 /* True if not checked out */
  17733. /*
  17734. ** All of the static variables used by this module are collected
  17735. ** into a single structure named "mem5". This is to keep the
  17736. ** static variables organized and to reduce namespace pollution
  17737. ** when this module is combined with other in the amalgamation.
  17738. */
  17739. static SQLITE_WSD struct Mem5Global {
  17740. /*
  17741. ** Memory available for allocation
  17742. */
  17743. int szAtom; /* Smallest possible allocation in bytes */
  17744. int nBlock; /* Number of szAtom sized blocks in zPool */
  17745. u8 *zPool; /* Memory available to be allocated */
  17746. /*
  17747. ** Mutex to control access to the memory allocation subsystem.
  17748. */
  17749. sqlite3_mutex *mutex;
  17750. /*
  17751. ** Performance statistics
  17752. */
  17753. u64 nAlloc; /* Total number of calls to malloc */
  17754. u64 totalAlloc; /* Total of all malloc calls - includes internal frag */
  17755. u64 totalExcess; /* Total internal fragmentation */
  17756. u32 currentOut; /* Current checkout, including internal fragmentation */
  17757. u32 currentCount; /* Current number of distinct checkouts */
  17758. u32 maxOut; /* Maximum instantaneous currentOut */
  17759. u32 maxCount; /* Maximum instantaneous currentCount */
  17760. u32 maxRequest; /* Largest allocation (exclusive of internal frag) */
  17761. /*
  17762. ** Lists of free blocks. aiFreelist[0] is a list of free blocks of
  17763. ** size mem5.szAtom. aiFreelist[1] holds blocks of size szAtom*2.
  17764. ** and so forth.
  17765. */
  17766. int aiFreelist[LOGMAX+1];
  17767. /*
  17768. ** Space for tracking which blocks are checked out and the size
  17769. ** of each block. One byte per block.
  17770. */
  17771. u8 *aCtrl;
  17772. } mem5;
  17773. /*
  17774. ** Access the static variable through a macro for SQLITE_OMIT_WSD.
  17775. */
  17776. #define mem5 GLOBAL(struct Mem5Global, mem5)
  17777. /*
  17778. ** Assuming mem5.zPool is divided up into an array of Mem5Link
  17779. ** structures, return a pointer to the idx-th such link.
  17780. */
  17781. #define MEM5LINK(idx) ((Mem5Link *)(&mem5.zPool[(idx)*mem5.szAtom]))
  17782. /*
  17783. ** Unlink the chunk at mem5.aPool[i] from list it is currently
  17784. ** on. It should be found on mem5.aiFreelist[iLogsize].
  17785. */
  17786. static void memsys5Unlink(int i, int iLogsize){
  17787. int next, prev;
  17788. assert( i>=0 && i<mem5.nBlock );
  17789. assert( iLogsize>=0 && iLogsize<=LOGMAX );
  17790. assert( (mem5.aCtrl[i] & CTRL_LOGSIZE)==iLogsize );
  17791. next = MEM5LINK(i)->next;
  17792. prev = MEM5LINK(i)->prev;
  17793. if( prev<0 ){
  17794. mem5.aiFreelist[iLogsize] = next;
  17795. }else{
  17796. MEM5LINK(prev)->next = next;
  17797. }
  17798. if( next>=0 ){
  17799. MEM5LINK(next)->prev = prev;
  17800. }
  17801. }
  17802. /*
  17803. ** Link the chunk at mem5.aPool[i] so that is on the iLogsize
  17804. ** free list.
  17805. */
  17806. static void memsys5Link(int i, int iLogsize){
  17807. int x;
  17808. assert( sqlite3_mutex_held(mem5.mutex) );
  17809. assert( i>=0 && i<mem5.nBlock );
  17810. assert( iLogsize>=0 && iLogsize<=LOGMAX );
  17811. assert( (mem5.aCtrl[i] & CTRL_LOGSIZE)==iLogsize );
  17812. x = MEM5LINK(i)->next = mem5.aiFreelist[iLogsize];
  17813. MEM5LINK(i)->prev = -1;
  17814. if( x>=0 ){
  17815. assert( x<mem5.nBlock );
  17816. MEM5LINK(x)->prev = i;
  17817. }
  17818. mem5.aiFreelist[iLogsize] = i;
  17819. }
  17820. /*
  17821. ** If the STATIC_MEM mutex is not already held, obtain it now. The mutex
  17822. ** will already be held (obtained by code in malloc.c) if
  17823. ** sqlite3GlobalConfig.bMemStat is true.
  17824. */
  17825. static void memsys5Enter(void){
  17826. sqlite3_mutex_enter(mem5.mutex);
  17827. }
  17828. static void memsys5Leave(void){
  17829. sqlite3_mutex_leave(mem5.mutex);
  17830. }
  17831. /*
  17832. ** Return the size of an outstanding allocation, in bytes. The
  17833. ** size returned omits the 8-byte header overhead. This only
  17834. ** works for chunks that are currently checked out.
  17835. */
  17836. static int memsys5Size(void *p){
  17837. int iSize = 0;
  17838. if( p ){
  17839. int i = (int)(((u8 *)p-mem5.zPool)/mem5.szAtom);
  17840. assert( i>=0 && i<mem5.nBlock );
  17841. iSize = mem5.szAtom * (1 << (mem5.aCtrl[i]&CTRL_LOGSIZE));
  17842. }
  17843. return iSize;
  17844. }
  17845. /*
  17846. ** Return a block of memory of at least nBytes in size.
  17847. ** Return NULL if unable. Return NULL if nBytes==0.
  17848. **
  17849. ** The caller guarantees that nByte is positive.
  17850. **
  17851. ** The caller has obtained a mutex prior to invoking this
  17852. ** routine so there is never any chance that two or more
  17853. ** threads can be in this routine at the same time.
  17854. */
  17855. static void *memsys5MallocUnsafe(int nByte){
  17856. int i; /* Index of a mem5.aPool[] slot */
  17857. int iBin; /* Index into mem5.aiFreelist[] */
  17858. int iFullSz; /* Size of allocation rounded up to power of 2 */
  17859. int iLogsize; /* Log2 of iFullSz/POW2_MIN */
  17860. /* nByte must be a positive */
  17861. assert( nByte>0 );
  17862. /* Keep track of the maximum allocation request. Even unfulfilled
  17863. ** requests are counted */
  17864. if( (u32)nByte>mem5.maxRequest ){
  17865. mem5.maxRequest = nByte;
  17866. }
  17867. /* Abort if the requested allocation size is larger than the largest
  17868. ** power of two that we can represent using 32-bit signed integers.
  17869. */
  17870. if( nByte > 0x40000000 ){
  17871. return 0;
  17872. }
  17873. /* Round nByte up to the next valid power of two */
  17874. for(iFullSz=mem5.szAtom, iLogsize=0; iFullSz<nByte; iFullSz *= 2, iLogsize++){}
  17875. /* Make sure mem5.aiFreelist[iLogsize] contains at least one free
  17876. ** block. If not, then split a block of the next larger power of
  17877. ** two in order to create a new free block of size iLogsize.
  17878. */
  17879. for(iBin=iLogsize; iBin<=LOGMAX && mem5.aiFreelist[iBin]<0; iBin++){}
  17880. if( iBin>LOGMAX ){
  17881. testcase( sqlite3GlobalConfig.xLog!=0 );
  17882. sqlite3_log(SQLITE_NOMEM, "failed to allocate %u bytes", nByte);
  17883. return 0;
  17884. }
  17885. i = mem5.aiFreelist[iBin];
  17886. memsys5Unlink(i, iBin);
  17887. while( iBin>iLogsize ){
  17888. int newSize;
  17889. iBin--;
  17890. newSize = 1 << iBin;
  17891. mem5.aCtrl[i+newSize] = CTRL_FREE | iBin;
  17892. memsys5Link(i+newSize, iBin);
  17893. }
  17894. mem5.aCtrl[i] = iLogsize;
  17895. /* Update allocator performance statistics. */
  17896. mem5.nAlloc++;
  17897. mem5.totalAlloc += iFullSz;
  17898. mem5.totalExcess += iFullSz - nByte;
  17899. mem5.currentCount++;
  17900. mem5.currentOut += iFullSz;
  17901. if( mem5.maxCount<mem5.currentCount ) mem5.maxCount = mem5.currentCount;
  17902. if( mem5.maxOut<mem5.currentOut ) mem5.maxOut = mem5.currentOut;
  17903. #ifdef SQLITE_DEBUG
  17904. /* Make sure the allocated memory does not assume that it is set to zero
  17905. ** or retains a value from a previous allocation */
  17906. memset(&mem5.zPool[i*mem5.szAtom], 0xAA, iFullSz);
  17907. #endif
  17908. /* Return a pointer to the allocated memory. */
  17909. return (void*)&mem5.zPool[i*mem5.szAtom];
  17910. }
  17911. /*
  17912. ** Free an outstanding memory allocation.
  17913. */
  17914. static void memsys5FreeUnsafe(void *pOld){
  17915. u32 size, iLogsize;
  17916. int iBlock;
  17917. /* Set iBlock to the index of the block pointed to by pOld in
  17918. ** the array of mem5.szAtom byte blocks pointed to by mem5.zPool.
  17919. */
  17920. iBlock = (int)(((u8 *)pOld-mem5.zPool)/mem5.szAtom);
  17921. /* Check that the pointer pOld points to a valid, non-free block. */
  17922. assert( iBlock>=0 && iBlock<mem5.nBlock );
  17923. assert( ((u8 *)pOld-mem5.zPool)%mem5.szAtom==0 );
  17924. assert( (mem5.aCtrl[iBlock] & CTRL_FREE)==0 );
  17925. iLogsize = mem5.aCtrl[iBlock] & CTRL_LOGSIZE;
  17926. size = 1<<iLogsize;
  17927. assert( iBlock+size-1<(u32)mem5.nBlock );
  17928. mem5.aCtrl[iBlock] |= CTRL_FREE;
  17929. mem5.aCtrl[iBlock+size-1] |= CTRL_FREE;
  17930. assert( mem5.currentCount>0 );
  17931. assert( mem5.currentOut>=(size*mem5.szAtom) );
  17932. mem5.currentCount--;
  17933. mem5.currentOut -= size*mem5.szAtom;
  17934. assert( mem5.currentOut>0 || mem5.currentCount==0 );
  17935. assert( mem5.currentCount>0 || mem5.currentOut==0 );
  17936. mem5.aCtrl[iBlock] = CTRL_FREE | iLogsize;
  17937. while( ALWAYS(iLogsize<LOGMAX) ){
  17938. int iBuddy;
  17939. if( (iBlock>>iLogsize) & 1 ){
  17940. iBuddy = iBlock - size;
  17941. }else{
  17942. iBuddy = iBlock + size;
  17943. }
  17944. assert( iBuddy>=0 );
  17945. if( (iBuddy+(1<<iLogsize))>mem5.nBlock ) break;
  17946. if( mem5.aCtrl[iBuddy]!=(CTRL_FREE | iLogsize) ) break;
  17947. memsys5Unlink(iBuddy, iLogsize);
  17948. iLogsize++;
  17949. if( iBuddy<iBlock ){
  17950. mem5.aCtrl[iBuddy] = CTRL_FREE | iLogsize;
  17951. mem5.aCtrl[iBlock] = 0;
  17952. iBlock = iBuddy;
  17953. }else{
  17954. mem5.aCtrl[iBlock] = CTRL_FREE | iLogsize;
  17955. mem5.aCtrl[iBuddy] = 0;
  17956. }
  17957. size *= 2;
  17958. }
  17959. #ifdef SQLITE_DEBUG
  17960. /* Overwrite freed memory with the 0x55 bit pattern to verify that it is
  17961. ** not used after being freed */
  17962. memset(&mem5.zPool[iBlock*mem5.szAtom], 0x55, size);
  17963. #endif
  17964. memsys5Link(iBlock, iLogsize);
  17965. }
  17966. /*
  17967. ** Allocate nBytes of memory.
  17968. */
  17969. static void *memsys5Malloc(int nBytes){
  17970. sqlite3_int64 *p = 0;
  17971. if( nBytes>0 ){
  17972. memsys5Enter();
  17973. p = memsys5MallocUnsafe(nBytes);
  17974. memsys5Leave();
  17975. }
  17976. return (void*)p;
  17977. }
  17978. /*
  17979. ** Free memory.
  17980. **
  17981. ** The outer layer memory allocator prevents this routine from
  17982. ** being called with pPrior==0.
  17983. */
  17984. static void memsys5Free(void *pPrior){
  17985. assert( pPrior!=0 );
  17986. memsys5Enter();
  17987. memsys5FreeUnsafe(pPrior);
  17988. memsys5Leave();
  17989. }
  17990. /*
  17991. ** Change the size of an existing memory allocation.
  17992. **
  17993. ** The outer layer memory allocator prevents this routine from
  17994. ** being called with pPrior==0.
  17995. **
  17996. ** nBytes is always a value obtained from a prior call to
  17997. ** memsys5Round(). Hence nBytes is always a non-negative power
  17998. ** of two. If nBytes==0 that means that an oversize allocation
  17999. ** (an allocation larger than 0x40000000) was requested and this
  18000. ** routine should return 0 without freeing pPrior.
  18001. */
  18002. static void *memsys5Realloc(void *pPrior, int nBytes){
  18003. int nOld;
  18004. void *p;
  18005. assert( pPrior!=0 );
  18006. assert( (nBytes&(nBytes-1))==0 ); /* EV: R-46199-30249 */
  18007. assert( nBytes>=0 );
  18008. if( nBytes==0 ){
  18009. return 0;
  18010. }
  18011. nOld = memsys5Size(pPrior);
  18012. if( nBytes<=nOld ){
  18013. return pPrior;
  18014. }
  18015. memsys5Enter();
  18016. p = memsys5MallocUnsafe(nBytes);
  18017. if( p ){
  18018. memcpy(p, pPrior, nOld);
  18019. memsys5FreeUnsafe(pPrior);
  18020. }
  18021. memsys5Leave();
  18022. return p;
  18023. }
  18024. /*
  18025. ** Round up a request size to the next valid allocation size. If
  18026. ** the allocation is too large to be handled by this allocation system,
  18027. ** return 0.
  18028. **
  18029. ** All allocations must be a power of two and must be expressed by a
  18030. ** 32-bit signed integer. Hence the largest allocation is 0x40000000
  18031. ** or 1073741824 bytes.
  18032. */
  18033. static int memsys5Roundup(int n){
  18034. int iFullSz;
  18035. if( n > 0x40000000 ) return 0;
  18036. for(iFullSz=mem5.szAtom; iFullSz<n; iFullSz *= 2);
  18037. return iFullSz;
  18038. }
  18039. /*
  18040. ** Return the ceiling of the logarithm base 2 of iValue.
  18041. **
  18042. ** Examples: memsys5Log(1) -> 0
  18043. ** memsys5Log(2) -> 1
  18044. ** memsys5Log(4) -> 2
  18045. ** memsys5Log(5) -> 3
  18046. ** memsys5Log(8) -> 3
  18047. ** memsys5Log(9) -> 4
  18048. */
  18049. static int memsys5Log(int iValue){
  18050. int iLog;
  18051. for(iLog=0; (iLog<(int)((sizeof(int)*8)-1)) && (1<<iLog)<iValue; iLog++);
  18052. return iLog;
  18053. }
  18054. /*
  18055. ** Initialize the memory allocator.
  18056. **
  18057. ** This routine is not threadsafe. The caller must be holding a mutex
  18058. ** to prevent multiple threads from entering at the same time.
  18059. */
  18060. static int memsys5Init(void *NotUsed){
  18061. int ii; /* Loop counter */
  18062. int nByte; /* Number of bytes of memory available to this allocator */
  18063. u8 *zByte; /* Memory usable by this allocator */
  18064. int nMinLog; /* Log base 2 of minimum allocation size in bytes */
  18065. int iOffset; /* An offset into mem5.aCtrl[] */
  18066. UNUSED_PARAMETER(NotUsed);
  18067. /* For the purposes of this routine, disable the mutex */
  18068. mem5.mutex = 0;
  18069. /* The size of a Mem5Link object must be a power of two. Verify that
  18070. ** this is case.
  18071. */
  18072. assert( (sizeof(Mem5Link)&(sizeof(Mem5Link)-1))==0 );
  18073. nByte = sqlite3GlobalConfig.nHeap;
  18074. zByte = (u8*)sqlite3GlobalConfig.pHeap;
  18075. assert( zByte!=0 ); /* sqlite3_config() does not allow otherwise */
  18076. /* boundaries on sqlite3GlobalConfig.mnReq are enforced in sqlite3_config() */
  18077. nMinLog = memsys5Log(sqlite3GlobalConfig.mnReq);
  18078. mem5.szAtom = (1<<nMinLog);
  18079. while( (int)sizeof(Mem5Link)>mem5.szAtom ){
  18080. mem5.szAtom = mem5.szAtom << 1;
  18081. }
  18082. mem5.nBlock = (nByte / (mem5.szAtom+sizeof(u8)));
  18083. mem5.zPool = zByte;
  18084. mem5.aCtrl = (u8 *)&mem5.zPool[mem5.nBlock*mem5.szAtom];
  18085. for(ii=0; ii<=LOGMAX; ii++){
  18086. mem5.aiFreelist[ii] = -1;
  18087. }
  18088. iOffset = 0;
  18089. for(ii=LOGMAX; ii>=0; ii--){
  18090. int nAlloc = (1<<ii);
  18091. if( (iOffset+nAlloc)<=mem5.nBlock ){
  18092. mem5.aCtrl[iOffset] = ii | CTRL_FREE;
  18093. memsys5Link(iOffset, ii);
  18094. iOffset += nAlloc;
  18095. }
  18096. assert((iOffset+nAlloc)>mem5.nBlock);
  18097. }
  18098. /* If a mutex is required for normal operation, allocate one */
  18099. if( sqlite3GlobalConfig.bMemstat==0 ){
  18100. mem5.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
  18101. }
  18102. return SQLITE_OK;
  18103. }
  18104. /*
  18105. ** Deinitialize this module.
  18106. */
  18107. static void memsys5Shutdown(void *NotUsed){
  18108. UNUSED_PARAMETER(NotUsed);
  18109. mem5.mutex = 0;
  18110. return;
  18111. }
  18112. #ifdef SQLITE_TEST
  18113. /*
  18114. ** Open the file indicated and write a log of all unfreed memory
  18115. ** allocations into that log.
  18116. */
  18117. SQLITE_PRIVATE void sqlite3Memsys5Dump(const char *zFilename){
  18118. FILE *out;
  18119. int i, j, n;
  18120. int nMinLog;
  18121. if( zFilename==0 || zFilename[0]==0 ){
  18122. out = stdout;
  18123. }else{
  18124. out = fopen(zFilename, "w");
  18125. if( out==0 ){
  18126. fprintf(stderr, "** Unable to output memory debug output log: %s **\n",
  18127. zFilename);
  18128. return;
  18129. }
  18130. }
  18131. memsys5Enter();
  18132. nMinLog = memsys5Log(mem5.szAtom);
  18133. for(i=0; i<=LOGMAX && i+nMinLog<32; i++){
  18134. for(n=0, j=mem5.aiFreelist[i]; j>=0; j = MEM5LINK(j)->next, n++){}
  18135. fprintf(out, "freelist items of size %d: %d\n", mem5.szAtom << i, n);
  18136. }
  18137. fprintf(out, "mem5.nAlloc = %llu\n", mem5.nAlloc);
  18138. fprintf(out, "mem5.totalAlloc = %llu\n", mem5.totalAlloc);
  18139. fprintf(out, "mem5.totalExcess = %llu\n", mem5.totalExcess);
  18140. fprintf(out, "mem5.currentOut = %u\n", mem5.currentOut);
  18141. fprintf(out, "mem5.currentCount = %u\n", mem5.currentCount);
  18142. fprintf(out, "mem5.maxOut = %u\n", mem5.maxOut);
  18143. fprintf(out, "mem5.maxCount = %u\n", mem5.maxCount);
  18144. fprintf(out, "mem5.maxRequest = %u\n", mem5.maxRequest);
  18145. memsys5Leave();
  18146. if( out==stdout ){
  18147. fflush(stdout);
  18148. }else{
  18149. fclose(out);
  18150. }
  18151. }
  18152. #endif
  18153. /*
  18154. ** This routine is the only routine in this file with external
  18155. ** linkage. It returns a pointer to a static sqlite3_mem_methods
  18156. ** struct populated with the memsys5 methods.
  18157. */
  18158. SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys5(void){
  18159. static const sqlite3_mem_methods memsys5Methods = {
  18160. memsys5Malloc,
  18161. memsys5Free,
  18162. memsys5Realloc,
  18163. memsys5Size,
  18164. memsys5Roundup,
  18165. memsys5Init,
  18166. memsys5Shutdown,
  18167. 0
  18168. };
  18169. return &memsys5Methods;
  18170. }
  18171. #endif /* SQLITE_ENABLE_MEMSYS5 */
  18172. /************** End of mem5.c ************************************************/
  18173. /************** Begin file mutex.c *******************************************/
  18174. /*
  18175. ** 2007 August 14
  18176. **
  18177. ** The author disclaims copyright to this source code. In place of
  18178. ** a legal notice, here is a blessing:
  18179. **
  18180. ** May you do good and not evil.
  18181. ** May you find forgiveness for yourself and forgive others.
  18182. ** May you share freely, never taking more than you give.
  18183. **
  18184. *************************************************************************
  18185. ** This file contains the C functions that implement mutexes.
  18186. **
  18187. ** This file contains code that is common across all mutex implementations.
  18188. */
  18189. #if defined(SQLITE_DEBUG) && !defined(SQLITE_MUTEX_OMIT)
  18190. /*
  18191. ** For debugging purposes, record when the mutex subsystem is initialized
  18192. ** and uninitialized so that we can assert() if there is an attempt to
  18193. ** allocate a mutex while the system is uninitialized.
  18194. */
  18195. static SQLITE_WSD int mutexIsInit = 0;
  18196. #endif /* SQLITE_DEBUG */
  18197. #ifndef SQLITE_MUTEX_OMIT
  18198. /*
  18199. ** Initialize the mutex system.
  18200. */
  18201. SQLITE_PRIVATE int sqlite3MutexInit(void){
  18202. int rc = SQLITE_OK;
  18203. if( !sqlite3GlobalConfig.mutex.xMutexAlloc ){
  18204. /* If the xMutexAlloc method has not been set, then the user did not
  18205. ** install a mutex implementation via sqlite3_config() prior to
  18206. ** sqlite3_initialize() being called. This block copies pointers to
  18207. ** the default implementation into the sqlite3GlobalConfig structure.
  18208. */
  18209. sqlite3_mutex_methods const *pFrom;
  18210. sqlite3_mutex_methods *pTo = &sqlite3GlobalConfig.mutex;
  18211. if( sqlite3GlobalConfig.bCoreMutex ){
  18212. pFrom = sqlite3DefaultMutex();
  18213. }else{
  18214. pFrom = sqlite3NoopMutex();
  18215. }
  18216. memcpy(pTo, pFrom, offsetof(sqlite3_mutex_methods, xMutexAlloc));
  18217. memcpy(&pTo->xMutexFree, &pFrom->xMutexFree,
  18218. sizeof(*pTo) - offsetof(sqlite3_mutex_methods, xMutexFree));
  18219. pTo->xMutexAlloc = pFrom->xMutexAlloc;
  18220. }
  18221. rc = sqlite3GlobalConfig.mutex.xMutexInit();
  18222. #ifdef SQLITE_DEBUG
  18223. GLOBAL(int, mutexIsInit) = 1;
  18224. #endif
  18225. return rc;
  18226. }
  18227. /*
  18228. ** Shutdown the mutex system. This call frees resources allocated by
  18229. ** sqlite3MutexInit().
  18230. */
  18231. SQLITE_PRIVATE int sqlite3MutexEnd(void){
  18232. int rc = SQLITE_OK;
  18233. if( sqlite3GlobalConfig.mutex.xMutexEnd ){
  18234. rc = sqlite3GlobalConfig.mutex.xMutexEnd();
  18235. }
  18236. #ifdef SQLITE_DEBUG
  18237. GLOBAL(int, mutexIsInit) = 0;
  18238. #endif
  18239. return rc;
  18240. }
  18241. /*
  18242. ** Retrieve a pointer to a static mutex or allocate a new dynamic one.
  18243. */
  18244. SQLITE_API sqlite3_mutex *SQLITE_STDCALL sqlite3_mutex_alloc(int id){
  18245. #ifndef SQLITE_OMIT_AUTOINIT
  18246. if( id<=SQLITE_MUTEX_RECURSIVE && sqlite3_initialize() ) return 0;
  18247. if( id>SQLITE_MUTEX_RECURSIVE && sqlite3MutexInit() ) return 0;
  18248. #endif
  18249. return sqlite3GlobalConfig.mutex.xMutexAlloc(id);
  18250. }
  18251. SQLITE_PRIVATE sqlite3_mutex *sqlite3MutexAlloc(int id){
  18252. if( !sqlite3GlobalConfig.bCoreMutex ){
  18253. return 0;
  18254. }
  18255. assert( GLOBAL(int, mutexIsInit) );
  18256. return sqlite3GlobalConfig.mutex.xMutexAlloc(id);
  18257. }
  18258. /*
  18259. ** Free a dynamic mutex.
  18260. */
  18261. SQLITE_API void SQLITE_STDCALL sqlite3_mutex_free(sqlite3_mutex *p){
  18262. if( p ){
  18263. sqlite3GlobalConfig.mutex.xMutexFree(p);
  18264. }
  18265. }
  18266. /*
  18267. ** Obtain the mutex p. If some other thread already has the mutex, block
  18268. ** until it can be obtained.
  18269. */
  18270. SQLITE_API void SQLITE_STDCALL sqlite3_mutex_enter(sqlite3_mutex *p){
  18271. if( p ){
  18272. sqlite3GlobalConfig.mutex.xMutexEnter(p);
  18273. }
  18274. }
  18275. /*
  18276. ** Obtain the mutex p. If successful, return SQLITE_OK. Otherwise, if another
  18277. ** thread holds the mutex and it cannot be obtained, return SQLITE_BUSY.
  18278. */
  18279. SQLITE_API int SQLITE_STDCALL sqlite3_mutex_try(sqlite3_mutex *p){
  18280. int rc = SQLITE_OK;
  18281. if( p ){
  18282. return sqlite3GlobalConfig.mutex.xMutexTry(p);
  18283. }
  18284. return rc;
  18285. }
  18286. /*
  18287. ** The sqlite3_mutex_leave() routine exits a mutex that was previously
  18288. ** entered by the same thread. The behavior is undefined if the mutex
  18289. ** is not currently entered. If a NULL pointer is passed as an argument
  18290. ** this function is a no-op.
  18291. */
  18292. SQLITE_API void SQLITE_STDCALL sqlite3_mutex_leave(sqlite3_mutex *p){
  18293. if( p ){
  18294. sqlite3GlobalConfig.mutex.xMutexLeave(p);
  18295. }
  18296. }
  18297. #ifndef NDEBUG
  18298. /*
  18299. ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
  18300. ** intended for use inside assert() statements.
  18301. */
  18302. SQLITE_API int SQLITE_STDCALL sqlite3_mutex_held(sqlite3_mutex *p){
  18303. return p==0 || sqlite3GlobalConfig.mutex.xMutexHeld(p);
  18304. }
  18305. SQLITE_API int SQLITE_STDCALL sqlite3_mutex_notheld(sqlite3_mutex *p){
  18306. return p==0 || sqlite3GlobalConfig.mutex.xMutexNotheld(p);
  18307. }
  18308. #endif
  18309. #endif /* !defined(SQLITE_MUTEX_OMIT) */
  18310. /************** End of mutex.c ***********************************************/
  18311. /************** Begin file mutex_noop.c **************************************/
  18312. /*
  18313. ** 2008 October 07
  18314. **
  18315. ** The author disclaims copyright to this source code. In place of
  18316. ** a legal notice, here is a blessing:
  18317. **
  18318. ** May you do good and not evil.
  18319. ** May you find forgiveness for yourself and forgive others.
  18320. ** May you share freely, never taking more than you give.
  18321. **
  18322. *************************************************************************
  18323. ** This file contains the C functions that implement mutexes.
  18324. **
  18325. ** This implementation in this file does not provide any mutual
  18326. ** exclusion and is thus suitable for use only in applications
  18327. ** that use SQLite in a single thread. The routines defined
  18328. ** here are place-holders. Applications can substitute working
  18329. ** mutex routines at start-time using the
  18330. **
  18331. ** sqlite3_config(SQLITE_CONFIG_MUTEX,...)
  18332. **
  18333. ** interface.
  18334. **
  18335. ** If compiled with SQLITE_DEBUG, then additional logic is inserted
  18336. ** that does error checking on mutexes to make sure they are being
  18337. ** called correctly.
  18338. */
  18339. #ifndef SQLITE_MUTEX_OMIT
  18340. #ifndef SQLITE_DEBUG
  18341. /*
  18342. ** Stub routines for all mutex methods.
  18343. **
  18344. ** This routines provide no mutual exclusion or error checking.
  18345. */
  18346. static int noopMutexInit(void){ return SQLITE_OK; }
  18347. static int noopMutexEnd(void){ return SQLITE_OK; }
  18348. static sqlite3_mutex *noopMutexAlloc(int id){
  18349. UNUSED_PARAMETER(id);
  18350. return (sqlite3_mutex*)8;
  18351. }
  18352. static void noopMutexFree(sqlite3_mutex *p){ UNUSED_PARAMETER(p); return; }
  18353. static void noopMutexEnter(sqlite3_mutex *p){ UNUSED_PARAMETER(p); return; }
  18354. static int noopMutexTry(sqlite3_mutex *p){
  18355. UNUSED_PARAMETER(p);
  18356. return SQLITE_OK;
  18357. }
  18358. static void noopMutexLeave(sqlite3_mutex *p){ UNUSED_PARAMETER(p); return; }
  18359. SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3NoopMutex(void){
  18360. static const sqlite3_mutex_methods sMutex = {
  18361. noopMutexInit,
  18362. noopMutexEnd,
  18363. noopMutexAlloc,
  18364. noopMutexFree,
  18365. noopMutexEnter,
  18366. noopMutexTry,
  18367. noopMutexLeave,
  18368. 0,
  18369. 0,
  18370. };
  18371. return &sMutex;
  18372. }
  18373. #endif /* !SQLITE_DEBUG */
  18374. #ifdef SQLITE_DEBUG
  18375. /*
  18376. ** In this implementation, error checking is provided for testing
  18377. ** and debugging purposes. The mutexes still do not provide any
  18378. ** mutual exclusion.
  18379. */
  18380. /*
  18381. ** The mutex object
  18382. */
  18383. typedef struct sqlite3_debug_mutex {
  18384. int id; /* The mutex type */
  18385. int cnt; /* Number of entries without a matching leave */
  18386. } sqlite3_debug_mutex;
  18387. /*
  18388. ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
  18389. ** intended for use inside assert() statements.
  18390. */
  18391. static int debugMutexHeld(sqlite3_mutex *pX){
  18392. sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
  18393. return p==0 || p->cnt>0;
  18394. }
  18395. static int debugMutexNotheld(sqlite3_mutex *pX){
  18396. sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
  18397. return p==0 || p->cnt==0;
  18398. }
  18399. /*
  18400. ** Initialize and deinitialize the mutex subsystem.
  18401. */
  18402. static int debugMutexInit(void){ return SQLITE_OK; }
  18403. static int debugMutexEnd(void){ return SQLITE_OK; }
  18404. /*
  18405. ** The sqlite3_mutex_alloc() routine allocates a new
  18406. ** mutex and returns a pointer to it. If it returns NULL
  18407. ** that means that a mutex could not be allocated.
  18408. */
  18409. static sqlite3_mutex *debugMutexAlloc(int id){
  18410. static sqlite3_debug_mutex aStatic[SQLITE_MUTEX_STATIC_APP3 - 1];
  18411. sqlite3_debug_mutex *pNew = 0;
  18412. switch( id ){
  18413. case SQLITE_MUTEX_FAST:
  18414. case SQLITE_MUTEX_RECURSIVE: {
  18415. pNew = sqlite3Malloc(sizeof(*pNew));
  18416. if( pNew ){
  18417. pNew->id = id;
  18418. pNew->cnt = 0;
  18419. }
  18420. break;
  18421. }
  18422. default: {
  18423. #ifdef SQLITE_ENABLE_API_ARMOR
  18424. if( id-2<0 || id-2>=ArraySize(aStatic) ){
  18425. (void)SQLITE_MISUSE_BKPT;
  18426. return 0;
  18427. }
  18428. #endif
  18429. pNew = &aStatic[id-2];
  18430. pNew->id = id;
  18431. break;
  18432. }
  18433. }
  18434. return (sqlite3_mutex*)pNew;
  18435. }
  18436. /*
  18437. ** This routine deallocates a previously allocated mutex.
  18438. */
  18439. static void debugMutexFree(sqlite3_mutex *pX){
  18440. sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
  18441. assert( p->cnt==0 );
  18442. if( p->id==SQLITE_MUTEX_RECURSIVE || p->id==SQLITE_MUTEX_FAST ){
  18443. sqlite3_free(p);
  18444. }else{
  18445. #ifdef SQLITE_ENABLE_API_ARMOR
  18446. (void)SQLITE_MISUSE_BKPT;
  18447. #endif
  18448. }
  18449. }
  18450. /*
  18451. ** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
  18452. ** to enter a mutex. If another thread is already within the mutex,
  18453. ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
  18454. ** SQLITE_BUSY. The sqlite3_mutex_try() interface returns SQLITE_OK
  18455. ** upon successful entry. Mutexes created using SQLITE_MUTEX_RECURSIVE can
  18456. ** be entered multiple times by the same thread. In such cases the,
  18457. ** mutex must be exited an equal number of times before another thread
  18458. ** can enter. If the same thread tries to enter any other kind of mutex
  18459. ** more than once, the behavior is undefined.
  18460. */
  18461. static void debugMutexEnter(sqlite3_mutex *pX){
  18462. sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
  18463. assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(pX) );
  18464. p->cnt++;
  18465. }
  18466. static int debugMutexTry(sqlite3_mutex *pX){
  18467. sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
  18468. assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(pX) );
  18469. p->cnt++;
  18470. return SQLITE_OK;
  18471. }
  18472. /*
  18473. ** The sqlite3_mutex_leave() routine exits a mutex that was
  18474. ** previously entered by the same thread. The behavior
  18475. ** is undefined if the mutex is not currently entered or
  18476. ** is not currently allocated. SQLite will never do either.
  18477. */
  18478. static void debugMutexLeave(sqlite3_mutex *pX){
  18479. sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
  18480. assert( debugMutexHeld(pX) );
  18481. p->cnt--;
  18482. assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(pX) );
  18483. }
  18484. SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3NoopMutex(void){
  18485. static const sqlite3_mutex_methods sMutex = {
  18486. debugMutexInit,
  18487. debugMutexEnd,
  18488. debugMutexAlloc,
  18489. debugMutexFree,
  18490. debugMutexEnter,
  18491. debugMutexTry,
  18492. debugMutexLeave,
  18493. debugMutexHeld,
  18494. debugMutexNotheld
  18495. };
  18496. return &sMutex;
  18497. }
  18498. #endif /* SQLITE_DEBUG */
  18499. /*
  18500. ** If compiled with SQLITE_MUTEX_NOOP, then the no-op mutex implementation
  18501. ** is used regardless of the run-time threadsafety setting.
  18502. */
  18503. #ifdef SQLITE_MUTEX_NOOP
  18504. SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void){
  18505. return sqlite3NoopMutex();
  18506. }
  18507. #endif /* defined(SQLITE_MUTEX_NOOP) */
  18508. #endif /* !defined(SQLITE_MUTEX_OMIT) */
  18509. /************** End of mutex_noop.c ******************************************/
  18510. /************** Begin file mutex_unix.c **************************************/
  18511. /*
  18512. ** 2007 August 28
  18513. **
  18514. ** The author disclaims copyright to this source code. In place of
  18515. ** a legal notice, here is a blessing:
  18516. **
  18517. ** May you do good and not evil.
  18518. ** May you find forgiveness for yourself and forgive others.
  18519. ** May you share freely, never taking more than you give.
  18520. **
  18521. *************************************************************************
  18522. ** This file contains the C functions that implement mutexes for pthreads
  18523. */
  18524. /*
  18525. ** The code in this file is only used if we are compiling threadsafe
  18526. ** under unix with pthreads.
  18527. **
  18528. ** Note that this implementation requires a version of pthreads that
  18529. ** supports recursive mutexes.
  18530. */
  18531. #ifdef SQLITE_MUTEX_PTHREADS
  18532. #include <pthread.h>
  18533. /*
  18534. ** The sqlite3_mutex.id, sqlite3_mutex.nRef, and sqlite3_mutex.owner fields
  18535. ** are necessary under two condidtions: (1) Debug builds and (2) using
  18536. ** home-grown mutexes. Encapsulate these conditions into a single #define.
  18537. */
  18538. #if defined(SQLITE_DEBUG) || defined(SQLITE_HOMEGROWN_RECURSIVE_MUTEX)
  18539. # define SQLITE_MUTEX_NREF 1
  18540. #else
  18541. # define SQLITE_MUTEX_NREF 0
  18542. #endif
  18543. /*
  18544. ** Each recursive mutex is an instance of the following structure.
  18545. */
  18546. struct sqlite3_mutex {
  18547. pthread_mutex_t mutex; /* Mutex controlling the lock */
  18548. #if SQLITE_MUTEX_NREF || defined(SQLITE_ENABLE_API_ARMOR)
  18549. int id; /* Mutex type */
  18550. #endif
  18551. #if SQLITE_MUTEX_NREF
  18552. volatile int nRef; /* Number of entrances */
  18553. volatile pthread_t owner; /* Thread that is within this mutex */
  18554. int trace; /* True to trace changes */
  18555. #endif
  18556. };
  18557. #if SQLITE_MUTEX_NREF
  18558. #define SQLITE3_MUTEX_INITIALIZER { PTHREAD_MUTEX_INITIALIZER, 0, 0, (pthread_t)0, 0 }
  18559. #else
  18560. #define SQLITE3_MUTEX_INITIALIZER { PTHREAD_MUTEX_INITIALIZER }
  18561. #endif
  18562. /*
  18563. ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
  18564. ** intended for use only inside assert() statements. On some platforms,
  18565. ** there might be race conditions that can cause these routines to
  18566. ** deliver incorrect results. In particular, if pthread_equal() is
  18567. ** not an atomic operation, then these routines might delivery
  18568. ** incorrect results. On most platforms, pthread_equal() is a
  18569. ** comparison of two integers and is therefore atomic. But we are
  18570. ** told that HPUX is not such a platform. If so, then these routines
  18571. ** will not always work correctly on HPUX.
  18572. **
  18573. ** On those platforms where pthread_equal() is not atomic, SQLite
  18574. ** should be compiled without -DSQLITE_DEBUG and with -DNDEBUG to
  18575. ** make sure no assert() statements are evaluated and hence these
  18576. ** routines are never called.
  18577. */
  18578. #if !defined(NDEBUG) || defined(SQLITE_DEBUG)
  18579. static int pthreadMutexHeld(sqlite3_mutex *p){
  18580. return (p->nRef!=0 && pthread_equal(p->owner, pthread_self()));
  18581. }
  18582. static int pthreadMutexNotheld(sqlite3_mutex *p){
  18583. return p->nRef==0 || pthread_equal(p->owner, pthread_self())==0;
  18584. }
  18585. #endif
  18586. /*
  18587. ** Initialize and deinitialize the mutex subsystem.
  18588. */
  18589. static int pthreadMutexInit(void){ return SQLITE_OK; }
  18590. static int pthreadMutexEnd(void){ return SQLITE_OK; }
  18591. /*
  18592. ** The sqlite3_mutex_alloc() routine allocates a new
  18593. ** mutex and returns a pointer to it. If it returns NULL
  18594. ** that means that a mutex could not be allocated. SQLite
  18595. ** will unwind its stack and return an error. The argument
  18596. ** to sqlite3_mutex_alloc() is one of these integer constants:
  18597. **
  18598. ** <ul>
  18599. ** <li> SQLITE_MUTEX_FAST
  18600. ** <li> SQLITE_MUTEX_RECURSIVE
  18601. ** <li> SQLITE_MUTEX_STATIC_MASTER
  18602. ** <li> SQLITE_MUTEX_STATIC_MEM
  18603. ** <li> SQLITE_MUTEX_STATIC_OPEN
  18604. ** <li> SQLITE_MUTEX_STATIC_PRNG
  18605. ** <li> SQLITE_MUTEX_STATIC_LRU
  18606. ** <li> SQLITE_MUTEX_STATIC_PMEM
  18607. ** <li> SQLITE_MUTEX_STATIC_APP1
  18608. ** <li> SQLITE_MUTEX_STATIC_APP2
  18609. ** <li> SQLITE_MUTEX_STATIC_APP3
  18610. ** </ul>
  18611. **
  18612. ** The first two constants cause sqlite3_mutex_alloc() to create
  18613. ** a new mutex. The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
  18614. ** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
  18615. ** The mutex implementation does not need to make a distinction
  18616. ** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
  18617. ** not want to. But SQLite will only request a recursive mutex in
  18618. ** cases where it really needs one. If a faster non-recursive mutex
  18619. ** implementation is available on the host platform, the mutex subsystem
  18620. ** might return such a mutex in response to SQLITE_MUTEX_FAST.
  18621. **
  18622. ** The other allowed parameters to sqlite3_mutex_alloc() each return
  18623. ** a pointer to a static preexisting mutex. Six static mutexes are
  18624. ** used by the current version of SQLite. Future versions of SQLite
  18625. ** may add additional static mutexes. Static mutexes are for internal
  18626. ** use by SQLite only. Applications that use SQLite mutexes should
  18627. ** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
  18628. ** SQLITE_MUTEX_RECURSIVE.
  18629. **
  18630. ** Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
  18631. ** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
  18632. ** returns a different mutex on every call. But for the static
  18633. ** mutex types, the same mutex is returned on every call that has
  18634. ** the same type number.
  18635. */
  18636. static sqlite3_mutex *pthreadMutexAlloc(int iType){
  18637. static sqlite3_mutex staticMutexes[] = {
  18638. SQLITE3_MUTEX_INITIALIZER,
  18639. SQLITE3_MUTEX_INITIALIZER,
  18640. SQLITE3_MUTEX_INITIALIZER,
  18641. SQLITE3_MUTEX_INITIALIZER,
  18642. SQLITE3_MUTEX_INITIALIZER,
  18643. SQLITE3_MUTEX_INITIALIZER,
  18644. SQLITE3_MUTEX_INITIALIZER,
  18645. SQLITE3_MUTEX_INITIALIZER,
  18646. SQLITE3_MUTEX_INITIALIZER
  18647. };
  18648. sqlite3_mutex *p;
  18649. switch( iType ){
  18650. case SQLITE_MUTEX_RECURSIVE: {
  18651. p = sqlite3MallocZero( sizeof(*p) );
  18652. if( p ){
  18653. #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
  18654. /* If recursive mutexes are not available, we will have to
  18655. ** build our own. See below. */
  18656. pthread_mutex_init(&p->mutex, 0);
  18657. #else
  18658. /* Use a recursive mutex if it is available */
  18659. pthread_mutexattr_t recursiveAttr;
  18660. pthread_mutexattr_init(&recursiveAttr);
  18661. pthread_mutexattr_settype(&recursiveAttr, PTHREAD_MUTEX_RECURSIVE);
  18662. pthread_mutex_init(&p->mutex, &recursiveAttr);
  18663. pthread_mutexattr_destroy(&recursiveAttr);
  18664. #endif
  18665. }
  18666. break;
  18667. }
  18668. case SQLITE_MUTEX_FAST: {
  18669. p = sqlite3MallocZero( sizeof(*p) );
  18670. if( p ){
  18671. pthread_mutex_init(&p->mutex, 0);
  18672. }
  18673. break;
  18674. }
  18675. default: {
  18676. #ifdef SQLITE_ENABLE_API_ARMOR
  18677. if( iType-2<0 || iType-2>=ArraySize(staticMutexes) ){
  18678. (void)SQLITE_MISUSE_BKPT;
  18679. return 0;
  18680. }
  18681. #endif
  18682. p = &staticMutexes[iType-2];
  18683. break;
  18684. }
  18685. }
  18686. #if SQLITE_MUTEX_NREF || defined(SQLITE_ENABLE_API_ARMOR)
  18687. if( p ) p->id = iType;
  18688. #endif
  18689. return p;
  18690. }
  18691. /*
  18692. ** This routine deallocates a previously
  18693. ** allocated mutex. SQLite is careful to deallocate every
  18694. ** mutex that it allocates.
  18695. */
  18696. static void pthreadMutexFree(sqlite3_mutex *p){
  18697. assert( p->nRef==0 );
  18698. #if SQLITE_ENABLE_API_ARMOR
  18699. if( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE )
  18700. #endif
  18701. {
  18702. pthread_mutex_destroy(&p->mutex);
  18703. sqlite3_free(p);
  18704. }
  18705. #ifdef SQLITE_ENABLE_API_ARMOR
  18706. else{
  18707. (void)SQLITE_MISUSE_BKPT;
  18708. }
  18709. #endif
  18710. }
  18711. /*
  18712. ** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
  18713. ** to enter a mutex. If another thread is already within the mutex,
  18714. ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
  18715. ** SQLITE_BUSY. The sqlite3_mutex_try() interface returns SQLITE_OK
  18716. ** upon successful entry. Mutexes created using SQLITE_MUTEX_RECURSIVE can
  18717. ** be entered multiple times by the same thread. In such cases the,
  18718. ** mutex must be exited an equal number of times before another thread
  18719. ** can enter. If the same thread tries to enter any other kind of mutex
  18720. ** more than once, the behavior is undefined.
  18721. */
  18722. static void pthreadMutexEnter(sqlite3_mutex *p){
  18723. assert( p->id==SQLITE_MUTEX_RECURSIVE || pthreadMutexNotheld(p) );
  18724. #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
  18725. /* If recursive mutexes are not available, then we have to grow
  18726. ** our own. This implementation assumes that pthread_equal()
  18727. ** is atomic - that it cannot be deceived into thinking self
  18728. ** and p->owner are equal if p->owner changes between two values
  18729. ** that are not equal to self while the comparison is taking place.
  18730. ** This implementation also assumes a coherent cache - that
  18731. ** separate processes cannot read different values from the same
  18732. ** address at the same time. If either of these two conditions
  18733. ** are not met, then the mutexes will fail and problems will result.
  18734. */
  18735. {
  18736. pthread_t self = pthread_self();
  18737. if( p->nRef>0 && pthread_equal(p->owner, self) ){
  18738. p->nRef++;
  18739. }else{
  18740. pthread_mutex_lock(&p->mutex);
  18741. assert( p->nRef==0 );
  18742. p->owner = self;
  18743. p->nRef = 1;
  18744. }
  18745. }
  18746. #else
  18747. /* Use the built-in recursive mutexes if they are available.
  18748. */
  18749. pthread_mutex_lock(&p->mutex);
  18750. #if SQLITE_MUTEX_NREF
  18751. assert( p->nRef>0 || p->owner==0 );
  18752. p->owner = pthread_self();
  18753. p->nRef++;
  18754. #endif
  18755. #endif
  18756. #ifdef SQLITE_DEBUG
  18757. if( p->trace ){
  18758. printf("enter mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
  18759. }
  18760. #endif
  18761. }
  18762. static int pthreadMutexTry(sqlite3_mutex *p){
  18763. int rc;
  18764. assert( p->id==SQLITE_MUTEX_RECURSIVE || pthreadMutexNotheld(p) );
  18765. #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
  18766. /* If recursive mutexes are not available, then we have to grow
  18767. ** our own. This implementation assumes that pthread_equal()
  18768. ** is atomic - that it cannot be deceived into thinking self
  18769. ** and p->owner are equal if p->owner changes between two values
  18770. ** that are not equal to self while the comparison is taking place.
  18771. ** This implementation also assumes a coherent cache - that
  18772. ** separate processes cannot read different values from the same
  18773. ** address at the same time. If either of these two conditions
  18774. ** are not met, then the mutexes will fail and problems will result.
  18775. */
  18776. {
  18777. pthread_t self = pthread_self();
  18778. if( p->nRef>0 && pthread_equal(p->owner, self) ){
  18779. p->nRef++;
  18780. rc = SQLITE_OK;
  18781. }else if( pthread_mutex_trylock(&p->mutex)==0 ){
  18782. assert( p->nRef==0 );
  18783. p->owner = self;
  18784. p->nRef = 1;
  18785. rc = SQLITE_OK;
  18786. }else{
  18787. rc = SQLITE_BUSY;
  18788. }
  18789. }
  18790. #else
  18791. /* Use the built-in recursive mutexes if they are available.
  18792. */
  18793. if( pthread_mutex_trylock(&p->mutex)==0 ){
  18794. #if SQLITE_MUTEX_NREF
  18795. p->owner = pthread_self();
  18796. p->nRef++;
  18797. #endif
  18798. rc = SQLITE_OK;
  18799. }else{
  18800. rc = SQLITE_BUSY;
  18801. }
  18802. #endif
  18803. #ifdef SQLITE_DEBUG
  18804. if( rc==SQLITE_OK && p->trace ){
  18805. printf("enter mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
  18806. }
  18807. #endif
  18808. return rc;
  18809. }
  18810. /*
  18811. ** The sqlite3_mutex_leave() routine exits a mutex that was
  18812. ** previously entered by the same thread. The behavior
  18813. ** is undefined if the mutex is not currently entered or
  18814. ** is not currently allocated. SQLite will never do either.
  18815. */
  18816. static void pthreadMutexLeave(sqlite3_mutex *p){
  18817. assert( pthreadMutexHeld(p) );
  18818. #if SQLITE_MUTEX_NREF
  18819. p->nRef--;
  18820. if( p->nRef==0 ) p->owner = 0;
  18821. #endif
  18822. assert( p->nRef==0 || p->id==SQLITE_MUTEX_RECURSIVE );
  18823. #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
  18824. if( p->nRef==0 ){
  18825. pthread_mutex_unlock(&p->mutex);
  18826. }
  18827. #else
  18828. pthread_mutex_unlock(&p->mutex);
  18829. #endif
  18830. #ifdef SQLITE_DEBUG
  18831. if( p->trace ){
  18832. printf("leave mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
  18833. }
  18834. #endif
  18835. }
  18836. SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void){
  18837. static const sqlite3_mutex_methods sMutex = {
  18838. pthreadMutexInit,
  18839. pthreadMutexEnd,
  18840. pthreadMutexAlloc,
  18841. pthreadMutexFree,
  18842. pthreadMutexEnter,
  18843. pthreadMutexTry,
  18844. pthreadMutexLeave,
  18845. #ifdef SQLITE_DEBUG
  18846. pthreadMutexHeld,
  18847. pthreadMutexNotheld
  18848. #else
  18849. 0,
  18850. 0
  18851. #endif
  18852. };
  18853. return &sMutex;
  18854. }
  18855. #endif /* SQLITE_MUTEX_PTHREADS */
  18856. /************** End of mutex_unix.c ******************************************/
  18857. /************** Begin file mutex_w32.c ***************************************/
  18858. /*
  18859. ** 2007 August 14
  18860. **
  18861. ** The author disclaims copyright to this source code. In place of
  18862. ** a legal notice, here is a blessing:
  18863. **
  18864. ** May you do good and not evil.
  18865. ** May you find forgiveness for yourself and forgive others.
  18866. ** May you share freely, never taking more than you give.
  18867. **
  18868. *************************************************************************
  18869. ** This file contains the C functions that implement mutexes for Win32.
  18870. */
  18871. #if SQLITE_OS_WIN
  18872. /*
  18873. ** Include code that is common to all os_*.c files
  18874. */
  18875. /************** Include os_common.h in the middle of mutex_w32.c *************/
  18876. /************** Begin file os_common.h ***************************************/
  18877. /*
  18878. ** 2004 May 22
  18879. **
  18880. ** The author disclaims copyright to this source code. In place of
  18881. ** a legal notice, here is a blessing:
  18882. **
  18883. ** May you do good and not evil.
  18884. ** May you find forgiveness for yourself and forgive others.
  18885. ** May you share freely, never taking more than you give.
  18886. **
  18887. ******************************************************************************
  18888. **
  18889. ** This file contains macros and a little bit of code that is common to
  18890. ** all of the platform-specific files (os_*.c) and is #included into those
  18891. ** files.
  18892. **
  18893. ** This file should be #included by the os_*.c files only. It is not a
  18894. ** general purpose header file.
  18895. */
  18896. #ifndef _OS_COMMON_H_
  18897. #define _OS_COMMON_H_
  18898. /*
  18899. ** At least two bugs have slipped in because we changed the MEMORY_DEBUG
  18900. ** macro to SQLITE_DEBUG and some older makefiles have not yet made the
  18901. ** switch. The following code should catch this problem at compile-time.
  18902. */
  18903. #ifdef MEMORY_DEBUG
  18904. # error "The MEMORY_DEBUG macro is obsolete. Use SQLITE_DEBUG instead."
  18905. #endif
  18906. /*
  18907. ** Macros for performance tracing. Normally turned off. Only works
  18908. ** on i486 hardware.
  18909. */
  18910. #ifdef SQLITE_PERFORMANCE_TRACE
  18911. /*
  18912. ** hwtime.h contains inline assembler code for implementing
  18913. ** high-performance timing routines.
  18914. */
  18915. /************** Include hwtime.h in the middle of os_common.h ****************/
  18916. /************** Begin file hwtime.h ******************************************/
  18917. /*
  18918. ** 2008 May 27
  18919. **
  18920. ** The author disclaims copyright to this source code. In place of
  18921. ** a legal notice, here is a blessing:
  18922. **
  18923. ** May you do good and not evil.
  18924. ** May you find forgiveness for yourself and forgive others.
  18925. ** May you share freely, never taking more than you give.
  18926. **
  18927. ******************************************************************************
  18928. **
  18929. ** This file contains inline asm code for retrieving "high-performance"
  18930. ** counters for x86 class CPUs.
  18931. */
  18932. #ifndef _HWTIME_H_
  18933. #define _HWTIME_H_
  18934. /*
  18935. ** The following routine only works on pentium-class (or newer) processors.
  18936. ** It uses the RDTSC opcode to read the cycle count value out of the
  18937. ** processor and returns that value. This can be used for high-res
  18938. ** profiling.
  18939. */
  18940. #if (defined(__GNUC__) || defined(_MSC_VER)) && \
  18941. (defined(i386) || defined(__i386__) || defined(_M_IX86))
  18942. #if defined(__GNUC__)
  18943. __inline__ sqlite_uint64 sqlite3Hwtime(void){
  18944. unsigned int lo, hi;
  18945. __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
  18946. return (sqlite_uint64)hi << 32 | lo;
  18947. }
  18948. #elif defined(_MSC_VER)
  18949. __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
  18950. __asm {
  18951. rdtsc
  18952. ret ; return value at EDX:EAX
  18953. }
  18954. }
  18955. #endif
  18956. #elif (defined(__GNUC__) && defined(__x86_64__))
  18957. __inline__ sqlite_uint64 sqlite3Hwtime(void){
  18958. unsigned long val;
  18959. __asm__ __volatile__ ("rdtsc" : "=A" (val));
  18960. return val;
  18961. }
  18962. #elif (defined(__GNUC__) && defined(__ppc__))
  18963. __inline__ sqlite_uint64 sqlite3Hwtime(void){
  18964. unsigned long long retval;
  18965. unsigned long junk;
  18966. __asm__ __volatile__ ("\n\
  18967. 1: mftbu %1\n\
  18968. mftb %L0\n\
  18969. mftbu %0\n\
  18970. cmpw %0,%1\n\
  18971. bne 1b"
  18972. : "=r" (retval), "=r" (junk));
  18973. return retval;
  18974. }
  18975. #else
  18976. #error Need implementation of sqlite3Hwtime() for your platform.
  18977. /*
  18978. ** To compile without implementing sqlite3Hwtime() for your platform,
  18979. ** you can remove the above #error and use the following
  18980. ** stub function. You will lose timing support for many
  18981. ** of the debugging and testing utilities, but it should at
  18982. ** least compile and run.
  18983. */
  18984. SQLITE_PRIVATE sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
  18985. #endif
  18986. #endif /* !defined(_HWTIME_H_) */
  18987. /************** End of hwtime.h **********************************************/
  18988. /************** Continuing where we left off in os_common.h ******************/
  18989. static sqlite_uint64 g_start;
  18990. static sqlite_uint64 g_elapsed;
  18991. #define TIMER_START g_start=sqlite3Hwtime()
  18992. #define TIMER_END g_elapsed=sqlite3Hwtime()-g_start
  18993. #define TIMER_ELAPSED g_elapsed
  18994. #else
  18995. #define TIMER_START
  18996. #define TIMER_END
  18997. #define TIMER_ELAPSED ((sqlite_uint64)0)
  18998. #endif
  18999. /*
  19000. ** If we compile with the SQLITE_TEST macro set, then the following block
  19001. ** of code will give us the ability to simulate a disk I/O error. This
  19002. ** is used for testing the I/O recovery logic.
  19003. */
  19004. #ifdef SQLITE_TEST
  19005. SQLITE_API int sqlite3_io_error_hit = 0; /* Total number of I/O Errors */
  19006. SQLITE_API int sqlite3_io_error_hardhit = 0; /* Number of non-benign errors */
  19007. SQLITE_API int sqlite3_io_error_pending = 0; /* Count down to first I/O error */
  19008. SQLITE_API int sqlite3_io_error_persist = 0; /* True if I/O errors persist */
  19009. SQLITE_API int sqlite3_io_error_benign = 0; /* True if errors are benign */
  19010. SQLITE_API int sqlite3_diskfull_pending = 0;
  19011. SQLITE_API int sqlite3_diskfull = 0;
  19012. #define SimulateIOErrorBenign(X) sqlite3_io_error_benign=(X)
  19013. #define SimulateIOError(CODE) \
  19014. if( (sqlite3_io_error_persist && sqlite3_io_error_hit) \
  19015. || sqlite3_io_error_pending-- == 1 ) \
  19016. { local_ioerr(); CODE; }
  19017. static void local_ioerr(){
  19018. IOTRACE(("IOERR\n"));
  19019. sqlite3_io_error_hit++;
  19020. if( !sqlite3_io_error_benign ) sqlite3_io_error_hardhit++;
  19021. }
  19022. #define SimulateDiskfullError(CODE) \
  19023. if( sqlite3_diskfull_pending ){ \
  19024. if( sqlite3_diskfull_pending == 1 ){ \
  19025. local_ioerr(); \
  19026. sqlite3_diskfull = 1; \
  19027. sqlite3_io_error_hit = 1; \
  19028. CODE; \
  19029. }else{ \
  19030. sqlite3_diskfull_pending--; \
  19031. } \
  19032. }
  19033. #else
  19034. #define SimulateIOErrorBenign(X)
  19035. #define SimulateIOError(A)
  19036. #define SimulateDiskfullError(A)
  19037. #endif
  19038. /*
  19039. ** When testing, keep a count of the number of open files.
  19040. */
  19041. #ifdef SQLITE_TEST
  19042. SQLITE_API int sqlite3_open_file_count = 0;
  19043. #define OpenCounter(X) sqlite3_open_file_count+=(X)
  19044. #else
  19045. #define OpenCounter(X)
  19046. #endif
  19047. #endif /* !defined(_OS_COMMON_H_) */
  19048. /************** End of os_common.h *******************************************/
  19049. /************** Continuing where we left off in mutex_w32.c ******************/
  19050. /*
  19051. ** Include the header file for the Windows VFS.
  19052. */
  19053. /************** Include os_win.h in the middle of mutex_w32.c ****************/
  19054. /************** Begin file os_win.h ******************************************/
  19055. /*
  19056. ** 2013 November 25
  19057. **
  19058. ** The author disclaims copyright to this source code. In place of
  19059. ** a legal notice, here is a blessing:
  19060. **
  19061. ** May you do good and not evil.
  19062. ** May you find forgiveness for yourself and forgive others.
  19063. ** May you share freely, never taking more than you give.
  19064. **
  19065. ******************************************************************************
  19066. **
  19067. ** This file contains code that is specific to Windows.
  19068. */
  19069. #ifndef _OS_WIN_H_
  19070. #define _OS_WIN_H_
  19071. /*
  19072. ** Include the primary Windows SDK header file.
  19073. */
  19074. #include "windows.h"
  19075. #ifdef __CYGWIN__
  19076. # include <sys/cygwin.h>
  19077. # include <errno.h> /* amalgamator: dontcache */
  19078. #endif
  19079. /*
  19080. ** Determine if we are dealing with Windows NT.
  19081. **
  19082. ** We ought to be able to determine if we are compiling for Windows 9x or
  19083. ** Windows NT using the _WIN32_WINNT macro as follows:
  19084. **
  19085. ** #if defined(_WIN32_WINNT)
  19086. ** # define SQLITE_OS_WINNT 1
  19087. ** #else
  19088. ** # define SQLITE_OS_WINNT 0
  19089. ** #endif
  19090. **
  19091. ** However, Visual Studio 2005 does not set _WIN32_WINNT by default, as
  19092. ** it ought to, so the above test does not work. We'll just assume that
  19093. ** everything is Windows NT unless the programmer explicitly says otherwise
  19094. ** by setting SQLITE_OS_WINNT to 0.
  19095. */
  19096. #if SQLITE_OS_WIN && !defined(SQLITE_OS_WINNT)
  19097. # define SQLITE_OS_WINNT 1
  19098. #endif
  19099. /*
  19100. ** Determine if we are dealing with Windows CE - which has a much reduced
  19101. ** API.
  19102. */
  19103. #if defined(_WIN32_WCE)
  19104. # define SQLITE_OS_WINCE 1
  19105. #else
  19106. # define SQLITE_OS_WINCE 0
  19107. #endif
  19108. /*
  19109. ** Determine if we are dealing with WinRT, which provides only a subset of
  19110. ** the full Win32 API.
  19111. */
  19112. #if !defined(SQLITE_OS_WINRT)
  19113. # define SQLITE_OS_WINRT 0
  19114. #endif
  19115. /*
  19116. ** For WinCE, some API function parameters do not appear to be declared as
  19117. ** volatile.
  19118. */
  19119. #if SQLITE_OS_WINCE
  19120. # define SQLITE_WIN32_VOLATILE
  19121. #else
  19122. # define SQLITE_WIN32_VOLATILE volatile
  19123. #endif
  19124. /*
  19125. ** For some Windows sub-platforms, the _beginthreadex() / _endthreadex()
  19126. ** functions are not available (e.g. those not using MSVC, Cygwin, etc).
  19127. */
  19128. #if SQLITE_OS_WIN && !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && \
  19129. SQLITE_THREADSAFE>0 && !defined(__CYGWIN__)
  19130. # define SQLITE_OS_WIN_THREADS 1
  19131. #else
  19132. # define SQLITE_OS_WIN_THREADS 0
  19133. #endif
  19134. #endif /* _OS_WIN_H_ */
  19135. /************** End of os_win.h **********************************************/
  19136. /************** Continuing where we left off in mutex_w32.c ******************/
  19137. #endif
  19138. /*
  19139. ** The code in this file is only used if we are compiling multithreaded
  19140. ** on a Win32 system.
  19141. */
  19142. #ifdef SQLITE_MUTEX_W32
  19143. /*
  19144. ** Each recursive mutex is an instance of the following structure.
  19145. */
  19146. struct sqlite3_mutex {
  19147. CRITICAL_SECTION mutex; /* Mutex controlling the lock */
  19148. int id; /* Mutex type */
  19149. #ifdef SQLITE_DEBUG
  19150. volatile int nRef; /* Number of enterances */
  19151. volatile DWORD owner; /* Thread holding this mutex */
  19152. volatile int trace; /* True to trace changes */
  19153. #endif
  19154. };
  19155. /*
  19156. ** These are the initializer values used when declaring a "static" mutex
  19157. ** on Win32. It should be noted that all mutexes require initialization
  19158. ** on the Win32 platform.
  19159. */
  19160. #define SQLITE_W32_MUTEX_INITIALIZER { 0 }
  19161. #ifdef SQLITE_DEBUG
  19162. #define SQLITE3_MUTEX_INITIALIZER { SQLITE_W32_MUTEX_INITIALIZER, 0, \
  19163. 0L, (DWORD)0, 0 }
  19164. #else
  19165. #define SQLITE3_MUTEX_INITIALIZER { SQLITE_W32_MUTEX_INITIALIZER, 0 }
  19166. #endif
  19167. #ifdef SQLITE_DEBUG
  19168. /*
  19169. ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
  19170. ** intended for use only inside assert() statements.
  19171. */
  19172. static int winMutexHeld(sqlite3_mutex *p){
  19173. return p->nRef!=0 && p->owner==GetCurrentThreadId();
  19174. }
  19175. static int winMutexNotheld2(sqlite3_mutex *p, DWORD tid){
  19176. return p->nRef==0 || p->owner!=tid;
  19177. }
  19178. static int winMutexNotheld(sqlite3_mutex *p){
  19179. DWORD tid = GetCurrentThreadId();
  19180. return winMutexNotheld2(p, tid);
  19181. }
  19182. #endif
  19183. /*
  19184. ** Initialize and deinitialize the mutex subsystem.
  19185. */
  19186. static sqlite3_mutex winMutex_staticMutexes[] = {
  19187. SQLITE3_MUTEX_INITIALIZER,
  19188. SQLITE3_MUTEX_INITIALIZER,
  19189. SQLITE3_MUTEX_INITIALIZER,
  19190. SQLITE3_MUTEX_INITIALIZER,
  19191. SQLITE3_MUTEX_INITIALIZER,
  19192. SQLITE3_MUTEX_INITIALIZER,
  19193. SQLITE3_MUTEX_INITIALIZER,
  19194. SQLITE3_MUTEX_INITIALIZER,
  19195. SQLITE3_MUTEX_INITIALIZER
  19196. };
  19197. static int winMutex_isInit = 0;
  19198. static int winMutex_isNt = -1; /* <0 means "need to query" */
  19199. /* As the winMutexInit() and winMutexEnd() functions are called as part
  19200. ** of the sqlite3_initialize() and sqlite3_shutdown() processing, the
  19201. ** "interlocked" magic used here is probably not strictly necessary.
  19202. */
  19203. static LONG SQLITE_WIN32_VOLATILE winMutex_lock = 0;
  19204. SQLITE_API int SQLITE_STDCALL sqlite3_win32_is_nt(void); /* os_win.c */
  19205. SQLITE_API void SQLITE_STDCALL sqlite3_win32_sleep(DWORD milliseconds); /* os_win.c */
  19206. static int winMutexInit(void){
  19207. /* The first to increment to 1 does actual initialization */
  19208. if( InterlockedCompareExchange(&winMutex_lock, 1, 0)==0 ){
  19209. int i;
  19210. for(i=0; i<ArraySize(winMutex_staticMutexes); i++){
  19211. #if SQLITE_OS_WINRT
  19212. InitializeCriticalSectionEx(&winMutex_staticMutexes[i].mutex, 0, 0);
  19213. #else
  19214. InitializeCriticalSection(&winMutex_staticMutexes[i].mutex);
  19215. #endif
  19216. }
  19217. winMutex_isInit = 1;
  19218. }else{
  19219. /* Another thread is (in the process of) initializing the static
  19220. ** mutexes */
  19221. while( !winMutex_isInit ){
  19222. sqlite3_win32_sleep(1);
  19223. }
  19224. }
  19225. return SQLITE_OK;
  19226. }
  19227. static int winMutexEnd(void){
  19228. /* The first to decrement to 0 does actual shutdown
  19229. ** (which should be the last to shutdown.) */
  19230. if( InterlockedCompareExchange(&winMutex_lock, 0, 1)==1 ){
  19231. if( winMutex_isInit==1 ){
  19232. int i;
  19233. for(i=0; i<ArraySize(winMutex_staticMutexes); i++){
  19234. DeleteCriticalSection(&winMutex_staticMutexes[i].mutex);
  19235. }
  19236. winMutex_isInit = 0;
  19237. }
  19238. }
  19239. return SQLITE_OK;
  19240. }
  19241. /*
  19242. ** The sqlite3_mutex_alloc() routine allocates a new
  19243. ** mutex and returns a pointer to it. If it returns NULL
  19244. ** that means that a mutex could not be allocated. SQLite
  19245. ** will unwind its stack and return an error. The argument
  19246. ** to sqlite3_mutex_alloc() is one of these integer constants:
  19247. **
  19248. ** <ul>
  19249. ** <li> SQLITE_MUTEX_FAST
  19250. ** <li> SQLITE_MUTEX_RECURSIVE
  19251. ** <li> SQLITE_MUTEX_STATIC_MASTER
  19252. ** <li> SQLITE_MUTEX_STATIC_MEM
  19253. ** <li> SQLITE_MUTEX_STATIC_OPEN
  19254. ** <li> SQLITE_MUTEX_STATIC_PRNG
  19255. ** <li> SQLITE_MUTEX_STATIC_LRU
  19256. ** <li> SQLITE_MUTEX_STATIC_PMEM
  19257. ** <li> SQLITE_MUTEX_STATIC_APP1
  19258. ** <li> SQLITE_MUTEX_STATIC_APP2
  19259. ** <li> SQLITE_MUTEX_STATIC_APP3
  19260. ** </ul>
  19261. **
  19262. ** The first two constants cause sqlite3_mutex_alloc() to create
  19263. ** a new mutex. The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
  19264. ** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
  19265. ** The mutex implementation does not need to make a distinction
  19266. ** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
  19267. ** not want to. But SQLite will only request a recursive mutex in
  19268. ** cases where it really needs one. If a faster non-recursive mutex
  19269. ** implementation is available on the host platform, the mutex subsystem
  19270. ** might return such a mutex in response to SQLITE_MUTEX_FAST.
  19271. **
  19272. ** The other allowed parameters to sqlite3_mutex_alloc() each return
  19273. ** a pointer to a static preexisting mutex. Six static mutexes are
  19274. ** used by the current version of SQLite. Future versions of SQLite
  19275. ** may add additional static mutexes. Static mutexes are for internal
  19276. ** use by SQLite only. Applications that use SQLite mutexes should
  19277. ** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
  19278. ** SQLITE_MUTEX_RECURSIVE.
  19279. **
  19280. ** Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
  19281. ** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
  19282. ** returns a different mutex on every call. But for the static
  19283. ** mutex types, the same mutex is returned on every call that has
  19284. ** the same type number.
  19285. */
  19286. static sqlite3_mutex *winMutexAlloc(int iType){
  19287. sqlite3_mutex *p;
  19288. switch( iType ){
  19289. case SQLITE_MUTEX_FAST:
  19290. case SQLITE_MUTEX_RECURSIVE: {
  19291. p = sqlite3MallocZero( sizeof(*p) );
  19292. if( p ){
  19293. p->id = iType;
  19294. #ifdef SQLITE_DEBUG
  19295. #ifdef SQLITE_WIN32_MUTEX_TRACE_DYNAMIC
  19296. p->trace = 1;
  19297. #endif
  19298. #endif
  19299. #if SQLITE_OS_WINRT
  19300. InitializeCriticalSectionEx(&p->mutex, 0, 0);
  19301. #else
  19302. InitializeCriticalSection(&p->mutex);
  19303. #endif
  19304. }
  19305. break;
  19306. }
  19307. default: {
  19308. #ifdef SQLITE_ENABLE_API_ARMOR
  19309. if( iType-2<0 || iType-2>=ArraySize(winMutex_staticMutexes) ){
  19310. (void)SQLITE_MISUSE_BKPT;
  19311. return 0;
  19312. }
  19313. #endif
  19314. p = &winMutex_staticMutexes[iType-2];
  19315. p->id = iType;
  19316. #ifdef SQLITE_DEBUG
  19317. #ifdef SQLITE_WIN32_MUTEX_TRACE_STATIC
  19318. p->trace = 1;
  19319. #endif
  19320. #endif
  19321. break;
  19322. }
  19323. }
  19324. return p;
  19325. }
  19326. /*
  19327. ** This routine deallocates a previously
  19328. ** allocated mutex. SQLite is careful to deallocate every
  19329. ** mutex that it allocates.
  19330. */
  19331. static void winMutexFree(sqlite3_mutex *p){
  19332. assert( p );
  19333. assert( p->nRef==0 && p->owner==0 );
  19334. if( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE ){
  19335. DeleteCriticalSection(&p->mutex);
  19336. sqlite3_free(p);
  19337. }else{
  19338. #ifdef SQLITE_ENABLE_API_ARMOR
  19339. (void)SQLITE_MISUSE_BKPT;
  19340. #endif
  19341. }
  19342. }
  19343. /*
  19344. ** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
  19345. ** to enter a mutex. If another thread is already within the mutex,
  19346. ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
  19347. ** SQLITE_BUSY. The sqlite3_mutex_try() interface returns SQLITE_OK
  19348. ** upon successful entry. Mutexes created using SQLITE_MUTEX_RECURSIVE can
  19349. ** be entered multiple times by the same thread. In such cases the,
  19350. ** mutex must be exited an equal number of times before another thread
  19351. ** can enter. If the same thread tries to enter any other kind of mutex
  19352. ** more than once, the behavior is undefined.
  19353. */
  19354. static void winMutexEnter(sqlite3_mutex *p){
  19355. #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
  19356. DWORD tid = GetCurrentThreadId();
  19357. #endif
  19358. #ifdef SQLITE_DEBUG
  19359. assert( p );
  19360. assert( p->id==SQLITE_MUTEX_RECURSIVE || winMutexNotheld2(p, tid) );
  19361. #else
  19362. assert( p );
  19363. #endif
  19364. assert( winMutex_isInit==1 );
  19365. EnterCriticalSection(&p->mutex);
  19366. #ifdef SQLITE_DEBUG
  19367. assert( p->nRef>0 || p->owner==0 );
  19368. p->owner = tid;
  19369. p->nRef++;
  19370. if( p->trace ){
  19371. OSTRACE(("ENTER-MUTEX tid=%lu, mutex=%p (%d), nRef=%d\n",
  19372. tid, p, p->trace, p->nRef));
  19373. }
  19374. #endif
  19375. }
  19376. static int winMutexTry(sqlite3_mutex *p){
  19377. #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
  19378. DWORD tid = GetCurrentThreadId();
  19379. #endif
  19380. int rc = SQLITE_BUSY;
  19381. assert( p );
  19382. assert( p->id==SQLITE_MUTEX_RECURSIVE || winMutexNotheld2(p, tid) );
  19383. /*
  19384. ** The sqlite3_mutex_try() routine is very rarely used, and when it
  19385. ** is used it is merely an optimization. So it is OK for it to always
  19386. ** fail.
  19387. **
  19388. ** The TryEnterCriticalSection() interface is only available on WinNT.
  19389. ** And some windows compilers complain if you try to use it without
  19390. ** first doing some #defines that prevent SQLite from building on Win98.
  19391. ** For that reason, we will omit this optimization for now. See
  19392. ** ticket #2685.
  19393. */
  19394. #if defined(_WIN32_WINNT) && _WIN32_WINNT >= 0x0400
  19395. assert( winMutex_isInit==1 );
  19396. assert( winMutex_isNt>=-1 && winMutex_isNt<=1 );
  19397. if( winMutex_isNt<0 ){
  19398. winMutex_isNt = sqlite3_win32_is_nt();
  19399. }
  19400. assert( winMutex_isNt==0 || winMutex_isNt==1 );
  19401. if( winMutex_isNt && TryEnterCriticalSection(&p->mutex) ){
  19402. #ifdef SQLITE_DEBUG
  19403. p->owner = tid;
  19404. p->nRef++;
  19405. #endif
  19406. rc = SQLITE_OK;
  19407. }
  19408. #else
  19409. UNUSED_PARAMETER(p);
  19410. #endif
  19411. #ifdef SQLITE_DEBUG
  19412. if( p->trace ){
  19413. OSTRACE(("TRY-MUTEX tid=%lu, mutex=%p (%d), owner=%lu, nRef=%d, rc=%s\n",
  19414. tid, p, p->trace, p->owner, p->nRef, sqlite3ErrName(rc)));
  19415. }
  19416. #endif
  19417. return rc;
  19418. }
  19419. /*
  19420. ** The sqlite3_mutex_leave() routine exits a mutex that was
  19421. ** previously entered by the same thread. The behavior
  19422. ** is undefined if the mutex is not currently entered or
  19423. ** is not currently allocated. SQLite will never do either.
  19424. */
  19425. static void winMutexLeave(sqlite3_mutex *p){
  19426. #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
  19427. DWORD tid = GetCurrentThreadId();
  19428. #endif
  19429. assert( p );
  19430. #ifdef SQLITE_DEBUG
  19431. assert( p->nRef>0 );
  19432. assert( p->owner==tid );
  19433. p->nRef--;
  19434. if( p->nRef==0 ) p->owner = 0;
  19435. assert( p->nRef==0 || p->id==SQLITE_MUTEX_RECURSIVE );
  19436. #endif
  19437. assert( winMutex_isInit==1 );
  19438. LeaveCriticalSection(&p->mutex);
  19439. #ifdef SQLITE_DEBUG
  19440. if( p->trace ){
  19441. OSTRACE(("LEAVE-MUTEX tid=%lu, mutex=%p (%d), nRef=%d\n",
  19442. tid, p, p->trace, p->nRef));
  19443. }
  19444. #endif
  19445. }
  19446. SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void){
  19447. static const sqlite3_mutex_methods sMutex = {
  19448. winMutexInit,
  19449. winMutexEnd,
  19450. winMutexAlloc,
  19451. winMutexFree,
  19452. winMutexEnter,
  19453. winMutexTry,
  19454. winMutexLeave,
  19455. #ifdef SQLITE_DEBUG
  19456. winMutexHeld,
  19457. winMutexNotheld
  19458. #else
  19459. 0,
  19460. 0
  19461. #endif
  19462. };
  19463. return &sMutex;
  19464. }
  19465. #endif /* SQLITE_MUTEX_W32 */
  19466. /************** End of mutex_w32.c *******************************************/
  19467. /************** Begin file malloc.c ******************************************/
  19468. /*
  19469. ** 2001 September 15
  19470. **
  19471. ** The author disclaims copyright to this source code. In place of
  19472. ** a legal notice, here is a blessing:
  19473. **
  19474. ** May you do good and not evil.
  19475. ** May you find forgiveness for yourself and forgive others.
  19476. ** May you share freely, never taking more than you give.
  19477. **
  19478. *************************************************************************
  19479. **
  19480. ** Memory allocation functions used throughout sqlite.
  19481. */
  19482. /* #include <stdarg.h> */
  19483. /*
  19484. ** Attempt to release up to n bytes of non-essential memory currently
  19485. ** held by SQLite. An example of non-essential memory is memory used to
  19486. ** cache database pages that are not currently in use.
  19487. */
  19488. SQLITE_API int SQLITE_STDCALL sqlite3_release_memory(int n){
  19489. #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
  19490. return sqlite3PcacheReleaseMemory(n);
  19491. #else
  19492. /* IMPLEMENTATION-OF: R-34391-24921 The sqlite3_release_memory() routine
  19493. ** is a no-op returning zero if SQLite is not compiled with
  19494. ** SQLITE_ENABLE_MEMORY_MANAGEMENT. */
  19495. UNUSED_PARAMETER(n);
  19496. return 0;
  19497. #endif
  19498. }
  19499. /*
  19500. ** An instance of the following object records the location of
  19501. ** each unused scratch buffer.
  19502. */
  19503. typedef struct ScratchFreeslot {
  19504. struct ScratchFreeslot *pNext; /* Next unused scratch buffer */
  19505. } ScratchFreeslot;
  19506. /*
  19507. ** State information local to the memory allocation subsystem.
  19508. */
  19509. static SQLITE_WSD struct Mem0Global {
  19510. sqlite3_mutex *mutex; /* Mutex to serialize access */
  19511. /*
  19512. ** The alarm callback and its arguments. The mem0.mutex lock will
  19513. ** be held while the callback is running. Recursive calls into
  19514. ** the memory subsystem are allowed, but no new callbacks will be
  19515. ** issued.
  19516. */
  19517. sqlite3_int64 alarmThreshold;
  19518. void (*alarmCallback)(void*, sqlite3_int64,int);
  19519. void *alarmArg;
  19520. /*
  19521. ** Pointers to the end of sqlite3GlobalConfig.pScratch memory
  19522. ** (so that a range test can be used to determine if an allocation
  19523. ** being freed came from pScratch) and a pointer to the list of
  19524. ** unused scratch allocations.
  19525. */
  19526. void *pScratchEnd;
  19527. ScratchFreeslot *pScratchFree;
  19528. u32 nScratchFree;
  19529. /*
  19530. ** True if heap is nearly "full" where "full" is defined by the
  19531. ** sqlite3_soft_heap_limit() setting.
  19532. */
  19533. int nearlyFull;
  19534. } mem0 = { 0, 0, 0, 0, 0, 0, 0, 0 };
  19535. #define mem0 GLOBAL(struct Mem0Global, mem0)
  19536. /*
  19537. ** Return the memory allocator mutex. sqlite3_status() needs it.
  19538. */
  19539. SQLITE_PRIVATE sqlite3_mutex *sqlite3MallocMutex(void){
  19540. return mem0.mutex;
  19541. }
  19542. /*
  19543. ** This routine runs when the memory allocator sees that the
  19544. ** total memory allocation is about to exceed the soft heap
  19545. ** limit.
  19546. */
  19547. static void softHeapLimitEnforcer(
  19548. void *NotUsed,
  19549. sqlite3_int64 NotUsed2,
  19550. int allocSize
  19551. ){
  19552. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  19553. sqlite3_release_memory(allocSize);
  19554. }
  19555. /*
  19556. ** Change the alarm callback
  19557. */
  19558. static int sqlite3MemoryAlarm(
  19559. void(*xCallback)(void *pArg, sqlite3_int64 used,int N),
  19560. void *pArg,
  19561. sqlite3_int64 iThreshold
  19562. ){
  19563. sqlite3_int64 nUsed;
  19564. sqlite3_mutex_enter(mem0.mutex);
  19565. mem0.alarmCallback = xCallback;
  19566. mem0.alarmArg = pArg;
  19567. mem0.alarmThreshold = iThreshold;
  19568. nUsed = sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED);
  19569. mem0.nearlyFull = (iThreshold>0 && iThreshold<=nUsed);
  19570. sqlite3_mutex_leave(mem0.mutex);
  19571. return SQLITE_OK;
  19572. }
  19573. #ifndef SQLITE_OMIT_DEPRECATED
  19574. /*
  19575. ** Deprecated external interface. Internal/core SQLite code
  19576. ** should call sqlite3MemoryAlarm.
  19577. */
  19578. SQLITE_API int SQLITE_STDCALL sqlite3_memory_alarm(
  19579. void(*xCallback)(void *pArg, sqlite3_int64 used,int N),
  19580. void *pArg,
  19581. sqlite3_int64 iThreshold
  19582. ){
  19583. return sqlite3MemoryAlarm(xCallback, pArg, iThreshold);
  19584. }
  19585. #endif
  19586. /*
  19587. ** Set the soft heap-size limit for the library. Passing a zero or
  19588. ** negative value indicates no limit.
  19589. */
  19590. SQLITE_API sqlite3_int64 SQLITE_STDCALL sqlite3_soft_heap_limit64(sqlite3_int64 n){
  19591. sqlite3_int64 priorLimit;
  19592. sqlite3_int64 excess;
  19593. #ifndef SQLITE_OMIT_AUTOINIT
  19594. int rc = sqlite3_initialize();
  19595. if( rc ) return -1;
  19596. #endif
  19597. sqlite3_mutex_enter(mem0.mutex);
  19598. priorLimit = mem0.alarmThreshold;
  19599. sqlite3_mutex_leave(mem0.mutex);
  19600. if( n<0 ) return priorLimit;
  19601. if( n>0 ){
  19602. sqlite3MemoryAlarm(softHeapLimitEnforcer, 0, n);
  19603. }else{
  19604. sqlite3MemoryAlarm(0, 0, 0);
  19605. }
  19606. excess = sqlite3_memory_used() - n;
  19607. if( excess>0 ) sqlite3_release_memory((int)(excess & 0x7fffffff));
  19608. return priorLimit;
  19609. }
  19610. SQLITE_API void SQLITE_STDCALL sqlite3_soft_heap_limit(int n){
  19611. if( n<0 ) n = 0;
  19612. sqlite3_soft_heap_limit64(n);
  19613. }
  19614. /*
  19615. ** Initialize the memory allocation subsystem.
  19616. */
  19617. SQLITE_PRIVATE int sqlite3MallocInit(void){
  19618. int rc;
  19619. if( sqlite3GlobalConfig.m.xMalloc==0 ){
  19620. sqlite3MemSetDefault();
  19621. }
  19622. memset(&mem0, 0, sizeof(mem0));
  19623. if( sqlite3GlobalConfig.bCoreMutex ){
  19624. mem0.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
  19625. }
  19626. if( sqlite3GlobalConfig.pScratch && sqlite3GlobalConfig.szScratch>=100
  19627. && sqlite3GlobalConfig.nScratch>0 ){
  19628. int i, n, sz;
  19629. ScratchFreeslot *pSlot;
  19630. sz = ROUNDDOWN8(sqlite3GlobalConfig.szScratch);
  19631. sqlite3GlobalConfig.szScratch = sz;
  19632. pSlot = (ScratchFreeslot*)sqlite3GlobalConfig.pScratch;
  19633. n = sqlite3GlobalConfig.nScratch;
  19634. mem0.pScratchFree = pSlot;
  19635. mem0.nScratchFree = n;
  19636. for(i=0; i<n-1; i++){
  19637. pSlot->pNext = (ScratchFreeslot*)(sz+(char*)pSlot);
  19638. pSlot = pSlot->pNext;
  19639. }
  19640. pSlot->pNext = 0;
  19641. mem0.pScratchEnd = (void*)&pSlot[1];
  19642. }else{
  19643. mem0.pScratchEnd = 0;
  19644. sqlite3GlobalConfig.pScratch = 0;
  19645. sqlite3GlobalConfig.szScratch = 0;
  19646. sqlite3GlobalConfig.nScratch = 0;
  19647. }
  19648. if( sqlite3GlobalConfig.pPage==0 || sqlite3GlobalConfig.szPage<512
  19649. || sqlite3GlobalConfig.nPage<1 ){
  19650. sqlite3GlobalConfig.pPage = 0;
  19651. sqlite3GlobalConfig.szPage = 0;
  19652. sqlite3GlobalConfig.nPage = 0;
  19653. }
  19654. rc = sqlite3GlobalConfig.m.xInit(sqlite3GlobalConfig.m.pAppData);
  19655. if( rc!=SQLITE_OK ) memset(&mem0, 0, sizeof(mem0));
  19656. return rc;
  19657. }
  19658. /*
  19659. ** Return true if the heap is currently under memory pressure - in other
  19660. ** words if the amount of heap used is close to the limit set by
  19661. ** sqlite3_soft_heap_limit().
  19662. */
  19663. SQLITE_PRIVATE int sqlite3HeapNearlyFull(void){
  19664. return mem0.nearlyFull;
  19665. }
  19666. /*
  19667. ** Deinitialize the memory allocation subsystem.
  19668. */
  19669. SQLITE_PRIVATE void sqlite3MallocEnd(void){
  19670. if( sqlite3GlobalConfig.m.xShutdown ){
  19671. sqlite3GlobalConfig.m.xShutdown(sqlite3GlobalConfig.m.pAppData);
  19672. }
  19673. memset(&mem0, 0, sizeof(mem0));
  19674. }
  19675. /*
  19676. ** Return the amount of memory currently checked out.
  19677. */
  19678. SQLITE_API sqlite3_int64 SQLITE_STDCALL sqlite3_memory_used(void){
  19679. int n, mx;
  19680. sqlite3_int64 res;
  19681. sqlite3_status(SQLITE_STATUS_MEMORY_USED, &n, &mx, 0);
  19682. res = (sqlite3_int64)n; /* Work around bug in Borland C. Ticket #3216 */
  19683. return res;
  19684. }
  19685. /*
  19686. ** Return the maximum amount of memory that has ever been
  19687. ** checked out since either the beginning of this process
  19688. ** or since the most recent reset.
  19689. */
  19690. SQLITE_API sqlite3_int64 SQLITE_STDCALL sqlite3_memory_highwater(int resetFlag){
  19691. int n, mx;
  19692. sqlite3_int64 res;
  19693. sqlite3_status(SQLITE_STATUS_MEMORY_USED, &n, &mx, resetFlag);
  19694. res = (sqlite3_int64)mx; /* Work around bug in Borland C. Ticket #3216 */
  19695. return res;
  19696. }
  19697. /*
  19698. ** Trigger the alarm
  19699. */
  19700. static void sqlite3MallocAlarm(int nByte){
  19701. void (*xCallback)(void*,sqlite3_int64,int);
  19702. sqlite3_int64 nowUsed;
  19703. void *pArg;
  19704. if( mem0.alarmCallback==0 ) return;
  19705. xCallback = mem0.alarmCallback;
  19706. nowUsed = sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED);
  19707. pArg = mem0.alarmArg;
  19708. mem0.alarmCallback = 0;
  19709. sqlite3_mutex_leave(mem0.mutex);
  19710. xCallback(pArg, nowUsed, nByte);
  19711. sqlite3_mutex_enter(mem0.mutex);
  19712. mem0.alarmCallback = xCallback;
  19713. mem0.alarmArg = pArg;
  19714. }
  19715. /*
  19716. ** Do a memory allocation with statistics and alarms. Assume the
  19717. ** lock is already held.
  19718. */
  19719. static int mallocWithAlarm(int n, void **pp){
  19720. int nFull;
  19721. void *p;
  19722. assert( sqlite3_mutex_held(mem0.mutex) );
  19723. nFull = sqlite3GlobalConfig.m.xRoundup(n);
  19724. sqlite3StatusSet(SQLITE_STATUS_MALLOC_SIZE, n);
  19725. if( mem0.alarmCallback!=0 ){
  19726. sqlite3_int64 nUsed = sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED);
  19727. if( nUsed >= mem0.alarmThreshold - nFull ){
  19728. mem0.nearlyFull = 1;
  19729. sqlite3MallocAlarm(nFull);
  19730. }else{
  19731. mem0.nearlyFull = 0;
  19732. }
  19733. }
  19734. p = sqlite3GlobalConfig.m.xMalloc(nFull);
  19735. #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
  19736. if( p==0 && mem0.alarmCallback ){
  19737. sqlite3MallocAlarm(nFull);
  19738. p = sqlite3GlobalConfig.m.xMalloc(nFull);
  19739. }
  19740. #endif
  19741. if( p ){
  19742. nFull = sqlite3MallocSize(p);
  19743. sqlite3StatusUp(SQLITE_STATUS_MEMORY_USED, nFull);
  19744. sqlite3StatusUp(SQLITE_STATUS_MALLOC_COUNT, 1);
  19745. }
  19746. *pp = p;
  19747. return nFull;
  19748. }
  19749. /*
  19750. ** Allocate memory. This routine is like sqlite3_malloc() except that it
  19751. ** assumes the memory subsystem has already been initialized.
  19752. */
  19753. SQLITE_PRIVATE void *sqlite3Malloc(u64 n){
  19754. void *p;
  19755. if( n==0 || n>=0x7fffff00 ){
  19756. /* A memory allocation of a number of bytes which is near the maximum
  19757. ** signed integer value might cause an integer overflow inside of the
  19758. ** xMalloc(). Hence we limit the maximum size to 0x7fffff00, giving
  19759. ** 255 bytes of overhead. SQLite itself will never use anything near
  19760. ** this amount. The only way to reach the limit is with sqlite3_malloc() */
  19761. p = 0;
  19762. }else if( sqlite3GlobalConfig.bMemstat ){
  19763. sqlite3_mutex_enter(mem0.mutex);
  19764. mallocWithAlarm((int)n, &p);
  19765. sqlite3_mutex_leave(mem0.mutex);
  19766. }else{
  19767. p = sqlite3GlobalConfig.m.xMalloc((int)n);
  19768. }
  19769. assert( EIGHT_BYTE_ALIGNMENT(p) ); /* IMP: R-11148-40995 */
  19770. return p;
  19771. }
  19772. /*
  19773. ** This version of the memory allocation is for use by the application.
  19774. ** First make sure the memory subsystem is initialized, then do the
  19775. ** allocation.
  19776. */
  19777. SQLITE_API void *SQLITE_STDCALL sqlite3_malloc(int n){
  19778. #ifndef SQLITE_OMIT_AUTOINIT
  19779. if( sqlite3_initialize() ) return 0;
  19780. #endif
  19781. return n<=0 ? 0 : sqlite3Malloc(n);
  19782. }
  19783. SQLITE_API void *SQLITE_STDCALL sqlite3_malloc64(sqlite3_uint64 n){
  19784. #ifndef SQLITE_OMIT_AUTOINIT
  19785. if( sqlite3_initialize() ) return 0;
  19786. #endif
  19787. return sqlite3Malloc(n);
  19788. }
  19789. /*
  19790. ** Each thread may only have a single outstanding allocation from
  19791. ** xScratchMalloc(). We verify this constraint in the single-threaded
  19792. ** case by setting scratchAllocOut to 1 when an allocation
  19793. ** is outstanding clearing it when the allocation is freed.
  19794. */
  19795. #if SQLITE_THREADSAFE==0 && !defined(NDEBUG)
  19796. static int scratchAllocOut = 0;
  19797. #endif
  19798. /*
  19799. ** Allocate memory that is to be used and released right away.
  19800. ** This routine is similar to alloca() in that it is not intended
  19801. ** for situations where the memory might be held long-term. This
  19802. ** routine is intended to get memory to old large transient data
  19803. ** structures that would not normally fit on the stack of an
  19804. ** embedded processor.
  19805. */
  19806. SQLITE_PRIVATE void *sqlite3ScratchMalloc(int n){
  19807. void *p;
  19808. assert( n>0 );
  19809. sqlite3_mutex_enter(mem0.mutex);
  19810. sqlite3StatusSet(SQLITE_STATUS_SCRATCH_SIZE, n);
  19811. if( mem0.nScratchFree && sqlite3GlobalConfig.szScratch>=n ){
  19812. p = mem0.pScratchFree;
  19813. mem0.pScratchFree = mem0.pScratchFree->pNext;
  19814. mem0.nScratchFree--;
  19815. sqlite3StatusUp(SQLITE_STATUS_SCRATCH_USED, 1);
  19816. sqlite3_mutex_leave(mem0.mutex);
  19817. }else{
  19818. sqlite3_mutex_leave(mem0.mutex);
  19819. p = sqlite3Malloc(n);
  19820. if( sqlite3GlobalConfig.bMemstat && p ){
  19821. sqlite3_mutex_enter(mem0.mutex);
  19822. sqlite3StatusUp(SQLITE_STATUS_SCRATCH_OVERFLOW, sqlite3MallocSize(p));
  19823. sqlite3_mutex_leave(mem0.mutex);
  19824. }
  19825. sqlite3MemdebugSetType(p, MEMTYPE_SCRATCH);
  19826. }
  19827. assert( sqlite3_mutex_notheld(mem0.mutex) );
  19828. #if SQLITE_THREADSAFE==0 && !defined(NDEBUG)
  19829. /* EVIDENCE-OF: R-12970-05880 SQLite will not use more than one scratch
  19830. ** buffers per thread.
  19831. **
  19832. ** This can only be checked in single-threaded mode.
  19833. */
  19834. assert( scratchAllocOut==0 );
  19835. if( p ) scratchAllocOut++;
  19836. #endif
  19837. return p;
  19838. }
  19839. SQLITE_PRIVATE void sqlite3ScratchFree(void *p){
  19840. if( p ){
  19841. #if SQLITE_THREADSAFE==0 && !defined(NDEBUG)
  19842. /* Verify that no more than two scratch allocation per thread
  19843. ** is outstanding at one time. (This is only checked in the
  19844. ** single-threaded case since checking in the multi-threaded case
  19845. ** would be much more complicated.) */
  19846. assert( scratchAllocOut>=1 && scratchAllocOut<=2 );
  19847. scratchAllocOut--;
  19848. #endif
  19849. if( p>=sqlite3GlobalConfig.pScratch && p<mem0.pScratchEnd ){
  19850. /* Release memory from the SQLITE_CONFIG_SCRATCH allocation */
  19851. ScratchFreeslot *pSlot;
  19852. pSlot = (ScratchFreeslot*)p;
  19853. sqlite3_mutex_enter(mem0.mutex);
  19854. pSlot->pNext = mem0.pScratchFree;
  19855. mem0.pScratchFree = pSlot;
  19856. mem0.nScratchFree++;
  19857. assert( mem0.nScratchFree <= (u32)sqlite3GlobalConfig.nScratch );
  19858. sqlite3StatusDown(SQLITE_STATUS_SCRATCH_USED, 1);
  19859. sqlite3_mutex_leave(mem0.mutex);
  19860. }else{
  19861. /* Release memory back to the heap */
  19862. assert( sqlite3MemdebugHasType(p, MEMTYPE_SCRATCH) );
  19863. assert( sqlite3MemdebugNoType(p, (u8)~MEMTYPE_SCRATCH) );
  19864. sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
  19865. if( sqlite3GlobalConfig.bMemstat ){
  19866. int iSize = sqlite3MallocSize(p);
  19867. sqlite3_mutex_enter(mem0.mutex);
  19868. sqlite3StatusDown(SQLITE_STATUS_SCRATCH_OVERFLOW, iSize);
  19869. sqlite3StatusDown(SQLITE_STATUS_MEMORY_USED, iSize);
  19870. sqlite3StatusDown(SQLITE_STATUS_MALLOC_COUNT, 1);
  19871. sqlite3GlobalConfig.m.xFree(p);
  19872. sqlite3_mutex_leave(mem0.mutex);
  19873. }else{
  19874. sqlite3GlobalConfig.m.xFree(p);
  19875. }
  19876. }
  19877. }
  19878. }
  19879. /*
  19880. ** TRUE if p is a lookaside memory allocation from db
  19881. */
  19882. #ifndef SQLITE_OMIT_LOOKASIDE
  19883. static int isLookaside(sqlite3 *db, void *p){
  19884. return p>=db->lookaside.pStart && p<db->lookaside.pEnd;
  19885. }
  19886. #else
  19887. #define isLookaside(A,B) 0
  19888. #endif
  19889. /*
  19890. ** Return the size of a memory allocation previously obtained from
  19891. ** sqlite3Malloc() or sqlite3_malloc().
  19892. */
  19893. SQLITE_PRIVATE int sqlite3MallocSize(void *p){
  19894. assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) );
  19895. return sqlite3GlobalConfig.m.xSize(p);
  19896. }
  19897. SQLITE_PRIVATE int sqlite3DbMallocSize(sqlite3 *db, void *p){
  19898. if( db==0 ){
  19899. assert( sqlite3MemdebugNoType(p, (u8)~MEMTYPE_HEAP) );
  19900. assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) );
  19901. return sqlite3MallocSize(p);
  19902. }else{
  19903. assert( sqlite3_mutex_held(db->mutex) );
  19904. if( isLookaside(db, p) ){
  19905. return db->lookaside.sz;
  19906. }else{
  19907. assert( sqlite3MemdebugHasType(p, (MEMTYPE_LOOKASIDE|MEMTYPE_HEAP)) );
  19908. assert( sqlite3MemdebugNoType(p, (u8)~(MEMTYPE_LOOKASIDE|MEMTYPE_HEAP)) );
  19909. return sqlite3GlobalConfig.m.xSize(p);
  19910. }
  19911. }
  19912. }
  19913. SQLITE_API sqlite3_uint64 SQLITE_STDCALL sqlite3_msize(void *p){
  19914. assert( sqlite3MemdebugNoType(p, (u8)~MEMTYPE_HEAP) );
  19915. assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) );
  19916. return (sqlite3_uint64)sqlite3GlobalConfig.m.xSize(p);
  19917. }
  19918. /*
  19919. ** Free memory previously obtained from sqlite3Malloc().
  19920. */
  19921. SQLITE_API void SQLITE_STDCALL sqlite3_free(void *p){
  19922. if( p==0 ) return; /* IMP: R-49053-54554 */
  19923. assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) );
  19924. assert( sqlite3MemdebugNoType(p, (u8)~MEMTYPE_HEAP) );
  19925. if( sqlite3GlobalConfig.bMemstat ){
  19926. sqlite3_mutex_enter(mem0.mutex);
  19927. sqlite3StatusDown(SQLITE_STATUS_MEMORY_USED, sqlite3MallocSize(p));
  19928. sqlite3StatusDown(SQLITE_STATUS_MALLOC_COUNT, 1);
  19929. sqlite3GlobalConfig.m.xFree(p);
  19930. sqlite3_mutex_leave(mem0.mutex);
  19931. }else{
  19932. sqlite3GlobalConfig.m.xFree(p);
  19933. }
  19934. }
  19935. /*
  19936. ** Add the size of memory allocation "p" to the count in
  19937. ** *db->pnBytesFreed.
  19938. */
  19939. static SQLITE_NOINLINE void measureAllocationSize(sqlite3 *db, void *p){
  19940. *db->pnBytesFreed += sqlite3DbMallocSize(db,p);
  19941. }
  19942. /*
  19943. ** Free memory that might be associated with a particular database
  19944. ** connection.
  19945. */
  19946. SQLITE_PRIVATE void sqlite3DbFree(sqlite3 *db, void *p){
  19947. assert( db==0 || sqlite3_mutex_held(db->mutex) );
  19948. if( p==0 ) return;
  19949. if( db ){
  19950. if( db->pnBytesFreed ){
  19951. measureAllocationSize(db, p);
  19952. return;
  19953. }
  19954. if( isLookaside(db, p) ){
  19955. LookasideSlot *pBuf = (LookasideSlot*)p;
  19956. #if SQLITE_DEBUG
  19957. /* Trash all content in the buffer being freed */
  19958. memset(p, 0xaa, db->lookaside.sz);
  19959. #endif
  19960. pBuf->pNext = db->lookaside.pFree;
  19961. db->lookaside.pFree = pBuf;
  19962. db->lookaside.nOut--;
  19963. return;
  19964. }
  19965. }
  19966. assert( sqlite3MemdebugHasType(p, (MEMTYPE_LOOKASIDE|MEMTYPE_HEAP)) );
  19967. assert( sqlite3MemdebugNoType(p, (u8)~(MEMTYPE_LOOKASIDE|MEMTYPE_HEAP)) );
  19968. assert( db!=0 || sqlite3MemdebugNoType(p, MEMTYPE_LOOKASIDE) );
  19969. sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
  19970. sqlite3_free(p);
  19971. }
  19972. /*
  19973. ** Change the size of an existing memory allocation
  19974. */
  19975. SQLITE_PRIVATE void *sqlite3Realloc(void *pOld, u64 nBytes){
  19976. int nOld, nNew, nDiff;
  19977. void *pNew;
  19978. assert( sqlite3MemdebugHasType(pOld, MEMTYPE_HEAP) );
  19979. assert( sqlite3MemdebugNoType(pOld, (u8)~MEMTYPE_HEAP) );
  19980. if( pOld==0 ){
  19981. return sqlite3Malloc(nBytes); /* IMP: R-04300-56712 */
  19982. }
  19983. if( nBytes==0 ){
  19984. sqlite3_free(pOld); /* IMP: R-26507-47431 */
  19985. return 0;
  19986. }
  19987. if( nBytes>=0x7fffff00 ){
  19988. /* The 0x7ffff00 limit term is explained in comments on sqlite3Malloc() */
  19989. return 0;
  19990. }
  19991. nOld = sqlite3MallocSize(pOld);
  19992. /* IMPLEMENTATION-OF: R-46199-30249 SQLite guarantees that the second
  19993. ** argument to xRealloc is always a value returned by a prior call to
  19994. ** xRoundup. */
  19995. nNew = sqlite3GlobalConfig.m.xRoundup((int)nBytes);
  19996. if( nOld==nNew ){
  19997. pNew = pOld;
  19998. }else if( sqlite3GlobalConfig.bMemstat ){
  19999. sqlite3_mutex_enter(mem0.mutex);
  20000. sqlite3StatusSet(SQLITE_STATUS_MALLOC_SIZE, (int)nBytes);
  20001. nDiff = nNew - nOld;
  20002. if( sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED) >=
  20003. mem0.alarmThreshold-nDiff ){
  20004. sqlite3MallocAlarm(nDiff);
  20005. }
  20006. pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew);
  20007. if( pNew==0 && mem0.alarmCallback ){
  20008. sqlite3MallocAlarm((int)nBytes);
  20009. pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew);
  20010. }
  20011. if( pNew ){
  20012. nNew = sqlite3MallocSize(pNew);
  20013. sqlite3StatusUp(SQLITE_STATUS_MEMORY_USED, nNew-nOld);
  20014. }
  20015. sqlite3_mutex_leave(mem0.mutex);
  20016. }else{
  20017. pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew);
  20018. }
  20019. assert( EIGHT_BYTE_ALIGNMENT(pNew) ); /* IMP: R-11148-40995 */
  20020. return pNew;
  20021. }
  20022. /*
  20023. ** The public interface to sqlite3Realloc. Make sure that the memory
  20024. ** subsystem is initialized prior to invoking sqliteRealloc.
  20025. */
  20026. SQLITE_API void *SQLITE_STDCALL sqlite3_realloc(void *pOld, int n){
  20027. #ifndef SQLITE_OMIT_AUTOINIT
  20028. if( sqlite3_initialize() ) return 0;
  20029. #endif
  20030. if( n<0 ) n = 0; /* IMP: R-26507-47431 */
  20031. return sqlite3Realloc(pOld, n);
  20032. }
  20033. SQLITE_API void *SQLITE_STDCALL sqlite3_realloc64(void *pOld, sqlite3_uint64 n){
  20034. #ifndef SQLITE_OMIT_AUTOINIT
  20035. if( sqlite3_initialize() ) return 0;
  20036. #endif
  20037. return sqlite3Realloc(pOld, n);
  20038. }
  20039. /*
  20040. ** Allocate and zero memory.
  20041. */
  20042. SQLITE_PRIVATE void *sqlite3MallocZero(u64 n){
  20043. void *p = sqlite3Malloc(n);
  20044. if( p ){
  20045. memset(p, 0, (size_t)n);
  20046. }
  20047. return p;
  20048. }
  20049. /*
  20050. ** Allocate and zero memory. If the allocation fails, make
  20051. ** the mallocFailed flag in the connection pointer.
  20052. */
  20053. SQLITE_PRIVATE void *sqlite3DbMallocZero(sqlite3 *db, u64 n){
  20054. void *p = sqlite3DbMallocRaw(db, n);
  20055. if( p ){
  20056. memset(p, 0, (size_t)n);
  20057. }
  20058. return p;
  20059. }
  20060. /*
  20061. ** Allocate and zero memory. If the allocation fails, make
  20062. ** the mallocFailed flag in the connection pointer.
  20063. **
  20064. ** If db!=0 and db->mallocFailed is true (indicating a prior malloc
  20065. ** failure on the same database connection) then always return 0.
  20066. ** Hence for a particular database connection, once malloc starts
  20067. ** failing, it fails consistently until mallocFailed is reset.
  20068. ** This is an important assumption. There are many places in the
  20069. ** code that do things like this:
  20070. **
  20071. ** int *a = (int*)sqlite3DbMallocRaw(db, 100);
  20072. ** int *b = (int*)sqlite3DbMallocRaw(db, 200);
  20073. ** if( b ) a[10] = 9;
  20074. **
  20075. ** In other words, if a subsequent malloc (ex: "b") worked, it is assumed
  20076. ** that all prior mallocs (ex: "a") worked too.
  20077. */
  20078. SQLITE_PRIVATE void *sqlite3DbMallocRaw(sqlite3 *db, u64 n){
  20079. void *p;
  20080. assert( db==0 || sqlite3_mutex_held(db->mutex) );
  20081. assert( db==0 || db->pnBytesFreed==0 );
  20082. #ifndef SQLITE_OMIT_LOOKASIDE
  20083. if( db ){
  20084. LookasideSlot *pBuf;
  20085. if( db->mallocFailed ){
  20086. return 0;
  20087. }
  20088. if( db->lookaside.bEnabled ){
  20089. if( n>db->lookaside.sz ){
  20090. db->lookaside.anStat[1]++;
  20091. }else if( (pBuf = db->lookaside.pFree)==0 ){
  20092. db->lookaside.anStat[2]++;
  20093. }else{
  20094. db->lookaside.pFree = pBuf->pNext;
  20095. db->lookaside.nOut++;
  20096. db->lookaside.anStat[0]++;
  20097. if( db->lookaside.nOut>db->lookaside.mxOut ){
  20098. db->lookaside.mxOut = db->lookaside.nOut;
  20099. }
  20100. return (void*)pBuf;
  20101. }
  20102. }
  20103. }
  20104. #else
  20105. if( db && db->mallocFailed ){
  20106. return 0;
  20107. }
  20108. #endif
  20109. p = sqlite3Malloc(n);
  20110. if( !p && db ){
  20111. db->mallocFailed = 1;
  20112. }
  20113. sqlite3MemdebugSetType(p,
  20114. (db && db->lookaside.bEnabled) ? MEMTYPE_LOOKASIDE : MEMTYPE_HEAP);
  20115. return p;
  20116. }
  20117. /*
  20118. ** Resize the block of memory pointed to by p to n bytes. If the
  20119. ** resize fails, set the mallocFailed flag in the connection object.
  20120. */
  20121. SQLITE_PRIVATE void *sqlite3DbRealloc(sqlite3 *db, void *p, u64 n){
  20122. void *pNew = 0;
  20123. assert( db!=0 );
  20124. assert( sqlite3_mutex_held(db->mutex) );
  20125. if( db->mallocFailed==0 ){
  20126. if( p==0 ){
  20127. return sqlite3DbMallocRaw(db, n);
  20128. }
  20129. if( isLookaside(db, p) ){
  20130. if( n<=db->lookaside.sz ){
  20131. return p;
  20132. }
  20133. pNew = sqlite3DbMallocRaw(db, n);
  20134. if( pNew ){
  20135. memcpy(pNew, p, db->lookaside.sz);
  20136. sqlite3DbFree(db, p);
  20137. }
  20138. }else{
  20139. assert( sqlite3MemdebugHasType(p, (MEMTYPE_LOOKASIDE|MEMTYPE_HEAP)) );
  20140. assert( sqlite3MemdebugNoType(p, (u8)~(MEMTYPE_LOOKASIDE|MEMTYPE_HEAP)) );
  20141. sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
  20142. pNew = sqlite3_realloc64(p, n);
  20143. if( !pNew ){
  20144. db->mallocFailed = 1;
  20145. }
  20146. sqlite3MemdebugSetType(pNew,
  20147. (db->lookaside.bEnabled ? MEMTYPE_LOOKASIDE : MEMTYPE_HEAP));
  20148. }
  20149. }
  20150. return pNew;
  20151. }
  20152. /*
  20153. ** Attempt to reallocate p. If the reallocation fails, then free p
  20154. ** and set the mallocFailed flag in the database connection.
  20155. */
  20156. SQLITE_PRIVATE void *sqlite3DbReallocOrFree(sqlite3 *db, void *p, u64 n){
  20157. void *pNew;
  20158. pNew = sqlite3DbRealloc(db, p, n);
  20159. if( !pNew ){
  20160. sqlite3DbFree(db, p);
  20161. }
  20162. return pNew;
  20163. }
  20164. /*
  20165. ** Make a copy of a string in memory obtained from sqliteMalloc(). These
  20166. ** functions call sqlite3MallocRaw() directly instead of sqliteMalloc(). This
  20167. ** is because when memory debugging is turned on, these two functions are
  20168. ** called via macros that record the current file and line number in the
  20169. ** ThreadData structure.
  20170. */
  20171. SQLITE_PRIVATE char *sqlite3DbStrDup(sqlite3 *db, const char *z){
  20172. char *zNew;
  20173. size_t n;
  20174. if( z==0 ){
  20175. return 0;
  20176. }
  20177. n = sqlite3Strlen30(z) + 1;
  20178. assert( (n&0x7fffffff)==n );
  20179. zNew = sqlite3DbMallocRaw(db, (int)n);
  20180. if( zNew ){
  20181. memcpy(zNew, z, n);
  20182. }
  20183. return zNew;
  20184. }
  20185. SQLITE_PRIVATE char *sqlite3DbStrNDup(sqlite3 *db, const char *z, u64 n){
  20186. char *zNew;
  20187. if( z==0 ){
  20188. return 0;
  20189. }
  20190. assert( (n&0x7fffffff)==n );
  20191. zNew = sqlite3DbMallocRaw(db, n+1);
  20192. if( zNew ){
  20193. memcpy(zNew, z, (size_t)n);
  20194. zNew[n] = 0;
  20195. }
  20196. return zNew;
  20197. }
  20198. /*
  20199. ** Create a string from the zFromat argument and the va_list that follows.
  20200. ** Store the string in memory obtained from sqliteMalloc() and make *pz
  20201. ** point to that string.
  20202. */
  20203. SQLITE_PRIVATE void sqlite3SetString(char **pz, sqlite3 *db, const char *zFormat, ...){
  20204. va_list ap;
  20205. char *z;
  20206. va_start(ap, zFormat);
  20207. z = sqlite3VMPrintf(db, zFormat, ap);
  20208. va_end(ap);
  20209. sqlite3DbFree(db, *pz);
  20210. *pz = z;
  20211. }
  20212. /*
  20213. ** Take actions at the end of an API call to indicate an OOM error
  20214. */
  20215. static SQLITE_NOINLINE int apiOomError(sqlite3 *db){
  20216. db->mallocFailed = 0;
  20217. sqlite3Error(db, SQLITE_NOMEM);
  20218. return SQLITE_NOMEM;
  20219. }
  20220. /*
  20221. ** This function must be called before exiting any API function (i.e.
  20222. ** returning control to the user) that has called sqlite3_malloc or
  20223. ** sqlite3_realloc.
  20224. **
  20225. ** The returned value is normally a copy of the second argument to this
  20226. ** function. However, if a malloc() failure has occurred since the previous
  20227. ** invocation SQLITE_NOMEM is returned instead.
  20228. **
  20229. ** If the first argument, db, is not NULL and a malloc() error has occurred,
  20230. ** then the connection error-code (the value returned by sqlite3_errcode())
  20231. ** is set to SQLITE_NOMEM.
  20232. */
  20233. SQLITE_PRIVATE int sqlite3ApiExit(sqlite3* db, int rc){
  20234. /* If the db handle is not NULL, then we must hold the connection handle
  20235. ** mutex here. Otherwise the read (and possible write) of db->mallocFailed
  20236. ** is unsafe, as is the call to sqlite3Error().
  20237. */
  20238. assert( !db || sqlite3_mutex_held(db->mutex) );
  20239. if( db==0 ) return rc & 0xff;
  20240. if( db->mallocFailed || rc==SQLITE_IOERR_NOMEM ){
  20241. return apiOomError(db);
  20242. }
  20243. return rc & db->errMask;
  20244. }
  20245. /************** End of malloc.c **********************************************/
  20246. /************** Begin file printf.c ******************************************/
  20247. /*
  20248. ** The "printf" code that follows dates from the 1980's. It is in
  20249. ** the public domain. The original comments are included here for
  20250. ** completeness. They are very out-of-date but might be useful as
  20251. ** an historical reference. Most of the "enhancements" have been backed
  20252. ** out so that the functionality is now the same as standard printf().
  20253. **
  20254. **************************************************************************
  20255. **
  20256. ** This file contains code for a set of "printf"-like routines. These
  20257. ** routines format strings much like the printf() from the standard C
  20258. ** library, though the implementation here has enhancements to support
  20259. ** SQLlite.
  20260. */
  20261. /*
  20262. ** Conversion types fall into various categories as defined by the
  20263. ** following enumeration.
  20264. */
  20265. #define etRADIX 1 /* Integer types. %d, %x, %o, and so forth */
  20266. #define etFLOAT 2 /* Floating point. %f */
  20267. #define etEXP 3 /* Exponentional notation. %e and %E */
  20268. #define etGENERIC 4 /* Floating or exponential, depending on exponent. %g */
  20269. #define etSIZE 5 /* Return number of characters processed so far. %n */
  20270. #define etSTRING 6 /* Strings. %s */
  20271. #define etDYNSTRING 7 /* Dynamically allocated strings. %z */
  20272. #define etPERCENT 8 /* Percent symbol. %% */
  20273. #define etCHARX 9 /* Characters. %c */
  20274. /* The rest are extensions, not normally found in printf() */
  20275. #define etSQLESCAPE 10 /* Strings with '\'' doubled. %q */
  20276. #define etSQLESCAPE2 11 /* Strings with '\'' doubled and enclosed in '',
  20277. NULL pointers replaced by SQL NULL. %Q */
  20278. #define etTOKEN 12 /* a pointer to a Token structure */
  20279. #define etSRCLIST 13 /* a pointer to a SrcList */
  20280. #define etPOINTER 14 /* The %p conversion */
  20281. #define etSQLESCAPE3 15 /* %w -> Strings with '\"' doubled */
  20282. #define etORDINAL 16 /* %r -> 1st, 2nd, 3rd, 4th, etc. English only */
  20283. #define etINVALID 0 /* Any unrecognized conversion type */
  20284. /*
  20285. ** An "etByte" is an 8-bit unsigned value.
  20286. */
  20287. typedef unsigned char etByte;
  20288. /*
  20289. ** Each builtin conversion character (ex: the 'd' in "%d") is described
  20290. ** by an instance of the following structure
  20291. */
  20292. typedef struct et_info { /* Information about each format field */
  20293. char fmttype; /* The format field code letter */
  20294. etByte base; /* The base for radix conversion */
  20295. etByte flags; /* One or more of FLAG_ constants below */
  20296. etByte type; /* Conversion paradigm */
  20297. etByte charset; /* Offset into aDigits[] of the digits string */
  20298. etByte prefix; /* Offset into aPrefix[] of the prefix string */
  20299. } et_info;
  20300. /*
  20301. ** Allowed values for et_info.flags
  20302. */
  20303. #define FLAG_SIGNED 1 /* True if the value to convert is signed */
  20304. #define FLAG_INTERN 2 /* True if for internal use only */
  20305. #define FLAG_STRING 4 /* Allow infinity precision */
  20306. /*
  20307. ** The following table is searched linearly, so it is good to put the
  20308. ** most frequently used conversion types first.
  20309. */
  20310. static const char aDigits[] = "0123456789ABCDEF0123456789abcdef";
  20311. static const char aPrefix[] = "-x0\000X0";
  20312. static const et_info fmtinfo[] = {
  20313. { 'd', 10, 1, etRADIX, 0, 0 },
  20314. { 's', 0, 4, etSTRING, 0, 0 },
  20315. { 'g', 0, 1, etGENERIC, 30, 0 },
  20316. { 'z', 0, 4, etDYNSTRING, 0, 0 },
  20317. { 'q', 0, 4, etSQLESCAPE, 0, 0 },
  20318. { 'Q', 0, 4, etSQLESCAPE2, 0, 0 },
  20319. { 'w', 0, 4, etSQLESCAPE3, 0, 0 },
  20320. { 'c', 0, 0, etCHARX, 0, 0 },
  20321. { 'o', 8, 0, etRADIX, 0, 2 },
  20322. { 'u', 10, 0, etRADIX, 0, 0 },
  20323. { 'x', 16, 0, etRADIX, 16, 1 },
  20324. { 'X', 16, 0, etRADIX, 0, 4 },
  20325. #ifndef SQLITE_OMIT_FLOATING_POINT
  20326. { 'f', 0, 1, etFLOAT, 0, 0 },
  20327. { 'e', 0, 1, etEXP, 30, 0 },
  20328. { 'E', 0, 1, etEXP, 14, 0 },
  20329. { 'G', 0, 1, etGENERIC, 14, 0 },
  20330. #endif
  20331. { 'i', 10, 1, etRADIX, 0, 0 },
  20332. { 'n', 0, 0, etSIZE, 0, 0 },
  20333. { '%', 0, 0, etPERCENT, 0, 0 },
  20334. { 'p', 16, 0, etPOINTER, 0, 1 },
  20335. /* All the rest have the FLAG_INTERN bit set and are thus for internal
  20336. ** use only */
  20337. { 'T', 0, 2, etTOKEN, 0, 0 },
  20338. { 'S', 0, 2, etSRCLIST, 0, 0 },
  20339. { 'r', 10, 3, etORDINAL, 0, 0 },
  20340. };
  20341. /*
  20342. ** If SQLITE_OMIT_FLOATING_POINT is defined, then none of the floating point
  20343. ** conversions will work.
  20344. */
  20345. #ifndef SQLITE_OMIT_FLOATING_POINT
  20346. /*
  20347. ** "*val" is a double such that 0.1 <= *val < 10.0
  20348. ** Return the ascii code for the leading digit of *val, then
  20349. ** multiply "*val" by 10.0 to renormalize.
  20350. **
  20351. ** Example:
  20352. ** input: *val = 3.14159
  20353. ** output: *val = 1.4159 function return = '3'
  20354. **
  20355. ** The counter *cnt is incremented each time. After counter exceeds
  20356. ** 16 (the number of significant digits in a 64-bit float) '0' is
  20357. ** always returned.
  20358. */
  20359. static char et_getdigit(LONGDOUBLE_TYPE *val, int *cnt){
  20360. int digit;
  20361. LONGDOUBLE_TYPE d;
  20362. if( (*cnt)<=0 ) return '0';
  20363. (*cnt)--;
  20364. digit = (int)*val;
  20365. d = digit;
  20366. digit += '0';
  20367. *val = (*val - d)*10.0;
  20368. return (char)digit;
  20369. }
  20370. #endif /* SQLITE_OMIT_FLOATING_POINT */
  20371. /*
  20372. ** Set the StrAccum object to an error mode.
  20373. */
  20374. static void setStrAccumError(StrAccum *p, u8 eError){
  20375. assert( eError==STRACCUM_NOMEM || eError==STRACCUM_TOOBIG );
  20376. p->accError = eError;
  20377. p->nAlloc = 0;
  20378. }
  20379. /*
  20380. ** Extra argument values from a PrintfArguments object
  20381. */
  20382. static sqlite3_int64 getIntArg(PrintfArguments *p){
  20383. if( p->nArg<=p->nUsed ) return 0;
  20384. return sqlite3_value_int64(p->apArg[p->nUsed++]);
  20385. }
  20386. static double getDoubleArg(PrintfArguments *p){
  20387. if( p->nArg<=p->nUsed ) return 0.0;
  20388. return sqlite3_value_double(p->apArg[p->nUsed++]);
  20389. }
  20390. static char *getTextArg(PrintfArguments *p){
  20391. if( p->nArg<=p->nUsed ) return 0;
  20392. return (char*)sqlite3_value_text(p->apArg[p->nUsed++]);
  20393. }
  20394. /*
  20395. ** On machines with a small stack size, you can redefine the
  20396. ** SQLITE_PRINT_BUF_SIZE to be something smaller, if desired.
  20397. */
  20398. #ifndef SQLITE_PRINT_BUF_SIZE
  20399. # define SQLITE_PRINT_BUF_SIZE 70
  20400. #endif
  20401. #define etBUFSIZE SQLITE_PRINT_BUF_SIZE /* Size of the output buffer */
  20402. /*
  20403. ** Render a string given by "fmt" into the StrAccum object.
  20404. */
  20405. SQLITE_PRIVATE void sqlite3VXPrintf(
  20406. StrAccum *pAccum, /* Accumulate results here */
  20407. u32 bFlags, /* SQLITE_PRINTF_* flags */
  20408. const char *fmt, /* Format string */
  20409. va_list ap /* arguments */
  20410. ){
  20411. int c; /* Next character in the format string */
  20412. char *bufpt; /* Pointer to the conversion buffer */
  20413. int precision; /* Precision of the current field */
  20414. int length; /* Length of the field */
  20415. int idx; /* A general purpose loop counter */
  20416. int width; /* Width of the current field */
  20417. etByte flag_leftjustify; /* True if "-" flag is present */
  20418. etByte flag_plussign; /* True if "+" flag is present */
  20419. etByte flag_blanksign; /* True if " " flag is present */
  20420. etByte flag_alternateform; /* True if "#" flag is present */
  20421. etByte flag_altform2; /* True if "!" flag is present */
  20422. etByte flag_zeropad; /* True if field width constant starts with zero */
  20423. etByte flag_long; /* True if "l" flag is present */
  20424. etByte flag_longlong; /* True if the "ll" flag is present */
  20425. etByte done; /* Loop termination flag */
  20426. etByte xtype = 0; /* Conversion paradigm */
  20427. u8 bArgList; /* True for SQLITE_PRINTF_SQLFUNC */
  20428. u8 useIntern; /* Ok to use internal conversions (ex: %T) */
  20429. char prefix; /* Prefix character. "+" or "-" or " " or '\0'. */
  20430. sqlite_uint64 longvalue; /* Value for integer types */
  20431. LONGDOUBLE_TYPE realvalue; /* Value for real types */
  20432. const et_info *infop; /* Pointer to the appropriate info structure */
  20433. char *zOut; /* Rendering buffer */
  20434. int nOut; /* Size of the rendering buffer */
  20435. char *zExtra = 0; /* Malloced memory used by some conversion */
  20436. #ifndef SQLITE_OMIT_FLOATING_POINT
  20437. int exp, e2; /* exponent of real numbers */
  20438. int nsd; /* Number of significant digits returned */
  20439. double rounder; /* Used for rounding floating point values */
  20440. etByte flag_dp; /* True if decimal point should be shown */
  20441. etByte flag_rtz; /* True if trailing zeros should be removed */
  20442. #endif
  20443. PrintfArguments *pArgList = 0; /* Arguments for SQLITE_PRINTF_SQLFUNC */
  20444. char buf[etBUFSIZE]; /* Conversion buffer */
  20445. bufpt = 0;
  20446. if( bFlags ){
  20447. if( (bArgList = (bFlags & SQLITE_PRINTF_SQLFUNC))!=0 ){
  20448. pArgList = va_arg(ap, PrintfArguments*);
  20449. }
  20450. useIntern = bFlags & SQLITE_PRINTF_INTERNAL;
  20451. }else{
  20452. bArgList = useIntern = 0;
  20453. }
  20454. for(; (c=(*fmt))!=0; ++fmt){
  20455. if( c!='%' ){
  20456. bufpt = (char *)fmt;
  20457. #if HAVE_STRCHRNUL
  20458. fmt = strchrnul(fmt, '%');
  20459. #else
  20460. do{ fmt++; }while( *fmt && *fmt != '%' );
  20461. #endif
  20462. sqlite3StrAccumAppend(pAccum, bufpt, (int)(fmt - bufpt));
  20463. if( *fmt==0 ) break;
  20464. }
  20465. if( (c=(*++fmt))==0 ){
  20466. sqlite3StrAccumAppend(pAccum, "%", 1);
  20467. break;
  20468. }
  20469. /* Find out what flags are present */
  20470. flag_leftjustify = flag_plussign = flag_blanksign =
  20471. flag_alternateform = flag_altform2 = flag_zeropad = 0;
  20472. done = 0;
  20473. do{
  20474. switch( c ){
  20475. case '-': flag_leftjustify = 1; break;
  20476. case '+': flag_plussign = 1; break;
  20477. case ' ': flag_blanksign = 1; break;
  20478. case '#': flag_alternateform = 1; break;
  20479. case '!': flag_altform2 = 1; break;
  20480. case '0': flag_zeropad = 1; break;
  20481. default: done = 1; break;
  20482. }
  20483. }while( !done && (c=(*++fmt))!=0 );
  20484. /* Get the field width */
  20485. if( c=='*' ){
  20486. if( bArgList ){
  20487. width = (int)getIntArg(pArgList);
  20488. }else{
  20489. width = va_arg(ap,int);
  20490. }
  20491. if( width<0 ){
  20492. flag_leftjustify = 1;
  20493. width = width >= -2147483647 ? -width : 0;
  20494. }
  20495. c = *++fmt;
  20496. }else{
  20497. unsigned wx = 0;
  20498. while( c>='0' && c<='9' ){
  20499. wx = wx*10 + c - '0';
  20500. c = *++fmt;
  20501. }
  20502. testcase( wx>0x7fffffff );
  20503. width = wx & 0x7fffffff;
  20504. }
  20505. /* Get the precision */
  20506. if( c=='.' ){
  20507. c = *++fmt;
  20508. if( c=='*' ){
  20509. if( bArgList ){
  20510. precision = (int)getIntArg(pArgList);
  20511. }else{
  20512. precision = va_arg(ap,int);
  20513. }
  20514. c = *++fmt;
  20515. if( precision<0 ){
  20516. precision = precision >= -2147483647 ? -precision : -1;
  20517. }
  20518. }else{
  20519. unsigned px = 0;
  20520. while( c>='0' && c<='9' ){
  20521. px = px*10 + c - '0';
  20522. c = *++fmt;
  20523. }
  20524. testcase( px>0x7fffffff );
  20525. precision = px & 0x7fffffff;
  20526. }
  20527. }else{
  20528. precision = -1;
  20529. }
  20530. /* Get the conversion type modifier */
  20531. if( c=='l' ){
  20532. flag_long = 1;
  20533. c = *++fmt;
  20534. if( c=='l' ){
  20535. flag_longlong = 1;
  20536. c = *++fmt;
  20537. }else{
  20538. flag_longlong = 0;
  20539. }
  20540. }else{
  20541. flag_long = flag_longlong = 0;
  20542. }
  20543. /* Fetch the info entry for the field */
  20544. infop = &fmtinfo[0];
  20545. xtype = etINVALID;
  20546. for(idx=0; idx<ArraySize(fmtinfo); idx++){
  20547. if( c==fmtinfo[idx].fmttype ){
  20548. infop = &fmtinfo[idx];
  20549. if( useIntern || (infop->flags & FLAG_INTERN)==0 ){
  20550. xtype = infop->type;
  20551. }else{
  20552. return;
  20553. }
  20554. break;
  20555. }
  20556. }
  20557. /*
  20558. ** At this point, variables are initialized as follows:
  20559. **
  20560. ** flag_alternateform TRUE if a '#' is present.
  20561. ** flag_altform2 TRUE if a '!' is present.
  20562. ** flag_plussign TRUE if a '+' is present.
  20563. ** flag_leftjustify TRUE if a '-' is present or if the
  20564. ** field width was negative.
  20565. ** flag_zeropad TRUE if the width began with 0.
  20566. ** flag_long TRUE if the letter 'l' (ell) prefixed
  20567. ** the conversion character.
  20568. ** flag_longlong TRUE if the letter 'll' (ell ell) prefixed
  20569. ** the conversion character.
  20570. ** flag_blanksign TRUE if a ' ' is present.
  20571. ** width The specified field width. This is
  20572. ** always non-negative. Zero is the default.
  20573. ** precision The specified precision. The default
  20574. ** is -1.
  20575. ** xtype The class of the conversion.
  20576. ** infop Pointer to the appropriate info struct.
  20577. */
  20578. switch( xtype ){
  20579. case etPOINTER:
  20580. flag_longlong = sizeof(char*)==sizeof(i64);
  20581. flag_long = sizeof(char*)==sizeof(long int);
  20582. /* Fall through into the next case */
  20583. case etORDINAL:
  20584. case etRADIX:
  20585. if( infop->flags & FLAG_SIGNED ){
  20586. i64 v;
  20587. if( bArgList ){
  20588. v = getIntArg(pArgList);
  20589. }else if( flag_longlong ){
  20590. v = va_arg(ap,i64);
  20591. }else if( flag_long ){
  20592. v = va_arg(ap,long int);
  20593. }else{
  20594. v = va_arg(ap,int);
  20595. }
  20596. if( v<0 ){
  20597. if( v==SMALLEST_INT64 ){
  20598. longvalue = ((u64)1)<<63;
  20599. }else{
  20600. longvalue = -v;
  20601. }
  20602. prefix = '-';
  20603. }else{
  20604. longvalue = v;
  20605. if( flag_plussign ) prefix = '+';
  20606. else if( flag_blanksign ) prefix = ' ';
  20607. else prefix = 0;
  20608. }
  20609. }else{
  20610. if( bArgList ){
  20611. longvalue = (u64)getIntArg(pArgList);
  20612. }else if( flag_longlong ){
  20613. longvalue = va_arg(ap,u64);
  20614. }else if( flag_long ){
  20615. longvalue = va_arg(ap,unsigned long int);
  20616. }else{
  20617. longvalue = va_arg(ap,unsigned int);
  20618. }
  20619. prefix = 0;
  20620. }
  20621. if( longvalue==0 ) flag_alternateform = 0;
  20622. if( flag_zeropad && precision<width-(prefix!=0) ){
  20623. precision = width-(prefix!=0);
  20624. }
  20625. if( precision<etBUFSIZE-10 ){
  20626. nOut = etBUFSIZE;
  20627. zOut = buf;
  20628. }else{
  20629. nOut = precision + 10;
  20630. zOut = zExtra = sqlite3Malloc( nOut );
  20631. if( zOut==0 ){
  20632. setStrAccumError(pAccum, STRACCUM_NOMEM);
  20633. return;
  20634. }
  20635. }
  20636. bufpt = &zOut[nOut-1];
  20637. if( xtype==etORDINAL ){
  20638. static const char zOrd[] = "thstndrd";
  20639. int x = (int)(longvalue % 10);
  20640. if( x>=4 || (longvalue/10)%10==1 ){
  20641. x = 0;
  20642. }
  20643. *(--bufpt) = zOrd[x*2+1];
  20644. *(--bufpt) = zOrd[x*2];
  20645. }
  20646. {
  20647. const char *cset = &aDigits[infop->charset];
  20648. u8 base = infop->base;
  20649. do{ /* Convert to ascii */
  20650. *(--bufpt) = cset[longvalue%base];
  20651. longvalue = longvalue/base;
  20652. }while( longvalue>0 );
  20653. }
  20654. length = (int)(&zOut[nOut-1]-bufpt);
  20655. for(idx=precision-length; idx>0; idx--){
  20656. *(--bufpt) = '0'; /* Zero pad */
  20657. }
  20658. if( prefix ) *(--bufpt) = prefix; /* Add sign */
  20659. if( flag_alternateform && infop->prefix ){ /* Add "0" or "0x" */
  20660. const char *pre;
  20661. char x;
  20662. pre = &aPrefix[infop->prefix];
  20663. for(; (x=(*pre))!=0; pre++) *(--bufpt) = x;
  20664. }
  20665. length = (int)(&zOut[nOut-1]-bufpt);
  20666. break;
  20667. case etFLOAT:
  20668. case etEXP:
  20669. case etGENERIC:
  20670. if( bArgList ){
  20671. realvalue = getDoubleArg(pArgList);
  20672. }else{
  20673. realvalue = va_arg(ap,double);
  20674. }
  20675. #ifdef SQLITE_OMIT_FLOATING_POINT
  20676. length = 0;
  20677. #else
  20678. if( precision<0 ) precision = 6; /* Set default precision */
  20679. if( realvalue<0.0 ){
  20680. realvalue = -realvalue;
  20681. prefix = '-';
  20682. }else{
  20683. if( flag_plussign ) prefix = '+';
  20684. else if( flag_blanksign ) prefix = ' ';
  20685. else prefix = 0;
  20686. }
  20687. if( xtype==etGENERIC && precision>0 ) precision--;
  20688. testcase( precision>0xfff );
  20689. for(idx=precision&0xfff, rounder=0.5; idx>0; idx--, rounder*=0.1){}
  20690. if( xtype==etFLOAT ) realvalue += rounder;
  20691. /* Normalize realvalue to within 10.0 > realvalue >= 1.0 */
  20692. exp = 0;
  20693. if( sqlite3IsNaN((double)realvalue) ){
  20694. bufpt = "NaN";
  20695. length = 3;
  20696. break;
  20697. }
  20698. if( realvalue>0.0 ){
  20699. LONGDOUBLE_TYPE scale = 1.0;
  20700. while( realvalue>=1e100*scale && exp<=350 ){ scale *= 1e100;exp+=100;}
  20701. while( realvalue>=1e64*scale && exp<=350 ){ scale *= 1e64; exp+=64; }
  20702. while( realvalue>=1e8*scale && exp<=350 ){ scale *= 1e8; exp+=8; }
  20703. while( realvalue>=10.0*scale && exp<=350 ){ scale *= 10.0; exp++; }
  20704. realvalue /= scale;
  20705. while( realvalue<1e-8 ){ realvalue *= 1e8; exp-=8; }
  20706. while( realvalue<1.0 ){ realvalue *= 10.0; exp--; }
  20707. if( exp>350 ){
  20708. if( prefix=='-' ){
  20709. bufpt = "-Inf";
  20710. }else if( prefix=='+' ){
  20711. bufpt = "+Inf";
  20712. }else{
  20713. bufpt = "Inf";
  20714. }
  20715. length = sqlite3Strlen30(bufpt);
  20716. break;
  20717. }
  20718. }
  20719. bufpt = buf;
  20720. /*
  20721. ** If the field type is etGENERIC, then convert to either etEXP
  20722. ** or etFLOAT, as appropriate.
  20723. */
  20724. if( xtype!=etFLOAT ){
  20725. realvalue += rounder;
  20726. if( realvalue>=10.0 ){ realvalue *= 0.1; exp++; }
  20727. }
  20728. if( xtype==etGENERIC ){
  20729. flag_rtz = !flag_alternateform;
  20730. if( exp<-4 || exp>precision ){
  20731. xtype = etEXP;
  20732. }else{
  20733. precision = precision - exp;
  20734. xtype = etFLOAT;
  20735. }
  20736. }else{
  20737. flag_rtz = flag_altform2;
  20738. }
  20739. if( xtype==etEXP ){
  20740. e2 = 0;
  20741. }else{
  20742. e2 = exp;
  20743. }
  20744. if( MAX(e2,0)+(i64)precision+(i64)width > etBUFSIZE - 15 ){
  20745. bufpt = zExtra
  20746. = sqlite3Malloc( MAX(e2,0)+(i64)precision+(i64)width+15 );
  20747. if( bufpt==0 ){
  20748. setStrAccumError(pAccum, STRACCUM_NOMEM);
  20749. return;
  20750. }
  20751. }
  20752. zOut = bufpt;
  20753. nsd = 16 + flag_altform2*10;
  20754. flag_dp = (precision>0 ?1:0) | flag_alternateform | flag_altform2;
  20755. /* The sign in front of the number */
  20756. if( prefix ){
  20757. *(bufpt++) = prefix;
  20758. }
  20759. /* Digits prior to the decimal point */
  20760. if( e2<0 ){
  20761. *(bufpt++) = '0';
  20762. }else{
  20763. for(; e2>=0; e2--){
  20764. *(bufpt++) = et_getdigit(&realvalue,&nsd);
  20765. }
  20766. }
  20767. /* The decimal point */
  20768. if( flag_dp ){
  20769. *(bufpt++) = '.';
  20770. }
  20771. /* "0" digits after the decimal point but before the first
  20772. ** significant digit of the number */
  20773. for(e2++; e2<0; precision--, e2++){
  20774. assert( precision>0 );
  20775. *(bufpt++) = '0';
  20776. }
  20777. /* Significant digits after the decimal point */
  20778. while( (precision--)>0 ){
  20779. *(bufpt++) = et_getdigit(&realvalue,&nsd);
  20780. }
  20781. /* Remove trailing zeros and the "." if no digits follow the "." */
  20782. if( flag_rtz && flag_dp ){
  20783. while( bufpt[-1]=='0' ) *(--bufpt) = 0;
  20784. assert( bufpt>zOut );
  20785. if( bufpt[-1]=='.' ){
  20786. if( flag_altform2 ){
  20787. *(bufpt++) = '0';
  20788. }else{
  20789. *(--bufpt) = 0;
  20790. }
  20791. }
  20792. }
  20793. /* Add the "eNNN" suffix */
  20794. if( xtype==etEXP ){
  20795. *(bufpt++) = aDigits[infop->charset];
  20796. if( exp<0 ){
  20797. *(bufpt++) = '-'; exp = -exp;
  20798. }else{
  20799. *(bufpt++) = '+';
  20800. }
  20801. if( exp>=100 ){
  20802. *(bufpt++) = (char)((exp/100)+'0'); /* 100's digit */
  20803. exp %= 100;
  20804. }
  20805. *(bufpt++) = (char)(exp/10+'0'); /* 10's digit */
  20806. *(bufpt++) = (char)(exp%10+'0'); /* 1's digit */
  20807. }
  20808. *bufpt = 0;
  20809. /* The converted number is in buf[] and zero terminated. Output it.
  20810. ** Note that the number is in the usual order, not reversed as with
  20811. ** integer conversions. */
  20812. length = (int)(bufpt-zOut);
  20813. bufpt = zOut;
  20814. /* Special case: Add leading zeros if the flag_zeropad flag is
  20815. ** set and we are not left justified */
  20816. if( flag_zeropad && !flag_leftjustify && length < width){
  20817. int i;
  20818. int nPad = width - length;
  20819. for(i=width; i>=nPad; i--){
  20820. bufpt[i] = bufpt[i-nPad];
  20821. }
  20822. i = prefix!=0;
  20823. while( nPad-- ) bufpt[i++] = '0';
  20824. length = width;
  20825. }
  20826. #endif /* !defined(SQLITE_OMIT_FLOATING_POINT) */
  20827. break;
  20828. case etSIZE:
  20829. if( !bArgList ){
  20830. *(va_arg(ap,int*)) = pAccum->nChar;
  20831. }
  20832. length = width = 0;
  20833. break;
  20834. case etPERCENT:
  20835. buf[0] = '%';
  20836. bufpt = buf;
  20837. length = 1;
  20838. break;
  20839. case etCHARX:
  20840. if( bArgList ){
  20841. bufpt = getTextArg(pArgList);
  20842. c = bufpt ? bufpt[0] : 0;
  20843. }else{
  20844. c = va_arg(ap,int);
  20845. }
  20846. if( precision>1 ){
  20847. width -= precision-1;
  20848. if( width>1 && !flag_leftjustify ){
  20849. sqlite3AppendChar(pAccum, width-1, ' ');
  20850. width = 0;
  20851. }
  20852. sqlite3AppendChar(pAccum, precision-1, c);
  20853. }
  20854. length = 1;
  20855. buf[0] = c;
  20856. bufpt = buf;
  20857. break;
  20858. case etSTRING:
  20859. case etDYNSTRING:
  20860. if( bArgList ){
  20861. bufpt = getTextArg(pArgList);
  20862. }else{
  20863. bufpt = va_arg(ap,char*);
  20864. }
  20865. if( bufpt==0 ){
  20866. bufpt = "";
  20867. }else if( xtype==etDYNSTRING && !bArgList ){
  20868. zExtra = bufpt;
  20869. }
  20870. if( precision>=0 ){
  20871. for(length=0; length<precision && bufpt[length]; length++){}
  20872. }else{
  20873. length = sqlite3Strlen30(bufpt);
  20874. }
  20875. break;
  20876. case etSQLESCAPE:
  20877. case etSQLESCAPE2:
  20878. case etSQLESCAPE3: {
  20879. int i, j, k, n, isnull;
  20880. int needQuote;
  20881. char ch;
  20882. char q = ((xtype==etSQLESCAPE3)?'"':'\''); /* Quote character */
  20883. char *escarg;
  20884. if( bArgList ){
  20885. escarg = getTextArg(pArgList);
  20886. }else{
  20887. escarg = va_arg(ap,char*);
  20888. }
  20889. isnull = escarg==0;
  20890. if( isnull ) escarg = (xtype==etSQLESCAPE2 ? "NULL" : "(NULL)");
  20891. k = precision;
  20892. for(i=n=0; k!=0 && (ch=escarg[i])!=0; i++, k--){
  20893. if( ch==q ) n++;
  20894. }
  20895. needQuote = !isnull && xtype==etSQLESCAPE2;
  20896. n += i + 1 + needQuote*2;
  20897. if( n>etBUFSIZE ){
  20898. bufpt = zExtra = sqlite3Malloc( n );
  20899. if( bufpt==0 ){
  20900. setStrAccumError(pAccum, STRACCUM_NOMEM);
  20901. return;
  20902. }
  20903. }else{
  20904. bufpt = buf;
  20905. }
  20906. j = 0;
  20907. if( needQuote ) bufpt[j++] = q;
  20908. k = i;
  20909. for(i=0; i<k; i++){
  20910. bufpt[j++] = ch = escarg[i];
  20911. if( ch==q ) bufpt[j++] = ch;
  20912. }
  20913. if( needQuote ) bufpt[j++] = q;
  20914. bufpt[j] = 0;
  20915. length = j;
  20916. /* The precision in %q and %Q means how many input characters to
  20917. ** consume, not the length of the output...
  20918. ** if( precision>=0 && precision<length ) length = precision; */
  20919. break;
  20920. }
  20921. case etTOKEN: {
  20922. Token *pToken = va_arg(ap, Token*);
  20923. assert( bArgList==0 );
  20924. if( pToken && pToken->n ){
  20925. sqlite3StrAccumAppend(pAccum, (const char*)pToken->z, pToken->n);
  20926. }
  20927. length = width = 0;
  20928. break;
  20929. }
  20930. case etSRCLIST: {
  20931. SrcList *pSrc = va_arg(ap, SrcList*);
  20932. int k = va_arg(ap, int);
  20933. struct SrcList_item *pItem = &pSrc->a[k];
  20934. assert( bArgList==0 );
  20935. assert( k>=0 && k<pSrc->nSrc );
  20936. if( pItem->zDatabase ){
  20937. sqlite3StrAccumAppendAll(pAccum, pItem->zDatabase);
  20938. sqlite3StrAccumAppend(pAccum, ".", 1);
  20939. }
  20940. sqlite3StrAccumAppendAll(pAccum, pItem->zName);
  20941. length = width = 0;
  20942. break;
  20943. }
  20944. default: {
  20945. assert( xtype==etINVALID );
  20946. return;
  20947. }
  20948. }/* End switch over the format type */
  20949. /*
  20950. ** The text of the conversion is pointed to by "bufpt" and is
  20951. ** "length" characters long. The field width is "width". Do
  20952. ** the output.
  20953. */
  20954. width -= length;
  20955. if( width>0 && !flag_leftjustify ) sqlite3AppendChar(pAccum, width, ' ');
  20956. sqlite3StrAccumAppend(pAccum, bufpt, length);
  20957. if( width>0 && flag_leftjustify ) sqlite3AppendChar(pAccum, width, ' ');
  20958. if( zExtra ){
  20959. sqlite3_free(zExtra);
  20960. zExtra = 0;
  20961. }
  20962. }/* End for loop over the format string */
  20963. } /* End of function */
  20964. /*
  20965. ** Enlarge the memory allocation on a StrAccum object so that it is
  20966. ** able to accept at least N more bytes of text.
  20967. **
  20968. ** Return the number of bytes of text that StrAccum is able to accept
  20969. ** after the attempted enlargement. The value returned might be zero.
  20970. */
  20971. static int sqlite3StrAccumEnlarge(StrAccum *p, int N){
  20972. char *zNew;
  20973. assert( p->nChar+(i64)N >= p->nAlloc ); /* Only called if really needed */
  20974. if( p->accError ){
  20975. testcase(p->accError==STRACCUM_TOOBIG);
  20976. testcase(p->accError==STRACCUM_NOMEM);
  20977. return 0;
  20978. }
  20979. if( p->mxAlloc==0 ){
  20980. N = p->nAlloc - p->nChar - 1;
  20981. setStrAccumError(p, STRACCUM_TOOBIG);
  20982. return N;
  20983. }else{
  20984. char *zOld = (p->zText==p->zBase ? 0 : p->zText);
  20985. i64 szNew = p->nChar;
  20986. szNew += N + 1;
  20987. if( szNew+p->nChar<=p->mxAlloc ){
  20988. /* Force exponential buffer size growth as long as it does not overflow,
  20989. ** to avoid having to call this routine too often */
  20990. szNew += p->nChar;
  20991. }
  20992. if( szNew > p->mxAlloc ){
  20993. sqlite3StrAccumReset(p);
  20994. setStrAccumError(p, STRACCUM_TOOBIG);
  20995. return 0;
  20996. }else{
  20997. p->nAlloc = (int)szNew;
  20998. }
  20999. if( p->db ){
  21000. zNew = sqlite3DbRealloc(p->db, zOld, p->nAlloc);
  21001. }else{
  21002. zNew = sqlite3_realloc64(zOld, p->nAlloc);
  21003. }
  21004. if( zNew ){
  21005. assert( p->zText!=0 || p->nChar==0 );
  21006. if( zOld==0 && p->nChar>0 ) memcpy(zNew, p->zText, p->nChar);
  21007. p->zText = zNew;
  21008. p->nAlloc = sqlite3DbMallocSize(p->db, zNew);
  21009. }else{
  21010. sqlite3StrAccumReset(p);
  21011. setStrAccumError(p, STRACCUM_NOMEM);
  21012. return 0;
  21013. }
  21014. }
  21015. return N;
  21016. }
  21017. /*
  21018. ** Append N copies of character c to the given string buffer.
  21019. */
  21020. SQLITE_PRIVATE void sqlite3AppendChar(StrAccum *p, int N, char c){
  21021. testcase( p->nChar + (i64)N > 0x7fffffff );
  21022. if( p->nChar+(i64)N >= p->nAlloc && (N = sqlite3StrAccumEnlarge(p, N))<=0 ){
  21023. return;
  21024. }
  21025. while( (N--)>0 ) p->zText[p->nChar++] = c;
  21026. }
  21027. /*
  21028. ** The StrAccum "p" is not large enough to accept N new bytes of z[].
  21029. ** So enlarge if first, then do the append.
  21030. **
  21031. ** This is a helper routine to sqlite3StrAccumAppend() that does special-case
  21032. ** work (enlarging the buffer) using tail recursion, so that the
  21033. ** sqlite3StrAccumAppend() routine can use fast calling semantics.
  21034. */
  21035. static void SQLITE_NOINLINE enlargeAndAppend(StrAccum *p, const char *z, int N){
  21036. N = sqlite3StrAccumEnlarge(p, N);
  21037. if( N>0 ){
  21038. memcpy(&p->zText[p->nChar], z, N);
  21039. p->nChar += N;
  21040. }
  21041. }
  21042. /*
  21043. ** Append N bytes of text from z to the StrAccum object. Increase the
  21044. ** size of the memory allocation for StrAccum if necessary.
  21045. */
  21046. SQLITE_PRIVATE void sqlite3StrAccumAppend(StrAccum *p, const char *z, int N){
  21047. assert( z!=0 || N==0 );
  21048. assert( p->zText!=0 || p->nChar==0 || p->accError );
  21049. assert( N>=0 );
  21050. assert( p->accError==0 || p->nAlloc==0 );
  21051. if( p->nChar+N >= p->nAlloc ){
  21052. enlargeAndAppend(p,z,N);
  21053. }else{
  21054. assert( p->zText );
  21055. p->nChar += N;
  21056. memcpy(&p->zText[p->nChar-N], z, N);
  21057. }
  21058. }
  21059. /*
  21060. ** Append the complete text of zero-terminated string z[] to the p string.
  21061. */
  21062. SQLITE_PRIVATE void sqlite3StrAccumAppendAll(StrAccum *p, const char *z){
  21063. sqlite3StrAccumAppend(p, z, sqlite3Strlen30(z));
  21064. }
  21065. /*
  21066. ** Finish off a string by making sure it is zero-terminated.
  21067. ** Return a pointer to the resulting string. Return a NULL
  21068. ** pointer if any kind of error was encountered.
  21069. */
  21070. SQLITE_PRIVATE char *sqlite3StrAccumFinish(StrAccum *p){
  21071. if( p->zText ){
  21072. p->zText[p->nChar] = 0;
  21073. if( p->mxAlloc>0 && p->zText==p->zBase ){
  21074. p->zText = sqlite3DbMallocRaw(p->db, p->nChar+1 );
  21075. if( p->zText ){
  21076. memcpy(p->zText, p->zBase, p->nChar+1);
  21077. }else{
  21078. setStrAccumError(p, STRACCUM_NOMEM);
  21079. }
  21080. }
  21081. }
  21082. return p->zText;
  21083. }
  21084. /*
  21085. ** Reset an StrAccum string. Reclaim all malloced memory.
  21086. */
  21087. SQLITE_PRIVATE void sqlite3StrAccumReset(StrAccum *p){
  21088. if( p->zText!=p->zBase ){
  21089. sqlite3DbFree(p->db, p->zText);
  21090. }
  21091. p->zText = 0;
  21092. }
  21093. /*
  21094. ** Initialize a string accumulator.
  21095. **
  21096. ** p: The accumulator to be initialized.
  21097. ** db: Pointer to a database connection. May be NULL. Lookaside
  21098. ** memory is used if not NULL. db->mallocFailed is set appropriately
  21099. ** when not NULL.
  21100. ** zBase: An initial buffer. May be NULL in which case the initial buffer
  21101. ** is malloced.
  21102. ** n: Size of zBase in bytes. If total space requirements never exceed
  21103. ** n then no memory allocations ever occur.
  21104. ** mx: Maximum number of bytes to accumulate. If mx==0 then no memory
  21105. ** allocations will ever occur.
  21106. */
  21107. SQLITE_PRIVATE void sqlite3StrAccumInit(StrAccum *p, sqlite3 *db, char *zBase, int n, int mx){
  21108. p->zText = p->zBase = zBase;
  21109. p->db = db;
  21110. p->nChar = 0;
  21111. p->nAlloc = n;
  21112. p->mxAlloc = mx;
  21113. p->accError = 0;
  21114. }
  21115. /*
  21116. ** Print into memory obtained from sqliteMalloc(). Use the internal
  21117. ** %-conversion extensions.
  21118. */
  21119. SQLITE_PRIVATE char *sqlite3VMPrintf(sqlite3 *db, const char *zFormat, va_list ap){
  21120. char *z;
  21121. char zBase[SQLITE_PRINT_BUF_SIZE];
  21122. StrAccum acc;
  21123. assert( db!=0 );
  21124. sqlite3StrAccumInit(&acc, db, zBase, sizeof(zBase),
  21125. db->aLimit[SQLITE_LIMIT_LENGTH]);
  21126. sqlite3VXPrintf(&acc, SQLITE_PRINTF_INTERNAL, zFormat, ap);
  21127. z = sqlite3StrAccumFinish(&acc);
  21128. if( acc.accError==STRACCUM_NOMEM ){
  21129. db->mallocFailed = 1;
  21130. }
  21131. return z;
  21132. }
  21133. /*
  21134. ** Print into memory obtained from sqliteMalloc(). Use the internal
  21135. ** %-conversion extensions.
  21136. */
  21137. SQLITE_PRIVATE char *sqlite3MPrintf(sqlite3 *db, const char *zFormat, ...){
  21138. va_list ap;
  21139. char *z;
  21140. va_start(ap, zFormat);
  21141. z = sqlite3VMPrintf(db, zFormat, ap);
  21142. va_end(ap);
  21143. return z;
  21144. }
  21145. /*
  21146. ** Like sqlite3MPrintf(), but call sqlite3DbFree() on zStr after formatting
  21147. ** the string and before returning. This routine is intended to be used
  21148. ** to modify an existing string. For example:
  21149. **
  21150. ** x = sqlite3MPrintf(db, x, "prefix %s suffix", x);
  21151. **
  21152. */
  21153. SQLITE_PRIVATE char *sqlite3MAppendf(sqlite3 *db, char *zStr, const char *zFormat, ...){
  21154. va_list ap;
  21155. char *z;
  21156. va_start(ap, zFormat);
  21157. z = sqlite3VMPrintf(db, zFormat, ap);
  21158. va_end(ap);
  21159. sqlite3DbFree(db, zStr);
  21160. return z;
  21161. }
  21162. /*
  21163. ** Print into memory obtained from sqlite3_malloc(). Omit the internal
  21164. ** %-conversion extensions.
  21165. */
  21166. SQLITE_API char *SQLITE_STDCALL sqlite3_vmprintf(const char *zFormat, va_list ap){
  21167. char *z;
  21168. char zBase[SQLITE_PRINT_BUF_SIZE];
  21169. StrAccum acc;
  21170. #ifdef SQLITE_ENABLE_API_ARMOR
  21171. if( zFormat==0 ){
  21172. (void)SQLITE_MISUSE_BKPT;
  21173. return 0;
  21174. }
  21175. #endif
  21176. #ifndef SQLITE_OMIT_AUTOINIT
  21177. if( sqlite3_initialize() ) return 0;
  21178. #endif
  21179. sqlite3StrAccumInit(&acc, 0, zBase, sizeof(zBase), SQLITE_MAX_LENGTH);
  21180. sqlite3VXPrintf(&acc, 0, zFormat, ap);
  21181. z = sqlite3StrAccumFinish(&acc);
  21182. return z;
  21183. }
  21184. /*
  21185. ** Print into memory obtained from sqlite3_malloc()(). Omit the internal
  21186. ** %-conversion extensions.
  21187. */
  21188. SQLITE_API char *SQLITE_CDECL sqlite3_mprintf(const char *zFormat, ...){
  21189. va_list ap;
  21190. char *z;
  21191. #ifndef SQLITE_OMIT_AUTOINIT
  21192. if( sqlite3_initialize() ) return 0;
  21193. #endif
  21194. va_start(ap, zFormat);
  21195. z = sqlite3_vmprintf(zFormat, ap);
  21196. va_end(ap);
  21197. return z;
  21198. }
  21199. /*
  21200. ** sqlite3_snprintf() works like snprintf() except that it ignores the
  21201. ** current locale settings. This is important for SQLite because we
  21202. ** are not able to use a "," as the decimal point in place of "." as
  21203. ** specified by some locales.
  21204. **
  21205. ** Oops: The first two arguments of sqlite3_snprintf() are backwards
  21206. ** from the snprintf() standard. Unfortunately, it is too late to change
  21207. ** this without breaking compatibility, so we just have to live with the
  21208. ** mistake.
  21209. **
  21210. ** sqlite3_vsnprintf() is the varargs version.
  21211. */
  21212. SQLITE_API char *SQLITE_STDCALL sqlite3_vsnprintf(int n, char *zBuf, const char *zFormat, va_list ap){
  21213. StrAccum acc;
  21214. if( n<=0 ) return zBuf;
  21215. #ifdef SQLITE_ENABLE_API_ARMOR
  21216. if( zBuf==0 || zFormat==0 ) {
  21217. (void)SQLITE_MISUSE_BKPT;
  21218. if( zBuf ) zBuf[0] = 0;
  21219. return zBuf;
  21220. }
  21221. #endif
  21222. sqlite3StrAccumInit(&acc, 0, zBuf, n, 0);
  21223. sqlite3VXPrintf(&acc, 0, zFormat, ap);
  21224. return sqlite3StrAccumFinish(&acc);
  21225. }
  21226. SQLITE_API char *SQLITE_CDECL sqlite3_snprintf(int n, char *zBuf, const char *zFormat, ...){
  21227. char *z;
  21228. va_list ap;
  21229. va_start(ap,zFormat);
  21230. z = sqlite3_vsnprintf(n, zBuf, zFormat, ap);
  21231. va_end(ap);
  21232. return z;
  21233. }
  21234. /*
  21235. ** This is the routine that actually formats the sqlite3_log() message.
  21236. ** We house it in a separate routine from sqlite3_log() to avoid using
  21237. ** stack space on small-stack systems when logging is disabled.
  21238. **
  21239. ** sqlite3_log() must render into a static buffer. It cannot dynamically
  21240. ** allocate memory because it might be called while the memory allocator
  21241. ** mutex is held.
  21242. */
  21243. static void renderLogMsg(int iErrCode, const char *zFormat, va_list ap){
  21244. StrAccum acc; /* String accumulator */
  21245. char zMsg[SQLITE_PRINT_BUF_SIZE*3]; /* Complete log message */
  21246. sqlite3StrAccumInit(&acc, 0, zMsg, sizeof(zMsg), 0);
  21247. sqlite3VXPrintf(&acc, 0, zFormat, ap);
  21248. sqlite3GlobalConfig.xLog(sqlite3GlobalConfig.pLogArg, iErrCode,
  21249. sqlite3StrAccumFinish(&acc));
  21250. }
  21251. /*
  21252. ** Format and write a message to the log if logging is enabled.
  21253. */
  21254. SQLITE_API void SQLITE_CDECL sqlite3_log(int iErrCode, const char *zFormat, ...){
  21255. va_list ap; /* Vararg list */
  21256. if( sqlite3GlobalConfig.xLog ){
  21257. va_start(ap, zFormat);
  21258. renderLogMsg(iErrCode, zFormat, ap);
  21259. va_end(ap);
  21260. }
  21261. }
  21262. #if defined(SQLITE_DEBUG) || defined(SQLITE_HAVE_OS_TRACE)
  21263. /*
  21264. ** A version of printf() that understands %lld. Used for debugging.
  21265. ** The printf() built into some versions of windows does not understand %lld
  21266. ** and segfaults if you give it a long long int.
  21267. */
  21268. SQLITE_PRIVATE void sqlite3DebugPrintf(const char *zFormat, ...){
  21269. va_list ap;
  21270. StrAccum acc;
  21271. char zBuf[500];
  21272. sqlite3StrAccumInit(&acc, 0, zBuf, sizeof(zBuf), 0);
  21273. va_start(ap,zFormat);
  21274. sqlite3VXPrintf(&acc, 0, zFormat, ap);
  21275. va_end(ap);
  21276. sqlite3StrAccumFinish(&acc);
  21277. fprintf(stdout,"%s", zBuf);
  21278. fflush(stdout);
  21279. }
  21280. #endif
  21281. #ifdef SQLITE_DEBUG
  21282. /*************************************************************************
  21283. ** Routines for implementing the "TreeView" display of hierarchical
  21284. ** data structures for debugging.
  21285. **
  21286. ** The main entry points (coded elsewhere) are:
  21287. ** sqlite3TreeViewExpr(0, pExpr, 0);
  21288. ** sqlite3TreeViewExprList(0, pList, 0, 0);
  21289. ** sqlite3TreeViewSelect(0, pSelect, 0);
  21290. ** Insert calls to those routines while debugging in order to display
  21291. ** a diagram of Expr, ExprList, and Select objects.
  21292. **
  21293. */
  21294. /* Add a new subitem to the tree. The moreToFollow flag indicates that this
  21295. ** is not the last item in the tree. */
  21296. SQLITE_PRIVATE TreeView *sqlite3TreeViewPush(TreeView *p, u8 moreToFollow){
  21297. if( p==0 ){
  21298. p = sqlite3_malloc64( sizeof(*p) );
  21299. if( p==0 ) return 0;
  21300. memset(p, 0, sizeof(*p));
  21301. }else{
  21302. p->iLevel++;
  21303. }
  21304. assert( moreToFollow==0 || moreToFollow==1 );
  21305. if( p->iLevel<sizeof(p->bLine) ) p->bLine[p->iLevel] = moreToFollow;
  21306. return p;
  21307. }
  21308. /* Finished with one layer of the tree */
  21309. SQLITE_PRIVATE void sqlite3TreeViewPop(TreeView *p){
  21310. if( p==0 ) return;
  21311. p->iLevel--;
  21312. if( p->iLevel<0 ) sqlite3_free(p);
  21313. }
  21314. /* Generate a single line of output for the tree, with a prefix that contains
  21315. ** all the appropriate tree lines */
  21316. SQLITE_PRIVATE void sqlite3TreeViewLine(TreeView *p, const char *zFormat, ...){
  21317. va_list ap;
  21318. int i;
  21319. StrAccum acc;
  21320. char zBuf[500];
  21321. sqlite3StrAccumInit(&acc, 0, zBuf, sizeof(zBuf), 0);
  21322. if( p ){
  21323. for(i=0; i<p->iLevel && i<sizeof(p->bLine)-1; i++){
  21324. sqlite3StrAccumAppend(&acc, p->bLine[i] ? "| " : " ", 4);
  21325. }
  21326. sqlite3StrAccumAppend(&acc, p->bLine[i] ? "|-- " : "'-- ", 4);
  21327. }
  21328. va_start(ap, zFormat);
  21329. sqlite3VXPrintf(&acc, 0, zFormat, ap);
  21330. va_end(ap);
  21331. if( zBuf[acc.nChar-1]!='\n' ) sqlite3StrAccumAppend(&acc, "\n", 1);
  21332. sqlite3StrAccumFinish(&acc);
  21333. fprintf(stdout,"%s", zBuf);
  21334. fflush(stdout);
  21335. }
  21336. /* Shorthand for starting a new tree item that consists of a single label */
  21337. SQLITE_PRIVATE void sqlite3TreeViewItem(TreeView *p, const char *zLabel, u8 moreToFollow){
  21338. p = sqlite3TreeViewPush(p, moreToFollow);
  21339. sqlite3TreeViewLine(p, "%s", zLabel);
  21340. }
  21341. #endif /* SQLITE_DEBUG */
  21342. /*
  21343. ** variable-argument wrapper around sqlite3VXPrintf().
  21344. */
  21345. SQLITE_PRIVATE void sqlite3XPrintf(StrAccum *p, u32 bFlags, const char *zFormat, ...){
  21346. va_list ap;
  21347. va_start(ap,zFormat);
  21348. sqlite3VXPrintf(p, bFlags, zFormat, ap);
  21349. va_end(ap);
  21350. }
  21351. /************** End of printf.c **********************************************/
  21352. /************** Begin file random.c ******************************************/
  21353. /*
  21354. ** 2001 September 15
  21355. **
  21356. ** The author disclaims copyright to this source code. In place of
  21357. ** a legal notice, here is a blessing:
  21358. **
  21359. ** May you do good and not evil.
  21360. ** May you find forgiveness for yourself and forgive others.
  21361. ** May you share freely, never taking more than you give.
  21362. **
  21363. *************************************************************************
  21364. ** This file contains code to implement a pseudo-random number
  21365. ** generator (PRNG) for SQLite.
  21366. **
  21367. ** Random numbers are used by some of the database backends in order
  21368. ** to generate random integer keys for tables or random filenames.
  21369. */
  21370. /* All threads share a single random number generator.
  21371. ** This structure is the current state of the generator.
  21372. */
  21373. static SQLITE_WSD struct sqlite3PrngType {
  21374. unsigned char isInit; /* True if initialized */
  21375. unsigned char i, j; /* State variables */
  21376. unsigned char s[256]; /* State variables */
  21377. } sqlite3Prng;
  21378. /*
  21379. ** Return N random bytes.
  21380. */
  21381. SQLITE_API void SQLITE_STDCALL sqlite3_randomness(int N, void *pBuf){
  21382. unsigned char t;
  21383. unsigned char *zBuf = pBuf;
  21384. /* The "wsdPrng" macro will resolve to the pseudo-random number generator
  21385. ** state vector. If writable static data is unsupported on the target,
  21386. ** we have to locate the state vector at run-time. In the more common
  21387. ** case where writable static data is supported, wsdPrng can refer directly
  21388. ** to the "sqlite3Prng" state vector declared above.
  21389. */
  21390. #ifdef SQLITE_OMIT_WSD
  21391. struct sqlite3PrngType *p = &GLOBAL(struct sqlite3PrngType, sqlite3Prng);
  21392. # define wsdPrng p[0]
  21393. #else
  21394. # define wsdPrng sqlite3Prng
  21395. #endif
  21396. #if SQLITE_THREADSAFE
  21397. sqlite3_mutex *mutex;
  21398. #endif
  21399. #ifndef SQLITE_OMIT_AUTOINIT
  21400. if( sqlite3_initialize() ) return;
  21401. #endif
  21402. #if SQLITE_THREADSAFE
  21403. mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_PRNG);
  21404. #endif
  21405. sqlite3_mutex_enter(mutex);
  21406. if( N<=0 || pBuf==0 ){
  21407. wsdPrng.isInit = 0;
  21408. sqlite3_mutex_leave(mutex);
  21409. return;
  21410. }
  21411. /* Initialize the state of the random number generator once,
  21412. ** the first time this routine is called. The seed value does
  21413. ** not need to contain a lot of randomness since we are not
  21414. ** trying to do secure encryption or anything like that...
  21415. **
  21416. ** Nothing in this file or anywhere else in SQLite does any kind of
  21417. ** encryption. The RC4 algorithm is being used as a PRNG (pseudo-random
  21418. ** number generator) not as an encryption device.
  21419. */
  21420. if( !wsdPrng.isInit ){
  21421. int i;
  21422. char k[256];
  21423. wsdPrng.j = 0;
  21424. wsdPrng.i = 0;
  21425. sqlite3OsRandomness(sqlite3_vfs_find(0), 256, k);
  21426. for(i=0; i<256; i++){
  21427. wsdPrng.s[i] = (u8)i;
  21428. }
  21429. for(i=0; i<256; i++){
  21430. wsdPrng.j += wsdPrng.s[i] + k[i];
  21431. t = wsdPrng.s[wsdPrng.j];
  21432. wsdPrng.s[wsdPrng.j] = wsdPrng.s[i];
  21433. wsdPrng.s[i] = t;
  21434. }
  21435. wsdPrng.isInit = 1;
  21436. }
  21437. assert( N>0 );
  21438. do{
  21439. wsdPrng.i++;
  21440. t = wsdPrng.s[wsdPrng.i];
  21441. wsdPrng.j += t;
  21442. wsdPrng.s[wsdPrng.i] = wsdPrng.s[wsdPrng.j];
  21443. wsdPrng.s[wsdPrng.j] = t;
  21444. t += wsdPrng.s[wsdPrng.i];
  21445. *(zBuf++) = wsdPrng.s[t];
  21446. }while( --N );
  21447. sqlite3_mutex_leave(mutex);
  21448. }
  21449. #ifndef SQLITE_OMIT_BUILTIN_TEST
  21450. /*
  21451. ** For testing purposes, we sometimes want to preserve the state of
  21452. ** PRNG and restore the PRNG to its saved state at a later time, or
  21453. ** to reset the PRNG to its initial state. These routines accomplish
  21454. ** those tasks.
  21455. **
  21456. ** The sqlite3_test_control() interface calls these routines to
  21457. ** control the PRNG.
  21458. */
  21459. static SQLITE_WSD struct sqlite3PrngType sqlite3SavedPrng;
  21460. SQLITE_PRIVATE void sqlite3PrngSaveState(void){
  21461. memcpy(
  21462. &GLOBAL(struct sqlite3PrngType, sqlite3SavedPrng),
  21463. &GLOBAL(struct sqlite3PrngType, sqlite3Prng),
  21464. sizeof(sqlite3Prng)
  21465. );
  21466. }
  21467. SQLITE_PRIVATE void sqlite3PrngRestoreState(void){
  21468. memcpy(
  21469. &GLOBAL(struct sqlite3PrngType, sqlite3Prng),
  21470. &GLOBAL(struct sqlite3PrngType, sqlite3SavedPrng),
  21471. sizeof(sqlite3Prng)
  21472. );
  21473. }
  21474. #endif /* SQLITE_OMIT_BUILTIN_TEST */
  21475. /************** End of random.c **********************************************/
  21476. /************** Begin file threads.c *****************************************/
  21477. /*
  21478. ** 2012 July 21
  21479. **
  21480. ** The author disclaims copyright to this source code. In place of
  21481. ** a legal notice, here is a blessing:
  21482. **
  21483. ** May you do good and not evil.
  21484. ** May you find forgiveness for yourself and forgive others.
  21485. ** May you share freely, never taking more than you give.
  21486. **
  21487. ******************************************************************************
  21488. **
  21489. ** This file presents a simple cross-platform threading interface for
  21490. ** use internally by SQLite.
  21491. **
  21492. ** A "thread" can be created using sqlite3ThreadCreate(). This thread
  21493. ** runs independently of its creator until it is joined using
  21494. ** sqlite3ThreadJoin(), at which point it terminates.
  21495. **
  21496. ** Threads do not have to be real. It could be that the work of the
  21497. ** "thread" is done by the main thread at either the sqlite3ThreadCreate()
  21498. ** or sqlite3ThreadJoin() call. This is, in fact, what happens in
  21499. ** single threaded systems. Nothing in SQLite requires multiple threads.
  21500. ** This interface exists so that applications that want to take advantage
  21501. ** of multiple cores can do so, while also allowing applications to stay
  21502. ** single-threaded if desired.
  21503. */
  21504. #if SQLITE_OS_WIN
  21505. #endif
  21506. #if SQLITE_MAX_WORKER_THREADS>0
  21507. /********************************* Unix Pthreads ****************************/
  21508. #if SQLITE_OS_UNIX && defined(SQLITE_MUTEX_PTHREADS) && SQLITE_THREADSAFE>0
  21509. #define SQLITE_THREADS_IMPLEMENTED 1 /* Prevent the single-thread code below */
  21510. /* #include <pthread.h> */
  21511. /* A running thread */
  21512. struct SQLiteThread {
  21513. pthread_t tid; /* Thread ID */
  21514. int done; /* Set to true when thread finishes */
  21515. void *pOut; /* Result returned by the thread */
  21516. void *(*xTask)(void*); /* The thread routine */
  21517. void *pIn; /* Argument to the thread */
  21518. };
  21519. /* Create a new thread */
  21520. SQLITE_PRIVATE int sqlite3ThreadCreate(
  21521. SQLiteThread **ppThread, /* OUT: Write the thread object here */
  21522. void *(*xTask)(void*), /* Routine to run in a separate thread */
  21523. void *pIn /* Argument passed into xTask() */
  21524. ){
  21525. SQLiteThread *p;
  21526. int rc;
  21527. assert( ppThread!=0 );
  21528. assert( xTask!=0 );
  21529. /* This routine is never used in single-threaded mode */
  21530. assert( sqlite3GlobalConfig.bCoreMutex!=0 );
  21531. *ppThread = 0;
  21532. p = sqlite3Malloc(sizeof(*p));
  21533. if( p==0 ) return SQLITE_NOMEM;
  21534. memset(p, 0, sizeof(*p));
  21535. p->xTask = xTask;
  21536. p->pIn = pIn;
  21537. if( sqlite3FaultSim(200) ){
  21538. rc = 1;
  21539. }else{
  21540. rc = pthread_create(&p->tid, 0, xTask, pIn);
  21541. }
  21542. if( rc ){
  21543. p->done = 1;
  21544. p->pOut = xTask(pIn);
  21545. }
  21546. *ppThread = p;
  21547. return SQLITE_OK;
  21548. }
  21549. /* Get the results of the thread */
  21550. SQLITE_PRIVATE int sqlite3ThreadJoin(SQLiteThread *p, void **ppOut){
  21551. int rc;
  21552. assert( ppOut!=0 );
  21553. if( NEVER(p==0) ) return SQLITE_NOMEM;
  21554. if( p->done ){
  21555. *ppOut = p->pOut;
  21556. rc = SQLITE_OK;
  21557. }else{
  21558. rc = pthread_join(p->tid, ppOut) ? SQLITE_ERROR : SQLITE_OK;
  21559. }
  21560. sqlite3_free(p);
  21561. return rc;
  21562. }
  21563. #endif /* SQLITE_OS_UNIX && defined(SQLITE_MUTEX_PTHREADS) */
  21564. /******************************** End Unix Pthreads *************************/
  21565. /********************************* Win32 Threads ****************************/
  21566. #if SQLITE_OS_WIN_THREADS
  21567. #define SQLITE_THREADS_IMPLEMENTED 1 /* Prevent the single-thread code below */
  21568. #include <process.h>
  21569. /* A running thread */
  21570. struct SQLiteThread {
  21571. void *tid; /* The thread handle */
  21572. unsigned id; /* The thread identifier */
  21573. void *(*xTask)(void*); /* The routine to run as a thread */
  21574. void *pIn; /* Argument to xTask */
  21575. void *pResult; /* Result of xTask */
  21576. };
  21577. /* Thread procedure Win32 compatibility shim */
  21578. static unsigned __stdcall sqlite3ThreadProc(
  21579. void *pArg /* IN: Pointer to the SQLiteThread structure */
  21580. ){
  21581. SQLiteThread *p = (SQLiteThread *)pArg;
  21582. assert( p!=0 );
  21583. #if 0
  21584. /*
  21585. ** This assert appears to trigger spuriously on certain
  21586. ** versions of Windows, possibly due to _beginthreadex()
  21587. ** and/or CreateThread() not fully setting their thread
  21588. ** ID parameter before starting the thread.
  21589. */
  21590. assert( p->id==GetCurrentThreadId() );
  21591. #endif
  21592. assert( p->xTask!=0 );
  21593. p->pResult = p->xTask(p->pIn);
  21594. _endthreadex(0);
  21595. return 0; /* NOT REACHED */
  21596. }
  21597. /* Create a new thread */
  21598. SQLITE_PRIVATE int sqlite3ThreadCreate(
  21599. SQLiteThread **ppThread, /* OUT: Write the thread object here */
  21600. void *(*xTask)(void*), /* Routine to run in a separate thread */
  21601. void *pIn /* Argument passed into xTask() */
  21602. ){
  21603. SQLiteThread *p;
  21604. assert( ppThread!=0 );
  21605. assert( xTask!=0 );
  21606. *ppThread = 0;
  21607. p = sqlite3Malloc(sizeof(*p));
  21608. if( p==0 ) return SQLITE_NOMEM;
  21609. if( sqlite3GlobalConfig.bCoreMutex==0 ){
  21610. memset(p, 0, sizeof(*p));
  21611. }else{
  21612. p->xTask = xTask;
  21613. p->pIn = pIn;
  21614. p->tid = (void*)_beginthreadex(0, 0, sqlite3ThreadProc, p, 0, &p->id);
  21615. if( p->tid==0 ){
  21616. memset(p, 0, sizeof(*p));
  21617. }
  21618. }
  21619. if( p->xTask==0 ){
  21620. p->id = GetCurrentThreadId();
  21621. p->pResult = xTask(pIn);
  21622. }
  21623. *ppThread = p;
  21624. return SQLITE_OK;
  21625. }
  21626. SQLITE_PRIVATE DWORD sqlite3Win32Wait(HANDLE hObject); /* os_win.c */
  21627. /* Get the results of the thread */
  21628. SQLITE_PRIVATE int sqlite3ThreadJoin(SQLiteThread *p, void **ppOut){
  21629. DWORD rc;
  21630. BOOL bRc;
  21631. assert( ppOut!=0 );
  21632. if( NEVER(p==0) ) return SQLITE_NOMEM;
  21633. if( p->xTask==0 ){
  21634. assert( p->id==GetCurrentThreadId() );
  21635. rc = WAIT_OBJECT_0;
  21636. assert( p->tid==0 );
  21637. }else{
  21638. assert( p->id!=0 && p->id!=GetCurrentThreadId() );
  21639. rc = sqlite3Win32Wait((HANDLE)p->tid);
  21640. assert( rc!=WAIT_IO_COMPLETION );
  21641. bRc = CloseHandle((HANDLE)p->tid);
  21642. assert( bRc );
  21643. }
  21644. if( rc==WAIT_OBJECT_0 ) *ppOut = p->pResult;
  21645. sqlite3_free(p);
  21646. return (rc==WAIT_OBJECT_0) ? SQLITE_OK : SQLITE_ERROR;
  21647. }
  21648. #endif /* SQLITE_OS_WIN_THREADS */
  21649. /******************************** End Win32 Threads *************************/
  21650. /********************************* Single-Threaded **************************/
  21651. #ifndef SQLITE_THREADS_IMPLEMENTED
  21652. /*
  21653. ** This implementation does not actually create a new thread. It does the
  21654. ** work of the thread in the main thread, when either the thread is created
  21655. ** or when it is joined
  21656. */
  21657. /* A running thread */
  21658. struct SQLiteThread {
  21659. void *(*xTask)(void*); /* The routine to run as a thread */
  21660. void *pIn; /* Argument to xTask */
  21661. void *pResult; /* Result of xTask */
  21662. };
  21663. /* Create a new thread */
  21664. SQLITE_PRIVATE int sqlite3ThreadCreate(
  21665. SQLiteThread **ppThread, /* OUT: Write the thread object here */
  21666. void *(*xTask)(void*), /* Routine to run in a separate thread */
  21667. void *pIn /* Argument passed into xTask() */
  21668. ){
  21669. SQLiteThread *p;
  21670. assert( ppThread!=0 );
  21671. assert( xTask!=0 );
  21672. *ppThread = 0;
  21673. p = sqlite3Malloc(sizeof(*p));
  21674. if( p==0 ) return SQLITE_NOMEM;
  21675. if( (SQLITE_PTR_TO_INT(p)/17)&1 ){
  21676. p->xTask = xTask;
  21677. p->pIn = pIn;
  21678. }else{
  21679. p->xTask = 0;
  21680. p->pResult = xTask(pIn);
  21681. }
  21682. *ppThread = p;
  21683. return SQLITE_OK;
  21684. }
  21685. /* Get the results of the thread */
  21686. SQLITE_PRIVATE int sqlite3ThreadJoin(SQLiteThread *p, void **ppOut){
  21687. assert( ppOut!=0 );
  21688. if( NEVER(p==0) ) return SQLITE_NOMEM;
  21689. if( p->xTask ){
  21690. *ppOut = p->xTask(p->pIn);
  21691. }else{
  21692. *ppOut = p->pResult;
  21693. }
  21694. sqlite3_free(p);
  21695. #if defined(SQLITE_TEST)
  21696. {
  21697. void *pTstAlloc = sqlite3Malloc(10);
  21698. if (!pTstAlloc) return SQLITE_NOMEM;
  21699. sqlite3_free(pTstAlloc);
  21700. }
  21701. #endif
  21702. return SQLITE_OK;
  21703. }
  21704. #endif /* !defined(SQLITE_THREADS_IMPLEMENTED) */
  21705. /****************************** End Single-Threaded *************************/
  21706. #endif /* SQLITE_MAX_WORKER_THREADS>0 */
  21707. /************** End of threads.c *********************************************/
  21708. /************** Begin file utf.c *********************************************/
  21709. /*
  21710. ** 2004 April 13
  21711. **
  21712. ** The author disclaims copyright to this source code. In place of
  21713. ** a legal notice, here is a blessing:
  21714. **
  21715. ** May you do good and not evil.
  21716. ** May you find forgiveness for yourself and forgive others.
  21717. ** May you share freely, never taking more than you give.
  21718. **
  21719. *************************************************************************
  21720. ** This file contains routines used to translate between UTF-8,
  21721. ** UTF-16, UTF-16BE, and UTF-16LE.
  21722. **
  21723. ** Notes on UTF-8:
  21724. **
  21725. ** Byte-0 Byte-1 Byte-2 Byte-3 Value
  21726. ** 0xxxxxxx 00000000 00000000 0xxxxxxx
  21727. ** 110yyyyy 10xxxxxx 00000000 00000yyy yyxxxxxx
  21728. ** 1110zzzz 10yyyyyy 10xxxxxx 00000000 zzzzyyyy yyxxxxxx
  21729. ** 11110uuu 10uuzzzz 10yyyyyy 10xxxxxx 000uuuuu zzzzyyyy yyxxxxxx
  21730. **
  21731. **
  21732. ** Notes on UTF-16: (with wwww+1==uuuuu)
  21733. **
  21734. ** Word-0 Word-1 Value
  21735. ** 110110ww wwzzzzyy 110111yy yyxxxxxx 000uuuuu zzzzyyyy yyxxxxxx
  21736. ** zzzzyyyy yyxxxxxx 00000000 zzzzyyyy yyxxxxxx
  21737. **
  21738. **
  21739. ** BOM or Byte Order Mark:
  21740. ** 0xff 0xfe little-endian utf-16 follows
  21741. ** 0xfe 0xff big-endian utf-16 follows
  21742. **
  21743. */
  21744. /* #include <assert.h> */
  21745. #ifndef SQLITE_AMALGAMATION
  21746. /*
  21747. ** The following constant value is used by the SQLITE_BIGENDIAN and
  21748. ** SQLITE_LITTLEENDIAN macros.
  21749. */
  21750. SQLITE_PRIVATE const int sqlite3one = 1;
  21751. #endif /* SQLITE_AMALGAMATION */
  21752. /*
  21753. ** This lookup table is used to help decode the first byte of
  21754. ** a multi-byte UTF8 character.
  21755. */
  21756. static const unsigned char sqlite3Utf8Trans1[] = {
  21757. 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
  21758. 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
  21759. 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
  21760. 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
  21761. 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
  21762. 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
  21763. 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
  21764. 0x00, 0x01, 0x02, 0x03, 0x00, 0x01, 0x00, 0x00,
  21765. };
  21766. #define WRITE_UTF8(zOut, c) { \
  21767. if( c<0x00080 ){ \
  21768. *zOut++ = (u8)(c&0xFF); \
  21769. } \
  21770. else if( c<0x00800 ){ \
  21771. *zOut++ = 0xC0 + (u8)((c>>6)&0x1F); \
  21772. *zOut++ = 0x80 + (u8)(c & 0x3F); \
  21773. } \
  21774. else if( c<0x10000 ){ \
  21775. *zOut++ = 0xE0 + (u8)((c>>12)&0x0F); \
  21776. *zOut++ = 0x80 + (u8)((c>>6) & 0x3F); \
  21777. *zOut++ = 0x80 + (u8)(c & 0x3F); \
  21778. }else{ \
  21779. *zOut++ = 0xF0 + (u8)((c>>18) & 0x07); \
  21780. *zOut++ = 0x80 + (u8)((c>>12) & 0x3F); \
  21781. *zOut++ = 0x80 + (u8)((c>>6) & 0x3F); \
  21782. *zOut++ = 0x80 + (u8)(c & 0x3F); \
  21783. } \
  21784. }
  21785. #define WRITE_UTF16LE(zOut, c) { \
  21786. if( c<=0xFFFF ){ \
  21787. *zOut++ = (u8)(c&0x00FF); \
  21788. *zOut++ = (u8)((c>>8)&0x00FF); \
  21789. }else{ \
  21790. *zOut++ = (u8)(((c>>10)&0x003F) + (((c-0x10000)>>10)&0x00C0)); \
  21791. *zOut++ = (u8)(0x00D8 + (((c-0x10000)>>18)&0x03)); \
  21792. *zOut++ = (u8)(c&0x00FF); \
  21793. *zOut++ = (u8)(0x00DC + ((c>>8)&0x03)); \
  21794. } \
  21795. }
  21796. #define WRITE_UTF16BE(zOut, c) { \
  21797. if( c<=0xFFFF ){ \
  21798. *zOut++ = (u8)((c>>8)&0x00FF); \
  21799. *zOut++ = (u8)(c&0x00FF); \
  21800. }else{ \
  21801. *zOut++ = (u8)(0x00D8 + (((c-0x10000)>>18)&0x03)); \
  21802. *zOut++ = (u8)(((c>>10)&0x003F) + (((c-0x10000)>>10)&0x00C0)); \
  21803. *zOut++ = (u8)(0x00DC + ((c>>8)&0x03)); \
  21804. *zOut++ = (u8)(c&0x00FF); \
  21805. } \
  21806. }
  21807. #define READ_UTF16LE(zIn, TERM, c){ \
  21808. c = (*zIn++); \
  21809. c += ((*zIn++)<<8); \
  21810. if( c>=0xD800 && c<0xE000 && TERM ){ \
  21811. int c2 = (*zIn++); \
  21812. c2 += ((*zIn++)<<8); \
  21813. c = (c2&0x03FF) + ((c&0x003F)<<10) + (((c&0x03C0)+0x0040)<<10); \
  21814. } \
  21815. }
  21816. #define READ_UTF16BE(zIn, TERM, c){ \
  21817. c = ((*zIn++)<<8); \
  21818. c += (*zIn++); \
  21819. if( c>=0xD800 && c<0xE000 && TERM ){ \
  21820. int c2 = ((*zIn++)<<8); \
  21821. c2 += (*zIn++); \
  21822. c = (c2&0x03FF) + ((c&0x003F)<<10) + (((c&0x03C0)+0x0040)<<10); \
  21823. } \
  21824. }
  21825. /*
  21826. ** Translate a single UTF-8 character. Return the unicode value.
  21827. **
  21828. ** During translation, assume that the byte that zTerm points
  21829. ** is a 0x00.
  21830. **
  21831. ** Write a pointer to the next unread byte back into *pzNext.
  21832. **
  21833. ** Notes On Invalid UTF-8:
  21834. **
  21835. ** * This routine never allows a 7-bit character (0x00 through 0x7f) to
  21836. ** be encoded as a multi-byte character. Any multi-byte character that
  21837. ** attempts to encode a value between 0x00 and 0x7f is rendered as 0xfffd.
  21838. **
  21839. ** * This routine never allows a UTF16 surrogate value to be encoded.
  21840. ** If a multi-byte character attempts to encode a value between
  21841. ** 0xd800 and 0xe000 then it is rendered as 0xfffd.
  21842. **
  21843. ** * Bytes in the range of 0x80 through 0xbf which occur as the first
  21844. ** byte of a character are interpreted as single-byte characters
  21845. ** and rendered as themselves even though they are technically
  21846. ** invalid characters.
  21847. **
  21848. ** * This routine accepts over-length UTF8 encodings
  21849. ** for unicode values 0x80 and greater. It does not change over-length
  21850. ** encodings to 0xfffd as some systems recommend.
  21851. */
  21852. #define READ_UTF8(zIn, zTerm, c) \
  21853. c = *(zIn++); \
  21854. if( c>=0xc0 ){ \
  21855. c = sqlite3Utf8Trans1[c-0xc0]; \
  21856. while( zIn!=zTerm && (*zIn & 0xc0)==0x80 ){ \
  21857. c = (c<<6) + (0x3f & *(zIn++)); \
  21858. } \
  21859. if( c<0x80 \
  21860. || (c&0xFFFFF800)==0xD800 \
  21861. || (c&0xFFFFFFFE)==0xFFFE ){ c = 0xFFFD; } \
  21862. }
  21863. SQLITE_PRIVATE u32 sqlite3Utf8Read(
  21864. const unsigned char **pz /* Pointer to string from which to read char */
  21865. ){
  21866. unsigned int c;
  21867. /* Same as READ_UTF8() above but without the zTerm parameter.
  21868. ** For this routine, we assume the UTF8 string is always zero-terminated.
  21869. */
  21870. c = *((*pz)++);
  21871. if( c>=0xc0 ){
  21872. c = sqlite3Utf8Trans1[c-0xc0];
  21873. while( (*(*pz) & 0xc0)==0x80 ){
  21874. c = (c<<6) + (0x3f & *((*pz)++));
  21875. }
  21876. if( c<0x80
  21877. || (c&0xFFFFF800)==0xD800
  21878. || (c&0xFFFFFFFE)==0xFFFE ){ c = 0xFFFD; }
  21879. }
  21880. return c;
  21881. }
  21882. /*
  21883. ** If the TRANSLATE_TRACE macro is defined, the value of each Mem is
  21884. ** printed on stderr on the way into and out of sqlite3VdbeMemTranslate().
  21885. */
  21886. /* #define TRANSLATE_TRACE 1 */
  21887. #ifndef SQLITE_OMIT_UTF16
  21888. /*
  21889. ** This routine transforms the internal text encoding used by pMem to
  21890. ** desiredEnc. It is an error if the string is already of the desired
  21891. ** encoding, or if *pMem does not contain a string value.
  21892. */
  21893. SQLITE_PRIVATE SQLITE_NOINLINE int sqlite3VdbeMemTranslate(Mem *pMem, u8 desiredEnc){
  21894. int len; /* Maximum length of output string in bytes */
  21895. unsigned char *zOut; /* Output buffer */
  21896. unsigned char *zIn; /* Input iterator */
  21897. unsigned char *zTerm; /* End of input */
  21898. unsigned char *z; /* Output iterator */
  21899. unsigned int c;
  21900. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  21901. assert( pMem->flags&MEM_Str );
  21902. assert( pMem->enc!=desiredEnc );
  21903. assert( pMem->enc!=0 );
  21904. assert( pMem->n>=0 );
  21905. #if defined(TRANSLATE_TRACE) && defined(SQLITE_DEBUG)
  21906. {
  21907. char zBuf[100];
  21908. sqlite3VdbeMemPrettyPrint(pMem, zBuf);
  21909. fprintf(stderr, "INPUT: %s\n", zBuf);
  21910. }
  21911. #endif
  21912. /* If the translation is between UTF-16 little and big endian, then
  21913. ** all that is required is to swap the byte order. This case is handled
  21914. ** differently from the others.
  21915. */
  21916. if( pMem->enc!=SQLITE_UTF8 && desiredEnc!=SQLITE_UTF8 ){
  21917. u8 temp;
  21918. int rc;
  21919. rc = sqlite3VdbeMemMakeWriteable(pMem);
  21920. if( rc!=SQLITE_OK ){
  21921. assert( rc==SQLITE_NOMEM );
  21922. return SQLITE_NOMEM;
  21923. }
  21924. zIn = (u8*)pMem->z;
  21925. zTerm = &zIn[pMem->n&~1];
  21926. while( zIn<zTerm ){
  21927. temp = *zIn;
  21928. *zIn = *(zIn+1);
  21929. zIn++;
  21930. *zIn++ = temp;
  21931. }
  21932. pMem->enc = desiredEnc;
  21933. goto translate_out;
  21934. }
  21935. /* Set len to the maximum number of bytes required in the output buffer. */
  21936. if( desiredEnc==SQLITE_UTF8 ){
  21937. /* When converting from UTF-16, the maximum growth results from
  21938. ** translating a 2-byte character to a 4-byte UTF-8 character.
  21939. ** A single byte is required for the output string
  21940. ** nul-terminator.
  21941. */
  21942. pMem->n &= ~1;
  21943. len = pMem->n * 2 + 1;
  21944. }else{
  21945. /* When converting from UTF-8 to UTF-16 the maximum growth is caused
  21946. ** when a 1-byte UTF-8 character is translated into a 2-byte UTF-16
  21947. ** character. Two bytes are required in the output buffer for the
  21948. ** nul-terminator.
  21949. */
  21950. len = pMem->n * 2 + 2;
  21951. }
  21952. /* Set zIn to point at the start of the input buffer and zTerm to point 1
  21953. ** byte past the end.
  21954. **
  21955. ** Variable zOut is set to point at the output buffer, space obtained
  21956. ** from sqlite3_malloc().
  21957. */
  21958. zIn = (u8*)pMem->z;
  21959. zTerm = &zIn[pMem->n];
  21960. zOut = sqlite3DbMallocRaw(pMem->db, len);
  21961. if( !zOut ){
  21962. return SQLITE_NOMEM;
  21963. }
  21964. z = zOut;
  21965. if( pMem->enc==SQLITE_UTF8 ){
  21966. if( desiredEnc==SQLITE_UTF16LE ){
  21967. /* UTF-8 -> UTF-16 Little-endian */
  21968. while( zIn<zTerm ){
  21969. READ_UTF8(zIn, zTerm, c);
  21970. WRITE_UTF16LE(z, c);
  21971. }
  21972. }else{
  21973. assert( desiredEnc==SQLITE_UTF16BE );
  21974. /* UTF-8 -> UTF-16 Big-endian */
  21975. while( zIn<zTerm ){
  21976. READ_UTF8(zIn, zTerm, c);
  21977. WRITE_UTF16BE(z, c);
  21978. }
  21979. }
  21980. pMem->n = (int)(z - zOut);
  21981. *z++ = 0;
  21982. }else{
  21983. assert( desiredEnc==SQLITE_UTF8 );
  21984. if( pMem->enc==SQLITE_UTF16LE ){
  21985. /* UTF-16 Little-endian -> UTF-8 */
  21986. while( zIn<zTerm ){
  21987. READ_UTF16LE(zIn, zIn<zTerm, c);
  21988. WRITE_UTF8(z, c);
  21989. }
  21990. }else{
  21991. /* UTF-16 Big-endian -> UTF-8 */
  21992. while( zIn<zTerm ){
  21993. READ_UTF16BE(zIn, zIn<zTerm, c);
  21994. WRITE_UTF8(z, c);
  21995. }
  21996. }
  21997. pMem->n = (int)(z - zOut);
  21998. }
  21999. *z = 0;
  22000. assert( (pMem->n+(desiredEnc==SQLITE_UTF8?1:2))<=len );
  22001. c = pMem->flags;
  22002. sqlite3VdbeMemRelease(pMem);
  22003. pMem->flags = MEM_Str|MEM_Term|(c&MEM_AffMask);
  22004. pMem->enc = desiredEnc;
  22005. pMem->z = (char*)zOut;
  22006. pMem->zMalloc = pMem->z;
  22007. pMem->szMalloc = sqlite3DbMallocSize(pMem->db, pMem->z);
  22008. translate_out:
  22009. #if defined(TRANSLATE_TRACE) && defined(SQLITE_DEBUG)
  22010. {
  22011. char zBuf[100];
  22012. sqlite3VdbeMemPrettyPrint(pMem, zBuf);
  22013. fprintf(stderr, "OUTPUT: %s\n", zBuf);
  22014. }
  22015. #endif
  22016. return SQLITE_OK;
  22017. }
  22018. /*
  22019. ** This routine checks for a byte-order mark at the beginning of the
  22020. ** UTF-16 string stored in *pMem. If one is present, it is removed and
  22021. ** the encoding of the Mem adjusted. This routine does not do any
  22022. ** byte-swapping, it just sets Mem.enc appropriately.
  22023. **
  22024. ** The allocation (static, dynamic etc.) and encoding of the Mem may be
  22025. ** changed by this function.
  22026. */
  22027. SQLITE_PRIVATE int sqlite3VdbeMemHandleBom(Mem *pMem){
  22028. int rc = SQLITE_OK;
  22029. u8 bom = 0;
  22030. assert( pMem->n>=0 );
  22031. if( pMem->n>1 ){
  22032. u8 b1 = *(u8 *)pMem->z;
  22033. u8 b2 = *(((u8 *)pMem->z) + 1);
  22034. if( b1==0xFE && b2==0xFF ){
  22035. bom = SQLITE_UTF16BE;
  22036. }
  22037. if( b1==0xFF && b2==0xFE ){
  22038. bom = SQLITE_UTF16LE;
  22039. }
  22040. }
  22041. if( bom ){
  22042. rc = sqlite3VdbeMemMakeWriteable(pMem);
  22043. if( rc==SQLITE_OK ){
  22044. pMem->n -= 2;
  22045. memmove(pMem->z, &pMem->z[2], pMem->n);
  22046. pMem->z[pMem->n] = '\0';
  22047. pMem->z[pMem->n+1] = '\0';
  22048. pMem->flags |= MEM_Term;
  22049. pMem->enc = bom;
  22050. }
  22051. }
  22052. return rc;
  22053. }
  22054. #endif /* SQLITE_OMIT_UTF16 */
  22055. /*
  22056. ** pZ is a UTF-8 encoded unicode string. If nByte is less than zero,
  22057. ** return the number of unicode characters in pZ up to (but not including)
  22058. ** the first 0x00 byte. If nByte is not less than zero, return the
  22059. ** number of unicode characters in the first nByte of pZ (or up to
  22060. ** the first 0x00, whichever comes first).
  22061. */
  22062. SQLITE_PRIVATE int sqlite3Utf8CharLen(const char *zIn, int nByte){
  22063. int r = 0;
  22064. const u8 *z = (const u8*)zIn;
  22065. const u8 *zTerm;
  22066. if( nByte>=0 ){
  22067. zTerm = &z[nByte];
  22068. }else{
  22069. zTerm = (const u8*)(-1);
  22070. }
  22071. assert( z<=zTerm );
  22072. while( *z!=0 && z<zTerm ){
  22073. SQLITE_SKIP_UTF8(z);
  22074. r++;
  22075. }
  22076. return r;
  22077. }
  22078. /* This test function is not currently used by the automated test-suite.
  22079. ** Hence it is only available in debug builds.
  22080. */
  22081. #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
  22082. /*
  22083. ** Translate UTF-8 to UTF-8.
  22084. **
  22085. ** This has the effect of making sure that the string is well-formed
  22086. ** UTF-8. Miscoded characters are removed.
  22087. **
  22088. ** The translation is done in-place and aborted if the output
  22089. ** overruns the input.
  22090. */
  22091. SQLITE_PRIVATE int sqlite3Utf8To8(unsigned char *zIn){
  22092. unsigned char *zOut = zIn;
  22093. unsigned char *zStart = zIn;
  22094. u32 c;
  22095. while( zIn[0] && zOut<=zIn ){
  22096. c = sqlite3Utf8Read((const u8**)&zIn);
  22097. if( c!=0xfffd ){
  22098. WRITE_UTF8(zOut, c);
  22099. }
  22100. }
  22101. *zOut = 0;
  22102. return (int)(zOut - zStart);
  22103. }
  22104. #endif
  22105. #ifndef SQLITE_OMIT_UTF16
  22106. /*
  22107. ** Convert a UTF-16 string in the native encoding into a UTF-8 string.
  22108. ** Memory to hold the UTF-8 string is obtained from sqlite3_malloc and must
  22109. ** be freed by the calling function.
  22110. **
  22111. ** NULL is returned if there is an allocation error.
  22112. */
  22113. SQLITE_PRIVATE char *sqlite3Utf16to8(sqlite3 *db, const void *z, int nByte, u8 enc){
  22114. Mem m;
  22115. memset(&m, 0, sizeof(m));
  22116. m.db = db;
  22117. sqlite3VdbeMemSetStr(&m, z, nByte, enc, SQLITE_STATIC);
  22118. sqlite3VdbeChangeEncoding(&m, SQLITE_UTF8);
  22119. if( db->mallocFailed ){
  22120. sqlite3VdbeMemRelease(&m);
  22121. m.z = 0;
  22122. }
  22123. assert( (m.flags & MEM_Term)!=0 || db->mallocFailed );
  22124. assert( (m.flags & MEM_Str)!=0 || db->mallocFailed );
  22125. assert( m.z || db->mallocFailed );
  22126. return m.z;
  22127. }
  22128. /*
  22129. ** zIn is a UTF-16 encoded unicode string at least nChar characters long.
  22130. ** Return the number of bytes in the first nChar unicode characters
  22131. ** in pZ. nChar must be non-negative.
  22132. */
  22133. SQLITE_PRIVATE int sqlite3Utf16ByteLen(const void *zIn, int nChar){
  22134. int c;
  22135. unsigned char const *z = zIn;
  22136. int n = 0;
  22137. if( SQLITE_UTF16NATIVE==SQLITE_UTF16BE ){
  22138. while( n<nChar ){
  22139. READ_UTF16BE(z, 1, c);
  22140. n++;
  22141. }
  22142. }else{
  22143. while( n<nChar ){
  22144. READ_UTF16LE(z, 1, c);
  22145. n++;
  22146. }
  22147. }
  22148. return (int)(z-(unsigned char const *)zIn);
  22149. }
  22150. #if defined(SQLITE_TEST)
  22151. /*
  22152. ** This routine is called from the TCL test function "translate_selftest".
  22153. ** It checks that the primitives for serializing and deserializing
  22154. ** characters in each encoding are inverses of each other.
  22155. */
  22156. SQLITE_PRIVATE void sqlite3UtfSelfTest(void){
  22157. unsigned int i, t;
  22158. unsigned char zBuf[20];
  22159. unsigned char *z;
  22160. int n;
  22161. unsigned int c;
  22162. for(i=0; i<0x00110000; i++){
  22163. z = zBuf;
  22164. WRITE_UTF8(z, i);
  22165. n = (int)(z-zBuf);
  22166. assert( n>0 && n<=4 );
  22167. z[0] = 0;
  22168. z = zBuf;
  22169. c = sqlite3Utf8Read((const u8**)&z);
  22170. t = i;
  22171. if( i>=0xD800 && i<=0xDFFF ) t = 0xFFFD;
  22172. if( (i&0xFFFFFFFE)==0xFFFE ) t = 0xFFFD;
  22173. assert( c==t );
  22174. assert( (z-zBuf)==n );
  22175. }
  22176. for(i=0; i<0x00110000; i++){
  22177. if( i>=0xD800 && i<0xE000 ) continue;
  22178. z = zBuf;
  22179. WRITE_UTF16LE(z, i);
  22180. n = (int)(z-zBuf);
  22181. assert( n>0 && n<=4 );
  22182. z[0] = 0;
  22183. z = zBuf;
  22184. READ_UTF16LE(z, 1, c);
  22185. assert( c==i );
  22186. assert( (z-zBuf)==n );
  22187. }
  22188. for(i=0; i<0x00110000; i++){
  22189. if( i>=0xD800 && i<0xE000 ) continue;
  22190. z = zBuf;
  22191. WRITE_UTF16BE(z, i);
  22192. n = (int)(z-zBuf);
  22193. assert( n>0 && n<=4 );
  22194. z[0] = 0;
  22195. z = zBuf;
  22196. READ_UTF16BE(z, 1, c);
  22197. assert( c==i );
  22198. assert( (z-zBuf)==n );
  22199. }
  22200. }
  22201. #endif /* SQLITE_TEST */
  22202. #endif /* SQLITE_OMIT_UTF16 */
  22203. /************** End of utf.c *************************************************/
  22204. /************** Begin file util.c ********************************************/
  22205. /*
  22206. ** 2001 September 15
  22207. **
  22208. ** The author disclaims copyright to this source code. In place of
  22209. ** a legal notice, here is a blessing:
  22210. **
  22211. ** May you do good and not evil.
  22212. ** May you find forgiveness for yourself and forgive others.
  22213. ** May you share freely, never taking more than you give.
  22214. **
  22215. *************************************************************************
  22216. ** Utility functions used throughout sqlite.
  22217. **
  22218. ** This file contains functions for allocating memory, comparing
  22219. ** strings, and stuff like that.
  22220. **
  22221. */
  22222. /* #include <stdarg.h> */
  22223. #if HAVE_ISNAN || SQLITE_HAVE_ISNAN
  22224. # include <math.h>
  22225. #endif
  22226. /*
  22227. ** Routine needed to support the testcase() macro.
  22228. */
  22229. #ifdef SQLITE_COVERAGE_TEST
  22230. SQLITE_PRIVATE void sqlite3Coverage(int x){
  22231. static unsigned dummy = 0;
  22232. dummy += (unsigned)x;
  22233. }
  22234. #endif
  22235. /*
  22236. ** Give a callback to the test harness that can be used to simulate faults
  22237. ** in places where it is difficult or expensive to do so purely by means
  22238. ** of inputs.
  22239. **
  22240. ** The intent of the integer argument is to let the fault simulator know
  22241. ** which of multiple sqlite3FaultSim() calls has been hit.
  22242. **
  22243. ** Return whatever integer value the test callback returns, or return
  22244. ** SQLITE_OK if no test callback is installed.
  22245. */
  22246. #ifndef SQLITE_OMIT_BUILTIN_TEST
  22247. SQLITE_PRIVATE int sqlite3FaultSim(int iTest){
  22248. int (*xCallback)(int) = sqlite3GlobalConfig.xTestCallback;
  22249. return xCallback ? xCallback(iTest) : SQLITE_OK;
  22250. }
  22251. #endif
  22252. #ifndef SQLITE_OMIT_FLOATING_POINT
  22253. /*
  22254. ** Return true if the floating point value is Not a Number (NaN).
  22255. **
  22256. ** Use the math library isnan() function if compiled with SQLITE_HAVE_ISNAN.
  22257. ** Otherwise, we have our own implementation that works on most systems.
  22258. */
  22259. SQLITE_PRIVATE int sqlite3IsNaN(double x){
  22260. int rc; /* The value return */
  22261. #if !SQLITE_HAVE_ISNAN && !HAVE_ISNAN
  22262. /*
  22263. ** Systems that support the isnan() library function should probably
  22264. ** make use of it by compiling with -DSQLITE_HAVE_ISNAN. But we have
  22265. ** found that many systems do not have a working isnan() function so
  22266. ** this implementation is provided as an alternative.
  22267. **
  22268. ** This NaN test sometimes fails if compiled on GCC with -ffast-math.
  22269. ** On the other hand, the use of -ffast-math comes with the following
  22270. ** warning:
  22271. **
  22272. ** This option [-ffast-math] should never be turned on by any
  22273. ** -O option since it can result in incorrect output for programs
  22274. ** which depend on an exact implementation of IEEE or ISO
  22275. ** rules/specifications for math functions.
  22276. **
  22277. ** Under MSVC, this NaN test may fail if compiled with a floating-
  22278. ** point precision mode other than /fp:precise. From the MSDN
  22279. ** documentation:
  22280. **
  22281. ** The compiler [with /fp:precise] will properly handle comparisons
  22282. ** involving NaN. For example, x != x evaluates to true if x is NaN
  22283. ** ...
  22284. */
  22285. #ifdef __FAST_MATH__
  22286. # error SQLite will not work correctly with the -ffast-math option of GCC.
  22287. #endif
  22288. volatile double y = x;
  22289. volatile double z = y;
  22290. rc = (y!=z);
  22291. #else /* if HAVE_ISNAN */
  22292. rc = isnan(x);
  22293. #endif /* HAVE_ISNAN */
  22294. testcase( rc );
  22295. return rc;
  22296. }
  22297. #endif /* SQLITE_OMIT_FLOATING_POINT */
  22298. /*
  22299. ** Compute a string length that is limited to what can be stored in
  22300. ** lower 30 bits of a 32-bit signed integer.
  22301. **
  22302. ** The value returned will never be negative. Nor will it ever be greater
  22303. ** than the actual length of the string. For very long strings (greater
  22304. ** than 1GiB) the value returned might be less than the true string length.
  22305. */
  22306. SQLITE_PRIVATE int sqlite3Strlen30(const char *z){
  22307. const char *z2 = z;
  22308. if( z==0 ) return 0;
  22309. while( *z2 ){ z2++; }
  22310. return 0x3fffffff & (int)(z2 - z);
  22311. }
  22312. /*
  22313. ** Set the current error code to err_code and clear any prior error message.
  22314. */
  22315. SQLITE_PRIVATE void sqlite3Error(sqlite3 *db, int err_code){
  22316. assert( db!=0 );
  22317. db->errCode = err_code;
  22318. if( db->pErr ) sqlite3ValueSetNull(db->pErr);
  22319. }
  22320. /*
  22321. ** Set the most recent error code and error string for the sqlite
  22322. ** handle "db". The error code is set to "err_code".
  22323. **
  22324. ** If it is not NULL, string zFormat specifies the format of the
  22325. ** error string in the style of the printf functions: The following
  22326. ** format characters are allowed:
  22327. **
  22328. ** %s Insert a string
  22329. ** %z A string that should be freed after use
  22330. ** %d Insert an integer
  22331. ** %T Insert a token
  22332. ** %S Insert the first element of a SrcList
  22333. **
  22334. ** zFormat and any string tokens that follow it are assumed to be
  22335. ** encoded in UTF-8.
  22336. **
  22337. ** To clear the most recent error for sqlite handle "db", sqlite3Error
  22338. ** should be called with err_code set to SQLITE_OK and zFormat set
  22339. ** to NULL.
  22340. */
  22341. SQLITE_PRIVATE void sqlite3ErrorWithMsg(sqlite3 *db, int err_code, const char *zFormat, ...){
  22342. assert( db!=0 );
  22343. db->errCode = err_code;
  22344. if( zFormat==0 ){
  22345. sqlite3Error(db, err_code);
  22346. }else if( db->pErr || (db->pErr = sqlite3ValueNew(db))!=0 ){
  22347. char *z;
  22348. va_list ap;
  22349. va_start(ap, zFormat);
  22350. z = sqlite3VMPrintf(db, zFormat, ap);
  22351. va_end(ap);
  22352. sqlite3ValueSetStr(db->pErr, -1, z, SQLITE_UTF8, SQLITE_DYNAMIC);
  22353. }
  22354. }
  22355. /*
  22356. ** Add an error message to pParse->zErrMsg and increment pParse->nErr.
  22357. ** The following formatting characters are allowed:
  22358. **
  22359. ** %s Insert a string
  22360. ** %z A string that should be freed after use
  22361. ** %d Insert an integer
  22362. ** %T Insert a token
  22363. ** %S Insert the first element of a SrcList
  22364. **
  22365. ** This function should be used to report any error that occurs while
  22366. ** compiling an SQL statement (i.e. within sqlite3_prepare()). The
  22367. ** last thing the sqlite3_prepare() function does is copy the error
  22368. ** stored by this function into the database handle using sqlite3Error().
  22369. ** Functions sqlite3Error() or sqlite3ErrorWithMsg() should be used
  22370. ** during statement execution (sqlite3_step() etc.).
  22371. */
  22372. SQLITE_PRIVATE void sqlite3ErrorMsg(Parse *pParse, const char *zFormat, ...){
  22373. char *zMsg;
  22374. va_list ap;
  22375. sqlite3 *db = pParse->db;
  22376. va_start(ap, zFormat);
  22377. zMsg = sqlite3VMPrintf(db, zFormat, ap);
  22378. va_end(ap);
  22379. if( db->suppressErr ){
  22380. sqlite3DbFree(db, zMsg);
  22381. }else{
  22382. pParse->nErr++;
  22383. sqlite3DbFree(db, pParse->zErrMsg);
  22384. pParse->zErrMsg = zMsg;
  22385. pParse->rc = SQLITE_ERROR;
  22386. }
  22387. }
  22388. /*
  22389. ** Convert an SQL-style quoted string into a normal string by removing
  22390. ** the quote characters. The conversion is done in-place. If the
  22391. ** input does not begin with a quote character, then this routine
  22392. ** is a no-op.
  22393. **
  22394. ** The input string must be zero-terminated. A new zero-terminator
  22395. ** is added to the dequoted string.
  22396. **
  22397. ** The return value is -1 if no dequoting occurs or the length of the
  22398. ** dequoted string, exclusive of the zero terminator, if dequoting does
  22399. ** occur.
  22400. **
  22401. ** 2002-Feb-14: This routine is extended to remove MS-Access style
  22402. ** brackets from around identifiers. For example: "[a-b-c]" becomes
  22403. ** "a-b-c".
  22404. */
  22405. SQLITE_PRIVATE int sqlite3Dequote(char *z){
  22406. char quote;
  22407. int i, j;
  22408. if( z==0 ) return -1;
  22409. quote = z[0];
  22410. switch( quote ){
  22411. case '\'': break;
  22412. case '"': break;
  22413. case '`': break; /* For MySQL compatibility */
  22414. case '[': quote = ']'; break; /* For MS SqlServer compatibility */
  22415. default: return -1;
  22416. }
  22417. for(i=1, j=0;; i++){
  22418. assert( z[i] );
  22419. if( z[i]==quote ){
  22420. if( z[i+1]==quote ){
  22421. z[j++] = quote;
  22422. i++;
  22423. }else{
  22424. break;
  22425. }
  22426. }else{
  22427. z[j++] = z[i];
  22428. }
  22429. }
  22430. z[j] = 0;
  22431. return j;
  22432. }
  22433. /* Convenient short-hand */
  22434. #define UpperToLower sqlite3UpperToLower
  22435. /*
  22436. ** Some systems have stricmp(). Others have strcasecmp(). Because
  22437. ** there is no consistency, we will define our own.
  22438. **
  22439. ** IMPLEMENTATION-OF: R-30243-02494 The sqlite3_stricmp() and
  22440. ** sqlite3_strnicmp() APIs allow applications and extensions to compare
  22441. ** the contents of two buffers containing UTF-8 strings in a
  22442. ** case-independent fashion, using the same definition of "case
  22443. ** independence" that SQLite uses internally when comparing identifiers.
  22444. */
  22445. SQLITE_API int SQLITE_STDCALL sqlite3_stricmp(const char *zLeft, const char *zRight){
  22446. register unsigned char *a, *b;
  22447. if( zLeft==0 ){
  22448. return zRight ? -1 : 0;
  22449. }else if( zRight==0 ){
  22450. return 1;
  22451. }
  22452. a = (unsigned char *)zLeft;
  22453. b = (unsigned char *)zRight;
  22454. while( *a!=0 && UpperToLower[*a]==UpperToLower[*b]){ a++; b++; }
  22455. return UpperToLower[*a] - UpperToLower[*b];
  22456. }
  22457. SQLITE_API int SQLITE_STDCALL sqlite3_strnicmp(const char *zLeft, const char *zRight, int N){
  22458. register unsigned char *a, *b;
  22459. if( zLeft==0 ){
  22460. return zRight ? -1 : 0;
  22461. }else if( zRight==0 ){
  22462. return 1;
  22463. }
  22464. a = (unsigned char *)zLeft;
  22465. b = (unsigned char *)zRight;
  22466. while( N-- > 0 && *a!=0 && UpperToLower[*a]==UpperToLower[*b]){ a++; b++; }
  22467. return N<0 ? 0 : UpperToLower[*a] - UpperToLower[*b];
  22468. }
  22469. /*
  22470. ** The string z[] is an text representation of a real number.
  22471. ** Convert this string to a double and write it into *pResult.
  22472. **
  22473. ** The string z[] is length bytes in length (bytes, not characters) and
  22474. ** uses the encoding enc. The string is not necessarily zero-terminated.
  22475. **
  22476. ** Return TRUE if the result is a valid real number (or integer) and FALSE
  22477. ** if the string is empty or contains extraneous text. Valid numbers
  22478. ** are in one of these formats:
  22479. **
  22480. ** [+-]digits[E[+-]digits]
  22481. ** [+-]digits.[digits][E[+-]digits]
  22482. ** [+-].digits[E[+-]digits]
  22483. **
  22484. ** Leading and trailing whitespace is ignored for the purpose of determining
  22485. ** validity.
  22486. **
  22487. ** If some prefix of the input string is a valid number, this routine
  22488. ** returns FALSE but it still converts the prefix and writes the result
  22489. ** into *pResult.
  22490. */
  22491. SQLITE_PRIVATE int sqlite3AtoF(const char *z, double *pResult, int length, u8 enc){
  22492. #ifndef SQLITE_OMIT_FLOATING_POINT
  22493. int incr;
  22494. const char *zEnd = z + length;
  22495. /* sign * significand * (10 ^ (esign * exponent)) */
  22496. int sign = 1; /* sign of significand */
  22497. i64 s = 0; /* significand */
  22498. int d = 0; /* adjust exponent for shifting decimal point */
  22499. int esign = 1; /* sign of exponent */
  22500. int e = 0; /* exponent */
  22501. int eValid = 1; /* True exponent is either not used or is well-formed */
  22502. double result;
  22503. int nDigits = 0;
  22504. int nonNum = 0;
  22505. assert( enc==SQLITE_UTF8 || enc==SQLITE_UTF16LE || enc==SQLITE_UTF16BE );
  22506. *pResult = 0.0; /* Default return value, in case of an error */
  22507. if( enc==SQLITE_UTF8 ){
  22508. incr = 1;
  22509. }else{
  22510. int i;
  22511. incr = 2;
  22512. assert( SQLITE_UTF16LE==2 && SQLITE_UTF16BE==3 );
  22513. for(i=3-enc; i<length && z[i]==0; i+=2){}
  22514. nonNum = i<length;
  22515. zEnd = z+i+enc-3;
  22516. z += (enc&1);
  22517. }
  22518. /* skip leading spaces */
  22519. while( z<zEnd && sqlite3Isspace(*z) ) z+=incr;
  22520. if( z>=zEnd ) return 0;
  22521. /* get sign of significand */
  22522. if( *z=='-' ){
  22523. sign = -1;
  22524. z+=incr;
  22525. }else if( *z=='+' ){
  22526. z+=incr;
  22527. }
  22528. /* skip leading zeroes */
  22529. while( z<zEnd && z[0]=='0' ) z+=incr, nDigits++;
  22530. /* copy max significant digits to significand */
  22531. while( z<zEnd && sqlite3Isdigit(*z) && s<((LARGEST_INT64-9)/10) ){
  22532. s = s*10 + (*z - '0');
  22533. z+=incr, nDigits++;
  22534. }
  22535. /* skip non-significant significand digits
  22536. ** (increase exponent by d to shift decimal left) */
  22537. while( z<zEnd && sqlite3Isdigit(*z) ) z+=incr, nDigits++, d++;
  22538. if( z>=zEnd ) goto do_atof_calc;
  22539. /* if decimal point is present */
  22540. if( *z=='.' ){
  22541. z+=incr;
  22542. /* copy digits from after decimal to significand
  22543. ** (decrease exponent by d to shift decimal right) */
  22544. while( z<zEnd && sqlite3Isdigit(*z) && s<((LARGEST_INT64-9)/10) ){
  22545. s = s*10 + (*z - '0');
  22546. z+=incr, nDigits++, d--;
  22547. }
  22548. /* skip non-significant digits */
  22549. while( z<zEnd && sqlite3Isdigit(*z) ) z+=incr, nDigits++;
  22550. }
  22551. if( z>=zEnd ) goto do_atof_calc;
  22552. /* if exponent is present */
  22553. if( *z=='e' || *z=='E' ){
  22554. z+=incr;
  22555. eValid = 0;
  22556. if( z>=zEnd ) goto do_atof_calc;
  22557. /* get sign of exponent */
  22558. if( *z=='-' ){
  22559. esign = -1;
  22560. z+=incr;
  22561. }else if( *z=='+' ){
  22562. z+=incr;
  22563. }
  22564. /* copy digits to exponent */
  22565. while( z<zEnd && sqlite3Isdigit(*z) ){
  22566. e = e<10000 ? (e*10 + (*z - '0')) : 10000;
  22567. z+=incr;
  22568. eValid = 1;
  22569. }
  22570. }
  22571. /* skip trailing spaces */
  22572. if( nDigits && eValid ){
  22573. while( z<zEnd && sqlite3Isspace(*z) ) z+=incr;
  22574. }
  22575. do_atof_calc:
  22576. /* adjust exponent by d, and update sign */
  22577. e = (e*esign) + d;
  22578. if( e<0 ) {
  22579. esign = -1;
  22580. e *= -1;
  22581. } else {
  22582. esign = 1;
  22583. }
  22584. /* if 0 significand */
  22585. if( !s ) {
  22586. /* In the IEEE 754 standard, zero is signed.
  22587. ** Add the sign if we've seen at least one digit */
  22588. result = (sign<0 && nDigits) ? -(double)0 : (double)0;
  22589. } else {
  22590. /* attempt to reduce exponent */
  22591. if( esign>0 ){
  22592. while( s<(LARGEST_INT64/10) && e>0 ) e--,s*=10;
  22593. }else{
  22594. while( !(s%10) && e>0 ) e--,s/=10;
  22595. }
  22596. /* adjust the sign of significand */
  22597. s = sign<0 ? -s : s;
  22598. /* if exponent, scale significand as appropriate
  22599. ** and store in result. */
  22600. if( e ){
  22601. LONGDOUBLE_TYPE scale = 1.0;
  22602. /* attempt to handle extremely small/large numbers better */
  22603. if( e>307 && e<342 ){
  22604. while( e%308 ) { scale *= 1.0e+1; e -= 1; }
  22605. if( esign<0 ){
  22606. result = s / scale;
  22607. result /= 1.0e+308;
  22608. }else{
  22609. result = s * scale;
  22610. result *= 1.0e+308;
  22611. }
  22612. }else if( e>=342 ){
  22613. if( esign<0 ){
  22614. result = 0.0*s;
  22615. }else{
  22616. result = 1e308*1e308*s; /* Infinity */
  22617. }
  22618. }else{
  22619. /* 1.0e+22 is the largest power of 10 than can be
  22620. ** represented exactly. */
  22621. while( e%22 ) { scale *= 1.0e+1; e -= 1; }
  22622. while( e>0 ) { scale *= 1.0e+22; e -= 22; }
  22623. if( esign<0 ){
  22624. result = s / scale;
  22625. }else{
  22626. result = s * scale;
  22627. }
  22628. }
  22629. } else {
  22630. result = (double)s;
  22631. }
  22632. }
  22633. /* store the result */
  22634. *pResult = result;
  22635. /* return true if number and no extra non-whitespace chracters after */
  22636. return z>=zEnd && nDigits>0 && eValid && nonNum==0;
  22637. #else
  22638. return !sqlite3Atoi64(z, pResult, length, enc);
  22639. #endif /* SQLITE_OMIT_FLOATING_POINT */
  22640. }
  22641. /*
  22642. ** Compare the 19-character string zNum against the text representation
  22643. ** value 2^63: 9223372036854775808. Return negative, zero, or positive
  22644. ** if zNum is less than, equal to, or greater than the string.
  22645. ** Note that zNum must contain exactly 19 characters.
  22646. **
  22647. ** Unlike memcmp() this routine is guaranteed to return the difference
  22648. ** in the values of the last digit if the only difference is in the
  22649. ** last digit. So, for example,
  22650. **
  22651. ** compare2pow63("9223372036854775800", 1)
  22652. **
  22653. ** will return -8.
  22654. */
  22655. static int compare2pow63(const char *zNum, int incr){
  22656. int c = 0;
  22657. int i;
  22658. /* 012345678901234567 */
  22659. const char *pow63 = "922337203685477580";
  22660. for(i=0; c==0 && i<18; i++){
  22661. c = (zNum[i*incr]-pow63[i])*10;
  22662. }
  22663. if( c==0 ){
  22664. c = zNum[18*incr] - '8';
  22665. testcase( c==(-1) );
  22666. testcase( c==0 );
  22667. testcase( c==(+1) );
  22668. }
  22669. return c;
  22670. }
  22671. /*
  22672. ** Convert zNum to a 64-bit signed integer. zNum must be decimal. This
  22673. ** routine does *not* accept hexadecimal notation.
  22674. **
  22675. ** If the zNum value is representable as a 64-bit twos-complement
  22676. ** integer, then write that value into *pNum and return 0.
  22677. **
  22678. ** If zNum is exactly 9223372036854775808, return 2. This special
  22679. ** case is broken out because while 9223372036854775808 cannot be a
  22680. ** signed 64-bit integer, its negative -9223372036854775808 can be.
  22681. **
  22682. ** If zNum is too big for a 64-bit integer and is not
  22683. ** 9223372036854775808 or if zNum contains any non-numeric text,
  22684. ** then return 1.
  22685. **
  22686. ** length is the number of bytes in the string (bytes, not characters).
  22687. ** The string is not necessarily zero-terminated. The encoding is
  22688. ** given by enc.
  22689. */
  22690. SQLITE_PRIVATE int sqlite3Atoi64(const char *zNum, i64 *pNum, int length, u8 enc){
  22691. int incr;
  22692. u64 u = 0;
  22693. int neg = 0; /* assume positive */
  22694. int i;
  22695. int c = 0;
  22696. int nonNum = 0;
  22697. const char *zStart;
  22698. const char *zEnd = zNum + length;
  22699. assert( enc==SQLITE_UTF8 || enc==SQLITE_UTF16LE || enc==SQLITE_UTF16BE );
  22700. if( enc==SQLITE_UTF8 ){
  22701. incr = 1;
  22702. }else{
  22703. incr = 2;
  22704. assert( SQLITE_UTF16LE==2 && SQLITE_UTF16BE==3 );
  22705. for(i=3-enc; i<length && zNum[i]==0; i+=2){}
  22706. nonNum = i<length;
  22707. zEnd = zNum+i+enc-3;
  22708. zNum += (enc&1);
  22709. }
  22710. while( zNum<zEnd && sqlite3Isspace(*zNum) ) zNum+=incr;
  22711. if( zNum<zEnd ){
  22712. if( *zNum=='-' ){
  22713. neg = 1;
  22714. zNum+=incr;
  22715. }else if( *zNum=='+' ){
  22716. zNum+=incr;
  22717. }
  22718. }
  22719. zStart = zNum;
  22720. while( zNum<zEnd && zNum[0]=='0' ){ zNum+=incr; } /* Skip leading zeros. */
  22721. for(i=0; &zNum[i]<zEnd && (c=zNum[i])>='0' && c<='9'; i+=incr){
  22722. u = u*10 + c - '0';
  22723. }
  22724. if( u>LARGEST_INT64 ){
  22725. *pNum = neg ? SMALLEST_INT64 : LARGEST_INT64;
  22726. }else if( neg ){
  22727. *pNum = -(i64)u;
  22728. }else{
  22729. *pNum = (i64)u;
  22730. }
  22731. testcase( i==18 );
  22732. testcase( i==19 );
  22733. testcase( i==20 );
  22734. if( (c!=0 && &zNum[i]<zEnd) || (i==0 && zStart==zNum) || i>19*incr || nonNum ){
  22735. /* zNum is empty or contains non-numeric text or is longer
  22736. ** than 19 digits (thus guaranteeing that it is too large) */
  22737. return 1;
  22738. }else if( i<19*incr ){
  22739. /* Less than 19 digits, so we know that it fits in 64 bits */
  22740. assert( u<=LARGEST_INT64 );
  22741. return 0;
  22742. }else{
  22743. /* zNum is a 19-digit numbers. Compare it against 9223372036854775808. */
  22744. c = compare2pow63(zNum, incr);
  22745. if( c<0 ){
  22746. /* zNum is less than 9223372036854775808 so it fits */
  22747. assert( u<=LARGEST_INT64 );
  22748. return 0;
  22749. }else if( c>0 ){
  22750. /* zNum is greater than 9223372036854775808 so it overflows */
  22751. return 1;
  22752. }else{
  22753. /* zNum is exactly 9223372036854775808. Fits if negative. The
  22754. ** special case 2 overflow if positive */
  22755. assert( u-1==LARGEST_INT64 );
  22756. return neg ? 0 : 2;
  22757. }
  22758. }
  22759. }
  22760. /*
  22761. ** Transform a UTF-8 integer literal, in either decimal or hexadecimal,
  22762. ** into a 64-bit signed integer. This routine accepts hexadecimal literals,
  22763. ** whereas sqlite3Atoi64() does not.
  22764. **
  22765. ** Returns:
  22766. **
  22767. ** 0 Successful transformation. Fits in a 64-bit signed integer.
  22768. ** 1 Integer too large for a 64-bit signed integer or is malformed
  22769. ** 2 Special case of 9223372036854775808
  22770. */
  22771. SQLITE_PRIVATE int sqlite3DecOrHexToI64(const char *z, i64 *pOut){
  22772. #ifndef SQLITE_OMIT_HEX_INTEGER
  22773. if( z[0]=='0'
  22774. && (z[1]=='x' || z[1]=='X')
  22775. && sqlite3Isxdigit(z[2])
  22776. ){
  22777. u64 u = 0;
  22778. int i, k;
  22779. for(i=2; z[i]=='0'; i++){}
  22780. for(k=i; sqlite3Isxdigit(z[k]); k++){
  22781. u = u*16 + sqlite3HexToInt(z[k]);
  22782. }
  22783. memcpy(pOut, &u, 8);
  22784. return (z[k]==0 && k-i<=16) ? 0 : 1;
  22785. }else
  22786. #endif /* SQLITE_OMIT_HEX_INTEGER */
  22787. {
  22788. return sqlite3Atoi64(z, pOut, sqlite3Strlen30(z), SQLITE_UTF8);
  22789. }
  22790. }
  22791. /*
  22792. ** If zNum represents an integer that will fit in 32-bits, then set
  22793. ** *pValue to that integer and return true. Otherwise return false.
  22794. **
  22795. ** This routine accepts both decimal and hexadecimal notation for integers.
  22796. **
  22797. ** Any non-numeric characters that following zNum are ignored.
  22798. ** This is different from sqlite3Atoi64() which requires the
  22799. ** input number to be zero-terminated.
  22800. */
  22801. SQLITE_PRIVATE int sqlite3GetInt32(const char *zNum, int *pValue){
  22802. sqlite_int64 v = 0;
  22803. int i, c;
  22804. int neg = 0;
  22805. if( zNum[0]=='-' ){
  22806. neg = 1;
  22807. zNum++;
  22808. }else if( zNum[0]=='+' ){
  22809. zNum++;
  22810. }
  22811. #ifndef SQLITE_OMIT_HEX_INTEGER
  22812. else if( zNum[0]=='0'
  22813. && (zNum[1]=='x' || zNum[1]=='X')
  22814. && sqlite3Isxdigit(zNum[2])
  22815. ){
  22816. u32 u = 0;
  22817. zNum += 2;
  22818. while( zNum[0]=='0' ) zNum++;
  22819. for(i=0; sqlite3Isxdigit(zNum[i]) && i<8; i++){
  22820. u = u*16 + sqlite3HexToInt(zNum[i]);
  22821. }
  22822. if( (u&0x80000000)==0 && sqlite3Isxdigit(zNum[i])==0 ){
  22823. memcpy(pValue, &u, 4);
  22824. return 1;
  22825. }else{
  22826. return 0;
  22827. }
  22828. }
  22829. #endif
  22830. while( zNum[0]=='0' ) zNum++;
  22831. for(i=0; i<11 && (c = zNum[i] - '0')>=0 && c<=9; i++){
  22832. v = v*10 + c;
  22833. }
  22834. /* The longest decimal representation of a 32 bit integer is 10 digits:
  22835. **
  22836. ** 1234567890
  22837. ** 2^31 -> 2147483648
  22838. */
  22839. testcase( i==10 );
  22840. if( i>10 ){
  22841. return 0;
  22842. }
  22843. testcase( v-neg==2147483647 );
  22844. if( v-neg>2147483647 ){
  22845. return 0;
  22846. }
  22847. if( neg ){
  22848. v = -v;
  22849. }
  22850. *pValue = (int)v;
  22851. return 1;
  22852. }
  22853. /*
  22854. ** Return a 32-bit integer value extracted from a string. If the
  22855. ** string is not an integer, just return 0.
  22856. */
  22857. SQLITE_PRIVATE int sqlite3Atoi(const char *z){
  22858. int x = 0;
  22859. if( z ) sqlite3GetInt32(z, &x);
  22860. return x;
  22861. }
  22862. /*
  22863. ** The variable-length integer encoding is as follows:
  22864. **
  22865. ** KEY:
  22866. ** A = 0xxxxxxx 7 bits of data and one flag bit
  22867. ** B = 1xxxxxxx 7 bits of data and one flag bit
  22868. ** C = xxxxxxxx 8 bits of data
  22869. **
  22870. ** 7 bits - A
  22871. ** 14 bits - BA
  22872. ** 21 bits - BBA
  22873. ** 28 bits - BBBA
  22874. ** 35 bits - BBBBA
  22875. ** 42 bits - BBBBBA
  22876. ** 49 bits - BBBBBBA
  22877. ** 56 bits - BBBBBBBA
  22878. ** 64 bits - BBBBBBBBC
  22879. */
  22880. /*
  22881. ** Write a 64-bit variable-length integer to memory starting at p[0].
  22882. ** The length of data write will be between 1 and 9 bytes. The number
  22883. ** of bytes written is returned.
  22884. **
  22885. ** A variable-length integer consists of the lower 7 bits of each byte
  22886. ** for all bytes that have the 8th bit set and one byte with the 8th
  22887. ** bit clear. Except, if we get to the 9th byte, it stores the full
  22888. ** 8 bits and is the last byte.
  22889. */
  22890. static int SQLITE_NOINLINE putVarint64(unsigned char *p, u64 v){
  22891. int i, j, n;
  22892. u8 buf[10];
  22893. if( v & (((u64)0xff000000)<<32) ){
  22894. p[8] = (u8)v;
  22895. v >>= 8;
  22896. for(i=7; i>=0; i--){
  22897. p[i] = (u8)((v & 0x7f) | 0x80);
  22898. v >>= 7;
  22899. }
  22900. return 9;
  22901. }
  22902. n = 0;
  22903. do{
  22904. buf[n++] = (u8)((v & 0x7f) | 0x80);
  22905. v >>= 7;
  22906. }while( v!=0 );
  22907. buf[0] &= 0x7f;
  22908. assert( n<=9 );
  22909. for(i=0, j=n-1; j>=0; j--, i++){
  22910. p[i] = buf[j];
  22911. }
  22912. return n;
  22913. }
  22914. SQLITE_PRIVATE int sqlite3PutVarint(unsigned char *p, u64 v){
  22915. if( v<=0x7f ){
  22916. p[0] = v&0x7f;
  22917. return 1;
  22918. }
  22919. if( v<=0x3fff ){
  22920. p[0] = ((v>>7)&0x7f)|0x80;
  22921. p[1] = v&0x7f;
  22922. return 2;
  22923. }
  22924. return putVarint64(p,v);
  22925. }
  22926. /*
  22927. ** Bitmasks used by sqlite3GetVarint(). These precomputed constants
  22928. ** are defined here rather than simply putting the constant expressions
  22929. ** inline in order to work around bugs in the RVT compiler.
  22930. **
  22931. ** SLOT_2_0 A mask for (0x7f<<14) | 0x7f
  22932. **
  22933. ** SLOT_4_2_0 A mask for (0x7f<<28) | SLOT_2_0
  22934. */
  22935. #define SLOT_2_0 0x001fc07f
  22936. #define SLOT_4_2_0 0xf01fc07f
  22937. /*
  22938. ** Read a 64-bit variable-length integer from memory starting at p[0].
  22939. ** Return the number of bytes read. The value is stored in *v.
  22940. */
  22941. SQLITE_PRIVATE u8 sqlite3GetVarint(const unsigned char *p, u64 *v){
  22942. u32 a,b,s;
  22943. a = *p;
  22944. /* a: p0 (unmasked) */
  22945. if (!(a&0x80))
  22946. {
  22947. *v = a;
  22948. return 1;
  22949. }
  22950. p++;
  22951. b = *p;
  22952. /* b: p1 (unmasked) */
  22953. if (!(b&0x80))
  22954. {
  22955. a &= 0x7f;
  22956. a = a<<7;
  22957. a |= b;
  22958. *v = a;
  22959. return 2;
  22960. }
  22961. /* Verify that constants are precomputed correctly */
  22962. assert( SLOT_2_0 == ((0x7f<<14) | (0x7f)) );
  22963. assert( SLOT_4_2_0 == ((0xfU<<28) | (0x7f<<14) | (0x7f)) );
  22964. p++;
  22965. a = a<<14;
  22966. a |= *p;
  22967. /* a: p0<<14 | p2 (unmasked) */
  22968. if (!(a&0x80))
  22969. {
  22970. a &= SLOT_2_0;
  22971. b &= 0x7f;
  22972. b = b<<7;
  22973. a |= b;
  22974. *v = a;
  22975. return 3;
  22976. }
  22977. /* CSE1 from below */
  22978. a &= SLOT_2_0;
  22979. p++;
  22980. b = b<<14;
  22981. b |= *p;
  22982. /* b: p1<<14 | p3 (unmasked) */
  22983. if (!(b&0x80))
  22984. {
  22985. b &= SLOT_2_0;
  22986. /* moved CSE1 up */
  22987. /* a &= (0x7f<<14)|(0x7f); */
  22988. a = a<<7;
  22989. a |= b;
  22990. *v = a;
  22991. return 4;
  22992. }
  22993. /* a: p0<<14 | p2 (masked) */
  22994. /* b: p1<<14 | p3 (unmasked) */
  22995. /* 1:save off p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
  22996. /* moved CSE1 up */
  22997. /* a &= (0x7f<<14)|(0x7f); */
  22998. b &= SLOT_2_0;
  22999. s = a;
  23000. /* s: p0<<14 | p2 (masked) */
  23001. p++;
  23002. a = a<<14;
  23003. a |= *p;
  23004. /* a: p0<<28 | p2<<14 | p4 (unmasked) */
  23005. if (!(a&0x80))
  23006. {
  23007. /* we can skip these cause they were (effectively) done above in calc'ing s */
  23008. /* a &= (0x7f<<28)|(0x7f<<14)|(0x7f); */
  23009. /* b &= (0x7f<<14)|(0x7f); */
  23010. b = b<<7;
  23011. a |= b;
  23012. s = s>>18;
  23013. *v = ((u64)s)<<32 | a;
  23014. return 5;
  23015. }
  23016. /* 2:save off p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
  23017. s = s<<7;
  23018. s |= b;
  23019. /* s: p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
  23020. p++;
  23021. b = b<<14;
  23022. b |= *p;
  23023. /* b: p1<<28 | p3<<14 | p5 (unmasked) */
  23024. if (!(b&0x80))
  23025. {
  23026. /* we can skip this cause it was (effectively) done above in calc'ing s */
  23027. /* b &= (0x7f<<28)|(0x7f<<14)|(0x7f); */
  23028. a &= SLOT_2_0;
  23029. a = a<<7;
  23030. a |= b;
  23031. s = s>>18;
  23032. *v = ((u64)s)<<32 | a;
  23033. return 6;
  23034. }
  23035. p++;
  23036. a = a<<14;
  23037. a |= *p;
  23038. /* a: p2<<28 | p4<<14 | p6 (unmasked) */
  23039. if (!(a&0x80))
  23040. {
  23041. a &= SLOT_4_2_0;
  23042. b &= SLOT_2_0;
  23043. b = b<<7;
  23044. a |= b;
  23045. s = s>>11;
  23046. *v = ((u64)s)<<32 | a;
  23047. return 7;
  23048. }
  23049. /* CSE2 from below */
  23050. a &= SLOT_2_0;
  23051. p++;
  23052. b = b<<14;
  23053. b |= *p;
  23054. /* b: p3<<28 | p5<<14 | p7 (unmasked) */
  23055. if (!(b&0x80))
  23056. {
  23057. b &= SLOT_4_2_0;
  23058. /* moved CSE2 up */
  23059. /* a &= (0x7f<<14)|(0x7f); */
  23060. a = a<<7;
  23061. a |= b;
  23062. s = s>>4;
  23063. *v = ((u64)s)<<32 | a;
  23064. return 8;
  23065. }
  23066. p++;
  23067. a = a<<15;
  23068. a |= *p;
  23069. /* a: p4<<29 | p6<<15 | p8 (unmasked) */
  23070. /* moved CSE2 up */
  23071. /* a &= (0x7f<<29)|(0x7f<<15)|(0xff); */
  23072. b &= SLOT_2_0;
  23073. b = b<<8;
  23074. a |= b;
  23075. s = s<<4;
  23076. b = p[-4];
  23077. b &= 0x7f;
  23078. b = b>>3;
  23079. s |= b;
  23080. *v = ((u64)s)<<32 | a;
  23081. return 9;
  23082. }
  23083. /*
  23084. ** Read a 32-bit variable-length integer from memory starting at p[0].
  23085. ** Return the number of bytes read. The value is stored in *v.
  23086. **
  23087. ** If the varint stored in p[0] is larger than can fit in a 32-bit unsigned
  23088. ** integer, then set *v to 0xffffffff.
  23089. **
  23090. ** A MACRO version, getVarint32, is provided which inlines the
  23091. ** single-byte case. All code should use the MACRO version as
  23092. ** this function assumes the single-byte case has already been handled.
  23093. */
  23094. SQLITE_PRIVATE u8 sqlite3GetVarint32(const unsigned char *p, u32 *v){
  23095. u32 a,b;
  23096. /* The 1-byte case. Overwhelmingly the most common. Handled inline
  23097. ** by the getVarin32() macro */
  23098. a = *p;
  23099. /* a: p0 (unmasked) */
  23100. #ifndef getVarint32
  23101. if (!(a&0x80))
  23102. {
  23103. /* Values between 0 and 127 */
  23104. *v = a;
  23105. return 1;
  23106. }
  23107. #endif
  23108. /* The 2-byte case */
  23109. p++;
  23110. b = *p;
  23111. /* b: p1 (unmasked) */
  23112. if (!(b&0x80))
  23113. {
  23114. /* Values between 128 and 16383 */
  23115. a &= 0x7f;
  23116. a = a<<7;
  23117. *v = a | b;
  23118. return 2;
  23119. }
  23120. /* The 3-byte case */
  23121. p++;
  23122. a = a<<14;
  23123. a |= *p;
  23124. /* a: p0<<14 | p2 (unmasked) */
  23125. if (!(a&0x80))
  23126. {
  23127. /* Values between 16384 and 2097151 */
  23128. a &= (0x7f<<14)|(0x7f);
  23129. b &= 0x7f;
  23130. b = b<<7;
  23131. *v = a | b;
  23132. return 3;
  23133. }
  23134. /* A 32-bit varint is used to store size information in btrees.
  23135. ** Objects are rarely larger than 2MiB limit of a 3-byte varint.
  23136. ** A 3-byte varint is sufficient, for example, to record the size
  23137. ** of a 1048569-byte BLOB or string.
  23138. **
  23139. ** We only unroll the first 1-, 2-, and 3- byte cases. The very
  23140. ** rare larger cases can be handled by the slower 64-bit varint
  23141. ** routine.
  23142. */
  23143. #if 1
  23144. {
  23145. u64 v64;
  23146. u8 n;
  23147. p -= 2;
  23148. n = sqlite3GetVarint(p, &v64);
  23149. assert( n>3 && n<=9 );
  23150. if( (v64 & SQLITE_MAX_U32)!=v64 ){
  23151. *v = 0xffffffff;
  23152. }else{
  23153. *v = (u32)v64;
  23154. }
  23155. return n;
  23156. }
  23157. #else
  23158. /* For following code (kept for historical record only) shows an
  23159. ** unrolling for the 3- and 4-byte varint cases. This code is
  23160. ** slightly faster, but it is also larger and much harder to test.
  23161. */
  23162. p++;
  23163. b = b<<14;
  23164. b |= *p;
  23165. /* b: p1<<14 | p3 (unmasked) */
  23166. if (!(b&0x80))
  23167. {
  23168. /* Values between 2097152 and 268435455 */
  23169. b &= (0x7f<<14)|(0x7f);
  23170. a &= (0x7f<<14)|(0x7f);
  23171. a = a<<7;
  23172. *v = a | b;
  23173. return 4;
  23174. }
  23175. p++;
  23176. a = a<<14;
  23177. a |= *p;
  23178. /* a: p0<<28 | p2<<14 | p4 (unmasked) */
  23179. if (!(a&0x80))
  23180. {
  23181. /* Values between 268435456 and 34359738367 */
  23182. a &= SLOT_4_2_0;
  23183. b &= SLOT_4_2_0;
  23184. b = b<<7;
  23185. *v = a | b;
  23186. return 5;
  23187. }
  23188. /* We can only reach this point when reading a corrupt database
  23189. ** file. In that case we are not in any hurry. Use the (relatively
  23190. ** slow) general-purpose sqlite3GetVarint() routine to extract the
  23191. ** value. */
  23192. {
  23193. u64 v64;
  23194. u8 n;
  23195. p -= 4;
  23196. n = sqlite3GetVarint(p, &v64);
  23197. assert( n>5 && n<=9 );
  23198. *v = (u32)v64;
  23199. return n;
  23200. }
  23201. #endif
  23202. }
  23203. /*
  23204. ** Return the number of bytes that will be needed to store the given
  23205. ** 64-bit integer.
  23206. */
  23207. SQLITE_PRIVATE int sqlite3VarintLen(u64 v){
  23208. int i = 0;
  23209. do{
  23210. i++;
  23211. v >>= 7;
  23212. }while( v!=0 && ALWAYS(i<9) );
  23213. return i;
  23214. }
  23215. /*
  23216. ** Read or write a four-byte big-endian integer value.
  23217. */
  23218. SQLITE_PRIVATE u32 sqlite3Get4byte(const u8 *p){
  23219. testcase( p[0]&0x80 );
  23220. return ((unsigned)p[0]<<24) | (p[1]<<16) | (p[2]<<8) | p[3];
  23221. }
  23222. SQLITE_PRIVATE void sqlite3Put4byte(unsigned char *p, u32 v){
  23223. p[0] = (u8)(v>>24);
  23224. p[1] = (u8)(v>>16);
  23225. p[2] = (u8)(v>>8);
  23226. p[3] = (u8)v;
  23227. }
  23228. /*
  23229. ** Translate a single byte of Hex into an integer.
  23230. ** This routine only works if h really is a valid hexadecimal
  23231. ** character: 0..9a..fA..F
  23232. */
  23233. SQLITE_PRIVATE u8 sqlite3HexToInt(int h){
  23234. assert( (h>='0' && h<='9') || (h>='a' && h<='f') || (h>='A' && h<='F') );
  23235. #ifdef SQLITE_ASCII
  23236. h += 9*(1&(h>>6));
  23237. #endif
  23238. #ifdef SQLITE_EBCDIC
  23239. h += 9*(1&~(h>>4));
  23240. #endif
  23241. return (u8)(h & 0xf);
  23242. }
  23243. #if !defined(SQLITE_OMIT_BLOB_LITERAL) || defined(SQLITE_HAS_CODEC)
  23244. /*
  23245. ** Convert a BLOB literal of the form "x'hhhhhh'" into its binary
  23246. ** value. Return a pointer to its binary value. Space to hold the
  23247. ** binary value has been obtained from malloc and must be freed by
  23248. ** the calling routine.
  23249. */
  23250. SQLITE_PRIVATE void *sqlite3HexToBlob(sqlite3 *db, const char *z, int n){
  23251. char *zBlob;
  23252. int i;
  23253. zBlob = (char *)sqlite3DbMallocRaw(db, n/2 + 1);
  23254. n--;
  23255. if( zBlob ){
  23256. for(i=0; i<n; i+=2){
  23257. zBlob[i/2] = (sqlite3HexToInt(z[i])<<4) | sqlite3HexToInt(z[i+1]);
  23258. }
  23259. zBlob[i/2] = 0;
  23260. }
  23261. return zBlob;
  23262. }
  23263. #endif /* !SQLITE_OMIT_BLOB_LITERAL || SQLITE_HAS_CODEC */
  23264. /*
  23265. ** Log an error that is an API call on a connection pointer that should
  23266. ** not have been used. The "type" of connection pointer is given as the
  23267. ** argument. The zType is a word like "NULL" or "closed" or "invalid".
  23268. */
  23269. static void logBadConnection(const char *zType){
  23270. sqlite3_log(SQLITE_MISUSE,
  23271. "API call with %s database connection pointer",
  23272. zType
  23273. );
  23274. }
  23275. /*
  23276. ** Check to make sure we have a valid db pointer. This test is not
  23277. ** foolproof but it does provide some measure of protection against
  23278. ** misuse of the interface such as passing in db pointers that are
  23279. ** NULL or which have been previously closed. If this routine returns
  23280. ** 1 it means that the db pointer is valid and 0 if it should not be
  23281. ** dereferenced for any reason. The calling function should invoke
  23282. ** SQLITE_MISUSE immediately.
  23283. **
  23284. ** sqlite3SafetyCheckOk() requires that the db pointer be valid for
  23285. ** use. sqlite3SafetyCheckSickOrOk() allows a db pointer that failed to
  23286. ** open properly and is not fit for general use but which can be
  23287. ** used as an argument to sqlite3_errmsg() or sqlite3_close().
  23288. */
  23289. SQLITE_PRIVATE int sqlite3SafetyCheckOk(sqlite3 *db){
  23290. u32 magic;
  23291. if( db==0 ){
  23292. logBadConnection("NULL");
  23293. return 0;
  23294. }
  23295. magic = db->magic;
  23296. if( magic!=SQLITE_MAGIC_OPEN ){
  23297. if( sqlite3SafetyCheckSickOrOk(db) ){
  23298. testcase( sqlite3GlobalConfig.xLog!=0 );
  23299. logBadConnection("unopened");
  23300. }
  23301. return 0;
  23302. }else{
  23303. return 1;
  23304. }
  23305. }
  23306. SQLITE_PRIVATE int sqlite3SafetyCheckSickOrOk(sqlite3 *db){
  23307. u32 magic;
  23308. magic = db->magic;
  23309. if( magic!=SQLITE_MAGIC_SICK &&
  23310. magic!=SQLITE_MAGIC_OPEN &&
  23311. magic!=SQLITE_MAGIC_BUSY ){
  23312. testcase( sqlite3GlobalConfig.xLog!=0 );
  23313. logBadConnection("invalid");
  23314. return 0;
  23315. }else{
  23316. return 1;
  23317. }
  23318. }
  23319. /*
  23320. ** Attempt to add, substract, or multiply the 64-bit signed value iB against
  23321. ** the other 64-bit signed integer at *pA and store the result in *pA.
  23322. ** Return 0 on success. Or if the operation would have resulted in an
  23323. ** overflow, leave *pA unchanged and return 1.
  23324. */
  23325. SQLITE_PRIVATE int sqlite3AddInt64(i64 *pA, i64 iB){
  23326. i64 iA = *pA;
  23327. testcase( iA==0 ); testcase( iA==1 );
  23328. testcase( iB==-1 ); testcase( iB==0 );
  23329. if( iB>=0 ){
  23330. testcase( iA>0 && LARGEST_INT64 - iA == iB );
  23331. testcase( iA>0 && LARGEST_INT64 - iA == iB - 1 );
  23332. if( iA>0 && LARGEST_INT64 - iA < iB ) return 1;
  23333. }else{
  23334. testcase( iA<0 && -(iA + LARGEST_INT64) == iB + 1 );
  23335. testcase( iA<0 && -(iA + LARGEST_INT64) == iB + 2 );
  23336. if( iA<0 && -(iA + LARGEST_INT64) > iB + 1 ) return 1;
  23337. }
  23338. *pA += iB;
  23339. return 0;
  23340. }
  23341. SQLITE_PRIVATE int sqlite3SubInt64(i64 *pA, i64 iB){
  23342. testcase( iB==SMALLEST_INT64+1 );
  23343. if( iB==SMALLEST_INT64 ){
  23344. testcase( (*pA)==(-1) ); testcase( (*pA)==0 );
  23345. if( (*pA)>=0 ) return 1;
  23346. *pA -= iB;
  23347. return 0;
  23348. }else{
  23349. return sqlite3AddInt64(pA, -iB);
  23350. }
  23351. }
  23352. #define TWOPOWER32 (((i64)1)<<32)
  23353. #define TWOPOWER31 (((i64)1)<<31)
  23354. SQLITE_PRIVATE int sqlite3MulInt64(i64 *pA, i64 iB){
  23355. i64 iA = *pA;
  23356. i64 iA1, iA0, iB1, iB0, r;
  23357. iA1 = iA/TWOPOWER32;
  23358. iA0 = iA % TWOPOWER32;
  23359. iB1 = iB/TWOPOWER32;
  23360. iB0 = iB % TWOPOWER32;
  23361. if( iA1==0 ){
  23362. if( iB1==0 ){
  23363. *pA *= iB;
  23364. return 0;
  23365. }
  23366. r = iA0*iB1;
  23367. }else if( iB1==0 ){
  23368. r = iA1*iB0;
  23369. }else{
  23370. /* If both iA1 and iB1 are non-zero, overflow will result */
  23371. return 1;
  23372. }
  23373. testcase( r==(-TWOPOWER31)-1 );
  23374. testcase( r==(-TWOPOWER31) );
  23375. testcase( r==TWOPOWER31 );
  23376. testcase( r==TWOPOWER31-1 );
  23377. if( r<(-TWOPOWER31) || r>=TWOPOWER31 ) return 1;
  23378. r *= TWOPOWER32;
  23379. if( sqlite3AddInt64(&r, iA0*iB0) ) return 1;
  23380. *pA = r;
  23381. return 0;
  23382. }
  23383. /*
  23384. ** Compute the absolute value of a 32-bit signed integer, of possible. Or
  23385. ** if the integer has a value of -2147483648, return +2147483647
  23386. */
  23387. SQLITE_PRIVATE int sqlite3AbsInt32(int x){
  23388. if( x>=0 ) return x;
  23389. if( x==(int)0x80000000 ) return 0x7fffffff;
  23390. return -x;
  23391. }
  23392. #ifdef SQLITE_ENABLE_8_3_NAMES
  23393. /*
  23394. ** If SQLITE_ENABLE_8_3_NAMES is set at compile-time and if the database
  23395. ** filename in zBaseFilename is a URI with the "8_3_names=1" parameter and
  23396. ** if filename in z[] has a suffix (a.k.a. "extension") that is longer than
  23397. ** three characters, then shorten the suffix on z[] to be the last three
  23398. ** characters of the original suffix.
  23399. **
  23400. ** If SQLITE_ENABLE_8_3_NAMES is set to 2 at compile-time, then always
  23401. ** do the suffix shortening regardless of URI parameter.
  23402. **
  23403. ** Examples:
  23404. **
  23405. ** test.db-journal => test.nal
  23406. ** test.db-wal => test.wal
  23407. ** test.db-shm => test.shm
  23408. ** test.db-mj7f3319fa => test.9fa
  23409. */
  23410. SQLITE_PRIVATE void sqlite3FileSuffix3(const char *zBaseFilename, char *z){
  23411. #if SQLITE_ENABLE_8_3_NAMES<2
  23412. if( sqlite3_uri_boolean(zBaseFilename, "8_3_names", 0) )
  23413. #endif
  23414. {
  23415. int i, sz;
  23416. sz = sqlite3Strlen30(z);
  23417. for(i=sz-1; i>0 && z[i]!='/' && z[i]!='.'; i--){}
  23418. if( z[i]=='.' && ALWAYS(sz>i+4) ) memmove(&z[i+1], &z[sz-3], 4);
  23419. }
  23420. }
  23421. #endif
  23422. /*
  23423. ** Find (an approximate) sum of two LogEst values. This computation is
  23424. ** not a simple "+" operator because LogEst is stored as a logarithmic
  23425. ** value.
  23426. **
  23427. */
  23428. SQLITE_PRIVATE LogEst sqlite3LogEstAdd(LogEst a, LogEst b){
  23429. static const unsigned char x[] = {
  23430. 10, 10, /* 0,1 */
  23431. 9, 9, /* 2,3 */
  23432. 8, 8, /* 4,5 */
  23433. 7, 7, 7, /* 6,7,8 */
  23434. 6, 6, 6, /* 9,10,11 */
  23435. 5, 5, 5, /* 12-14 */
  23436. 4, 4, 4, 4, /* 15-18 */
  23437. 3, 3, 3, 3, 3, 3, /* 19-24 */
  23438. 2, 2, 2, 2, 2, 2, 2, /* 25-31 */
  23439. };
  23440. if( a>=b ){
  23441. if( a>b+49 ) return a;
  23442. if( a>b+31 ) return a+1;
  23443. return a+x[a-b];
  23444. }else{
  23445. if( b>a+49 ) return b;
  23446. if( b>a+31 ) return b+1;
  23447. return b+x[b-a];
  23448. }
  23449. }
  23450. /*
  23451. ** Convert an integer into a LogEst. In other words, compute an
  23452. ** approximation for 10*log2(x).
  23453. */
  23454. SQLITE_PRIVATE LogEst sqlite3LogEst(u64 x){
  23455. static LogEst a[] = { 0, 2, 3, 5, 6, 7, 8, 9 };
  23456. LogEst y = 40;
  23457. if( x<8 ){
  23458. if( x<2 ) return 0;
  23459. while( x<8 ){ y -= 10; x <<= 1; }
  23460. }else{
  23461. while( x>255 ){ y += 40; x >>= 4; }
  23462. while( x>15 ){ y += 10; x >>= 1; }
  23463. }
  23464. return a[x&7] + y - 10;
  23465. }
  23466. #ifndef SQLITE_OMIT_VIRTUALTABLE
  23467. /*
  23468. ** Convert a double into a LogEst
  23469. ** In other words, compute an approximation for 10*log2(x).
  23470. */
  23471. SQLITE_PRIVATE LogEst sqlite3LogEstFromDouble(double x){
  23472. u64 a;
  23473. LogEst e;
  23474. assert( sizeof(x)==8 && sizeof(a)==8 );
  23475. if( x<=1 ) return 0;
  23476. if( x<=2000000000 ) return sqlite3LogEst((u64)x);
  23477. memcpy(&a, &x, 8);
  23478. e = (a>>52) - 1022;
  23479. return e*10;
  23480. }
  23481. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  23482. /*
  23483. ** Convert a LogEst into an integer.
  23484. */
  23485. SQLITE_PRIVATE u64 sqlite3LogEstToInt(LogEst x){
  23486. u64 n;
  23487. if( x<10 ) return 1;
  23488. n = x%10;
  23489. x /= 10;
  23490. if( n>=5 ) n -= 2;
  23491. else if( n>=1 ) n -= 1;
  23492. if( x>=3 ){
  23493. return x>60 ? (u64)LARGEST_INT64 : (n+8)<<(x-3);
  23494. }
  23495. return (n+8)>>(3-x);
  23496. }
  23497. /************** End of util.c ************************************************/
  23498. /************** Begin file hash.c ********************************************/
  23499. /*
  23500. ** 2001 September 22
  23501. **
  23502. ** The author disclaims copyright to this source code. In place of
  23503. ** a legal notice, here is a blessing:
  23504. **
  23505. ** May you do good and not evil.
  23506. ** May you find forgiveness for yourself and forgive others.
  23507. ** May you share freely, never taking more than you give.
  23508. **
  23509. *************************************************************************
  23510. ** This is the implementation of generic hash-tables
  23511. ** used in SQLite.
  23512. */
  23513. /* #include <assert.h> */
  23514. /* Turn bulk memory into a hash table object by initializing the
  23515. ** fields of the Hash structure.
  23516. **
  23517. ** "pNew" is a pointer to the hash table that is to be initialized.
  23518. */
  23519. SQLITE_PRIVATE void sqlite3HashInit(Hash *pNew){
  23520. assert( pNew!=0 );
  23521. pNew->first = 0;
  23522. pNew->count = 0;
  23523. pNew->htsize = 0;
  23524. pNew->ht = 0;
  23525. }
  23526. /* Remove all entries from a hash table. Reclaim all memory.
  23527. ** Call this routine to delete a hash table or to reset a hash table
  23528. ** to the empty state.
  23529. */
  23530. SQLITE_PRIVATE void sqlite3HashClear(Hash *pH){
  23531. HashElem *elem; /* For looping over all elements of the table */
  23532. assert( pH!=0 );
  23533. elem = pH->first;
  23534. pH->first = 0;
  23535. sqlite3_free(pH->ht);
  23536. pH->ht = 0;
  23537. pH->htsize = 0;
  23538. while( elem ){
  23539. HashElem *next_elem = elem->next;
  23540. sqlite3_free(elem);
  23541. elem = next_elem;
  23542. }
  23543. pH->count = 0;
  23544. }
  23545. /*
  23546. ** The hashing function.
  23547. */
  23548. static unsigned int strHash(const char *z){
  23549. unsigned int h = 0;
  23550. unsigned char c;
  23551. while( (c = (unsigned char)*z++)!=0 ){
  23552. h = (h<<3) ^ h ^ sqlite3UpperToLower[c];
  23553. }
  23554. return h;
  23555. }
  23556. /* Link pNew element into the hash table pH. If pEntry!=0 then also
  23557. ** insert pNew into the pEntry hash bucket.
  23558. */
  23559. static void insertElement(
  23560. Hash *pH, /* The complete hash table */
  23561. struct _ht *pEntry, /* The entry into which pNew is inserted */
  23562. HashElem *pNew /* The element to be inserted */
  23563. ){
  23564. HashElem *pHead; /* First element already in pEntry */
  23565. if( pEntry ){
  23566. pHead = pEntry->count ? pEntry->chain : 0;
  23567. pEntry->count++;
  23568. pEntry->chain = pNew;
  23569. }else{
  23570. pHead = 0;
  23571. }
  23572. if( pHead ){
  23573. pNew->next = pHead;
  23574. pNew->prev = pHead->prev;
  23575. if( pHead->prev ){ pHead->prev->next = pNew; }
  23576. else { pH->first = pNew; }
  23577. pHead->prev = pNew;
  23578. }else{
  23579. pNew->next = pH->first;
  23580. if( pH->first ){ pH->first->prev = pNew; }
  23581. pNew->prev = 0;
  23582. pH->first = pNew;
  23583. }
  23584. }
  23585. /* Resize the hash table so that it cantains "new_size" buckets.
  23586. **
  23587. ** The hash table might fail to resize if sqlite3_malloc() fails or
  23588. ** if the new size is the same as the prior size.
  23589. ** Return TRUE if the resize occurs and false if not.
  23590. */
  23591. static int rehash(Hash *pH, unsigned int new_size){
  23592. struct _ht *new_ht; /* The new hash table */
  23593. HashElem *elem, *next_elem; /* For looping over existing elements */
  23594. #if SQLITE_MALLOC_SOFT_LIMIT>0
  23595. if( new_size*sizeof(struct _ht)>SQLITE_MALLOC_SOFT_LIMIT ){
  23596. new_size = SQLITE_MALLOC_SOFT_LIMIT/sizeof(struct _ht);
  23597. }
  23598. if( new_size==pH->htsize ) return 0;
  23599. #endif
  23600. /* The inability to allocates space for a larger hash table is
  23601. ** a performance hit but it is not a fatal error. So mark the
  23602. ** allocation as a benign. Use sqlite3Malloc()/memset(0) instead of
  23603. ** sqlite3MallocZero() to make the allocation, as sqlite3MallocZero()
  23604. ** only zeroes the requested number of bytes whereas this module will
  23605. ** use the actual amount of space allocated for the hash table (which
  23606. ** may be larger than the requested amount).
  23607. */
  23608. sqlite3BeginBenignMalloc();
  23609. new_ht = (struct _ht *)sqlite3Malloc( new_size*sizeof(struct _ht) );
  23610. sqlite3EndBenignMalloc();
  23611. if( new_ht==0 ) return 0;
  23612. sqlite3_free(pH->ht);
  23613. pH->ht = new_ht;
  23614. pH->htsize = new_size = sqlite3MallocSize(new_ht)/sizeof(struct _ht);
  23615. memset(new_ht, 0, new_size*sizeof(struct _ht));
  23616. for(elem=pH->first, pH->first=0; elem; elem = next_elem){
  23617. unsigned int h = strHash(elem->pKey) % new_size;
  23618. next_elem = elem->next;
  23619. insertElement(pH, &new_ht[h], elem);
  23620. }
  23621. return 1;
  23622. }
  23623. /* This function (for internal use only) locates an element in an
  23624. ** hash table that matches the given key. The hash for this key is
  23625. ** also computed and returned in the *pH parameter.
  23626. */
  23627. static HashElem *findElementWithHash(
  23628. const Hash *pH, /* The pH to be searched */
  23629. const char *pKey, /* The key we are searching for */
  23630. unsigned int *pHash /* Write the hash value here */
  23631. ){
  23632. HashElem *elem; /* Used to loop thru the element list */
  23633. int count; /* Number of elements left to test */
  23634. unsigned int h; /* The computed hash */
  23635. if( pH->ht ){
  23636. struct _ht *pEntry;
  23637. h = strHash(pKey) % pH->htsize;
  23638. pEntry = &pH->ht[h];
  23639. elem = pEntry->chain;
  23640. count = pEntry->count;
  23641. }else{
  23642. h = 0;
  23643. elem = pH->first;
  23644. count = pH->count;
  23645. }
  23646. *pHash = h;
  23647. while( count-- ){
  23648. assert( elem!=0 );
  23649. if( sqlite3StrICmp(elem->pKey,pKey)==0 ){
  23650. return elem;
  23651. }
  23652. elem = elem->next;
  23653. }
  23654. return 0;
  23655. }
  23656. /* Remove a single entry from the hash table given a pointer to that
  23657. ** element and a hash on the element's key.
  23658. */
  23659. static void removeElementGivenHash(
  23660. Hash *pH, /* The pH containing "elem" */
  23661. HashElem* elem, /* The element to be removed from the pH */
  23662. unsigned int h /* Hash value for the element */
  23663. ){
  23664. struct _ht *pEntry;
  23665. if( elem->prev ){
  23666. elem->prev->next = elem->next;
  23667. }else{
  23668. pH->first = elem->next;
  23669. }
  23670. if( elem->next ){
  23671. elem->next->prev = elem->prev;
  23672. }
  23673. if( pH->ht ){
  23674. pEntry = &pH->ht[h];
  23675. if( pEntry->chain==elem ){
  23676. pEntry->chain = elem->next;
  23677. }
  23678. pEntry->count--;
  23679. assert( pEntry->count>=0 );
  23680. }
  23681. sqlite3_free( elem );
  23682. pH->count--;
  23683. if( pH->count==0 ){
  23684. assert( pH->first==0 );
  23685. assert( pH->count==0 );
  23686. sqlite3HashClear(pH);
  23687. }
  23688. }
  23689. /* Attempt to locate an element of the hash table pH with a key
  23690. ** that matches pKey. Return the data for this element if it is
  23691. ** found, or NULL if there is no match.
  23692. */
  23693. SQLITE_PRIVATE void *sqlite3HashFind(const Hash *pH, const char *pKey){
  23694. HashElem *elem; /* The element that matches key */
  23695. unsigned int h; /* A hash on key */
  23696. assert( pH!=0 );
  23697. assert( pKey!=0 );
  23698. elem = findElementWithHash(pH, pKey, &h);
  23699. return elem ? elem->data : 0;
  23700. }
  23701. /* Insert an element into the hash table pH. The key is pKey
  23702. ** and the data is "data".
  23703. **
  23704. ** If no element exists with a matching key, then a new
  23705. ** element is created and NULL is returned.
  23706. **
  23707. ** If another element already exists with the same key, then the
  23708. ** new data replaces the old data and the old data is returned.
  23709. ** The key is not copied in this instance. If a malloc fails, then
  23710. ** the new data is returned and the hash table is unchanged.
  23711. **
  23712. ** If the "data" parameter to this function is NULL, then the
  23713. ** element corresponding to "key" is removed from the hash table.
  23714. */
  23715. SQLITE_PRIVATE void *sqlite3HashInsert(Hash *pH, const char *pKey, void *data){
  23716. unsigned int h; /* the hash of the key modulo hash table size */
  23717. HashElem *elem; /* Used to loop thru the element list */
  23718. HashElem *new_elem; /* New element added to the pH */
  23719. assert( pH!=0 );
  23720. assert( pKey!=0 );
  23721. elem = findElementWithHash(pH,pKey,&h);
  23722. if( elem ){
  23723. void *old_data = elem->data;
  23724. if( data==0 ){
  23725. removeElementGivenHash(pH,elem,h);
  23726. }else{
  23727. elem->data = data;
  23728. elem->pKey = pKey;
  23729. }
  23730. return old_data;
  23731. }
  23732. if( data==0 ) return 0;
  23733. new_elem = (HashElem*)sqlite3Malloc( sizeof(HashElem) );
  23734. if( new_elem==0 ) return data;
  23735. new_elem->pKey = pKey;
  23736. new_elem->data = data;
  23737. pH->count++;
  23738. if( pH->count>=10 && pH->count > 2*pH->htsize ){
  23739. if( rehash(pH, pH->count*2) ){
  23740. assert( pH->htsize>0 );
  23741. h = strHash(pKey) % pH->htsize;
  23742. }
  23743. }
  23744. insertElement(pH, pH->ht ? &pH->ht[h] : 0, new_elem);
  23745. return 0;
  23746. }
  23747. /************** End of hash.c ************************************************/
  23748. /************** Begin file opcodes.c *****************************************/
  23749. /* Automatically generated. Do not edit */
  23750. /* See the mkopcodec.awk script for details. */
  23751. #if !defined(SQLITE_OMIT_EXPLAIN) || defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)
  23752. #if defined(SQLITE_ENABLE_EXPLAIN_COMMENTS) || defined(SQLITE_DEBUG)
  23753. # define OpHelp(X) "\0" X
  23754. #else
  23755. # define OpHelp(X)
  23756. #endif
  23757. SQLITE_PRIVATE const char *sqlite3OpcodeName(int i){
  23758. static const char *const azName[] = { "?",
  23759. /* 1 */ "Function" OpHelp("r[P3]=func(r[P2@P5])"),
  23760. /* 2 */ "Savepoint" OpHelp(""),
  23761. /* 3 */ "AutoCommit" OpHelp(""),
  23762. /* 4 */ "Transaction" OpHelp(""),
  23763. /* 5 */ "SorterNext" OpHelp(""),
  23764. /* 6 */ "PrevIfOpen" OpHelp(""),
  23765. /* 7 */ "NextIfOpen" OpHelp(""),
  23766. /* 8 */ "Prev" OpHelp(""),
  23767. /* 9 */ "Next" OpHelp(""),
  23768. /* 10 */ "AggStep" OpHelp("accum=r[P3] step(r[P2@P5])"),
  23769. /* 11 */ "Checkpoint" OpHelp(""),
  23770. /* 12 */ "JournalMode" OpHelp(""),
  23771. /* 13 */ "Vacuum" OpHelp(""),
  23772. /* 14 */ "VFilter" OpHelp("iplan=r[P3] zplan='P4'"),
  23773. /* 15 */ "VUpdate" OpHelp("data=r[P3@P2]"),
  23774. /* 16 */ "Goto" OpHelp(""),
  23775. /* 17 */ "Gosub" OpHelp(""),
  23776. /* 18 */ "Return" OpHelp(""),
  23777. /* 19 */ "Not" OpHelp("r[P2]= !r[P1]"),
  23778. /* 20 */ "InitCoroutine" OpHelp(""),
  23779. /* 21 */ "EndCoroutine" OpHelp(""),
  23780. /* 22 */ "Yield" OpHelp(""),
  23781. /* 23 */ "HaltIfNull" OpHelp("if r[P3]=null halt"),
  23782. /* 24 */ "Halt" OpHelp(""),
  23783. /* 25 */ "Integer" OpHelp("r[P2]=P1"),
  23784. /* 26 */ "Int64" OpHelp("r[P2]=P4"),
  23785. /* 27 */ "String" OpHelp("r[P2]='P4' (len=P1)"),
  23786. /* 28 */ "Null" OpHelp("r[P2..P3]=NULL"),
  23787. /* 29 */ "SoftNull" OpHelp("r[P1]=NULL"),
  23788. /* 30 */ "Blob" OpHelp("r[P2]=P4 (len=P1)"),
  23789. /* 31 */ "Variable" OpHelp("r[P2]=parameter(P1,P4)"),
  23790. /* 32 */ "Move" OpHelp("r[P2@P3]=r[P1@P3]"),
  23791. /* 33 */ "Copy" OpHelp("r[P2@P3+1]=r[P1@P3+1]"),
  23792. /* 34 */ "SCopy" OpHelp("r[P2]=r[P1]"),
  23793. /* 35 */ "ResultRow" OpHelp("output=r[P1@P2]"),
  23794. /* 36 */ "CollSeq" OpHelp(""),
  23795. /* 37 */ "AddImm" OpHelp("r[P1]=r[P1]+P2"),
  23796. /* 38 */ "MustBeInt" OpHelp(""),
  23797. /* 39 */ "RealAffinity" OpHelp(""),
  23798. /* 40 */ "Cast" OpHelp("affinity(r[P1])"),
  23799. /* 41 */ "Permutation" OpHelp(""),
  23800. /* 42 */ "Compare" OpHelp("r[P1@P3] <-> r[P2@P3]"),
  23801. /* 43 */ "Jump" OpHelp(""),
  23802. /* 44 */ "Once" OpHelp(""),
  23803. /* 45 */ "If" OpHelp(""),
  23804. /* 46 */ "IfNot" OpHelp(""),
  23805. /* 47 */ "Column" OpHelp("r[P3]=PX"),
  23806. /* 48 */ "Affinity" OpHelp("affinity(r[P1@P2])"),
  23807. /* 49 */ "MakeRecord" OpHelp("r[P3]=mkrec(r[P1@P2])"),
  23808. /* 50 */ "Count" OpHelp("r[P2]=count()"),
  23809. /* 51 */ "ReadCookie" OpHelp(""),
  23810. /* 52 */ "SetCookie" OpHelp(""),
  23811. /* 53 */ "ReopenIdx" OpHelp("root=P2 iDb=P3"),
  23812. /* 54 */ "OpenRead" OpHelp("root=P2 iDb=P3"),
  23813. /* 55 */ "OpenWrite" OpHelp("root=P2 iDb=P3"),
  23814. /* 56 */ "OpenAutoindex" OpHelp("nColumn=P2"),
  23815. /* 57 */ "OpenEphemeral" OpHelp("nColumn=P2"),
  23816. /* 58 */ "SorterOpen" OpHelp(""),
  23817. /* 59 */ "SequenceTest" OpHelp("if( cursor[P1].ctr++ ) pc = P2"),
  23818. /* 60 */ "OpenPseudo" OpHelp("P3 columns in r[P2]"),
  23819. /* 61 */ "Close" OpHelp(""),
  23820. /* 62 */ "SeekLT" OpHelp("key=r[P3@P4]"),
  23821. /* 63 */ "SeekLE" OpHelp("key=r[P3@P4]"),
  23822. /* 64 */ "SeekGE" OpHelp("key=r[P3@P4]"),
  23823. /* 65 */ "SeekGT" OpHelp("key=r[P3@P4]"),
  23824. /* 66 */ "Seek" OpHelp("intkey=r[P2]"),
  23825. /* 67 */ "NoConflict" OpHelp("key=r[P3@P4]"),
  23826. /* 68 */ "NotFound" OpHelp("key=r[P3@P4]"),
  23827. /* 69 */ "Found" OpHelp("key=r[P3@P4]"),
  23828. /* 70 */ "NotExists" OpHelp("intkey=r[P3]"),
  23829. /* 71 */ "Or" OpHelp("r[P3]=(r[P1] || r[P2])"),
  23830. /* 72 */ "And" OpHelp("r[P3]=(r[P1] && r[P2])"),
  23831. /* 73 */ "Sequence" OpHelp("r[P2]=cursor[P1].ctr++"),
  23832. /* 74 */ "NewRowid" OpHelp("r[P2]=rowid"),
  23833. /* 75 */ "Insert" OpHelp("intkey=r[P3] data=r[P2]"),
  23834. /* 76 */ "IsNull" OpHelp("if r[P1]==NULL goto P2"),
  23835. /* 77 */ "NotNull" OpHelp("if r[P1]!=NULL goto P2"),
  23836. /* 78 */ "Ne" OpHelp("if r[P1]!=r[P3] goto P2"),
  23837. /* 79 */ "Eq" OpHelp("if r[P1]==r[P3] goto P2"),
  23838. /* 80 */ "Gt" OpHelp("if r[P1]>r[P3] goto P2"),
  23839. /* 81 */ "Le" OpHelp("if r[P1]<=r[P3] goto P2"),
  23840. /* 82 */ "Lt" OpHelp("if r[P1]<r[P3] goto P2"),
  23841. /* 83 */ "Ge" OpHelp("if r[P1]>=r[P3] goto P2"),
  23842. /* 84 */ "InsertInt" OpHelp("intkey=P3 data=r[P2]"),
  23843. /* 85 */ "BitAnd" OpHelp("r[P3]=r[P1]&r[P2]"),
  23844. /* 86 */ "BitOr" OpHelp("r[P3]=r[P1]|r[P2]"),
  23845. /* 87 */ "ShiftLeft" OpHelp("r[P3]=r[P2]<<r[P1]"),
  23846. /* 88 */ "ShiftRight" OpHelp("r[P3]=r[P2]>>r[P1]"),
  23847. /* 89 */ "Add" OpHelp("r[P3]=r[P1]+r[P2]"),
  23848. /* 90 */ "Subtract" OpHelp("r[P3]=r[P2]-r[P1]"),
  23849. /* 91 */ "Multiply" OpHelp("r[P3]=r[P1]*r[P2]"),
  23850. /* 92 */ "Divide" OpHelp("r[P3]=r[P2]/r[P1]"),
  23851. /* 93 */ "Remainder" OpHelp("r[P3]=r[P2]%r[P1]"),
  23852. /* 94 */ "Concat" OpHelp("r[P3]=r[P2]+r[P1]"),
  23853. /* 95 */ "Delete" OpHelp(""),
  23854. /* 96 */ "BitNot" OpHelp("r[P1]= ~r[P1]"),
  23855. /* 97 */ "String8" OpHelp("r[P2]='P4'"),
  23856. /* 98 */ "ResetCount" OpHelp(""),
  23857. /* 99 */ "SorterCompare" OpHelp("if key(P1)!=trim(r[P3],P4) goto P2"),
  23858. /* 100 */ "SorterData" OpHelp("r[P2]=data"),
  23859. /* 101 */ "RowKey" OpHelp("r[P2]=key"),
  23860. /* 102 */ "RowData" OpHelp("r[P2]=data"),
  23861. /* 103 */ "Rowid" OpHelp("r[P2]=rowid"),
  23862. /* 104 */ "NullRow" OpHelp(""),
  23863. /* 105 */ "Last" OpHelp(""),
  23864. /* 106 */ "SorterSort" OpHelp(""),
  23865. /* 107 */ "Sort" OpHelp(""),
  23866. /* 108 */ "Rewind" OpHelp(""),
  23867. /* 109 */ "SorterInsert" OpHelp(""),
  23868. /* 110 */ "IdxInsert" OpHelp("key=r[P2]"),
  23869. /* 111 */ "IdxDelete" OpHelp("key=r[P2@P3]"),
  23870. /* 112 */ "IdxRowid" OpHelp("r[P2]=rowid"),
  23871. /* 113 */ "IdxLE" OpHelp("key=r[P3@P4]"),
  23872. /* 114 */ "IdxGT" OpHelp("key=r[P3@P4]"),
  23873. /* 115 */ "IdxLT" OpHelp("key=r[P3@P4]"),
  23874. /* 116 */ "IdxGE" OpHelp("key=r[P3@P4]"),
  23875. /* 117 */ "Destroy" OpHelp(""),
  23876. /* 118 */ "Clear" OpHelp(""),
  23877. /* 119 */ "ResetSorter" OpHelp(""),
  23878. /* 120 */ "CreateIndex" OpHelp("r[P2]=root iDb=P1"),
  23879. /* 121 */ "CreateTable" OpHelp("r[P2]=root iDb=P1"),
  23880. /* 122 */ "ParseSchema" OpHelp(""),
  23881. /* 123 */ "LoadAnalysis" OpHelp(""),
  23882. /* 124 */ "DropTable" OpHelp(""),
  23883. /* 125 */ "DropIndex" OpHelp(""),
  23884. /* 126 */ "DropTrigger" OpHelp(""),
  23885. /* 127 */ "IntegrityCk" OpHelp(""),
  23886. /* 128 */ "RowSetAdd" OpHelp("rowset(P1)=r[P2]"),
  23887. /* 129 */ "RowSetRead" OpHelp("r[P3]=rowset(P1)"),
  23888. /* 130 */ "RowSetTest" OpHelp("if r[P3] in rowset(P1) goto P2"),
  23889. /* 131 */ "Program" OpHelp(""),
  23890. /* 132 */ "Param" OpHelp(""),
  23891. /* 133 */ "Real" OpHelp("r[P2]=P4"),
  23892. /* 134 */ "FkCounter" OpHelp("fkctr[P1]+=P2"),
  23893. /* 135 */ "FkIfZero" OpHelp("if fkctr[P1]==0 goto P2"),
  23894. /* 136 */ "MemMax" OpHelp("r[P1]=max(r[P1],r[P2])"),
  23895. /* 137 */ "IfPos" OpHelp("if r[P1]>0 goto P2"),
  23896. /* 138 */ "IfNeg" OpHelp("r[P1]+=P3, if r[P1]<0 goto P2"),
  23897. /* 139 */ "IfNotZero" OpHelp("if r[P1]!=0 then r[P1]+=P3, goto P2"),
  23898. /* 140 */ "DecrJumpZero" OpHelp("if (--r[P1])==0 goto P2"),
  23899. /* 141 */ "JumpZeroIncr" OpHelp("if (r[P1]++)==0 ) goto P2"),
  23900. /* 142 */ "AggFinal" OpHelp("accum=r[P1] N=P2"),
  23901. /* 143 */ "IncrVacuum" OpHelp(""),
  23902. /* 144 */ "Expire" OpHelp(""),
  23903. /* 145 */ "TableLock" OpHelp("iDb=P1 root=P2 write=P3"),
  23904. /* 146 */ "VBegin" OpHelp(""),
  23905. /* 147 */ "VCreate" OpHelp(""),
  23906. /* 148 */ "VDestroy" OpHelp(""),
  23907. /* 149 */ "VOpen" OpHelp(""),
  23908. /* 150 */ "VColumn" OpHelp("r[P3]=vcolumn(P2)"),
  23909. /* 151 */ "VNext" OpHelp(""),
  23910. /* 152 */ "VRename" OpHelp(""),
  23911. /* 153 */ "Pagecount" OpHelp(""),
  23912. /* 154 */ "MaxPgcnt" OpHelp(""),
  23913. /* 155 */ "Init" OpHelp("Start at P2"),
  23914. /* 156 */ "Noop" OpHelp(""),
  23915. /* 157 */ "Explain" OpHelp(""),
  23916. };
  23917. return azName[i];
  23918. }
  23919. #endif
  23920. /************** End of opcodes.c *********************************************/
  23921. /************** Begin file os_unix.c *****************************************/
  23922. /*
  23923. ** 2004 May 22
  23924. **
  23925. ** The author disclaims copyright to this source code. In place of
  23926. ** a legal notice, here is a blessing:
  23927. **
  23928. ** May you do good and not evil.
  23929. ** May you find forgiveness for yourself and forgive others.
  23930. ** May you share freely, never taking more than you give.
  23931. **
  23932. ******************************************************************************
  23933. **
  23934. ** This file contains the VFS implementation for unix-like operating systems
  23935. ** include Linux, MacOSX, *BSD, QNX, VxWorks, AIX, HPUX, and others.
  23936. **
  23937. ** There are actually several different VFS implementations in this file.
  23938. ** The differences are in the way that file locking is done. The default
  23939. ** implementation uses Posix Advisory Locks. Alternative implementations
  23940. ** use flock(), dot-files, various proprietary locking schemas, or simply
  23941. ** skip locking all together.
  23942. **
  23943. ** This source file is organized into divisions where the logic for various
  23944. ** subfunctions is contained within the appropriate division. PLEASE
  23945. ** KEEP THE STRUCTURE OF THIS FILE INTACT. New code should be placed
  23946. ** in the correct division and should be clearly labeled.
  23947. **
  23948. ** The layout of divisions is as follows:
  23949. **
  23950. ** * General-purpose declarations and utility functions.
  23951. ** * Unique file ID logic used by VxWorks.
  23952. ** * Various locking primitive implementations (all except proxy locking):
  23953. ** + for Posix Advisory Locks
  23954. ** + for no-op locks
  23955. ** + for dot-file locks
  23956. ** + for flock() locking
  23957. ** + for named semaphore locks (VxWorks only)
  23958. ** + for AFP filesystem locks (MacOSX only)
  23959. ** * sqlite3_file methods not associated with locking.
  23960. ** * Definitions of sqlite3_io_methods objects for all locking
  23961. ** methods plus "finder" functions for each locking method.
  23962. ** * sqlite3_vfs method implementations.
  23963. ** * Locking primitives for the proxy uber-locking-method. (MacOSX only)
  23964. ** * Definitions of sqlite3_vfs objects for all locking methods
  23965. ** plus implementations of sqlite3_os_init() and sqlite3_os_end().
  23966. */
  23967. #if SQLITE_OS_UNIX /* This file is used on unix only */
  23968. /*
  23969. ** There are various methods for file locking used for concurrency
  23970. ** control:
  23971. **
  23972. ** 1. POSIX locking (the default),
  23973. ** 2. No locking,
  23974. ** 3. Dot-file locking,
  23975. ** 4. flock() locking,
  23976. ** 5. AFP locking (OSX only),
  23977. ** 6. Named POSIX semaphores (VXWorks only),
  23978. ** 7. proxy locking. (OSX only)
  23979. **
  23980. ** Styles 4, 5, and 7 are only available of SQLITE_ENABLE_LOCKING_STYLE
  23981. ** is defined to 1. The SQLITE_ENABLE_LOCKING_STYLE also enables automatic
  23982. ** selection of the appropriate locking style based on the filesystem
  23983. ** where the database is located.
  23984. */
  23985. #if !defined(SQLITE_ENABLE_LOCKING_STYLE)
  23986. # if defined(__APPLE__)
  23987. # define SQLITE_ENABLE_LOCKING_STYLE 1
  23988. # else
  23989. # define SQLITE_ENABLE_LOCKING_STYLE 0
  23990. # endif
  23991. #endif
  23992. /*
  23993. ** standard include files.
  23994. */
  23995. #include <sys/types.h>
  23996. #include <sys/stat.h>
  23997. #include <fcntl.h>
  23998. #include <unistd.h>
  23999. /* #include <time.h> */
  24000. #include <sys/time.h>
  24001. #include <errno.h>
  24002. #if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
  24003. # include <sys/mman.h>
  24004. #endif
  24005. #if SQLITE_ENABLE_LOCKING_STYLE
  24006. # include <sys/ioctl.h>
  24007. # include <sys/file.h>
  24008. # include <sys/param.h>
  24009. #endif /* SQLITE_ENABLE_LOCKING_STYLE */
  24010. #if defined(__APPLE__) && ((__MAC_OS_X_VERSION_MIN_REQUIRED > 1050) || \
  24011. (__IPHONE_OS_VERSION_MIN_REQUIRED > 2000))
  24012. # if (!defined(TARGET_OS_EMBEDDED) || (TARGET_OS_EMBEDDED==0)) \
  24013. && (!defined(TARGET_IPHONE_SIMULATOR) || (TARGET_IPHONE_SIMULATOR==0))
  24014. # define HAVE_GETHOSTUUID 1
  24015. # else
  24016. # warning "gethostuuid() is disabled."
  24017. # endif
  24018. #endif
  24019. #if OS_VXWORKS
  24020. /* # include <sys/ioctl.h> */
  24021. # include <semaphore.h>
  24022. # include <limits.h>
  24023. #endif /* OS_VXWORKS */
  24024. #if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
  24025. # include <sys/mount.h>
  24026. #endif
  24027. #ifdef HAVE_UTIME
  24028. # include <utime.h>
  24029. #endif
  24030. /*
  24031. ** Allowed values of unixFile.fsFlags
  24032. */
  24033. #define SQLITE_FSFLAGS_IS_MSDOS 0x1
  24034. /*
  24035. ** If we are to be thread-safe, include the pthreads header and define
  24036. ** the SQLITE_UNIX_THREADS macro.
  24037. */
  24038. #if SQLITE_THREADSAFE
  24039. /* # include <pthread.h> */
  24040. # define SQLITE_UNIX_THREADS 1
  24041. #endif
  24042. /*
  24043. ** Default permissions when creating a new file
  24044. */
  24045. #ifndef SQLITE_DEFAULT_FILE_PERMISSIONS
  24046. # define SQLITE_DEFAULT_FILE_PERMISSIONS 0644
  24047. #endif
  24048. /*
  24049. ** Default permissions when creating auto proxy dir
  24050. */
  24051. #ifndef SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
  24052. # define SQLITE_DEFAULT_PROXYDIR_PERMISSIONS 0755
  24053. #endif
  24054. /*
  24055. ** Maximum supported path-length.
  24056. */
  24057. #define MAX_PATHNAME 512
  24058. /* Always cast the getpid() return type for compatibility with
  24059. ** kernel modules in VxWorks. */
  24060. #define osGetpid(X) (pid_t)getpid()
  24061. /*
  24062. ** Only set the lastErrno if the error code is a real error and not
  24063. ** a normal expected return code of SQLITE_BUSY or SQLITE_OK
  24064. */
  24065. #define IS_LOCK_ERROR(x) ((x != SQLITE_OK) && (x != SQLITE_BUSY))
  24066. /* Forward references */
  24067. typedef struct unixShm unixShm; /* Connection shared memory */
  24068. typedef struct unixShmNode unixShmNode; /* Shared memory instance */
  24069. typedef struct unixInodeInfo unixInodeInfo; /* An i-node */
  24070. typedef struct UnixUnusedFd UnixUnusedFd; /* An unused file descriptor */
  24071. /*
  24072. ** Sometimes, after a file handle is closed by SQLite, the file descriptor
  24073. ** cannot be closed immediately. In these cases, instances of the following
  24074. ** structure are used to store the file descriptor while waiting for an
  24075. ** opportunity to either close or reuse it.
  24076. */
  24077. struct UnixUnusedFd {
  24078. int fd; /* File descriptor to close */
  24079. int flags; /* Flags this file descriptor was opened with */
  24080. UnixUnusedFd *pNext; /* Next unused file descriptor on same file */
  24081. };
  24082. /*
  24083. ** The unixFile structure is subclass of sqlite3_file specific to the unix
  24084. ** VFS implementations.
  24085. */
  24086. typedef struct unixFile unixFile;
  24087. struct unixFile {
  24088. sqlite3_io_methods const *pMethod; /* Always the first entry */
  24089. sqlite3_vfs *pVfs; /* The VFS that created this unixFile */
  24090. unixInodeInfo *pInode; /* Info about locks on this inode */
  24091. int h; /* The file descriptor */
  24092. unsigned char eFileLock; /* The type of lock held on this fd */
  24093. unsigned short int ctrlFlags; /* Behavioral bits. UNIXFILE_* flags */
  24094. int lastErrno; /* The unix errno from last I/O error */
  24095. void *lockingContext; /* Locking style specific state */
  24096. UnixUnusedFd *pUnused; /* Pre-allocated UnixUnusedFd */
  24097. const char *zPath; /* Name of the file */
  24098. unixShm *pShm; /* Shared memory segment information */
  24099. int szChunk; /* Configured by FCNTL_CHUNK_SIZE */
  24100. #if SQLITE_MAX_MMAP_SIZE>0
  24101. int nFetchOut; /* Number of outstanding xFetch refs */
  24102. sqlite3_int64 mmapSize; /* Usable size of mapping at pMapRegion */
  24103. sqlite3_int64 mmapSizeActual; /* Actual size of mapping at pMapRegion */
  24104. sqlite3_int64 mmapSizeMax; /* Configured FCNTL_MMAP_SIZE value */
  24105. void *pMapRegion; /* Memory mapped region */
  24106. #endif
  24107. #ifdef __QNXNTO__
  24108. int sectorSize; /* Device sector size */
  24109. int deviceCharacteristics; /* Precomputed device characteristics */
  24110. #endif
  24111. #if SQLITE_ENABLE_LOCKING_STYLE
  24112. int openFlags; /* The flags specified at open() */
  24113. #endif
  24114. #if SQLITE_ENABLE_LOCKING_STYLE || defined(__APPLE__)
  24115. unsigned fsFlags; /* cached details from statfs() */
  24116. #endif
  24117. #if OS_VXWORKS
  24118. struct vxworksFileId *pId; /* Unique file ID */
  24119. #endif
  24120. #ifdef SQLITE_DEBUG
  24121. /* The next group of variables are used to track whether or not the
  24122. ** transaction counter in bytes 24-27 of database files are updated
  24123. ** whenever any part of the database changes. An assertion fault will
  24124. ** occur if a file is updated without also updating the transaction
  24125. ** counter. This test is made to avoid new problems similar to the
  24126. ** one described by ticket #3584.
  24127. */
  24128. unsigned char transCntrChng; /* True if the transaction counter changed */
  24129. unsigned char dbUpdate; /* True if any part of database file changed */
  24130. unsigned char inNormalWrite; /* True if in a normal write operation */
  24131. #endif
  24132. #ifdef SQLITE_TEST
  24133. /* In test mode, increase the size of this structure a bit so that
  24134. ** it is larger than the struct CrashFile defined in test6.c.
  24135. */
  24136. char aPadding[32];
  24137. #endif
  24138. };
  24139. /* This variable holds the process id (pid) from when the xRandomness()
  24140. ** method was called. If xOpen() is called from a different process id,
  24141. ** indicating that a fork() has occurred, the PRNG will be reset.
  24142. */
  24143. static pid_t randomnessPid = 0;
  24144. /*
  24145. ** Allowed values for the unixFile.ctrlFlags bitmask:
  24146. */
  24147. #define UNIXFILE_EXCL 0x01 /* Connections from one process only */
  24148. #define UNIXFILE_RDONLY 0x02 /* Connection is read only */
  24149. #define UNIXFILE_PERSIST_WAL 0x04 /* Persistent WAL mode */
  24150. #ifndef SQLITE_DISABLE_DIRSYNC
  24151. # define UNIXFILE_DIRSYNC 0x08 /* Directory sync needed */
  24152. #else
  24153. # define UNIXFILE_DIRSYNC 0x00
  24154. #endif
  24155. #define UNIXFILE_PSOW 0x10 /* SQLITE_IOCAP_POWERSAFE_OVERWRITE */
  24156. #define UNIXFILE_DELETE 0x20 /* Delete on close */
  24157. #define UNIXFILE_URI 0x40 /* Filename might have query parameters */
  24158. #define UNIXFILE_NOLOCK 0x80 /* Do no file locking */
  24159. #define UNIXFILE_WARNED 0x0100 /* verifyDbFile() warnings issued */
  24160. #define UNIXFILE_BLOCK 0x0200 /* Next SHM lock might block */
  24161. /*
  24162. ** Include code that is common to all os_*.c files
  24163. */
  24164. /************** Include os_common.h in the middle of os_unix.c ***************/
  24165. /************** Begin file os_common.h ***************************************/
  24166. /*
  24167. ** 2004 May 22
  24168. **
  24169. ** The author disclaims copyright to this source code. In place of
  24170. ** a legal notice, here is a blessing:
  24171. **
  24172. ** May you do good and not evil.
  24173. ** May you find forgiveness for yourself and forgive others.
  24174. ** May you share freely, never taking more than you give.
  24175. **
  24176. ******************************************************************************
  24177. **
  24178. ** This file contains macros and a little bit of code that is common to
  24179. ** all of the platform-specific files (os_*.c) and is #included into those
  24180. ** files.
  24181. **
  24182. ** This file should be #included by the os_*.c files only. It is not a
  24183. ** general purpose header file.
  24184. */
  24185. #ifndef _OS_COMMON_H_
  24186. #define _OS_COMMON_H_
  24187. /*
  24188. ** At least two bugs have slipped in because we changed the MEMORY_DEBUG
  24189. ** macro to SQLITE_DEBUG and some older makefiles have not yet made the
  24190. ** switch. The following code should catch this problem at compile-time.
  24191. */
  24192. #ifdef MEMORY_DEBUG
  24193. # error "The MEMORY_DEBUG macro is obsolete. Use SQLITE_DEBUG instead."
  24194. #endif
  24195. /*
  24196. ** Macros for performance tracing. Normally turned off. Only works
  24197. ** on i486 hardware.
  24198. */
  24199. #ifdef SQLITE_PERFORMANCE_TRACE
  24200. /*
  24201. ** hwtime.h contains inline assembler code for implementing
  24202. ** high-performance timing routines.
  24203. */
  24204. /************** Include hwtime.h in the middle of os_common.h ****************/
  24205. /************** Begin file hwtime.h ******************************************/
  24206. /*
  24207. ** 2008 May 27
  24208. **
  24209. ** The author disclaims copyright to this source code. In place of
  24210. ** a legal notice, here is a blessing:
  24211. **
  24212. ** May you do good and not evil.
  24213. ** May you find forgiveness for yourself and forgive others.
  24214. ** May you share freely, never taking more than you give.
  24215. **
  24216. ******************************************************************************
  24217. **
  24218. ** This file contains inline asm code for retrieving "high-performance"
  24219. ** counters for x86 class CPUs.
  24220. */
  24221. #ifndef _HWTIME_H_
  24222. #define _HWTIME_H_
  24223. /*
  24224. ** The following routine only works on pentium-class (or newer) processors.
  24225. ** It uses the RDTSC opcode to read the cycle count value out of the
  24226. ** processor and returns that value. This can be used for high-res
  24227. ** profiling.
  24228. */
  24229. #if (defined(__GNUC__) || defined(_MSC_VER)) && \
  24230. (defined(i386) || defined(__i386__) || defined(_M_IX86))
  24231. #if defined(__GNUC__)
  24232. __inline__ sqlite_uint64 sqlite3Hwtime(void){
  24233. unsigned int lo, hi;
  24234. __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
  24235. return (sqlite_uint64)hi << 32 | lo;
  24236. }
  24237. #elif defined(_MSC_VER)
  24238. __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
  24239. __asm {
  24240. rdtsc
  24241. ret ; return value at EDX:EAX
  24242. }
  24243. }
  24244. #endif
  24245. #elif (defined(__GNUC__) && defined(__x86_64__))
  24246. __inline__ sqlite_uint64 sqlite3Hwtime(void){
  24247. unsigned long val;
  24248. __asm__ __volatile__ ("rdtsc" : "=A" (val));
  24249. return val;
  24250. }
  24251. #elif (defined(__GNUC__) && defined(__ppc__))
  24252. __inline__ sqlite_uint64 sqlite3Hwtime(void){
  24253. unsigned long long retval;
  24254. unsigned long junk;
  24255. __asm__ __volatile__ ("\n\
  24256. 1: mftbu %1\n\
  24257. mftb %L0\n\
  24258. mftbu %0\n\
  24259. cmpw %0,%1\n\
  24260. bne 1b"
  24261. : "=r" (retval), "=r" (junk));
  24262. return retval;
  24263. }
  24264. #else
  24265. #error Need implementation of sqlite3Hwtime() for your platform.
  24266. /*
  24267. ** To compile without implementing sqlite3Hwtime() for your platform,
  24268. ** you can remove the above #error and use the following
  24269. ** stub function. You will lose timing support for many
  24270. ** of the debugging and testing utilities, but it should at
  24271. ** least compile and run.
  24272. */
  24273. SQLITE_PRIVATE sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
  24274. #endif
  24275. #endif /* !defined(_HWTIME_H_) */
  24276. /************** End of hwtime.h **********************************************/
  24277. /************** Continuing where we left off in os_common.h ******************/
  24278. static sqlite_uint64 g_start;
  24279. static sqlite_uint64 g_elapsed;
  24280. #define TIMER_START g_start=sqlite3Hwtime()
  24281. #define TIMER_END g_elapsed=sqlite3Hwtime()-g_start
  24282. #define TIMER_ELAPSED g_elapsed
  24283. #else
  24284. #define TIMER_START
  24285. #define TIMER_END
  24286. #define TIMER_ELAPSED ((sqlite_uint64)0)
  24287. #endif
  24288. /*
  24289. ** If we compile with the SQLITE_TEST macro set, then the following block
  24290. ** of code will give us the ability to simulate a disk I/O error. This
  24291. ** is used for testing the I/O recovery logic.
  24292. */
  24293. #ifdef SQLITE_TEST
  24294. SQLITE_API int sqlite3_io_error_hit = 0; /* Total number of I/O Errors */
  24295. SQLITE_API int sqlite3_io_error_hardhit = 0; /* Number of non-benign errors */
  24296. SQLITE_API int sqlite3_io_error_pending = 0; /* Count down to first I/O error */
  24297. SQLITE_API int sqlite3_io_error_persist = 0; /* True if I/O errors persist */
  24298. SQLITE_API int sqlite3_io_error_benign = 0; /* True if errors are benign */
  24299. SQLITE_API int sqlite3_diskfull_pending = 0;
  24300. SQLITE_API int sqlite3_diskfull = 0;
  24301. #define SimulateIOErrorBenign(X) sqlite3_io_error_benign=(X)
  24302. #define SimulateIOError(CODE) \
  24303. if( (sqlite3_io_error_persist && sqlite3_io_error_hit) \
  24304. || sqlite3_io_error_pending-- == 1 ) \
  24305. { local_ioerr(); CODE; }
  24306. static void local_ioerr(){
  24307. IOTRACE(("IOERR\n"));
  24308. sqlite3_io_error_hit++;
  24309. if( !sqlite3_io_error_benign ) sqlite3_io_error_hardhit++;
  24310. }
  24311. #define SimulateDiskfullError(CODE) \
  24312. if( sqlite3_diskfull_pending ){ \
  24313. if( sqlite3_diskfull_pending == 1 ){ \
  24314. local_ioerr(); \
  24315. sqlite3_diskfull = 1; \
  24316. sqlite3_io_error_hit = 1; \
  24317. CODE; \
  24318. }else{ \
  24319. sqlite3_diskfull_pending--; \
  24320. } \
  24321. }
  24322. #else
  24323. #define SimulateIOErrorBenign(X)
  24324. #define SimulateIOError(A)
  24325. #define SimulateDiskfullError(A)
  24326. #endif
  24327. /*
  24328. ** When testing, keep a count of the number of open files.
  24329. */
  24330. #ifdef SQLITE_TEST
  24331. SQLITE_API int sqlite3_open_file_count = 0;
  24332. #define OpenCounter(X) sqlite3_open_file_count+=(X)
  24333. #else
  24334. #define OpenCounter(X)
  24335. #endif
  24336. #endif /* !defined(_OS_COMMON_H_) */
  24337. /************** End of os_common.h *******************************************/
  24338. /************** Continuing where we left off in os_unix.c ********************/
  24339. /*
  24340. ** Define various macros that are missing from some systems.
  24341. */
  24342. #ifndef O_LARGEFILE
  24343. # define O_LARGEFILE 0
  24344. #endif
  24345. #ifdef SQLITE_DISABLE_LFS
  24346. # undef O_LARGEFILE
  24347. # define O_LARGEFILE 0
  24348. #endif
  24349. #ifndef O_NOFOLLOW
  24350. # define O_NOFOLLOW 0
  24351. #endif
  24352. #ifndef O_BINARY
  24353. # define O_BINARY 0
  24354. #endif
  24355. /*
  24356. ** The threadid macro resolves to the thread-id or to 0. Used for
  24357. ** testing and debugging only.
  24358. */
  24359. #if SQLITE_THREADSAFE
  24360. #define threadid pthread_self()
  24361. #else
  24362. #define threadid 0
  24363. #endif
  24364. /*
  24365. ** HAVE_MREMAP defaults to true on Linux and false everywhere else.
  24366. */
  24367. #if !defined(HAVE_MREMAP)
  24368. # if defined(__linux__) && defined(_GNU_SOURCE)
  24369. # define HAVE_MREMAP 1
  24370. # else
  24371. # define HAVE_MREMAP 0
  24372. # endif
  24373. #endif
  24374. /*
  24375. ** Explicitly call the 64-bit version of lseek() on Android. Otherwise, lseek()
  24376. ** is the 32-bit version, even if _FILE_OFFSET_BITS=64 is defined.
  24377. */
  24378. #ifdef __ANDROID__
  24379. # define lseek lseek64
  24380. #endif
  24381. /*
  24382. ** Different Unix systems declare open() in different ways. Same use
  24383. ** open(const char*,int,mode_t). Others use open(const char*,int,...).
  24384. ** The difference is important when using a pointer to the function.
  24385. **
  24386. ** The safest way to deal with the problem is to always use this wrapper
  24387. ** which always has the same well-defined interface.
  24388. */
  24389. static int posixOpen(const char *zFile, int flags, int mode){
  24390. return open(zFile, flags, mode);
  24391. }
  24392. /*
  24393. ** On some systems, calls to fchown() will trigger a message in a security
  24394. ** log if they come from non-root processes. So avoid calling fchown() if
  24395. ** we are not running as root.
  24396. */
  24397. static int posixFchown(int fd, uid_t uid, gid_t gid){
  24398. #if OS_VXWORKS
  24399. return 0;
  24400. #else
  24401. return geteuid() ? 0 : fchown(fd,uid,gid);
  24402. #endif
  24403. }
  24404. /* Forward reference */
  24405. static int openDirectory(const char*, int*);
  24406. static int unixGetpagesize(void);
  24407. /*
  24408. ** Many system calls are accessed through pointer-to-functions so that
  24409. ** they may be overridden at runtime to facilitate fault injection during
  24410. ** testing and sandboxing. The following array holds the names and pointers
  24411. ** to all overrideable system calls.
  24412. */
  24413. static struct unix_syscall {
  24414. const char *zName; /* Name of the system call */
  24415. sqlite3_syscall_ptr pCurrent; /* Current value of the system call */
  24416. sqlite3_syscall_ptr pDefault; /* Default value */
  24417. } aSyscall[] = {
  24418. { "open", (sqlite3_syscall_ptr)posixOpen, 0 },
  24419. #define osOpen ((int(*)(const char*,int,int))aSyscall[0].pCurrent)
  24420. { "close", (sqlite3_syscall_ptr)close, 0 },
  24421. #define osClose ((int(*)(int))aSyscall[1].pCurrent)
  24422. { "access", (sqlite3_syscall_ptr)access, 0 },
  24423. #define osAccess ((int(*)(const char*,int))aSyscall[2].pCurrent)
  24424. { "getcwd", (sqlite3_syscall_ptr)getcwd, 0 },
  24425. #define osGetcwd ((char*(*)(char*,size_t))aSyscall[3].pCurrent)
  24426. { "stat", (sqlite3_syscall_ptr)stat, 0 },
  24427. #define osStat ((int(*)(const char*,struct stat*))aSyscall[4].pCurrent)
  24428. /*
  24429. ** The DJGPP compiler environment looks mostly like Unix, but it
  24430. ** lacks the fcntl() system call. So redefine fcntl() to be something
  24431. ** that always succeeds. This means that locking does not occur under
  24432. ** DJGPP. But it is DOS - what did you expect?
  24433. */
  24434. #ifdef __DJGPP__
  24435. { "fstat", 0, 0 },
  24436. #define osFstat(a,b,c) 0
  24437. #else
  24438. { "fstat", (sqlite3_syscall_ptr)fstat, 0 },
  24439. #define osFstat ((int(*)(int,struct stat*))aSyscall[5].pCurrent)
  24440. #endif
  24441. { "ftruncate", (sqlite3_syscall_ptr)ftruncate, 0 },
  24442. #define osFtruncate ((int(*)(int,off_t))aSyscall[6].pCurrent)
  24443. { "fcntl", (sqlite3_syscall_ptr)fcntl, 0 },
  24444. #define osFcntl ((int(*)(int,int,...))aSyscall[7].pCurrent)
  24445. { "read", (sqlite3_syscall_ptr)read, 0 },
  24446. #define osRead ((ssize_t(*)(int,void*,size_t))aSyscall[8].pCurrent)
  24447. #if defined(USE_PREAD) || SQLITE_ENABLE_LOCKING_STYLE
  24448. { "pread", (sqlite3_syscall_ptr)pread, 0 },
  24449. #else
  24450. { "pread", (sqlite3_syscall_ptr)0, 0 },
  24451. #endif
  24452. #define osPread ((ssize_t(*)(int,void*,size_t,off_t))aSyscall[9].pCurrent)
  24453. #if defined(USE_PREAD64)
  24454. { "pread64", (sqlite3_syscall_ptr)pread64, 0 },
  24455. #else
  24456. { "pread64", (sqlite3_syscall_ptr)0, 0 },
  24457. #endif
  24458. #define osPread64 ((ssize_t(*)(int,void*,size_t,off_t))aSyscall[10].pCurrent)
  24459. { "write", (sqlite3_syscall_ptr)write, 0 },
  24460. #define osWrite ((ssize_t(*)(int,const void*,size_t))aSyscall[11].pCurrent)
  24461. #if defined(USE_PREAD) || SQLITE_ENABLE_LOCKING_STYLE
  24462. { "pwrite", (sqlite3_syscall_ptr)pwrite, 0 },
  24463. #else
  24464. { "pwrite", (sqlite3_syscall_ptr)0, 0 },
  24465. #endif
  24466. #define osPwrite ((ssize_t(*)(int,const void*,size_t,off_t))\
  24467. aSyscall[12].pCurrent)
  24468. #if defined(USE_PREAD64)
  24469. { "pwrite64", (sqlite3_syscall_ptr)pwrite64, 0 },
  24470. #else
  24471. { "pwrite64", (sqlite3_syscall_ptr)0, 0 },
  24472. #endif
  24473. #define osPwrite64 ((ssize_t(*)(int,const void*,size_t,off_t))\
  24474. aSyscall[13].pCurrent)
  24475. { "fchmod", (sqlite3_syscall_ptr)fchmod, 0 },
  24476. #define osFchmod ((int(*)(int,mode_t))aSyscall[14].pCurrent)
  24477. #if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
  24478. { "fallocate", (sqlite3_syscall_ptr)posix_fallocate, 0 },
  24479. #else
  24480. { "fallocate", (sqlite3_syscall_ptr)0, 0 },
  24481. #endif
  24482. #define osFallocate ((int(*)(int,off_t,off_t))aSyscall[15].pCurrent)
  24483. { "unlink", (sqlite3_syscall_ptr)unlink, 0 },
  24484. #define osUnlink ((int(*)(const char*))aSyscall[16].pCurrent)
  24485. { "openDirectory", (sqlite3_syscall_ptr)openDirectory, 0 },
  24486. #define osOpenDirectory ((int(*)(const char*,int*))aSyscall[17].pCurrent)
  24487. { "mkdir", (sqlite3_syscall_ptr)mkdir, 0 },
  24488. #define osMkdir ((int(*)(const char*,mode_t))aSyscall[18].pCurrent)
  24489. { "rmdir", (sqlite3_syscall_ptr)rmdir, 0 },
  24490. #define osRmdir ((int(*)(const char*))aSyscall[19].pCurrent)
  24491. { "fchown", (sqlite3_syscall_ptr)posixFchown, 0 },
  24492. #define osFchown ((int(*)(int,uid_t,gid_t))aSyscall[20].pCurrent)
  24493. #if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
  24494. { "mmap", (sqlite3_syscall_ptr)mmap, 0 },
  24495. #define osMmap ((void*(*)(void*,size_t,int,int,int,off_t))aSyscall[21].pCurrent)
  24496. { "munmap", (sqlite3_syscall_ptr)munmap, 0 },
  24497. #define osMunmap ((void*(*)(void*,size_t))aSyscall[22].pCurrent)
  24498. #if HAVE_MREMAP
  24499. { "mremap", (sqlite3_syscall_ptr)mremap, 0 },
  24500. #else
  24501. { "mremap", (sqlite3_syscall_ptr)0, 0 },
  24502. #endif
  24503. #define osMremap ((void*(*)(void*,size_t,size_t,int,...))aSyscall[23].pCurrent)
  24504. { "getpagesize", (sqlite3_syscall_ptr)unixGetpagesize, 0 },
  24505. #define osGetpagesize ((int(*)(void))aSyscall[24].pCurrent)
  24506. #endif
  24507. }; /* End of the overrideable system calls */
  24508. /*
  24509. ** This is the xSetSystemCall() method of sqlite3_vfs for all of the
  24510. ** "unix" VFSes. Return SQLITE_OK opon successfully updating the
  24511. ** system call pointer, or SQLITE_NOTFOUND if there is no configurable
  24512. ** system call named zName.
  24513. */
  24514. static int unixSetSystemCall(
  24515. sqlite3_vfs *pNotUsed, /* The VFS pointer. Not used */
  24516. const char *zName, /* Name of system call to override */
  24517. sqlite3_syscall_ptr pNewFunc /* Pointer to new system call value */
  24518. ){
  24519. unsigned int i;
  24520. int rc = SQLITE_NOTFOUND;
  24521. UNUSED_PARAMETER(pNotUsed);
  24522. if( zName==0 ){
  24523. /* If no zName is given, restore all system calls to their default
  24524. ** settings and return NULL
  24525. */
  24526. rc = SQLITE_OK;
  24527. for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
  24528. if( aSyscall[i].pDefault ){
  24529. aSyscall[i].pCurrent = aSyscall[i].pDefault;
  24530. }
  24531. }
  24532. }else{
  24533. /* If zName is specified, operate on only the one system call
  24534. ** specified.
  24535. */
  24536. for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
  24537. if( strcmp(zName, aSyscall[i].zName)==0 ){
  24538. if( aSyscall[i].pDefault==0 ){
  24539. aSyscall[i].pDefault = aSyscall[i].pCurrent;
  24540. }
  24541. rc = SQLITE_OK;
  24542. if( pNewFunc==0 ) pNewFunc = aSyscall[i].pDefault;
  24543. aSyscall[i].pCurrent = pNewFunc;
  24544. break;
  24545. }
  24546. }
  24547. }
  24548. return rc;
  24549. }
  24550. /*
  24551. ** Return the value of a system call. Return NULL if zName is not a
  24552. ** recognized system call name. NULL is also returned if the system call
  24553. ** is currently undefined.
  24554. */
  24555. static sqlite3_syscall_ptr unixGetSystemCall(
  24556. sqlite3_vfs *pNotUsed,
  24557. const char *zName
  24558. ){
  24559. unsigned int i;
  24560. UNUSED_PARAMETER(pNotUsed);
  24561. for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
  24562. if( strcmp(zName, aSyscall[i].zName)==0 ) return aSyscall[i].pCurrent;
  24563. }
  24564. return 0;
  24565. }
  24566. /*
  24567. ** Return the name of the first system call after zName. If zName==NULL
  24568. ** then return the name of the first system call. Return NULL if zName
  24569. ** is the last system call or if zName is not the name of a valid
  24570. ** system call.
  24571. */
  24572. static const char *unixNextSystemCall(sqlite3_vfs *p, const char *zName){
  24573. int i = -1;
  24574. UNUSED_PARAMETER(p);
  24575. if( zName ){
  24576. for(i=0; i<ArraySize(aSyscall)-1; i++){
  24577. if( strcmp(zName, aSyscall[i].zName)==0 ) break;
  24578. }
  24579. }
  24580. for(i++; i<ArraySize(aSyscall); i++){
  24581. if( aSyscall[i].pCurrent!=0 ) return aSyscall[i].zName;
  24582. }
  24583. return 0;
  24584. }
  24585. /*
  24586. ** Do not accept any file descriptor less than this value, in order to avoid
  24587. ** opening database file using file descriptors that are commonly used for
  24588. ** standard input, output, and error.
  24589. */
  24590. #ifndef SQLITE_MINIMUM_FILE_DESCRIPTOR
  24591. # define SQLITE_MINIMUM_FILE_DESCRIPTOR 3
  24592. #endif
  24593. /*
  24594. ** Invoke open(). Do so multiple times, until it either succeeds or
  24595. ** fails for some reason other than EINTR.
  24596. **
  24597. ** If the file creation mode "m" is 0 then set it to the default for
  24598. ** SQLite. The default is SQLITE_DEFAULT_FILE_PERMISSIONS (normally
  24599. ** 0644) as modified by the system umask. If m is not 0, then
  24600. ** make the file creation mode be exactly m ignoring the umask.
  24601. **
  24602. ** The m parameter will be non-zero only when creating -wal, -journal,
  24603. ** and -shm files. We want those files to have *exactly* the same
  24604. ** permissions as their original database, unadulterated by the umask.
  24605. ** In that way, if a database file is -rw-rw-rw or -rw-rw-r-, and a
  24606. ** transaction crashes and leaves behind hot journals, then any
  24607. ** process that is able to write to the database will also be able to
  24608. ** recover the hot journals.
  24609. */
  24610. static int robust_open(const char *z, int f, mode_t m){
  24611. int fd;
  24612. mode_t m2 = m ? m : SQLITE_DEFAULT_FILE_PERMISSIONS;
  24613. while(1){
  24614. #if defined(O_CLOEXEC)
  24615. fd = osOpen(z,f|O_CLOEXEC,m2);
  24616. #else
  24617. fd = osOpen(z,f,m2);
  24618. #endif
  24619. if( fd<0 ){
  24620. if( errno==EINTR ) continue;
  24621. break;
  24622. }
  24623. if( fd>=SQLITE_MINIMUM_FILE_DESCRIPTOR ) break;
  24624. osClose(fd);
  24625. sqlite3_log(SQLITE_WARNING,
  24626. "attempt to open \"%s\" as file descriptor %d", z, fd);
  24627. fd = -1;
  24628. if( osOpen("/dev/null", f, m)<0 ) break;
  24629. }
  24630. if( fd>=0 ){
  24631. if( m!=0 ){
  24632. struct stat statbuf;
  24633. if( osFstat(fd, &statbuf)==0
  24634. && statbuf.st_size==0
  24635. && (statbuf.st_mode&0777)!=m
  24636. ){
  24637. osFchmod(fd, m);
  24638. }
  24639. }
  24640. #if defined(FD_CLOEXEC) && (!defined(O_CLOEXEC) || O_CLOEXEC==0)
  24641. osFcntl(fd, F_SETFD, osFcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
  24642. #endif
  24643. }
  24644. return fd;
  24645. }
  24646. /*
  24647. ** Helper functions to obtain and relinquish the global mutex. The
  24648. ** global mutex is used to protect the unixInodeInfo and
  24649. ** vxworksFileId objects used by this file, all of which may be
  24650. ** shared by multiple threads.
  24651. **
  24652. ** Function unixMutexHeld() is used to assert() that the global mutex
  24653. ** is held when required. This function is only used as part of assert()
  24654. ** statements. e.g.
  24655. **
  24656. ** unixEnterMutex()
  24657. ** assert( unixMutexHeld() );
  24658. ** unixEnterLeave()
  24659. */
  24660. static void unixEnterMutex(void){
  24661. sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
  24662. }
  24663. static void unixLeaveMutex(void){
  24664. sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
  24665. }
  24666. #ifdef SQLITE_DEBUG
  24667. static int unixMutexHeld(void) {
  24668. return sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
  24669. }
  24670. #endif
  24671. #ifdef SQLITE_HAVE_OS_TRACE
  24672. /*
  24673. ** Helper function for printing out trace information from debugging
  24674. ** binaries. This returns the string representation of the supplied
  24675. ** integer lock-type.
  24676. */
  24677. static const char *azFileLock(int eFileLock){
  24678. switch( eFileLock ){
  24679. case NO_LOCK: return "NONE";
  24680. case SHARED_LOCK: return "SHARED";
  24681. case RESERVED_LOCK: return "RESERVED";
  24682. case PENDING_LOCK: return "PENDING";
  24683. case EXCLUSIVE_LOCK: return "EXCLUSIVE";
  24684. }
  24685. return "ERROR";
  24686. }
  24687. #endif
  24688. #ifdef SQLITE_LOCK_TRACE
  24689. /*
  24690. ** Print out information about all locking operations.
  24691. **
  24692. ** This routine is used for troubleshooting locks on multithreaded
  24693. ** platforms. Enable by compiling with the -DSQLITE_LOCK_TRACE
  24694. ** command-line option on the compiler. This code is normally
  24695. ** turned off.
  24696. */
  24697. static int lockTrace(int fd, int op, struct flock *p){
  24698. char *zOpName, *zType;
  24699. int s;
  24700. int savedErrno;
  24701. if( op==F_GETLK ){
  24702. zOpName = "GETLK";
  24703. }else if( op==F_SETLK ){
  24704. zOpName = "SETLK";
  24705. }else{
  24706. s = osFcntl(fd, op, p);
  24707. sqlite3DebugPrintf("fcntl unknown %d %d %d\n", fd, op, s);
  24708. return s;
  24709. }
  24710. if( p->l_type==F_RDLCK ){
  24711. zType = "RDLCK";
  24712. }else if( p->l_type==F_WRLCK ){
  24713. zType = "WRLCK";
  24714. }else if( p->l_type==F_UNLCK ){
  24715. zType = "UNLCK";
  24716. }else{
  24717. assert( 0 );
  24718. }
  24719. assert( p->l_whence==SEEK_SET );
  24720. s = osFcntl(fd, op, p);
  24721. savedErrno = errno;
  24722. sqlite3DebugPrintf("fcntl %d %d %s %s %d %d %d %d\n",
  24723. threadid, fd, zOpName, zType, (int)p->l_start, (int)p->l_len,
  24724. (int)p->l_pid, s);
  24725. if( s==(-1) && op==F_SETLK && (p->l_type==F_RDLCK || p->l_type==F_WRLCK) ){
  24726. struct flock l2;
  24727. l2 = *p;
  24728. osFcntl(fd, F_GETLK, &l2);
  24729. if( l2.l_type==F_RDLCK ){
  24730. zType = "RDLCK";
  24731. }else if( l2.l_type==F_WRLCK ){
  24732. zType = "WRLCK";
  24733. }else if( l2.l_type==F_UNLCK ){
  24734. zType = "UNLCK";
  24735. }else{
  24736. assert( 0 );
  24737. }
  24738. sqlite3DebugPrintf("fcntl-failure-reason: %s %d %d %d\n",
  24739. zType, (int)l2.l_start, (int)l2.l_len, (int)l2.l_pid);
  24740. }
  24741. errno = savedErrno;
  24742. return s;
  24743. }
  24744. #undef osFcntl
  24745. #define osFcntl lockTrace
  24746. #endif /* SQLITE_LOCK_TRACE */
  24747. /*
  24748. ** Retry ftruncate() calls that fail due to EINTR
  24749. **
  24750. ** All calls to ftruncate() within this file should be made through
  24751. ** this wrapper. On the Android platform, bypassing the logic below
  24752. ** could lead to a corrupt database.
  24753. */
  24754. static int robust_ftruncate(int h, sqlite3_int64 sz){
  24755. int rc;
  24756. #ifdef __ANDROID__
  24757. /* On Android, ftruncate() always uses 32-bit offsets, even if
  24758. ** _FILE_OFFSET_BITS=64 is defined. This means it is unsafe to attempt to
  24759. ** truncate a file to any size larger than 2GiB. Silently ignore any
  24760. ** such attempts. */
  24761. if( sz>(sqlite3_int64)0x7FFFFFFF ){
  24762. rc = SQLITE_OK;
  24763. }else
  24764. #endif
  24765. do{ rc = osFtruncate(h,sz); }while( rc<0 && errno==EINTR );
  24766. return rc;
  24767. }
  24768. /*
  24769. ** This routine translates a standard POSIX errno code into something
  24770. ** useful to the clients of the sqlite3 functions. Specifically, it is
  24771. ** intended to translate a variety of "try again" errors into SQLITE_BUSY
  24772. ** and a variety of "please close the file descriptor NOW" errors into
  24773. ** SQLITE_IOERR
  24774. **
  24775. ** Errors during initialization of locks, or file system support for locks,
  24776. ** should handle ENOLCK, ENOTSUP, EOPNOTSUPP separately.
  24777. */
  24778. static int sqliteErrorFromPosixError(int posixError, int sqliteIOErr) {
  24779. switch (posixError) {
  24780. #if 0
  24781. /* At one point this code was not commented out. In theory, this branch
  24782. ** should never be hit, as this function should only be called after
  24783. ** a locking-related function (i.e. fcntl()) has returned non-zero with
  24784. ** the value of errno as the first argument. Since a system call has failed,
  24785. ** errno should be non-zero.
  24786. **
  24787. ** Despite this, if errno really is zero, we still don't want to return
  24788. ** SQLITE_OK. The system call failed, and *some* SQLite error should be
  24789. ** propagated back to the caller. Commenting this branch out means errno==0
  24790. ** will be handled by the "default:" case below.
  24791. */
  24792. case 0:
  24793. return SQLITE_OK;
  24794. #endif
  24795. case EAGAIN:
  24796. case ETIMEDOUT:
  24797. case EBUSY:
  24798. case EINTR:
  24799. case ENOLCK:
  24800. /* random NFS retry error, unless during file system support
  24801. * introspection, in which it actually means what it says */
  24802. return SQLITE_BUSY;
  24803. case EACCES:
  24804. /* EACCES is like EAGAIN during locking operations, but not any other time*/
  24805. if( (sqliteIOErr == SQLITE_IOERR_LOCK) ||
  24806. (sqliteIOErr == SQLITE_IOERR_UNLOCK) ||
  24807. (sqliteIOErr == SQLITE_IOERR_RDLOCK) ||
  24808. (sqliteIOErr == SQLITE_IOERR_CHECKRESERVEDLOCK) ){
  24809. return SQLITE_BUSY;
  24810. }
  24811. /* else fall through */
  24812. case EPERM:
  24813. return SQLITE_PERM;
  24814. #if EOPNOTSUPP!=ENOTSUP
  24815. case EOPNOTSUPP:
  24816. /* something went terribly awry, unless during file system support
  24817. * introspection, in which it actually means what it says */
  24818. #endif
  24819. #ifdef ENOTSUP
  24820. case ENOTSUP:
  24821. /* invalid fd, unless during file system support introspection, in which
  24822. * it actually means what it says */
  24823. #endif
  24824. case EIO:
  24825. case EBADF:
  24826. case EINVAL:
  24827. case ENOTCONN:
  24828. case ENODEV:
  24829. case ENXIO:
  24830. case ENOENT:
  24831. #ifdef ESTALE /* ESTALE is not defined on Interix systems */
  24832. case ESTALE:
  24833. #endif
  24834. case ENOSYS:
  24835. /* these should force the client to close the file and reconnect */
  24836. default:
  24837. return sqliteIOErr;
  24838. }
  24839. }
  24840. /******************************************************************************
  24841. ****************** Begin Unique File ID Utility Used By VxWorks ***************
  24842. **
  24843. ** On most versions of unix, we can get a unique ID for a file by concatenating
  24844. ** the device number and the inode number. But this does not work on VxWorks.
  24845. ** On VxWorks, a unique file id must be based on the canonical filename.
  24846. **
  24847. ** A pointer to an instance of the following structure can be used as a
  24848. ** unique file ID in VxWorks. Each instance of this structure contains
  24849. ** a copy of the canonical filename. There is also a reference count.
  24850. ** The structure is reclaimed when the number of pointers to it drops to
  24851. ** zero.
  24852. **
  24853. ** There are never very many files open at one time and lookups are not
  24854. ** a performance-critical path, so it is sufficient to put these
  24855. ** structures on a linked list.
  24856. */
  24857. struct vxworksFileId {
  24858. struct vxworksFileId *pNext; /* Next in a list of them all */
  24859. int nRef; /* Number of references to this one */
  24860. int nName; /* Length of the zCanonicalName[] string */
  24861. char *zCanonicalName; /* Canonical filename */
  24862. };
  24863. #if OS_VXWORKS
  24864. /*
  24865. ** All unique filenames are held on a linked list headed by this
  24866. ** variable:
  24867. */
  24868. static struct vxworksFileId *vxworksFileList = 0;
  24869. /*
  24870. ** Simplify a filename into its canonical form
  24871. ** by making the following changes:
  24872. **
  24873. ** * removing any trailing and duplicate /
  24874. ** * convert /./ into just /
  24875. ** * convert /A/../ where A is any simple name into just /
  24876. **
  24877. ** Changes are made in-place. Return the new name length.
  24878. **
  24879. ** The original filename is in z[0..n-1]. Return the number of
  24880. ** characters in the simplified name.
  24881. */
  24882. static int vxworksSimplifyName(char *z, int n){
  24883. int i, j;
  24884. while( n>1 && z[n-1]=='/' ){ n--; }
  24885. for(i=j=0; i<n; i++){
  24886. if( z[i]=='/' ){
  24887. if( z[i+1]=='/' ) continue;
  24888. if( z[i+1]=='.' && i+2<n && z[i+2]=='/' ){
  24889. i += 1;
  24890. continue;
  24891. }
  24892. if( z[i+1]=='.' && i+3<n && z[i+2]=='.' && z[i+3]=='/' ){
  24893. while( j>0 && z[j-1]!='/' ){ j--; }
  24894. if( j>0 ){ j--; }
  24895. i += 2;
  24896. continue;
  24897. }
  24898. }
  24899. z[j++] = z[i];
  24900. }
  24901. z[j] = 0;
  24902. return j;
  24903. }
  24904. /*
  24905. ** Find a unique file ID for the given absolute pathname. Return
  24906. ** a pointer to the vxworksFileId object. This pointer is the unique
  24907. ** file ID.
  24908. **
  24909. ** The nRef field of the vxworksFileId object is incremented before
  24910. ** the object is returned. A new vxworksFileId object is created
  24911. ** and added to the global list if necessary.
  24912. **
  24913. ** If a memory allocation error occurs, return NULL.
  24914. */
  24915. static struct vxworksFileId *vxworksFindFileId(const char *zAbsoluteName){
  24916. struct vxworksFileId *pNew; /* search key and new file ID */
  24917. struct vxworksFileId *pCandidate; /* For looping over existing file IDs */
  24918. int n; /* Length of zAbsoluteName string */
  24919. assert( zAbsoluteName[0]=='/' );
  24920. n = (int)strlen(zAbsoluteName);
  24921. pNew = sqlite3_malloc64( sizeof(*pNew) + (n+1) );
  24922. if( pNew==0 ) return 0;
  24923. pNew->zCanonicalName = (char*)&pNew[1];
  24924. memcpy(pNew->zCanonicalName, zAbsoluteName, n+1);
  24925. n = vxworksSimplifyName(pNew->zCanonicalName, n);
  24926. /* Search for an existing entry that matching the canonical name.
  24927. ** If found, increment the reference count and return a pointer to
  24928. ** the existing file ID.
  24929. */
  24930. unixEnterMutex();
  24931. for(pCandidate=vxworksFileList; pCandidate; pCandidate=pCandidate->pNext){
  24932. if( pCandidate->nName==n
  24933. && memcmp(pCandidate->zCanonicalName, pNew->zCanonicalName, n)==0
  24934. ){
  24935. sqlite3_free(pNew);
  24936. pCandidate->nRef++;
  24937. unixLeaveMutex();
  24938. return pCandidate;
  24939. }
  24940. }
  24941. /* No match was found. We will make a new file ID */
  24942. pNew->nRef = 1;
  24943. pNew->nName = n;
  24944. pNew->pNext = vxworksFileList;
  24945. vxworksFileList = pNew;
  24946. unixLeaveMutex();
  24947. return pNew;
  24948. }
  24949. /*
  24950. ** Decrement the reference count on a vxworksFileId object. Free
  24951. ** the object when the reference count reaches zero.
  24952. */
  24953. static void vxworksReleaseFileId(struct vxworksFileId *pId){
  24954. unixEnterMutex();
  24955. assert( pId->nRef>0 );
  24956. pId->nRef--;
  24957. if( pId->nRef==0 ){
  24958. struct vxworksFileId **pp;
  24959. for(pp=&vxworksFileList; *pp && *pp!=pId; pp = &((*pp)->pNext)){}
  24960. assert( *pp==pId );
  24961. *pp = pId->pNext;
  24962. sqlite3_free(pId);
  24963. }
  24964. unixLeaveMutex();
  24965. }
  24966. #endif /* OS_VXWORKS */
  24967. /*************** End of Unique File ID Utility Used By VxWorks ****************
  24968. ******************************************************************************/
  24969. /******************************************************************************
  24970. *************************** Posix Advisory Locking ****************************
  24971. **
  24972. ** POSIX advisory locks are broken by design. ANSI STD 1003.1 (1996)
  24973. ** section 6.5.2.2 lines 483 through 490 specify that when a process
  24974. ** sets or clears a lock, that operation overrides any prior locks set
  24975. ** by the same process. It does not explicitly say so, but this implies
  24976. ** that it overrides locks set by the same process using a different
  24977. ** file descriptor. Consider this test case:
  24978. **
  24979. ** int fd1 = open("./file1", O_RDWR|O_CREAT, 0644);
  24980. ** int fd2 = open("./file2", O_RDWR|O_CREAT, 0644);
  24981. **
  24982. ** Suppose ./file1 and ./file2 are really the same file (because
  24983. ** one is a hard or symbolic link to the other) then if you set
  24984. ** an exclusive lock on fd1, then try to get an exclusive lock
  24985. ** on fd2, it works. I would have expected the second lock to
  24986. ** fail since there was already a lock on the file due to fd1.
  24987. ** But not so. Since both locks came from the same process, the
  24988. ** second overrides the first, even though they were on different
  24989. ** file descriptors opened on different file names.
  24990. **
  24991. ** This means that we cannot use POSIX locks to synchronize file access
  24992. ** among competing threads of the same process. POSIX locks will work fine
  24993. ** to synchronize access for threads in separate processes, but not
  24994. ** threads within the same process.
  24995. **
  24996. ** To work around the problem, SQLite has to manage file locks internally
  24997. ** on its own. Whenever a new database is opened, we have to find the
  24998. ** specific inode of the database file (the inode is determined by the
  24999. ** st_dev and st_ino fields of the stat structure that fstat() fills in)
  25000. ** and check for locks already existing on that inode. When locks are
  25001. ** created or removed, we have to look at our own internal record of the
  25002. ** locks to see if another thread has previously set a lock on that same
  25003. ** inode.
  25004. **
  25005. ** (Aside: The use of inode numbers as unique IDs does not work on VxWorks.
  25006. ** For VxWorks, we have to use the alternative unique ID system based on
  25007. ** canonical filename and implemented in the previous division.)
  25008. **
  25009. ** The sqlite3_file structure for POSIX is no longer just an integer file
  25010. ** descriptor. It is now a structure that holds the integer file
  25011. ** descriptor and a pointer to a structure that describes the internal
  25012. ** locks on the corresponding inode. There is one locking structure
  25013. ** per inode, so if the same inode is opened twice, both unixFile structures
  25014. ** point to the same locking structure. The locking structure keeps
  25015. ** a reference count (so we will know when to delete it) and a "cnt"
  25016. ** field that tells us its internal lock status. cnt==0 means the
  25017. ** file is unlocked. cnt==-1 means the file has an exclusive lock.
  25018. ** cnt>0 means there are cnt shared locks on the file.
  25019. **
  25020. ** Any attempt to lock or unlock a file first checks the locking
  25021. ** structure. The fcntl() system call is only invoked to set a
  25022. ** POSIX lock if the internal lock structure transitions between
  25023. ** a locked and an unlocked state.
  25024. **
  25025. ** But wait: there are yet more problems with POSIX advisory locks.
  25026. **
  25027. ** If you close a file descriptor that points to a file that has locks,
  25028. ** all locks on that file that are owned by the current process are
  25029. ** released. To work around this problem, each unixInodeInfo object
  25030. ** maintains a count of the number of pending locks on tha inode.
  25031. ** When an attempt is made to close an unixFile, if there are
  25032. ** other unixFile open on the same inode that are holding locks, the call
  25033. ** to close() the file descriptor is deferred until all of the locks clear.
  25034. ** The unixInodeInfo structure keeps a list of file descriptors that need to
  25035. ** be closed and that list is walked (and cleared) when the last lock
  25036. ** clears.
  25037. **
  25038. ** Yet another problem: LinuxThreads do not play well with posix locks.
  25039. **
  25040. ** Many older versions of linux use the LinuxThreads library which is
  25041. ** not posix compliant. Under LinuxThreads, a lock created by thread
  25042. ** A cannot be modified or overridden by a different thread B.
  25043. ** Only thread A can modify the lock. Locking behavior is correct
  25044. ** if the appliation uses the newer Native Posix Thread Library (NPTL)
  25045. ** on linux - with NPTL a lock created by thread A can override locks
  25046. ** in thread B. But there is no way to know at compile-time which
  25047. ** threading library is being used. So there is no way to know at
  25048. ** compile-time whether or not thread A can override locks on thread B.
  25049. ** One has to do a run-time check to discover the behavior of the
  25050. ** current process.
  25051. **
  25052. ** SQLite used to support LinuxThreads. But support for LinuxThreads
  25053. ** was dropped beginning with version 3.7.0. SQLite will still work with
  25054. ** LinuxThreads provided that (1) there is no more than one connection
  25055. ** per database file in the same process and (2) database connections
  25056. ** do not move across threads.
  25057. */
  25058. /*
  25059. ** An instance of the following structure serves as the key used
  25060. ** to locate a particular unixInodeInfo object.
  25061. */
  25062. struct unixFileId {
  25063. dev_t dev; /* Device number */
  25064. #if OS_VXWORKS
  25065. struct vxworksFileId *pId; /* Unique file ID for vxworks. */
  25066. #else
  25067. ino_t ino; /* Inode number */
  25068. #endif
  25069. };
  25070. /*
  25071. ** An instance of the following structure is allocated for each open
  25072. ** inode. Or, on LinuxThreads, there is one of these structures for
  25073. ** each inode opened by each thread.
  25074. **
  25075. ** A single inode can have multiple file descriptors, so each unixFile
  25076. ** structure contains a pointer to an instance of this object and this
  25077. ** object keeps a count of the number of unixFile pointing to it.
  25078. */
  25079. struct unixInodeInfo {
  25080. struct unixFileId fileId; /* The lookup key */
  25081. int nShared; /* Number of SHARED locks held */
  25082. unsigned char eFileLock; /* One of SHARED_LOCK, RESERVED_LOCK etc. */
  25083. unsigned char bProcessLock; /* An exclusive process lock is held */
  25084. int nRef; /* Number of pointers to this structure */
  25085. unixShmNode *pShmNode; /* Shared memory associated with this inode */
  25086. int nLock; /* Number of outstanding file locks */
  25087. UnixUnusedFd *pUnused; /* Unused file descriptors to close */
  25088. unixInodeInfo *pNext; /* List of all unixInodeInfo objects */
  25089. unixInodeInfo *pPrev; /* .... doubly linked */
  25090. #if SQLITE_ENABLE_LOCKING_STYLE
  25091. unsigned long long sharedByte; /* for AFP simulated shared lock */
  25092. #endif
  25093. #if OS_VXWORKS
  25094. sem_t *pSem; /* Named POSIX semaphore */
  25095. char aSemName[MAX_PATHNAME+2]; /* Name of that semaphore */
  25096. #endif
  25097. };
  25098. /*
  25099. ** A lists of all unixInodeInfo objects.
  25100. */
  25101. static unixInodeInfo *inodeList = 0;
  25102. /*
  25103. **
  25104. ** This function - unixLogError_x(), is only ever called via the macro
  25105. ** unixLogError().
  25106. **
  25107. ** It is invoked after an error occurs in an OS function and errno has been
  25108. ** set. It logs a message using sqlite3_log() containing the current value of
  25109. ** errno and, if possible, the human-readable equivalent from strerror() or
  25110. ** strerror_r().
  25111. **
  25112. ** The first argument passed to the macro should be the error code that
  25113. ** will be returned to SQLite (e.g. SQLITE_IOERR_DELETE, SQLITE_CANTOPEN).
  25114. ** The two subsequent arguments should be the name of the OS function that
  25115. ** failed (e.g. "unlink", "open") and the associated file-system path,
  25116. ** if any.
  25117. */
  25118. #define unixLogError(a,b,c) unixLogErrorAtLine(a,b,c,__LINE__)
  25119. static int unixLogErrorAtLine(
  25120. int errcode, /* SQLite error code */
  25121. const char *zFunc, /* Name of OS function that failed */
  25122. const char *zPath, /* File path associated with error */
  25123. int iLine /* Source line number where error occurred */
  25124. ){
  25125. char *zErr; /* Message from strerror() or equivalent */
  25126. int iErrno = errno; /* Saved syscall error number */
  25127. /* If this is not a threadsafe build (SQLITE_THREADSAFE==0), then use
  25128. ** the strerror() function to obtain the human-readable error message
  25129. ** equivalent to errno. Otherwise, use strerror_r().
  25130. */
  25131. #if SQLITE_THREADSAFE && defined(HAVE_STRERROR_R)
  25132. char aErr[80];
  25133. memset(aErr, 0, sizeof(aErr));
  25134. zErr = aErr;
  25135. /* If STRERROR_R_CHAR_P (set by autoconf scripts) or __USE_GNU is defined,
  25136. ** assume that the system provides the GNU version of strerror_r() that
  25137. ** returns a pointer to a buffer containing the error message. That pointer
  25138. ** may point to aErr[], or it may point to some static storage somewhere.
  25139. ** Otherwise, assume that the system provides the POSIX version of
  25140. ** strerror_r(), which always writes an error message into aErr[].
  25141. **
  25142. ** If the code incorrectly assumes that it is the POSIX version that is
  25143. ** available, the error message will often be an empty string. Not a
  25144. ** huge problem. Incorrectly concluding that the GNU version is available
  25145. ** could lead to a segfault though.
  25146. */
  25147. #if defined(STRERROR_R_CHAR_P) || defined(__USE_GNU)
  25148. zErr =
  25149. # endif
  25150. strerror_r(iErrno, aErr, sizeof(aErr)-1);
  25151. #elif SQLITE_THREADSAFE
  25152. /* This is a threadsafe build, but strerror_r() is not available. */
  25153. zErr = "";
  25154. #else
  25155. /* Non-threadsafe build, use strerror(). */
  25156. zErr = strerror(iErrno);
  25157. #endif
  25158. if( zPath==0 ) zPath = "";
  25159. sqlite3_log(errcode,
  25160. "os_unix.c:%d: (%d) %s(%s) - %s",
  25161. iLine, iErrno, zFunc, zPath, zErr
  25162. );
  25163. return errcode;
  25164. }
  25165. /*
  25166. ** Close a file descriptor.
  25167. **
  25168. ** We assume that close() almost always works, since it is only in a
  25169. ** very sick application or on a very sick platform that it might fail.
  25170. ** If it does fail, simply leak the file descriptor, but do log the
  25171. ** error.
  25172. **
  25173. ** Note that it is not safe to retry close() after EINTR since the
  25174. ** file descriptor might have already been reused by another thread.
  25175. ** So we don't even try to recover from an EINTR. Just log the error
  25176. ** and move on.
  25177. */
  25178. static void robust_close(unixFile *pFile, int h, int lineno){
  25179. if( osClose(h) ){
  25180. unixLogErrorAtLine(SQLITE_IOERR_CLOSE, "close",
  25181. pFile ? pFile->zPath : 0, lineno);
  25182. }
  25183. }
  25184. /*
  25185. ** Set the pFile->lastErrno. Do this in a subroutine as that provides
  25186. ** a convenient place to set a breakpoint.
  25187. */
  25188. static void storeLastErrno(unixFile *pFile, int error){
  25189. pFile->lastErrno = error;
  25190. }
  25191. /*
  25192. ** Close all file descriptors accumuated in the unixInodeInfo->pUnused list.
  25193. */
  25194. static void closePendingFds(unixFile *pFile){
  25195. unixInodeInfo *pInode = pFile->pInode;
  25196. UnixUnusedFd *p;
  25197. UnixUnusedFd *pNext;
  25198. for(p=pInode->pUnused; p; p=pNext){
  25199. pNext = p->pNext;
  25200. robust_close(pFile, p->fd, __LINE__);
  25201. sqlite3_free(p);
  25202. }
  25203. pInode->pUnused = 0;
  25204. }
  25205. /*
  25206. ** Release a unixInodeInfo structure previously allocated by findInodeInfo().
  25207. **
  25208. ** The mutex entered using the unixEnterMutex() function must be held
  25209. ** when this function is called.
  25210. */
  25211. static void releaseInodeInfo(unixFile *pFile){
  25212. unixInodeInfo *pInode = pFile->pInode;
  25213. assert( unixMutexHeld() );
  25214. if( ALWAYS(pInode) ){
  25215. pInode->nRef--;
  25216. if( pInode->nRef==0 ){
  25217. assert( pInode->pShmNode==0 );
  25218. closePendingFds(pFile);
  25219. if( pInode->pPrev ){
  25220. assert( pInode->pPrev->pNext==pInode );
  25221. pInode->pPrev->pNext = pInode->pNext;
  25222. }else{
  25223. assert( inodeList==pInode );
  25224. inodeList = pInode->pNext;
  25225. }
  25226. if( pInode->pNext ){
  25227. assert( pInode->pNext->pPrev==pInode );
  25228. pInode->pNext->pPrev = pInode->pPrev;
  25229. }
  25230. sqlite3_free(pInode);
  25231. }
  25232. }
  25233. }
  25234. /*
  25235. ** Given a file descriptor, locate the unixInodeInfo object that
  25236. ** describes that file descriptor. Create a new one if necessary. The
  25237. ** return value might be uninitialized if an error occurs.
  25238. **
  25239. ** The mutex entered using the unixEnterMutex() function must be held
  25240. ** when this function is called.
  25241. **
  25242. ** Return an appropriate error code.
  25243. */
  25244. static int findInodeInfo(
  25245. unixFile *pFile, /* Unix file with file desc used in the key */
  25246. unixInodeInfo **ppInode /* Return the unixInodeInfo object here */
  25247. ){
  25248. int rc; /* System call return code */
  25249. int fd; /* The file descriptor for pFile */
  25250. struct unixFileId fileId; /* Lookup key for the unixInodeInfo */
  25251. struct stat statbuf; /* Low-level file information */
  25252. unixInodeInfo *pInode = 0; /* Candidate unixInodeInfo object */
  25253. assert( unixMutexHeld() );
  25254. /* Get low-level information about the file that we can used to
  25255. ** create a unique name for the file.
  25256. */
  25257. fd = pFile->h;
  25258. rc = osFstat(fd, &statbuf);
  25259. if( rc!=0 ){
  25260. storeLastErrno(pFile, errno);
  25261. #ifdef EOVERFLOW
  25262. if( pFile->lastErrno==EOVERFLOW ) return SQLITE_NOLFS;
  25263. #endif
  25264. return SQLITE_IOERR;
  25265. }
  25266. #ifdef __APPLE__
  25267. /* On OS X on an msdos filesystem, the inode number is reported
  25268. ** incorrectly for zero-size files. See ticket #3260. To work
  25269. ** around this problem (we consider it a bug in OS X, not SQLite)
  25270. ** we always increase the file size to 1 by writing a single byte
  25271. ** prior to accessing the inode number. The one byte written is
  25272. ** an ASCII 'S' character which also happens to be the first byte
  25273. ** in the header of every SQLite database. In this way, if there
  25274. ** is a race condition such that another thread has already populated
  25275. ** the first page of the database, no damage is done.
  25276. */
  25277. if( statbuf.st_size==0 && (pFile->fsFlags & SQLITE_FSFLAGS_IS_MSDOS)!=0 ){
  25278. do{ rc = osWrite(fd, "S", 1); }while( rc<0 && errno==EINTR );
  25279. if( rc!=1 ){
  25280. storeLastErrno(pFile, errno);
  25281. return SQLITE_IOERR;
  25282. }
  25283. rc = osFstat(fd, &statbuf);
  25284. if( rc!=0 ){
  25285. storeLastErrno(pFile, errno);
  25286. return SQLITE_IOERR;
  25287. }
  25288. }
  25289. #endif
  25290. memset(&fileId, 0, sizeof(fileId));
  25291. fileId.dev = statbuf.st_dev;
  25292. #if OS_VXWORKS
  25293. fileId.pId = pFile->pId;
  25294. #else
  25295. fileId.ino = statbuf.st_ino;
  25296. #endif
  25297. pInode = inodeList;
  25298. while( pInode && memcmp(&fileId, &pInode->fileId, sizeof(fileId)) ){
  25299. pInode = pInode->pNext;
  25300. }
  25301. if( pInode==0 ){
  25302. pInode = sqlite3_malloc64( sizeof(*pInode) );
  25303. if( pInode==0 ){
  25304. return SQLITE_NOMEM;
  25305. }
  25306. memset(pInode, 0, sizeof(*pInode));
  25307. memcpy(&pInode->fileId, &fileId, sizeof(fileId));
  25308. pInode->nRef = 1;
  25309. pInode->pNext = inodeList;
  25310. pInode->pPrev = 0;
  25311. if( inodeList ) inodeList->pPrev = pInode;
  25312. inodeList = pInode;
  25313. }else{
  25314. pInode->nRef++;
  25315. }
  25316. *ppInode = pInode;
  25317. return SQLITE_OK;
  25318. }
  25319. /*
  25320. ** Return TRUE if pFile has been renamed or unlinked since it was first opened.
  25321. */
  25322. static int fileHasMoved(unixFile *pFile){
  25323. #if OS_VXWORKS
  25324. return pFile->pInode!=0 && pFile->pId!=pFile->pInode->fileId.pId;
  25325. #else
  25326. struct stat buf;
  25327. return pFile->pInode!=0 &&
  25328. (osStat(pFile->zPath, &buf)!=0 || buf.st_ino!=pFile->pInode->fileId.ino);
  25329. #endif
  25330. }
  25331. /*
  25332. ** Check a unixFile that is a database. Verify the following:
  25333. **
  25334. ** (1) There is exactly one hard link on the file
  25335. ** (2) The file is not a symbolic link
  25336. ** (3) The file has not been renamed or unlinked
  25337. **
  25338. ** Issue sqlite3_log(SQLITE_WARNING,...) messages if anything is not right.
  25339. */
  25340. static void verifyDbFile(unixFile *pFile){
  25341. struct stat buf;
  25342. int rc;
  25343. if( pFile->ctrlFlags & UNIXFILE_WARNED ){
  25344. /* One or more of the following warnings have already been issued. Do not
  25345. ** repeat them so as not to clutter the error log */
  25346. return;
  25347. }
  25348. rc = osFstat(pFile->h, &buf);
  25349. if( rc!=0 ){
  25350. sqlite3_log(SQLITE_WARNING, "cannot fstat db file %s", pFile->zPath);
  25351. pFile->ctrlFlags |= UNIXFILE_WARNED;
  25352. return;
  25353. }
  25354. if( buf.st_nlink==0 && (pFile->ctrlFlags & UNIXFILE_DELETE)==0 ){
  25355. sqlite3_log(SQLITE_WARNING, "file unlinked while open: %s", pFile->zPath);
  25356. pFile->ctrlFlags |= UNIXFILE_WARNED;
  25357. return;
  25358. }
  25359. if( buf.st_nlink>1 ){
  25360. sqlite3_log(SQLITE_WARNING, "multiple links to file: %s", pFile->zPath);
  25361. pFile->ctrlFlags |= UNIXFILE_WARNED;
  25362. return;
  25363. }
  25364. if( fileHasMoved(pFile) ){
  25365. sqlite3_log(SQLITE_WARNING, "file renamed while open: %s", pFile->zPath);
  25366. pFile->ctrlFlags |= UNIXFILE_WARNED;
  25367. return;
  25368. }
  25369. }
  25370. /*
  25371. ** This routine checks if there is a RESERVED lock held on the specified
  25372. ** file by this or any other process. If such a lock is held, set *pResOut
  25373. ** to a non-zero value otherwise *pResOut is set to zero. The return value
  25374. ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
  25375. */
  25376. static int unixCheckReservedLock(sqlite3_file *id, int *pResOut){
  25377. int rc = SQLITE_OK;
  25378. int reserved = 0;
  25379. unixFile *pFile = (unixFile*)id;
  25380. SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
  25381. assert( pFile );
  25382. unixEnterMutex(); /* Because pFile->pInode is shared across threads */
  25383. /* Check if a thread in this process holds such a lock */
  25384. if( pFile->pInode->eFileLock>SHARED_LOCK ){
  25385. reserved = 1;
  25386. }
  25387. /* Otherwise see if some other process holds it.
  25388. */
  25389. #ifndef __DJGPP__
  25390. if( !reserved && !pFile->pInode->bProcessLock ){
  25391. struct flock lock;
  25392. lock.l_whence = SEEK_SET;
  25393. lock.l_start = RESERVED_BYTE;
  25394. lock.l_len = 1;
  25395. lock.l_type = F_WRLCK;
  25396. if( osFcntl(pFile->h, F_GETLK, &lock) ){
  25397. rc = SQLITE_IOERR_CHECKRESERVEDLOCK;
  25398. storeLastErrno(pFile, errno);
  25399. } else if( lock.l_type!=F_UNLCK ){
  25400. reserved = 1;
  25401. }
  25402. }
  25403. #endif
  25404. unixLeaveMutex();
  25405. OSTRACE(("TEST WR-LOCK %d %d %d (unix)\n", pFile->h, rc, reserved));
  25406. *pResOut = reserved;
  25407. return rc;
  25408. }
  25409. /*
  25410. ** Attempt to set a system-lock on the file pFile. The lock is
  25411. ** described by pLock.
  25412. **
  25413. ** If the pFile was opened read/write from unix-excl, then the only lock
  25414. ** ever obtained is an exclusive lock, and it is obtained exactly once
  25415. ** the first time any lock is attempted. All subsequent system locking
  25416. ** operations become no-ops. Locking operations still happen internally,
  25417. ** in order to coordinate access between separate database connections
  25418. ** within this process, but all of that is handled in memory and the
  25419. ** operating system does not participate.
  25420. **
  25421. ** This function is a pass-through to fcntl(F_SETLK) if pFile is using
  25422. ** any VFS other than "unix-excl" or if pFile is opened on "unix-excl"
  25423. ** and is read-only.
  25424. **
  25425. ** Zero is returned if the call completes successfully, or -1 if a call
  25426. ** to fcntl() fails. In this case, errno is set appropriately (by fcntl()).
  25427. */
  25428. static int unixFileLock(unixFile *pFile, struct flock *pLock){
  25429. int rc;
  25430. unixInodeInfo *pInode = pFile->pInode;
  25431. assert( unixMutexHeld() );
  25432. assert( pInode!=0 );
  25433. if( ((pFile->ctrlFlags & UNIXFILE_EXCL)!=0 || pInode->bProcessLock)
  25434. && ((pFile->ctrlFlags & UNIXFILE_RDONLY)==0)
  25435. ){
  25436. if( pInode->bProcessLock==0 ){
  25437. struct flock lock;
  25438. assert( pInode->nLock==0 );
  25439. lock.l_whence = SEEK_SET;
  25440. lock.l_start = SHARED_FIRST;
  25441. lock.l_len = SHARED_SIZE;
  25442. lock.l_type = F_WRLCK;
  25443. rc = osFcntl(pFile->h, F_SETLK, &lock);
  25444. if( rc<0 ) return rc;
  25445. pInode->bProcessLock = 1;
  25446. pInode->nLock++;
  25447. }else{
  25448. rc = 0;
  25449. }
  25450. }else{
  25451. rc = osFcntl(pFile->h, F_SETLK, pLock);
  25452. }
  25453. return rc;
  25454. }
  25455. /*
  25456. ** Lock the file with the lock specified by parameter eFileLock - one
  25457. ** of the following:
  25458. **
  25459. ** (1) SHARED_LOCK
  25460. ** (2) RESERVED_LOCK
  25461. ** (3) PENDING_LOCK
  25462. ** (4) EXCLUSIVE_LOCK
  25463. **
  25464. ** Sometimes when requesting one lock state, additional lock states
  25465. ** are inserted in between. The locking might fail on one of the later
  25466. ** transitions leaving the lock state different from what it started but
  25467. ** still short of its goal. The following chart shows the allowed
  25468. ** transitions and the inserted intermediate states:
  25469. **
  25470. ** UNLOCKED -> SHARED
  25471. ** SHARED -> RESERVED
  25472. ** SHARED -> (PENDING) -> EXCLUSIVE
  25473. ** RESERVED -> (PENDING) -> EXCLUSIVE
  25474. ** PENDING -> EXCLUSIVE
  25475. **
  25476. ** This routine will only increase a lock. Use the sqlite3OsUnlock()
  25477. ** routine to lower a locking level.
  25478. */
  25479. static int unixLock(sqlite3_file *id, int eFileLock){
  25480. /* The following describes the implementation of the various locks and
  25481. ** lock transitions in terms of the POSIX advisory shared and exclusive
  25482. ** lock primitives (called read-locks and write-locks below, to avoid
  25483. ** confusion with SQLite lock names). The algorithms are complicated
  25484. ** slightly in order to be compatible with windows systems simultaneously
  25485. ** accessing the same database file, in case that is ever required.
  25486. **
  25487. ** Symbols defined in os.h indentify the 'pending byte' and the 'reserved
  25488. ** byte', each single bytes at well known offsets, and the 'shared byte
  25489. ** range', a range of 510 bytes at a well known offset.
  25490. **
  25491. ** To obtain a SHARED lock, a read-lock is obtained on the 'pending
  25492. ** byte'. If this is successful, a random byte from the 'shared byte
  25493. ** range' is read-locked and the lock on the 'pending byte' released.
  25494. **
  25495. ** A process may only obtain a RESERVED lock after it has a SHARED lock.
  25496. ** A RESERVED lock is implemented by grabbing a write-lock on the
  25497. ** 'reserved byte'.
  25498. **
  25499. ** A process may only obtain a PENDING lock after it has obtained a
  25500. ** SHARED lock. A PENDING lock is implemented by obtaining a write-lock
  25501. ** on the 'pending byte'. This ensures that no new SHARED locks can be
  25502. ** obtained, but existing SHARED locks are allowed to persist. A process
  25503. ** does not have to obtain a RESERVED lock on the way to a PENDING lock.
  25504. ** This property is used by the algorithm for rolling back a journal file
  25505. ** after a crash.
  25506. **
  25507. ** An EXCLUSIVE lock, obtained after a PENDING lock is held, is
  25508. ** implemented by obtaining a write-lock on the entire 'shared byte
  25509. ** range'. Since all other locks require a read-lock on one of the bytes
  25510. ** within this range, this ensures that no other locks are held on the
  25511. ** database.
  25512. **
  25513. ** The reason a single byte cannot be used instead of the 'shared byte
  25514. ** range' is that some versions of windows do not support read-locks. By
  25515. ** locking a random byte from a range, concurrent SHARED locks may exist
  25516. ** even if the locking primitive used is always a write-lock.
  25517. */
  25518. int rc = SQLITE_OK;
  25519. unixFile *pFile = (unixFile*)id;
  25520. unixInodeInfo *pInode;
  25521. struct flock lock;
  25522. int tErrno = 0;
  25523. assert( pFile );
  25524. OSTRACE(("LOCK %d %s was %s(%s,%d) pid=%d (unix)\n", pFile->h,
  25525. azFileLock(eFileLock), azFileLock(pFile->eFileLock),
  25526. azFileLock(pFile->pInode->eFileLock), pFile->pInode->nShared,
  25527. osGetpid(0)));
  25528. /* If there is already a lock of this type or more restrictive on the
  25529. ** unixFile, do nothing. Don't use the end_lock: exit path, as
  25530. ** unixEnterMutex() hasn't been called yet.
  25531. */
  25532. if( pFile->eFileLock>=eFileLock ){
  25533. OSTRACE(("LOCK %d %s ok (already held) (unix)\n", pFile->h,
  25534. azFileLock(eFileLock)));
  25535. return SQLITE_OK;
  25536. }
  25537. /* Make sure the locking sequence is correct.
  25538. ** (1) We never move from unlocked to anything higher than shared lock.
  25539. ** (2) SQLite never explicitly requests a pendig lock.
  25540. ** (3) A shared lock is always held when a reserve lock is requested.
  25541. */
  25542. assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
  25543. assert( eFileLock!=PENDING_LOCK );
  25544. assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
  25545. /* This mutex is needed because pFile->pInode is shared across threads
  25546. */
  25547. unixEnterMutex();
  25548. pInode = pFile->pInode;
  25549. /* If some thread using this PID has a lock via a different unixFile*
  25550. ** handle that precludes the requested lock, return BUSY.
  25551. */
  25552. if( (pFile->eFileLock!=pInode->eFileLock &&
  25553. (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
  25554. ){
  25555. rc = SQLITE_BUSY;
  25556. goto end_lock;
  25557. }
  25558. /* If a SHARED lock is requested, and some thread using this PID already
  25559. ** has a SHARED or RESERVED lock, then increment reference counts and
  25560. ** return SQLITE_OK.
  25561. */
  25562. if( eFileLock==SHARED_LOCK &&
  25563. (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
  25564. assert( eFileLock==SHARED_LOCK );
  25565. assert( pFile->eFileLock==0 );
  25566. assert( pInode->nShared>0 );
  25567. pFile->eFileLock = SHARED_LOCK;
  25568. pInode->nShared++;
  25569. pInode->nLock++;
  25570. goto end_lock;
  25571. }
  25572. /* A PENDING lock is needed before acquiring a SHARED lock and before
  25573. ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
  25574. ** be released.
  25575. */
  25576. lock.l_len = 1L;
  25577. lock.l_whence = SEEK_SET;
  25578. if( eFileLock==SHARED_LOCK
  25579. || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
  25580. ){
  25581. lock.l_type = (eFileLock==SHARED_LOCK?F_RDLCK:F_WRLCK);
  25582. lock.l_start = PENDING_BYTE;
  25583. if( unixFileLock(pFile, &lock) ){
  25584. tErrno = errno;
  25585. rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
  25586. if( rc!=SQLITE_BUSY ){
  25587. storeLastErrno(pFile, tErrno);
  25588. }
  25589. goto end_lock;
  25590. }
  25591. }
  25592. /* If control gets to this point, then actually go ahead and make
  25593. ** operating system calls for the specified lock.
  25594. */
  25595. if( eFileLock==SHARED_LOCK ){
  25596. assert( pInode->nShared==0 );
  25597. assert( pInode->eFileLock==0 );
  25598. assert( rc==SQLITE_OK );
  25599. /* Now get the read-lock */
  25600. lock.l_start = SHARED_FIRST;
  25601. lock.l_len = SHARED_SIZE;
  25602. if( unixFileLock(pFile, &lock) ){
  25603. tErrno = errno;
  25604. rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
  25605. }
  25606. /* Drop the temporary PENDING lock */
  25607. lock.l_start = PENDING_BYTE;
  25608. lock.l_len = 1L;
  25609. lock.l_type = F_UNLCK;
  25610. if( unixFileLock(pFile, &lock) && rc==SQLITE_OK ){
  25611. /* This could happen with a network mount */
  25612. tErrno = errno;
  25613. rc = SQLITE_IOERR_UNLOCK;
  25614. }
  25615. if( rc ){
  25616. if( rc!=SQLITE_BUSY ){
  25617. storeLastErrno(pFile, tErrno);
  25618. }
  25619. goto end_lock;
  25620. }else{
  25621. pFile->eFileLock = SHARED_LOCK;
  25622. pInode->nLock++;
  25623. pInode->nShared = 1;
  25624. }
  25625. }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
  25626. /* We are trying for an exclusive lock but another thread in this
  25627. ** same process is still holding a shared lock. */
  25628. rc = SQLITE_BUSY;
  25629. }else{
  25630. /* The request was for a RESERVED or EXCLUSIVE lock. It is
  25631. ** assumed that there is a SHARED or greater lock on the file
  25632. ** already.
  25633. */
  25634. assert( 0!=pFile->eFileLock );
  25635. lock.l_type = F_WRLCK;
  25636. assert( eFileLock==RESERVED_LOCK || eFileLock==EXCLUSIVE_LOCK );
  25637. if( eFileLock==RESERVED_LOCK ){
  25638. lock.l_start = RESERVED_BYTE;
  25639. lock.l_len = 1L;
  25640. }else{
  25641. lock.l_start = SHARED_FIRST;
  25642. lock.l_len = SHARED_SIZE;
  25643. }
  25644. if( unixFileLock(pFile, &lock) ){
  25645. tErrno = errno;
  25646. rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
  25647. if( rc!=SQLITE_BUSY ){
  25648. storeLastErrno(pFile, tErrno);
  25649. }
  25650. }
  25651. }
  25652. #ifdef SQLITE_DEBUG
  25653. /* Set up the transaction-counter change checking flags when
  25654. ** transitioning from a SHARED to a RESERVED lock. The change
  25655. ** from SHARED to RESERVED marks the beginning of a normal
  25656. ** write operation (not a hot journal rollback).
  25657. */
  25658. if( rc==SQLITE_OK
  25659. && pFile->eFileLock<=SHARED_LOCK
  25660. && eFileLock==RESERVED_LOCK
  25661. ){
  25662. pFile->transCntrChng = 0;
  25663. pFile->dbUpdate = 0;
  25664. pFile->inNormalWrite = 1;
  25665. }
  25666. #endif
  25667. if( rc==SQLITE_OK ){
  25668. pFile->eFileLock = eFileLock;
  25669. pInode->eFileLock = eFileLock;
  25670. }else if( eFileLock==EXCLUSIVE_LOCK ){
  25671. pFile->eFileLock = PENDING_LOCK;
  25672. pInode->eFileLock = PENDING_LOCK;
  25673. }
  25674. end_lock:
  25675. unixLeaveMutex();
  25676. OSTRACE(("LOCK %d %s %s (unix)\n", pFile->h, azFileLock(eFileLock),
  25677. rc==SQLITE_OK ? "ok" : "failed"));
  25678. return rc;
  25679. }
  25680. /*
  25681. ** Add the file descriptor used by file handle pFile to the corresponding
  25682. ** pUnused list.
  25683. */
  25684. static void setPendingFd(unixFile *pFile){
  25685. unixInodeInfo *pInode = pFile->pInode;
  25686. UnixUnusedFd *p = pFile->pUnused;
  25687. p->pNext = pInode->pUnused;
  25688. pInode->pUnused = p;
  25689. pFile->h = -1;
  25690. pFile->pUnused = 0;
  25691. }
  25692. /*
  25693. ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
  25694. ** must be either NO_LOCK or SHARED_LOCK.
  25695. **
  25696. ** If the locking level of the file descriptor is already at or below
  25697. ** the requested locking level, this routine is a no-op.
  25698. **
  25699. ** If handleNFSUnlock is true, then on downgrading an EXCLUSIVE_LOCK to SHARED
  25700. ** the byte range is divided into 2 parts and the first part is unlocked then
  25701. ** set to a read lock, then the other part is simply unlocked. This works
  25702. ** around a bug in BSD NFS lockd (also seen on MacOSX 10.3+) that fails to
  25703. ** remove the write lock on a region when a read lock is set.
  25704. */
  25705. static int posixUnlock(sqlite3_file *id, int eFileLock, int handleNFSUnlock){
  25706. unixFile *pFile = (unixFile*)id;
  25707. unixInodeInfo *pInode;
  25708. struct flock lock;
  25709. int rc = SQLITE_OK;
  25710. assert( pFile );
  25711. OSTRACE(("UNLOCK %d %d was %d(%d,%d) pid=%d (unix)\n", pFile->h, eFileLock,
  25712. pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
  25713. osGetpid(0)));
  25714. assert( eFileLock<=SHARED_LOCK );
  25715. if( pFile->eFileLock<=eFileLock ){
  25716. return SQLITE_OK;
  25717. }
  25718. unixEnterMutex();
  25719. pInode = pFile->pInode;
  25720. assert( pInode->nShared!=0 );
  25721. if( pFile->eFileLock>SHARED_LOCK ){
  25722. assert( pInode->eFileLock==pFile->eFileLock );
  25723. #ifdef SQLITE_DEBUG
  25724. /* When reducing a lock such that other processes can start
  25725. ** reading the database file again, make sure that the
  25726. ** transaction counter was updated if any part of the database
  25727. ** file changed. If the transaction counter is not updated,
  25728. ** other connections to the same file might not realize that
  25729. ** the file has changed and hence might not know to flush their
  25730. ** cache. The use of a stale cache can lead to database corruption.
  25731. */
  25732. pFile->inNormalWrite = 0;
  25733. #endif
  25734. /* downgrading to a shared lock on NFS involves clearing the write lock
  25735. ** before establishing the readlock - to avoid a race condition we downgrade
  25736. ** the lock in 2 blocks, so that part of the range will be covered by a
  25737. ** write lock until the rest is covered by a read lock:
  25738. ** 1: [WWWWW]
  25739. ** 2: [....W]
  25740. ** 3: [RRRRW]
  25741. ** 4: [RRRR.]
  25742. */
  25743. if( eFileLock==SHARED_LOCK ){
  25744. #if !defined(__APPLE__) || !SQLITE_ENABLE_LOCKING_STYLE
  25745. (void)handleNFSUnlock;
  25746. assert( handleNFSUnlock==0 );
  25747. #endif
  25748. #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
  25749. if( handleNFSUnlock ){
  25750. int tErrno; /* Error code from system call errors */
  25751. off_t divSize = SHARED_SIZE - 1;
  25752. lock.l_type = F_UNLCK;
  25753. lock.l_whence = SEEK_SET;
  25754. lock.l_start = SHARED_FIRST;
  25755. lock.l_len = divSize;
  25756. if( unixFileLock(pFile, &lock)==(-1) ){
  25757. tErrno = errno;
  25758. rc = SQLITE_IOERR_UNLOCK;
  25759. if( IS_LOCK_ERROR(rc) ){
  25760. storeLastErrno(pFile, tErrno);
  25761. }
  25762. goto end_unlock;
  25763. }
  25764. lock.l_type = F_RDLCK;
  25765. lock.l_whence = SEEK_SET;
  25766. lock.l_start = SHARED_FIRST;
  25767. lock.l_len = divSize;
  25768. if( unixFileLock(pFile, &lock)==(-1) ){
  25769. tErrno = errno;
  25770. rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_RDLOCK);
  25771. if( IS_LOCK_ERROR(rc) ){
  25772. storeLastErrno(pFile, tErrno);
  25773. }
  25774. goto end_unlock;
  25775. }
  25776. lock.l_type = F_UNLCK;
  25777. lock.l_whence = SEEK_SET;
  25778. lock.l_start = SHARED_FIRST+divSize;
  25779. lock.l_len = SHARED_SIZE-divSize;
  25780. if( unixFileLock(pFile, &lock)==(-1) ){
  25781. tErrno = errno;
  25782. rc = SQLITE_IOERR_UNLOCK;
  25783. if( IS_LOCK_ERROR(rc) ){
  25784. storeLastErrno(pFile, tErrno);
  25785. }
  25786. goto end_unlock;
  25787. }
  25788. }else
  25789. #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
  25790. {
  25791. lock.l_type = F_RDLCK;
  25792. lock.l_whence = SEEK_SET;
  25793. lock.l_start = SHARED_FIRST;
  25794. lock.l_len = SHARED_SIZE;
  25795. if( unixFileLock(pFile, &lock) ){
  25796. /* In theory, the call to unixFileLock() cannot fail because another
  25797. ** process is holding an incompatible lock. If it does, this
  25798. ** indicates that the other process is not following the locking
  25799. ** protocol. If this happens, return SQLITE_IOERR_RDLOCK. Returning
  25800. ** SQLITE_BUSY would confuse the upper layer (in practice it causes
  25801. ** an assert to fail). */
  25802. rc = SQLITE_IOERR_RDLOCK;
  25803. storeLastErrno(pFile, errno);
  25804. goto end_unlock;
  25805. }
  25806. }
  25807. }
  25808. lock.l_type = F_UNLCK;
  25809. lock.l_whence = SEEK_SET;
  25810. lock.l_start = PENDING_BYTE;
  25811. lock.l_len = 2L; assert( PENDING_BYTE+1==RESERVED_BYTE );
  25812. if( unixFileLock(pFile, &lock)==0 ){
  25813. pInode->eFileLock = SHARED_LOCK;
  25814. }else{
  25815. rc = SQLITE_IOERR_UNLOCK;
  25816. storeLastErrno(pFile, errno);
  25817. goto end_unlock;
  25818. }
  25819. }
  25820. if( eFileLock==NO_LOCK ){
  25821. /* Decrement the shared lock counter. Release the lock using an
  25822. ** OS call only when all threads in this same process have released
  25823. ** the lock.
  25824. */
  25825. pInode->nShared--;
  25826. if( pInode->nShared==0 ){
  25827. lock.l_type = F_UNLCK;
  25828. lock.l_whence = SEEK_SET;
  25829. lock.l_start = lock.l_len = 0L;
  25830. if( unixFileLock(pFile, &lock)==0 ){
  25831. pInode->eFileLock = NO_LOCK;
  25832. }else{
  25833. rc = SQLITE_IOERR_UNLOCK;
  25834. storeLastErrno(pFile, errno);
  25835. pInode->eFileLock = NO_LOCK;
  25836. pFile->eFileLock = NO_LOCK;
  25837. }
  25838. }
  25839. /* Decrement the count of locks against this same file. When the
  25840. ** count reaches zero, close any other file descriptors whose close
  25841. ** was deferred because of outstanding locks.
  25842. */
  25843. pInode->nLock--;
  25844. assert( pInode->nLock>=0 );
  25845. if( pInode->nLock==0 ){
  25846. closePendingFds(pFile);
  25847. }
  25848. }
  25849. end_unlock:
  25850. unixLeaveMutex();
  25851. if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
  25852. return rc;
  25853. }
  25854. /*
  25855. ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
  25856. ** must be either NO_LOCK or SHARED_LOCK.
  25857. **
  25858. ** If the locking level of the file descriptor is already at or below
  25859. ** the requested locking level, this routine is a no-op.
  25860. */
  25861. static int unixUnlock(sqlite3_file *id, int eFileLock){
  25862. #if SQLITE_MAX_MMAP_SIZE>0
  25863. assert( eFileLock==SHARED_LOCK || ((unixFile *)id)->nFetchOut==0 );
  25864. #endif
  25865. return posixUnlock(id, eFileLock, 0);
  25866. }
  25867. #if SQLITE_MAX_MMAP_SIZE>0
  25868. static int unixMapfile(unixFile *pFd, i64 nByte);
  25869. static void unixUnmapfile(unixFile *pFd);
  25870. #endif
  25871. /*
  25872. ** This function performs the parts of the "close file" operation
  25873. ** common to all locking schemes. It closes the directory and file
  25874. ** handles, if they are valid, and sets all fields of the unixFile
  25875. ** structure to 0.
  25876. **
  25877. ** It is *not* necessary to hold the mutex when this routine is called,
  25878. ** even on VxWorks. A mutex will be acquired on VxWorks by the
  25879. ** vxworksReleaseFileId() routine.
  25880. */
  25881. static int closeUnixFile(sqlite3_file *id){
  25882. unixFile *pFile = (unixFile*)id;
  25883. #if SQLITE_MAX_MMAP_SIZE>0
  25884. unixUnmapfile(pFile);
  25885. #endif
  25886. if( pFile->h>=0 ){
  25887. robust_close(pFile, pFile->h, __LINE__);
  25888. pFile->h = -1;
  25889. }
  25890. #if OS_VXWORKS
  25891. if( pFile->pId ){
  25892. if( pFile->ctrlFlags & UNIXFILE_DELETE ){
  25893. osUnlink(pFile->pId->zCanonicalName);
  25894. }
  25895. vxworksReleaseFileId(pFile->pId);
  25896. pFile->pId = 0;
  25897. }
  25898. #endif
  25899. #ifdef SQLITE_UNLINK_AFTER_CLOSE
  25900. if( pFile->ctrlFlags & UNIXFILE_DELETE ){
  25901. osUnlink(pFile->zPath);
  25902. sqlite3_free(*(char**)&pFile->zPath);
  25903. pFile->zPath = 0;
  25904. }
  25905. #endif
  25906. OSTRACE(("CLOSE %-3d\n", pFile->h));
  25907. OpenCounter(-1);
  25908. sqlite3_free(pFile->pUnused);
  25909. memset(pFile, 0, sizeof(unixFile));
  25910. return SQLITE_OK;
  25911. }
  25912. /*
  25913. ** Close a file.
  25914. */
  25915. static int unixClose(sqlite3_file *id){
  25916. int rc = SQLITE_OK;
  25917. unixFile *pFile = (unixFile *)id;
  25918. verifyDbFile(pFile);
  25919. unixUnlock(id, NO_LOCK);
  25920. unixEnterMutex();
  25921. /* unixFile.pInode is always valid here. Otherwise, a different close
  25922. ** routine (e.g. nolockClose()) would be called instead.
  25923. */
  25924. assert( pFile->pInode->nLock>0 || pFile->pInode->bProcessLock==0 );
  25925. if( ALWAYS(pFile->pInode) && pFile->pInode->nLock ){
  25926. /* If there are outstanding locks, do not actually close the file just
  25927. ** yet because that would clear those locks. Instead, add the file
  25928. ** descriptor to pInode->pUnused list. It will be automatically closed
  25929. ** when the last lock is cleared.
  25930. */
  25931. setPendingFd(pFile);
  25932. }
  25933. releaseInodeInfo(pFile);
  25934. rc = closeUnixFile(id);
  25935. unixLeaveMutex();
  25936. return rc;
  25937. }
  25938. /************** End of the posix advisory lock implementation *****************
  25939. ******************************************************************************/
  25940. /******************************************************************************
  25941. ****************************** No-op Locking **********************************
  25942. **
  25943. ** Of the various locking implementations available, this is by far the
  25944. ** simplest: locking is ignored. No attempt is made to lock the database
  25945. ** file for reading or writing.
  25946. **
  25947. ** This locking mode is appropriate for use on read-only databases
  25948. ** (ex: databases that are burned into CD-ROM, for example.) It can
  25949. ** also be used if the application employs some external mechanism to
  25950. ** prevent simultaneous access of the same database by two or more
  25951. ** database connections. But there is a serious risk of database
  25952. ** corruption if this locking mode is used in situations where multiple
  25953. ** database connections are accessing the same database file at the same
  25954. ** time and one or more of those connections are writing.
  25955. */
  25956. static int nolockCheckReservedLock(sqlite3_file *NotUsed, int *pResOut){
  25957. UNUSED_PARAMETER(NotUsed);
  25958. *pResOut = 0;
  25959. return SQLITE_OK;
  25960. }
  25961. static int nolockLock(sqlite3_file *NotUsed, int NotUsed2){
  25962. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  25963. return SQLITE_OK;
  25964. }
  25965. static int nolockUnlock(sqlite3_file *NotUsed, int NotUsed2){
  25966. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  25967. return SQLITE_OK;
  25968. }
  25969. /*
  25970. ** Close the file.
  25971. */
  25972. static int nolockClose(sqlite3_file *id) {
  25973. return closeUnixFile(id);
  25974. }
  25975. /******************* End of the no-op lock implementation *********************
  25976. ******************************************************************************/
  25977. /******************************************************************************
  25978. ************************* Begin dot-file Locking ******************************
  25979. **
  25980. ** The dotfile locking implementation uses the existence of separate lock
  25981. ** files (really a directory) to control access to the database. This works
  25982. ** on just about every filesystem imaginable. But there are serious downsides:
  25983. **
  25984. ** (1) There is zero concurrency. A single reader blocks all other
  25985. ** connections from reading or writing the database.
  25986. **
  25987. ** (2) An application crash or power loss can leave stale lock files
  25988. ** sitting around that need to be cleared manually.
  25989. **
  25990. ** Nevertheless, a dotlock is an appropriate locking mode for use if no
  25991. ** other locking strategy is available.
  25992. **
  25993. ** Dotfile locking works by creating a subdirectory in the same directory as
  25994. ** the database and with the same name but with a ".lock" extension added.
  25995. ** The existence of a lock directory implies an EXCLUSIVE lock. All other
  25996. ** lock types (SHARED, RESERVED, PENDING) are mapped into EXCLUSIVE.
  25997. */
  25998. /*
  25999. ** The file suffix added to the data base filename in order to create the
  26000. ** lock directory.
  26001. */
  26002. #define DOTLOCK_SUFFIX ".lock"
  26003. /*
  26004. ** This routine checks if there is a RESERVED lock held on the specified
  26005. ** file by this or any other process. If such a lock is held, set *pResOut
  26006. ** to a non-zero value otherwise *pResOut is set to zero. The return value
  26007. ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
  26008. **
  26009. ** In dotfile locking, either a lock exists or it does not. So in this
  26010. ** variation of CheckReservedLock(), *pResOut is set to true if any lock
  26011. ** is held on the file and false if the file is unlocked.
  26012. */
  26013. static int dotlockCheckReservedLock(sqlite3_file *id, int *pResOut) {
  26014. int rc = SQLITE_OK;
  26015. int reserved = 0;
  26016. unixFile *pFile = (unixFile*)id;
  26017. SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
  26018. assert( pFile );
  26019. /* Check if a thread in this process holds such a lock */
  26020. if( pFile->eFileLock>SHARED_LOCK ){
  26021. /* Either this connection or some other connection in the same process
  26022. ** holds a lock on the file. No need to check further. */
  26023. reserved = 1;
  26024. }else{
  26025. /* The lock is held if and only if the lockfile exists */
  26026. const char *zLockFile = (const char*)pFile->lockingContext;
  26027. reserved = osAccess(zLockFile, 0)==0;
  26028. }
  26029. OSTRACE(("TEST WR-LOCK %d %d %d (dotlock)\n", pFile->h, rc, reserved));
  26030. *pResOut = reserved;
  26031. return rc;
  26032. }
  26033. /*
  26034. ** Lock the file with the lock specified by parameter eFileLock - one
  26035. ** of the following:
  26036. **
  26037. ** (1) SHARED_LOCK
  26038. ** (2) RESERVED_LOCK
  26039. ** (3) PENDING_LOCK
  26040. ** (4) EXCLUSIVE_LOCK
  26041. **
  26042. ** Sometimes when requesting one lock state, additional lock states
  26043. ** are inserted in between. The locking might fail on one of the later
  26044. ** transitions leaving the lock state different from what it started but
  26045. ** still short of its goal. The following chart shows the allowed
  26046. ** transitions and the inserted intermediate states:
  26047. **
  26048. ** UNLOCKED -> SHARED
  26049. ** SHARED -> RESERVED
  26050. ** SHARED -> (PENDING) -> EXCLUSIVE
  26051. ** RESERVED -> (PENDING) -> EXCLUSIVE
  26052. ** PENDING -> EXCLUSIVE
  26053. **
  26054. ** This routine will only increase a lock. Use the sqlite3OsUnlock()
  26055. ** routine to lower a locking level.
  26056. **
  26057. ** With dotfile locking, we really only support state (4): EXCLUSIVE.
  26058. ** But we track the other locking levels internally.
  26059. */
  26060. static int dotlockLock(sqlite3_file *id, int eFileLock) {
  26061. unixFile *pFile = (unixFile*)id;
  26062. char *zLockFile = (char *)pFile->lockingContext;
  26063. int rc = SQLITE_OK;
  26064. /* If we have any lock, then the lock file already exists. All we have
  26065. ** to do is adjust our internal record of the lock level.
  26066. */
  26067. if( pFile->eFileLock > NO_LOCK ){
  26068. pFile->eFileLock = eFileLock;
  26069. /* Always update the timestamp on the old file */
  26070. #ifdef HAVE_UTIME
  26071. utime(zLockFile, NULL);
  26072. #else
  26073. utimes(zLockFile, NULL);
  26074. #endif
  26075. return SQLITE_OK;
  26076. }
  26077. /* grab an exclusive lock */
  26078. rc = osMkdir(zLockFile, 0777);
  26079. if( rc<0 ){
  26080. /* failed to open/create the lock directory */
  26081. int tErrno = errno;
  26082. if( EEXIST == tErrno ){
  26083. rc = SQLITE_BUSY;
  26084. } else {
  26085. rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
  26086. if( IS_LOCK_ERROR(rc) ){
  26087. storeLastErrno(pFile, tErrno);
  26088. }
  26089. }
  26090. return rc;
  26091. }
  26092. /* got it, set the type and return ok */
  26093. pFile->eFileLock = eFileLock;
  26094. return rc;
  26095. }
  26096. /*
  26097. ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
  26098. ** must be either NO_LOCK or SHARED_LOCK.
  26099. **
  26100. ** If the locking level of the file descriptor is already at or below
  26101. ** the requested locking level, this routine is a no-op.
  26102. **
  26103. ** When the locking level reaches NO_LOCK, delete the lock file.
  26104. */
  26105. static int dotlockUnlock(sqlite3_file *id, int eFileLock) {
  26106. unixFile *pFile = (unixFile*)id;
  26107. char *zLockFile = (char *)pFile->lockingContext;
  26108. int rc;
  26109. assert( pFile );
  26110. OSTRACE(("UNLOCK %d %d was %d pid=%d (dotlock)\n", pFile->h, eFileLock,
  26111. pFile->eFileLock, osGetpid(0)));
  26112. assert( eFileLock<=SHARED_LOCK );
  26113. /* no-op if possible */
  26114. if( pFile->eFileLock==eFileLock ){
  26115. return SQLITE_OK;
  26116. }
  26117. /* To downgrade to shared, simply update our internal notion of the
  26118. ** lock state. No need to mess with the file on disk.
  26119. */
  26120. if( eFileLock==SHARED_LOCK ){
  26121. pFile->eFileLock = SHARED_LOCK;
  26122. return SQLITE_OK;
  26123. }
  26124. /* To fully unlock the database, delete the lock file */
  26125. assert( eFileLock==NO_LOCK );
  26126. rc = osRmdir(zLockFile);
  26127. if( rc<0 && errno==ENOTDIR ) rc = osUnlink(zLockFile);
  26128. if( rc<0 ){
  26129. int tErrno = errno;
  26130. rc = 0;
  26131. if( ENOENT != tErrno ){
  26132. rc = SQLITE_IOERR_UNLOCK;
  26133. }
  26134. if( IS_LOCK_ERROR(rc) ){
  26135. storeLastErrno(pFile, tErrno);
  26136. }
  26137. return rc;
  26138. }
  26139. pFile->eFileLock = NO_LOCK;
  26140. return SQLITE_OK;
  26141. }
  26142. /*
  26143. ** Close a file. Make sure the lock has been released before closing.
  26144. */
  26145. static int dotlockClose(sqlite3_file *id) {
  26146. int rc = SQLITE_OK;
  26147. if( id ){
  26148. unixFile *pFile = (unixFile*)id;
  26149. dotlockUnlock(id, NO_LOCK);
  26150. sqlite3_free(pFile->lockingContext);
  26151. rc = closeUnixFile(id);
  26152. }
  26153. return rc;
  26154. }
  26155. /****************** End of the dot-file lock implementation *******************
  26156. ******************************************************************************/
  26157. /******************************************************************************
  26158. ************************** Begin flock Locking ********************************
  26159. **
  26160. ** Use the flock() system call to do file locking.
  26161. **
  26162. ** flock() locking is like dot-file locking in that the various
  26163. ** fine-grain locking levels supported by SQLite are collapsed into
  26164. ** a single exclusive lock. In other words, SHARED, RESERVED, and
  26165. ** PENDING locks are the same thing as an EXCLUSIVE lock. SQLite
  26166. ** still works when you do this, but concurrency is reduced since
  26167. ** only a single process can be reading the database at a time.
  26168. **
  26169. ** Omit this section if SQLITE_ENABLE_LOCKING_STYLE is turned off
  26170. */
  26171. #if SQLITE_ENABLE_LOCKING_STYLE
  26172. /*
  26173. ** Retry flock() calls that fail with EINTR
  26174. */
  26175. #ifdef EINTR
  26176. static int robust_flock(int fd, int op){
  26177. int rc;
  26178. do{ rc = flock(fd,op); }while( rc<0 && errno==EINTR );
  26179. return rc;
  26180. }
  26181. #else
  26182. # define robust_flock(a,b) flock(a,b)
  26183. #endif
  26184. /*
  26185. ** This routine checks if there is a RESERVED lock held on the specified
  26186. ** file by this or any other process. If such a lock is held, set *pResOut
  26187. ** to a non-zero value otherwise *pResOut is set to zero. The return value
  26188. ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
  26189. */
  26190. static int flockCheckReservedLock(sqlite3_file *id, int *pResOut){
  26191. int rc = SQLITE_OK;
  26192. int reserved = 0;
  26193. unixFile *pFile = (unixFile*)id;
  26194. SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
  26195. assert( pFile );
  26196. /* Check if a thread in this process holds such a lock */
  26197. if( pFile->eFileLock>SHARED_LOCK ){
  26198. reserved = 1;
  26199. }
  26200. /* Otherwise see if some other process holds it. */
  26201. if( !reserved ){
  26202. /* attempt to get the lock */
  26203. int lrc = robust_flock(pFile->h, LOCK_EX | LOCK_NB);
  26204. if( !lrc ){
  26205. /* got the lock, unlock it */
  26206. lrc = robust_flock(pFile->h, LOCK_UN);
  26207. if ( lrc ) {
  26208. int tErrno = errno;
  26209. /* unlock failed with an error */
  26210. lrc = SQLITE_IOERR_UNLOCK;
  26211. if( IS_LOCK_ERROR(lrc) ){
  26212. storeLastErrno(pFile, tErrno);
  26213. rc = lrc;
  26214. }
  26215. }
  26216. } else {
  26217. int tErrno = errno;
  26218. reserved = 1;
  26219. /* someone else might have it reserved */
  26220. lrc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
  26221. if( IS_LOCK_ERROR(lrc) ){
  26222. storeLastErrno(pFile, tErrno);
  26223. rc = lrc;
  26224. }
  26225. }
  26226. }
  26227. OSTRACE(("TEST WR-LOCK %d %d %d (flock)\n", pFile->h, rc, reserved));
  26228. #ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
  26229. if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
  26230. rc = SQLITE_OK;
  26231. reserved=1;
  26232. }
  26233. #endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
  26234. *pResOut = reserved;
  26235. return rc;
  26236. }
  26237. /*
  26238. ** Lock the file with the lock specified by parameter eFileLock - one
  26239. ** of the following:
  26240. **
  26241. ** (1) SHARED_LOCK
  26242. ** (2) RESERVED_LOCK
  26243. ** (3) PENDING_LOCK
  26244. ** (4) EXCLUSIVE_LOCK
  26245. **
  26246. ** Sometimes when requesting one lock state, additional lock states
  26247. ** are inserted in between. The locking might fail on one of the later
  26248. ** transitions leaving the lock state different from what it started but
  26249. ** still short of its goal. The following chart shows the allowed
  26250. ** transitions and the inserted intermediate states:
  26251. **
  26252. ** UNLOCKED -> SHARED
  26253. ** SHARED -> RESERVED
  26254. ** SHARED -> (PENDING) -> EXCLUSIVE
  26255. ** RESERVED -> (PENDING) -> EXCLUSIVE
  26256. ** PENDING -> EXCLUSIVE
  26257. **
  26258. ** flock() only really support EXCLUSIVE locks. We track intermediate
  26259. ** lock states in the sqlite3_file structure, but all locks SHARED or
  26260. ** above are really EXCLUSIVE locks and exclude all other processes from
  26261. ** access the file.
  26262. **
  26263. ** This routine will only increase a lock. Use the sqlite3OsUnlock()
  26264. ** routine to lower a locking level.
  26265. */
  26266. static int flockLock(sqlite3_file *id, int eFileLock) {
  26267. int rc = SQLITE_OK;
  26268. unixFile *pFile = (unixFile*)id;
  26269. assert( pFile );
  26270. /* if we already have a lock, it is exclusive.
  26271. ** Just adjust level and punt on outta here. */
  26272. if (pFile->eFileLock > NO_LOCK) {
  26273. pFile->eFileLock = eFileLock;
  26274. return SQLITE_OK;
  26275. }
  26276. /* grab an exclusive lock */
  26277. if (robust_flock(pFile->h, LOCK_EX | LOCK_NB)) {
  26278. int tErrno = errno;
  26279. /* didn't get, must be busy */
  26280. rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
  26281. if( IS_LOCK_ERROR(rc) ){
  26282. storeLastErrno(pFile, tErrno);
  26283. }
  26284. } else {
  26285. /* got it, set the type and return ok */
  26286. pFile->eFileLock = eFileLock;
  26287. }
  26288. OSTRACE(("LOCK %d %s %s (flock)\n", pFile->h, azFileLock(eFileLock),
  26289. rc==SQLITE_OK ? "ok" : "failed"));
  26290. #ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
  26291. if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
  26292. rc = SQLITE_BUSY;
  26293. }
  26294. #endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
  26295. return rc;
  26296. }
  26297. /*
  26298. ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
  26299. ** must be either NO_LOCK or SHARED_LOCK.
  26300. **
  26301. ** If the locking level of the file descriptor is already at or below
  26302. ** the requested locking level, this routine is a no-op.
  26303. */
  26304. static int flockUnlock(sqlite3_file *id, int eFileLock) {
  26305. unixFile *pFile = (unixFile*)id;
  26306. assert( pFile );
  26307. OSTRACE(("UNLOCK %d %d was %d pid=%d (flock)\n", pFile->h, eFileLock,
  26308. pFile->eFileLock, osGetpid(0)));
  26309. assert( eFileLock<=SHARED_LOCK );
  26310. /* no-op if possible */
  26311. if( pFile->eFileLock==eFileLock ){
  26312. return SQLITE_OK;
  26313. }
  26314. /* shared can just be set because we always have an exclusive */
  26315. if (eFileLock==SHARED_LOCK) {
  26316. pFile->eFileLock = eFileLock;
  26317. return SQLITE_OK;
  26318. }
  26319. /* no, really, unlock. */
  26320. if( robust_flock(pFile->h, LOCK_UN) ){
  26321. #ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
  26322. return SQLITE_OK;
  26323. #endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
  26324. return SQLITE_IOERR_UNLOCK;
  26325. }else{
  26326. pFile->eFileLock = NO_LOCK;
  26327. return SQLITE_OK;
  26328. }
  26329. }
  26330. /*
  26331. ** Close a file.
  26332. */
  26333. static int flockClose(sqlite3_file *id) {
  26334. int rc = SQLITE_OK;
  26335. if( id ){
  26336. flockUnlock(id, NO_LOCK);
  26337. rc = closeUnixFile(id);
  26338. }
  26339. return rc;
  26340. }
  26341. #endif /* SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORK */
  26342. /******************* End of the flock lock implementation *********************
  26343. ******************************************************************************/
  26344. /******************************************************************************
  26345. ************************ Begin Named Semaphore Locking ************************
  26346. **
  26347. ** Named semaphore locking is only supported on VxWorks.
  26348. **
  26349. ** Semaphore locking is like dot-lock and flock in that it really only
  26350. ** supports EXCLUSIVE locking. Only a single process can read or write
  26351. ** the database file at a time. This reduces potential concurrency, but
  26352. ** makes the lock implementation much easier.
  26353. */
  26354. #if OS_VXWORKS
  26355. /*
  26356. ** This routine checks if there is a RESERVED lock held on the specified
  26357. ** file by this or any other process. If such a lock is held, set *pResOut
  26358. ** to a non-zero value otherwise *pResOut is set to zero. The return value
  26359. ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
  26360. */
  26361. static int semXCheckReservedLock(sqlite3_file *id, int *pResOut) {
  26362. int rc = SQLITE_OK;
  26363. int reserved = 0;
  26364. unixFile *pFile = (unixFile*)id;
  26365. SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
  26366. assert( pFile );
  26367. /* Check if a thread in this process holds such a lock */
  26368. if( pFile->eFileLock>SHARED_LOCK ){
  26369. reserved = 1;
  26370. }
  26371. /* Otherwise see if some other process holds it. */
  26372. if( !reserved ){
  26373. sem_t *pSem = pFile->pInode->pSem;
  26374. if( sem_trywait(pSem)==-1 ){
  26375. int tErrno = errno;
  26376. if( EAGAIN != tErrno ){
  26377. rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_CHECKRESERVEDLOCK);
  26378. storeLastErrno(pFile, tErrno);
  26379. } else {
  26380. /* someone else has the lock when we are in NO_LOCK */
  26381. reserved = (pFile->eFileLock < SHARED_LOCK);
  26382. }
  26383. }else{
  26384. /* we could have it if we want it */
  26385. sem_post(pSem);
  26386. }
  26387. }
  26388. OSTRACE(("TEST WR-LOCK %d %d %d (sem)\n", pFile->h, rc, reserved));
  26389. *pResOut = reserved;
  26390. return rc;
  26391. }
  26392. /*
  26393. ** Lock the file with the lock specified by parameter eFileLock - one
  26394. ** of the following:
  26395. **
  26396. ** (1) SHARED_LOCK
  26397. ** (2) RESERVED_LOCK
  26398. ** (3) PENDING_LOCK
  26399. ** (4) EXCLUSIVE_LOCK
  26400. **
  26401. ** Sometimes when requesting one lock state, additional lock states
  26402. ** are inserted in between. The locking might fail on one of the later
  26403. ** transitions leaving the lock state different from what it started but
  26404. ** still short of its goal. The following chart shows the allowed
  26405. ** transitions and the inserted intermediate states:
  26406. **
  26407. ** UNLOCKED -> SHARED
  26408. ** SHARED -> RESERVED
  26409. ** SHARED -> (PENDING) -> EXCLUSIVE
  26410. ** RESERVED -> (PENDING) -> EXCLUSIVE
  26411. ** PENDING -> EXCLUSIVE
  26412. **
  26413. ** Semaphore locks only really support EXCLUSIVE locks. We track intermediate
  26414. ** lock states in the sqlite3_file structure, but all locks SHARED or
  26415. ** above are really EXCLUSIVE locks and exclude all other processes from
  26416. ** access the file.
  26417. **
  26418. ** This routine will only increase a lock. Use the sqlite3OsUnlock()
  26419. ** routine to lower a locking level.
  26420. */
  26421. static int semXLock(sqlite3_file *id, int eFileLock) {
  26422. unixFile *pFile = (unixFile*)id;
  26423. sem_t *pSem = pFile->pInode->pSem;
  26424. int rc = SQLITE_OK;
  26425. /* if we already have a lock, it is exclusive.
  26426. ** Just adjust level and punt on outta here. */
  26427. if (pFile->eFileLock > NO_LOCK) {
  26428. pFile->eFileLock = eFileLock;
  26429. rc = SQLITE_OK;
  26430. goto sem_end_lock;
  26431. }
  26432. /* lock semaphore now but bail out when already locked. */
  26433. if( sem_trywait(pSem)==-1 ){
  26434. rc = SQLITE_BUSY;
  26435. goto sem_end_lock;
  26436. }
  26437. /* got it, set the type and return ok */
  26438. pFile->eFileLock = eFileLock;
  26439. sem_end_lock:
  26440. return rc;
  26441. }
  26442. /*
  26443. ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
  26444. ** must be either NO_LOCK or SHARED_LOCK.
  26445. **
  26446. ** If the locking level of the file descriptor is already at or below
  26447. ** the requested locking level, this routine is a no-op.
  26448. */
  26449. static int semXUnlock(sqlite3_file *id, int eFileLock) {
  26450. unixFile *pFile = (unixFile*)id;
  26451. sem_t *pSem = pFile->pInode->pSem;
  26452. assert( pFile );
  26453. assert( pSem );
  26454. OSTRACE(("UNLOCK %d %d was %d pid=%d (sem)\n", pFile->h, eFileLock,
  26455. pFile->eFileLock, osGetpid(0)));
  26456. assert( eFileLock<=SHARED_LOCK );
  26457. /* no-op if possible */
  26458. if( pFile->eFileLock==eFileLock ){
  26459. return SQLITE_OK;
  26460. }
  26461. /* shared can just be set because we always have an exclusive */
  26462. if (eFileLock==SHARED_LOCK) {
  26463. pFile->eFileLock = eFileLock;
  26464. return SQLITE_OK;
  26465. }
  26466. /* no, really unlock. */
  26467. if ( sem_post(pSem)==-1 ) {
  26468. int rc, tErrno = errno;
  26469. rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
  26470. if( IS_LOCK_ERROR(rc) ){
  26471. storeLastErrno(pFile, tErrno);
  26472. }
  26473. return rc;
  26474. }
  26475. pFile->eFileLock = NO_LOCK;
  26476. return SQLITE_OK;
  26477. }
  26478. /*
  26479. ** Close a file.
  26480. */
  26481. static int semXClose(sqlite3_file *id) {
  26482. if( id ){
  26483. unixFile *pFile = (unixFile*)id;
  26484. semXUnlock(id, NO_LOCK);
  26485. assert( pFile );
  26486. unixEnterMutex();
  26487. releaseInodeInfo(pFile);
  26488. unixLeaveMutex();
  26489. closeUnixFile(id);
  26490. }
  26491. return SQLITE_OK;
  26492. }
  26493. #endif /* OS_VXWORKS */
  26494. /*
  26495. ** Named semaphore locking is only available on VxWorks.
  26496. **
  26497. *************** End of the named semaphore lock implementation ****************
  26498. ******************************************************************************/
  26499. /******************************************************************************
  26500. *************************** Begin AFP Locking *********************************
  26501. **
  26502. ** AFP is the Apple Filing Protocol. AFP is a network filesystem found
  26503. ** on Apple Macintosh computers - both OS9 and OSX.
  26504. **
  26505. ** Third-party implementations of AFP are available. But this code here
  26506. ** only works on OSX.
  26507. */
  26508. #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
  26509. /*
  26510. ** The afpLockingContext structure contains all afp lock specific state
  26511. */
  26512. typedef struct afpLockingContext afpLockingContext;
  26513. struct afpLockingContext {
  26514. int reserved;
  26515. const char *dbPath; /* Name of the open file */
  26516. };
  26517. struct ByteRangeLockPB2
  26518. {
  26519. unsigned long long offset; /* offset to first byte to lock */
  26520. unsigned long long length; /* nbr of bytes to lock */
  26521. unsigned long long retRangeStart; /* nbr of 1st byte locked if successful */
  26522. unsigned char unLockFlag; /* 1 = unlock, 0 = lock */
  26523. unsigned char startEndFlag; /* 1=rel to end of fork, 0=rel to start */
  26524. int fd; /* file desc to assoc this lock with */
  26525. };
  26526. #define afpfsByteRangeLock2FSCTL _IOWR('z', 23, struct ByteRangeLockPB2)
  26527. /*
  26528. ** This is a utility for setting or clearing a bit-range lock on an
  26529. ** AFP filesystem.
  26530. **
  26531. ** Return SQLITE_OK on success, SQLITE_BUSY on failure.
  26532. */
  26533. static int afpSetLock(
  26534. const char *path, /* Name of the file to be locked or unlocked */
  26535. unixFile *pFile, /* Open file descriptor on path */
  26536. unsigned long long offset, /* First byte to be locked */
  26537. unsigned long long length, /* Number of bytes to lock */
  26538. int setLockFlag /* True to set lock. False to clear lock */
  26539. ){
  26540. struct ByteRangeLockPB2 pb;
  26541. int err;
  26542. pb.unLockFlag = setLockFlag ? 0 : 1;
  26543. pb.startEndFlag = 0;
  26544. pb.offset = offset;
  26545. pb.length = length;
  26546. pb.fd = pFile->h;
  26547. OSTRACE(("AFPSETLOCK [%s] for %d%s in range %llx:%llx\n",
  26548. (setLockFlag?"ON":"OFF"), pFile->h, (pb.fd==-1?"[testval-1]":""),
  26549. offset, length));
  26550. err = fsctl(path, afpfsByteRangeLock2FSCTL, &pb, 0);
  26551. if ( err==-1 ) {
  26552. int rc;
  26553. int tErrno = errno;
  26554. OSTRACE(("AFPSETLOCK failed to fsctl() '%s' %d %s\n",
  26555. path, tErrno, strerror(tErrno)));
  26556. #ifdef SQLITE_IGNORE_AFP_LOCK_ERRORS
  26557. rc = SQLITE_BUSY;
  26558. #else
  26559. rc = sqliteErrorFromPosixError(tErrno,
  26560. setLockFlag ? SQLITE_IOERR_LOCK : SQLITE_IOERR_UNLOCK);
  26561. #endif /* SQLITE_IGNORE_AFP_LOCK_ERRORS */
  26562. if( IS_LOCK_ERROR(rc) ){
  26563. storeLastErrno(pFile, tErrno);
  26564. }
  26565. return rc;
  26566. } else {
  26567. return SQLITE_OK;
  26568. }
  26569. }
  26570. /*
  26571. ** This routine checks if there is a RESERVED lock held on the specified
  26572. ** file by this or any other process. If such a lock is held, set *pResOut
  26573. ** to a non-zero value otherwise *pResOut is set to zero. The return value
  26574. ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
  26575. */
  26576. static int afpCheckReservedLock(sqlite3_file *id, int *pResOut){
  26577. int rc = SQLITE_OK;
  26578. int reserved = 0;
  26579. unixFile *pFile = (unixFile*)id;
  26580. afpLockingContext *context;
  26581. SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
  26582. assert( pFile );
  26583. context = (afpLockingContext *) pFile->lockingContext;
  26584. if( context->reserved ){
  26585. *pResOut = 1;
  26586. return SQLITE_OK;
  26587. }
  26588. unixEnterMutex(); /* Because pFile->pInode is shared across threads */
  26589. /* Check if a thread in this process holds such a lock */
  26590. if( pFile->pInode->eFileLock>SHARED_LOCK ){
  26591. reserved = 1;
  26592. }
  26593. /* Otherwise see if some other process holds it.
  26594. */
  26595. if( !reserved ){
  26596. /* lock the RESERVED byte */
  26597. int lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
  26598. if( SQLITE_OK==lrc ){
  26599. /* if we succeeded in taking the reserved lock, unlock it to restore
  26600. ** the original state */
  26601. lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
  26602. } else {
  26603. /* if we failed to get the lock then someone else must have it */
  26604. reserved = 1;
  26605. }
  26606. if( IS_LOCK_ERROR(lrc) ){
  26607. rc=lrc;
  26608. }
  26609. }
  26610. unixLeaveMutex();
  26611. OSTRACE(("TEST WR-LOCK %d %d %d (afp)\n", pFile->h, rc, reserved));
  26612. *pResOut = reserved;
  26613. return rc;
  26614. }
  26615. /*
  26616. ** Lock the file with the lock specified by parameter eFileLock - one
  26617. ** of the following:
  26618. **
  26619. ** (1) SHARED_LOCK
  26620. ** (2) RESERVED_LOCK
  26621. ** (3) PENDING_LOCK
  26622. ** (4) EXCLUSIVE_LOCK
  26623. **
  26624. ** Sometimes when requesting one lock state, additional lock states
  26625. ** are inserted in between. The locking might fail on one of the later
  26626. ** transitions leaving the lock state different from what it started but
  26627. ** still short of its goal. The following chart shows the allowed
  26628. ** transitions and the inserted intermediate states:
  26629. **
  26630. ** UNLOCKED -> SHARED
  26631. ** SHARED -> RESERVED
  26632. ** SHARED -> (PENDING) -> EXCLUSIVE
  26633. ** RESERVED -> (PENDING) -> EXCLUSIVE
  26634. ** PENDING -> EXCLUSIVE
  26635. **
  26636. ** This routine will only increase a lock. Use the sqlite3OsUnlock()
  26637. ** routine to lower a locking level.
  26638. */
  26639. static int afpLock(sqlite3_file *id, int eFileLock){
  26640. int rc = SQLITE_OK;
  26641. unixFile *pFile = (unixFile*)id;
  26642. unixInodeInfo *pInode = pFile->pInode;
  26643. afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
  26644. assert( pFile );
  26645. OSTRACE(("LOCK %d %s was %s(%s,%d) pid=%d (afp)\n", pFile->h,
  26646. azFileLock(eFileLock), azFileLock(pFile->eFileLock),
  26647. azFileLock(pInode->eFileLock), pInode->nShared , osGetpid(0)));
  26648. /* If there is already a lock of this type or more restrictive on the
  26649. ** unixFile, do nothing. Don't use the afp_end_lock: exit path, as
  26650. ** unixEnterMutex() hasn't been called yet.
  26651. */
  26652. if( pFile->eFileLock>=eFileLock ){
  26653. OSTRACE(("LOCK %d %s ok (already held) (afp)\n", pFile->h,
  26654. azFileLock(eFileLock)));
  26655. return SQLITE_OK;
  26656. }
  26657. /* Make sure the locking sequence is correct
  26658. ** (1) We never move from unlocked to anything higher than shared lock.
  26659. ** (2) SQLite never explicitly requests a pendig lock.
  26660. ** (3) A shared lock is always held when a reserve lock is requested.
  26661. */
  26662. assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
  26663. assert( eFileLock!=PENDING_LOCK );
  26664. assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
  26665. /* This mutex is needed because pFile->pInode is shared across threads
  26666. */
  26667. unixEnterMutex();
  26668. pInode = pFile->pInode;
  26669. /* If some thread using this PID has a lock via a different unixFile*
  26670. ** handle that precludes the requested lock, return BUSY.
  26671. */
  26672. if( (pFile->eFileLock!=pInode->eFileLock &&
  26673. (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
  26674. ){
  26675. rc = SQLITE_BUSY;
  26676. goto afp_end_lock;
  26677. }
  26678. /* If a SHARED lock is requested, and some thread using this PID already
  26679. ** has a SHARED or RESERVED lock, then increment reference counts and
  26680. ** return SQLITE_OK.
  26681. */
  26682. if( eFileLock==SHARED_LOCK &&
  26683. (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
  26684. assert( eFileLock==SHARED_LOCK );
  26685. assert( pFile->eFileLock==0 );
  26686. assert( pInode->nShared>0 );
  26687. pFile->eFileLock = SHARED_LOCK;
  26688. pInode->nShared++;
  26689. pInode->nLock++;
  26690. goto afp_end_lock;
  26691. }
  26692. /* A PENDING lock is needed before acquiring a SHARED lock and before
  26693. ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
  26694. ** be released.
  26695. */
  26696. if( eFileLock==SHARED_LOCK
  26697. || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
  26698. ){
  26699. int failed;
  26700. failed = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 1);
  26701. if (failed) {
  26702. rc = failed;
  26703. goto afp_end_lock;
  26704. }
  26705. }
  26706. /* If control gets to this point, then actually go ahead and make
  26707. ** operating system calls for the specified lock.
  26708. */
  26709. if( eFileLock==SHARED_LOCK ){
  26710. int lrc1, lrc2, lrc1Errno = 0;
  26711. long lk, mask;
  26712. assert( pInode->nShared==0 );
  26713. assert( pInode->eFileLock==0 );
  26714. mask = (sizeof(long)==8) ? LARGEST_INT64 : 0x7fffffff;
  26715. /* Now get the read-lock SHARED_LOCK */
  26716. /* note that the quality of the randomness doesn't matter that much */
  26717. lk = random();
  26718. pInode->sharedByte = (lk & mask)%(SHARED_SIZE - 1);
  26719. lrc1 = afpSetLock(context->dbPath, pFile,
  26720. SHARED_FIRST+pInode->sharedByte, 1, 1);
  26721. if( IS_LOCK_ERROR(lrc1) ){
  26722. lrc1Errno = pFile->lastErrno;
  26723. }
  26724. /* Drop the temporary PENDING lock */
  26725. lrc2 = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
  26726. if( IS_LOCK_ERROR(lrc1) ) {
  26727. storeLastErrno(pFile, lrc1Errno);
  26728. rc = lrc1;
  26729. goto afp_end_lock;
  26730. } else if( IS_LOCK_ERROR(lrc2) ){
  26731. rc = lrc2;
  26732. goto afp_end_lock;
  26733. } else if( lrc1 != SQLITE_OK ) {
  26734. rc = lrc1;
  26735. } else {
  26736. pFile->eFileLock = SHARED_LOCK;
  26737. pInode->nLock++;
  26738. pInode->nShared = 1;
  26739. }
  26740. }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
  26741. /* We are trying for an exclusive lock but another thread in this
  26742. ** same process is still holding a shared lock. */
  26743. rc = SQLITE_BUSY;
  26744. }else{
  26745. /* The request was for a RESERVED or EXCLUSIVE lock. It is
  26746. ** assumed that there is a SHARED or greater lock on the file
  26747. ** already.
  26748. */
  26749. int failed = 0;
  26750. assert( 0!=pFile->eFileLock );
  26751. if (eFileLock >= RESERVED_LOCK && pFile->eFileLock < RESERVED_LOCK) {
  26752. /* Acquire a RESERVED lock */
  26753. failed = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
  26754. if( !failed ){
  26755. context->reserved = 1;
  26756. }
  26757. }
  26758. if (!failed && eFileLock == EXCLUSIVE_LOCK) {
  26759. /* Acquire an EXCLUSIVE lock */
  26760. /* Remove the shared lock before trying the range. we'll need to
  26761. ** reestablish the shared lock if we can't get the afpUnlock
  26762. */
  26763. if( !(failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST +
  26764. pInode->sharedByte, 1, 0)) ){
  26765. int failed2 = SQLITE_OK;
  26766. /* now attemmpt to get the exclusive lock range */
  26767. failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST,
  26768. SHARED_SIZE, 1);
  26769. if( failed && (failed2 = afpSetLock(context->dbPath, pFile,
  26770. SHARED_FIRST + pInode->sharedByte, 1, 1)) ){
  26771. /* Can't reestablish the shared lock. Sqlite can't deal, this is
  26772. ** a critical I/O error
  26773. */
  26774. rc = ((failed & SQLITE_IOERR) == SQLITE_IOERR) ? failed2 :
  26775. SQLITE_IOERR_LOCK;
  26776. goto afp_end_lock;
  26777. }
  26778. }else{
  26779. rc = failed;
  26780. }
  26781. }
  26782. if( failed ){
  26783. rc = failed;
  26784. }
  26785. }
  26786. if( rc==SQLITE_OK ){
  26787. pFile->eFileLock = eFileLock;
  26788. pInode->eFileLock = eFileLock;
  26789. }else if( eFileLock==EXCLUSIVE_LOCK ){
  26790. pFile->eFileLock = PENDING_LOCK;
  26791. pInode->eFileLock = PENDING_LOCK;
  26792. }
  26793. afp_end_lock:
  26794. unixLeaveMutex();
  26795. OSTRACE(("LOCK %d %s %s (afp)\n", pFile->h, azFileLock(eFileLock),
  26796. rc==SQLITE_OK ? "ok" : "failed"));
  26797. return rc;
  26798. }
  26799. /*
  26800. ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
  26801. ** must be either NO_LOCK or SHARED_LOCK.
  26802. **
  26803. ** If the locking level of the file descriptor is already at or below
  26804. ** the requested locking level, this routine is a no-op.
  26805. */
  26806. static int afpUnlock(sqlite3_file *id, int eFileLock) {
  26807. int rc = SQLITE_OK;
  26808. unixFile *pFile = (unixFile*)id;
  26809. unixInodeInfo *pInode;
  26810. afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
  26811. int skipShared = 0;
  26812. #ifdef SQLITE_TEST
  26813. int h = pFile->h;
  26814. #endif
  26815. assert( pFile );
  26816. OSTRACE(("UNLOCK %d %d was %d(%d,%d) pid=%d (afp)\n", pFile->h, eFileLock,
  26817. pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
  26818. osGetpid(0)));
  26819. assert( eFileLock<=SHARED_LOCK );
  26820. if( pFile->eFileLock<=eFileLock ){
  26821. return SQLITE_OK;
  26822. }
  26823. unixEnterMutex();
  26824. pInode = pFile->pInode;
  26825. assert( pInode->nShared!=0 );
  26826. if( pFile->eFileLock>SHARED_LOCK ){
  26827. assert( pInode->eFileLock==pFile->eFileLock );
  26828. SimulateIOErrorBenign(1);
  26829. SimulateIOError( h=(-1) )
  26830. SimulateIOErrorBenign(0);
  26831. #ifdef SQLITE_DEBUG
  26832. /* When reducing a lock such that other processes can start
  26833. ** reading the database file again, make sure that the
  26834. ** transaction counter was updated if any part of the database
  26835. ** file changed. If the transaction counter is not updated,
  26836. ** other connections to the same file might not realize that
  26837. ** the file has changed and hence might not know to flush their
  26838. ** cache. The use of a stale cache can lead to database corruption.
  26839. */
  26840. assert( pFile->inNormalWrite==0
  26841. || pFile->dbUpdate==0
  26842. || pFile->transCntrChng==1 );
  26843. pFile->inNormalWrite = 0;
  26844. #endif
  26845. if( pFile->eFileLock==EXCLUSIVE_LOCK ){
  26846. rc = afpSetLock(context->dbPath, pFile, SHARED_FIRST, SHARED_SIZE, 0);
  26847. if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1) ){
  26848. /* only re-establish the shared lock if necessary */
  26849. int sharedLockByte = SHARED_FIRST+pInode->sharedByte;
  26850. rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 1);
  26851. } else {
  26852. skipShared = 1;
  26853. }
  26854. }
  26855. if( rc==SQLITE_OK && pFile->eFileLock>=PENDING_LOCK ){
  26856. rc = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
  26857. }
  26858. if( rc==SQLITE_OK && pFile->eFileLock>=RESERVED_LOCK && context->reserved ){
  26859. rc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
  26860. if( !rc ){
  26861. context->reserved = 0;
  26862. }
  26863. }
  26864. if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1)){
  26865. pInode->eFileLock = SHARED_LOCK;
  26866. }
  26867. }
  26868. if( rc==SQLITE_OK && eFileLock==NO_LOCK ){
  26869. /* Decrement the shared lock counter. Release the lock using an
  26870. ** OS call only when all threads in this same process have released
  26871. ** the lock.
  26872. */
  26873. unsigned long long sharedLockByte = SHARED_FIRST+pInode->sharedByte;
  26874. pInode->nShared--;
  26875. if( pInode->nShared==0 ){
  26876. SimulateIOErrorBenign(1);
  26877. SimulateIOError( h=(-1) )
  26878. SimulateIOErrorBenign(0);
  26879. if( !skipShared ){
  26880. rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 0);
  26881. }
  26882. if( !rc ){
  26883. pInode->eFileLock = NO_LOCK;
  26884. pFile->eFileLock = NO_LOCK;
  26885. }
  26886. }
  26887. if( rc==SQLITE_OK ){
  26888. pInode->nLock--;
  26889. assert( pInode->nLock>=0 );
  26890. if( pInode->nLock==0 ){
  26891. closePendingFds(pFile);
  26892. }
  26893. }
  26894. }
  26895. unixLeaveMutex();
  26896. if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
  26897. return rc;
  26898. }
  26899. /*
  26900. ** Close a file & cleanup AFP specific locking context
  26901. */
  26902. static int afpClose(sqlite3_file *id) {
  26903. int rc = SQLITE_OK;
  26904. if( id ){
  26905. unixFile *pFile = (unixFile*)id;
  26906. afpUnlock(id, NO_LOCK);
  26907. unixEnterMutex();
  26908. if( pFile->pInode && pFile->pInode->nLock ){
  26909. /* If there are outstanding locks, do not actually close the file just
  26910. ** yet because that would clear those locks. Instead, add the file
  26911. ** descriptor to pInode->aPending. It will be automatically closed when
  26912. ** the last lock is cleared.
  26913. */
  26914. setPendingFd(pFile);
  26915. }
  26916. releaseInodeInfo(pFile);
  26917. sqlite3_free(pFile->lockingContext);
  26918. rc = closeUnixFile(id);
  26919. unixLeaveMutex();
  26920. }
  26921. return rc;
  26922. }
  26923. #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
  26924. /*
  26925. ** The code above is the AFP lock implementation. The code is specific
  26926. ** to MacOSX and does not work on other unix platforms. No alternative
  26927. ** is available. If you don't compile for a mac, then the "unix-afp"
  26928. ** VFS is not available.
  26929. **
  26930. ********************* End of the AFP lock implementation **********************
  26931. ******************************************************************************/
  26932. /******************************************************************************
  26933. *************************** Begin NFS Locking ********************************/
  26934. #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
  26935. /*
  26936. ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
  26937. ** must be either NO_LOCK or SHARED_LOCK.
  26938. **
  26939. ** If the locking level of the file descriptor is already at or below
  26940. ** the requested locking level, this routine is a no-op.
  26941. */
  26942. static int nfsUnlock(sqlite3_file *id, int eFileLock){
  26943. return posixUnlock(id, eFileLock, 1);
  26944. }
  26945. #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
  26946. /*
  26947. ** The code above is the NFS lock implementation. The code is specific
  26948. ** to MacOSX and does not work on other unix platforms. No alternative
  26949. ** is available.
  26950. **
  26951. ********************* End of the NFS lock implementation **********************
  26952. ******************************************************************************/
  26953. /******************************************************************************
  26954. **************** Non-locking sqlite3_file methods *****************************
  26955. **
  26956. ** The next division contains implementations for all methods of the
  26957. ** sqlite3_file object other than the locking methods. The locking
  26958. ** methods were defined in divisions above (one locking method per
  26959. ** division). Those methods that are common to all locking modes
  26960. ** are gather together into this division.
  26961. */
  26962. /*
  26963. ** Seek to the offset passed as the second argument, then read cnt
  26964. ** bytes into pBuf. Return the number of bytes actually read.
  26965. **
  26966. ** NB: If you define USE_PREAD or USE_PREAD64, then it might also
  26967. ** be necessary to define _XOPEN_SOURCE to be 500. This varies from
  26968. ** one system to another. Since SQLite does not define USE_PREAD
  26969. ** in any form by default, we will not attempt to define _XOPEN_SOURCE.
  26970. ** See tickets #2741 and #2681.
  26971. **
  26972. ** To avoid stomping the errno value on a failed read the lastErrno value
  26973. ** is set before returning.
  26974. */
  26975. static int seekAndRead(unixFile *id, sqlite3_int64 offset, void *pBuf, int cnt){
  26976. int got;
  26977. int prior = 0;
  26978. #if (!defined(USE_PREAD) && !defined(USE_PREAD64))
  26979. i64 newOffset;
  26980. #endif
  26981. TIMER_START;
  26982. assert( cnt==(cnt&0x1ffff) );
  26983. assert( id->h>2 );
  26984. cnt &= 0x1ffff;
  26985. do{
  26986. #if defined(USE_PREAD)
  26987. got = osPread(id->h, pBuf, cnt, offset);
  26988. SimulateIOError( got = -1 );
  26989. #elif defined(USE_PREAD64)
  26990. got = osPread64(id->h, pBuf, cnt, offset);
  26991. SimulateIOError( got = -1 );
  26992. #else
  26993. newOffset = lseek(id->h, offset, SEEK_SET);
  26994. SimulateIOError( newOffset-- );
  26995. if( newOffset!=offset ){
  26996. if( newOffset == -1 ){
  26997. storeLastErrno((unixFile*)id, errno);
  26998. }else{
  26999. storeLastErrno((unixFile*)id, 0);
  27000. }
  27001. return -1;
  27002. }
  27003. got = osRead(id->h, pBuf, cnt);
  27004. #endif
  27005. if( got==cnt ) break;
  27006. if( got<0 ){
  27007. if( errno==EINTR ){ got = 1; continue; }
  27008. prior = 0;
  27009. storeLastErrno((unixFile*)id, errno);
  27010. break;
  27011. }else if( got>0 ){
  27012. cnt -= got;
  27013. offset += got;
  27014. prior += got;
  27015. pBuf = (void*)(got + (char*)pBuf);
  27016. }
  27017. }while( got>0 );
  27018. TIMER_END;
  27019. OSTRACE(("READ %-3d %5d %7lld %llu\n",
  27020. id->h, got+prior, offset-prior, TIMER_ELAPSED));
  27021. return got+prior;
  27022. }
  27023. /*
  27024. ** Read data from a file into a buffer. Return SQLITE_OK if all
  27025. ** bytes were read successfully and SQLITE_IOERR if anything goes
  27026. ** wrong.
  27027. */
  27028. static int unixRead(
  27029. sqlite3_file *id,
  27030. void *pBuf,
  27031. int amt,
  27032. sqlite3_int64 offset
  27033. ){
  27034. unixFile *pFile = (unixFile *)id;
  27035. int got;
  27036. assert( id );
  27037. assert( offset>=0 );
  27038. assert( amt>0 );
  27039. /* If this is a database file (not a journal, master-journal or temp
  27040. ** file), the bytes in the locking range should never be read or written. */
  27041. #if 0
  27042. assert( pFile->pUnused==0
  27043. || offset>=PENDING_BYTE+512
  27044. || offset+amt<=PENDING_BYTE
  27045. );
  27046. #endif
  27047. #if SQLITE_MAX_MMAP_SIZE>0
  27048. /* Deal with as much of this read request as possible by transfering
  27049. ** data from the memory mapping using memcpy(). */
  27050. if( offset<pFile->mmapSize ){
  27051. if( offset+amt <= pFile->mmapSize ){
  27052. memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], amt);
  27053. return SQLITE_OK;
  27054. }else{
  27055. int nCopy = pFile->mmapSize - offset;
  27056. memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], nCopy);
  27057. pBuf = &((u8 *)pBuf)[nCopy];
  27058. amt -= nCopy;
  27059. offset += nCopy;
  27060. }
  27061. }
  27062. #endif
  27063. got = seekAndRead(pFile, offset, pBuf, amt);
  27064. if( got==amt ){
  27065. return SQLITE_OK;
  27066. }else if( got<0 ){
  27067. /* lastErrno set by seekAndRead */
  27068. return SQLITE_IOERR_READ;
  27069. }else{
  27070. storeLastErrno(pFile, 0); /* not a system error */
  27071. /* Unread parts of the buffer must be zero-filled */
  27072. memset(&((char*)pBuf)[got], 0, amt-got);
  27073. return SQLITE_IOERR_SHORT_READ;
  27074. }
  27075. }
  27076. /*
  27077. ** Attempt to seek the file-descriptor passed as the first argument to
  27078. ** absolute offset iOff, then attempt to write nBuf bytes of data from
  27079. ** pBuf to it. If an error occurs, return -1 and set *piErrno. Otherwise,
  27080. ** return the actual number of bytes written (which may be less than
  27081. ** nBuf).
  27082. */
  27083. static int seekAndWriteFd(
  27084. int fd, /* File descriptor to write to */
  27085. i64 iOff, /* File offset to begin writing at */
  27086. const void *pBuf, /* Copy data from this buffer to the file */
  27087. int nBuf, /* Size of buffer pBuf in bytes */
  27088. int *piErrno /* OUT: Error number if error occurs */
  27089. ){
  27090. int rc = 0; /* Value returned by system call */
  27091. assert( nBuf==(nBuf&0x1ffff) );
  27092. assert( fd>2 );
  27093. nBuf &= 0x1ffff;
  27094. TIMER_START;
  27095. #if defined(USE_PREAD)
  27096. do{ rc = (int)osPwrite(fd, pBuf, nBuf, iOff); }while( rc<0 && errno==EINTR );
  27097. #elif defined(USE_PREAD64)
  27098. do{ rc = (int)osPwrite64(fd, pBuf, nBuf, iOff);}while( rc<0 && errno==EINTR);
  27099. #else
  27100. do{
  27101. i64 iSeek = lseek(fd, iOff, SEEK_SET);
  27102. SimulateIOError( iSeek-- );
  27103. if( iSeek!=iOff ){
  27104. if( piErrno ) *piErrno = (iSeek==-1 ? errno : 0);
  27105. return -1;
  27106. }
  27107. rc = osWrite(fd, pBuf, nBuf);
  27108. }while( rc<0 && errno==EINTR );
  27109. #endif
  27110. TIMER_END;
  27111. OSTRACE(("WRITE %-3d %5d %7lld %llu\n", fd, rc, iOff, TIMER_ELAPSED));
  27112. if( rc<0 && piErrno ) *piErrno = errno;
  27113. return rc;
  27114. }
  27115. /*
  27116. ** Seek to the offset in id->offset then read cnt bytes into pBuf.
  27117. ** Return the number of bytes actually read. Update the offset.
  27118. **
  27119. ** To avoid stomping the errno value on a failed write the lastErrno value
  27120. ** is set before returning.
  27121. */
  27122. static int seekAndWrite(unixFile *id, i64 offset, const void *pBuf, int cnt){
  27123. return seekAndWriteFd(id->h, offset, pBuf, cnt, &id->lastErrno);
  27124. }
  27125. /*
  27126. ** Write data from a buffer into a file. Return SQLITE_OK on success
  27127. ** or some other error code on failure.
  27128. */
  27129. static int unixWrite(
  27130. sqlite3_file *id,
  27131. const void *pBuf,
  27132. int amt,
  27133. sqlite3_int64 offset
  27134. ){
  27135. unixFile *pFile = (unixFile*)id;
  27136. int wrote = 0;
  27137. assert( id );
  27138. assert( amt>0 );
  27139. /* If this is a database file (not a journal, master-journal or temp
  27140. ** file), the bytes in the locking range should never be read or written. */
  27141. #if 0
  27142. assert( pFile->pUnused==0
  27143. || offset>=PENDING_BYTE+512
  27144. || offset+amt<=PENDING_BYTE
  27145. );
  27146. #endif
  27147. #ifdef SQLITE_DEBUG
  27148. /* If we are doing a normal write to a database file (as opposed to
  27149. ** doing a hot-journal rollback or a write to some file other than a
  27150. ** normal database file) then record the fact that the database
  27151. ** has changed. If the transaction counter is modified, record that
  27152. ** fact too.
  27153. */
  27154. if( pFile->inNormalWrite ){
  27155. pFile->dbUpdate = 1; /* The database has been modified */
  27156. if( offset<=24 && offset+amt>=27 ){
  27157. int rc;
  27158. char oldCntr[4];
  27159. SimulateIOErrorBenign(1);
  27160. rc = seekAndRead(pFile, 24, oldCntr, 4);
  27161. SimulateIOErrorBenign(0);
  27162. if( rc!=4 || memcmp(oldCntr, &((char*)pBuf)[24-offset], 4)!=0 ){
  27163. pFile->transCntrChng = 1; /* The transaction counter has changed */
  27164. }
  27165. }
  27166. }
  27167. #endif
  27168. #if SQLITE_MAX_MMAP_SIZE>0
  27169. /* Deal with as much of this write request as possible by transfering
  27170. ** data from the memory mapping using memcpy(). */
  27171. if( offset<pFile->mmapSize ){
  27172. if( offset+amt <= pFile->mmapSize ){
  27173. memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, amt);
  27174. return SQLITE_OK;
  27175. }else{
  27176. int nCopy = pFile->mmapSize - offset;
  27177. memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, nCopy);
  27178. pBuf = &((u8 *)pBuf)[nCopy];
  27179. amt -= nCopy;
  27180. offset += nCopy;
  27181. }
  27182. }
  27183. #endif
  27184. while( amt>0 && (wrote = seekAndWrite(pFile, offset, pBuf, amt))>0 ){
  27185. amt -= wrote;
  27186. offset += wrote;
  27187. pBuf = &((char*)pBuf)[wrote];
  27188. }
  27189. SimulateIOError(( wrote=(-1), amt=1 ));
  27190. SimulateDiskfullError(( wrote=0, amt=1 ));
  27191. if( amt>0 ){
  27192. if( wrote<0 && pFile->lastErrno!=ENOSPC ){
  27193. /* lastErrno set by seekAndWrite */
  27194. return SQLITE_IOERR_WRITE;
  27195. }else{
  27196. storeLastErrno(pFile, 0); /* not a system error */
  27197. return SQLITE_FULL;
  27198. }
  27199. }
  27200. return SQLITE_OK;
  27201. }
  27202. #ifdef SQLITE_TEST
  27203. /*
  27204. ** Count the number of fullsyncs and normal syncs. This is used to test
  27205. ** that syncs and fullsyncs are occurring at the right times.
  27206. */
  27207. SQLITE_API int sqlite3_sync_count = 0;
  27208. SQLITE_API int sqlite3_fullsync_count = 0;
  27209. #endif
  27210. /*
  27211. ** We do not trust systems to provide a working fdatasync(). Some do.
  27212. ** Others do no. To be safe, we will stick with the (slightly slower)
  27213. ** fsync(). If you know that your system does support fdatasync() correctly,
  27214. ** then simply compile with -Dfdatasync=fdatasync or -DHAVE_FDATASYNC
  27215. */
  27216. #if !defined(fdatasync) && !HAVE_FDATASYNC
  27217. # define fdatasync fsync
  27218. #endif
  27219. /*
  27220. ** Define HAVE_FULLFSYNC to 0 or 1 depending on whether or not
  27221. ** the F_FULLFSYNC macro is defined. F_FULLFSYNC is currently
  27222. ** only available on Mac OS X. But that could change.
  27223. */
  27224. #ifdef F_FULLFSYNC
  27225. # define HAVE_FULLFSYNC 1
  27226. #else
  27227. # define HAVE_FULLFSYNC 0
  27228. #endif
  27229. /*
  27230. ** The fsync() system call does not work as advertised on many
  27231. ** unix systems. The following procedure is an attempt to make
  27232. ** it work better.
  27233. **
  27234. ** The SQLITE_NO_SYNC macro disables all fsync()s. This is useful
  27235. ** for testing when we want to run through the test suite quickly.
  27236. ** You are strongly advised *not* to deploy with SQLITE_NO_SYNC
  27237. ** enabled, however, since with SQLITE_NO_SYNC enabled, an OS crash
  27238. ** or power failure will likely corrupt the database file.
  27239. **
  27240. ** SQLite sets the dataOnly flag if the size of the file is unchanged.
  27241. ** The idea behind dataOnly is that it should only write the file content
  27242. ** to disk, not the inode. We only set dataOnly if the file size is
  27243. ** unchanged since the file size is part of the inode. However,
  27244. ** Ted Ts'o tells us that fdatasync() will also write the inode if the
  27245. ** file size has changed. The only real difference between fdatasync()
  27246. ** and fsync(), Ted tells us, is that fdatasync() will not flush the
  27247. ** inode if the mtime or owner or other inode attributes have changed.
  27248. ** We only care about the file size, not the other file attributes, so
  27249. ** as far as SQLite is concerned, an fdatasync() is always adequate.
  27250. ** So, we always use fdatasync() if it is available, regardless of
  27251. ** the value of the dataOnly flag.
  27252. */
  27253. static int full_fsync(int fd, int fullSync, int dataOnly){
  27254. int rc;
  27255. /* The following "ifdef/elif/else/" block has the same structure as
  27256. ** the one below. It is replicated here solely to avoid cluttering
  27257. ** up the real code with the UNUSED_PARAMETER() macros.
  27258. */
  27259. #ifdef SQLITE_NO_SYNC
  27260. UNUSED_PARAMETER(fd);
  27261. UNUSED_PARAMETER(fullSync);
  27262. UNUSED_PARAMETER(dataOnly);
  27263. #elif HAVE_FULLFSYNC
  27264. UNUSED_PARAMETER(dataOnly);
  27265. #else
  27266. UNUSED_PARAMETER(fullSync);
  27267. UNUSED_PARAMETER(dataOnly);
  27268. #endif
  27269. /* Record the number of times that we do a normal fsync() and
  27270. ** FULLSYNC. This is used during testing to verify that this procedure
  27271. ** gets called with the correct arguments.
  27272. */
  27273. #ifdef SQLITE_TEST
  27274. if( fullSync ) sqlite3_fullsync_count++;
  27275. sqlite3_sync_count++;
  27276. #endif
  27277. /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
  27278. ** no-op
  27279. */
  27280. #ifdef SQLITE_NO_SYNC
  27281. rc = SQLITE_OK;
  27282. #elif HAVE_FULLFSYNC
  27283. if( fullSync ){
  27284. rc = osFcntl(fd, F_FULLFSYNC, 0);
  27285. }else{
  27286. rc = 1;
  27287. }
  27288. /* If the FULLFSYNC failed, fall back to attempting an fsync().
  27289. ** It shouldn't be possible for fullfsync to fail on the local
  27290. ** file system (on OSX), so failure indicates that FULLFSYNC
  27291. ** isn't supported for this file system. So, attempt an fsync
  27292. ** and (for now) ignore the overhead of a superfluous fcntl call.
  27293. ** It'd be better to detect fullfsync support once and avoid
  27294. ** the fcntl call every time sync is called.
  27295. */
  27296. if( rc ) rc = fsync(fd);
  27297. #elif defined(__APPLE__)
  27298. /* fdatasync() on HFS+ doesn't yet flush the file size if it changed correctly
  27299. ** so currently we default to the macro that redefines fdatasync to fsync
  27300. */
  27301. rc = fsync(fd);
  27302. #else
  27303. rc = fdatasync(fd);
  27304. #if OS_VXWORKS
  27305. if( rc==-1 && errno==ENOTSUP ){
  27306. rc = fsync(fd);
  27307. }
  27308. #endif /* OS_VXWORKS */
  27309. #endif /* ifdef SQLITE_NO_SYNC elif HAVE_FULLFSYNC */
  27310. if( OS_VXWORKS && rc!= -1 ){
  27311. rc = 0;
  27312. }
  27313. return rc;
  27314. }
  27315. /*
  27316. ** Open a file descriptor to the directory containing file zFilename.
  27317. ** If successful, *pFd is set to the opened file descriptor and
  27318. ** SQLITE_OK is returned. If an error occurs, either SQLITE_NOMEM
  27319. ** or SQLITE_CANTOPEN is returned and *pFd is set to an undefined
  27320. ** value.
  27321. **
  27322. ** The directory file descriptor is used for only one thing - to
  27323. ** fsync() a directory to make sure file creation and deletion events
  27324. ** are flushed to disk. Such fsyncs are not needed on newer
  27325. ** journaling filesystems, but are required on older filesystems.
  27326. **
  27327. ** This routine can be overridden using the xSetSysCall interface.
  27328. ** The ability to override this routine was added in support of the
  27329. ** chromium sandbox. Opening a directory is a security risk (we are
  27330. ** told) so making it overrideable allows the chromium sandbox to
  27331. ** replace this routine with a harmless no-op. To make this routine
  27332. ** a no-op, replace it with a stub that returns SQLITE_OK but leaves
  27333. ** *pFd set to a negative number.
  27334. **
  27335. ** If SQLITE_OK is returned, the caller is responsible for closing
  27336. ** the file descriptor *pFd using close().
  27337. */
  27338. static int openDirectory(const char *zFilename, int *pFd){
  27339. int ii;
  27340. int fd = -1;
  27341. char zDirname[MAX_PATHNAME+1];
  27342. sqlite3_snprintf(MAX_PATHNAME, zDirname, "%s", zFilename);
  27343. for(ii=(int)strlen(zDirname); ii>1 && zDirname[ii]!='/'; ii--);
  27344. if( ii>0 ){
  27345. zDirname[ii] = '\0';
  27346. fd = robust_open(zDirname, O_RDONLY|O_BINARY, 0);
  27347. if( fd>=0 ){
  27348. OSTRACE(("OPENDIR %-3d %s\n", fd, zDirname));
  27349. }
  27350. }
  27351. *pFd = fd;
  27352. return (fd>=0?SQLITE_OK:unixLogError(SQLITE_CANTOPEN_BKPT, "open", zDirname));
  27353. }
  27354. /*
  27355. ** Make sure all writes to a particular file are committed to disk.
  27356. **
  27357. ** If dataOnly==0 then both the file itself and its metadata (file
  27358. ** size, access time, etc) are synced. If dataOnly!=0 then only the
  27359. ** file data is synced.
  27360. **
  27361. ** Under Unix, also make sure that the directory entry for the file
  27362. ** has been created by fsync-ing the directory that contains the file.
  27363. ** If we do not do this and we encounter a power failure, the directory
  27364. ** entry for the journal might not exist after we reboot. The next
  27365. ** SQLite to access the file will not know that the journal exists (because
  27366. ** the directory entry for the journal was never created) and the transaction
  27367. ** will not roll back - possibly leading to database corruption.
  27368. */
  27369. static int unixSync(sqlite3_file *id, int flags){
  27370. int rc;
  27371. unixFile *pFile = (unixFile*)id;
  27372. int isDataOnly = (flags&SQLITE_SYNC_DATAONLY);
  27373. int isFullsync = (flags&0x0F)==SQLITE_SYNC_FULL;
  27374. /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
  27375. assert((flags&0x0F)==SQLITE_SYNC_NORMAL
  27376. || (flags&0x0F)==SQLITE_SYNC_FULL
  27377. );
  27378. /* Unix cannot, but some systems may return SQLITE_FULL from here. This
  27379. ** line is to test that doing so does not cause any problems.
  27380. */
  27381. SimulateDiskfullError( return SQLITE_FULL );
  27382. assert( pFile );
  27383. OSTRACE(("SYNC %-3d\n", pFile->h));
  27384. rc = full_fsync(pFile->h, isFullsync, isDataOnly);
  27385. SimulateIOError( rc=1 );
  27386. if( rc ){
  27387. storeLastErrno(pFile, errno);
  27388. return unixLogError(SQLITE_IOERR_FSYNC, "full_fsync", pFile->zPath);
  27389. }
  27390. /* Also fsync the directory containing the file if the DIRSYNC flag
  27391. ** is set. This is a one-time occurrence. Many systems (examples: AIX)
  27392. ** are unable to fsync a directory, so ignore errors on the fsync.
  27393. */
  27394. if( pFile->ctrlFlags & UNIXFILE_DIRSYNC ){
  27395. int dirfd;
  27396. OSTRACE(("DIRSYNC %s (have_fullfsync=%d fullsync=%d)\n", pFile->zPath,
  27397. HAVE_FULLFSYNC, isFullsync));
  27398. rc = osOpenDirectory(pFile->zPath, &dirfd);
  27399. if( rc==SQLITE_OK && dirfd>=0 ){
  27400. full_fsync(dirfd, 0, 0);
  27401. robust_close(pFile, dirfd, __LINE__);
  27402. }else if( rc==SQLITE_CANTOPEN ){
  27403. rc = SQLITE_OK;
  27404. }
  27405. pFile->ctrlFlags &= ~UNIXFILE_DIRSYNC;
  27406. }
  27407. return rc;
  27408. }
  27409. /*
  27410. ** Truncate an open file to a specified size
  27411. */
  27412. static int unixTruncate(sqlite3_file *id, i64 nByte){
  27413. unixFile *pFile = (unixFile *)id;
  27414. int rc;
  27415. assert( pFile );
  27416. SimulateIOError( return SQLITE_IOERR_TRUNCATE );
  27417. /* If the user has configured a chunk-size for this file, truncate the
  27418. ** file so that it consists of an integer number of chunks (i.e. the
  27419. ** actual file size after the operation may be larger than the requested
  27420. ** size).
  27421. */
  27422. if( pFile->szChunk>0 ){
  27423. nByte = ((nByte + pFile->szChunk - 1)/pFile->szChunk) * pFile->szChunk;
  27424. }
  27425. rc = robust_ftruncate(pFile->h, nByte);
  27426. if( rc ){
  27427. storeLastErrno(pFile, errno);
  27428. return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
  27429. }else{
  27430. #ifdef SQLITE_DEBUG
  27431. /* If we are doing a normal write to a database file (as opposed to
  27432. ** doing a hot-journal rollback or a write to some file other than a
  27433. ** normal database file) and we truncate the file to zero length,
  27434. ** that effectively updates the change counter. This might happen
  27435. ** when restoring a database using the backup API from a zero-length
  27436. ** source.
  27437. */
  27438. if( pFile->inNormalWrite && nByte==0 ){
  27439. pFile->transCntrChng = 1;
  27440. }
  27441. #endif
  27442. #if SQLITE_MAX_MMAP_SIZE>0
  27443. /* If the file was just truncated to a size smaller than the currently
  27444. ** mapped region, reduce the effective mapping size as well. SQLite will
  27445. ** use read() and write() to access data beyond this point from now on.
  27446. */
  27447. if( nByte<pFile->mmapSize ){
  27448. pFile->mmapSize = nByte;
  27449. }
  27450. #endif
  27451. return SQLITE_OK;
  27452. }
  27453. }
  27454. /*
  27455. ** Determine the current size of a file in bytes
  27456. */
  27457. static int unixFileSize(sqlite3_file *id, i64 *pSize){
  27458. int rc;
  27459. struct stat buf;
  27460. assert( id );
  27461. rc = osFstat(((unixFile*)id)->h, &buf);
  27462. SimulateIOError( rc=1 );
  27463. if( rc!=0 ){
  27464. storeLastErrno((unixFile*)id, errno);
  27465. return SQLITE_IOERR_FSTAT;
  27466. }
  27467. *pSize = buf.st_size;
  27468. /* When opening a zero-size database, the findInodeInfo() procedure
  27469. ** writes a single byte into that file in order to work around a bug
  27470. ** in the OS-X msdos filesystem. In order to avoid problems with upper
  27471. ** layers, we need to report this file size as zero even though it is
  27472. ** really 1. Ticket #3260.
  27473. */
  27474. if( *pSize==1 ) *pSize = 0;
  27475. return SQLITE_OK;
  27476. }
  27477. #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
  27478. /*
  27479. ** Handler for proxy-locking file-control verbs. Defined below in the
  27480. ** proxying locking division.
  27481. */
  27482. static int proxyFileControl(sqlite3_file*,int,void*);
  27483. #endif
  27484. /*
  27485. ** This function is called to handle the SQLITE_FCNTL_SIZE_HINT
  27486. ** file-control operation. Enlarge the database to nBytes in size
  27487. ** (rounded up to the next chunk-size). If the database is already
  27488. ** nBytes or larger, this routine is a no-op.
  27489. */
  27490. static int fcntlSizeHint(unixFile *pFile, i64 nByte){
  27491. if( pFile->szChunk>0 ){
  27492. i64 nSize; /* Required file size */
  27493. struct stat buf; /* Used to hold return values of fstat() */
  27494. if( osFstat(pFile->h, &buf) ){
  27495. return SQLITE_IOERR_FSTAT;
  27496. }
  27497. nSize = ((nByte+pFile->szChunk-1) / pFile->szChunk) * pFile->szChunk;
  27498. if( nSize>(i64)buf.st_size ){
  27499. #if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
  27500. /* The code below is handling the return value of osFallocate()
  27501. ** correctly. posix_fallocate() is defined to "returns zero on success,
  27502. ** or an error number on failure". See the manpage for details. */
  27503. int err;
  27504. do{
  27505. err = osFallocate(pFile->h, buf.st_size, nSize-buf.st_size);
  27506. }while( err==EINTR );
  27507. if( err ) return SQLITE_IOERR_WRITE;
  27508. #else
  27509. /* If the OS does not have posix_fallocate(), fake it. Write a
  27510. ** single byte to the last byte in each block that falls entirely
  27511. ** within the extended region. Then, if required, a single byte
  27512. ** at offset (nSize-1), to set the size of the file correctly.
  27513. ** This is a similar technique to that used by glibc on systems
  27514. ** that do not have a real fallocate() call.
  27515. */
  27516. int nBlk = buf.st_blksize; /* File-system block size */
  27517. int nWrite = 0; /* Number of bytes written by seekAndWrite */
  27518. i64 iWrite; /* Next offset to write to */
  27519. iWrite = ((buf.st_size + 2*nBlk - 1)/nBlk)*nBlk-1;
  27520. assert( iWrite>=buf.st_size );
  27521. assert( (iWrite/nBlk)==((buf.st_size+nBlk-1)/nBlk) );
  27522. assert( ((iWrite+1)%nBlk)==0 );
  27523. for(/*no-op*/; iWrite<nSize; iWrite+=nBlk ){
  27524. nWrite = seekAndWrite(pFile, iWrite, "", 1);
  27525. if( nWrite!=1 ) return SQLITE_IOERR_WRITE;
  27526. }
  27527. if( nWrite==0 || (nSize%nBlk) ){
  27528. nWrite = seekAndWrite(pFile, nSize-1, "", 1);
  27529. if( nWrite!=1 ) return SQLITE_IOERR_WRITE;
  27530. }
  27531. #endif
  27532. }
  27533. }
  27534. #if SQLITE_MAX_MMAP_SIZE>0
  27535. if( pFile->mmapSizeMax>0 && nByte>pFile->mmapSize ){
  27536. int rc;
  27537. if( pFile->szChunk<=0 ){
  27538. if( robust_ftruncate(pFile->h, nByte) ){
  27539. storeLastErrno(pFile, errno);
  27540. return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
  27541. }
  27542. }
  27543. rc = unixMapfile(pFile, nByte);
  27544. return rc;
  27545. }
  27546. #endif
  27547. return SQLITE_OK;
  27548. }
  27549. /*
  27550. ** If *pArg is initially negative then this is a query. Set *pArg to
  27551. ** 1 or 0 depending on whether or not bit mask of pFile->ctrlFlags is set.
  27552. **
  27553. ** If *pArg is 0 or 1, then clear or set the mask bit of pFile->ctrlFlags.
  27554. */
  27555. static void unixModeBit(unixFile *pFile, unsigned char mask, int *pArg){
  27556. if( *pArg<0 ){
  27557. *pArg = (pFile->ctrlFlags & mask)!=0;
  27558. }else if( (*pArg)==0 ){
  27559. pFile->ctrlFlags &= ~mask;
  27560. }else{
  27561. pFile->ctrlFlags |= mask;
  27562. }
  27563. }
  27564. /* Forward declaration */
  27565. static int unixGetTempname(int nBuf, char *zBuf);
  27566. /*
  27567. ** Information and control of an open file handle.
  27568. */
  27569. static int unixFileControl(sqlite3_file *id, int op, void *pArg){
  27570. unixFile *pFile = (unixFile*)id;
  27571. switch( op ){
  27572. case SQLITE_FCNTL_WAL_BLOCK: {
  27573. /* pFile->ctrlFlags |= UNIXFILE_BLOCK; // Deferred feature */
  27574. return SQLITE_OK;
  27575. }
  27576. case SQLITE_FCNTL_LOCKSTATE: {
  27577. *(int*)pArg = pFile->eFileLock;
  27578. return SQLITE_OK;
  27579. }
  27580. case SQLITE_FCNTL_LAST_ERRNO: {
  27581. *(int*)pArg = pFile->lastErrno;
  27582. return SQLITE_OK;
  27583. }
  27584. case SQLITE_FCNTL_CHUNK_SIZE: {
  27585. pFile->szChunk = *(int *)pArg;
  27586. return SQLITE_OK;
  27587. }
  27588. case SQLITE_FCNTL_SIZE_HINT: {
  27589. int rc;
  27590. SimulateIOErrorBenign(1);
  27591. rc = fcntlSizeHint(pFile, *(i64 *)pArg);
  27592. SimulateIOErrorBenign(0);
  27593. return rc;
  27594. }
  27595. case SQLITE_FCNTL_PERSIST_WAL: {
  27596. unixModeBit(pFile, UNIXFILE_PERSIST_WAL, (int*)pArg);
  27597. return SQLITE_OK;
  27598. }
  27599. case SQLITE_FCNTL_POWERSAFE_OVERWRITE: {
  27600. unixModeBit(pFile, UNIXFILE_PSOW, (int*)pArg);
  27601. return SQLITE_OK;
  27602. }
  27603. case SQLITE_FCNTL_VFSNAME: {
  27604. *(char**)pArg = sqlite3_mprintf("%s", pFile->pVfs->zName);
  27605. return SQLITE_OK;
  27606. }
  27607. case SQLITE_FCNTL_TEMPFILENAME: {
  27608. char *zTFile = sqlite3_malloc64( pFile->pVfs->mxPathname );
  27609. if( zTFile ){
  27610. unixGetTempname(pFile->pVfs->mxPathname, zTFile);
  27611. *(char**)pArg = zTFile;
  27612. }
  27613. return SQLITE_OK;
  27614. }
  27615. case SQLITE_FCNTL_HAS_MOVED: {
  27616. *(int*)pArg = fileHasMoved(pFile);
  27617. return SQLITE_OK;
  27618. }
  27619. #if SQLITE_MAX_MMAP_SIZE>0
  27620. case SQLITE_FCNTL_MMAP_SIZE: {
  27621. i64 newLimit = *(i64*)pArg;
  27622. int rc = SQLITE_OK;
  27623. if( newLimit>sqlite3GlobalConfig.mxMmap ){
  27624. newLimit = sqlite3GlobalConfig.mxMmap;
  27625. }
  27626. *(i64*)pArg = pFile->mmapSizeMax;
  27627. if( newLimit>=0 && newLimit!=pFile->mmapSizeMax && pFile->nFetchOut==0 ){
  27628. pFile->mmapSizeMax = newLimit;
  27629. if( pFile->mmapSize>0 ){
  27630. unixUnmapfile(pFile);
  27631. rc = unixMapfile(pFile, -1);
  27632. }
  27633. }
  27634. return rc;
  27635. }
  27636. #endif
  27637. #ifdef SQLITE_DEBUG
  27638. /* The pager calls this method to signal that it has done
  27639. ** a rollback and that the database is therefore unchanged and
  27640. ** it hence it is OK for the transaction change counter to be
  27641. ** unchanged.
  27642. */
  27643. case SQLITE_FCNTL_DB_UNCHANGED: {
  27644. ((unixFile*)id)->dbUpdate = 0;
  27645. return SQLITE_OK;
  27646. }
  27647. #endif
  27648. #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
  27649. case SQLITE_FCNTL_SET_LOCKPROXYFILE:
  27650. case SQLITE_FCNTL_GET_LOCKPROXYFILE: {
  27651. return proxyFileControl(id,op,pArg);
  27652. }
  27653. #endif /* SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__) */
  27654. }
  27655. return SQLITE_NOTFOUND;
  27656. }
  27657. /*
  27658. ** Return the sector size in bytes of the underlying block device for
  27659. ** the specified file. This is almost always 512 bytes, but may be
  27660. ** larger for some devices.
  27661. **
  27662. ** SQLite code assumes this function cannot fail. It also assumes that
  27663. ** if two files are created in the same file-system directory (i.e.
  27664. ** a database and its journal file) that the sector size will be the
  27665. ** same for both.
  27666. */
  27667. #ifndef __QNXNTO__
  27668. static int unixSectorSize(sqlite3_file *NotUsed){
  27669. UNUSED_PARAMETER(NotUsed);
  27670. return SQLITE_DEFAULT_SECTOR_SIZE;
  27671. }
  27672. #endif
  27673. /*
  27674. ** The following version of unixSectorSize() is optimized for QNX.
  27675. */
  27676. #ifdef __QNXNTO__
  27677. #include <sys/dcmd_blk.h>
  27678. #include <sys/statvfs.h>
  27679. static int unixSectorSize(sqlite3_file *id){
  27680. unixFile *pFile = (unixFile*)id;
  27681. if( pFile->sectorSize == 0 ){
  27682. struct statvfs fsInfo;
  27683. /* Set defaults for non-supported filesystems */
  27684. pFile->sectorSize = SQLITE_DEFAULT_SECTOR_SIZE;
  27685. pFile->deviceCharacteristics = 0;
  27686. if( fstatvfs(pFile->h, &fsInfo) == -1 ) {
  27687. return pFile->sectorSize;
  27688. }
  27689. if( !strcmp(fsInfo.f_basetype, "tmp") ) {
  27690. pFile->sectorSize = fsInfo.f_bsize;
  27691. pFile->deviceCharacteristics =
  27692. SQLITE_IOCAP_ATOMIC4K | /* All ram filesystem writes are atomic */
  27693. SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
  27694. ** the write succeeds */
  27695. SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
  27696. ** so it is ordered */
  27697. 0;
  27698. }else if( strstr(fsInfo.f_basetype, "etfs") ){
  27699. pFile->sectorSize = fsInfo.f_bsize;
  27700. pFile->deviceCharacteristics =
  27701. /* etfs cluster size writes are atomic */
  27702. (pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) |
  27703. SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
  27704. ** the write succeeds */
  27705. SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
  27706. ** so it is ordered */
  27707. 0;
  27708. }else if( !strcmp(fsInfo.f_basetype, "qnx6") ){
  27709. pFile->sectorSize = fsInfo.f_bsize;
  27710. pFile->deviceCharacteristics =
  27711. SQLITE_IOCAP_ATOMIC | /* All filesystem writes are atomic */
  27712. SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
  27713. ** the write succeeds */
  27714. SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
  27715. ** so it is ordered */
  27716. 0;
  27717. }else if( !strcmp(fsInfo.f_basetype, "qnx4") ){
  27718. pFile->sectorSize = fsInfo.f_bsize;
  27719. pFile->deviceCharacteristics =
  27720. /* full bitset of atomics from max sector size and smaller */
  27721. ((pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) << 1) - 2 |
  27722. SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
  27723. ** so it is ordered */
  27724. 0;
  27725. }else if( strstr(fsInfo.f_basetype, "dos") ){
  27726. pFile->sectorSize = fsInfo.f_bsize;
  27727. pFile->deviceCharacteristics =
  27728. /* full bitset of atomics from max sector size and smaller */
  27729. ((pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) << 1) - 2 |
  27730. SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
  27731. ** so it is ordered */
  27732. 0;
  27733. }else{
  27734. pFile->deviceCharacteristics =
  27735. SQLITE_IOCAP_ATOMIC512 | /* blocks are atomic */
  27736. SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
  27737. ** the write succeeds */
  27738. 0;
  27739. }
  27740. }
  27741. /* Last chance verification. If the sector size isn't a multiple of 512
  27742. ** then it isn't valid.*/
  27743. if( pFile->sectorSize % 512 != 0 ){
  27744. pFile->deviceCharacteristics = 0;
  27745. pFile->sectorSize = SQLITE_DEFAULT_SECTOR_SIZE;
  27746. }
  27747. return pFile->sectorSize;
  27748. }
  27749. #endif /* __QNXNTO__ */
  27750. /*
  27751. ** Return the device characteristics for the file.
  27752. **
  27753. ** This VFS is set up to return SQLITE_IOCAP_POWERSAFE_OVERWRITE by default.
  27754. ** However, that choice is controversial since technically the underlying
  27755. ** file system does not always provide powersafe overwrites. (In other
  27756. ** words, after a power-loss event, parts of the file that were never
  27757. ** written might end up being altered.) However, non-PSOW behavior is very,
  27758. ** very rare. And asserting PSOW makes a large reduction in the amount
  27759. ** of required I/O for journaling, since a lot of padding is eliminated.
  27760. ** Hence, while POWERSAFE_OVERWRITE is on by default, there is a file-control
  27761. ** available to turn it off and URI query parameter available to turn it off.
  27762. */
  27763. static int unixDeviceCharacteristics(sqlite3_file *id){
  27764. unixFile *p = (unixFile*)id;
  27765. int rc = 0;
  27766. #ifdef __QNXNTO__
  27767. if( p->sectorSize==0 ) unixSectorSize(id);
  27768. rc = p->deviceCharacteristics;
  27769. #endif
  27770. if( p->ctrlFlags & UNIXFILE_PSOW ){
  27771. rc |= SQLITE_IOCAP_POWERSAFE_OVERWRITE;
  27772. }
  27773. return rc;
  27774. }
  27775. #if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
  27776. /*
  27777. ** Return the system page size.
  27778. **
  27779. ** This function should not be called directly by other code in this file.
  27780. ** Instead, it should be called via macro osGetpagesize().
  27781. */
  27782. static int unixGetpagesize(void){
  27783. #if OS_VXWORKS
  27784. return 1024;
  27785. #elif defined(_BSD_SOURCE)
  27786. return getpagesize();
  27787. #else
  27788. return (int)sysconf(_SC_PAGESIZE);
  27789. #endif
  27790. }
  27791. #endif /* !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0 */
  27792. #ifndef SQLITE_OMIT_WAL
  27793. /*
  27794. ** Object used to represent an shared memory buffer.
  27795. **
  27796. ** When multiple threads all reference the same wal-index, each thread
  27797. ** has its own unixShm object, but they all point to a single instance
  27798. ** of this unixShmNode object. In other words, each wal-index is opened
  27799. ** only once per process.
  27800. **
  27801. ** Each unixShmNode object is connected to a single unixInodeInfo object.
  27802. ** We could coalesce this object into unixInodeInfo, but that would mean
  27803. ** every open file that does not use shared memory (in other words, most
  27804. ** open files) would have to carry around this extra information. So
  27805. ** the unixInodeInfo object contains a pointer to this unixShmNode object
  27806. ** and the unixShmNode object is created only when needed.
  27807. **
  27808. ** unixMutexHeld() must be true when creating or destroying
  27809. ** this object or while reading or writing the following fields:
  27810. **
  27811. ** nRef
  27812. **
  27813. ** The following fields are read-only after the object is created:
  27814. **
  27815. ** fid
  27816. ** zFilename
  27817. **
  27818. ** Either unixShmNode.mutex must be held or unixShmNode.nRef==0 and
  27819. ** unixMutexHeld() is true when reading or writing any other field
  27820. ** in this structure.
  27821. */
  27822. struct unixShmNode {
  27823. unixInodeInfo *pInode; /* unixInodeInfo that owns this SHM node */
  27824. sqlite3_mutex *mutex; /* Mutex to access this object */
  27825. char *zFilename; /* Name of the mmapped file */
  27826. int h; /* Open file descriptor */
  27827. int szRegion; /* Size of shared-memory regions */
  27828. u16 nRegion; /* Size of array apRegion */
  27829. u8 isReadonly; /* True if read-only */
  27830. char **apRegion; /* Array of mapped shared-memory regions */
  27831. int nRef; /* Number of unixShm objects pointing to this */
  27832. unixShm *pFirst; /* All unixShm objects pointing to this */
  27833. #ifdef SQLITE_DEBUG
  27834. u8 exclMask; /* Mask of exclusive locks held */
  27835. u8 sharedMask; /* Mask of shared locks held */
  27836. u8 nextShmId; /* Next available unixShm.id value */
  27837. #endif
  27838. };
  27839. /*
  27840. ** Structure used internally by this VFS to record the state of an
  27841. ** open shared memory connection.
  27842. **
  27843. ** The following fields are initialized when this object is created and
  27844. ** are read-only thereafter:
  27845. **
  27846. ** unixShm.pFile
  27847. ** unixShm.id
  27848. **
  27849. ** All other fields are read/write. The unixShm.pFile->mutex must be held
  27850. ** while accessing any read/write fields.
  27851. */
  27852. struct unixShm {
  27853. unixShmNode *pShmNode; /* The underlying unixShmNode object */
  27854. unixShm *pNext; /* Next unixShm with the same unixShmNode */
  27855. u8 hasMutex; /* True if holding the unixShmNode mutex */
  27856. u8 id; /* Id of this connection within its unixShmNode */
  27857. u16 sharedMask; /* Mask of shared locks held */
  27858. u16 exclMask; /* Mask of exclusive locks held */
  27859. };
  27860. /*
  27861. ** Constants used for locking
  27862. */
  27863. #define UNIX_SHM_BASE ((22+SQLITE_SHM_NLOCK)*4) /* first lock byte */
  27864. #define UNIX_SHM_DMS (UNIX_SHM_BASE+SQLITE_SHM_NLOCK) /* deadman switch */
  27865. /*
  27866. ** Apply posix advisory locks for all bytes from ofst through ofst+n-1.
  27867. **
  27868. ** Locks block if the mask is exactly UNIX_SHM_C and are non-blocking
  27869. ** otherwise.
  27870. */
  27871. static int unixShmSystemLock(
  27872. unixFile *pFile, /* Open connection to the WAL file */
  27873. int lockType, /* F_UNLCK, F_RDLCK, or F_WRLCK */
  27874. int ofst, /* First byte of the locking range */
  27875. int n /* Number of bytes to lock */
  27876. ){
  27877. unixShmNode *pShmNode; /* Apply locks to this open shared-memory segment */
  27878. struct flock f; /* The posix advisory locking structure */
  27879. int rc = SQLITE_OK; /* Result code form fcntl() */
  27880. /* Access to the unixShmNode object is serialized by the caller */
  27881. pShmNode = pFile->pInode->pShmNode;
  27882. assert( sqlite3_mutex_held(pShmNode->mutex) || pShmNode->nRef==0 );
  27883. /* Shared locks never span more than one byte */
  27884. assert( n==1 || lockType!=F_RDLCK );
  27885. /* Locks are within range */
  27886. assert( n>=1 && n<SQLITE_SHM_NLOCK );
  27887. if( pShmNode->h>=0 ){
  27888. int lkType;
  27889. /* Initialize the locking parameters */
  27890. memset(&f, 0, sizeof(f));
  27891. f.l_type = lockType;
  27892. f.l_whence = SEEK_SET;
  27893. f.l_start = ofst;
  27894. f.l_len = n;
  27895. lkType = (pFile->ctrlFlags & UNIXFILE_BLOCK)!=0 ? F_SETLKW : F_SETLK;
  27896. rc = osFcntl(pShmNode->h, lkType, &f);
  27897. rc = (rc!=(-1)) ? SQLITE_OK : SQLITE_BUSY;
  27898. pFile->ctrlFlags &= ~UNIXFILE_BLOCK;
  27899. }
  27900. /* Update the global lock state and do debug tracing */
  27901. #ifdef SQLITE_DEBUG
  27902. { u16 mask;
  27903. OSTRACE(("SHM-LOCK "));
  27904. mask = ofst>31 ? 0xffff : (1<<(ofst+n)) - (1<<ofst);
  27905. if( rc==SQLITE_OK ){
  27906. if( lockType==F_UNLCK ){
  27907. OSTRACE(("unlock %d ok", ofst));
  27908. pShmNode->exclMask &= ~mask;
  27909. pShmNode->sharedMask &= ~mask;
  27910. }else if( lockType==F_RDLCK ){
  27911. OSTRACE(("read-lock %d ok", ofst));
  27912. pShmNode->exclMask &= ~mask;
  27913. pShmNode->sharedMask |= mask;
  27914. }else{
  27915. assert( lockType==F_WRLCK );
  27916. OSTRACE(("write-lock %d ok", ofst));
  27917. pShmNode->exclMask |= mask;
  27918. pShmNode->sharedMask &= ~mask;
  27919. }
  27920. }else{
  27921. if( lockType==F_UNLCK ){
  27922. OSTRACE(("unlock %d failed", ofst));
  27923. }else if( lockType==F_RDLCK ){
  27924. OSTRACE(("read-lock failed"));
  27925. }else{
  27926. assert( lockType==F_WRLCK );
  27927. OSTRACE(("write-lock %d failed", ofst));
  27928. }
  27929. }
  27930. OSTRACE((" - afterwards %03x,%03x\n",
  27931. pShmNode->sharedMask, pShmNode->exclMask));
  27932. }
  27933. #endif
  27934. return rc;
  27935. }
  27936. /*
  27937. ** Return the minimum number of 32KB shm regions that should be mapped at
  27938. ** a time, assuming that each mapping must be an integer multiple of the
  27939. ** current system page-size.
  27940. **
  27941. ** Usually, this is 1. The exception seems to be systems that are configured
  27942. ** to use 64KB pages - in this case each mapping must cover at least two
  27943. ** shm regions.
  27944. */
  27945. static int unixShmRegionPerMap(void){
  27946. int shmsz = 32*1024; /* SHM region size */
  27947. int pgsz = osGetpagesize(); /* System page size */
  27948. assert( ((pgsz-1)&pgsz)==0 ); /* Page size must be a power of 2 */
  27949. if( pgsz<shmsz ) return 1;
  27950. return pgsz/shmsz;
  27951. }
  27952. /*
  27953. ** Purge the unixShmNodeList list of all entries with unixShmNode.nRef==0.
  27954. **
  27955. ** This is not a VFS shared-memory method; it is a utility function called
  27956. ** by VFS shared-memory methods.
  27957. */
  27958. static void unixShmPurge(unixFile *pFd){
  27959. unixShmNode *p = pFd->pInode->pShmNode;
  27960. assert( unixMutexHeld() );
  27961. if( p && p->nRef==0 ){
  27962. int nShmPerMap = unixShmRegionPerMap();
  27963. int i;
  27964. assert( p->pInode==pFd->pInode );
  27965. sqlite3_mutex_free(p->mutex);
  27966. for(i=0; i<p->nRegion; i+=nShmPerMap){
  27967. if( p->h>=0 ){
  27968. osMunmap(p->apRegion[i], p->szRegion);
  27969. }else{
  27970. sqlite3_free(p->apRegion[i]);
  27971. }
  27972. }
  27973. sqlite3_free(p->apRegion);
  27974. if( p->h>=0 ){
  27975. robust_close(pFd, p->h, __LINE__);
  27976. p->h = -1;
  27977. }
  27978. p->pInode->pShmNode = 0;
  27979. sqlite3_free(p);
  27980. }
  27981. }
  27982. /*
  27983. ** Open a shared-memory area associated with open database file pDbFd.
  27984. ** This particular implementation uses mmapped files.
  27985. **
  27986. ** The file used to implement shared-memory is in the same directory
  27987. ** as the open database file and has the same name as the open database
  27988. ** file with the "-shm" suffix added. For example, if the database file
  27989. ** is "/home/user1/config.db" then the file that is created and mmapped
  27990. ** for shared memory will be called "/home/user1/config.db-shm".
  27991. **
  27992. ** Another approach to is to use files in /dev/shm or /dev/tmp or an
  27993. ** some other tmpfs mount. But if a file in a different directory
  27994. ** from the database file is used, then differing access permissions
  27995. ** or a chroot() might cause two different processes on the same
  27996. ** database to end up using different files for shared memory -
  27997. ** meaning that their memory would not really be shared - resulting
  27998. ** in database corruption. Nevertheless, this tmpfs file usage
  27999. ** can be enabled at compile-time using -DSQLITE_SHM_DIRECTORY="/dev/shm"
  28000. ** or the equivalent. The use of the SQLITE_SHM_DIRECTORY compile-time
  28001. ** option results in an incompatible build of SQLite; builds of SQLite
  28002. ** that with differing SQLITE_SHM_DIRECTORY settings attempt to use the
  28003. ** same database file at the same time, database corruption will likely
  28004. ** result. The SQLITE_SHM_DIRECTORY compile-time option is considered
  28005. ** "unsupported" and may go away in a future SQLite release.
  28006. **
  28007. ** When opening a new shared-memory file, if no other instances of that
  28008. ** file are currently open, in this process or in other processes, then
  28009. ** the file must be truncated to zero length or have its header cleared.
  28010. **
  28011. ** If the original database file (pDbFd) is using the "unix-excl" VFS
  28012. ** that means that an exclusive lock is held on the database file and
  28013. ** that no other processes are able to read or write the database. In
  28014. ** that case, we do not really need shared memory. No shared memory
  28015. ** file is created. The shared memory will be simulated with heap memory.
  28016. */
  28017. static int unixOpenSharedMemory(unixFile *pDbFd){
  28018. struct unixShm *p = 0; /* The connection to be opened */
  28019. struct unixShmNode *pShmNode; /* The underlying mmapped file */
  28020. int rc; /* Result code */
  28021. unixInodeInfo *pInode; /* The inode of fd */
  28022. char *zShmFilename; /* Name of the file used for SHM */
  28023. int nShmFilename; /* Size of the SHM filename in bytes */
  28024. /* Allocate space for the new unixShm object. */
  28025. p = sqlite3_malloc64( sizeof(*p) );
  28026. if( p==0 ) return SQLITE_NOMEM;
  28027. memset(p, 0, sizeof(*p));
  28028. assert( pDbFd->pShm==0 );
  28029. /* Check to see if a unixShmNode object already exists. Reuse an existing
  28030. ** one if present. Create a new one if necessary.
  28031. */
  28032. unixEnterMutex();
  28033. pInode = pDbFd->pInode;
  28034. pShmNode = pInode->pShmNode;
  28035. if( pShmNode==0 ){
  28036. struct stat sStat; /* fstat() info for database file */
  28037. #ifndef SQLITE_SHM_DIRECTORY
  28038. const char *zBasePath = pDbFd->zPath;
  28039. #endif
  28040. /* Call fstat() to figure out the permissions on the database file. If
  28041. ** a new *-shm file is created, an attempt will be made to create it
  28042. ** with the same permissions.
  28043. */
  28044. if( osFstat(pDbFd->h, &sStat) && pInode->bProcessLock==0 ){
  28045. rc = SQLITE_IOERR_FSTAT;
  28046. goto shm_open_err;
  28047. }
  28048. #ifdef SQLITE_SHM_DIRECTORY
  28049. nShmFilename = sizeof(SQLITE_SHM_DIRECTORY) + 31;
  28050. #else
  28051. nShmFilename = 6 + (int)strlen(zBasePath);
  28052. #endif
  28053. pShmNode = sqlite3_malloc64( sizeof(*pShmNode) + nShmFilename );
  28054. if( pShmNode==0 ){
  28055. rc = SQLITE_NOMEM;
  28056. goto shm_open_err;
  28057. }
  28058. memset(pShmNode, 0, sizeof(*pShmNode)+nShmFilename);
  28059. zShmFilename = pShmNode->zFilename = (char*)&pShmNode[1];
  28060. #ifdef SQLITE_SHM_DIRECTORY
  28061. sqlite3_snprintf(nShmFilename, zShmFilename,
  28062. SQLITE_SHM_DIRECTORY "/sqlite-shm-%x-%x",
  28063. (u32)sStat.st_ino, (u32)sStat.st_dev);
  28064. #else
  28065. sqlite3_snprintf(nShmFilename, zShmFilename, "%s-shm", zBasePath);
  28066. sqlite3FileSuffix3(pDbFd->zPath, zShmFilename);
  28067. #endif
  28068. pShmNode->h = -1;
  28069. pDbFd->pInode->pShmNode = pShmNode;
  28070. pShmNode->pInode = pDbFd->pInode;
  28071. pShmNode->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
  28072. if( pShmNode->mutex==0 ){
  28073. rc = SQLITE_NOMEM;
  28074. goto shm_open_err;
  28075. }
  28076. if( pInode->bProcessLock==0 ){
  28077. int openFlags = O_RDWR | O_CREAT;
  28078. if( sqlite3_uri_boolean(pDbFd->zPath, "readonly_shm", 0) ){
  28079. openFlags = O_RDONLY;
  28080. pShmNode->isReadonly = 1;
  28081. }
  28082. pShmNode->h = robust_open(zShmFilename, openFlags, (sStat.st_mode&0777));
  28083. if( pShmNode->h<0 ){
  28084. rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zShmFilename);
  28085. goto shm_open_err;
  28086. }
  28087. /* If this process is running as root, make sure that the SHM file
  28088. ** is owned by the same user that owns the original database. Otherwise,
  28089. ** the original owner will not be able to connect.
  28090. */
  28091. osFchown(pShmNode->h, sStat.st_uid, sStat.st_gid);
  28092. /* Check to see if another process is holding the dead-man switch.
  28093. ** If not, truncate the file to zero length.
  28094. */
  28095. rc = SQLITE_OK;
  28096. if( unixShmSystemLock(pDbFd, F_WRLCK, UNIX_SHM_DMS, 1)==SQLITE_OK ){
  28097. if( robust_ftruncate(pShmNode->h, 0) ){
  28098. rc = unixLogError(SQLITE_IOERR_SHMOPEN, "ftruncate", zShmFilename);
  28099. }
  28100. }
  28101. if( rc==SQLITE_OK ){
  28102. rc = unixShmSystemLock(pDbFd, F_RDLCK, UNIX_SHM_DMS, 1);
  28103. }
  28104. if( rc ) goto shm_open_err;
  28105. }
  28106. }
  28107. /* Make the new connection a child of the unixShmNode */
  28108. p->pShmNode = pShmNode;
  28109. #ifdef SQLITE_DEBUG
  28110. p->id = pShmNode->nextShmId++;
  28111. #endif
  28112. pShmNode->nRef++;
  28113. pDbFd->pShm = p;
  28114. unixLeaveMutex();
  28115. /* The reference count on pShmNode has already been incremented under
  28116. ** the cover of the unixEnterMutex() mutex and the pointer from the
  28117. ** new (struct unixShm) object to the pShmNode has been set. All that is
  28118. ** left to do is to link the new object into the linked list starting
  28119. ** at pShmNode->pFirst. This must be done while holding the pShmNode->mutex
  28120. ** mutex.
  28121. */
  28122. sqlite3_mutex_enter(pShmNode->mutex);
  28123. p->pNext = pShmNode->pFirst;
  28124. pShmNode->pFirst = p;
  28125. sqlite3_mutex_leave(pShmNode->mutex);
  28126. return SQLITE_OK;
  28127. /* Jump here on any error */
  28128. shm_open_err:
  28129. unixShmPurge(pDbFd); /* This call frees pShmNode if required */
  28130. sqlite3_free(p);
  28131. unixLeaveMutex();
  28132. return rc;
  28133. }
  28134. /*
  28135. ** This function is called to obtain a pointer to region iRegion of the
  28136. ** shared-memory associated with the database file fd. Shared-memory regions
  28137. ** are numbered starting from zero. Each shared-memory region is szRegion
  28138. ** bytes in size.
  28139. **
  28140. ** If an error occurs, an error code is returned and *pp is set to NULL.
  28141. **
  28142. ** Otherwise, if the bExtend parameter is 0 and the requested shared-memory
  28143. ** region has not been allocated (by any client, including one running in a
  28144. ** separate process), then *pp is set to NULL and SQLITE_OK returned. If
  28145. ** bExtend is non-zero and the requested shared-memory region has not yet
  28146. ** been allocated, it is allocated by this function.
  28147. **
  28148. ** If the shared-memory region has already been allocated or is allocated by
  28149. ** this call as described above, then it is mapped into this processes
  28150. ** address space (if it is not already), *pp is set to point to the mapped
  28151. ** memory and SQLITE_OK returned.
  28152. */
  28153. static int unixShmMap(
  28154. sqlite3_file *fd, /* Handle open on database file */
  28155. int iRegion, /* Region to retrieve */
  28156. int szRegion, /* Size of regions */
  28157. int bExtend, /* True to extend file if necessary */
  28158. void volatile **pp /* OUT: Mapped memory */
  28159. ){
  28160. unixFile *pDbFd = (unixFile*)fd;
  28161. unixShm *p;
  28162. unixShmNode *pShmNode;
  28163. int rc = SQLITE_OK;
  28164. int nShmPerMap = unixShmRegionPerMap();
  28165. int nReqRegion;
  28166. /* If the shared-memory file has not yet been opened, open it now. */
  28167. if( pDbFd->pShm==0 ){
  28168. rc = unixOpenSharedMemory(pDbFd);
  28169. if( rc!=SQLITE_OK ) return rc;
  28170. }
  28171. p = pDbFd->pShm;
  28172. pShmNode = p->pShmNode;
  28173. sqlite3_mutex_enter(pShmNode->mutex);
  28174. assert( szRegion==pShmNode->szRegion || pShmNode->nRegion==0 );
  28175. assert( pShmNode->pInode==pDbFd->pInode );
  28176. assert( pShmNode->h>=0 || pDbFd->pInode->bProcessLock==1 );
  28177. assert( pShmNode->h<0 || pDbFd->pInode->bProcessLock==0 );
  28178. /* Minimum number of regions required to be mapped. */
  28179. nReqRegion = ((iRegion+nShmPerMap) / nShmPerMap) * nShmPerMap;
  28180. if( pShmNode->nRegion<nReqRegion ){
  28181. char **apNew; /* New apRegion[] array */
  28182. int nByte = nReqRegion*szRegion; /* Minimum required file size */
  28183. struct stat sStat; /* Used by fstat() */
  28184. pShmNode->szRegion = szRegion;
  28185. if( pShmNode->h>=0 ){
  28186. /* The requested region is not mapped into this processes address space.
  28187. ** Check to see if it has been allocated (i.e. if the wal-index file is
  28188. ** large enough to contain the requested region).
  28189. */
  28190. if( osFstat(pShmNode->h, &sStat) ){
  28191. rc = SQLITE_IOERR_SHMSIZE;
  28192. goto shmpage_out;
  28193. }
  28194. if( sStat.st_size<nByte ){
  28195. /* The requested memory region does not exist. If bExtend is set to
  28196. ** false, exit early. *pp will be set to NULL and SQLITE_OK returned.
  28197. */
  28198. if( !bExtend ){
  28199. goto shmpage_out;
  28200. }
  28201. /* Alternatively, if bExtend is true, extend the file. Do this by
  28202. ** writing a single byte to the end of each (OS) page being
  28203. ** allocated or extended. Technically, we need only write to the
  28204. ** last page in order to extend the file. But writing to all new
  28205. ** pages forces the OS to allocate them immediately, which reduces
  28206. ** the chances of SIGBUS while accessing the mapped region later on.
  28207. */
  28208. else{
  28209. static const int pgsz = 4096;
  28210. int iPg;
  28211. /* Write to the last byte of each newly allocated or extended page */
  28212. assert( (nByte % pgsz)==0 );
  28213. for(iPg=(sStat.st_size/pgsz); iPg<(nByte/pgsz); iPg++){
  28214. if( seekAndWriteFd(pShmNode->h, iPg*pgsz + pgsz-1, "", 1, 0)!=1 ){
  28215. const char *zFile = pShmNode->zFilename;
  28216. rc = unixLogError(SQLITE_IOERR_SHMSIZE, "write", zFile);
  28217. goto shmpage_out;
  28218. }
  28219. }
  28220. }
  28221. }
  28222. }
  28223. /* Map the requested memory region into this processes address space. */
  28224. apNew = (char **)sqlite3_realloc(
  28225. pShmNode->apRegion, nReqRegion*sizeof(char *)
  28226. );
  28227. if( !apNew ){
  28228. rc = SQLITE_IOERR_NOMEM;
  28229. goto shmpage_out;
  28230. }
  28231. pShmNode->apRegion = apNew;
  28232. while( pShmNode->nRegion<nReqRegion ){
  28233. int nMap = szRegion*nShmPerMap;
  28234. int i;
  28235. void *pMem;
  28236. if( pShmNode->h>=0 ){
  28237. pMem = osMmap(0, nMap,
  28238. pShmNode->isReadonly ? PROT_READ : PROT_READ|PROT_WRITE,
  28239. MAP_SHARED, pShmNode->h, szRegion*(i64)pShmNode->nRegion
  28240. );
  28241. if( pMem==MAP_FAILED ){
  28242. rc = unixLogError(SQLITE_IOERR_SHMMAP, "mmap", pShmNode->zFilename);
  28243. goto shmpage_out;
  28244. }
  28245. }else{
  28246. pMem = sqlite3_malloc64(szRegion);
  28247. if( pMem==0 ){
  28248. rc = SQLITE_NOMEM;
  28249. goto shmpage_out;
  28250. }
  28251. memset(pMem, 0, szRegion);
  28252. }
  28253. for(i=0; i<nShmPerMap; i++){
  28254. pShmNode->apRegion[pShmNode->nRegion+i] = &((char*)pMem)[szRegion*i];
  28255. }
  28256. pShmNode->nRegion += nShmPerMap;
  28257. }
  28258. }
  28259. shmpage_out:
  28260. if( pShmNode->nRegion>iRegion ){
  28261. *pp = pShmNode->apRegion[iRegion];
  28262. }else{
  28263. *pp = 0;
  28264. }
  28265. if( pShmNode->isReadonly && rc==SQLITE_OK ) rc = SQLITE_READONLY;
  28266. sqlite3_mutex_leave(pShmNode->mutex);
  28267. return rc;
  28268. }
  28269. /*
  28270. ** Change the lock state for a shared-memory segment.
  28271. **
  28272. ** Note that the relationship between SHAREd and EXCLUSIVE locks is a little
  28273. ** different here than in posix. In xShmLock(), one can go from unlocked
  28274. ** to shared and back or from unlocked to exclusive and back. But one may
  28275. ** not go from shared to exclusive or from exclusive to shared.
  28276. */
  28277. static int unixShmLock(
  28278. sqlite3_file *fd, /* Database file holding the shared memory */
  28279. int ofst, /* First lock to acquire or release */
  28280. int n, /* Number of locks to acquire or release */
  28281. int flags /* What to do with the lock */
  28282. ){
  28283. unixFile *pDbFd = (unixFile*)fd; /* Connection holding shared memory */
  28284. unixShm *p = pDbFd->pShm; /* The shared memory being locked */
  28285. unixShm *pX; /* For looping over all siblings */
  28286. unixShmNode *pShmNode = p->pShmNode; /* The underlying file iNode */
  28287. int rc = SQLITE_OK; /* Result code */
  28288. u16 mask; /* Mask of locks to take or release */
  28289. assert( pShmNode==pDbFd->pInode->pShmNode );
  28290. assert( pShmNode->pInode==pDbFd->pInode );
  28291. assert( ofst>=0 && ofst+n<=SQLITE_SHM_NLOCK );
  28292. assert( n>=1 );
  28293. assert( flags==(SQLITE_SHM_LOCK | SQLITE_SHM_SHARED)
  28294. || flags==(SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE)
  28295. || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED)
  28296. || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE) );
  28297. assert( n==1 || (flags & SQLITE_SHM_EXCLUSIVE)!=0 );
  28298. assert( pShmNode->h>=0 || pDbFd->pInode->bProcessLock==1 );
  28299. assert( pShmNode->h<0 || pDbFd->pInode->bProcessLock==0 );
  28300. mask = (1<<(ofst+n)) - (1<<ofst);
  28301. assert( n>1 || mask==(1<<ofst) );
  28302. sqlite3_mutex_enter(pShmNode->mutex);
  28303. if( flags & SQLITE_SHM_UNLOCK ){
  28304. u16 allMask = 0; /* Mask of locks held by siblings */
  28305. /* See if any siblings hold this same lock */
  28306. for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
  28307. if( pX==p ) continue;
  28308. assert( (pX->exclMask & (p->exclMask|p->sharedMask))==0 );
  28309. allMask |= pX->sharedMask;
  28310. }
  28311. /* Unlock the system-level locks */
  28312. if( (mask & allMask)==0 ){
  28313. rc = unixShmSystemLock(pDbFd, F_UNLCK, ofst+UNIX_SHM_BASE, n);
  28314. }else{
  28315. rc = SQLITE_OK;
  28316. }
  28317. /* Undo the local locks */
  28318. if( rc==SQLITE_OK ){
  28319. p->exclMask &= ~mask;
  28320. p->sharedMask &= ~mask;
  28321. }
  28322. }else if( flags & SQLITE_SHM_SHARED ){
  28323. u16 allShared = 0; /* Union of locks held by connections other than "p" */
  28324. /* Find out which shared locks are already held by sibling connections.
  28325. ** If any sibling already holds an exclusive lock, go ahead and return
  28326. ** SQLITE_BUSY.
  28327. */
  28328. for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
  28329. if( (pX->exclMask & mask)!=0 ){
  28330. rc = SQLITE_BUSY;
  28331. break;
  28332. }
  28333. allShared |= pX->sharedMask;
  28334. }
  28335. /* Get shared locks at the system level, if necessary */
  28336. if( rc==SQLITE_OK ){
  28337. if( (allShared & mask)==0 ){
  28338. rc = unixShmSystemLock(pDbFd, F_RDLCK, ofst+UNIX_SHM_BASE, n);
  28339. }else{
  28340. rc = SQLITE_OK;
  28341. }
  28342. }
  28343. /* Get the local shared locks */
  28344. if( rc==SQLITE_OK ){
  28345. p->sharedMask |= mask;
  28346. }
  28347. }else{
  28348. /* Make sure no sibling connections hold locks that will block this
  28349. ** lock. If any do, return SQLITE_BUSY right away.
  28350. */
  28351. for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
  28352. if( (pX->exclMask & mask)!=0 || (pX->sharedMask & mask)!=0 ){
  28353. rc = SQLITE_BUSY;
  28354. break;
  28355. }
  28356. }
  28357. /* Get the exclusive locks at the system level. Then if successful
  28358. ** also mark the local connection as being locked.
  28359. */
  28360. if( rc==SQLITE_OK ){
  28361. rc = unixShmSystemLock(pDbFd, F_WRLCK, ofst+UNIX_SHM_BASE, n);
  28362. if( rc==SQLITE_OK ){
  28363. assert( (p->sharedMask & mask)==0 );
  28364. p->exclMask |= mask;
  28365. }
  28366. }
  28367. }
  28368. sqlite3_mutex_leave(pShmNode->mutex);
  28369. OSTRACE(("SHM-LOCK shmid-%d, pid-%d got %03x,%03x\n",
  28370. p->id, osGetpid(0), p->sharedMask, p->exclMask));
  28371. return rc;
  28372. }
  28373. /*
  28374. ** Implement a memory barrier or memory fence on shared memory.
  28375. **
  28376. ** All loads and stores begun before the barrier must complete before
  28377. ** any load or store begun after the barrier.
  28378. */
  28379. static void unixShmBarrier(
  28380. sqlite3_file *fd /* Database file holding the shared memory */
  28381. ){
  28382. UNUSED_PARAMETER(fd);
  28383. unixEnterMutex();
  28384. unixLeaveMutex();
  28385. }
  28386. /*
  28387. ** Close a connection to shared-memory. Delete the underlying
  28388. ** storage if deleteFlag is true.
  28389. **
  28390. ** If there is no shared memory associated with the connection then this
  28391. ** routine is a harmless no-op.
  28392. */
  28393. static int unixShmUnmap(
  28394. sqlite3_file *fd, /* The underlying database file */
  28395. int deleteFlag /* Delete shared-memory if true */
  28396. ){
  28397. unixShm *p; /* The connection to be closed */
  28398. unixShmNode *pShmNode; /* The underlying shared-memory file */
  28399. unixShm **pp; /* For looping over sibling connections */
  28400. unixFile *pDbFd; /* The underlying database file */
  28401. pDbFd = (unixFile*)fd;
  28402. p = pDbFd->pShm;
  28403. if( p==0 ) return SQLITE_OK;
  28404. pShmNode = p->pShmNode;
  28405. assert( pShmNode==pDbFd->pInode->pShmNode );
  28406. assert( pShmNode->pInode==pDbFd->pInode );
  28407. /* Remove connection p from the set of connections associated
  28408. ** with pShmNode */
  28409. sqlite3_mutex_enter(pShmNode->mutex);
  28410. for(pp=&pShmNode->pFirst; (*pp)!=p; pp = &(*pp)->pNext){}
  28411. *pp = p->pNext;
  28412. /* Free the connection p */
  28413. sqlite3_free(p);
  28414. pDbFd->pShm = 0;
  28415. sqlite3_mutex_leave(pShmNode->mutex);
  28416. /* If pShmNode->nRef has reached 0, then close the underlying
  28417. ** shared-memory file, too */
  28418. unixEnterMutex();
  28419. assert( pShmNode->nRef>0 );
  28420. pShmNode->nRef--;
  28421. if( pShmNode->nRef==0 ){
  28422. if( deleteFlag && pShmNode->h>=0 ){
  28423. osUnlink(pShmNode->zFilename);
  28424. }
  28425. unixShmPurge(pDbFd);
  28426. }
  28427. unixLeaveMutex();
  28428. return SQLITE_OK;
  28429. }
  28430. #else
  28431. # define unixShmMap 0
  28432. # define unixShmLock 0
  28433. # define unixShmBarrier 0
  28434. # define unixShmUnmap 0
  28435. #endif /* #ifndef SQLITE_OMIT_WAL */
  28436. #if SQLITE_MAX_MMAP_SIZE>0
  28437. /*
  28438. ** If it is currently memory mapped, unmap file pFd.
  28439. */
  28440. static void unixUnmapfile(unixFile *pFd){
  28441. assert( pFd->nFetchOut==0 );
  28442. if( pFd->pMapRegion ){
  28443. osMunmap(pFd->pMapRegion, pFd->mmapSizeActual);
  28444. pFd->pMapRegion = 0;
  28445. pFd->mmapSize = 0;
  28446. pFd->mmapSizeActual = 0;
  28447. }
  28448. }
  28449. /*
  28450. ** Attempt to set the size of the memory mapping maintained by file
  28451. ** descriptor pFd to nNew bytes. Any existing mapping is discarded.
  28452. **
  28453. ** If successful, this function sets the following variables:
  28454. **
  28455. ** unixFile.pMapRegion
  28456. ** unixFile.mmapSize
  28457. ** unixFile.mmapSizeActual
  28458. **
  28459. ** If unsuccessful, an error message is logged via sqlite3_log() and
  28460. ** the three variables above are zeroed. In this case SQLite should
  28461. ** continue accessing the database using the xRead() and xWrite()
  28462. ** methods.
  28463. */
  28464. static void unixRemapfile(
  28465. unixFile *pFd, /* File descriptor object */
  28466. i64 nNew /* Required mapping size */
  28467. ){
  28468. const char *zErr = "mmap";
  28469. int h = pFd->h; /* File descriptor open on db file */
  28470. u8 *pOrig = (u8 *)pFd->pMapRegion; /* Pointer to current file mapping */
  28471. i64 nOrig = pFd->mmapSizeActual; /* Size of pOrig region in bytes */
  28472. u8 *pNew = 0; /* Location of new mapping */
  28473. int flags = PROT_READ; /* Flags to pass to mmap() */
  28474. assert( pFd->nFetchOut==0 );
  28475. assert( nNew>pFd->mmapSize );
  28476. assert( nNew<=pFd->mmapSizeMax );
  28477. assert( nNew>0 );
  28478. assert( pFd->mmapSizeActual>=pFd->mmapSize );
  28479. assert( MAP_FAILED!=0 );
  28480. if( (pFd->ctrlFlags & UNIXFILE_RDONLY)==0 ) flags |= PROT_WRITE;
  28481. if( pOrig ){
  28482. #if HAVE_MREMAP
  28483. i64 nReuse = pFd->mmapSize;
  28484. #else
  28485. const int szSyspage = osGetpagesize();
  28486. i64 nReuse = (pFd->mmapSize & ~(szSyspage-1));
  28487. #endif
  28488. u8 *pReq = &pOrig[nReuse];
  28489. /* Unmap any pages of the existing mapping that cannot be reused. */
  28490. if( nReuse!=nOrig ){
  28491. osMunmap(pReq, nOrig-nReuse);
  28492. }
  28493. #if HAVE_MREMAP
  28494. pNew = osMremap(pOrig, nReuse, nNew, MREMAP_MAYMOVE);
  28495. zErr = "mremap";
  28496. #else
  28497. pNew = osMmap(pReq, nNew-nReuse, flags, MAP_SHARED, h, nReuse);
  28498. if( pNew!=MAP_FAILED ){
  28499. if( pNew!=pReq ){
  28500. osMunmap(pNew, nNew - nReuse);
  28501. pNew = 0;
  28502. }else{
  28503. pNew = pOrig;
  28504. }
  28505. }
  28506. #endif
  28507. /* The attempt to extend the existing mapping failed. Free it. */
  28508. if( pNew==MAP_FAILED || pNew==0 ){
  28509. osMunmap(pOrig, nReuse);
  28510. }
  28511. }
  28512. /* If pNew is still NULL, try to create an entirely new mapping. */
  28513. if( pNew==0 ){
  28514. pNew = osMmap(0, nNew, flags, MAP_SHARED, h, 0);
  28515. }
  28516. if( pNew==MAP_FAILED ){
  28517. pNew = 0;
  28518. nNew = 0;
  28519. unixLogError(SQLITE_OK, zErr, pFd->zPath);
  28520. /* If the mmap() above failed, assume that all subsequent mmap() calls
  28521. ** will probably fail too. Fall back to using xRead/xWrite exclusively
  28522. ** in this case. */
  28523. pFd->mmapSizeMax = 0;
  28524. }
  28525. pFd->pMapRegion = (void *)pNew;
  28526. pFd->mmapSize = pFd->mmapSizeActual = nNew;
  28527. }
  28528. /*
  28529. ** Memory map or remap the file opened by file-descriptor pFd (if the file
  28530. ** is already mapped, the existing mapping is replaced by the new). Or, if
  28531. ** there already exists a mapping for this file, and there are still
  28532. ** outstanding xFetch() references to it, this function is a no-op.
  28533. **
  28534. ** If parameter nByte is non-negative, then it is the requested size of
  28535. ** the mapping to create. Otherwise, if nByte is less than zero, then the
  28536. ** requested size is the size of the file on disk. The actual size of the
  28537. ** created mapping is either the requested size or the value configured
  28538. ** using SQLITE_FCNTL_MMAP_LIMIT, whichever is smaller.
  28539. **
  28540. ** SQLITE_OK is returned if no error occurs (even if the mapping is not
  28541. ** recreated as a result of outstanding references) or an SQLite error
  28542. ** code otherwise.
  28543. */
  28544. static int unixMapfile(unixFile *pFd, i64 nByte){
  28545. i64 nMap = nByte;
  28546. int rc;
  28547. assert( nMap>=0 || pFd->nFetchOut==0 );
  28548. if( pFd->nFetchOut>0 ) return SQLITE_OK;
  28549. if( nMap<0 ){
  28550. struct stat statbuf; /* Low-level file information */
  28551. rc = osFstat(pFd->h, &statbuf);
  28552. if( rc!=SQLITE_OK ){
  28553. return SQLITE_IOERR_FSTAT;
  28554. }
  28555. nMap = statbuf.st_size;
  28556. }
  28557. if( nMap>pFd->mmapSizeMax ){
  28558. nMap = pFd->mmapSizeMax;
  28559. }
  28560. if( nMap!=pFd->mmapSize ){
  28561. if( nMap>0 ){
  28562. unixRemapfile(pFd, nMap);
  28563. }else{
  28564. unixUnmapfile(pFd);
  28565. }
  28566. }
  28567. return SQLITE_OK;
  28568. }
  28569. #endif /* SQLITE_MAX_MMAP_SIZE>0 */
  28570. /*
  28571. ** If possible, return a pointer to a mapping of file fd starting at offset
  28572. ** iOff. The mapping must be valid for at least nAmt bytes.
  28573. **
  28574. ** If such a pointer can be obtained, store it in *pp and return SQLITE_OK.
  28575. ** Or, if one cannot but no error occurs, set *pp to 0 and return SQLITE_OK.
  28576. ** Finally, if an error does occur, return an SQLite error code. The final
  28577. ** value of *pp is undefined in this case.
  28578. **
  28579. ** If this function does return a pointer, the caller must eventually
  28580. ** release the reference by calling unixUnfetch().
  28581. */
  28582. static int unixFetch(sqlite3_file *fd, i64 iOff, int nAmt, void **pp){
  28583. #if SQLITE_MAX_MMAP_SIZE>0
  28584. unixFile *pFd = (unixFile *)fd; /* The underlying database file */
  28585. #endif
  28586. *pp = 0;
  28587. #if SQLITE_MAX_MMAP_SIZE>0
  28588. if( pFd->mmapSizeMax>0 ){
  28589. if( pFd->pMapRegion==0 ){
  28590. int rc = unixMapfile(pFd, -1);
  28591. if( rc!=SQLITE_OK ) return rc;
  28592. }
  28593. if( pFd->mmapSize >= iOff+nAmt ){
  28594. *pp = &((u8 *)pFd->pMapRegion)[iOff];
  28595. pFd->nFetchOut++;
  28596. }
  28597. }
  28598. #endif
  28599. return SQLITE_OK;
  28600. }
  28601. /*
  28602. ** If the third argument is non-NULL, then this function releases a
  28603. ** reference obtained by an earlier call to unixFetch(). The second
  28604. ** argument passed to this function must be the same as the corresponding
  28605. ** argument that was passed to the unixFetch() invocation.
  28606. **
  28607. ** Or, if the third argument is NULL, then this function is being called
  28608. ** to inform the VFS layer that, according to POSIX, any existing mapping
  28609. ** may now be invalid and should be unmapped.
  28610. */
  28611. static int unixUnfetch(sqlite3_file *fd, i64 iOff, void *p){
  28612. #if SQLITE_MAX_MMAP_SIZE>0
  28613. unixFile *pFd = (unixFile *)fd; /* The underlying database file */
  28614. UNUSED_PARAMETER(iOff);
  28615. /* If p==0 (unmap the entire file) then there must be no outstanding
  28616. ** xFetch references. Or, if p!=0 (meaning it is an xFetch reference),
  28617. ** then there must be at least one outstanding. */
  28618. assert( (p==0)==(pFd->nFetchOut==0) );
  28619. /* If p!=0, it must match the iOff value. */
  28620. assert( p==0 || p==&((u8 *)pFd->pMapRegion)[iOff] );
  28621. if( p ){
  28622. pFd->nFetchOut--;
  28623. }else{
  28624. unixUnmapfile(pFd);
  28625. }
  28626. assert( pFd->nFetchOut>=0 );
  28627. #else
  28628. UNUSED_PARAMETER(fd);
  28629. UNUSED_PARAMETER(p);
  28630. UNUSED_PARAMETER(iOff);
  28631. #endif
  28632. return SQLITE_OK;
  28633. }
  28634. /*
  28635. ** Here ends the implementation of all sqlite3_file methods.
  28636. **
  28637. ********************** End sqlite3_file Methods *******************************
  28638. ******************************************************************************/
  28639. /*
  28640. ** This division contains definitions of sqlite3_io_methods objects that
  28641. ** implement various file locking strategies. It also contains definitions
  28642. ** of "finder" functions. A finder-function is used to locate the appropriate
  28643. ** sqlite3_io_methods object for a particular database file. The pAppData
  28644. ** field of the sqlite3_vfs VFS objects are initialized to be pointers to
  28645. ** the correct finder-function for that VFS.
  28646. **
  28647. ** Most finder functions return a pointer to a fixed sqlite3_io_methods
  28648. ** object. The only interesting finder-function is autolockIoFinder, which
  28649. ** looks at the filesystem type and tries to guess the best locking
  28650. ** strategy from that.
  28651. **
  28652. ** For finder-function F, two objects are created:
  28653. **
  28654. ** (1) The real finder-function named "FImpt()".
  28655. **
  28656. ** (2) A constant pointer to this function named just "F".
  28657. **
  28658. **
  28659. ** A pointer to the F pointer is used as the pAppData value for VFS
  28660. ** objects. We have to do this instead of letting pAppData point
  28661. ** directly at the finder-function since C90 rules prevent a void*
  28662. ** from be cast into a function pointer.
  28663. **
  28664. **
  28665. ** Each instance of this macro generates two objects:
  28666. **
  28667. ** * A constant sqlite3_io_methods object call METHOD that has locking
  28668. ** methods CLOSE, LOCK, UNLOCK, CKRESLOCK.
  28669. **
  28670. ** * An I/O method finder function called FINDER that returns a pointer
  28671. ** to the METHOD object in the previous bullet.
  28672. */
  28673. #define IOMETHODS(FINDER,METHOD,VERSION,CLOSE,LOCK,UNLOCK,CKLOCK,SHMMAP) \
  28674. static const sqlite3_io_methods METHOD = { \
  28675. VERSION, /* iVersion */ \
  28676. CLOSE, /* xClose */ \
  28677. unixRead, /* xRead */ \
  28678. unixWrite, /* xWrite */ \
  28679. unixTruncate, /* xTruncate */ \
  28680. unixSync, /* xSync */ \
  28681. unixFileSize, /* xFileSize */ \
  28682. LOCK, /* xLock */ \
  28683. UNLOCK, /* xUnlock */ \
  28684. CKLOCK, /* xCheckReservedLock */ \
  28685. unixFileControl, /* xFileControl */ \
  28686. unixSectorSize, /* xSectorSize */ \
  28687. unixDeviceCharacteristics, /* xDeviceCapabilities */ \
  28688. SHMMAP, /* xShmMap */ \
  28689. unixShmLock, /* xShmLock */ \
  28690. unixShmBarrier, /* xShmBarrier */ \
  28691. unixShmUnmap, /* xShmUnmap */ \
  28692. unixFetch, /* xFetch */ \
  28693. unixUnfetch, /* xUnfetch */ \
  28694. }; \
  28695. static const sqlite3_io_methods *FINDER##Impl(const char *z, unixFile *p){ \
  28696. UNUSED_PARAMETER(z); UNUSED_PARAMETER(p); \
  28697. return &METHOD; \
  28698. } \
  28699. static const sqlite3_io_methods *(*const FINDER)(const char*,unixFile *p) \
  28700. = FINDER##Impl;
  28701. /*
  28702. ** Here are all of the sqlite3_io_methods objects for each of the
  28703. ** locking strategies. Functions that return pointers to these methods
  28704. ** are also created.
  28705. */
  28706. IOMETHODS(
  28707. posixIoFinder, /* Finder function name */
  28708. posixIoMethods, /* sqlite3_io_methods object name */
  28709. 3, /* shared memory and mmap are enabled */
  28710. unixClose, /* xClose method */
  28711. unixLock, /* xLock method */
  28712. unixUnlock, /* xUnlock method */
  28713. unixCheckReservedLock, /* xCheckReservedLock method */
  28714. unixShmMap /* xShmMap method */
  28715. )
  28716. IOMETHODS(
  28717. nolockIoFinder, /* Finder function name */
  28718. nolockIoMethods, /* sqlite3_io_methods object name */
  28719. 3, /* shared memory is disabled */
  28720. nolockClose, /* xClose method */
  28721. nolockLock, /* xLock method */
  28722. nolockUnlock, /* xUnlock method */
  28723. nolockCheckReservedLock, /* xCheckReservedLock method */
  28724. 0 /* xShmMap method */
  28725. )
  28726. IOMETHODS(
  28727. dotlockIoFinder, /* Finder function name */
  28728. dotlockIoMethods, /* sqlite3_io_methods object name */
  28729. 1, /* shared memory is disabled */
  28730. dotlockClose, /* xClose method */
  28731. dotlockLock, /* xLock method */
  28732. dotlockUnlock, /* xUnlock method */
  28733. dotlockCheckReservedLock, /* xCheckReservedLock method */
  28734. 0 /* xShmMap method */
  28735. )
  28736. #if SQLITE_ENABLE_LOCKING_STYLE
  28737. IOMETHODS(
  28738. flockIoFinder, /* Finder function name */
  28739. flockIoMethods, /* sqlite3_io_methods object name */
  28740. 1, /* shared memory is disabled */
  28741. flockClose, /* xClose method */
  28742. flockLock, /* xLock method */
  28743. flockUnlock, /* xUnlock method */
  28744. flockCheckReservedLock, /* xCheckReservedLock method */
  28745. 0 /* xShmMap method */
  28746. )
  28747. #endif
  28748. #if OS_VXWORKS
  28749. IOMETHODS(
  28750. semIoFinder, /* Finder function name */
  28751. semIoMethods, /* sqlite3_io_methods object name */
  28752. 1, /* shared memory is disabled */
  28753. semXClose, /* xClose method */
  28754. semXLock, /* xLock method */
  28755. semXUnlock, /* xUnlock method */
  28756. semXCheckReservedLock, /* xCheckReservedLock method */
  28757. 0 /* xShmMap method */
  28758. )
  28759. #endif
  28760. #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
  28761. IOMETHODS(
  28762. afpIoFinder, /* Finder function name */
  28763. afpIoMethods, /* sqlite3_io_methods object name */
  28764. 1, /* shared memory is disabled */
  28765. afpClose, /* xClose method */
  28766. afpLock, /* xLock method */
  28767. afpUnlock, /* xUnlock method */
  28768. afpCheckReservedLock, /* xCheckReservedLock method */
  28769. 0 /* xShmMap method */
  28770. )
  28771. #endif
  28772. /*
  28773. ** The proxy locking method is a "super-method" in the sense that it
  28774. ** opens secondary file descriptors for the conch and lock files and
  28775. ** it uses proxy, dot-file, AFP, and flock() locking methods on those
  28776. ** secondary files. For this reason, the division that implements
  28777. ** proxy locking is located much further down in the file. But we need
  28778. ** to go ahead and define the sqlite3_io_methods and finder function
  28779. ** for proxy locking here. So we forward declare the I/O methods.
  28780. */
  28781. #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
  28782. static int proxyClose(sqlite3_file*);
  28783. static int proxyLock(sqlite3_file*, int);
  28784. static int proxyUnlock(sqlite3_file*, int);
  28785. static int proxyCheckReservedLock(sqlite3_file*, int*);
  28786. IOMETHODS(
  28787. proxyIoFinder, /* Finder function name */
  28788. proxyIoMethods, /* sqlite3_io_methods object name */
  28789. 1, /* shared memory is disabled */
  28790. proxyClose, /* xClose method */
  28791. proxyLock, /* xLock method */
  28792. proxyUnlock, /* xUnlock method */
  28793. proxyCheckReservedLock, /* xCheckReservedLock method */
  28794. 0 /* xShmMap method */
  28795. )
  28796. #endif
  28797. /* nfs lockd on OSX 10.3+ doesn't clear write locks when a read lock is set */
  28798. #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
  28799. IOMETHODS(
  28800. nfsIoFinder, /* Finder function name */
  28801. nfsIoMethods, /* sqlite3_io_methods object name */
  28802. 1, /* shared memory is disabled */
  28803. unixClose, /* xClose method */
  28804. unixLock, /* xLock method */
  28805. nfsUnlock, /* xUnlock method */
  28806. unixCheckReservedLock, /* xCheckReservedLock method */
  28807. 0 /* xShmMap method */
  28808. )
  28809. #endif
  28810. #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
  28811. /*
  28812. ** This "finder" function attempts to determine the best locking strategy
  28813. ** for the database file "filePath". It then returns the sqlite3_io_methods
  28814. ** object that implements that strategy.
  28815. **
  28816. ** This is for MacOSX only.
  28817. */
  28818. static const sqlite3_io_methods *autolockIoFinderImpl(
  28819. const char *filePath, /* name of the database file */
  28820. unixFile *pNew /* open file object for the database file */
  28821. ){
  28822. static const struct Mapping {
  28823. const char *zFilesystem; /* Filesystem type name */
  28824. const sqlite3_io_methods *pMethods; /* Appropriate locking method */
  28825. } aMap[] = {
  28826. { "hfs", &posixIoMethods },
  28827. { "ufs", &posixIoMethods },
  28828. { "afpfs", &afpIoMethods },
  28829. { "smbfs", &afpIoMethods },
  28830. { "webdav", &nolockIoMethods },
  28831. { 0, 0 }
  28832. };
  28833. int i;
  28834. struct statfs fsInfo;
  28835. struct flock lockInfo;
  28836. if( !filePath ){
  28837. /* If filePath==NULL that means we are dealing with a transient file
  28838. ** that does not need to be locked. */
  28839. return &nolockIoMethods;
  28840. }
  28841. if( statfs(filePath, &fsInfo) != -1 ){
  28842. if( fsInfo.f_flags & MNT_RDONLY ){
  28843. return &nolockIoMethods;
  28844. }
  28845. for(i=0; aMap[i].zFilesystem; i++){
  28846. if( strcmp(fsInfo.f_fstypename, aMap[i].zFilesystem)==0 ){
  28847. return aMap[i].pMethods;
  28848. }
  28849. }
  28850. }
  28851. /* Default case. Handles, amongst others, "nfs".
  28852. ** Test byte-range lock using fcntl(). If the call succeeds,
  28853. ** assume that the file-system supports POSIX style locks.
  28854. */
  28855. lockInfo.l_len = 1;
  28856. lockInfo.l_start = 0;
  28857. lockInfo.l_whence = SEEK_SET;
  28858. lockInfo.l_type = F_RDLCK;
  28859. if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
  28860. if( strcmp(fsInfo.f_fstypename, "nfs")==0 ){
  28861. return &nfsIoMethods;
  28862. } else {
  28863. return &posixIoMethods;
  28864. }
  28865. }else{
  28866. return &dotlockIoMethods;
  28867. }
  28868. }
  28869. static const sqlite3_io_methods
  28870. *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
  28871. #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
  28872. #if OS_VXWORKS
  28873. /*
  28874. ** This "finder" function for VxWorks checks to see if posix advisory
  28875. ** locking works. If it does, then that is what is used. If it does not
  28876. ** work, then fallback to named semaphore locking.
  28877. */
  28878. static const sqlite3_io_methods *vxworksIoFinderImpl(
  28879. const char *filePath, /* name of the database file */
  28880. unixFile *pNew /* the open file object */
  28881. ){
  28882. struct flock lockInfo;
  28883. if( !filePath ){
  28884. /* If filePath==NULL that means we are dealing with a transient file
  28885. ** that does not need to be locked. */
  28886. return &nolockIoMethods;
  28887. }
  28888. /* Test if fcntl() is supported and use POSIX style locks.
  28889. ** Otherwise fall back to the named semaphore method.
  28890. */
  28891. lockInfo.l_len = 1;
  28892. lockInfo.l_start = 0;
  28893. lockInfo.l_whence = SEEK_SET;
  28894. lockInfo.l_type = F_RDLCK;
  28895. if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
  28896. return &posixIoMethods;
  28897. }else{
  28898. return &semIoMethods;
  28899. }
  28900. }
  28901. static const sqlite3_io_methods
  28902. *(*const vxworksIoFinder)(const char*,unixFile*) = vxworksIoFinderImpl;
  28903. #endif /* OS_VXWORKS */
  28904. /*
  28905. ** An abstract type for a pointer to an IO method finder function:
  28906. */
  28907. typedef const sqlite3_io_methods *(*finder_type)(const char*,unixFile*);
  28908. /****************************************************************************
  28909. **************************** sqlite3_vfs methods ****************************
  28910. **
  28911. ** This division contains the implementation of methods on the
  28912. ** sqlite3_vfs object.
  28913. */
  28914. /*
  28915. ** Initialize the contents of the unixFile structure pointed to by pId.
  28916. */
  28917. static int fillInUnixFile(
  28918. sqlite3_vfs *pVfs, /* Pointer to vfs object */
  28919. int h, /* Open file descriptor of file being opened */
  28920. sqlite3_file *pId, /* Write to the unixFile structure here */
  28921. const char *zFilename, /* Name of the file being opened */
  28922. int ctrlFlags /* Zero or more UNIXFILE_* values */
  28923. ){
  28924. const sqlite3_io_methods *pLockingStyle;
  28925. unixFile *pNew = (unixFile *)pId;
  28926. int rc = SQLITE_OK;
  28927. assert( pNew->pInode==NULL );
  28928. /* Usually the path zFilename should not be a relative pathname. The
  28929. ** exception is when opening the proxy "conch" file in builds that
  28930. ** include the special Apple locking styles.
  28931. */
  28932. #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
  28933. assert( zFilename==0 || zFilename[0]=='/'
  28934. || pVfs->pAppData==(void*)&autolockIoFinder );
  28935. #else
  28936. assert( zFilename==0 || zFilename[0]=='/' );
  28937. #endif
  28938. /* No locking occurs in temporary files */
  28939. assert( zFilename!=0 || (ctrlFlags & UNIXFILE_NOLOCK)!=0 );
  28940. OSTRACE(("OPEN %-3d %s\n", h, zFilename));
  28941. pNew->h = h;
  28942. pNew->pVfs = pVfs;
  28943. pNew->zPath = zFilename;
  28944. pNew->ctrlFlags = (u8)ctrlFlags;
  28945. #if SQLITE_MAX_MMAP_SIZE>0
  28946. pNew->mmapSizeMax = sqlite3GlobalConfig.szMmap;
  28947. #endif
  28948. if( sqlite3_uri_boolean(((ctrlFlags & UNIXFILE_URI) ? zFilename : 0),
  28949. "psow", SQLITE_POWERSAFE_OVERWRITE) ){
  28950. pNew->ctrlFlags |= UNIXFILE_PSOW;
  28951. }
  28952. if( strcmp(pVfs->zName,"unix-excl")==0 ){
  28953. pNew->ctrlFlags |= UNIXFILE_EXCL;
  28954. }
  28955. #if OS_VXWORKS
  28956. pNew->pId = vxworksFindFileId(zFilename);
  28957. if( pNew->pId==0 ){
  28958. ctrlFlags |= UNIXFILE_NOLOCK;
  28959. rc = SQLITE_NOMEM;
  28960. }
  28961. #endif
  28962. if( ctrlFlags & UNIXFILE_NOLOCK ){
  28963. pLockingStyle = &nolockIoMethods;
  28964. }else{
  28965. pLockingStyle = (**(finder_type*)pVfs->pAppData)(zFilename, pNew);
  28966. #if SQLITE_ENABLE_LOCKING_STYLE
  28967. /* Cache zFilename in the locking context (AFP and dotlock override) for
  28968. ** proxyLock activation is possible (remote proxy is based on db name)
  28969. ** zFilename remains valid until file is closed, to support */
  28970. pNew->lockingContext = (void*)zFilename;
  28971. #endif
  28972. }
  28973. if( pLockingStyle == &posixIoMethods
  28974. #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
  28975. || pLockingStyle == &nfsIoMethods
  28976. #endif
  28977. ){
  28978. unixEnterMutex();
  28979. rc = findInodeInfo(pNew, &pNew->pInode);
  28980. if( rc!=SQLITE_OK ){
  28981. /* If an error occurred in findInodeInfo(), close the file descriptor
  28982. ** immediately, before releasing the mutex. findInodeInfo() may fail
  28983. ** in two scenarios:
  28984. **
  28985. ** (a) A call to fstat() failed.
  28986. ** (b) A malloc failed.
  28987. **
  28988. ** Scenario (b) may only occur if the process is holding no other
  28989. ** file descriptors open on the same file. If there were other file
  28990. ** descriptors on this file, then no malloc would be required by
  28991. ** findInodeInfo(). If this is the case, it is quite safe to close
  28992. ** handle h - as it is guaranteed that no posix locks will be released
  28993. ** by doing so.
  28994. **
  28995. ** If scenario (a) caused the error then things are not so safe. The
  28996. ** implicit assumption here is that if fstat() fails, things are in
  28997. ** such bad shape that dropping a lock or two doesn't matter much.
  28998. */
  28999. robust_close(pNew, h, __LINE__);
  29000. h = -1;
  29001. }
  29002. unixLeaveMutex();
  29003. }
  29004. #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
  29005. else if( pLockingStyle == &afpIoMethods ){
  29006. /* AFP locking uses the file path so it needs to be included in
  29007. ** the afpLockingContext.
  29008. */
  29009. afpLockingContext *pCtx;
  29010. pNew->lockingContext = pCtx = sqlite3_malloc64( sizeof(*pCtx) );
  29011. if( pCtx==0 ){
  29012. rc = SQLITE_NOMEM;
  29013. }else{
  29014. /* NB: zFilename exists and remains valid until the file is closed
  29015. ** according to requirement F11141. So we do not need to make a
  29016. ** copy of the filename. */
  29017. pCtx->dbPath = zFilename;
  29018. pCtx->reserved = 0;
  29019. srandomdev();
  29020. unixEnterMutex();
  29021. rc = findInodeInfo(pNew, &pNew->pInode);
  29022. if( rc!=SQLITE_OK ){
  29023. sqlite3_free(pNew->lockingContext);
  29024. robust_close(pNew, h, __LINE__);
  29025. h = -1;
  29026. }
  29027. unixLeaveMutex();
  29028. }
  29029. }
  29030. #endif
  29031. else if( pLockingStyle == &dotlockIoMethods ){
  29032. /* Dotfile locking uses the file path so it needs to be included in
  29033. ** the dotlockLockingContext
  29034. */
  29035. char *zLockFile;
  29036. int nFilename;
  29037. assert( zFilename!=0 );
  29038. nFilename = (int)strlen(zFilename) + 6;
  29039. zLockFile = (char *)sqlite3_malloc64(nFilename);
  29040. if( zLockFile==0 ){
  29041. rc = SQLITE_NOMEM;
  29042. }else{
  29043. sqlite3_snprintf(nFilename, zLockFile, "%s" DOTLOCK_SUFFIX, zFilename);
  29044. }
  29045. pNew->lockingContext = zLockFile;
  29046. }
  29047. #if OS_VXWORKS
  29048. else if( pLockingStyle == &semIoMethods ){
  29049. /* Named semaphore locking uses the file path so it needs to be
  29050. ** included in the semLockingContext
  29051. */
  29052. unixEnterMutex();
  29053. rc = findInodeInfo(pNew, &pNew->pInode);
  29054. if( (rc==SQLITE_OK) && (pNew->pInode->pSem==NULL) ){
  29055. char *zSemName = pNew->pInode->aSemName;
  29056. int n;
  29057. sqlite3_snprintf(MAX_PATHNAME, zSemName, "/%s.sem",
  29058. pNew->pId->zCanonicalName);
  29059. for( n=1; zSemName[n]; n++ )
  29060. if( zSemName[n]=='/' ) zSemName[n] = '_';
  29061. pNew->pInode->pSem = sem_open(zSemName, O_CREAT, 0666, 1);
  29062. if( pNew->pInode->pSem == SEM_FAILED ){
  29063. rc = SQLITE_NOMEM;
  29064. pNew->pInode->aSemName[0] = '\0';
  29065. }
  29066. }
  29067. unixLeaveMutex();
  29068. }
  29069. #endif
  29070. storeLastErrno(pNew, 0);
  29071. #if OS_VXWORKS
  29072. if( rc!=SQLITE_OK ){
  29073. if( h>=0 ) robust_close(pNew, h, __LINE__);
  29074. h = -1;
  29075. osUnlink(zFilename);
  29076. pNew->ctrlFlags |= UNIXFILE_DELETE;
  29077. }
  29078. #endif
  29079. if( rc!=SQLITE_OK ){
  29080. if( h>=0 ) robust_close(pNew, h, __LINE__);
  29081. }else{
  29082. pNew->pMethod = pLockingStyle;
  29083. OpenCounter(+1);
  29084. verifyDbFile(pNew);
  29085. }
  29086. return rc;
  29087. }
  29088. /*
  29089. ** Return the name of a directory in which to put temporary files.
  29090. ** If no suitable temporary file directory can be found, return NULL.
  29091. */
  29092. static const char *unixTempFileDir(void){
  29093. static const char *azDirs[] = {
  29094. 0,
  29095. 0,
  29096. 0,
  29097. "/var/tmp",
  29098. "/usr/tmp",
  29099. "/tmp",
  29100. 0 /* List terminator */
  29101. };
  29102. unsigned int i;
  29103. struct stat buf;
  29104. const char *zDir = 0;
  29105. azDirs[0] = sqlite3_temp_directory;
  29106. if( !azDirs[1] ) azDirs[1] = getenv("SQLITE_TMPDIR");
  29107. if( !azDirs[2] ) azDirs[2] = getenv("TMPDIR");
  29108. for(i=0; i<sizeof(azDirs)/sizeof(azDirs[0]); zDir=azDirs[i++]){
  29109. if( zDir==0 ) continue;
  29110. if( osStat(zDir, &buf) ) continue;
  29111. if( !S_ISDIR(buf.st_mode) ) continue;
  29112. if( osAccess(zDir, 07) ) continue;
  29113. break;
  29114. }
  29115. return zDir;
  29116. }
  29117. /*
  29118. ** Create a temporary file name in zBuf. zBuf must be allocated
  29119. ** by the calling process and must be big enough to hold at least
  29120. ** pVfs->mxPathname bytes.
  29121. */
  29122. static int unixGetTempname(int nBuf, char *zBuf){
  29123. static const unsigned char zChars[] =
  29124. "abcdefghijklmnopqrstuvwxyz"
  29125. "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
  29126. "0123456789";
  29127. unsigned int i, j;
  29128. const char *zDir;
  29129. /* It's odd to simulate an io-error here, but really this is just
  29130. ** using the io-error infrastructure to test that SQLite handles this
  29131. ** function failing.
  29132. */
  29133. SimulateIOError( return SQLITE_IOERR );
  29134. zDir = unixTempFileDir();
  29135. if( zDir==0 ) zDir = ".";
  29136. /* Check that the output buffer is large enough for the temporary file
  29137. ** name. If it is not, return SQLITE_ERROR.
  29138. */
  29139. if( (strlen(zDir) + strlen(SQLITE_TEMP_FILE_PREFIX) + 18) >= (size_t)nBuf ){
  29140. return SQLITE_ERROR;
  29141. }
  29142. do{
  29143. sqlite3_snprintf(nBuf-18, zBuf, "%s/"SQLITE_TEMP_FILE_PREFIX, zDir);
  29144. j = (int)strlen(zBuf);
  29145. sqlite3_randomness(15, &zBuf[j]);
  29146. for(i=0; i<15; i++, j++){
  29147. zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
  29148. }
  29149. zBuf[j] = 0;
  29150. zBuf[j+1] = 0;
  29151. }while( osAccess(zBuf,0)==0 );
  29152. return SQLITE_OK;
  29153. }
  29154. #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
  29155. /*
  29156. ** Routine to transform a unixFile into a proxy-locking unixFile.
  29157. ** Implementation in the proxy-lock division, but used by unixOpen()
  29158. ** if SQLITE_PREFER_PROXY_LOCKING is defined.
  29159. */
  29160. static int proxyTransformUnixFile(unixFile*, const char*);
  29161. #endif
  29162. /*
  29163. ** Search for an unused file descriptor that was opened on the database
  29164. ** file (not a journal or master-journal file) identified by pathname
  29165. ** zPath with SQLITE_OPEN_XXX flags matching those passed as the second
  29166. ** argument to this function.
  29167. **
  29168. ** Such a file descriptor may exist if a database connection was closed
  29169. ** but the associated file descriptor could not be closed because some
  29170. ** other file descriptor open on the same file is holding a file-lock.
  29171. ** Refer to comments in the unixClose() function and the lengthy comment
  29172. ** describing "Posix Advisory Locking" at the start of this file for
  29173. ** further details. Also, ticket #4018.
  29174. **
  29175. ** If a suitable file descriptor is found, then it is returned. If no
  29176. ** such file descriptor is located, -1 is returned.
  29177. */
  29178. static UnixUnusedFd *findReusableFd(const char *zPath, int flags){
  29179. UnixUnusedFd *pUnused = 0;
  29180. /* Do not search for an unused file descriptor on vxworks. Not because
  29181. ** vxworks would not benefit from the change (it might, we're not sure),
  29182. ** but because no way to test it is currently available. It is better
  29183. ** not to risk breaking vxworks support for the sake of such an obscure
  29184. ** feature. */
  29185. #if !OS_VXWORKS
  29186. struct stat sStat; /* Results of stat() call */
  29187. /* A stat() call may fail for various reasons. If this happens, it is
  29188. ** almost certain that an open() call on the same path will also fail.
  29189. ** For this reason, if an error occurs in the stat() call here, it is
  29190. ** ignored and -1 is returned. The caller will try to open a new file
  29191. ** descriptor on the same path, fail, and return an error to SQLite.
  29192. **
  29193. ** Even if a subsequent open() call does succeed, the consequences of
  29194. ** not searching for a reusable file descriptor are not dire. */
  29195. if( 0==osStat(zPath, &sStat) ){
  29196. unixInodeInfo *pInode;
  29197. unixEnterMutex();
  29198. pInode = inodeList;
  29199. while( pInode && (pInode->fileId.dev!=sStat.st_dev
  29200. || pInode->fileId.ino!=sStat.st_ino) ){
  29201. pInode = pInode->pNext;
  29202. }
  29203. if( pInode ){
  29204. UnixUnusedFd **pp;
  29205. for(pp=&pInode->pUnused; *pp && (*pp)->flags!=flags; pp=&((*pp)->pNext));
  29206. pUnused = *pp;
  29207. if( pUnused ){
  29208. *pp = pUnused->pNext;
  29209. }
  29210. }
  29211. unixLeaveMutex();
  29212. }
  29213. #endif /* if !OS_VXWORKS */
  29214. return pUnused;
  29215. }
  29216. /*
  29217. ** This function is called by unixOpen() to determine the unix permissions
  29218. ** to create new files with. If no error occurs, then SQLITE_OK is returned
  29219. ** and a value suitable for passing as the third argument to open(2) is
  29220. ** written to *pMode. If an IO error occurs, an SQLite error code is
  29221. ** returned and the value of *pMode is not modified.
  29222. **
  29223. ** In most cases, this routine sets *pMode to 0, which will become
  29224. ** an indication to robust_open() to create the file using
  29225. ** SQLITE_DEFAULT_FILE_PERMISSIONS adjusted by the umask.
  29226. ** But if the file being opened is a WAL or regular journal file, then
  29227. ** this function queries the file-system for the permissions on the
  29228. ** corresponding database file and sets *pMode to this value. Whenever
  29229. ** possible, WAL and journal files are created using the same permissions
  29230. ** as the associated database file.
  29231. **
  29232. ** If the SQLITE_ENABLE_8_3_NAMES option is enabled, then the
  29233. ** original filename is unavailable. But 8_3_NAMES is only used for
  29234. ** FAT filesystems and permissions do not matter there, so just use
  29235. ** the default permissions.
  29236. */
  29237. static int findCreateFileMode(
  29238. const char *zPath, /* Path of file (possibly) being created */
  29239. int flags, /* Flags passed as 4th argument to xOpen() */
  29240. mode_t *pMode, /* OUT: Permissions to open file with */
  29241. uid_t *pUid, /* OUT: uid to set on the file */
  29242. gid_t *pGid /* OUT: gid to set on the file */
  29243. ){
  29244. int rc = SQLITE_OK; /* Return Code */
  29245. *pMode = 0;
  29246. *pUid = 0;
  29247. *pGid = 0;
  29248. if( flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL) ){
  29249. char zDb[MAX_PATHNAME+1]; /* Database file path */
  29250. int nDb; /* Number of valid bytes in zDb */
  29251. struct stat sStat; /* Output of stat() on database file */
  29252. /* zPath is a path to a WAL or journal file. The following block derives
  29253. ** the path to the associated database file from zPath. This block handles
  29254. ** the following naming conventions:
  29255. **
  29256. ** "<path to db>-journal"
  29257. ** "<path to db>-wal"
  29258. ** "<path to db>-journalNN"
  29259. ** "<path to db>-walNN"
  29260. **
  29261. ** where NN is a decimal number. The NN naming schemes are
  29262. ** used by the test_multiplex.c module.
  29263. */
  29264. nDb = sqlite3Strlen30(zPath) - 1;
  29265. #ifdef SQLITE_ENABLE_8_3_NAMES
  29266. while( nDb>0 && sqlite3Isalnum(zPath[nDb]) ) nDb--;
  29267. if( nDb==0 || zPath[nDb]!='-' ) return SQLITE_OK;
  29268. #else
  29269. while( zPath[nDb]!='-' ){
  29270. assert( nDb>0 );
  29271. assert( zPath[nDb]!='\n' );
  29272. nDb--;
  29273. }
  29274. #endif
  29275. memcpy(zDb, zPath, nDb);
  29276. zDb[nDb] = '\0';
  29277. if( 0==osStat(zDb, &sStat) ){
  29278. *pMode = sStat.st_mode & 0777;
  29279. *pUid = sStat.st_uid;
  29280. *pGid = sStat.st_gid;
  29281. }else{
  29282. rc = SQLITE_IOERR_FSTAT;
  29283. }
  29284. }else if( flags & SQLITE_OPEN_DELETEONCLOSE ){
  29285. *pMode = 0600;
  29286. }
  29287. return rc;
  29288. }
  29289. /*
  29290. ** Open the file zPath.
  29291. **
  29292. ** Previously, the SQLite OS layer used three functions in place of this
  29293. ** one:
  29294. **
  29295. ** sqlite3OsOpenReadWrite();
  29296. ** sqlite3OsOpenReadOnly();
  29297. ** sqlite3OsOpenExclusive();
  29298. **
  29299. ** These calls correspond to the following combinations of flags:
  29300. **
  29301. ** ReadWrite() -> (READWRITE | CREATE)
  29302. ** ReadOnly() -> (READONLY)
  29303. ** OpenExclusive() -> (READWRITE | CREATE | EXCLUSIVE)
  29304. **
  29305. ** The old OpenExclusive() accepted a boolean argument - "delFlag". If
  29306. ** true, the file was configured to be automatically deleted when the
  29307. ** file handle closed. To achieve the same effect using this new
  29308. ** interface, add the DELETEONCLOSE flag to those specified above for
  29309. ** OpenExclusive().
  29310. */
  29311. static int unixOpen(
  29312. sqlite3_vfs *pVfs, /* The VFS for which this is the xOpen method */
  29313. const char *zPath, /* Pathname of file to be opened */
  29314. sqlite3_file *pFile, /* The file descriptor to be filled in */
  29315. int flags, /* Input flags to control the opening */
  29316. int *pOutFlags /* Output flags returned to SQLite core */
  29317. ){
  29318. unixFile *p = (unixFile *)pFile;
  29319. int fd = -1; /* File descriptor returned by open() */
  29320. int openFlags = 0; /* Flags to pass to open() */
  29321. int eType = flags&0xFFFFFF00; /* Type of file to open */
  29322. int noLock; /* True to omit locking primitives */
  29323. int rc = SQLITE_OK; /* Function Return Code */
  29324. int ctrlFlags = 0; /* UNIXFILE_* flags */
  29325. int isExclusive = (flags & SQLITE_OPEN_EXCLUSIVE);
  29326. int isDelete = (flags & SQLITE_OPEN_DELETEONCLOSE);
  29327. int isCreate = (flags & SQLITE_OPEN_CREATE);
  29328. int isReadonly = (flags & SQLITE_OPEN_READONLY);
  29329. int isReadWrite = (flags & SQLITE_OPEN_READWRITE);
  29330. #if SQLITE_ENABLE_LOCKING_STYLE
  29331. int isAutoProxy = (flags & SQLITE_OPEN_AUTOPROXY);
  29332. #endif
  29333. #if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
  29334. struct statfs fsInfo;
  29335. #endif
  29336. /* If creating a master or main-file journal, this function will open
  29337. ** a file-descriptor on the directory too. The first time unixSync()
  29338. ** is called the directory file descriptor will be fsync()ed and close()d.
  29339. */
  29340. int syncDir = (isCreate && (
  29341. eType==SQLITE_OPEN_MASTER_JOURNAL
  29342. || eType==SQLITE_OPEN_MAIN_JOURNAL
  29343. || eType==SQLITE_OPEN_WAL
  29344. ));
  29345. /* If argument zPath is a NULL pointer, this function is required to open
  29346. ** a temporary file. Use this buffer to store the file name in.
  29347. */
  29348. char zTmpname[MAX_PATHNAME+2];
  29349. const char *zName = zPath;
  29350. /* Check the following statements are true:
  29351. **
  29352. ** (a) Exactly one of the READWRITE and READONLY flags must be set, and
  29353. ** (b) if CREATE is set, then READWRITE must also be set, and
  29354. ** (c) if EXCLUSIVE is set, then CREATE must also be set.
  29355. ** (d) if DELETEONCLOSE is set, then CREATE must also be set.
  29356. */
  29357. assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
  29358. assert(isCreate==0 || isReadWrite);
  29359. assert(isExclusive==0 || isCreate);
  29360. assert(isDelete==0 || isCreate);
  29361. /* The main DB, main journal, WAL file and master journal are never
  29362. ** automatically deleted. Nor are they ever temporary files. */
  29363. assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB );
  29364. assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL );
  29365. assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MASTER_JOURNAL );
  29366. assert( (!isDelete && zName) || eType!=SQLITE_OPEN_WAL );
  29367. /* Assert that the upper layer has set one of the "file-type" flags. */
  29368. assert( eType==SQLITE_OPEN_MAIN_DB || eType==SQLITE_OPEN_TEMP_DB
  29369. || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL
  29370. || eType==SQLITE_OPEN_SUBJOURNAL || eType==SQLITE_OPEN_MASTER_JOURNAL
  29371. || eType==SQLITE_OPEN_TRANSIENT_DB || eType==SQLITE_OPEN_WAL
  29372. );
  29373. /* Detect a pid change and reset the PRNG. There is a race condition
  29374. ** here such that two or more threads all trying to open databases at
  29375. ** the same instant might all reset the PRNG. But multiple resets
  29376. ** are harmless.
  29377. */
  29378. if( randomnessPid!=osGetpid(0) ){
  29379. randomnessPid = osGetpid(0);
  29380. sqlite3_randomness(0,0);
  29381. }
  29382. memset(p, 0, sizeof(unixFile));
  29383. if( eType==SQLITE_OPEN_MAIN_DB ){
  29384. UnixUnusedFd *pUnused;
  29385. pUnused = findReusableFd(zName, flags);
  29386. if( pUnused ){
  29387. fd = pUnused->fd;
  29388. }else{
  29389. pUnused = sqlite3_malloc64(sizeof(*pUnused));
  29390. if( !pUnused ){
  29391. return SQLITE_NOMEM;
  29392. }
  29393. }
  29394. p->pUnused = pUnused;
  29395. /* Database filenames are double-zero terminated if they are not
  29396. ** URIs with parameters. Hence, they can always be passed into
  29397. ** sqlite3_uri_parameter(). */
  29398. assert( (flags & SQLITE_OPEN_URI) || zName[strlen(zName)+1]==0 );
  29399. }else if( !zName ){
  29400. /* If zName is NULL, the upper layer is requesting a temp file. */
  29401. assert(isDelete && !syncDir);
  29402. rc = unixGetTempname(MAX_PATHNAME+2, zTmpname);
  29403. if( rc!=SQLITE_OK ){
  29404. return rc;
  29405. }
  29406. zName = zTmpname;
  29407. /* Generated temporary filenames are always double-zero terminated
  29408. ** for use by sqlite3_uri_parameter(). */
  29409. assert( zName[strlen(zName)+1]==0 );
  29410. }
  29411. /* Determine the value of the flags parameter passed to POSIX function
  29412. ** open(). These must be calculated even if open() is not called, as
  29413. ** they may be stored as part of the file handle and used by the
  29414. ** 'conch file' locking functions later on. */
  29415. if( isReadonly ) openFlags |= O_RDONLY;
  29416. if( isReadWrite ) openFlags |= O_RDWR;
  29417. if( isCreate ) openFlags |= O_CREAT;
  29418. if( isExclusive ) openFlags |= (O_EXCL|O_NOFOLLOW);
  29419. openFlags |= (O_LARGEFILE|O_BINARY);
  29420. if( fd<0 ){
  29421. mode_t openMode; /* Permissions to create file with */
  29422. uid_t uid; /* Userid for the file */
  29423. gid_t gid; /* Groupid for the file */
  29424. rc = findCreateFileMode(zName, flags, &openMode, &uid, &gid);
  29425. if( rc!=SQLITE_OK ){
  29426. assert( !p->pUnused );
  29427. assert( eType==SQLITE_OPEN_WAL || eType==SQLITE_OPEN_MAIN_JOURNAL );
  29428. return rc;
  29429. }
  29430. fd = robust_open(zName, openFlags, openMode);
  29431. OSTRACE(("OPENX %-3d %s 0%o\n", fd, zName, openFlags));
  29432. if( fd<0 && errno!=EISDIR && isReadWrite && !isExclusive ){
  29433. /* Failed to open the file for read/write access. Try read-only. */
  29434. flags &= ~(SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE);
  29435. openFlags &= ~(O_RDWR|O_CREAT);
  29436. flags |= SQLITE_OPEN_READONLY;
  29437. openFlags |= O_RDONLY;
  29438. isReadonly = 1;
  29439. fd = robust_open(zName, openFlags, openMode);
  29440. }
  29441. if( fd<0 ){
  29442. rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zName);
  29443. goto open_finished;
  29444. }
  29445. /* If this process is running as root and if creating a new rollback
  29446. ** journal or WAL file, set the ownership of the journal or WAL to be
  29447. ** the same as the original database.
  29448. */
  29449. if( flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL) ){
  29450. osFchown(fd, uid, gid);
  29451. }
  29452. }
  29453. assert( fd>=0 );
  29454. if( pOutFlags ){
  29455. *pOutFlags = flags;
  29456. }
  29457. if( p->pUnused ){
  29458. p->pUnused->fd = fd;
  29459. p->pUnused->flags = flags;
  29460. }
  29461. if( isDelete ){
  29462. #if OS_VXWORKS
  29463. zPath = zName;
  29464. #elif defined(SQLITE_UNLINK_AFTER_CLOSE)
  29465. zPath = sqlite3_mprintf("%s", zName);
  29466. if( zPath==0 ){
  29467. robust_close(p, fd, __LINE__);
  29468. return SQLITE_NOMEM;
  29469. }
  29470. #else
  29471. osUnlink(zName);
  29472. #endif
  29473. }
  29474. #if SQLITE_ENABLE_LOCKING_STYLE
  29475. else{
  29476. p->openFlags = openFlags;
  29477. }
  29478. #endif
  29479. noLock = eType!=SQLITE_OPEN_MAIN_DB;
  29480. #if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
  29481. if( fstatfs(fd, &fsInfo) == -1 ){
  29482. storeLastErrno(p, errno);
  29483. robust_close(p, fd, __LINE__);
  29484. return SQLITE_IOERR_ACCESS;
  29485. }
  29486. if (0 == strncmp("msdos", fsInfo.f_fstypename, 5)) {
  29487. ((unixFile*)pFile)->fsFlags |= SQLITE_FSFLAGS_IS_MSDOS;
  29488. }
  29489. if (0 == strncmp("exfat", fsInfo.f_fstypename, 5)) {
  29490. ((unixFile*)pFile)->fsFlags |= SQLITE_FSFLAGS_IS_MSDOS;
  29491. }
  29492. #endif
  29493. /* Set up appropriate ctrlFlags */
  29494. if( isDelete ) ctrlFlags |= UNIXFILE_DELETE;
  29495. if( isReadonly ) ctrlFlags |= UNIXFILE_RDONLY;
  29496. if( noLock ) ctrlFlags |= UNIXFILE_NOLOCK;
  29497. if( syncDir ) ctrlFlags |= UNIXFILE_DIRSYNC;
  29498. if( flags & SQLITE_OPEN_URI ) ctrlFlags |= UNIXFILE_URI;
  29499. #if SQLITE_ENABLE_LOCKING_STYLE
  29500. #if SQLITE_PREFER_PROXY_LOCKING
  29501. isAutoProxy = 1;
  29502. #endif
  29503. if( isAutoProxy && (zPath!=NULL) && (!noLock) && pVfs->xOpen ){
  29504. char *envforce = getenv("SQLITE_FORCE_PROXY_LOCKING");
  29505. int useProxy = 0;
  29506. /* SQLITE_FORCE_PROXY_LOCKING==1 means force always use proxy, 0 means
  29507. ** never use proxy, NULL means use proxy for non-local files only. */
  29508. if( envforce!=NULL ){
  29509. useProxy = atoi(envforce)>0;
  29510. }else{
  29511. useProxy = !(fsInfo.f_flags&MNT_LOCAL);
  29512. }
  29513. if( useProxy ){
  29514. rc = fillInUnixFile(pVfs, fd, pFile, zPath, ctrlFlags);
  29515. if( rc==SQLITE_OK ){
  29516. rc = proxyTransformUnixFile((unixFile*)pFile, ":auto:");
  29517. if( rc!=SQLITE_OK ){
  29518. /* Use unixClose to clean up the resources added in fillInUnixFile
  29519. ** and clear all the structure's references. Specifically,
  29520. ** pFile->pMethods will be NULL so sqlite3OsClose will be a no-op
  29521. */
  29522. unixClose(pFile);
  29523. return rc;
  29524. }
  29525. }
  29526. goto open_finished;
  29527. }
  29528. }
  29529. #endif
  29530. rc = fillInUnixFile(pVfs, fd, pFile, zPath, ctrlFlags);
  29531. open_finished:
  29532. if( rc!=SQLITE_OK ){
  29533. sqlite3_free(p->pUnused);
  29534. }
  29535. return rc;
  29536. }
  29537. /*
  29538. ** Delete the file at zPath. If the dirSync argument is true, fsync()
  29539. ** the directory after deleting the file.
  29540. */
  29541. static int unixDelete(
  29542. sqlite3_vfs *NotUsed, /* VFS containing this as the xDelete method */
  29543. const char *zPath, /* Name of file to be deleted */
  29544. int dirSync /* If true, fsync() directory after deleting file */
  29545. ){
  29546. int rc = SQLITE_OK;
  29547. UNUSED_PARAMETER(NotUsed);
  29548. SimulateIOError(return SQLITE_IOERR_DELETE);
  29549. if( osUnlink(zPath)==(-1) ){
  29550. if( errno==ENOENT
  29551. #if OS_VXWORKS
  29552. || osAccess(zPath,0)!=0
  29553. #endif
  29554. ){
  29555. rc = SQLITE_IOERR_DELETE_NOENT;
  29556. }else{
  29557. rc = unixLogError(SQLITE_IOERR_DELETE, "unlink", zPath);
  29558. }
  29559. return rc;
  29560. }
  29561. #ifndef SQLITE_DISABLE_DIRSYNC
  29562. if( (dirSync & 1)!=0 ){
  29563. int fd;
  29564. rc = osOpenDirectory(zPath, &fd);
  29565. if( rc==SQLITE_OK ){
  29566. #if OS_VXWORKS
  29567. if( fsync(fd)==-1 )
  29568. #else
  29569. if( fsync(fd) )
  29570. #endif
  29571. {
  29572. rc = unixLogError(SQLITE_IOERR_DIR_FSYNC, "fsync", zPath);
  29573. }
  29574. robust_close(0, fd, __LINE__);
  29575. }else if( rc==SQLITE_CANTOPEN ){
  29576. rc = SQLITE_OK;
  29577. }
  29578. }
  29579. #endif
  29580. return rc;
  29581. }
  29582. /*
  29583. ** Test the existence of or access permissions of file zPath. The
  29584. ** test performed depends on the value of flags:
  29585. **
  29586. ** SQLITE_ACCESS_EXISTS: Return 1 if the file exists
  29587. ** SQLITE_ACCESS_READWRITE: Return 1 if the file is read and writable.
  29588. ** SQLITE_ACCESS_READONLY: Return 1 if the file is readable.
  29589. **
  29590. ** Otherwise return 0.
  29591. */
  29592. static int unixAccess(
  29593. sqlite3_vfs *NotUsed, /* The VFS containing this xAccess method */
  29594. const char *zPath, /* Path of the file to examine */
  29595. int flags, /* What do we want to learn about the zPath file? */
  29596. int *pResOut /* Write result boolean here */
  29597. ){
  29598. int amode = 0;
  29599. UNUSED_PARAMETER(NotUsed);
  29600. SimulateIOError( return SQLITE_IOERR_ACCESS; );
  29601. switch( flags ){
  29602. case SQLITE_ACCESS_EXISTS:
  29603. amode = F_OK;
  29604. break;
  29605. case SQLITE_ACCESS_READWRITE:
  29606. amode = W_OK|R_OK;
  29607. break;
  29608. case SQLITE_ACCESS_READ:
  29609. amode = R_OK;
  29610. break;
  29611. default:
  29612. assert(!"Invalid flags argument");
  29613. }
  29614. *pResOut = (osAccess(zPath, amode)==0);
  29615. if( flags==SQLITE_ACCESS_EXISTS && *pResOut ){
  29616. struct stat buf;
  29617. if( 0==osStat(zPath, &buf) && buf.st_size==0 ){
  29618. *pResOut = 0;
  29619. }
  29620. }
  29621. return SQLITE_OK;
  29622. }
  29623. /*
  29624. ** Turn a relative pathname into a full pathname. The relative path
  29625. ** is stored as a nul-terminated string in the buffer pointed to by
  29626. ** zPath.
  29627. **
  29628. ** zOut points to a buffer of at least sqlite3_vfs.mxPathname bytes
  29629. ** (in this case, MAX_PATHNAME bytes). The full-path is written to
  29630. ** this buffer before returning.
  29631. */
  29632. static int unixFullPathname(
  29633. sqlite3_vfs *pVfs, /* Pointer to vfs object */
  29634. const char *zPath, /* Possibly relative input path */
  29635. int nOut, /* Size of output buffer in bytes */
  29636. char *zOut /* Output buffer */
  29637. ){
  29638. /* It's odd to simulate an io-error here, but really this is just
  29639. ** using the io-error infrastructure to test that SQLite handles this
  29640. ** function failing. This function could fail if, for example, the
  29641. ** current working directory has been unlinked.
  29642. */
  29643. SimulateIOError( return SQLITE_ERROR );
  29644. assert( pVfs->mxPathname==MAX_PATHNAME );
  29645. UNUSED_PARAMETER(pVfs);
  29646. zOut[nOut-1] = '\0';
  29647. if( zPath[0]=='/' ){
  29648. sqlite3_snprintf(nOut, zOut, "%s", zPath);
  29649. }else{
  29650. int nCwd;
  29651. if( osGetcwd(zOut, nOut-1)==0 ){
  29652. return unixLogError(SQLITE_CANTOPEN_BKPT, "getcwd", zPath);
  29653. }
  29654. nCwd = (int)strlen(zOut);
  29655. sqlite3_snprintf(nOut-nCwd, &zOut[nCwd], "/%s", zPath);
  29656. }
  29657. return SQLITE_OK;
  29658. }
  29659. #ifndef SQLITE_OMIT_LOAD_EXTENSION
  29660. /*
  29661. ** Interfaces for opening a shared library, finding entry points
  29662. ** within the shared library, and closing the shared library.
  29663. */
  29664. #include <dlfcn.h>
  29665. static void *unixDlOpen(sqlite3_vfs *NotUsed, const char *zFilename){
  29666. UNUSED_PARAMETER(NotUsed);
  29667. return dlopen(zFilename, RTLD_NOW | RTLD_GLOBAL);
  29668. }
  29669. /*
  29670. ** SQLite calls this function immediately after a call to unixDlSym() or
  29671. ** unixDlOpen() fails (returns a null pointer). If a more detailed error
  29672. ** message is available, it is written to zBufOut. If no error message
  29673. ** is available, zBufOut is left unmodified and SQLite uses a default
  29674. ** error message.
  29675. */
  29676. static void unixDlError(sqlite3_vfs *NotUsed, int nBuf, char *zBufOut){
  29677. const char *zErr;
  29678. UNUSED_PARAMETER(NotUsed);
  29679. unixEnterMutex();
  29680. zErr = dlerror();
  29681. if( zErr ){
  29682. sqlite3_snprintf(nBuf, zBufOut, "%s", zErr);
  29683. }
  29684. unixLeaveMutex();
  29685. }
  29686. static void (*unixDlSym(sqlite3_vfs *NotUsed, void *p, const char*zSym))(void){
  29687. /*
  29688. ** GCC with -pedantic-errors says that C90 does not allow a void* to be
  29689. ** cast into a pointer to a function. And yet the library dlsym() routine
  29690. ** returns a void* which is really a pointer to a function. So how do we
  29691. ** use dlsym() with -pedantic-errors?
  29692. **
  29693. ** Variable x below is defined to be a pointer to a function taking
  29694. ** parameters void* and const char* and returning a pointer to a function.
  29695. ** We initialize x by assigning it a pointer to the dlsym() function.
  29696. ** (That assignment requires a cast.) Then we call the function that
  29697. ** x points to.
  29698. **
  29699. ** This work-around is unlikely to work correctly on any system where
  29700. ** you really cannot cast a function pointer into void*. But then, on the
  29701. ** other hand, dlsym() will not work on such a system either, so we have
  29702. ** not really lost anything.
  29703. */
  29704. void (*(*x)(void*,const char*))(void);
  29705. UNUSED_PARAMETER(NotUsed);
  29706. x = (void(*(*)(void*,const char*))(void))dlsym;
  29707. return (*x)(p, zSym);
  29708. }
  29709. static void unixDlClose(sqlite3_vfs *NotUsed, void *pHandle){
  29710. UNUSED_PARAMETER(NotUsed);
  29711. dlclose(pHandle);
  29712. }
  29713. #else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
  29714. #define unixDlOpen 0
  29715. #define unixDlError 0
  29716. #define unixDlSym 0
  29717. #define unixDlClose 0
  29718. #endif
  29719. /*
  29720. ** Write nBuf bytes of random data to the supplied buffer zBuf.
  29721. */
  29722. static int unixRandomness(sqlite3_vfs *NotUsed, int nBuf, char *zBuf){
  29723. UNUSED_PARAMETER(NotUsed);
  29724. assert((size_t)nBuf>=(sizeof(time_t)+sizeof(int)));
  29725. /* We have to initialize zBuf to prevent valgrind from reporting
  29726. ** errors. The reports issued by valgrind are incorrect - we would
  29727. ** prefer that the randomness be increased by making use of the
  29728. ** uninitialized space in zBuf - but valgrind errors tend to worry
  29729. ** some users. Rather than argue, it seems easier just to initialize
  29730. ** the whole array and silence valgrind, even if that means less randomness
  29731. ** in the random seed.
  29732. **
  29733. ** When testing, initializing zBuf[] to zero is all we do. That means
  29734. ** that we always use the same random number sequence. This makes the
  29735. ** tests repeatable.
  29736. */
  29737. memset(zBuf, 0, nBuf);
  29738. randomnessPid = osGetpid(0);
  29739. #if !defined(SQLITE_TEST) && !defined(SQLITE_OMIT_RANDOMNESS)
  29740. {
  29741. int fd, got;
  29742. fd = robust_open("/dev/urandom", O_RDONLY, 0);
  29743. if( fd<0 ){
  29744. time_t t;
  29745. time(&t);
  29746. memcpy(zBuf, &t, sizeof(t));
  29747. memcpy(&zBuf[sizeof(t)], &randomnessPid, sizeof(randomnessPid));
  29748. assert( sizeof(t)+sizeof(randomnessPid)<=(size_t)nBuf );
  29749. nBuf = sizeof(t) + sizeof(randomnessPid);
  29750. }else{
  29751. do{ got = osRead(fd, zBuf, nBuf); }while( got<0 && errno==EINTR );
  29752. robust_close(0, fd, __LINE__);
  29753. }
  29754. }
  29755. #endif
  29756. return nBuf;
  29757. }
  29758. /*
  29759. ** Sleep for a little while. Return the amount of time slept.
  29760. ** The argument is the number of microseconds we want to sleep.
  29761. ** The return value is the number of microseconds of sleep actually
  29762. ** requested from the underlying operating system, a number which
  29763. ** might be greater than or equal to the argument, but not less
  29764. ** than the argument.
  29765. */
  29766. static int unixSleep(sqlite3_vfs *NotUsed, int microseconds){
  29767. #if OS_VXWORKS
  29768. struct timespec sp;
  29769. sp.tv_sec = microseconds / 1000000;
  29770. sp.tv_nsec = (microseconds % 1000000) * 1000;
  29771. nanosleep(&sp, NULL);
  29772. UNUSED_PARAMETER(NotUsed);
  29773. return microseconds;
  29774. #elif defined(HAVE_USLEEP) && HAVE_USLEEP
  29775. usleep(microseconds);
  29776. UNUSED_PARAMETER(NotUsed);
  29777. return microseconds;
  29778. #else
  29779. int seconds = (microseconds+999999)/1000000;
  29780. sleep(seconds);
  29781. UNUSED_PARAMETER(NotUsed);
  29782. return seconds*1000000;
  29783. #endif
  29784. }
  29785. /*
  29786. ** The following variable, if set to a non-zero value, is interpreted as
  29787. ** the number of seconds since 1970 and is used to set the result of
  29788. ** sqlite3OsCurrentTime() during testing.
  29789. */
  29790. #ifdef SQLITE_TEST
  29791. SQLITE_API int sqlite3_current_time = 0; /* Fake system time in seconds since 1970. */
  29792. #endif
  29793. /*
  29794. ** Find the current time (in Universal Coordinated Time). Write into *piNow
  29795. ** the current time and date as a Julian Day number times 86_400_000. In
  29796. ** other words, write into *piNow the number of milliseconds since the Julian
  29797. ** epoch of noon in Greenwich on November 24, 4714 B.C according to the
  29798. ** proleptic Gregorian calendar.
  29799. **
  29800. ** On success, return SQLITE_OK. Return SQLITE_ERROR if the time and date
  29801. ** cannot be found.
  29802. */
  29803. static int unixCurrentTimeInt64(sqlite3_vfs *NotUsed, sqlite3_int64 *piNow){
  29804. static const sqlite3_int64 unixEpoch = 24405875*(sqlite3_int64)8640000;
  29805. int rc = SQLITE_OK;
  29806. #if defined(NO_GETTOD)
  29807. time_t t;
  29808. time(&t);
  29809. *piNow = ((sqlite3_int64)t)*1000 + unixEpoch;
  29810. #elif OS_VXWORKS
  29811. struct timespec sNow;
  29812. clock_gettime(CLOCK_REALTIME, &sNow);
  29813. *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_nsec/1000000;
  29814. #else
  29815. struct timeval sNow;
  29816. if( gettimeofday(&sNow, 0)==0 ){
  29817. *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_usec/1000;
  29818. }else{
  29819. rc = SQLITE_ERROR;
  29820. }
  29821. #endif
  29822. #ifdef SQLITE_TEST
  29823. if( sqlite3_current_time ){
  29824. *piNow = 1000*(sqlite3_int64)sqlite3_current_time + unixEpoch;
  29825. }
  29826. #endif
  29827. UNUSED_PARAMETER(NotUsed);
  29828. return rc;
  29829. }
  29830. /*
  29831. ** Find the current time (in Universal Coordinated Time). Write the
  29832. ** current time and date as a Julian Day number into *prNow and
  29833. ** return 0. Return 1 if the time and date cannot be found.
  29834. */
  29835. static int unixCurrentTime(sqlite3_vfs *NotUsed, double *prNow){
  29836. sqlite3_int64 i = 0;
  29837. int rc;
  29838. UNUSED_PARAMETER(NotUsed);
  29839. rc = unixCurrentTimeInt64(0, &i);
  29840. *prNow = i/86400000.0;
  29841. return rc;
  29842. }
  29843. /*
  29844. ** We added the xGetLastError() method with the intention of providing
  29845. ** better low-level error messages when operating-system problems come up
  29846. ** during SQLite operation. But so far, none of that has been implemented
  29847. ** in the core. So this routine is never called. For now, it is merely
  29848. ** a place-holder.
  29849. */
  29850. static int unixGetLastError(sqlite3_vfs *NotUsed, int NotUsed2, char *NotUsed3){
  29851. UNUSED_PARAMETER(NotUsed);
  29852. UNUSED_PARAMETER(NotUsed2);
  29853. UNUSED_PARAMETER(NotUsed3);
  29854. return 0;
  29855. }
  29856. /*
  29857. ************************ End of sqlite3_vfs methods ***************************
  29858. ******************************************************************************/
  29859. /******************************************************************************
  29860. ************************** Begin Proxy Locking ********************************
  29861. **
  29862. ** Proxy locking is a "uber-locking-method" in this sense: It uses the
  29863. ** other locking methods on secondary lock files. Proxy locking is a
  29864. ** meta-layer over top of the primitive locking implemented above. For
  29865. ** this reason, the division that implements of proxy locking is deferred
  29866. ** until late in the file (here) after all of the other I/O methods have
  29867. ** been defined - so that the primitive locking methods are available
  29868. ** as services to help with the implementation of proxy locking.
  29869. **
  29870. ****
  29871. **
  29872. ** The default locking schemes in SQLite use byte-range locks on the
  29873. ** database file to coordinate safe, concurrent access by multiple readers
  29874. ** and writers [http://sqlite.org/lockingv3.html]. The five file locking
  29875. ** states (UNLOCKED, PENDING, SHARED, RESERVED, EXCLUSIVE) are implemented
  29876. ** as POSIX read & write locks over fixed set of locations (via fsctl),
  29877. ** on AFP and SMB only exclusive byte-range locks are available via fsctl
  29878. ** with _IOWR('z', 23, struct ByteRangeLockPB2) to track the same 5 states.
  29879. ** To simulate a F_RDLCK on the shared range, on AFP a randomly selected
  29880. ** address in the shared range is taken for a SHARED lock, the entire
  29881. ** shared range is taken for an EXCLUSIVE lock):
  29882. **
  29883. ** PENDING_BYTE 0x40000000
  29884. ** RESERVED_BYTE 0x40000001
  29885. ** SHARED_RANGE 0x40000002 -> 0x40000200
  29886. **
  29887. ** This works well on the local file system, but shows a nearly 100x
  29888. ** slowdown in read performance on AFP because the AFP client disables
  29889. ** the read cache when byte-range locks are present. Enabling the read
  29890. ** cache exposes a cache coherency problem that is present on all OS X
  29891. ** supported network file systems. NFS and AFP both observe the
  29892. ** close-to-open semantics for ensuring cache coherency
  29893. ** [http://nfs.sourceforge.net/#faq_a8], which does not effectively
  29894. ** address the requirements for concurrent database access by multiple
  29895. ** readers and writers
  29896. ** [http://www.nabble.com/SQLite-on-NFS-cache-coherency-td15655701.html].
  29897. **
  29898. ** To address the performance and cache coherency issues, proxy file locking
  29899. ** changes the way database access is controlled by limiting access to a
  29900. ** single host at a time and moving file locks off of the database file
  29901. ** and onto a proxy file on the local file system.
  29902. **
  29903. **
  29904. ** Using proxy locks
  29905. ** -----------------
  29906. **
  29907. ** C APIs
  29908. **
  29909. ** sqlite3_file_control(db, dbname, SQLITE_FCNTL_SET_LOCKPROXYFILE,
  29910. ** <proxy_path> | ":auto:");
  29911. ** sqlite3_file_control(db, dbname, SQLITE_FCNTL_GET_LOCKPROXYFILE,
  29912. ** &<proxy_path>);
  29913. **
  29914. **
  29915. ** SQL pragmas
  29916. **
  29917. ** PRAGMA [database.]lock_proxy_file=<proxy_path> | :auto:
  29918. ** PRAGMA [database.]lock_proxy_file
  29919. **
  29920. ** Specifying ":auto:" means that if there is a conch file with a matching
  29921. ** host ID in it, the proxy path in the conch file will be used, otherwise
  29922. ** a proxy path based on the user's temp dir
  29923. ** (via confstr(_CS_DARWIN_USER_TEMP_DIR,...)) will be used and the
  29924. ** actual proxy file name is generated from the name and path of the
  29925. ** database file. For example:
  29926. **
  29927. ** For database path "/Users/me/foo.db"
  29928. ** The lock path will be "<tmpdir>/sqliteplocks/_Users_me_foo.db:auto:")
  29929. **
  29930. ** Once a lock proxy is configured for a database connection, it can not
  29931. ** be removed, however it may be switched to a different proxy path via
  29932. ** the above APIs (assuming the conch file is not being held by another
  29933. ** connection or process).
  29934. **
  29935. **
  29936. ** How proxy locking works
  29937. ** -----------------------
  29938. **
  29939. ** Proxy file locking relies primarily on two new supporting files:
  29940. **
  29941. ** * conch file to limit access to the database file to a single host
  29942. ** at a time
  29943. **
  29944. ** * proxy file to act as a proxy for the advisory locks normally
  29945. ** taken on the database
  29946. **
  29947. ** The conch file - to use a proxy file, sqlite must first "hold the conch"
  29948. ** by taking an sqlite-style shared lock on the conch file, reading the
  29949. ** contents and comparing the host's unique host ID (see below) and lock
  29950. ** proxy path against the values stored in the conch. The conch file is
  29951. ** stored in the same directory as the database file and the file name
  29952. ** is patterned after the database file name as ".<databasename>-conch".
  29953. ** If the conch file does not exist, or its contents do not match the
  29954. ** host ID and/or proxy path, then the lock is escalated to an exclusive
  29955. ** lock and the conch file contents is updated with the host ID and proxy
  29956. ** path and the lock is downgraded to a shared lock again. If the conch
  29957. ** is held by another process (with a shared lock), the exclusive lock
  29958. ** will fail and SQLITE_BUSY is returned.
  29959. **
  29960. ** The proxy file - a single-byte file used for all advisory file locks
  29961. ** normally taken on the database file. This allows for safe sharing
  29962. ** of the database file for multiple readers and writers on the same
  29963. ** host (the conch ensures that they all use the same local lock file).
  29964. **
  29965. ** Requesting the lock proxy does not immediately take the conch, it is
  29966. ** only taken when the first request to lock database file is made.
  29967. ** This matches the semantics of the traditional locking behavior, where
  29968. ** opening a connection to a database file does not take a lock on it.
  29969. ** The shared lock and an open file descriptor are maintained until
  29970. ** the connection to the database is closed.
  29971. **
  29972. ** The proxy file and the lock file are never deleted so they only need
  29973. ** to be created the first time they are used.
  29974. **
  29975. ** Configuration options
  29976. ** ---------------------
  29977. **
  29978. ** SQLITE_PREFER_PROXY_LOCKING
  29979. **
  29980. ** Database files accessed on non-local file systems are
  29981. ** automatically configured for proxy locking, lock files are
  29982. ** named automatically using the same logic as
  29983. ** PRAGMA lock_proxy_file=":auto:"
  29984. **
  29985. ** SQLITE_PROXY_DEBUG
  29986. **
  29987. ** Enables the logging of error messages during host id file
  29988. ** retrieval and creation
  29989. **
  29990. ** LOCKPROXYDIR
  29991. **
  29992. ** Overrides the default directory used for lock proxy files that
  29993. ** are named automatically via the ":auto:" setting
  29994. **
  29995. ** SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
  29996. **
  29997. ** Permissions to use when creating a directory for storing the
  29998. ** lock proxy files, only used when LOCKPROXYDIR is not set.
  29999. **
  30000. **
  30001. ** As mentioned above, when compiled with SQLITE_PREFER_PROXY_LOCKING,
  30002. ** setting the environment variable SQLITE_FORCE_PROXY_LOCKING to 1 will
  30003. ** force proxy locking to be used for every database file opened, and 0
  30004. ** will force automatic proxy locking to be disabled for all database
  30005. ** files (explicitly calling the SQLITE_FCNTL_SET_LOCKPROXYFILE pragma or
  30006. ** sqlite_file_control API is not affected by SQLITE_FORCE_PROXY_LOCKING).
  30007. */
  30008. /*
  30009. ** Proxy locking is only available on MacOSX
  30010. */
  30011. #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
  30012. /*
  30013. ** The proxyLockingContext has the path and file structures for the remote
  30014. ** and local proxy files in it
  30015. */
  30016. typedef struct proxyLockingContext proxyLockingContext;
  30017. struct proxyLockingContext {
  30018. unixFile *conchFile; /* Open conch file */
  30019. char *conchFilePath; /* Name of the conch file */
  30020. unixFile *lockProxy; /* Open proxy lock file */
  30021. char *lockProxyPath; /* Name of the proxy lock file */
  30022. char *dbPath; /* Name of the open file */
  30023. int conchHeld; /* 1 if the conch is held, -1 if lockless */
  30024. int nFails; /* Number of conch taking failures */
  30025. void *oldLockingContext; /* Original lockingcontext to restore on close */
  30026. sqlite3_io_methods const *pOldMethod; /* Original I/O methods for close */
  30027. };
  30028. /*
  30029. ** The proxy lock file path for the database at dbPath is written into lPath,
  30030. ** which must point to valid, writable memory large enough for a maxLen length
  30031. ** file path.
  30032. */
  30033. static int proxyGetLockPath(const char *dbPath, char *lPath, size_t maxLen){
  30034. int len;
  30035. int dbLen;
  30036. int i;
  30037. #ifdef LOCKPROXYDIR
  30038. len = strlcpy(lPath, LOCKPROXYDIR, maxLen);
  30039. #else
  30040. # ifdef _CS_DARWIN_USER_TEMP_DIR
  30041. {
  30042. if( !confstr(_CS_DARWIN_USER_TEMP_DIR, lPath, maxLen) ){
  30043. OSTRACE(("GETLOCKPATH failed %s errno=%d pid=%d\n",
  30044. lPath, errno, osGetpid(0)));
  30045. return SQLITE_IOERR_LOCK;
  30046. }
  30047. len = strlcat(lPath, "sqliteplocks", maxLen);
  30048. }
  30049. # else
  30050. len = strlcpy(lPath, "/tmp/", maxLen);
  30051. # endif
  30052. #endif
  30053. if( lPath[len-1]!='/' ){
  30054. len = strlcat(lPath, "/", maxLen);
  30055. }
  30056. /* transform the db path to a unique cache name */
  30057. dbLen = (int)strlen(dbPath);
  30058. for( i=0; i<dbLen && (i+len+7)<(int)maxLen; i++){
  30059. char c = dbPath[i];
  30060. lPath[i+len] = (c=='/')?'_':c;
  30061. }
  30062. lPath[i+len]='\0';
  30063. strlcat(lPath, ":auto:", maxLen);
  30064. OSTRACE(("GETLOCKPATH proxy lock path=%s pid=%d\n", lPath, osGetpid(0)));
  30065. return SQLITE_OK;
  30066. }
  30067. /*
  30068. ** Creates the lock file and any missing directories in lockPath
  30069. */
  30070. static int proxyCreateLockPath(const char *lockPath){
  30071. int i, len;
  30072. char buf[MAXPATHLEN];
  30073. int start = 0;
  30074. assert(lockPath!=NULL);
  30075. /* try to create all the intermediate directories */
  30076. len = (int)strlen(lockPath);
  30077. buf[0] = lockPath[0];
  30078. for( i=1; i<len; i++ ){
  30079. if( lockPath[i] == '/' && (i - start > 0) ){
  30080. /* only mkdir if leaf dir != "." or "/" or ".." */
  30081. if( i-start>2 || (i-start==1 && buf[start] != '.' && buf[start] != '/')
  30082. || (i-start==2 && buf[start] != '.' && buf[start+1] != '.') ){
  30083. buf[i]='\0';
  30084. if( osMkdir(buf, SQLITE_DEFAULT_PROXYDIR_PERMISSIONS) ){
  30085. int err=errno;
  30086. if( err!=EEXIST ) {
  30087. OSTRACE(("CREATELOCKPATH FAILED creating %s, "
  30088. "'%s' proxy lock path=%s pid=%d\n",
  30089. buf, strerror(err), lockPath, osGetpid(0)));
  30090. return err;
  30091. }
  30092. }
  30093. }
  30094. start=i+1;
  30095. }
  30096. buf[i] = lockPath[i];
  30097. }
  30098. OSTRACE(("CREATELOCKPATH proxy lock path=%s pid=%d\n", lockPath, osGetpid(0)));
  30099. return 0;
  30100. }
  30101. /*
  30102. ** Create a new VFS file descriptor (stored in memory obtained from
  30103. ** sqlite3_malloc) and open the file named "path" in the file descriptor.
  30104. **
  30105. ** The caller is responsible not only for closing the file descriptor
  30106. ** but also for freeing the memory associated with the file descriptor.
  30107. */
  30108. static int proxyCreateUnixFile(
  30109. const char *path, /* path for the new unixFile */
  30110. unixFile **ppFile, /* unixFile created and returned by ref */
  30111. int islockfile /* if non zero missing dirs will be created */
  30112. ) {
  30113. int fd = -1;
  30114. unixFile *pNew;
  30115. int rc = SQLITE_OK;
  30116. int openFlags = O_RDWR | O_CREAT;
  30117. sqlite3_vfs dummyVfs;
  30118. int terrno = 0;
  30119. UnixUnusedFd *pUnused = NULL;
  30120. /* 1. first try to open/create the file
  30121. ** 2. if that fails, and this is a lock file (not-conch), try creating
  30122. ** the parent directories and then try again.
  30123. ** 3. if that fails, try to open the file read-only
  30124. ** otherwise return BUSY (if lock file) or CANTOPEN for the conch file
  30125. */
  30126. pUnused = findReusableFd(path, openFlags);
  30127. if( pUnused ){
  30128. fd = pUnused->fd;
  30129. }else{
  30130. pUnused = sqlite3_malloc64(sizeof(*pUnused));
  30131. if( !pUnused ){
  30132. return SQLITE_NOMEM;
  30133. }
  30134. }
  30135. if( fd<0 ){
  30136. fd = robust_open(path, openFlags, 0);
  30137. terrno = errno;
  30138. if( fd<0 && errno==ENOENT && islockfile ){
  30139. if( proxyCreateLockPath(path) == SQLITE_OK ){
  30140. fd = robust_open(path, openFlags, 0);
  30141. }
  30142. }
  30143. }
  30144. if( fd<0 ){
  30145. openFlags = O_RDONLY;
  30146. fd = robust_open(path, openFlags, 0);
  30147. terrno = errno;
  30148. }
  30149. if( fd<0 ){
  30150. if( islockfile ){
  30151. return SQLITE_BUSY;
  30152. }
  30153. switch (terrno) {
  30154. case EACCES:
  30155. return SQLITE_PERM;
  30156. case EIO:
  30157. return SQLITE_IOERR_LOCK; /* even though it is the conch */
  30158. default:
  30159. return SQLITE_CANTOPEN_BKPT;
  30160. }
  30161. }
  30162. pNew = (unixFile *)sqlite3_malloc64(sizeof(*pNew));
  30163. if( pNew==NULL ){
  30164. rc = SQLITE_NOMEM;
  30165. goto end_create_proxy;
  30166. }
  30167. memset(pNew, 0, sizeof(unixFile));
  30168. pNew->openFlags = openFlags;
  30169. memset(&dummyVfs, 0, sizeof(dummyVfs));
  30170. dummyVfs.pAppData = (void*)&autolockIoFinder;
  30171. dummyVfs.zName = "dummy";
  30172. pUnused->fd = fd;
  30173. pUnused->flags = openFlags;
  30174. pNew->pUnused = pUnused;
  30175. rc = fillInUnixFile(&dummyVfs, fd, (sqlite3_file*)pNew, path, 0);
  30176. if( rc==SQLITE_OK ){
  30177. *ppFile = pNew;
  30178. return SQLITE_OK;
  30179. }
  30180. end_create_proxy:
  30181. robust_close(pNew, fd, __LINE__);
  30182. sqlite3_free(pNew);
  30183. sqlite3_free(pUnused);
  30184. return rc;
  30185. }
  30186. #ifdef SQLITE_TEST
  30187. /* simulate multiple hosts by creating unique hostid file paths */
  30188. SQLITE_API int sqlite3_hostid_num = 0;
  30189. #endif
  30190. #define PROXY_HOSTIDLEN 16 /* conch file host id length */
  30191. #ifdef HAVE_GETHOSTUUID
  30192. /* Not always defined in the headers as it ought to be */
  30193. extern int gethostuuid(uuid_t id, const struct timespec *wait);
  30194. #endif
  30195. /* get the host ID via gethostuuid(), pHostID must point to PROXY_HOSTIDLEN
  30196. ** bytes of writable memory.
  30197. */
  30198. static int proxyGetHostID(unsigned char *pHostID, int *pError){
  30199. assert(PROXY_HOSTIDLEN == sizeof(uuid_t));
  30200. memset(pHostID, 0, PROXY_HOSTIDLEN);
  30201. #ifdef HAVE_GETHOSTUUID
  30202. {
  30203. struct timespec timeout = {1, 0}; /* 1 sec timeout */
  30204. if( gethostuuid(pHostID, &timeout) ){
  30205. int err = errno;
  30206. if( pError ){
  30207. *pError = err;
  30208. }
  30209. return SQLITE_IOERR;
  30210. }
  30211. }
  30212. #else
  30213. UNUSED_PARAMETER(pError);
  30214. #endif
  30215. #ifdef SQLITE_TEST
  30216. /* simulate multiple hosts by creating unique hostid file paths */
  30217. if( sqlite3_hostid_num != 0){
  30218. pHostID[0] = (char)(pHostID[0] + (char)(sqlite3_hostid_num & 0xFF));
  30219. }
  30220. #endif
  30221. return SQLITE_OK;
  30222. }
  30223. /* The conch file contains the header, host id and lock file path
  30224. */
  30225. #define PROXY_CONCHVERSION 2 /* 1-byte header, 16-byte host id, path */
  30226. #define PROXY_HEADERLEN 1 /* conch file header length */
  30227. #define PROXY_PATHINDEX (PROXY_HEADERLEN+PROXY_HOSTIDLEN)
  30228. #define PROXY_MAXCONCHLEN (PROXY_HEADERLEN+PROXY_HOSTIDLEN+MAXPATHLEN)
  30229. /*
  30230. ** Takes an open conch file, copies the contents to a new path and then moves
  30231. ** it back. The newly created file's file descriptor is assigned to the
  30232. ** conch file structure and finally the original conch file descriptor is
  30233. ** closed. Returns zero if successful.
  30234. */
  30235. static int proxyBreakConchLock(unixFile *pFile, uuid_t myHostID){
  30236. proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
  30237. unixFile *conchFile = pCtx->conchFile;
  30238. char tPath[MAXPATHLEN];
  30239. char buf[PROXY_MAXCONCHLEN];
  30240. char *cPath = pCtx->conchFilePath;
  30241. size_t readLen = 0;
  30242. size_t pathLen = 0;
  30243. char errmsg[64] = "";
  30244. int fd = -1;
  30245. int rc = -1;
  30246. UNUSED_PARAMETER(myHostID);
  30247. /* create a new path by replace the trailing '-conch' with '-break' */
  30248. pathLen = strlcpy(tPath, cPath, MAXPATHLEN);
  30249. if( pathLen>MAXPATHLEN || pathLen<6 ||
  30250. (strlcpy(&tPath[pathLen-5], "break", 6) != 5) ){
  30251. sqlite3_snprintf(sizeof(errmsg),errmsg,"path error (len %d)",(int)pathLen);
  30252. goto end_breaklock;
  30253. }
  30254. /* read the conch content */
  30255. readLen = osPread(conchFile->h, buf, PROXY_MAXCONCHLEN, 0);
  30256. if( readLen<PROXY_PATHINDEX ){
  30257. sqlite3_snprintf(sizeof(errmsg),errmsg,"read error (len %d)",(int)readLen);
  30258. goto end_breaklock;
  30259. }
  30260. /* write it out to the temporary break file */
  30261. fd = robust_open(tPath, (O_RDWR|O_CREAT|O_EXCL), 0);
  30262. if( fd<0 ){
  30263. sqlite3_snprintf(sizeof(errmsg), errmsg, "create failed (%d)", errno);
  30264. goto end_breaklock;
  30265. }
  30266. if( osPwrite(fd, buf, readLen, 0) != (ssize_t)readLen ){
  30267. sqlite3_snprintf(sizeof(errmsg), errmsg, "write failed (%d)", errno);
  30268. goto end_breaklock;
  30269. }
  30270. if( rename(tPath, cPath) ){
  30271. sqlite3_snprintf(sizeof(errmsg), errmsg, "rename failed (%d)", errno);
  30272. goto end_breaklock;
  30273. }
  30274. rc = 0;
  30275. fprintf(stderr, "broke stale lock on %s\n", cPath);
  30276. robust_close(pFile, conchFile->h, __LINE__);
  30277. conchFile->h = fd;
  30278. conchFile->openFlags = O_RDWR | O_CREAT;
  30279. end_breaklock:
  30280. if( rc ){
  30281. if( fd>=0 ){
  30282. osUnlink(tPath);
  30283. robust_close(pFile, fd, __LINE__);
  30284. }
  30285. fprintf(stderr, "failed to break stale lock on %s, %s\n", cPath, errmsg);
  30286. }
  30287. return rc;
  30288. }
  30289. /* Take the requested lock on the conch file and break a stale lock if the
  30290. ** host id matches.
  30291. */
  30292. static int proxyConchLock(unixFile *pFile, uuid_t myHostID, int lockType){
  30293. proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
  30294. unixFile *conchFile = pCtx->conchFile;
  30295. int rc = SQLITE_OK;
  30296. int nTries = 0;
  30297. struct timespec conchModTime;
  30298. memset(&conchModTime, 0, sizeof(conchModTime));
  30299. do {
  30300. rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
  30301. nTries ++;
  30302. if( rc==SQLITE_BUSY ){
  30303. /* If the lock failed (busy):
  30304. * 1st try: get the mod time of the conch, wait 0.5s and try again.
  30305. * 2nd try: fail if the mod time changed or host id is different, wait
  30306. * 10 sec and try again
  30307. * 3rd try: break the lock unless the mod time has changed.
  30308. */
  30309. struct stat buf;
  30310. if( osFstat(conchFile->h, &buf) ){
  30311. storeLastErrno(pFile, errno);
  30312. return SQLITE_IOERR_LOCK;
  30313. }
  30314. if( nTries==1 ){
  30315. conchModTime = buf.st_mtimespec;
  30316. usleep(500000); /* wait 0.5 sec and try the lock again*/
  30317. continue;
  30318. }
  30319. assert( nTries>1 );
  30320. if( conchModTime.tv_sec != buf.st_mtimespec.tv_sec ||
  30321. conchModTime.tv_nsec != buf.st_mtimespec.tv_nsec ){
  30322. return SQLITE_BUSY;
  30323. }
  30324. if( nTries==2 ){
  30325. char tBuf[PROXY_MAXCONCHLEN];
  30326. int len = osPread(conchFile->h, tBuf, PROXY_MAXCONCHLEN, 0);
  30327. if( len<0 ){
  30328. storeLastErrno(pFile, errno);
  30329. return SQLITE_IOERR_LOCK;
  30330. }
  30331. if( len>PROXY_PATHINDEX && tBuf[0]==(char)PROXY_CONCHVERSION){
  30332. /* don't break the lock if the host id doesn't match */
  30333. if( 0!=memcmp(&tBuf[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN) ){
  30334. return SQLITE_BUSY;
  30335. }
  30336. }else{
  30337. /* don't break the lock on short read or a version mismatch */
  30338. return SQLITE_BUSY;
  30339. }
  30340. usleep(10000000); /* wait 10 sec and try the lock again */
  30341. continue;
  30342. }
  30343. assert( nTries==3 );
  30344. if( 0==proxyBreakConchLock(pFile, myHostID) ){
  30345. rc = SQLITE_OK;
  30346. if( lockType==EXCLUSIVE_LOCK ){
  30347. rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, SHARED_LOCK);
  30348. }
  30349. if( !rc ){
  30350. rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
  30351. }
  30352. }
  30353. }
  30354. } while( rc==SQLITE_BUSY && nTries<3 );
  30355. return rc;
  30356. }
  30357. /* Takes the conch by taking a shared lock and read the contents conch, if
  30358. ** lockPath is non-NULL, the host ID and lock file path must match. A NULL
  30359. ** lockPath means that the lockPath in the conch file will be used if the
  30360. ** host IDs match, or a new lock path will be generated automatically
  30361. ** and written to the conch file.
  30362. */
  30363. static int proxyTakeConch(unixFile *pFile){
  30364. proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
  30365. if( pCtx->conchHeld!=0 ){
  30366. return SQLITE_OK;
  30367. }else{
  30368. unixFile *conchFile = pCtx->conchFile;
  30369. uuid_t myHostID;
  30370. int pError = 0;
  30371. char readBuf[PROXY_MAXCONCHLEN];
  30372. char lockPath[MAXPATHLEN];
  30373. char *tempLockPath = NULL;
  30374. int rc = SQLITE_OK;
  30375. int createConch = 0;
  30376. int hostIdMatch = 0;
  30377. int readLen = 0;
  30378. int tryOldLockPath = 0;
  30379. int forceNewLockPath = 0;
  30380. OSTRACE(("TAKECONCH %d for %s pid=%d\n", conchFile->h,
  30381. (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"),
  30382. osGetpid(0)));
  30383. rc = proxyGetHostID(myHostID, &pError);
  30384. if( (rc&0xff)==SQLITE_IOERR ){
  30385. storeLastErrno(pFile, pError);
  30386. goto end_takeconch;
  30387. }
  30388. rc = proxyConchLock(pFile, myHostID, SHARED_LOCK);
  30389. if( rc!=SQLITE_OK ){
  30390. goto end_takeconch;
  30391. }
  30392. /* read the existing conch file */
  30393. readLen = seekAndRead((unixFile*)conchFile, 0, readBuf, PROXY_MAXCONCHLEN);
  30394. if( readLen<0 ){
  30395. /* I/O error: lastErrno set by seekAndRead */
  30396. storeLastErrno(pFile, conchFile->lastErrno);
  30397. rc = SQLITE_IOERR_READ;
  30398. goto end_takeconch;
  30399. }else if( readLen<=(PROXY_HEADERLEN+PROXY_HOSTIDLEN) ||
  30400. readBuf[0]!=(char)PROXY_CONCHVERSION ){
  30401. /* a short read or version format mismatch means we need to create a new
  30402. ** conch file.
  30403. */
  30404. createConch = 1;
  30405. }
  30406. /* if the host id matches and the lock path already exists in the conch
  30407. ** we'll try to use the path there, if we can't open that path, we'll
  30408. ** retry with a new auto-generated path
  30409. */
  30410. do { /* in case we need to try again for an :auto: named lock file */
  30411. if( !createConch && !forceNewLockPath ){
  30412. hostIdMatch = !memcmp(&readBuf[PROXY_HEADERLEN], myHostID,
  30413. PROXY_HOSTIDLEN);
  30414. /* if the conch has data compare the contents */
  30415. if( !pCtx->lockProxyPath ){
  30416. /* for auto-named local lock file, just check the host ID and we'll
  30417. ** use the local lock file path that's already in there
  30418. */
  30419. if( hostIdMatch ){
  30420. size_t pathLen = (readLen - PROXY_PATHINDEX);
  30421. if( pathLen>=MAXPATHLEN ){
  30422. pathLen=MAXPATHLEN-1;
  30423. }
  30424. memcpy(lockPath, &readBuf[PROXY_PATHINDEX], pathLen);
  30425. lockPath[pathLen] = 0;
  30426. tempLockPath = lockPath;
  30427. tryOldLockPath = 1;
  30428. /* create a copy of the lock path if the conch is taken */
  30429. goto end_takeconch;
  30430. }
  30431. }else if( hostIdMatch
  30432. && !strncmp(pCtx->lockProxyPath, &readBuf[PROXY_PATHINDEX],
  30433. readLen-PROXY_PATHINDEX)
  30434. ){
  30435. /* conch host and lock path match */
  30436. goto end_takeconch;
  30437. }
  30438. }
  30439. /* if the conch isn't writable and doesn't match, we can't take it */
  30440. if( (conchFile->openFlags&O_RDWR) == 0 ){
  30441. rc = SQLITE_BUSY;
  30442. goto end_takeconch;
  30443. }
  30444. /* either the conch didn't match or we need to create a new one */
  30445. if( !pCtx->lockProxyPath ){
  30446. proxyGetLockPath(pCtx->dbPath, lockPath, MAXPATHLEN);
  30447. tempLockPath = lockPath;
  30448. /* create a copy of the lock path _only_ if the conch is taken */
  30449. }
  30450. /* update conch with host and path (this will fail if other process
  30451. ** has a shared lock already), if the host id matches, use the big
  30452. ** stick.
  30453. */
  30454. futimes(conchFile->h, NULL);
  30455. if( hostIdMatch && !createConch ){
  30456. if( conchFile->pInode && conchFile->pInode->nShared>1 ){
  30457. /* We are trying for an exclusive lock but another thread in this
  30458. ** same process is still holding a shared lock. */
  30459. rc = SQLITE_BUSY;
  30460. } else {
  30461. rc = proxyConchLock(pFile, myHostID, EXCLUSIVE_LOCK);
  30462. }
  30463. }else{
  30464. rc = proxyConchLock(pFile, myHostID, EXCLUSIVE_LOCK);
  30465. }
  30466. if( rc==SQLITE_OK ){
  30467. char writeBuffer[PROXY_MAXCONCHLEN];
  30468. int writeSize = 0;
  30469. writeBuffer[0] = (char)PROXY_CONCHVERSION;
  30470. memcpy(&writeBuffer[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN);
  30471. if( pCtx->lockProxyPath!=NULL ){
  30472. strlcpy(&writeBuffer[PROXY_PATHINDEX], pCtx->lockProxyPath,
  30473. MAXPATHLEN);
  30474. }else{
  30475. strlcpy(&writeBuffer[PROXY_PATHINDEX], tempLockPath, MAXPATHLEN);
  30476. }
  30477. writeSize = PROXY_PATHINDEX + strlen(&writeBuffer[PROXY_PATHINDEX]);
  30478. robust_ftruncate(conchFile->h, writeSize);
  30479. rc = unixWrite((sqlite3_file *)conchFile, writeBuffer, writeSize, 0);
  30480. fsync(conchFile->h);
  30481. /* If we created a new conch file (not just updated the contents of a
  30482. ** valid conch file), try to match the permissions of the database
  30483. */
  30484. if( rc==SQLITE_OK && createConch ){
  30485. struct stat buf;
  30486. int err = osFstat(pFile->h, &buf);
  30487. if( err==0 ){
  30488. mode_t cmode = buf.st_mode&(S_IRUSR|S_IWUSR | S_IRGRP|S_IWGRP |
  30489. S_IROTH|S_IWOTH);
  30490. /* try to match the database file R/W permissions, ignore failure */
  30491. #ifndef SQLITE_PROXY_DEBUG
  30492. osFchmod(conchFile->h, cmode);
  30493. #else
  30494. do{
  30495. rc = osFchmod(conchFile->h, cmode);
  30496. }while( rc==(-1) && errno==EINTR );
  30497. if( rc!=0 ){
  30498. int code = errno;
  30499. fprintf(stderr, "fchmod %o FAILED with %d %s\n",
  30500. cmode, code, strerror(code));
  30501. } else {
  30502. fprintf(stderr, "fchmod %o SUCCEDED\n",cmode);
  30503. }
  30504. }else{
  30505. int code = errno;
  30506. fprintf(stderr, "STAT FAILED[%d] with %d %s\n",
  30507. err, code, strerror(code));
  30508. #endif
  30509. }
  30510. }
  30511. }
  30512. conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, SHARED_LOCK);
  30513. end_takeconch:
  30514. OSTRACE(("TRANSPROXY: CLOSE %d\n", pFile->h));
  30515. if( rc==SQLITE_OK && pFile->openFlags ){
  30516. int fd;
  30517. if( pFile->h>=0 ){
  30518. robust_close(pFile, pFile->h, __LINE__);
  30519. }
  30520. pFile->h = -1;
  30521. fd = robust_open(pCtx->dbPath, pFile->openFlags, 0);
  30522. OSTRACE(("TRANSPROXY: OPEN %d\n", fd));
  30523. if( fd>=0 ){
  30524. pFile->h = fd;
  30525. }else{
  30526. rc=SQLITE_CANTOPEN_BKPT; /* SQLITE_BUSY? proxyTakeConch called
  30527. during locking */
  30528. }
  30529. }
  30530. if( rc==SQLITE_OK && !pCtx->lockProxy ){
  30531. char *path = tempLockPath ? tempLockPath : pCtx->lockProxyPath;
  30532. rc = proxyCreateUnixFile(path, &pCtx->lockProxy, 1);
  30533. if( rc!=SQLITE_OK && rc!=SQLITE_NOMEM && tryOldLockPath ){
  30534. /* we couldn't create the proxy lock file with the old lock file path
  30535. ** so try again via auto-naming
  30536. */
  30537. forceNewLockPath = 1;
  30538. tryOldLockPath = 0;
  30539. continue; /* go back to the do {} while start point, try again */
  30540. }
  30541. }
  30542. if( rc==SQLITE_OK ){
  30543. /* Need to make a copy of path if we extracted the value
  30544. ** from the conch file or the path was allocated on the stack
  30545. */
  30546. if( tempLockPath ){
  30547. pCtx->lockProxyPath = sqlite3DbStrDup(0, tempLockPath);
  30548. if( !pCtx->lockProxyPath ){
  30549. rc = SQLITE_NOMEM;
  30550. }
  30551. }
  30552. }
  30553. if( rc==SQLITE_OK ){
  30554. pCtx->conchHeld = 1;
  30555. if( pCtx->lockProxy->pMethod == &afpIoMethods ){
  30556. afpLockingContext *afpCtx;
  30557. afpCtx = (afpLockingContext *)pCtx->lockProxy->lockingContext;
  30558. afpCtx->dbPath = pCtx->lockProxyPath;
  30559. }
  30560. } else {
  30561. conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
  30562. }
  30563. OSTRACE(("TAKECONCH %d %s\n", conchFile->h,
  30564. rc==SQLITE_OK?"ok":"failed"));
  30565. return rc;
  30566. } while (1); /* in case we need to retry the :auto: lock file -
  30567. ** we should never get here except via the 'continue' call. */
  30568. }
  30569. }
  30570. /*
  30571. ** If pFile holds a lock on a conch file, then release that lock.
  30572. */
  30573. static int proxyReleaseConch(unixFile *pFile){
  30574. int rc = SQLITE_OK; /* Subroutine return code */
  30575. proxyLockingContext *pCtx; /* The locking context for the proxy lock */
  30576. unixFile *conchFile; /* Name of the conch file */
  30577. pCtx = (proxyLockingContext *)pFile->lockingContext;
  30578. conchFile = pCtx->conchFile;
  30579. OSTRACE(("RELEASECONCH %d for %s pid=%d\n", conchFile->h,
  30580. (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"),
  30581. osGetpid(0)));
  30582. if( pCtx->conchHeld>0 ){
  30583. rc = conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
  30584. }
  30585. pCtx->conchHeld = 0;
  30586. OSTRACE(("RELEASECONCH %d %s\n", conchFile->h,
  30587. (rc==SQLITE_OK ? "ok" : "failed")));
  30588. return rc;
  30589. }
  30590. /*
  30591. ** Given the name of a database file, compute the name of its conch file.
  30592. ** Store the conch filename in memory obtained from sqlite3_malloc64().
  30593. ** Make *pConchPath point to the new name. Return SQLITE_OK on success
  30594. ** or SQLITE_NOMEM if unable to obtain memory.
  30595. **
  30596. ** The caller is responsible for ensuring that the allocated memory
  30597. ** space is eventually freed.
  30598. **
  30599. ** *pConchPath is set to NULL if a memory allocation error occurs.
  30600. */
  30601. static int proxyCreateConchPathname(char *dbPath, char **pConchPath){
  30602. int i; /* Loop counter */
  30603. int len = (int)strlen(dbPath); /* Length of database filename - dbPath */
  30604. char *conchPath; /* buffer in which to construct conch name */
  30605. /* Allocate space for the conch filename and initialize the name to
  30606. ** the name of the original database file. */
  30607. *pConchPath = conchPath = (char *)sqlite3_malloc64(len + 8);
  30608. if( conchPath==0 ){
  30609. return SQLITE_NOMEM;
  30610. }
  30611. memcpy(conchPath, dbPath, len+1);
  30612. /* now insert a "." before the last / character */
  30613. for( i=(len-1); i>=0; i-- ){
  30614. if( conchPath[i]=='/' ){
  30615. i++;
  30616. break;
  30617. }
  30618. }
  30619. conchPath[i]='.';
  30620. while ( i<len ){
  30621. conchPath[i+1]=dbPath[i];
  30622. i++;
  30623. }
  30624. /* append the "-conch" suffix to the file */
  30625. memcpy(&conchPath[i+1], "-conch", 7);
  30626. assert( (int)strlen(conchPath) == len+7 );
  30627. return SQLITE_OK;
  30628. }
  30629. /* Takes a fully configured proxy locking-style unix file and switches
  30630. ** the local lock file path
  30631. */
  30632. static int switchLockProxyPath(unixFile *pFile, const char *path) {
  30633. proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
  30634. char *oldPath = pCtx->lockProxyPath;
  30635. int rc = SQLITE_OK;
  30636. if( pFile->eFileLock!=NO_LOCK ){
  30637. return SQLITE_BUSY;
  30638. }
  30639. /* nothing to do if the path is NULL, :auto: or matches the existing path */
  30640. if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ||
  30641. (oldPath && !strncmp(oldPath, path, MAXPATHLEN)) ){
  30642. return SQLITE_OK;
  30643. }else{
  30644. unixFile *lockProxy = pCtx->lockProxy;
  30645. pCtx->lockProxy=NULL;
  30646. pCtx->conchHeld = 0;
  30647. if( lockProxy!=NULL ){
  30648. rc=lockProxy->pMethod->xClose((sqlite3_file *)lockProxy);
  30649. if( rc ) return rc;
  30650. sqlite3_free(lockProxy);
  30651. }
  30652. sqlite3_free(oldPath);
  30653. pCtx->lockProxyPath = sqlite3DbStrDup(0, path);
  30654. }
  30655. return rc;
  30656. }
  30657. /*
  30658. ** pFile is a file that has been opened by a prior xOpen call. dbPath
  30659. ** is a string buffer at least MAXPATHLEN+1 characters in size.
  30660. **
  30661. ** This routine find the filename associated with pFile and writes it
  30662. ** int dbPath.
  30663. */
  30664. static int proxyGetDbPathForUnixFile(unixFile *pFile, char *dbPath){
  30665. #if defined(__APPLE__)
  30666. if( pFile->pMethod == &afpIoMethods ){
  30667. /* afp style keeps a reference to the db path in the filePath field
  30668. ** of the struct */
  30669. assert( (int)strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
  30670. strlcpy(dbPath, ((afpLockingContext *)pFile->lockingContext)->dbPath,
  30671. MAXPATHLEN);
  30672. } else
  30673. #endif
  30674. if( pFile->pMethod == &dotlockIoMethods ){
  30675. /* dot lock style uses the locking context to store the dot lock
  30676. ** file path */
  30677. int len = strlen((char *)pFile->lockingContext) - strlen(DOTLOCK_SUFFIX);
  30678. memcpy(dbPath, (char *)pFile->lockingContext, len + 1);
  30679. }else{
  30680. /* all other styles use the locking context to store the db file path */
  30681. assert( strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
  30682. strlcpy(dbPath, (char *)pFile->lockingContext, MAXPATHLEN);
  30683. }
  30684. return SQLITE_OK;
  30685. }
  30686. /*
  30687. ** Takes an already filled in unix file and alters it so all file locking
  30688. ** will be performed on the local proxy lock file. The following fields
  30689. ** are preserved in the locking context so that they can be restored and
  30690. ** the unix structure properly cleaned up at close time:
  30691. ** ->lockingContext
  30692. ** ->pMethod
  30693. */
  30694. static int proxyTransformUnixFile(unixFile *pFile, const char *path) {
  30695. proxyLockingContext *pCtx;
  30696. char dbPath[MAXPATHLEN+1]; /* Name of the database file */
  30697. char *lockPath=NULL;
  30698. int rc = SQLITE_OK;
  30699. if( pFile->eFileLock!=NO_LOCK ){
  30700. return SQLITE_BUSY;
  30701. }
  30702. proxyGetDbPathForUnixFile(pFile, dbPath);
  30703. if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ){
  30704. lockPath=NULL;
  30705. }else{
  30706. lockPath=(char *)path;
  30707. }
  30708. OSTRACE(("TRANSPROXY %d for %s pid=%d\n", pFile->h,
  30709. (lockPath ? lockPath : ":auto:"), osGetpid(0)));
  30710. pCtx = sqlite3_malloc64( sizeof(*pCtx) );
  30711. if( pCtx==0 ){
  30712. return SQLITE_NOMEM;
  30713. }
  30714. memset(pCtx, 0, sizeof(*pCtx));
  30715. rc = proxyCreateConchPathname(dbPath, &pCtx->conchFilePath);
  30716. if( rc==SQLITE_OK ){
  30717. rc = proxyCreateUnixFile(pCtx->conchFilePath, &pCtx->conchFile, 0);
  30718. if( rc==SQLITE_CANTOPEN && ((pFile->openFlags&O_RDWR) == 0) ){
  30719. /* if (a) the open flags are not O_RDWR, (b) the conch isn't there, and
  30720. ** (c) the file system is read-only, then enable no-locking access.
  30721. ** Ugh, since O_RDONLY==0x0000 we test for !O_RDWR since unixOpen asserts
  30722. ** that openFlags will have only one of O_RDONLY or O_RDWR.
  30723. */
  30724. struct statfs fsInfo;
  30725. struct stat conchInfo;
  30726. int goLockless = 0;
  30727. if( osStat(pCtx->conchFilePath, &conchInfo) == -1 ) {
  30728. int err = errno;
  30729. if( (err==ENOENT) && (statfs(dbPath, &fsInfo) != -1) ){
  30730. goLockless = (fsInfo.f_flags&MNT_RDONLY) == MNT_RDONLY;
  30731. }
  30732. }
  30733. if( goLockless ){
  30734. pCtx->conchHeld = -1; /* read only FS/ lockless */
  30735. rc = SQLITE_OK;
  30736. }
  30737. }
  30738. }
  30739. if( rc==SQLITE_OK && lockPath ){
  30740. pCtx->lockProxyPath = sqlite3DbStrDup(0, lockPath);
  30741. }
  30742. if( rc==SQLITE_OK ){
  30743. pCtx->dbPath = sqlite3DbStrDup(0, dbPath);
  30744. if( pCtx->dbPath==NULL ){
  30745. rc = SQLITE_NOMEM;
  30746. }
  30747. }
  30748. if( rc==SQLITE_OK ){
  30749. /* all memory is allocated, proxys are created and assigned,
  30750. ** switch the locking context and pMethod then return.
  30751. */
  30752. pCtx->oldLockingContext = pFile->lockingContext;
  30753. pFile->lockingContext = pCtx;
  30754. pCtx->pOldMethod = pFile->pMethod;
  30755. pFile->pMethod = &proxyIoMethods;
  30756. }else{
  30757. if( pCtx->conchFile ){
  30758. pCtx->conchFile->pMethod->xClose((sqlite3_file *)pCtx->conchFile);
  30759. sqlite3_free(pCtx->conchFile);
  30760. }
  30761. sqlite3DbFree(0, pCtx->lockProxyPath);
  30762. sqlite3_free(pCtx->conchFilePath);
  30763. sqlite3_free(pCtx);
  30764. }
  30765. OSTRACE(("TRANSPROXY %d %s\n", pFile->h,
  30766. (rc==SQLITE_OK ? "ok" : "failed")));
  30767. return rc;
  30768. }
  30769. /*
  30770. ** This routine handles sqlite3_file_control() calls that are specific
  30771. ** to proxy locking.
  30772. */
  30773. static int proxyFileControl(sqlite3_file *id, int op, void *pArg){
  30774. switch( op ){
  30775. case SQLITE_FCNTL_GET_LOCKPROXYFILE: {
  30776. unixFile *pFile = (unixFile*)id;
  30777. if( pFile->pMethod == &proxyIoMethods ){
  30778. proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
  30779. proxyTakeConch(pFile);
  30780. if( pCtx->lockProxyPath ){
  30781. *(const char **)pArg = pCtx->lockProxyPath;
  30782. }else{
  30783. *(const char **)pArg = ":auto: (not held)";
  30784. }
  30785. } else {
  30786. *(const char **)pArg = NULL;
  30787. }
  30788. return SQLITE_OK;
  30789. }
  30790. case SQLITE_FCNTL_SET_LOCKPROXYFILE: {
  30791. unixFile *pFile = (unixFile*)id;
  30792. int rc = SQLITE_OK;
  30793. int isProxyStyle = (pFile->pMethod == &proxyIoMethods);
  30794. if( pArg==NULL || (const char *)pArg==0 ){
  30795. if( isProxyStyle ){
  30796. /* turn off proxy locking - not supported. If support is added for
  30797. ** switching proxy locking mode off then it will need to fail if
  30798. ** the journal mode is WAL mode.
  30799. */
  30800. rc = SQLITE_ERROR /*SQLITE_PROTOCOL? SQLITE_MISUSE?*/;
  30801. }else{
  30802. /* turn off proxy locking - already off - NOOP */
  30803. rc = SQLITE_OK;
  30804. }
  30805. }else{
  30806. const char *proxyPath = (const char *)pArg;
  30807. if( isProxyStyle ){
  30808. proxyLockingContext *pCtx =
  30809. (proxyLockingContext*)pFile->lockingContext;
  30810. if( !strcmp(pArg, ":auto:")
  30811. || (pCtx->lockProxyPath &&
  30812. !strncmp(pCtx->lockProxyPath, proxyPath, MAXPATHLEN))
  30813. ){
  30814. rc = SQLITE_OK;
  30815. }else{
  30816. rc = switchLockProxyPath(pFile, proxyPath);
  30817. }
  30818. }else{
  30819. /* turn on proxy file locking */
  30820. rc = proxyTransformUnixFile(pFile, proxyPath);
  30821. }
  30822. }
  30823. return rc;
  30824. }
  30825. default: {
  30826. assert( 0 ); /* The call assures that only valid opcodes are sent */
  30827. }
  30828. }
  30829. /*NOTREACHED*/
  30830. return SQLITE_ERROR;
  30831. }
  30832. /*
  30833. ** Within this division (the proxying locking implementation) the procedures
  30834. ** above this point are all utilities. The lock-related methods of the
  30835. ** proxy-locking sqlite3_io_method object follow.
  30836. */
  30837. /*
  30838. ** This routine checks if there is a RESERVED lock held on the specified
  30839. ** file by this or any other process. If such a lock is held, set *pResOut
  30840. ** to a non-zero value otherwise *pResOut is set to zero. The return value
  30841. ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
  30842. */
  30843. static int proxyCheckReservedLock(sqlite3_file *id, int *pResOut) {
  30844. unixFile *pFile = (unixFile*)id;
  30845. int rc = proxyTakeConch(pFile);
  30846. if( rc==SQLITE_OK ){
  30847. proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
  30848. if( pCtx->conchHeld>0 ){
  30849. unixFile *proxy = pCtx->lockProxy;
  30850. return proxy->pMethod->xCheckReservedLock((sqlite3_file*)proxy, pResOut);
  30851. }else{ /* conchHeld < 0 is lockless */
  30852. pResOut=0;
  30853. }
  30854. }
  30855. return rc;
  30856. }
  30857. /*
  30858. ** Lock the file with the lock specified by parameter eFileLock - one
  30859. ** of the following:
  30860. **
  30861. ** (1) SHARED_LOCK
  30862. ** (2) RESERVED_LOCK
  30863. ** (3) PENDING_LOCK
  30864. ** (4) EXCLUSIVE_LOCK
  30865. **
  30866. ** Sometimes when requesting one lock state, additional lock states
  30867. ** are inserted in between. The locking might fail on one of the later
  30868. ** transitions leaving the lock state different from what it started but
  30869. ** still short of its goal. The following chart shows the allowed
  30870. ** transitions and the inserted intermediate states:
  30871. **
  30872. ** UNLOCKED -> SHARED
  30873. ** SHARED -> RESERVED
  30874. ** SHARED -> (PENDING) -> EXCLUSIVE
  30875. ** RESERVED -> (PENDING) -> EXCLUSIVE
  30876. ** PENDING -> EXCLUSIVE
  30877. **
  30878. ** This routine will only increase a lock. Use the sqlite3OsUnlock()
  30879. ** routine to lower a locking level.
  30880. */
  30881. static int proxyLock(sqlite3_file *id, int eFileLock) {
  30882. unixFile *pFile = (unixFile*)id;
  30883. int rc = proxyTakeConch(pFile);
  30884. if( rc==SQLITE_OK ){
  30885. proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
  30886. if( pCtx->conchHeld>0 ){
  30887. unixFile *proxy = pCtx->lockProxy;
  30888. rc = proxy->pMethod->xLock((sqlite3_file*)proxy, eFileLock);
  30889. pFile->eFileLock = proxy->eFileLock;
  30890. }else{
  30891. /* conchHeld < 0 is lockless */
  30892. }
  30893. }
  30894. return rc;
  30895. }
  30896. /*
  30897. ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
  30898. ** must be either NO_LOCK or SHARED_LOCK.
  30899. **
  30900. ** If the locking level of the file descriptor is already at or below
  30901. ** the requested locking level, this routine is a no-op.
  30902. */
  30903. static int proxyUnlock(sqlite3_file *id, int eFileLock) {
  30904. unixFile *pFile = (unixFile*)id;
  30905. int rc = proxyTakeConch(pFile);
  30906. if( rc==SQLITE_OK ){
  30907. proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
  30908. if( pCtx->conchHeld>0 ){
  30909. unixFile *proxy = pCtx->lockProxy;
  30910. rc = proxy->pMethod->xUnlock((sqlite3_file*)proxy, eFileLock);
  30911. pFile->eFileLock = proxy->eFileLock;
  30912. }else{
  30913. /* conchHeld < 0 is lockless */
  30914. }
  30915. }
  30916. return rc;
  30917. }
  30918. /*
  30919. ** Close a file that uses proxy locks.
  30920. */
  30921. static int proxyClose(sqlite3_file *id) {
  30922. if( id ){
  30923. unixFile *pFile = (unixFile*)id;
  30924. proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
  30925. unixFile *lockProxy = pCtx->lockProxy;
  30926. unixFile *conchFile = pCtx->conchFile;
  30927. int rc = SQLITE_OK;
  30928. if( lockProxy ){
  30929. rc = lockProxy->pMethod->xUnlock((sqlite3_file*)lockProxy, NO_LOCK);
  30930. if( rc ) return rc;
  30931. rc = lockProxy->pMethod->xClose((sqlite3_file*)lockProxy);
  30932. if( rc ) return rc;
  30933. sqlite3_free(lockProxy);
  30934. pCtx->lockProxy = 0;
  30935. }
  30936. if( conchFile ){
  30937. if( pCtx->conchHeld ){
  30938. rc = proxyReleaseConch(pFile);
  30939. if( rc ) return rc;
  30940. }
  30941. rc = conchFile->pMethod->xClose((sqlite3_file*)conchFile);
  30942. if( rc ) return rc;
  30943. sqlite3_free(conchFile);
  30944. }
  30945. sqlite3DbFree(0, pCtx->lockProxyPath);
  30946. sqlite3_free(pCtx->conchFilePath);
  30947. sqlite3DbFree(0, pCtx->dbPath);
  30948. /* restore the original locking context and pMethod then close it */
  30949. pFile->lockingContext = pCtx->oldLockingContext;
  30950. pFile->pMethod = pCtx->pOldMethod;
  30951. sqlite3_free(pCtx);
  30952. return pFile->pMethod->xClose(id);
  30953. }
  30954. return SQLITE_OK;
  30955. }
  30956. #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
  30957. /*
  30958. ** The proxy locking style is intended for use with AFP filesystems.
  30959. ** And since AFP is only supported on MacOSX, the proxy locking is also
  30960. ** restricted to MacOSX.
  30961. **
  30962. **
  30963. ******************* End of the proxy lock implementation **********************
  30964. ******************************************************************************/
  30965. /*
  30966. ** Initialize the operating system interface.
  30967. **
  30968. ** This routine registers all VFS implementations for unix-like operating
  30969. ** systems. This routine, and the sqlite3_os_end() routine that follows,
  30970. ** should be the only routines in this file that are visible from other
  30971. ** files.
  30972. **
  30973. ** This routine is called once during SQLite initialization and by a
  30974. ** single thread. The memory allocation and mutex subsystems have not
  30975. ** necessarily been initialized when this routine is called, and so they
  30976. ** should not be used.
  30977. */
  30978. SQLITE_API int SQLITE_STDCALL sqlite3_os_init(void){
  30979. /*
  30980. ** The following macro defines an initializer for an sqlite3_vfs object.
  30981. ** The name of the VFS is NAME. The pAppData is a pointer to a pointer
  30982. ** to the "finder" function. (pAppData is a pointer to a pointer because
  30983. ** silly C90 rules prohibit a void* from being cast to a function pointer
  30984. ** and so we have to go through the intermediate pointer to avoid problems
  30985. ** when compiling with -pedantic-errors on GCC.)
  30986. **
  30987. ** The FINDER parameter to this macro is the name of the pointer to the
  30988. ** finder-function. The finder-function returns a pointer to the
  30989. ** sqlite_io_methods object that implements the desired locking
  30990. ** behaviors. See the division above that contains the IOMETHODS
  30991. ** macro for addition information on finder-functions.
  30992. **
  30993. ** Most finders simply return a pointer to a fixed sqlite3_io_methods
  30994. ** object. But the "autolockIoFinder" available on MacOSX does a little
  30995. ** more than that; it looks at the filesystem type that hosts the
  30996. ** database file and tries to choose an locking method appropriate for
  30997. ** that filesystem time.
  30998. */
  30999. #define UNIXVFS(VFSNAME, FINDER) { \
  31000. 3, /* iVersion */ \
  31001. sizeof(unixFile), /* szOsFile */ \
  31002. MAX_PATHNAME, /* mxPathname */ \
  31003. 0, /* pNext */ \
  31004. VFSNAME, /* zName */ \
  31005. (void*)&FINDER, /* pAppData */ \
  31006. unixOpen, /* xOpen */ \
  31007. unixDelete, /* xDelete */ \
  31008. unixAccess, /* xAccess */ \
  31009. unixFullPathname, /* xFullPathname */ \
  31010. unixDlOpen, /* xDlOpen */ \
  31011. unixDlError, /* xDlError */ \
  31012. unixDlSym, /* xDlSym */ \
  31013. unixDlClose, /* xDlClose */ \
  31014. unixRandomness, /* xRandomness */ \
  31015. unixSleep, /* xSleep */ \
  31016. unixCurrentTime, /* xCurrentTime */ \
  31017. unixGetLastError, /* xGetLastError */ \
  31018. unixCurrentTimeInt64, /* xCurrentTimeInt64 */ \
  31019. unixSetSystemCall, /* xSetSystemCall */ \
  31020. unixGetSystemCall, /* xGetSystemCall */ \
  31021. unixNextSystemCall, /* xNextSystemCall */ \
  31022. }
  31023. /*
  31024. ** All default VFSes for unix are contained in the following array.
  31025. **
  31026. ** Note that the sqlite3_vfs.pNext field of the VFS object is modified
  31027. ** by the SQLite core when the VFS is registered. So the following
  31028. ** array cannot be const.
  31029. */
  31030. static sqlite3_vfs aVfs[] = {
  31031. #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
  31032. UNIXVFS("unix", autolockIoFinder ),
  31033. #elif OS_VXWORKS
  31034. UNIXVFS("unix", vxworksIoFinder ),
  31035. #else
  31036. UNIXVFS("unix", posixIoFinder ),
  31037. #endif
  31038. UNIXVFS("unix-none", nolockIoFinder ),
  31039. UNIXVFS("unix-dotfile", dotlockIoFinder ),
  31040. UNIXVFS("unix-excl", posixIoFinder ),
  31041. #if OS_VXWORKS
  31042. UNIXVFS("unix-namedsem", semIoFinder ),
  31043. #endif
  31044. #if SQLITE_ENABLE_LOCKING_STYLE || OS_VXWORKS
  31045. UNIXVFS("unix-posix", posixIoFinder ),
  31046. #endif
  31047. #if SQLITE_ENABLE_LOCKING_STYLE
  31048. UNIXVFS("unix-flock", flockIoFinder ),
  31049. #endif
  31050. #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
  31051. UNIXVFS("unix-afp", afpIoFinder ),
  31052. UNIXVFS("unix-nfs", nfsIoFinder ),
  31053. UNIXVFS("unix-proxy", proxyIoFinder ),
  31054. #endif
  31055. };
  31056. unsigned int i; /* Loop counter */
  31057. /* Double-check that the aSyscall[] array has been constructed
  31058. ** correctly. See ticket [bb3a86e890c8e96ab] */
  31059. assert( ArraySize(aSyscall)==25 );
  31060. /* Register all VFSes defined in the aVfs[] array */
  31061. for(i=0; i<(sizeof(aVfs)/sizeof(sqlite3_vfs)); i++){
  31062. sqlite3_vfs_register(&aVfs[i], i==0);
  31063. }
  31064. return SQLITE_OK;
  31065. }
  31066. /*
  31067. ** Shutdown the operating system interface.
  31068. **
  31069. ** Some operating systems might need to do some cleanup in this routine,
  31070. ** to release dynamically allocated objects. But not on unix.
  31071. ** This routine is a no-op for unix.
  31072. */
  31073. SQLITE_API int SQLITE_STDCALL sqlite3_os_end(void){
  31074. return SQLITE_OK;
  31075. }
  31076. #endif /* SQLITE_OS_UNIX */
  31077. /************** End of os_unix.c *********************************************/
  31078. /************** Begin file os_win.c ******************************************/
  31079. /*
  31080. ** 2004 May 22
  31081. **
  31082. ** The author disclaims copyright to this source code. In place of
  31083. ** a legal notice, here is a blessing:
  31084. **
  31085. ** May you do good and not evil.
  31086. ** May you find forgiveness for yourself and forgive others.
  31087. ** May you share freely, never taking more than you give.
  31088. **
  31089. ******************************************************************************
  31090. **
  31091. ** This file contains code that is specific to Windows.
  31092. */
  31093. #if SQLITE_OS_WIN /* This file is used for Windows only */
  31094. /*
  31095. ** Include code that is common to all os_*.c files
  31096. */
  31097. /************** Include os_common.h in the middle of os_win.c ****************/
  31098. /************** Begin file os_common.h ***************************************/
  31099. /*
  31100. ** 2004 May 22
  31101. **
  31102. ** The author disclaims copyright to this source code. In place of
  31103. ** a legal notice, here is a blessing:
  31104. **
  31105. ** May you do good and not evil.
  31106. ** May you find forgiveness for yourself and forgive others.
  31107. ** May you share freely, never taking more than you give.
  31108. **
  31109. ******************************************************************************
  31110. **
  31111. ** This file contains macros and a little bit of code that is common to
  31112. ** all of the platform-specific files (os_*.c) and is #included into those
  31113. ** files.
  31114. **
  31115. ** This file should be #included by the os_*.c files only. It is not a
  31116. ** general purpose header file.
  31117. */
  31118. #ifndef _OS_COMMON_H_
  31119. #define _OS_COMMON_H_
  31120. /*
  31121. ** At least two bugs have slipped in because we changed the MEMORY_DEBUG
  31122. ** macro to SQLITE_DEBUG and some older makefiles have not yet made the
  31123. ** switch. The following code should catch this problem at compile-time.
  31124. */
  31125. #ifdef MEMORY_DEBUG
  31126. # error "The MEMORY_DEBUG macro is obsolete. Use SQLITE_DEBUG instead."
  31127. #endif
  31128. /*
  31129. ** Macros for performance tracing. Normally turned off. Only works
  31130. ** on i486 hardware.
  31131. */
  31132. #ifdef SQLITE_PERFORMANCE_TRACE
  31133. /*
  31134. ** hwtime.h contains inline assembler code for implementing
  31135. ** high-performance timing routines.
  31136. */
  31137. /************** Include hwtime.h in the middle of os_common.h ****************/
  31138. /************** Begin file hwtime.h ******************************************/
  31139. /*
  31140. ** 2008 May 27
  31141. **
  31142. ** The author disclaims copyright to this source code. In place of
  31143. ** a legal notice, here is a blessing:
  31144. **
  31145. ** May you do good and not evil.
  31146. ** May you find forgiveness for yourself and forgive others.
  31147. ** May you share freely, never taking more than you give.
  31148. **
  31149. ******************************************************************************
  31150. **
  31151. ** This file contains inline asm code for retrieving "high-performance"
  31152. ** counters for x86 class CPUs.
  31153. */
  31154. #ifndef _HWTIME_H_
  31155. #define _HWTIME_H_
  31156. /*
  31157. ** The following routine only works on pentium-class (or newer) processors.
  31158. ** It uses the RDTSC opcode to read the cycle count value out of the
  31159. ** processor and returns that value. This can be used for high-res
  31160. ** profiling.
  31161. */
  31162. #if (defined(__GNUC__) || defined(_MSC_VER)) && \
  31163. (defined(i386) || defined(__i386__) || defined(_M_IX86))
  31164. #if defined(__GNUC__)
  31165. __inline__ sqlite_uint64 sqlite3Hwtime(void){
  31166. unsigned int lo, hi;
  31167. __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
  31168. return (sqlite_uint64)hi << 32 | lo;
  31169. }
  31170. #elif defined(_MSC_VER)
  31171. __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
  31172. __asm {
  31173. rdtsc
  31174. ret ; return value at EDX:EAX
  31175. }
  31176. }
  31177. #endif
  31178. #elif (defined(__GNUC__) && defined(__x86_64__))
  31179. __inline__ sqlite_uint64 sqlite3Hwtime(void){
  31180. unsigned long val;
  31181. __asm__ __volatile__ ("rdtsc" : "=A" (val));
  31182. return val;
  31183. }
  31184. #elif (defined(__GNUC__) && defined(__ppc__))
  31185. __inline__ sqlite_uint64 sqlite3Hwtime(void){
  31186. unsigned long long retval;
  31187. unsigned long junk;
  31188. __asm__ __volatile__ ("\n\
  31189. 1: mftbu %1\n\
  31190. mftb %L0\n\
  31191. mftbu %0\n\
  31192. cmpw %0,%1\n\
  31193. bne 1b"
  31194. : "=r" (retval), "=r" (junk));
  31195. return retval;
  31196. }
  31197. #else
  31198. #error Need implementation of sqlite3Hwtime() for your platform.
  31199. /*
  31200. ** To compile without implementing sqlite3Hwtime() for your platform,
  31201. ** you can remove the above #error and use the following
  31202. ** stub function. You will lose timing support for many
  31203. ** of the debugging and testing utilities, but it should at
  31204. ** least compile and run.
  31205. */
  31206. SQLITE_PRIVATE sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
  31207. #endif
  31208. #endif /* !defined(_HWTIME_H_) */
  31209. /************** End of hwtime.h **********************************************/
  31210. /************** Continuing where we left off in os_common.h ******************/
  31211. static sqlite_uint64 g_start;
  31212. static sqlite_uint64 g_elapsed;
  31213. #define TIMER_START g_start=sqlite3Hwtime()
  31214. #define TIMER_END g_elapsed=sqlite3Hwtime()-g_start
  31215. #define TIMER_ELAPSED g_elapsed
  31216. #else
  31217. #define TIMER_START
  31218. #define TIMER_END
  31219. #define TIMER_ELAPSED ((sqlite_uint64)0)
  31220. #endif
  31221. /*
  31222. ** If we compile with the SQLITE_TEST macro set, then the following block
  31223. ** of code will give us the ability to simulate a disk I/O error. This
  31224. ** is used for testing the I/O recovery logic.
  31225. */
  31226. #ifdef SQLITE_TEST
  31227. SQLITE_API int sqlite3_io_error_hit = 0; /* Total number of I/O Errors */
  31228. SQLITE_API int sqlite3_io_error_hardhit = 0; /* Number of non-benign errors */
  31229. SQLITE_API int sqlite3_io_error_pending = 0; /* Count down to first I/O error */
  31230. SQLITE_API int sqlite3_io_error_persist = 0; /* True if I/O errors persist */
  31231. SQLITE_API int sqlite3_io_error_benign = 0; /* True if errors are benign */
  31232. SQLITE_API int sqlite3_diskfull_pending = 0;
  31233. SQLITE_API int sqlite3_diskfull = 0;
  31234. #define SimulateIOErrorBenign(X) sqlite3_io_error_benign=(X)
  31235. #define SimulateIOError(CODE) \
  31236. if( (sqlite3_io_error_persist && sqlite3_io_error_hit) \
  31237. || sqlite3_io_error_pending-- == 1 ) \
  31238. { local_ioerr(); CODE; }
  31239. static void local_ioerr(){
  31240. IOTRACE(("IOERR\n"));
  31241. sqlite3_io_error_hit++;
  31242. if( !sqlite3_io_error_benign ) sqlite3_io_error_hardhit++;
  31243. }
  31244. #define SimulateDiskfullError(CODE) \
  31245. if( sqlite3_diskfull_pending ){ \
  31246. if( sqlite3_diskfull_pending == 1 ){ \
  31247. local_ioerr(); \
  31248. sqlite3_diskfull = 1; \
  31249. sqlite3_io_error_hit = 1; \
  31250. CODE; \
  31251. }else{ \
  31252. sqlite3_diskfull_pending--; \
  31253. } \
  31254. }
  31255. #else
  31256. #define SimulateIOErrorBenign(X)
  31257. #define SimulateIOError(A)
  31258. #define SimulateDiskfullError(A)
  31259. #endif
  31260. /*
  31261. ** When testing, keep a count of the number of open files.
  31262. */
  31263. #ifdef SQLITE_TEST
  31264. SQLITE_API int sqlite3_open_file_count = 0;
  31265. #define OpenCounter(X) sqlite3_open_file_count+=(X)
  31266. #else
  31267. #define OpenCounter(X)
  31268. #endif
  31269. #endif /* !defined(_OS_COMMON_H_) */
  31270. /************** End of os_common.h *******************************************/
  31271. /************** Continuing where we left off in os_win.c *********************/
  31272. /*
  31273. ** Include the header file for the Windows VFS.
  31274. */
  31275. /*
  31276. ** Compiling and using WAL mode requires several APIs that are only
  31277. ** available in Windows platforms based on the NT kernel.
  31278. */
  31279. #if !SQLITE_OS_WINNT && !defined(SQLITE_OMIT_WAL)
  31280. # error "WAL mode requires support from the Windows NT kernel, compile\
  31281. with SQLITE_OMIT_WAL."
  31282. #endif
  31283. #if !SQLITE_OS_WINNT && SQLITE_MAX_MMAP_SIZE>0
  31284. # error "Memory mapped files require support from the Windows NT kernel,\
  31285. compile with SQLITE_MAX_MMAP_SIZE=0."
  31286. #endif
  31287. /*
  31288. ** Are most of the Win32 ANSI APIs available (i.e. with certain exceptions
  31289. ** based on the sub-platform)?
  31290. */
  31291. #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && !defined(SQLITE_WIN32_NO_ANSI)
  31292. # define SQLITE_WIN32_HAS_ANSI
  31293. #endif
  31294. /*
  31295. ** Are most of the Win32 Unicode APIs available (i.e. with certain exceptions
  31296. ** based on the sub-platform)?
  31297. */
  31298. #if (SQLITE_OS_WINCE || SQLITE_OS_WINNT || SQLITE_OS_WINRT) && \
  31299. !defined(SQLITE_WIN32_NO_WIDE)
  31300. # define SQLITE_WIN32_HAS_WIDE
  31301. #endif
  31302. /*
  31303. ** Make sure at least one set of Win32 APIs is available.
  31304. */
  31305. #if !defined(SQLITE_WIN32_HAS_ANSI) && !defined(SQLITE_WIN32_HAS_WIDE)
  31306. # error "At least one of SQLITE_WIN32_HAS_ANSI and SQLITE_WIN32_HAS_WIDE\
  31307. must be defined."
  31308. #endif
  31309. /*
  31310. ** Define the required Windows SDK version constants if they are not
  31311. ** already available.
  31312. */
  31313. #ifndef NTDDI_WIN8
  31314. # define NTDDI_WIN8 0x06020000
  31315. #endif
  31316. #ifndef NTDDI_WINBLUE
  31317. # define NTDDI_WINBLUE 0x06030000
  31318. #endif
  31319. /*
  31320. ** Check to see if the GetVersionEx[AW] functions are deprecated on the
  31321. ** target system. GetVersionEx was first deprecated in Win8.1.
  31322. */
  31323. #ifndef SQLITE_WIN32_GETVERSIONEX
  31324. # if defined(NTDDI_VERSION) && NTDDI_VERSION >= NTDDI_WINBLUE
  31325. # define SQLITE_WIN32_GETVERSIONEX 0 /* GetVersionEx() is deprecated */
  31326. # else
  31327. # define SQLITE_WIN32_GETVERSIONEX 1 /* GetVersionEx() is current */
  31328. # endif
  31329. #endif
  31330. /*
  31331. ** This constant should already be defined (in the "WinDef.h" SDK file).
  31332. */
  31333. #ifndef MAX_PATH
  31334. # define MAX_PATH (260)
  31335. #endif
  31336. /*
  31337. ** Maximum pathname length (in chars) for Win32. This should normally be
  31338. ** MAX_PATH.
  31339. */
  31340. #ifndef SQLITE_WIN32_MAX_PATH_CHARS
  31341. # define SQLITE_WIN32_MAX_PATH_CHARS (MAX_PATH)
  31342. #endif
  31343. /*
  31344. ** This constant should already be defined (in the "WinNT.h" SDK file).
  31345. */
  31346. #ifndef UNICODE_STRING_MAX_CHARS
  31347. # define UNICODE_STRING_MAX_CHARS (32767)
  31348. #endif
  31349. /*
  31350. ** Maximum pathname length (in chars) for WinNT. This should normally be
  31351. ** UNICODE_STRING_MAX_CHARS.
  31352. */
  31353. #ifndef SQLITE_WINNT_MAX_PATH_CHARS
  31354. # define SQLITE_WINNT_MAX_PATH_CHARS (UNICODE_STRING_MAX_CHARS)
  31355. #endif
  31356. /*
  31357. ** Maximum pathname length (in bytes) for Win32. The MAX_PATH macro is in
  31358. ** characters, so we allocate 4 bytes per character assuming worst-case of
  31359. ** 4-bytes-per-character for UTF8.
  31360. */
  31361. #ifndef SQLITE_WIN32_MAX_PATH_BYTES
  31362. # define SQLITE_WIN32_MAX_PATH_BYTES (SQLITE_WIN32_MAX_PATH_CHARS*4)
  31363. #endif
  31364. /*
  31365. ** Maximum pathname length (in bytes) for WinNT. This should normally be
  31366. ** UNICODE_STRING_MAX_CHARS * sizeof(WCHAR).
  31367. */
  31368. #ifndef SQLITE_WINNT_MAX_PATH_BYTES
  31369. # define SQLITE_WINNT_MAX_PATH_BYTES \
  31370. (sizeof(WCHAR) * SQLITE_WINNT_MAX_PATH_CHARS)
  31371. #endif
  31372. /*
  31373. ** Maximum error message length (in chars) for WinRT.
  31374. */
  31375. #ifndef SQLITE_WIN32_MAX_ERRMSG_CHARS
  31376. # define SQLITE_WIN32_MAX_ERRMSG_CHARS (1024)
  31377. #endif
  31378. /*
  31379. ** Returns non-zero if the character should be treated as a directory
  31380. ** separator.
  31381. */
  31382. #ifndef winIsDirSep
  31383. # define winIsDirSep(a) (((a) == '/') || ((a) == '\\'))
  31384. #endif
  31385. /*
  31386. ** This macro is used when a local variable is set to a value that is
  31387. ** [sometimes] not used by the code (e.g. via conditional compilation).
  31388. */
  31389. #ifndef UNUSED_VARIABLE_VALUE
  31390. # define UNUSED_VARIABLE_VALUE(x) (void)(x)
  31391. #endif
  31392. /*
  31393. ** Returns the character that should be used as the directory separator.
  31394. */
  31395. #ifndef winGetDirSep
  31396. # define winGetDirSep() '\\'
  31397. #endif
  31398. /*
  31399. ** Do we need to manually define the Win32 file mapping APIs for use with WAL
  31400. ** mode or memory mapped files (e.g. these APIs are available in the Windows
  31401. ** CE SDK; however, they are not present in the header file)?
  31402. */
  31403. #if SQLITE_WIN32_FILEMAPPING_API && \
  31404. (!defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0)
  31405. /*
  31406. ** Two of the file mapping APIs are different under WinRT. Figure out which
  31407. ** set we need.
  31408. */
  31409. #if SQLITE_OS_WINRT
  31410. WINBASEAPI HANDLE WINAPI CreateFileMappingFromApp(HANDLE, \
  31411. LPSECURITY_ATTRIBUTES, ULONG, ULONG64, LPCWSTR);
  31412. WINBASEAPI LPVOID WINAPI MapViewOfFileFromApp(HANDLE, ULONG, ULONG64, SIZE_T);
  31413. #else
  31414. #if defined(SQLITE_WIN32_HAS_ANSI)
  31415. WINBASEAPI HANDLE WINAPI CreateFileMappingA(HANDLE, LPSECURITY_ATTRIBUTES, \
  31416. DWORD, DWORD, DWORD, LPCSTR);
  31417. #endif /* defined(SQLITE_WIN32_HAS_ANSI) */
  31418. #if defined(SQLITE_WIN32_HAS_WIDE)
  31419. WINBASEAPI HANDLE WINAPI CreateFileMappingW(HANDLE, LPSECURITY_ATTRIBUTES, \
  31420. DWORD, DWORD, DWORD, LPCWSTR);
  31421. #endif /* defined(SQLITE_WIN32_HAS_WIDE) */
  31422. WINBASEAPI LPVOID WINAPI MapViewOfFile(HANDLE, DWORD, DWORD, DWORD, SIZE_T);
  31423. #endif /* SQLITE_OS_WINRT */
  31424. /*
  31425. ** These file mapping APIs are common to both Win32 and WinRT.
  31426. */
  31427. WINBASEAPI BOOL WINAPI FlushViewOfFile(LPCVOID, SIZE_T);
  31428. WINBASEAPI BOOL WINAPI UnmapViewOfFile(LPCVOID);
  31429. #endif /* SQLITE_WIN32_FILEMAPPING_API */
  31430. /*
  31431. ** Some Microsoft compilers lack this definition.
  31432. */
  31433. #ifndef INVALID_FILE_ATTRIBUTES
  31434. # define INVALID_FILE_ATTRIBUTES ((DWORD)-1)
  31435. #endif
  31436. #ifndef FILE_FLAG_MASK
  31437. # define FILE_FLAG_MASK (0xFF3C0000)
  31438. #endif
  31439. #ifndef FILE_ATTRIBUTE_MASK
  31440. # define FILE_ATTRIBUTE_MASK (0x0003FFF7)
  31441. #endif
  31442. #ifndef SQLITE_OMIT_WAL
  31443. /* Forward references to structures used for WAL */
  31444. typedef struct winShm winShm; /* A connection to shared-memory */
  31445. typedef struct winShmNode winShmNode; /* A region of shared-memory */
  31446. #endif
  31447. /*
  31448. ** WinCE lacks native support for file locking so we have to fake it
  31449. ** with some code of our own.
  31450. */
  31451. #if SQLITE_OS_WINCE
  31452. typedef struct winceLock {
  31453. int nReaders; /* Number of reader locks obtained */
  31454. BOOL bPending; /* Indicates a pending lock has been obtained */
  31455. BOOL bReserved; /* Indicates a reserved lock has been obtained */
  31456. BOOL bExclusive; /* Indicates an exclusive lock has been obtained */
  31457. } winceLock;
  31458. #endif
  31459. /*
  31460. ** The winFile structure is a subclass of sqlite3_file* specific to the win32
  31461. ** portability layer.
  31462. */
  31463. typedef struct winFile winFile;
  31464. struct winFile {
  31465. const sqlite3_io_methods *pMethod; /*** Must be first ***/
  31466. sqlite3_vfs *pVfs; /* The VFS used to open this file */
  31467. HANDLE h; /* Handle for accessing the file */
  31468. u8 locktype; /* Type of lock currently held on this file */
  31469. short sharedLockByte; /* Randomly chosen byte used as a shared lock */
  31470. u8 ctrlFlags; /* Flags. See WINFILE_* below */
  31471. DWORD lastErrno; /* The Windows errno from the last I/O error */
  31472. #ifndef SQLITE_OMIT_WAL
  31473. winShm *pShm; /* Instance of shared memory on this file */
  31474. #endif
  31475. const char *zPath; /* Full pathname of this file */
  31476. int szChunk; /* Chunk size configured by FCNTL_CHUNK_SIZE */
  31477. #if SQLITE_OS_WINCE
  31478. LPWSTR zDeleteOnClose; /* Name of file to delete when closing */
  31479. HANDLE hMutex; /* Mutex used to control access to shared lock */
  31480. HANDLE hShared; /* Shared memory segment used for locking */
  31481. winceLock local; /* Locks obtained by this instance of winFile */
  31482. winceLock *shared; /* Global shared lock memory for the file */
  31483. #endif
  31484. #if SQLITE_MAX_MMAP_SIZE>0
  31485. int nFetchOut; /* Number of outstanding xFetch references */
  31486. HANDLE hMap; /* Handle for accessing memory mapping */
  31487. void *pMapRegion; /* Area memory mapped */
  31488. sqlite3_int64 mmapSize; /* Usable size of mapped region */
  31489. sqlite3_int64 mmapSizeActual; /* Actual size of mapped region */
  31490. sqlite3_int64 mmapSizeMax; /* Configured FCNTL_MMAP_SIZE value */
  31491. #endif
  31492. };
  31493. /*
  31494. ** Allowed values for winFile.ctrlFlags
  31495. */
  31496. #define WINFILE_RDONLY 0x02 /* Connection is read only */
  31497. #define WINFILE_PERSIST_WAL 0x04 /* Persistent WAL mode */
  31498. #define WINFILE_PSOW 0x10 /* SQLITE_IOCAP_POWERSAFE_OVERWRITE */
  31499. /*
  31500. * The size of the buffer used by sqlite3_win32_write_debug().
  31501. */
  31502. #ifndef SQLITE_WIN32_DBG_BUF_SIZE
  31503. # define SQLITE_WIN32_DBG_BUF_SIZE ((int)(4096-sizeof(DWORD)))
  31504. #endif
  31505. /*
  31506. * The value used with sqlite3_win32_set_directory() to specify that
  31507. * the data directory should be changed.
  31508. */
  31509. #ifndef SQLITE_WIN32_DATA_DIRECTORY_TYPE
  31510. # define SQLITE_WIN32_DATA_DIRECTORY_TYPE (1)
  31511. #endif
  31512. /*
  31513. * The value used with sqlite3_win32_set_directory() to specify that
  31514. * the temporary directory should be changed.
  31515. */
  31516. #ifndef SQLITE_WIN32_TEMP_DIRECTORY_TYPE
  31517. # define SQLITE_WIN32_TEMP_DIRECTORY_TYPE (2)
  31518. #endif
  31519. /*
  31520. * If compiled with SQLITE_WIN32_MALLOC on Windows, we will use the
  31521. * various Win32 API heap functions instead of our own.
  31522. */
  31523. #ifdef SQLITE_WIN32_MALLOC
  31524. /*
  31525. * If this is non-zero, an isolated heap will be created by the native Win32
  31526. * allocator subsystem; otherwise, the default process heap will be used. This
  31527. * setting has no effect when compiling for WinRT. By default, this is enabled
  31528. * and an isolated heap will be created to store all allocated data.
  31529. *
  31530. ******************************************************************************
  31531. * WARNING: It is important to note that when this setting is non-zero and the
  31532. * winMemShutdown function is called (e.g. by the sqlite3_shutdown
  31533. * function), all data that was allocated using the isolated heap will
  31534. * be freed immediately and any attempt to access any of that freed
  31535. * data will almost certainly result in an immediate access violation.
  31536. ******************************************************************************
  31537. */
  31538. #ifndef SQLITE_WIN32_HEAP_CREATE
  31539. # define SQLITE_WIN32_HEAP_CREATE (TRUE)
  31540. #endif
  31541. /*
  31542. * The initial size of the Win32-specific heap. This value may be zero.
  31543. */
  31544. #ifndef SQLITE_WIN32_HEAP_INIT_SIZE
  31545. # define SQLITE_WIN32_HEAP_INIT_SIZE ((SQLITE_DEFAULT_CACHE_SIZE) * \
  31546. (SQLITE_DEFAULT_PAGE_SIZE) + 4194304)
  31547. #endif
  31548. /*
  31549. * The maximum size of the Win32-specific heap. This value may be zero.
  31550. */
  31551. #ifndef SQLITE_WIN32_HEAP_MAX_SIZE
  31552. # define SQLITE_WIN32_HEAP_MAX_SIZE (0)
  31553. #endif
  31554. /*
  31555. * The extra flags to use in calls to the Win32 heap APIs. This value may be
  31556. * zero for the default behavior.
  31557. */
  31558. #ifndef SQLITE_WIN32_HEAP_FLAGS
  31559. # define SQLITE_WIN32_HEAP_FLAGS (0)
  31560. #endif
  31561. /*
  31562. ** The winMemData structure stores information required by the Win32-specific
  31563. ** sqlite3_mem_methods implementation.
  31564. */
  31565. typedef struct winMemData winMemData;
  31566. struct winMemData {
  31567. #ifndef NDEBUG
  31568. u32 magic1; /* Magic number to detect structure corruption. */
  31569. #endif
  31570. HANDLE hHeap; /* The handle to our heap. */
  31571. BOOL bOwned; /* Do we own the heap (i.e. destroy it on shutdown)? */
  31572. #ifndef NDEBUG
  31573. u32 magic2; /* Magic number to detect structure corruption. */
  31574. #endif
  31575. };
  31576. #ifndef NDEBUG
  31577. #define WINMEM_MAGIC1 0x42b2830b
  31578. #define WINMEM_MAGIC2 0xbd4d7cf4
  31579. #endif
  31580. static struct winMemData win_mem_data = {
  31581. #ifndef NDEBUG
  31582. WINMEM_MAGIC1,
  31583. #endif
  31584. NULL, FALSE
  31585. #ifndef NDEBUG
  31586. ,WINMEM_MAGIC2
  31587. #endif
  31588. };
  31589. #ifndef NDEBUG
  31590. #define winMemAssertMagic1() assert( win_mem_data.magic1==WINMEM_MAGIC1 )
  31591. #define winMemAssertMagic2() assert( win_mem_data.magic2==WINMEM_MAGIC2 )
  31592. #define winMemAssertMagic() winMemAssertMagic1(); winMemAssertMagic2();
  31593. #else
  31594. #define winMemAssertMagic()
  31595. #endif
  31596. #define winMemGetDataPtr() &win_mem_data
  31597. #define winMemGetHeap() win_mem_data.hHeap
  31598. #define winMemGetOwned() win_mem_data.bOwned
  31599. static void *winMemMalloc(int nBytes);
  31600. static void winMemFree(void *pPrior);
  31601. static void *winMemRealloc(void *pPrior, int nBytes);
  31602. static int winMemSize(void *p);
  31603. static int winMemRoundup(int n);
  31604. static int winMemInit(void *pAppData);
  31605. static void winMemShutdown(void *pAppData);
  31606. SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetWin32(void);
  31607. #endif /* SQLITE_WIN32_MALLOC */
  31608. /*
  31609. ** The following variable is (normally) set once and never changes
  31610. ** thereafter. It records whether the operating system is Win9x
  31611. ** or WinNT.
  31612. **
  31613. ** 0: Operating system unknown.
  31614. ** 1: Operating system is Win9x.
  31615. ** 2: Operating system is WinNT.
  31616. **
  31617. ** In order to facilitate testing on a WinNT system, the test fixture
  31618. ** can manually set this value to 1 to emulate Win98 behavior.
  31619. */
  31620. #ifdef SQLITE_TEST
  31621. SQLITE_API LONG SQLITE_WIN32_VOLATILE sqlite3_os_type = 0;
  31622. #else
  31623. static LONG SQLITE_WIN32_VOLATILE sqlite3_os_type = 0;
  31624. #endif
  31625. #ifndef SYSCALL
  31626. # define SYSCALL sqlite3_syscall_ptr
  31627. #endif
  31628. /*
  31629. ** This function is not available on Windows CE or WinRT.
  31630. */
  31631. #if SQLITE_OS_WINCE || SQLITE_OS_WINRT
  31632. # define osAreFileApisANSI() 1
  31633. #endif
  31634. /*
  31635. ** Many system calls are accessed through pointer-to-functions so that
  31636. ** they may be overridden at runtime to facilitate fault injection during
  31637. ** testing and sandboxing. The following array holds the names and pointers
  31638. ** to all overrideable system calls.
  31639. */
  31640. static struct win_syscall {
  31641. const char *zName; /* Name of the system call */
  31642. sqlite3_syscall_ptr pCurrent; /* Current value of the system call */
  31643. sqlite3_syscall_ptr pDefault; /* Default value */
  31644. } aSyscall[] = {
  31645. #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT
  31646. { "AreFileApisANSI", (SYSCALL)AreFileApisANSI, 0 },
  31647. #else
  31648. { "AreFileApisANSI", (SYSCALL)0, 0 },
  31649. #endif
  31650. #ifndef osAreFileApisANSI
  31651. #define osAreFileApisANSI ((BOOL(WINAPI*)(VOID))aSyscall[0].pCurrent)
  31652. #endif
  31653. #if SQLITE_OS_WINCE && defined(SQLITE_WIN32_HAS_WIDE)
  31654. { "CharLowerW", (SYSCALL)CharLowerW, 0 },
  31655. #else
  31656. { "CharLowerW", (SYSCALL)0, 0 },
  31657. #endif
  31658. #define osCharLowerW ((LPWSTR(WINAPI*)(LPWSTR))aSyscall[1].pCurrent)
  31659. #if SQLITE_OS_WINCE && defined(SQLITE_WIN32_HAS_WIDE)
  31660. { "CharUpperW", (SYSCALL)CharUpperW, 0 },
  31661. #else
  31662. { "CharUpperW", (SYSCALL)0, 0 },
  31663. #endif
  31664. #define osCharUpperW ((LPWSTR(WINAPI*)(LPWSTR))aSyscall[2].pCurrent)
  31665. { "CloseHandle", (SYSCALL)CloseHandle, 0 },
  31666. #define osCloseHandle ((BOOL(WINAPI*)(HANDLE))aSyscall[3].pCurrent)
  31667. #if defined(SQLITE_WIN32_HAS_ANSI)
  31668. { "CreateFileA", (SYSCALL)CreateFileA, 0 },
  31669. #else
  31670. { "CreateFileA", (SYSCALL)0, 0 },
  31671. #endif
  31672. #define osCreateFileA ((HANDLE(WINAPI*)(LPCSTR,DWORD,DWORD, \
  31673. LPSECURITY_ATTRIBUTES,DWORD,DWORD,HANDLE))aSyscall[4].pCurrent)
  31674. #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
  31675. { "CreateFileW", (SYSCALL)CreateFileW, 0 },
  31676. #else
  31677. { "CreateFileW", (SYSCALL)0, 0 },
  31678. #endif
  31679. #define osCreateFileW ((HANDLE(WINAPI*)(LPCWSTR,DWORD,DWORD, \
  31680. LPSECURITY_ATTRIBUTES,DWORD,DWORD,HANDLE))aSyscall[5].pCurrent)
  31681. #if (!SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_ANSI) && \
  31682. (!defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0))
  31683. { "CreateFileMappingA", (SYSCALL)CreateFileMappingA, 0 },
  31684. #else
  31685. { "CreateFileMappingA", (SYSCALL)0, 0 },
  31686. #endif
  31687. #define osCreateFileMappingA ((HANDLE(WINAPI*)(HANDLE,LPSECURITY_ATTRIBUTES, \
  31688. DWORD,DWORD,DWORD,LPCSTR))aSyscall[6].pCurrent)
  31689. #if SQLITE_OS_WINCE || (!SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE) && \
  31690. (!defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0))
  31691. { "CreateFileMappingW", (SYSCALL)CreateFileMappingW, 0 },
  31692. #else
  31693. { "CreateFileMappingW", (SYSCALL)0, 0 },
  31694. #endif
  31695. #define osCreateFileMappingW ((HANDLE(WINAPI*)(HANDLE,LPSECURITY_ATTRIBUTES, \
  31696. DWORD,DWORD,DWORD,LPCWSTR))aSyscall[7].pCurrent)
  31697. #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
  31698. { "CreateMutexW", (SYSCALL)CreateMutexW, 0 },
  31699. #else
  31700. { "CreateMutexW", (SYSCALL)0, 0 },
  31701. #endif
  31702. #define osCreateMutexW ((HANDLE(WINAPI*)(LPSECURITY_ATTRIBUTES,BOOL, \
  31703. LPCWSTR))aSyscall[8].pCurrent)
  31704. #if defined(SQLITE_WIN32_HAS_ANSI)
  31705. { "DeleteFileA", (SYSCALL)DeleteFileA, 0 },
  31706. #else
  31707. { "DeleteFileA", (SYSCALL)0, 0 },
  31708. #endif
  31709. #define osDeleteFileA ((BOOL(WINAPI*)(LPCSTR))aSyscall[9].pCurrent)
  31710. #if defined(SQLITE_WIN32_HAS_WIDE)
  31711. { "DeleteFileW", (SYSCALL)DeleteFileW, 0 },
  31712. #else
  31713. { "DeleteFileW", (SYSCALL)0, 0 },
  31714. #endif
  31715. #define osDeleteFileW ((BOOL(WINAPI*)(LPCWSTR))aSyscall[10].pCurrent)
  31716. #if SQLITE_OS_WINCE
  31717. { "FileTimeToLocalFileTime", (SYSCALL)FileTimeToLocalFileTime, 0 },
  31718. #else
  31719. { "FileTimeToLocalFileTime", (SYSCALL)0, 0 },
  31720. #endif
  31721. #define osFileTimeToLocalFileTime ((BOOL(WINAPI*)(CONST FILETIME*, \
  31722. LPFILETIME))aSyscall[11].pCurrent)
  31723. #if SQLITE_OS_WINCE
  31724. { "FileTimeToSystemTime", (SYSCALL)FileTimeToSystemTime, 0 },
  31725. #else
  31726. { "FileTimeToSystemTime", (SYSCALL)0, 0 },
  31727. #endif
  31728. #define osFileTimeToSystemTime ((BOOL(WINAPI*)(CONST FILETIME*, \
  31729. LPSYSTEMTIME))aSyscall[12].pCurrent)
  31730. { "FlushFileBuffers", (SYSCALL)FlushFileBuffers, 0 },
  31731. #define osFlushFileBuffers ((BOOL(WINAPI*)(HANDLE))aSyscall[13].pCurrent)
  31732. #if defined(SQLITE_WIN32_HAS_ANSI)
  31733. { "FormatMessageA", (SYSCALL)FormatMessageA, 0 },
  31734. #else
  31735. { "FormatMessageA", (SYSCALL)0, 0 },
  31736. #endif
  31737. #define osFormatMessageA ((DWORD(WINAPI*)(DWORD,LPCVOID,DWORD,DWORD,LPSTR, \
  31738. DWORD,va_list*))aSyscall[14].pCurrent)
  31739. #if defined(SQLITE_WIN32_HAS_WIDE)
  31740. { "FormatMessageW", (SYSCALL)FormatMessageW, 0 },
  31741. #else
  31742. { "FormatMessageW", (SYSCALL)0, 0 },
  31743. #endif
  31744. #define osFormatMessageW ((DWORD(WINAPI*)(DWORD,LPCVOID,DWORD,DWORD,LPWSTR, \
  31745. DWORD,va_list*))aSyscall[15].pCurrent)
  31746. #if !defined(SQLITE_OMIT_LOAD_EXTENSION)
  31747. { "FreeLibrary", (SYSCALL)FreeLibrary, 0 },
  31748. #else
  31749. { "FreeLibrary", (SYSCALL)0, 0 },
  31750. #endif
  31751. #define osFreeLibrary ((BOOL(WINAPI*)(HMODULE))aSyscall[16].pCurrent)
  31752. { "GetCurrentProcessId", (SYSCALL)GetCurrentProcessId, 0 },
  31753. #define osGetCurrentProcessId ((DWORD(WINAPI*)(VOID))aSyscall[17].pCurrent)
  31754. #if !SQLITE_OS_WINCE && defined(SQLITE_WIN32_HAS_ANSI)
  31755. { "GetDiskFreeSpaceA", (SYSCALL)GetDiskFreeSpaceA, 0 },
  31756. #else
  31757. { "GetDiskFreeSpaceA", (SYSCALL)0, 0 },
  31758. #endif
  31759. #define osGetDiskFreeSpaceA ((BOOL(WINAPI*)(LPCSTR,LPDWORD,LPDWORD,LPDWORD, \
  31760. LPDWORD))aSyscall[18].pCurrent)
  31761. #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
  31762. { "GetDiskFreeSpaceW", (SYSCALL)GetDiskFreeSpaceW, 0 },
  31763. #else
  31764. { "GetDiskFreeSpaceW", (SYSCALL)0, 0 },
  31765. #endif
  31766. #define osGetDiskFreeSpaceW ((BOOL(WINAPI*)(LPCWSTR,LPDWORD,LPDWORD,LPDWORD, \
  31767. LPDWORD))aSyscall[19].pCurrent)
  31768. #if defined(SQLITE_WIN32_HAS_ANSI)
  31769. { "GetFileAttributesA", (SYSCALL)GetFileAttributesA, 0 },
  31770. #else
  31771. { "GetFileAttributesA", (SYSCALL)0, 0 },
  31772. #endif
  31773. #define osGetFileAttributesA ((DWORD(WINAPI*)(LPCSTR))aSyscall[20].pCurrent)
  31774. #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
  31775. { "GetFileAttributesW", (SYSCALL)GetFileAttributesW, 0 },
  31776. #else
  31777. { "GetFileAttributesW", (SYSCALL)0, 0 },
  31778. #endif
  31779. #define osGetFileAttributesW ((DWORD(WINAPI*)(LPCWSTR))aSyscall[21].pCurrent)
  31780. #if defined(SQLITE_WIN32_HAS_WIDE)
  31781. { "GetFileAttributesExW", (SYSCALL)GetFileAttributesExW, 0 },
  31782. #else
  31783. { "GetFileAttributesExW", (SYSCALL)0, 0 },
  31784. #endif
  31785. #define osGetFileAttributesExW ((BOOL(WINAPI*)(LPCWSTR,GET_FILEEX_INFO_LEVELS, \
  31786. LPVOID))aSyscall[22].pCurrent)
  31787. #if !SQLITE_OS_WINRT
  31788. { "GetFileSize", (SYSCALL)GetFileSize, 0 },
  31789. #else
  31790. { "GetFileSize", (SYSCALL)0, 0 },
  31791. #endif
  31792. #define osGetFileSize ((DWORD(WINAPI*)(HANDLE,LPDWORD))aSyscall[23].pCurrent)
  31793. #if !SQLITE_OS_WINCE && defined(SQLITE_WIN32_HAS_ANSI)
  31794. { "GetFullPathNameA", (SYSCALL)GetFullPathNameA, 0 },
  31795. #else
  31796. { "GetFullPathNameA", (SYSCALL)0, 0 },
  31797. #endif
  31798. #define osGetFullPathNameA ((DWORD(WINAPI*)(LPCSTR,DWORD,LPSTR, \
  31799. LPSTR*))aSyscall[24].pCurrent)
  31800. #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
  31801. { "GetFullPathNameW", (SYSCALL)GetFullPathNameW, 0 },
  31802. #else
  31803. { "GetFullPathNameW", (SYSCALL)0, 0 },
  31804. #endif
  31805. #define osGetFullPathNameW ((DWORD(WINAPI*)(LPCWSTR,DWORD,LPWSTR, \
  31806. LPWSTR*))aSyscall[25].pCurrent)
  31807. { "GetLastError", (SYSCALL)GetLastError, 0 },
  31808. #define osGetLastError ((DWORD(WINAPI*)(VOID))aSyscall[26].pCurrent)
  31809. #if !defined(SQLITE_OMIT_LOAD_EXTENSION)
  31810. #if SQLITE_OS_WINCE
  31811. /* The GetProcAddressA() routine is only available on Windows CE. */
  31812. { "GetProcAddressA", (SYSCALL)GetProcAddressA, 0 },
  31813. #else
  31814. /* All other Windows platforms expect GetProcAddress() to take
  31815. ** an ANSI string regardless of the _UNICODE setting */
  31816. { "GetProcAddressA", (SYSCALL)GetProcAddress, 0 },
  31817. #endif
  31818. #else
  31819. { "GetProcAddressA", (SYSCALL)0, 0 },
  31820. #endif
  31821. #define osGetProcAddressA ((FARPROC(WINAPI*)(HMODULE, \
  31822. LPCSTR))aSyscall[27].pCurrent)
  31823. #if !SQLITE_OS_WINRT
  31824. { "GetSystemInfo", (SYSCALL)GetSystemInfo, 0 },
  31825. #else
  31826. { "GetSystemInfo", (SYSCALL)0, 0 },
  31827. #endif
  31828. #define osGetSystemInfo ((VOID(WINAPI*)(LPSYSTEM_INFO))aSyscall[28].pCurrent)
  31829. { "GetSystemTime", (SYSCALL)GetSystemTime, 0 },
  31830. #define osGetSystemTime ((VOID(WINAPI*)(LPSYSTEMTIME))aSyscall[29].pCurrent)
  31831. #if !SQLITE_OS_WINCE
  31832. { "GetSystemTimeAsFileTime", (SYSCALL)GetSystemTimeAsFileTime, 0 },
  31833. #else
  31834. { "GetSystemTimeAsFileTime", (SYSCALL)0, 0 },
  31835. #endif
  31836. #define osGetSystemTimeAsFileTime ((VOID(WINAPI*)( \
  31837. LPFILETIME))aSyscall[30].pCurrent)
  31838. #if defined(SQLITE_WIN32_HAS_ANSI)
  31839. { "GetTempPathA", (SYSCALL)GetTempPathA, 0 },
  31840. #else
  31841. { "GetTempPathA", (SYSCALL)0, 0 },
  31842. #endif
  31843. #define osGetTempPathA ((DWORD(WINAPI*)(DWORD,LPSTR))aSyscall[31].pCurrent)
  31844. #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
  31845. { "GetTempPathW", (SYSCALL)GetTempPathW, 0 },
  31846. #else
  31847. { "GetTempPathW", (SYSCALL)0, 0 },
  31848. #endif
  31849. #define osGetTempPathW ((DWORD(WINAPI*)(DWORD,LPWSTR))aSyscall[32].pCurrent)
  31850. #if !SQLITE_OS_WINRT
  31851. { "GetTickCount", (SYSCALL)GetTickCount, 0 },
  31852. #else
  31853. { "GetTickCount", (SYSCALL)0, 0 },
  31854. #endif
  31855. #define osGetTickCount ((DWORD(WINAPI*)(VOID))aSyscall[33].pCurrent)
  31856. #if defined(SQLITE_WIN32_HAS_ANSI) && defined(SQLITE_WIN32_GETVERSIONEX) && \
  31857. SQLITE_WIN32_GETVERSIONEX
  31858. { "GetVersionExA", (SYSCALL)GetVersionExA, 0 },
  31859. #else
  31860. { "GetVersionExA", (SYSCALL)0, 0 },
  31861. #endif
  31862. #define osGetVersionExA ((BOOL(WINAPI*)( \
  31863. LPOSVERSIONINFOA))aSyscall[34].pCurrent)
  31864. #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE) && \
  31865. defined(SQLITE_WIN32_GETVERSIONEX) && SQLITE_WIN32_GETVERSIONEX
  31866. { "GetVersionExW", (SYSCALL)GetVersionExW, 0 },
  31867. #else
  31868. { "GetVersionExW", (SYSCALL)0, 0 },
  31869. #endif
  31870. #define osGetVersionExW ((BOOL(WINAPI*)( \
  31871. LPOSVERSIONINFOW))aSyscall[35].pCurrent)
  31872. { "HeapAlloc", (SYSCALL)HeapAlloc, 0 },
  31873. #define osHeapAlloc ((LPVOID(WINAPI*)(HANDLE,DWORD, \
  31874. SIZE_T))aSyscall[36].pCurrent)
  31875. #if !SQLITE_OS_WINRT
  31876. { "HeapCreate", (SYSCALL)HeapCreate, 0 },
  31877. #else
  31878. { "HeapCreate", (SYSCALL)0, 0 },
  31879. #endif
  31880. #define osHeapCreate ((HANDLE(WINAPI*)(DWORD,SIZE_T, \
  31881. SIZE_T))aSyscall[37].pCurrent)
  31882. #if !SQLITE_OS_WINRT
  31883. { "HeapDestroy", (SYSCALL)HeapDestroy, 0 },
  31884. #else
  31885. { "HeapDestroy", (SYSCALL)0, 0 },
  31886. #endif
  31887. #define osHeapDestroy ((BOOL(WINAPI*)(HANDLE))aSyscall[38].pCurrent)
  31888. { "HeapFree", (SYSCALL)HeapFree, 0 },
  31889. #define osHeapFree ((BOOL(WINAPI*)(HANDLE,DWORD,LPVOID))aSyscall[39].pCurrent)
  31890. { "HeapReAlloc", (SYSCALL)HeapReAlloc, 0 },
  31891. #define osHeapReAlloc ((LPVOID(WINAPI*)(HANDLE,DWORD,LPVOID, \
  31892. SIZE_T))aSyscall[40].pCurrent)
  31893. { "HeapSize", (SYSCALL)HeapSize, 0 },
  31894. #define osHeapSize ((SIZE_T(WINAPI*)(HANDLE,DWORD, \
  31895. LPCVOID))aSyscall[41].pCurrent)
  31896. #if !SQLITE_OS_WINRT
  31897. { "HeapValidate", (SYSCALL)HeapValidate, 0 },
  31898. #else
  31899. { "HeapValidate", (SYSCALL)0, 0 },
  31900. #endif
  31901. #define osHeapValidate ((BOOL(WINAPI*)(HANDLE,DWORD, \
  31902. LPCVOID))aSyscall[42].pCurrent)
  31903. #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT
  31904. { "HeapCompact", (SYSCALL)HeapCompact, 0 },
  31905. #else
  31906. { "HeapCompact", (SYSCALL)0, 0 },
  31907. #endif
  31908. #define osHeapCompact ((UINT(WINAPI*)(HANDLE,DWORD))aSyscall[43].pCurrent)
  31909. #if defined(SQLITE_WIN32_HAS_ANSI) && !defined(SQLITE_OMIT_LOAD_EXTENSION)
  31910. { "LoadLibraryA", (SYSCALL)LoadLibraryA, 0 },
  31911. #else
  31912. { "LoadLibraryA", (SYSCALL)0, 0 },
  31913. #endif
  31914. #define osLoadLibraryA ((HMODULE(WINAPI*)(LPCSTR))aSyscall[44].pCurrent)
  31915. #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE) && \
  31916. !defined(SQLITE_OMIT_LOAD_EXTENSION)
  31917. { "LoadLibraryW", (SYSCALL)LoadLibraryW, 0 },
  31918. #else
  31919. { "LoadLibraryW", (SYSCALL)0, 0 },
  31920. #endif
  31921. #define osLoadLibraryW ((HMODULE(WINAPI*)(LPCWSTR))aSyscall[45].pCurrent)
  31922. #if !SQLITE_OS_WINRT
  31923. { "LocalFree", (SYSCALL)LocalFree, 0 },
  31924. #else
  31925. { "LocalFree", (SYSCALL)0, 0 },
  31926. #endif
  31927. #define osLocalFree ((HLOCAL(WINAPI*)(HLOCAL))aSyscall[46].pCurrent)
  31928. #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT
  31929. { "LockFile", (SYSCALL)LockFile, 0 },
  31930. #else
  31931. { "LockFile", (SYSCALL)0, 0 },
  31932. #endif
  31933. #ifndef osLockFile
  31934. #define osLockFile ((BOOL(WINAPI*)(HANDLE,DWORD,DWORD,DWORD, \
  31935. DWORD))aSyscall[47].pCurrent)
  31936. #endif
  31937. #if !SQLITE_OS_WINCE
  31938. { "LockFileEx", (SYSCALL)LockFileEx, 0 },
  31939. #else
  31940. { "LockFileEx", (SYSCALL)0, 0 },
  31941. #endif
  31942. #ifndef osLockFileEx
  31943. #define osLockFileEx ((BOOL(WINAPI*)(HANDLE,DWORD,DWORD,DWORD,DWORD, \
  31944. LPOVERLAPPED))aSyscall[48].pCurrent)
  31945. #endif
  31946. #if SQLITE_OS_WINCE || (!SQLITE_OS_WINRT && \
  31947. (!defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0))
  31948. { "MapViewOfFile", (SYSCALL)MapViewOfFile, 0 },
  31949. #else
  31950. { "MapViewOfFile", (SYSCALL)0, 0 },
  31951. #endif
  31952. #define osMapViewOfFile ((LPVOID(WINAPI*)(HANDLE,DWORD,DWORD,DWORD, \
  31953. SIZE_T))aSyscall[49].pCurrent)
  31954. { "MultiByteToWideChar", (SYSCALL)MultiByteToWideChar, 0 },
  31955. #define osMultiByteToWideChar ((int(WINAPI*)(UINT,DWORD,LPCSTR,int,LPWSTR, \
  31956. int))aSyscall[50].pCurrent)
  31957. { "QueryPerformanceCounter", (SYSCALL)QueryPerformanceCounter, 0 },
  31958. #define osQueryPerformanceCounter ((BOOL(WINAPI*)( \
  31959. LARGE_INTEGER*))aSyscall[51].pCurrent)
  31960. { "ReadFile", (SYSCALL)ReadFile, 0 },
  31961. #define osReadFile ((BOOL(WINAPI*)(HANDLE,LPVOID,DWORD,LPDWORD, \
  31962. LPOVERLAPPED))aSyscall[52].pCurrent)
  31963. { "SetEndOfFile", (SYSCALL)SetEndOfFile, 0 },
  31964. #define osSetEndOfFile ((BOOL(WINAPI*)(HANDLE))aSyscall[53].pCurrent)
  31965. #if !SQLITE_OS_WINRT
  31966. { "SetFilePointer", (SYSCALL)SetFilePointer, 0 },
  31967. #else
  31968. { "SetFilePointer", (SYSCALL)0, 0 },
  31969. #endif
  31970. #define osSetFilePointer ((DWORD(WINAPI*)(HANDLE,LONG,PLONG, \
  31971. DWORD))aSyscall[54].pCurrent)
  31972. #if !SQLITE_OS_WINRT
  31973. { "Sleep", (SYSCALL)Sleep, 0 },
  31974. #else
  31975. { "Sleep", (SYSCALL)0, 0 },
  31976. #endif
  31977. #define osSleep ((VOID(WINAPI*)(DWORD))aSyscall[55].pCurrent)
  31978. { "SystemTimeToFileTime", (SYSCALL)SystemTimeToFileTime, 0 },
  31979. #define osSystemTimeToFileTime ((BOOL(WINAPI*)(CONST SYSTEMTIME*, \
  31980. LPFILETIME))aSyscall[56].pCurrent)
  31981. #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT
  31982. { "UnlockFile", (SYSCALL)UnlockFile, 0 },
  31983. #else
  31984. { "UnlockFile", (SYSCALL)0, 0 },
  31985. #endif
  31986. #ifndef osUnlockFile
  31987. #define osUnlockFile ((BOOL(WINAPI*)(HANDLE,DWORD,DWORD,DWORD, \
  31988. DWORD))aSyscall[57].pCurrent)
  31989. #endif
  31990. #if !SQLITE_OS_WINCE
  31991. { "UnlockFileEx", (SYSCALL)UnlockFileEx, 0 },
  31992. #else
  31993. { "UnlockFileEx", (SYSCALL)0, 0 },
  31994. #endif
  31995. #define osUnlockFileEx ((BOOL(WINAPI*)(HANDLE,DWORD,DWORD,DWORD, \
  31996. LPOVERLAPPED))aSyscall[58].pCurrent)
  31997. #if SQLITE_OS_WINCE || !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
  31998. { "UnmapViewOfFile", (SYSCALL)UnmapViewOfFile, 0 },
  31999. #else
  32000. { "UnmapViewOfFile", (SYSCALL)0, 0 },
  32001. #endif
  32002. #define osUnmapViewOfFile ((BOOL(WINAPI*)(LPCVOID))aSyscall[59].pCurrent)
  32003. { "WideCharToMultiByte", (SYSCALL)WideCharToMultiByte, 0 },
  32004. #define osWideCharToMultiByte ((int(WINAPI*)(UINT,DWORD,LPCWSTR,int,LPSTR,int, \
  32005. LPCSTR,LPBOOL))aSyscall[60].pCurrent)
  32006. { "WriteFile", (SYSCALL)WriteFile, 0 },
  32007. #define osWriteFile ((BOOL(WINAPI*)(HANDLE,LPCVOID,DWORD,LPDWORD, \
  32008. LPOVERLAPPED))aSyscall[61].pCurrent)
  32009. #if SQLITE_OS_WINRT
  32010. { "CreateEventExW", (SYSCALL)CreateEventExW, 0 },
  32011. #else
  32012. { "CreateEventExW", (SYSCALL)0, 0 },
  32013. #endif
  32014. #define osCreateEventExW ((HANDLE(WINAPI*)(LPSECURITY_ATTRIBUTES,LPCWSTR, \
  32015. DWORD,DWORD))aSyscall[62].pCurrent)
  32016. #if !SQLITE_OS_WINRT
  32017. { "WaitForSingleObject", (SYSCALL)WaitForSingleObject, 0 },
  32018. #else
  32019. { "WaitForSingleObject", (SYSCALL)0, 0 },
  32020. #endif
  32021. #define osWaitForSingleObject ((DWORD(WINAPI*)(HANDLE, \
  32022. DWORD))aSyscall[63].pCurrent)
  32023. #if !SQLITE_OS_WINCE
  32024. { "WaitForSingleObjectEx", (SYSCALL)WaitForSingleObjectEx, 0 },
  32025. #else
  32026. { "WaitForSingleObjectEx", (SYSCALL)0, 0 },
  32027. #endif
  32028. #define osWaitForSingleObjectEx ((DWORD(WINAPI*)(HANDLE,DWORD, \
  32029. BOOL))aSyscall[64].pCurrent)
  32030. #if SQLITE_OS_WINRT
  32031. { "SetFilePointerEx", (SYSCALL)SetFilePointerEx, 0 },
  32032. #else
  32033. { "SetFilePointerEx", (SYSCALL)0, 0 },
  32034. #endif
  32035. #define osSetFilePointerEx ((BOOL(WINAPI*)(HANDLE,LARGE_INTEGER, \
  32036. PLARGE_INTEGER,DWORD))aSyscall[65].pCurrent)
  32037. #if SQLITE_OS_WINRT
  32038. { "GetFileInformationByHandleEx", (SYSCALL)GetFileInformationByHandleEx, 0 },
  32039. #else
  32040. { "GetFileInformationByHandleEx", (SYSCALL)0, 0 },
  32041. #endif
  32042. #define osGetFileInformationByHandleEx ((BOOL(WINAPI*)(HANDLE, \
  32043. FILE_INFO_BY_HANDLE_CLASS,LPVOID,DWORD))aSyscall[66].pCurrent)
  32044. #if SQLITE_OS_WINRT && (!defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0)
  32045. { "MapViewOfFileFromApp", (SYSCALL)MapViewOfFileFromApp, 0 },
  32046. #else
  32047. { "MapViewOfFileFromApp", (SYSCALL)0, 0 },
  32048. #endif
  32049. #define osMapViewOfFileFromApp ((LPVOID(WINAPI*)(HANDLE,ULONG,ULONG64, \
  32050. SIZE_T))aSyscall[67].pCurrent)
  32051. #if SQLITE_OS_WINRT
  32052. { "CreateFile2", (SYSCALL)CreateFile2, 0 },
  32053. #else
  32054. { "CreateFile2", (SYSCALL)0, 0 },
  32055. #endif
  32056. #define osCreateFile2 ((HANDLE(WINAPI*)(LPCWSTR,DWORD,DWORD,DWORD, \
  32057. LPCREATEFILE2_EXTENDED_PARAMETERS))aSyscall[68].pCurrent)
  32058. #if SQLITE_OS_WINRT && !defined(SQLITE_OMIT_LOAD_EXTENSION)
  32059. { "LoadPackagedLibrary", (SYSCALL)LoadPackagedLibrary, 0 },
  32060. #else
  32061. { "LoadPackagedLibrary", (SYSCALL)0, 0 },
  32062. #endif
  32063. #define osLoadPackagedLibrary ((HMODULE(WINAPI*)(LPCWSTR, \
  32064. DWORD))aSyscall[69].pCurrent)
  32065. #if SQLITE_OS_WINRT
  32066. { "GetTickCount64", (SYSCALL)GetTickCount64, 0 },
  32067. #else
  32068. { "GetTickCount64", (SYSCALL)0, 0 },
  32069. #endif
  32070. #define osGetTickCount64 ((ULONGLONG(WINAPI*)(VOID))aSyscall[70].pCurrent)
  32071. #if SQLITE_OS_WINRT
  32072. { "GetNativeSystemInfo", (SYSCALL)GetNativeSystemInfo, 0 },
  32073. #else
  32074. { "GetNativeSystemInfo", (SYSCALL)0, 0 },
  32075. #endif
  32076. #define osGetNativeSystemInfo ((VOID(WINAPI*)( \
  32077. LPSYSTEM_INFO))aSyscall[71].pCurrent)
  32078. #if defined(SQLITE_WIN32_HAS_ANSI)
  32079. { "OutputDebugStringA", (SYSCALL)OutputDebugStringA, 0 },
  32080. #else
  32081. { "OutputDebugStringA", (SYSCALL)0, 0 },
  32082. #endif
  32083. #define osOutputDebugStringA ((VOID(WINAPI*)(LPCSTR))aSyscall[72].pCurrent)
  32084. #if defined(SQLITE_WIN32_HAS_WIDE)
  32085. { "OutputDebugStringW", (SYSCALL)OutputDebugStringW, 0 },
  32086. #else
  32087. { "OutputDebugStringW", (SYSCALL)0, 0 },
  32088. #endif
  32089. #define osOutputDebugStringW ((VOID(WINAPI*)(LPCWSTR))aSyscall[73].pCurrent)
  32090. { "GetProcessHeap", (SYSCALL)GetProcessHeap, 0 },
  32091. #define osGetProcessHeap ((HANDLE(WINAPI*)(VOID))aSyscall[74].pCurrent)
  32092. #if SQLITE_OS_WINRT && (!defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0)
  32093. { "CreateFileMappingFromApp", (SYSCALL)CreateFileMappingFromApp, 0 },
  32094. #else
  32095. { "CreateFileMappingFromApp", (SYSCALL)0, 0 },
  32096. #endif
  32097. #define osCreateFileMappingFromApp ((HANDLE(WINAPI*)(HANDLE, \
  32098. LPSECURITY_ATTRIBUTES,ULONG,ULONG64,LPCWSTR))aSyscall[75].pCurrent)
  32099. /*
  32100. ** NOTE: On some sub-platforms, the InterlockedCompareExchange "function"
  32101. ** is really just a macro that uses a compiler intrinsic (e.g. x64).
  32102. ** So do not try to make this is into a redefinable interface.
  32103. */
  32104. #if defined(InterlockedCompareExchange)
  32105. { "InterlockedCompareExchange", (SYSCALL)0, 0 },
  32106. #define osInterlockedCompareExchange InterlockedCompareExchange
  32107. #else
  32108. { "InterlockedCompareExchange", (SYSCALL)InterlockedCompareExchange, 0 },
  32109. #define osInterlockedCompareExchange ((LONG(WINAPI*)(LONG \
  32110. SQLITE_WIN32_VOLATILE*, LONG,LONG))aSyscall[76].pCurrent)
  32111. #endif /* defined(InterlockedCompareExchange) */
  32112. #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && SQLITE_WIN32_USE_UUID
  32113. { "UuidCreate", (SYSCALL)UuidCreate, 0 },
  32114. #else
  32115. { "UuidCreate", (SYSCALL)0, 0 },
  32116. #endif
  32117. #define osUuidCreate ((RPC_STATUS(RPC_ENTRY*)(UUID*))aSyscall[77].pCurrent)
  32118. #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && SQLITE_WIN32_USE_UUID
  32119. { "UuidCreateSequential", (SYSCALL)UuidCreateSequential, 0 },
  32120. #else
  32121. { "UuidCreateSequential", (SYSCALL)0, 0 },
  32122. #endif
  32123. #define osUuidCreateSequential \
  32124. ((RPC_STATUS(RPC_ENTRY*)(UUID*))aSyscall[78].pCurrent)
  32125. #if !defined(SQLITE_NO_SYNC) && SQLITE_MAX_MMAP_SIZE>0
  32126. { "FlushViewOfFile", (SYSCALL)FlushViewOfFile, 0 },
  32127. #else
  32128. { "FlushViewOfFile", (SYSCALL)0, 0 },
  32129. #endif
  32130. #define osFlushViewOfFile \
  32131. ((BOOL(WINAPI*)(LPCVOID,SIZE_T))aSyscall[79].pCurrent)
  32132. }; /* End of the overrideable system calls */
  32133. /*
  32134. ** This is the xSetSystemCall() method of sqlite3_vfs for all of the
  32135. ** "win32" VFSes. Return SQLITE_OK opon successfully updating the
  32136. ** system call pointer, or SQLITE_NOTFOUND if there is no configurable
  32137. ** system call named zName.
  32138. */
  32139. static int winSetSystemCall(
  32140. sqlite3_vfs *pNotUsed, /* The VFS pointer. Not used */
  32141. const char *zName, /* Name of system call to override */
  32142. sqlite3_syscall_ptr pNewFunc /* Pointer to new system call value */
  32143. ){
  32144. unsigned int i;
  32145. int rc = SQLITE_NOTFOUND;
  32146. UNUSED_PARAMETER(pNotUsed);
  32147. if( zName==0 ){
  32148. /* If no zName is given, restore all system calls to their default
  32149. ** settings and return NULL
  32150. */
  32151. rc = SQLITE_OK;
  32152. for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
  32153. if( aSyscall[i].pDefault ){
  32154. aSyscall[i].pCurrent = aSyscall[i].pDefault;
  32155. }
  32156. }
  32157. }else{
  32158. /* If zName is specified, operate on only the one system call
  32159. ** specified.
  32160. */
  32161. for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
  32162. if( strcmp(zName, aSyscall[i].zName)==0 ){
  32163. if( aSyscall[i].pDefault==0 ){
  32164. aSyscall[i].pDefault = aSyscall[i].pCurrent;
  32165. }
  32166. rc = SQLITE_OK;
  32167. if( pNewFunc==0 ) pNewFunc = aSyscall[i].pDefault;
  32168. aSyscall[i].pCurrent = pNewFunc;
  32169. break;
  32170. }
  32171. }
  32172. }
  32173. return rc;
  32174. }
  32175. /*
  32176. ** Return the value of a system call. Return NULL if zName is not a
  32177. ** recognized system call name. NULL is also returned if the system call
  32178. ** is currently undefined.
  32179. */
  32180. static sqlite3_syscall_ptr winGetSystemCall(
  32181. sqlite3_vfs *pNotUsed,
  32182. const char *zName
  32183. ){
  32184. unsigned int i;
  32185. UNUSED_PARAMETER(pNotUsed);
  32186. for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
  32187. if( strcmp(zName, aSyscall[i].zName)==0 ) return aSyscall[i].pCurrent;
  32188. }
  32189. return 0;
  32190. }
  32191. /*
  32192. ** Return the name of the first system call after zName. If zName==NULL
  32193. ** then return the name of the first system call. Return NULL if zName
  32194. ** is the last system call or if zName is not the name of a valid
  32195. ** system call.
  32196. */
  32197. static const char *winNextSystemCall(sqlite3_vfs *p, const char *zName){
  32198. int i = -1;
  32199. UNUSED_PARAMETER(p);
  32200. if( zName ){
  32201. for(i=0; i<ArraySize(aSyscall)-1; i++){
  32202. if( strcmp(zName, aSyscall[i].zName)==0 ) break;
  32203. }
  32204. }
  32205. for(i++; i<ArraySize(aSyscall); i++){
  32206. if( aSyscall[i].pCurrent!=0 ) return aSyscall[i].zName;
  32207. }
  32208. return 0;
  32209. }
  32210. #ifdef SQLITE_WIN32_MALLOC
  32211. /*
  32212. ** If a Win32 native heap has been configured, this function will attempt to
  32213. ** compact it. Upon success, SQLITE_OK will be returned. Upon failure, one
  32214. ** of SQLITE_NOMEM, SQLITE_ERROR, or SQLITE_NOTFOUND will be returned. The
  32215. ** "pnLargest" argument, if non-zero, will be used to return the size of the
  32216. ** largest committed free block in the heap, in bytes.
  32217. */
  32218. SQLITE_API int SQLITE_STDCALL sqlite3_win32_compact_heap(LPUINT pnLargest){
  32219. int rc = SQLITE_OK;
  32220. UINT nLargest = 0;
  32221. HANDLE hHeap;
  32222. winMemAssertMagic();
  32223. hHeap = winMemGetHeap();
  32224. assert( hHeap!=0 );
  32225. assert( hHeap!=INVALID_HANDLE_VALUE );
  32226. #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
  32227. assert( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, NULL) );
  32228. #endif
  32229. #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT
  32230. if( (nLargest=osHeapCompact(hHeap, SQLITE_WIN32_HEAP_FLAGS))==0 ){
  32231. DWORD lastErrno = osGetLastError();
  32232. if( lastErrno==NO_ERROR ){
  32233. sqlite3_log(SQLITE_NOMEM, "failed to HeapCompact (no space), heap=%p",
  32234. (void*)hHeap);
  32235. rc = SQLITE_NOMEM;
  32236. }else{
  32237. sqlite3_log(SQLITE_ERROR, "failed to HeapCompact (%lu), heap=%p",
  32238. osGetLastError(), (void*)hHeap);
  32239. rc = SQLITE_ERROR;
  32240. }
  32241. }
  32242. #else
  32243. sqlite3_log(SQLITE_NOTFOUND, "failed to HeapCompact, heap=%p",
  32244. (void*)hHeap);
  32245. rc = SQLITE_NOTFOUND;
  32246. #endif
  32247. if( pnLargest ) *pnLargest = nLargest;
  32248. return rc;
  32249. }
  32250. /*
  32251. ** If a Win32 native heap has been configured, this function will attempt to
  32252. ** destroy and recreate it. If the Win32 native heap is not isolated and/or
  32253. ** the sqlite3_memory_used() function does not return zero, SQLITE_BUSY will
  32254. ** be returned and no changes will be made to the Win32 native heap.
  32255. */
  32256. SQLITE_API int SQLITE_STDCALL sqlite3_win32_reset_heap(){
  32257. int rc;
  32258. MUTEX_LOGIC( sqlite3_mutex *pMaster; ) /* The main static mutex */
  32259. MUTEX_LOGIC( sqlite3_mutex *pMem; ) /* The memsys static mutex */
  32260. MUTEX_LOGIC( pMaster = sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_MASTER); )
  32261. MUTEX_LOGIC( pMem = sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_MEM); )
  32262. sqlite3_mutex_enter(pMaster);
  32263. sqlite3_mutex_enter(pMem);
  32264. winMemAssertMagic();
  32265. if( winMemGetHeap()!=NULL && winMemGetOwned() && sqlite3_memory_used()==0 ){
  32266. /*
  32267. ** At this point, there should be no outstanding memory allocations on
  32268. ** the heap. Also, since both the master and memsys locks are currently
  32269. ** being held by us, no other function (i.e. from another thread) should
  32270. ** be able to even access the heap. Attempt to destroy and recreate our
  32271. ** isolated Win32 native heap now.
  32272. */
  32273. assert( winMemGetHeap()!=NULL );
  32274. assert( winMemGetOwned() );
  32275. assert( sqlite3_memory_used()==0 );
  32276. winMemShutdown(winMemGetDataPtr());
  32277. assert( winMemGetHeap()==NULL );
  32278. assert( !winMemGetOwned() );
  32279. assert( sqlite3_memory_used()==0 );
  32280. rc = winMemInit(winMemGetDataPtr());
  32281. assert( rc!=SQLITE_OK || winMemGetHeap()!=NULL );
  32282. assert( rc!=SQLITE_OK || winMemGetOwned() );
  32283. assert( rc!=SQLITE_OK || sqlite3_memory_used()==0 );
  32284. }else{
  32285. /*
  32286. ** The Win32 native heap cannot be modified because it may be in use.
  32287. */
  32288. rc = SQLITE_BUSY;
  32289. }
  32290. sqlite3_mutex_leave(pMem);
  32291. sqlite3_mutex_leave(pMaster);
  32292. return rc;
  32293. }
  32294. #endif /* SQLITE_WIN32_MALLOC */
  32295. /*
  32296. ** This function outputs the specified (ANSI) string to the Win32 debugger
  32297. ** (if available).
  32298. */
  32299. SQLITE_API void SQLITE_STDCALL sqlite3_win32_write_debug(const char *zBuf, int nBuf){
  32300. char zDbgBuf[SQLITE_WIN32_DBG_BUF_SIZE];
  32301. int nMin = MIN(nBuf, (SQLITE_WIN32_DBG_BUF_SIZE - 1)); /* may be negative. */
  32302. if( nMin<-1 ) nMin = -1; /* all negative values become -1. */
  32303. assert( nMin==-1 || nMin==0 || nMin<SQLITE_WIN32_DBG_BUF_SIZE );
  32304. #if defined(SQLITE_WIN32_HAS_ANSI)
  32305. if( nMin>0 ){
  32306. memset(zDbgBuf, 0, SQLITE_WIN32_DBG_BUF_SIZE);
  32307. memcpy(zDbgBuf, zBuf, nMin);
  32308. osOutputDebugStringA(zDbgBuf);
  32309. }else{
  32310. osOutputDebugStringA(zBuf);
  32311. }
  32312. #elif defined(SQLITE_WIN32_HAS_WIDE)
  32313. memset(zDbgBuf, 0, SQLITE_WIN32_DBG_BUF_SIZE);
  32314. if ( osMultiByteToWideChar(
  32315. osAreFileApisANSI() ? CP_ACP : CP_OEMCP, 0, zBuf,
  32316. nMin, (LPWSTR)zDbgBuf, SQLITE_WIN32_DBG_BUF_SIZE/sizeof(WCHAR))<=0 ){
  32317. return;
  32318. }
  32319. osOutputDebugStringW((LPCWSTR)zDbgBuf);
  32320. #else
  32321. if( nMin>0 ){
  32322. memset(zDbgBuf, 0, SQLITE_WIN32_DBG_BUF_SIZE);
  32323. memcpy(zDbgBuf, zBuf, nMin);
  32324. fprintf(stderr, "%s", zDbgBuf);
  32325. }else{
  32326. fprintf(stderr, "%s", zBuf);
  32327. }
  32328. #endif
  32329. }
  32330. /*
  32331. ** The following routine suspends the current thread for at least ms
  32332. ** milliseconds. This is equivalent to the Win32 Sleep() interface.
  32333. */
  32334. #if SQLITE_OS_WINRT
  32335. static HANDLE sleepObj = NULL;
  32336. #endif
  32337. SQLITE_API void SQLITE_STDCALL sqlite3_win32_sleep(DWORD milliseconds){
  32338. #if SQLITE_OS_WINRT
  32339. if ( sleepObj==NULL ){
  32340. sleepObj = osCreateEventExW(NULL, NULL, CREATE_EVENT_MANUAL_RESET,
  32341. SYNCHRONIZE);
  32342. }
  32343. assert( sleepObj!=NULL );
  32344. osWaitForSingleObjectEx(sleepObj, milliseconds, FALSE);
  32345. #else
  32346. osSleep(milliseconds);
  32347. #endif
  32348. }
  32349. #if SQLITE_MAX_WORKER_THREADS>0 && !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && \
  32350. SQLITE_THREADSAFE>0
  32351. SQLITE_PRIVATE DWORD sqlite3Win32Wait(HANDLE hObject){
  32352. DWORD rc;
  32353. while( (rc = osWaitForSingleObjectEx(hObject, INFINITE,
  32354. TRUE))==WAIT_IO_COMPLETION ){}
  32355. return rc;
  32356. }
  32357. #endif
  32358. /*
  32359. ** Return true (non-zero) if we are running under WinNT, Win2K, WinXP,
  32360. ** or WinCE. Return false (zero) for Win95, Win98, or WinME.
  32361. **
  32362. ** Here is an interesting observation: Win95, Win98, and WinME lack
  32363. ** the LockFileEx() API. But we can still statically link against that
  32364. ** API as long as we don't call it when running Win95/98/ME. A call to
  32365. ** this routine is used to determine if the host is Win95/98/ME or
  32366. ** WinNT/2K/XP so that we will know whether or not we can safely call
  32367. ** the LockFileEx() API.
  32368. */
  32369. #if !defined(SQLITE_WIN32_GETVERSIONEX) || !SQLITE_WIN32_GETVERSIONEX
  32370. # define osIsNT() (1)
  32371. #elif SQLITE_OS_WINCE || SQLITE_OS_WINRT || !defined(SQLITE_WIN32_HAS_ANSI)
  32372. # define osIsNT() (1)
  32373. #elif !defined(SQLITE_WIN32_HAS_WIDE)
  32374. # define osIsNT() (0)
  32375. #else
  32376. # define osIsNT() ((sqlite3_os_type==2) || sqlite3_win32_is_nt())
  32377. #endif
  32378. /*
  32379. ** This function determines if the machine is running a version of Windows
  32380. ** based on the NT kernel.
  32381. */
  32382. SQLITE_API int SQLITE_STDCALL sqlite3_win32_is_nt(void){
  32383. #if SQLITE_OS_WINRT
  32384. /*
  32385. ** NOTE: The WinRT sub-platform is always assumed to be based on the NT
  32386. ** kernel.
  32387. */
  32388. return 1;
  32389. #elif defined(SQLITE_WIN32_GETVERSIONEX) && SQLITE_WIN32_GETVERSIONEX
  32390. if( osInterlockedCompareExchange(&sqlite3_os_type, 0, 0)==0 ){
  32391. #if defined(SQLITE_WIN32_HAS_ANSI)
  32392. OSVERSIONINFOA sInfo;
  32393. sInfo.dwOSVersionInfoSize = sizeof(sInfo);
  32394. osGetVersionExA(&sInfo);
  32395. osInterlockedCompareExchange(&sqlite3_os_type,
  32396. (sInfo.dwPlatformId == VER_PLATFORM_WIN32_NT) ? 2 : 1, 0);
  32397. #elif defined(SQLITE_WIN32_HAS_WIDE)
  32398. OSVERSIONINFOW sInfo;
  32399. sInfo.dwOSVersionInfoSize = sizeof(sInfo);
  32400. osGetVersionExW(&sInfo);
  32401. osInterlockedCompareExchange(&sqlite3_os_type,
  32402. (sInfo.dwPlatformId == VER_PLATFORM_WIN32_NT) ? 2 : 1, 0);
  32403. #endif
  32404. }
  32405. return osInterlockedCompareExchange(&sqlite3_os_type, 2, 2)==2;
  32406. #elif SQLITE_TEST
  32407. return osInterlockedCompareExchange(&sqlite3_os_type, 2, 2)==2;
  32408. #else
  32409. /*
  32410. ** NOTE: All sub-platforms where the GetVersionEx[AW] functions are
  32411. ** deprecated are always assumed to be based on the NT kernel.
  32412. */
  32413. return 1;
  32414. #endif
  32415. }
  32416. #ifdef SQLITE_WIN32_MALLOC
  32417. /*
  32418. ** Allocate nBytes of memory.
  32419. */
  32420. static void *winMemMalloc(int nBytes){
  32421. HANDLE hHeap;
  32422. void *p;
  32423. winMemAssertMagic();
  32424. hHeap = winMemGetHeap();
  32425. assert( hHeap!=0 );
  32426. assert( hHeap!=INVALID_HANDLE_VALUE );
  32427. #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
  32428. assert( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, NULL) );
  32429. #endif
  32430. assert( nBytes>=0 );
  32431. p = osHeapAlloc(hHeap, SQLITE_WIN32_HEAP_FLAGS, (SIZE_T)nBytes);
  32432. if( !p ){
  32433. sqlite3_log(SQLITE_NOMEM, "failed to HeapAlloc %u bytes (%lu), heap=%p",
  32434. nBytes, osGetLastError(), (void*)hHeap);
  32435. }
  32436. return p;
  32437. }
  32438. /*
  32439. ** Free memory.
  32440. */
  32441. static void winMemFree(void *pPrior){
  32442. HANDLE hHeap;
  32443. winMemAssertMagic();
  32444. hHeap = winMemGetHeap();
  32445. assert( hHeap!=0 );
  32446. assert( hHeap!=INVALID_HANDLE_VALUE );
  32447. #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
  32448. assert( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior) );
  32449. #endif
  32450. if( !pPrior ) return; /* Passing NULL to HeapFree is undefined. */
  32451. if( !osHeapFree(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior) ){
  32452. sqlite3_log(SQLITE_NOMEM, "failed to HeapFree block %p (%lu), heap=%p",
  32453. pPrior, osGetLastError(), (void*)hHeap);
  32454. }
  32455. }
  32456. /*
  32457. ** Change the size of an existing memory allocation
  32458. */
  32459. static void *winMemRealloc(void *pPrior, int nBytes){
  32460. HANDLE hHeap;
  32461. void *p;
  32462. winMemAssertMagic();
  32463. hHeap = winMemGetHeap();
  32464. assert( hHeap!=0 );
  32465. assert( hHeap!=INVALID_HANDLE_VALUE );
  32466. #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
  32467. assert( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior) );
  32468. #endif
  32469. assert( nBytes>=0 );
  32470. if( !pPrior ){
  32471. p = osHeapAlloc(hHeap, SQLITE_WIN32_HEAP_FLAGS, (SIZE_T)nBytes);
  32472. }else{
  32473. p = osHeapReAlloc(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior, (SIZE_T)nBytes);
  32474. }
  32475. if( !p ){
  32476. sqlite3_log(SQLITE_NOMEM, "failed to %s %u bytes (%lu), heap=%p",
  32477. pPrior ? "HeapReAlloc" : "HeapAlloc", nBytes, osGetLastError(),
  32478. (void*)hHeap);
  32479. }
  32480. return p;
  32481. }
  32482. /*
  32483. ** Return the size of an outstanding allocation, in bytes.
  32484. */
  32485. static int winMemSize(void *p){
  32486. HANDLE hHeap;
  32487. SIZE_T n;
  32488. winMemAssertMagic();
  32489. hHeap = winMemGetHeap();
  32490. assert( hHeap!=0 );
  32491. assert( hHeap!=INVALID_HANDLE_VALUE );
  32492. #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
  32493. assert( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, p) );
  32494. #endif
  32495. if( !p ) return 0;
  32496. n = osHeapSize(hHeap, SQLITE_WIN32_HEAP_FLAGS, p);
  32497. if( n==(SIZE_T)-1 ){
  32498. sqlite3_log(SQLITE_NOMEM, "failed to HeapSize block %p (%lu), heap=%p",
  32499. p, osGetLastError(), (void*)hHeap);
  32500. return 0;
  32501. }
  32502. return (int)n;
  32503. }
  32504. /*
  32505. ** Round up a request size to the next valid allocation size.
  32506. */
  32507. static int winMemRoundup(int n){
  32508. return n;
  32509. }
  32510. /*
  32511. ** Initialize this module.
  32512. */
  32513. static int winMemInit(void *pAppData){
  32514. winMemData *pWinMemData = (winMemData *)pAppData;
  32515. if( !pWinMemData ) return SQLITE_ERROR;
  32516. assert( pWinMemData->magic1==WINMEM_MAGIC1 );
  32517. assert( pWinMemData->magic2==WINMEM_MAGIC2 );
  32518. #if !SQLITE_OS_WINRT && SQLITE_WIN32_HEAP_CREATE
  32519. if( !pWinMemData->hHeap ){
  32520. DWORD dwInitialSize = SQLITE_WIN32_HEAP_INIT_SIZE;
  32521. DWORD dwMaximumSize = (DWORD)sqlite3GlobalConfig.nHeap;
  32522. if( dwMaximumSize==0 ){
  32523. dwMaximumSize = SQLITE_WIN32_HEAP_MAX_SIZE;
  32524. }else if( dwInitialSize>dwMaximumSize ){
  32525. dwInitialSize = dwMaximumSize;
  32526. }
  32527. pWinMemData->hHeap = osHeapCreate(SQLITE_WIN32_HEAP_FLAGS,
  32528. dwInitialSize, dwMaximumSize);
  32529. if( !pWinMemData->hHeap ){
  32530. sqlite3_log(SQLITE_NOMEM,
  32531. "failed to HeapCreate (%lu), flags=%u, initSize=%lu, maxSize=%lu",
  32532. osGetLastError(), SQLITE_WIN32_HEAP_FLAGS, dwInitialSize,
  32533. dwMaximumSize);
  32534. return SQLITE_NOMEM;
  32535. }
  32536. pWinMemData->bOwned = TRUE;
  32537. assert( pWinMemData->bOwned );
  32538. }
  32539. #else
  32540. pWinMemData->hHeap = osGetProcessHeap();
  32541. if( !pWinMemData->hHeap ){
  32542. sqlite3_log(SQLITE_NOMEM,
  32543. "failed to GetProcessHeap (%lu)", osGetLastError());
  32544. return SQLITE_NOMEM;
  32545. }
  32546. pWinMemData->bOwned = FALSE;
  32547. assert( !pWinMemData->bOwned );
  32548. #endif
  32549. assert( pWinMemData->hHeap!=0 );
  32550. assert( pWinMemData->hHeap!=INVALID_HANDLE_VALUE );
  32551. #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
  32552. assert( osHeapValidate(pWinMemData->hHeap, SQLITE_WIN32_HEAP_FLAGS, NULL) );
  32553. #endif
  32554. return SQLITE_OK;
  32555. }
  32556. /*
  32557. ** Deinitialize this module.
  32558. */
  32559. static void winMemShutdown(void *pAppData){
  32560. winMemData *pWinMemData = (winMemData *)pAppData;
  32561. if( !pWinMemData ) return;
  32562. assert( pWinMemData->magic1==WINMEM_MAGIC1 );
  32563. assert( pWinMemData->magic2==WINMEM_MAGIC2 );
  32564. if( pWinMemData->hHeap ){
  32565. assert( pWinMemData->hHeap!=INVALID_HANDLE_VALUE );
  32566. #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
  32567. assert( osHeapValidate(pWinMemData->hHeap, SQLITE_WIN32_HEAP_FLAGS, NULL) );
  32568. #endif
  32569. if( pWinMemData->bOwned ){
  32570. if( !osHeapDestroy(pWinMemData->hHeap) ){
  32571. sqlite3_log(SQLITE_NOMEM, "failed to HeapDestroy (%lu), heap=%p",
  32572. osGetLastError(), (void*)pWinMemData->hHeap);
  32573. }
  32574. pWinMemData->bOwned = FALSE;
  32575. }
  32576. pWinMemData->hHeap = NULL;
  32577. }
  32578. }
  32579. /*
  32580. ** Populate the low-level memory allocation function pointers in
  32581. ** sqlite3GlobalConfig.m with pointers to the routines in this file. The
  32582. ** arguments specify the block of memory to manage.
  32583. **
  32584. ** This routine is only called by sqlite3_config(), and therefore
  32585. ** is not required to be threadsafe (it is not).
  32586. */
  32587. SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetWin32(void){
  32588. static const sqlite3_mem_methods winMemMethods = {
  32589. winMemMalloc,
  32590. winMemFree,
  32591. winMemRealloc,
  32592. winMemSize,
  32593. winMemRoundup,
  32594. winMemInit,
  32595. winMemShutdown,
  32596. &win_mem_data
  32597. };
  32598. return &winMemMethods;
  32599. }
  32600. SQLITE_PRIVATE void sqlite3MemSetDefault(void){
  32601. sqlite3_config(SQLITE_CONFIG_MALLOC, sqlite3MemGetWin32());
  32602. }
  32603. #endif /* SQLITE_WIN32_MALLOC */
  32604. /*
  32605. ** Convert a UTF-8 string to Microsoft Unicode (UTF-16?).
  32606. **
  32607. ** Space to hold the returned string is obtained from malloc.
  32608. */
  32609. static LPWSTR winUtf8ToUnicode(const char *zFilename){
  32610. int nChar;
  32611. LPWSTR zWideFilename;
  32612. nChar = osMultiByteToWideChar(CP_UTF8, 0, zFilename, -1, NULL, 0);
  32613. if( nChar==0 ){
  32614. return 0;
  32615. }
  32616. zWideFilename = sqlite3MallocZero( nChar*sizeof(zWideFilename[0]) );
  32617. if( zWideFilename==0 ){
  32618. return 0;
  32619. }
  32620. nChar = osMultiByteToWideChar(CP_UTF8, 0, zFilename, -1, zWideFilename,
  32621. nChar);
  32622. if( nChar==0 ){
  32623. sqlite3_free(zWideFilename);
  32624. zWideFilename = 0;
  32625. }
  32626. return zWideFilename;
  32627. }
  32628. /*
  32629. ** Convert Microsoft Unicode to UTF-8. Space to hold the returned string is
  32630. ** obtained from sqlite3_malloc().
  32631. */
  32632. static char *winUnicodeToUtf8(LPCWSTR zWideFilename){
  32633. int nByte;
  32634. char *zFilename;
  32635. nByte = osWideCharToMultiByte(CP_UTF8, 0, zWideFilename, -1, 0, 0, 0, 0);
  32636. if( nByte == 0 ){
  32637. return 0;
  32638. }
  32639. zFilename = sqlite3MallocZero( nByte );
  32640. if( zFilename==0 ){
  32641. return 0;
  32642. }
  32643. nByte = osWideCharToMultiByte(CP_UTF8, 0, zWideFilename, -1, zFilename, nByte,
  32644. 0, 0);
  32645. if( nByte == 0 ){
  32646. sqlite3_free(zFilename);
  32647. zFilename = 0;
  32648. }
  32649. return zFilename;
  32650. }
  32651. /*
  32652. ** Convert an ANSI string to Microsoft Unicode, based on the
  32653. ** current codepage settings for file apis.
  32654. **
  32655. ** Space to hold the returned string is obtained
  32656. ** from sqlite3_malloc.
  32657. */
  32658. static LPWSTR winMbcsToUnicode(const char *zFilename){
  32659. int nByte;
  32660. LPWSTR zMbcsFilename;
  32661. int codepage = osAreFileApisANSI() ? CP_ACP : CP_OEMCP;
  32662. nByte = osMultiByteToWideChar(codepage, 0, zFilename, -1, NULL,
  32663. 0)*sizeof(WCHAR);
  32664. if( nByte==0 ){
  32665. return 0;
  32666. }
  32667. zMbcsFilename = sqlite3MallocZero( nByte*sizeof(zMbcsFilename[0]) );
  32668. if( zMbcsFilename==0 ){
  32669. return 0;
  32670. }
  32671. nByte = osMultiByteToWideChar(codepage, 0, zFilename, -1, zMbcsFilename,
  32672. nByte);
  32673. if( nByte==0 ){
  32674. sqlite3_free(zMbcsFilename);
  32675. zMbcsFilename = 0;
  32676. }
  32677. return zMbcsFilename;
  32678. }
  32679. /*
  32680. ** Convert Microsoft Unicode to multi-byte character string, based on the
  32681. ** user's ANSI codepage.
  32682. **
  32683. ** Space to hold the returned string is obtained from
  32684. ** sqlite3_malloc().
  32685. */
  32686. static char *winUnicodeToMbcs(LPCWSTR zWideFilename){
  32687. int nByte;
  32688. char *zFilename;
  32689. int codepage = osAreFileApisANSI() ? CP_ACP : CP_OEMCP;
  32690. nByte = osWideCharToMultiByte(codepage, 0, zWideFilename, -1, 0, 0, 0, 0);
  32691. if( nByte == 0 ){
  32692. return 0;
  32693. }
  32694. zFilename = sqlite3MallocZero( nByte );
  32695. if( zFilename==0 ){
  32696. return 0;
  32697. }
  32698. nByte = osWideCharToMultiByte(codepage, 0, zWideFilename, -1, zFilename,
  32699. nByte, 0, 0);
  32700. if( nByte == 0 ){
  32701. sqlite3_free(zFilename);
  32702. zFilename = 0;
  32703. }
  32704. return zFilename;
  32705. }
  32706. /*
  32707. ** Convert multibyte character string to UTF-8. Space to hold the
  32708. ** returned string is obtained from sqlite3_malloc().
  32709. */
  32710. SQLITE_API char *SQLITE_STDCALL sqlite3_win32_mbcs_to_utf8(const char *zFilename){
  32711. char *zFilenameUtf8;
  32712. LPWSTR zTmpWide;
  32713. zTmpWide = winMbcsToUnicode(zFilename);
  32714. if( zTmpWide==0 ){
  32715. return 0;
  32716. }
  32717. zFilenameUtf8 = winUnicodeToUtf8(zTmpWide);
  32718. sqlite3_free(zTmpWide);
  32719. return zFilenameUtf8;
  32720. }
  32721. /*
  32722. ** Convert UTF-8 to multibyte character string. Space to hold the
  32723. ** returned string is obtained from sqlite3_malloc().
  32724. */
  32725. SQLITE_API char *SQLITE_STDCALL sqlite3_win32_utf8_to_mbcs(const char *zFilename){
  32726. char *zFilenameMbcs;
  32727. LPWSTR zTmpWide;
  32728. zTmpWide = winUtf8ToUnicode(zFilename);
  32729. if( zTmpWide==0 ){
  32730. return 0;
  32731. }
  32732. zFilenameMbcs = winUnicodeToMbcs(zTmpWide);
  32733. sqlite3_free(zTmpWide);
  32734. return zFilenameMbcs;
  32735. }
  32736. /*
  32737. ** This function sets the data directory or the temporary directory based on
  32738. ** the provided arguments. The type argument must be 1 in order to set the
  32739. ** data directory or 2 in order to set the temporary directory. The zValue
  32740. ** argument is the name of the directory to use. The return value will be
  32741. ** SQLITE_OK if successful.
  32742. */
  32743. SQLITE_API int SQLITE_STDCALL sqlite3_win32_set_directory(DWORD type, LPCWSTR zValue){
  32744. char **ppDirectory = 0;
  32745. #ifndef SQLITE_OMIT_AUTOINIT
  32746. int rc = sqlite3_initialize();
  32747. if( rc ) return rc;
  32748. #endif
  32749. if( type==SQLITE_WIN32_DATA_DIRECTORY_TYPE ){
  32750. ppDirectory = &sqlite3_data_directory;
  32751. }else if( type==SQLITE_WIN32_TEMP_DIRECTORY_TYPE ){
  32752. ppDirectory = &sqlite3_temp_directory;
  32753. }
  32754. assert( !ppDirectory || type==SQLITE_WIN32_DATA_DIRECTORY_TYPE
  32755. || type==SQLITE_WIN32_TEMP_DIRECTORY_TYPE
  32756. );
  32757. assert( !ppDirectory || sqlite3MemdebugHasType(*ppDirectory, MEMTYPE_HEAP) );
  32758. if( ppDirectory ){
  32759. char *zValueUtf8 = 0;
  32760. if( zValue && zValue[0] ){
  32761. zValueUtf8 = winUnicodeToUtf8(zValue);
  32762. if ( zValueUtf8==0 ){
  32763. return SQLITE_NOMEM;
  32764. }
  32765. }
  32766. sqlite3_free(*ppDirectory);
  32767. *ppDirectory = zValueUtf8;
  32768. return SQLITE_OK;
  32769. }
  32770. return SQLITE_ERROR;
  32771. }
  32772. /*
  32773. ** The return value of winGetLastErrorMsg
  32774. ** is zero if the error message fits in the buffer, or non-zero
  32775. ** otherwise (if the message was truncated).
  32776. */
  32777. static int winGetLastErrorMsg(DWORD lastErrno, int nBuf, char *zBuf){
  32778. /* FormatMessage returns 0 on failure. Otherwise it
  32779. ** returns the number of TCHARs written to the output
  32780. ** buffer, excluding the terminating null char.
  32781. */
  32782. DWORD dwLen = 0;
  32783. char *zOut = 0;
  32784. if( osIsNT() ){
  32785. #if SQLITE_OS_WINRT
  32786. WCHAR zTempWide[SQLITE_WIN32_MAX_ERRMSG_CHARS+1];
  32787. dwLen = osFormatMessageW(FORMAT_MESSAGE_FROM_SYSTEM |
  32788. FORMAT_MESSAGE_IGNORE_INSERTS,
  32789. NULL,
  32790. lastErrno,
  32791. 0,
  32792. zTempWide,
  32793. SQLITE_WIN32_MAX_ERRMSG_CHARS,
  32794. 0);
  32795. #else
  32796. LPWSTR zTempWide = NULL;
  32797. dwLen = osFormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER |
  32798. FORMAT_MESSAGE_FROM_SYSTEM |
  32799. FORMAT_MESSAGE_IGNORE_INSERTS,
  32800. NULL,
  32801. lastErrno,
  32802. 0,
  32803. (LPWSTR) &zTempWide,
  32804. 0,
  32805. 0);
  32806. #endif
  32807. if( dwLen > 0 ){
  32808. /* allocate a buffer and convert to UTF8 */
  32809. sqlite3BeginBenignMalloc();
  32810. zOut = winUnicodeToUtf8(zTempWide);
  32811. sqlite3EndBenignMalloc();
  32812. #if !SQLITE_OS_WINRT
  32813. /* free the system buffer allocated by FormatMessage */
  32814. osLocalFree(zTempWide);
  32815. #endif
  32816. }
  32817. }
  32818. #ifdef SQLITE_WIN32_HAS_ANSI
  32819. else{
  32820. char *zTemp = NULL;
  32821. dwLen = osFormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER |
  32822. FORMAT_MESSAGE_FROM_SYSTEM |
  32823. FORMAT_MESSAGE_IGNORE_INSERTS,
  32824. NULL,
  32825. lastErrno,
  32826. 0,
  32827. (LPSTR) &zTemp,
  32828. 0,
  32829. 0);
  32830. if( dwLen > 0 ){
  32831. /* allocate a buffer and convert to UTF8 */
  32832. sqlite3BeginBenignMalloc();
  32833. zOut = sqlite3_win32_mbcs_to_utf8(zTemp);
  32834. sqlite3EndBenignMalloc();
  32835. /* free the system buffer allocated by FormatMessage */
  32836. osLocalFree(zTemp);
  32837. }
  32838. }
  32839. #endif
  32840. if( 0 == dwLen ){
  32841. sqlite3_snprintf(nBuf, zBuf, "OsError 0x%lx (%lu)", lastErrno, lastErrno);
  32842. }else{
  32843. /* copy a maximum of nBuf chars to output buffer */
  32844. sqlite3_snprintf(nBuf, zBuf, "%s", zOut);
  32845. /* free the UTF8 buffer */
  32846. sqlite3_free(zOut);
  32847. }
  32848. return 0;
  32849. }
  32850. /*
  32851. **
  32852. ** This function - winLogErrorAtLine() - is only ever called via the macro
  32853. ** winLogError().
  32854. **
  32855. ** This routine is invoked after an error occurs in an OS function.
  32856. ** It logs a message using sqlite3_log() containing the current value of
  32857. ** error code and, if possible, the human-readable equivalent from
  32858. ** FormatMessage.
  32859. **
  32860. ** The first argument passed to the macro should be the error code that
  32861. ** will be returned to SQLite (e.g. SQLITE_IOERR_DELETE, SQLITE_CANTOPEN).
  32862. ** The two subsequent arguments should be the name of the OS function that
  32863. ** failed and the associated file-system path, if any.
  32864. */
  32865. #define winLogError(a,b,c,d) winLogErrorAtLine(a,b,c,d,__LINE__)
  32866. static int winLogErrorAtLine(
  32867. int errcode, /* SQLite error code */
  32868. DWORD lastErrno, /* Win32 last error */
  32869. const char *zFunc, /* Name of OS function that failed */
  32870. const char *zPath, /* File path associated with error */
  32871. int iLine /* Source line number where error occurred */
  32872. ){
  32873. char zMsg[500]; /* Human readable error text */
  32874. int i; /* Loop counter */
  32875. zMsg[0] = 0;
  32876. winGetLastErrorMsg(lastErrno, sizeof(zMsg), zMsg);
  32877. assert( errcode!=SQLITE_OK );
  32878. if( zPath==0 ) zPath = "";
  32879. for(i=0; zMsg[i] && zMsg[i]!='\r' && zMsg[i]!='\n'; i++){}
  32880. zMsg[i] = 0;
  32881. sqlite3_log(errcode,
  32882. "os_win.c:%d: (%lu) %s(%s) - %s",
  32883. iLine, lastErrno, zFunc, zPath, zMsg
  32884. );
  32885. return errcode;
  32886. }
  32887. /*
  32888. ** The number of times that a ReadFile(), WriteFile(), and DeleteFile()
  32889. ** will be retried following a locking error - probably caused by
  32890. ** antivirus software. Also the initial delay before the first retry.
  32891. ** The delay increases linearly with each retry.
  32892. */
  32893. #ifndef SQLITE_WIN32_IOERR_RETRY
  32894. # define SQLITE_WIN32_IOERR_RETRY 10
  32895. #endif
  32896. #ifndef SQLITE_WIN32_IOERR_RETRY_DELAY
  32897. # define SQLITE_WIN32_IOERR_RETRY_DELAY 25
  32898. #endif
  32899. static int winIoerrRetry = SQLITE_WIN32_IOERR_RETRY;
  32900. static int winIoerrRetryDelay = SQLITE_WIN32_IOERR_RETRY_DELAY;
  32901. /*
  32902. ** The "winIoerrCanRetry1" macro is used to determine if a particular I/O
  32903. ** error code obtained via GetLastError() is eligible to be retried. It
  32904. ** must accept the error code DWORD as its only argument and should return
  32905. ** non-zero if the error code is transient in nature and the operation
  32906. ** responsible for generating the original error might succeed upon being
  32907. ** retried. The argument to this macro should be a variable.
  32908. **
  32909. ** Additionally, a macro named "winIoerrCanRetry2" may be defined. If it
  32910. ** is defined, it will be consulted only when the macro "winIoerrCanRetry1"
  32911. ** returns zero. The "winIoerrCanRetry2" macro is completely optional and
  32912. ** may be used to include additional error codes in the set that should
  32913. ** result in the failing I/O operation being retried by the caller. If
  32914. ** defined, the "winIoerrCanRetry2" macro must exhibit external semantics
  32915. ** identical to those of the "winIoerrCanRetry1" macro.
  32916. */
  32917. #if !defined(winIoerrCanRetry1)
  32918. #define winIoerrCanRetry1(a) (((a)==ERROR_ACCESS_DENIED) || \
  32919. ((a)==ERROR_SHARING_VIOLATION) || \
  32920. ((a)==ERROR_LOCK_VIOLATION) || \
  32921. ((a)==ERROR_DEV_NOT_EXIST) || \
  32922. ((a)==ERROR_NETNAME_DELETED) || \
  32923. ((a)==ERROR_SEM_TIMEOUT) || \
  32924. ((a)==ERROR_NETWORK_UNREACHABLE))
  32925. #endif
  32926. /*
  32927. ** If a ReadFile() or WriteFile() error occurs, invoke this routine
  32928. ** to see if it should be retried. Return TRUE to retry. Return FALSE
  32929. ** to give up with an error.
  32930. */
  32931. static int winRetryIoerr(int *pnRetry, DWORD *pError){
  32932. DWORD e = osGetLastError();
  32933. if( *pnRetry>=winIoerrRetry ){
  32934. if( pError ){
  32935. *pError = e;
  32936. }
  32937. return 0;
  32938. }
  32939. if( winIoerrCanRetry1(e) ){
  32940. sqlite3_win32_sleep(winIoerrRetryDelay*(1+*pnRetry));
  32941. ++*pnRetry;
  32942. return 1;
  32943. }
  32944. #if defined(winIoerrCanRetry2)
  32945. else if( winIoerrCanRetry2(e) ){
  32946. sqlite3_win32_sleep(winIoerrRetryDelay*(1+*pnRetry));
  32947. ++*pnRetry;
  32948. return 1;
  32949. }
  32950. #endif
  32951. if( pError ){
  32952. *pError = e;
  32953. }
  32954. return 0;
  32955. }
  32956. /*
  32957. ** Log a I/O error retry episode.
  32958. */
  32959. static void winLogIoerr(int nRetry, int lineno){
  32960. if( nRetry ){
  32961. sqlite3_log(SQLITE_NOTICE,
  32962. "delayed %dms for lock/sharing conflict at line %d",
  32963. winIoerrRetryDelay*nRetry*(nRetry+1)/2, lineno
  32964. );
  32965. }
  32966. }
  32967. #if SQLITE_OS_WINCE
  32968. /*************************************************************************
  32969. ** This section contains code for WinCE only.
  32970. */
  32971. #if !defined(SQLITE_MSVC_LOCALTIME_API) || !SQLITE_MSVC_LOCALTIME_API
  32972. /*
  32973. ** The MSVC CRT on Windows CE may not have a localtime() function. So
  32974. ** create a substitute.
  32975. */
  32976. /* #include <time.h> */
  32977. struct tm *__cdecl localtime(const time_t *t)
  32978. {
  32979. static struct tm y;
  32980. FILETIME uTm, lTm;
  32981. SYSTEMTIME pTm;
  32982. sqlite3_int64 t64;
  32983. t64 = *t;
  32984. t64 = (t64 + 11644473600)*10000000;
  32985. uTm.dwLowDateTime = (DWORD)(t64 & 0xFFFFFFFF);
  32986. uTm.dwHighDateTime= (DWORD)(t64 >> 32);
  32987. osFileTimeToLocalFileTime(&uTm,&lTm);
  32988. osFileTimeToSystemTime(&lTm,&pTm);
  32989. y.tm_year = pTm.wYear - 1900;
  32990. y.tm_mon = pTm.wMonth - 1;
  32991. y.tm_wday = pTm.wDayOfWeek;
  32992. y.tm_mday = pTm.wDay;
  32993. y.tm_hour = pTm.wHour;
  32994. y.tm_min = pTm.wMinute;
  32995. y.tm_sec = pTm.wSecond;
  32996. return &y;
  32997. }
  32998. #endif
  32999. #define HANDLE_TO_WINFILE(a) (winFile*)&((char*)a)[-(int)offsetof(winFile,h)]
  33000. /*
  33001. ** Acquire a lock on the handle h
  33002. */
  33003. static void winceMutexAcquire(HANDLE h){
  33004. DWORD dwErr;
  33005. do {
  33006. dwErr = osWaitForSingleObject(h, INFINITE);
  33007. } while (dwErr != WAIT_OBJECT_0 && dwErr != WAIT_ABANDONED);
  33008. }
  33009. /*
  33010. ** Release a lock acquired by winceMutexAcquire()
  33011. */
  33012. #define winceMutexRelease(h) ReleaseMutex(h)
  33013. /*
  33014. ** Create the mutex and shared memory used for locking in the file
  33015. ** descriptor pFile
  33016. */
  33017. static int winceCreateLock(const char *zFilename, winFile *pFile){
  33018. LPWSTR zTok;
  33019. LPWSTR zName;
  33020. DWORD lastErrno;
  33021. BOOL bLogged = FALSE;
  33022. BOOL bInit = TRUE;
  33023. zName = winUtf8ToUnicode(zFilename);
  33024. if( zName==0 ){
  33025. /* out of memory */
  33026. return SQLITE_IOERR_NOMEM;
  33027. }
  33028. /* Initialize the local lockdata */
  33029. memset(&pFile->local, 0, sizeof(pFile->local));
  33030. /* Replace the backslashes from the filename and lowercase it
  33031. ** to derive a mutex name. */
  33032. zTok = osCharLowerW(zName);
  33033. for (;*zTok;zTok++){
  33034. if (*zTok == '\\') *zTok = '_';
  33035. }
  33036. /* Create/open the named mutex */
  33037. pFile->hMutex = osCreateMutexW(NULL, FALSE, zName);
  33038. if (!pFile->hMutex){
  33039. pFile->lastErrno = osGetLastError();
  33040. sqlite3_free(zName);
  33041. return winLogError(SQLITE_IOERR, pFile->lastErrno,
  33042. "winceCreateLock1", zFilename);
  33043. }
  33044. /* Acquire the mutex before continuing */
  33045. winceMutexAcquire(pFile->hMutex);
  33046. /* Since the names of named mutexes, semaphores, file mappings etc are
  33047. ** case-sensitive, take advantage of that by uppercasing the mutex name
  33048. ** and using that as the shared filemapping name.
  33049. */
  33050. osCharUpperW(zName);
  33051. pFile->hShared = osCreateFileMappingW(INVALID_HANDLE_VALUE, NULL,
  33052. PAGE_READWRITE, 0, sizeof(winceLock),
  33053. zName);
  33054. /* Set a flag that indicates we're the first to create the memory so it
  33055. ** must be zero-initialized */
  33056. lastErrno = osGetLastError();
  33057. if (lastErrno == ERROR_ALREADY_EXISTS){
  33058. bInit = FALSE;
  33059. }
  33060. sqlite3_free(zName);
  33061. /* If we succeeded in making the shared memory handle, map it. */
  33062. if( pFile->hShared ){
  33063. pFile->shared = (winceLock*)osMapViewOfFile(pFile->hShared,
  33064. FILE_MAP_READ|FILE_MAP_WRITE, 0, 0, sizeof(winceLock));
  33065. /* If mapping failed, close the shared memory handle and erase it */
  33066. if( !pFile->shared ){
  33067. pFile->lastErrno = osGetLastError();
  33068. winLogError(SQLITE_IOERR, pFile->lastErrno,
  33069. "winceCreateLock2", zFilename);
  33070. bLogged = TRUE;
  33071. osCloseHandle(pFile->hShared);
  33072. pFile->hShared = NULL;
  33073. }
  33074. }
  33075. /* If shared memory could not be created, then close the mutex and fail */
  33076. if( pFile->hShared==NULL ){
  33077. if( !bLogged ){
  33078. pFile->lastErrno = lastErrno;
  33079. winLogError(SQLITE_IOERR, pFile->lastErrno,
  33080. "winceCreateLock3", zFilename);
  33081. bLogged = TRUE;
  33082. }
  33083. winceMutexRelease(pFile->hMutex);
  33084. osCloseHandle(pFile->hMutex);
  33085. pFile->hMutex = NULL;
  33086. return SQLITE_IOERR;
  33087. }
  33088. /* Initialize the shared memory if we're supposed to */
  33089. if( bInit ){
  33090. memset(pFile->shared, 0, sizeof(winceLock));
  33091. }
  33092. winceMutexRelease(pFile->hMutex);
  33093. return SQLITE_OK;
  33094. }
  33095. /*
  33096. ** Destroy the part of winFile that deals with wince locks
  33097. */
  33098. static void winceDestroyLock(winFile *pFile){
  33099. if (pFile->hMutex){
  33100. /* Acquire the mutex */
  33101. winceMutexAcquire(pFile->hMutex);
  33102. /* The following blocks should probably assert in debug mode, but they
  33103. are to cleanup in case any locks remained open */
  33104. if (pFile->local.nReaders){
  33105. pFile->shared->nReaders --;
  33106. }
  33107. if (pFile->local.bReserved){
  33108. pFile->shared->bReserved = FALSE;
  33109. }
  33110. if (pFile->local.bPending){
  33111. pFile->shared->bPending = FALSE;
  33112. }
  33113. if (pFile->local.bExclusive){
  33114. pFile->shared->bExclusive = FALSE;
  33115. }
  33116. /* De-reference and close our copy of the shared memory handle */
  33117. osUnmapViewOfFile(pFile->shared);
  33118. osCloseHandle(pFile->hShared);
  33119. /* Done with the mutex */
  33120. winceMutexRelease(pFile->hMutex);
  33121. osCloseHandle(pFile->hMutex);
  33122. pFile->hMutex = NULL;
  33123. }
  33124. }
  33125. /*
  33126. ** An implementation of the LockFile() API of Windows for CE
  33127. */
  33128. static BOOL winceLockFile(
  33129. LPHANDLE phFile,
  33130. DWORD dwFileOffsetLow,
  33131. DWORD dwFileOffsetHigh,
  33132. DWORD nNumberOfBytesToLockLow,
  33133. DWORD nNumberOfBytesToLockHigh
  33134. ){
  33135. winFile *pFile = HANDLE_TO_WINFILE(phFile);
  33136. BOOL bReturn = FALSE;
  33137. UNUSED_PARAMETER(dwFileOffsetHigh);
  33138. UNUSED_PARAMETER(nNumberOfBytesToLockHigh);
  33139. if (!pFile->hMutex) return TRUE;
  33140. winceMutexAcquire(pFile->hMutex);
  33141. /* Wanting an exclusive lock? */
  33142. if (dwFileOffsetLow == (DWORD)SHARED_FIRST
  33143. && nNumberOfBytesToLockLow == (DWORD)SHARED_SIZE){
  33144. if (pFile->shared->nReaders == 0 && pFile->shared->bExclusive == 0){
  33145. pFile->shared->bExclusive = TRUE;
  33146. pFile->local.bExclusive = TRUE;
  33147. bReturn = TRUE;
  33148. }
  33149. }
  33150. /* Want a read-only lock? */
  33151. else if (dwFileOffsetLow == (DWORD)SHARED_FIRST &&
  33152. nNumberOfBytesToLockLow == 1){
  33153. if (pFile->shared->bExclusive == 0){
  33154. pFile->local.nReaders ++;
  33155. if (pFile->local.nReaders == 1){
  33156. pFile->shared->nReaders ++;
  33157. }
  33158. bReturn = TRUE;
  33159. }
  33160. }
  33161. /* Want a pending lock? */
  33162. else if (dwFileOffsetLow == (DWORD)PENDING_BYTE
  33163. && nNumberOfBytesToLockLow == 1){
  33164. /* If no pending lock has been acquired, then acquire it */
  33165. if (pFile->shared->bPending == 0) {
  33166. pFile->shared->bPending = TRUE;
  33167. pFile->local.bPending = TRUE;
  33168. bReturn = TRUE;
  33169. }
  33170. }
  33171. /* Want a reserved lock? */
  33172. else if (dwFileOffsetLow == (DWORD)RESERVED_BYTE
  33173. && nNumberOfBytesToLockLow == 1){
  33174. if (pFile->shared->bReserved == 0) {
  33175. pFile->shared->bReserved = TRUE;
  33176. pFile->local.bReserved = TRUE;
  33177. bReturn = TRUE;
  33178. }
  33179. }
  33180. winceMutexRelease(pFile->hMutex);
  33181. return bReturn;
  33182. }
  33183. /*
  33184. ** An implementation of the UnlockFile API of Windows for CE
  33185. */
  33186. static BOOL winceUnlockFile(
  33187. LPHANDLE phFile,
  33188. DWORD dwFileOffsetLow,
  33189. DWORD dwFileOffsetHigh,
  33190. DWORD nNumberOfBytesToUnlockLow,
  33191. DWORD nNumberOfBytesToUnlockHigh
  33192. ){
  33193. winFile *pFile = HANDLE_TO_WINFILE(phFile);
  33194. BOOL bReturn = FALSE;
  33195. UNUSED_PARAMETER(dwFileOffsetHigh);
  33196. UNUSED_PARAMETER(nNumberOfBytesToUnlockHigh);
  33197. if (!pFile->hMutex) return TRUE;
  33198. winceMutexAcquire(pFile->hMutex);
  33199. /* Releasing a reader lock or an exclusive lock */
  33200. if (dwFileOffsetLow == (DWORD)SHARED_FIRST){
  33201. /* Did we have an exclusive lock? */
  33202. if (pFile->local.bExclusive){
  33203. assert(nNumberOfBytesToUnlockLow == (DWORD)SHARED_SIZE);
  33204. pFile->local.bExclusive = FALSE;
  33205. pFile->shared->bExclusive = FALSE;
  33206. bReturn = TRUE;
  33207. }
  33208. /* Did we just have a reader lock? */
  33209. else if (pFile->local.nReaders){
  33210. assert(nNumberOfBytesToUnlockLow == (DWORD)SHARED_SIZE
  33211. || nNumberOfBytesToUnlockLow == 1);
  33212. pFile->local.nReaders --;
  33213. if (pFile->local.nReaders == 0)
  33214. {
  33215. pFile->shared->nReaders --;
  33216. }
  33217. bReturn = TRUE;
  33218. }
  33219. }
  33220. /* Releasing a pending lock */
  33221. else if (dwFileOffsetLow == (DWORD)PENDING_BYTE
  33222. && nNumberOfBytesToUnlockLow == 1){
  33223. if (pFile->local.bPending){
  33224. pFile->local.bPending = FALSE;
  33225. pFile->shared->bPending = FALSE;
  33226. bReturn = TRUE;
  33227. }
  33228. }
  33229. /* Releasing a reserved lock */
  33230. else if (dwFileOffsetLow == (DWORD)RESERVED_BYTE
  33231. && nNumberOfBytesToUnlockLow == 1){
  33232. if (pFile->local.bReserved) {
  33233. pFile->local.bReserved = FALSE;
  33234. pFile->shared->bReserved = FALSE;
  33235. bReturn = TRUE;
  33236. }
  33237. }
  33238. winceMutexRelease(pFile->hMutex);
  33239. return bReturn;
  33240. }
  33241. /*
  33242. ** End of the special code for wince
  33243. *****************************************************************************/
  33244. #endif /* SQLITE_OS_WINCE */
  33245. /*
  33246. ** Lock a file region.
  33247. */
  33248. static BOOL winLockFile(
  33249. LPHANDLE phFile,
  33250. DWORD flags,
  33251. DWORD offsetLow,
  33252. DWORD offsetHigh,
  33253. DWORD numBytesLow,
  33254. DWORD numBytesHigh
  33255. ){
  33256. #if SQLITE_OS_WINCE
  33257. /*
  33258. ** NOTE: Windows CE is handled differently here due its lack of the Win32
  33259. ** API LockFile.
  33260. */
  33261. return winceLockFile(phFile, offsetLow, offsetHigh,
  33262. numBytesLow, numBytesHigh);
  33263. #else
  33264. if( osIsNT() ){
  33265. OVERLAPPED ovlp;
  33266. memset(&ovlp, 0, sizeof(OVERLAPPED));
  33267. ovlp.Offset = offsetLow;
  33268. ovlp.OffsetHigh = offsetHigh;
  33269. return osLockFileEx(*phFile, flags, 0, numBytesLow, numBytesHigh, &ovlp);
  33270. }else{
  33271. return osLockFile(*phFile, offsetLow, offsetHigh, numBytesLow,
  33272. numBytesHigh);
  33273. }
  33274. #endif
  33275. }
  33276. /*
  33277. ** Unlock a file region.
  33278. */
  33279. static BOOL winUnlockFile(
  33280. LPHANDLE phFile,
  33281. DWORD offsetLow,
  33282. DWORD offsetHigh,
  33283. DWORD numBytesLow,
  33284. DWORD numBytesHigh
  33285. ){
  33286. #if SQLITE_OS_WINCE
  33287. /*
  33288. ** NOTE: Windows CE is handled differently here due its lack of the Win32
  33289. ** API UnlockFile.
  33290. */
  33291. return winceUnlockFile(phFile, offsetLow, offsetHigh,
  33292. numBytesLow, numBytesHigh);
  33293. #else
  33294. if( osIsNT() ){
  33295. OVERLAPPED ovlp;
  33296. memset(&ovlp, 0, sizeof(OVERLAPPED));
  33297. ovlp.Offset = offsetLow;
  33298. ovlp.OffsetHigh = offsetHigh;
  33299. return osUnlockFileEx(*phFile, 0, numBytesLow, numBytesHigh, &ovlp);
  33300. }else{
  33301. return osUnlockFile(*phFile, offsetLow, offsetHigh, numBytesLow,
  33302. numBytesHigh);
  33303. }
  33304. #endif
  33305. }
  33306. /*****************************************************************************
  33307. ** The next group of routines implement the I/O methods specified
  33308. ** by the sqlite3_io_methods object.
  33309. ******************************************************************************/
  33310. /*
  33311. ** Some Microsoft compilers lack this definition.
  33312. */
  33313. #ifndef INVALID_SET_FILE_POINTER
  33314. # define INVALID_SET_FILE_POINTER ((DWORD)-1)
  33315. #endif
  33316. /*
  33317. ** Move the current position of the file handle passed as the first
  33318. ** argument to offset iOffset within the file. If successful, return 0.
  33319. ** Otherwise, set pFile->lastErrno and return non-zero.
  33320. */
  33321. static int winSeekFile(winFile *pFile, sqlite3_int64 iOffset){
  33322. #if !SQLITE_OS_WINRT
  33323. LONG upperBits; /* Most sig. 32 bits of new offset */
  33324. LONG lowerBits; /* Least sig. 32 bits of new offset */
  33325. DWORD dwRet; /* Value returned by SetFilePointer() */
  33326. DWORD lastErrno; /* Value returned by GetLastError() */
  33327. OSTRACE(("SEEK file=%p, offset=%lld\n", pFile->h, iOffset));
  33328. upperBits = (LONG)((iOffset>>32) & 0x7fffffff);
  33329. lowerBits = (LONG)(iOffset & 0xffffffff);
  33330. /* API oddity: If successful, SetFilePointer() returns a dword
  33331. ** containing the lower 32-bits of the new file-offset. Or, if it fails,
  33332. ** it returns INVALID_SET_FILE_POINTER. However according to MSDN,
  33333. ** INVALID_SET_FILE_POINTER may also be a valid new offset. So to determine
  33334. ** whether an error has actually occurred, it is also necessary to call
  33335. ** GetLastError().
  33336. */
  33337. dwRet = osSetFilePointer(pFile->h, lowerBits, &upperBits, FILE_BEGIN);
  33338. if( (dwRet==INVALID_SET_FILE_POINTER
  33339. && ((lastErrno = osGetLastError())!=NO_ERROR)) ){
  33340. pFile->lastErrno = lastErrno;
  33341. winLogError(SQLITE_IOERR_SEEK, pFile->lastErrno,
  33342. "winSeekFile", pFile->zPath);
  33343. OSTRACE(("SEEK file=%p, rc=SQLITE_IOERR_SEEK\n", pFile->h));
  33344. return 1;
  33345. }
  33346. OSTRACE(("SEEK file=%p, rc=SQLITE_OK\n", pFile->h));
  33347. return 0;
  33348. #else
  33349. /*
  33350. ** Same as above, except that this implementation works for WinRT.
  33351. */
  33352. LARGE_INTEGER x; /* The new offset */
  33353. BOOL bRet; /* Value returned by SetFilePointerEx() */
  33354. x.QuadPart = iOffset;
  33355. bRet = osSetFilePointerEx(pFile->h, x, 0, FILE_BEGIN);
  33356. if(!bRet){
  33357. pFile->lastErrno = osGetLastError();
  33358. winLogError(SQLITE_IOERR_SEEK, pFile->lastErrno,
  33359. "winSeekFile", pFile->zPath);
  33360. OSTRACE(("SEEK file=%p, rc=SQLITE_IOERR_SEEK\n", pFile->h));
  33361. return 1;
  33362. }
  33363. OSTRACE(("SEEK file=%p, rc=SQLITE_OK\n", pFile->h));
  33364. return 0;
  33365. #endif
  33366. }
  33367. #if SQLITE_MAX_MMAP_SIZE>0
  33368. /* Forward references to VFS helper methods used for memory mapped files */
  33369. static int winMapfile(winFile*, sqlite3_int64);
  33370. static int winUnmapfile(winFile*);
  33371. #endif
  33372. /*
  33373. ** Close a file.
  33374. **
  33375. ** It is reported that an attempt to close a handle might sometimes
  33376. ** fail. This is a very unreasonable result, but Windows is notorious
  33377. ** for being unreasonable so I do not doubt that it might happen. If
  33378. ** the close fails, we pause for 100 milliseconds and try again. As
  33379. ** many as MX_CLOSE_ATTEMPT attempts to close the handle are made before
  33380. ** giving up and returning an error.
  33381. */
  33382. #define MX_CLOSE_ATTEMPT 3
  33383. static int winClose(sqlite3_file *id){
  33384. int rc, cnt = 0;
  33385. winFile *pFile = (winFile*)id;
  33386. assert( id!=0 );
  33387. #ifndef SQLITE_OMIT_WAL
  33388. assert( pFile->pShm==0 );
  33389. #endif
  33390. assert( pFile->h!=NULL && pFile->h!=INVALID_HANDLE_VALUE );
  33391. OSTRACE(("CLOSE pid=%lu, pFile=%p, file=%p\n",
  33392. osGetCurrentProcessId(), pFile, pFile->h));
  33393. #if SQLITE_MAX_MMAP_SIZE>0
  33394. winUnmapfile(pFile);
  33395. #endif
  33396. do{
  33397. rc = osCloseHandle(pFile->h);
  33398. /* SimulateIOError( rc=0; cnt=MX_CLOSE_ATTEMPT; ); */
  33399. }while( rc==0 && ++cnt < MX_CLOSE_ATTEMPT && (sqlite3_win32_sleep(100), 1) );
  33400. #if SQLITE_OS_WINCE
  33401. #define WINCE_DELETION_ATTEMPTS 3
  33402. winceDestroyLock(pFile);
  33403. if( pFile->zDeleteOnClose ){
  33404. int cnt = 0;
  33405. while(
  33406. osDeleteFileW(pFile->zDeleteOnClose)==0
  33407. && osGetFileAttributesW(pFile->zDeleteOnClose)!=0xffffffff
  33408. && cnt++ < WINCE_DELETION_ATTEMPTS
  33409. ){
  33410. sqlite3_win32_sleep(100); /* Wait a little before trying again */
  33411. }
  33412. sqlite3_free(pFile->zDeleteOnClose);
  33413. }
  33414. #endif
  33415. if( rc ){
  33416. pFile->h = NULL;
  33417. }
  33418. OpenCounter(-1);
  33419. OSTRACE(("CLOSE pid=%lu, pFile=%p, file=%p, rc=%s\n",
  33420. osGetCurrentProcessId(), pFile, pFile->h, rc ? "ok" : "failed"));
  33421. return rc ? SQLITE_OK
  33422. : winLogError(SQLITE_IOERR_CLOSE, osGetLastError(),
  33423. "winClose", pFile->zPath);
  33424. }
  33425. /*
  33426. ** Read data from a file into a buffer. Return SQLITE_OK if all
  33427. ** bytes were read successfully and SQLITE_IOERR if anything goes
  33428. ** wrong.
  33429. */
  33430. static int winRead(
  33431. sqlite3_file *id, /* File to read from */
  33432. void *pBuf, /* Write content into this buffer */
  33433. int amt, /* Number of bytes to read */
  33434. sqlite3_int64 offset /* Begin reading at this offset */
  33435. ){
  33436. #if !SQLITE_OS_WINCE && !defined(SQLITE_WIN32_NO_OVERLAPPED)
  33437. OVERLAPPED overlapped; /* The offset for ReadFile. */
  33438. #endif
  33439. winFile *pFile = (winFile*)id; /* file handle */
  33440. DWORD nRead; /* Number of bytes actually read from file */
  33441. int nRetry = 0; /* Number of retrys */
  33442. assert( id!=0 );
  33443. assert( amt>0 );
  33444. assert( offset>=0 );
  33445. SimulateIOError(return SQLITE_IOERR_READ);
  33446. OSTRACE(("READ pid=%lu, pFile=%p, file=%p, buffer=%p, amount=%d, "
  33447. "offset=%lld, lock=%d\n", osGetCurrentProcessId(), pFile,
  33448. pFile->h, pBuf, amt, offset, pFile->locktype));
  33449. #if SQLITE_MAX_MMAP_SIZE>0
  33450. /* Deal with as much of this read request as possible by transfering
  33451. ** data from the memory mapping using memcpy(). */
  33452. if( offset<pFile->mmapSize ){
  33453. if( offset+amt <= pFile->mmapSize ){
  33454. memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], amt);
  33455. OSTRACE(("READ-MMAP pid=%lu, pFile=%p, file=%p, rc=SQLITE_OK\n",
  33456. osGetCurrentProcessId(), pFile, pFile->h));
  33457. return SQLITE_OK;
  33458. }else{
  33459. int nCopy = (int)(pFile->mmapSize - offset);
  33460. memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], nCopy);
  33461. pBuf = &((u8 *)pBuf)[nCopy];
  33462. amt -= nCopy;
  33463. offset += nCopy;
  33464. }
  33465. }
  33466. #endif
  33467. #if SQLITE_OS_WINCE || defined(SQLITE_WIN32_NO_OVERLAPPED)
  33468. if( winSeekFile(pFile, offset) ){
  33469. OSTRACE(("READ pid=%lu, pFile=%p, file=%p, rc=SQLITE_FULL\n",
  33470. osGetCurrentProcessId(), pFile, pFile->h));
  33471. return SQLITE_FULL;
  33472. }
  33473. while( !osReadFile(pFile->h, pBuf, amt, &nRead, 0) ){
  33474. #else
  33475. memset(&overlapped, 0, sizeof(OVERLAPPED));
  33476. overlapped.Offset = (LONG)(offset & 0xffffffff);
  33477. overlapped.OffsetHigh = (LONG)((offset>>32) & 0x7fffffff);
  33478. while( !osReadFile(pFile->h, pBuf, amt, &nRead, &overlapped) &&
  33479. osGetLastError()!=ERROR_HANDLE_EOF ){
  33480. #endif
  33481. DWORD lastErrno;
  33482. if( winRetryIoerr(&nRetry, &lastErrno) ) continue;
  33483. pFile->lastErrno = lastErrno;
  33484. OSTRACE(("READ pid=%lu, pFile=%p, file=%p, rc=SQLITE_IOERR_READ\n",
  33485. osGetCurrentProcessId(), pFile, pFile->h));
  33486. return winLogError(SQLITE_IOERR_READ, pFile->lastErrno,
  33487. "winRead", pFile->zPath);
  33488. }
  33489. winLogIoerr(nRetry, __LINE__);
  33490. if( nRead<(DWORD)amt ){
  33491. /* Unread parts of the buffer must be zero-filled */
  33492. memset(&((char*)pBuf)[nRead], 0, amt-nRead);
  33493. OSTRACE(("READ pid=%lu, pFile=%p, file=%p, rc=SQLITE_IOERR_SHORT_READ\n",
  33494. osGetCurrentProcessId(), pFile, pFile->h));
  33495. return SQLITE_IOERR_SHORT_READ;
  33496. }
  33497. OSTRACE(("READ pid=%lu, pFile=%p, file=%p, rc=SQLITE_OK\n",
  33498. osGetCurrentProcessId(), pFile, pFile->h));
  33499. return SQLITE_OK;
  33500. }
  33501. /*
  33502. ** Write data from a buffer into a file. Return SQLITE_OK on success
  33503. ** or some other error code on failure.
  33504. */
  33505. static int winWrite(
  33506. sqlite3_file *id, /* File to write into */
  33507. const void *pBuf, /* The bytes to be written */
  33508. int amt, /* Number of bytes to write */
  33509. sqlite3_int64 offset /* Offset into the file to begin writing at */
  33510. ){
  33511. int rc = 0; /* True if error has occurred, else false */
  33512. winFile *pFile = (winFile*)id; /* File handle */
  33513. int nRetry = 0; /* Number of retries */
  33514. assert( amt>0 );
  33515. assert( pFile );
  33516. SimulateIOError(return SQLITE_IOERR_WRITE);
  33517. SimulateDiskfullError(return SQLITE_FULL);
  33518. OSTRACE(("WRITE pid=%lu, pFile=%p, file=%p, buffer=%p, amount=%d, "
  33519. "offset=%lld, lock=%d\n", osGetCurrentProcessId(), pFile,
  33520. pFile->h, pBuf, amt, offset, pFile->locktype));
  33521. #if SQLITE_MAX_MMAP_SIZE>0
  33522. /* Deal with as much of this write request as possible by transfering
  33523. ** data from the memory mapping using memcpy(). */
  33524. if( offset<pFile->mmapSize ){
  33525. if( offset+amt <= pFile->mmapSize ){
  33526. memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, amt);
  33527. OSTRACE(("WRITE-MMAP pid=%lu, pFile=%p, file=%p, rc=SQLITE_OK\n",
  33528. osGetCurrentProcessId(), pFile, pFile->h));
  33529. return SQLITE_OK;
  33530. }else{
  33531. int nCopy = (int)(pFile->mmapSize - offset);
  33532. memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, nCopy);
  33533. pBuf = &((u8 *)pBuf)[nCopy];
  33534. amt -= nCopy;
  33535. offset += nCopy;
  33536. }
  33537. }
  33538. #endif
  33539. #if SQLITE_OS_WINCE || defined(SQLITE_WIN32_NO_OVERLAPPED)
  33540. rc = winSeekFile(pFile, offset);
  33541. if( rc==0 ){
  33542. #else
  33543. {
  33544. #endif
  33545. #if !SQLITE_OS_WINCE && !defined(SQLITE_WIN32_NO_OVERLAPPED)
  33546. OVERLAPPED overlapped; /* The offset for WriteFile. */
  33547. #endif
  33548. u8 *aRem = (u8 *)pBuf; /* Data yet to be written */
  33549. int nRem = amt; /* Number of bytes yet to be written */
  33550. DWORD nWrite; /* Bytes written by each WriteFile() call */
  33551. DWORD lastErrno = NO_ERROR; /* Value returned by GetLastError() */
  33552. #if !SQLITE_OS_WINCE && !defined(SQLITE_WIN32_NO_OVERLAPPED)
  33553. memset(&overlapped, 0, sizeof(OVERLAPPED));
  33554. overlapped.Offset = (LONG)(offset & 0xffffffff);
  33555. overlapped.OffsetHigh = (LONG)((offset>>32) & 0x7fffffff);
  33556. #endif
  33557. while( nRem>0 ){
  33558. #if SQLITE_OS_WINCE || defined(SQLITE_WIN32_NO_OVERLAPPED)
  33559. if( !osWriteFile(pFile->h, aRem, nRem, &nWrite, 0) ){
  33560. #else
  33561. if( !osWriteFile(pFile->h, aRem, nRem, &nWrite, &overlapped) ){
  33562. #endif
  33563. if( winRetryIoerr(&nRetry, &lastErrno) ) continue;
  33564. break;
  33565. }
  33566. assert( nWrite==0 || nWrite<=(DWORD)nRem );
  33567. if( nWrite==0 || nWrite>(DWORD)nRem ){
  33568. lastErrno = osGetLastError();
  33569. break;
  33570. }
  33571. #if !SQLITE_OS_WINCE && !defined(SQLITE_WIN32_NO_OVERLAPPED)
  33572. offset += nWrite;
  33573. overlapped.Offset = (LONG)(offset & 0xffffffff);
  33574. overlapped.OffsetHigh = (LONG)((offset>>32) & 0x7fffffff);
  33575. #endif
  33576. aRem += nWrite;
  33577. nRem -= nWrite;
  33578. }
  33579. if( nRem>0 ){
  33580. pFile->lastErrno = lastErrno;
  33581. rc = 1;
  33582. }
  33583. }
  33584. if( rc ){
  33585. if( ( pFile->lastErrno==ERROR_HANDLE_DISK_FULL )
  33586. || ( pFile->lastErrno==ERROR_DISK_FULL )){
  33587. OSTRACE(("WRITE pid=%lu, pFile=%p, file=%p, rc=SQLITE_FULL\n",
  33588. osGetCurrentProcessId(), pFile, pFile->h));
  33589. return winLogError(SQLITE_FULL, pFile->lastErrno,
  33590. "winWrite1", pFile->zPath);
  33591. }
  33592. OSTRACE(("WRITE pid=%lu, pFile=%p, file=%p, rc=SQLITE_IOERR_WRITE\n",
  33593. osGetCurrentProcessId(), pFile, pFile->h));
  33594. return winLogError(SQLITE_IOERR_WRITE, pFile->lastErrno,
  33595. "winWrite2", pFile->zPath);
  33596. }else{
  33597. winLogIoerr(nRetry, __LINE__);
  33598. }
  33599. OSTRACE(("WRITE pid=%lu, pFile=%p, file=%p, rc=SQLITE_OK\n",
  33600. osGetCurrentProcessId(), pFile, pFile->h));
  33601. return SQLITE_OK;
  33602. }
  33603. /*
  33604. ** Truncate an open file to a specified size
  33605. */
  33606. static int winTruncate(sqlite3_file *id, sqlite3_int64 nByte){
  33607. winFile *pFile = (winFile*)id; /* File handle object */
  33608. int rc = SQLITE_OK; /* Return code for this function */
  33609. DWORD lastErrno;
  33610. assert( pFile );
  33611. SimulateIOError(return SQLITE_IOERR_TRUNCATE);
  33612. OSTRACE(("TRUNCATE pid=%lu, pFile=%p, file=%p, size=%lld, lock=%d\n",
  33613. osGetCurrentProcessId(), pFile, pFile->h, nByte, pFile->locktype));
  33614. /* If the user has configured a chunk-size for this file, truncate the
  33615. ** file so that it consists of an integer number of chunks (i.e. the
  33616. ** actual file size after the operation may be larger than the requested
  33617. ** size).
  33618. */
  33619. if( pFile->szChunk>0 ){
  33620. nByte = ((nByte + pFile->szChunk - 1)/pFile->szChunk) * pFile->szChunk;
  33621. }
  33622. /* SetEndOfFile() returns non-zero when successful, or zero when it fails. */
  33623. if( winSeekFile(pFile, nByte) ){
  33624. rc = winLogError(SQLITE_IOERR_TRUNCATE, pFile->lastErrno,
  33625. "winTruncate1", pFile->zPath);
  33626. }else if( 0==osSetEndOfFile(pFile->h) &&
  33627. ((lastErrno = osGetLastError())!=ERROR_USER_MAPPED_FILE) ){
  33628. pFile->lastErrno = lastErrno;
  33629. rc = winLogError(SQLITE_IOERR_TRUNCATE, pFile->lastErrno,
  33630. "winTruncate2", pFile->zPath);
  33631. }
  33632. #if SQLITE_MAX_MMAP_SIZE>0
  33633. /* If the file was truncated to a size smaller than the currently
  33634. ** mapped region, reduce the effective mapping size as well. SQLite will
  33635. ** use read() and write() to access data beyond this point from now on.
  33636. */
  33637. if( pFile->pMapRegion && nByte<pFile->mmapSize ){
  33638. pFile->mmapSize = nByte;
  33639. }
  33640. #endif
  33641. OSTRACE(("TRUNCATE pid=%lu, pFile=%p, file=%p, rc=%s\n",
  33642. osGetCurrentProcessId(), pFile, pFile->h, sqlite3ErrName(rc)));
  33643. return rc;
  33644. }
  33645. #ifdef SQLITE_TEST
  33646. /*
  33647. ** Count the number of fullsyncs and normal syncs. This is used to test
  33648. ** that syncs and fullsyncs are occuring at the right times.
  33649. */
  33650. SQLITE_API int sqlite3_sync_count = 0;
  33651. SQLITE_API int sqlite3_fullsync_count = 0;
  33652. #endif
  33653. /*
  33654. ** Make sure all writes to a particular file are committed to disk.
  33655. */
  33656. static int winSync(sqlite3_file *id, int flags){
  33657. #ifndef SQLITE_NO_SYNC
  33658. /*
  33659. ** Used only when SQLITE_NO_SYNC is not defined.
  33660. */
  33661. BOOL rc;
  33662. #endif
  33663. #if !defined(NDEBUG) || !defined(SQLITE_NO_SYNC) || \
  33664. defined(SQLITE_HAVE_OS_TRACE)
  33665. /*
  33666. ** Used when SQLITE_NO_SYNC is not defined and by the assert() and/or
  33667. ** OSTRACE() macros.
  33668. */
  33669. winFile *pFile = (winFile*)id;
  33670. #else
  33671. UNUSED_PARAMETER(id);
  33672. #endif
  33673. assert( pFile );
  33674. /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
  33675. assert((flags&0x0F)==SQLITE_SYNC_NORMAL
  33676. || (flags&0x0F)==SQLITE_SYNC_FULL
  33677. );
  33678. /* Unix cannot, but some systems may return SQLITE_FULL from here. This
  33679. ** line is to test that doing so does not cause any problems.
  33680. */
  33681. SimulateDiskfullError( return SQLITE_FULL );
  33682. OSTRACE(("SYNC pid=%lu, pFile=%p, file=%p, flags=%x, lock=%d\n",
  33683. osGetCurrentProcessId(), pFile, pFile->h, flags,
  33684. pFile->locktype));
  33685. #ifndef SQLITE_TEST
  33686. UNUSED_PARAMETER(flags);
  33687. #else
  33688. if( (flags&0x0F)==SQLITE_SYNC_FULL ){
  33689. sqlite3_fullsync_count++;
  33690. }
  33691. sqlite3_sync_count++;
  33692. #endif
  33693. /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
  33694. ** no-op
  33695. */
  33696. #ifdef SQLITE_NO_SYNC
  33697. OSTRACE(("SYNC-NOP pid=%lu, pFile=%p, file=%p, rc=SQLITE_OK\n",
  33698. osGetCurrentProcessId(), pFile, pFile->h));
  33699. return SQLITE_OK;
  33700. #else
  33701. #if SQLITE_MAX_MMAP_SIZE>0
  33702. if( pFile->pMapRegion ){
  33703. if( osFlushViewOfFile(pFile->pMapRegion, 0) ){
  33704. OSTRACE(("SYNC-MMAP pid=%lu, pFile=%p, pMapRegion=%p, "
  33705. "rc=SQLITE_OK\n", osGetCurrentProcessId(),
  33706. pFile, pFile->pMapRegion));
  33707. }else{
  33708. pFile->lastErrno = osGetLastError();
  33709. OSTRACE(("SYNC-MMAP pid=%lu, pFile=%p, pMapRegion=%p, "
  33710. "rc=SQLITE_IOERR_MMAP\n", osGetCurrentProcessId(),
  33711. pFile, pFile->pMapRegion));
  33712. return winLogError(SQLITE_IOERR_MMAP, pFile->lastErrno,
  33713. "winSync1", pFile->zPath);
  33714. }
  33715. }
  33716. #endif
  33717. rc = osFlushFileBuffers(pFile->h);
  33718. SimulateIOError( rc=FALSE );
  33719. if( rc ){
  33720. OSTRACE(("SYNC pid=%lu, pFile=%p, file=%p, rc=SQLITE_OK\n",
  33721. osGetCurrentProcessId(), pFile, pFile->h));
  33722. return SQLITE_OK;
  33723. }else{
  33724. pFile->lastErrno = osGetLastError();
  33725. OSTRACE(("SYNC pid=%lu, pFile=%p, file=%p, rc=SQLITE_IOERR_FSYNC\n",
  33726. osGetCurrentProcessId(), pFile, pFile->h));
  33727. return winLogError(SQLITE_IOERR_FSYNC, pFile->lastErrno,
  33728. "winSync2", pFile->zPath);
  33729. }
  33730. #endif
  33731. }
  33732. /*
  33733. ** Determine the current size of a file in bytes
  33734. */
  33735. static int winFileSize(sqlite3_file *id, sqlite3_int64 *pSize){
  33736. winFile *pFile = (winFile*)id;
  33737. int rc = SQLITE_OK;
  33738. assert( id!=0 );
  33739. assert( pSize!=0 );
  33740. SimulateIOError(return SQLITE_IOERR_FSTAT);
  33741. OSTRACE(("SIZE file=%p, pSize=%p\n", pFile->h, pSize));
  33742. #if SQLITE_OS_WINRT
  33743. {
  33744. FILE_STANDARD_INFO info;
  33745. if( osGetFileInformationByHandleEx(pFile->h, FileStandardInfo,
  33746. &info, sizeof(info)) ){
  33747. *pSize = info.EndOfFile.QuadPart;
  33748. }else{
  33749. pFile->lastErrno = osGetLastError();
  33750. rc = winLogError(SQLITE_IOERR_FSTAT, pFile->lastErrno,
  33751. "winFileSize", pFile->zPath);
  33752. }
  33753. }
  33754. #else
  33755. {
  33756. DWORD upperBits;
  33757. DWORD lowerBits;
  33758. DWORD lastErrno;
  33759. lowerBits = osGetFileSize(pFile->h, &upperBits);
  33760. *pSize = (((sqlite3_int64)upperBits)<<32) + lowerBits;
  33761. if( (lowerBits == INVALID_FILE_SIZE)
  33762. && ((lastErrno = osGetLastError())!=NO_ERROR) ){
  33763. pFile->lastErrno = lastErrno;
  33764. rc = winLogError(SQLITE_IOERR_FSTAT, pFile->lastErrno,
  33765. "winFileSize", pFile->zPath);
  33766. }
  33767. }
  33768. #endif
  33769. OSTRACE(("SIZE file=%p, pSize=%p, *pSize=%lld, rc=%s\n",
  33770. pFile->h, pSize, *pSize, sqlite3ErrName(rc)));
  33771. return rc;
  33772. }
  33773. /*
  33774. ** LOCKFILE_FAIL_IMMEDIATELY is undefined on some Windows systems.
  33775. */
  33776. #ifndef LOCKFILE_FAIL_IMMEDIATELY
  33777. # define LOCKFILE_FAIL_IMMEDIATELY 1
  33778. #endif
  33779. #ifndef LOCKFILE_EXCLUSIVE_LOCK
  33780. # define LOCKFILE_EXCLUSIVE_LOCK 2
  33781. #endif
  33782. /*
  33783. ** Historically, SQLite has used both the LockFile and LockFileEx functions.
  33784. ** When the LockFile function was used, it was always expected to fail
  33785. ** immediately if the lock could not be obtained. Also, it always expected to
  33786. ** obtain an exclusive lock. These flags are used with the LockFileEx function
  33787. ** and reflect those expectations; therefore, they should not be changed.
  33788. */
  33789. #ifndef SQLITE_LOCKFILE_FLAGS
  33790. # define SQLITE_LOCKFILE_FLAGS (LOCKFILE_FAIL_IMMEDIATELY | \
  33791. LOCKFILE_EXCLUSIVE_LOCK)
  33792. #endif
  33793. /*
  33794. ** Currently, SQLite never calls the LockFileEx function without wanting the
  33795. ** call to fail immediately if the lock cannot be obtained.
  33796. */
  33797. #ifndef SQLITE_LOCKFILEEX_FLAGS
  33798. # define SQLITE_LOCKFILEEX_FLAGS (LOCKFILE_FAIL_IMMEDIATELY)
  33799. #endif
  33800. /*
  33801. ** Acquire a reader lock.
  33802. ** Different API routines are called depending on whether or not this
  33803. ** is Win9x or WinNT.
  33804. */
  33805. static int winGetReadLock(winFile *pFile){
  33806. int res;
  33807. OSTRACE(("READ-LOCK file=%p, lock=%d\n", pFile->h, pFile->locktype));
  33808. if( osIsNT() ){
  33809. #if SQLITE_OS_WINCE
  33810. /*
  33811. ** NOTE: Windows CE is handled differently here due its lack of the Win32
  33812. ** API LockFileEx.
  33813. */
  33814. res = winceLockFile(&pFile->h, SHARED_FIRST, 0, 1, 0);
  33815. #else
  33816. res = winLockFile(&pFile->h, SQLITE_LOCKFILEEX_FLAGS, SHARED_FIRST, 0,
  33817. SHARED_SIZE, 0);
  33818. #endif
  33819. }
  33820. #ifdef SQLITE_WIN32_HAS_ANSI
  33821. else{
  33822. int lk;
  33823. sqlite3_randomness(sizeof(lk), &lk);
  33824. pFile->sharedLockByte = (short)((lk & 0x7fffffff)%(SHARED_SIZE - 1));
  33825. res = winLockFile(&pFile->h, SQLITE_LOCKFILE_FLAGS,
  33826. SHARED_FIRST+pFile->sharedLockByte, 0, 1, 0);
  33827. }
  33828. #endif
  33829. if( res == 0 ){
  33830. pFile->lastErrno = osGetLastError();
  33831. /* No need to log a failure to lock */
  33832. }
  33833. OSTRACE(("READ-LOCK file=%p, result=%d\n", pFile->h, res));
  33834. return res;
  33835. }
  33836. /*
  33837. ** Undo a readlock
  33838. */
  33839. static int winUnlockReadLock(winFile *pFile){
  33840. int res;
  33841. DWORD lastErrno;
  33842. OSTRACE(("READ-UNLOCK file=%p, lock=%d\n", pFile->h, pFile->locktype));
  33843. if( osIsNT() ){
  33844. res = winUnlockFile(&pFile->h, SHARED_FIRST, 0, SHARED_SIZE, 0);
  33845. }
  33846. #ifdef SQLITE_WIN32_HAS_ANSI
  33847. else{
  33848. res = winUnlockFile(&pFile->h, SHARED_FIRST+pFile->sharedLockByte, 0, 1, 0);
  33849. }
  33850. #endif
  33851. if( res==0 && ((lastErrno = osGetLastError())!=ERROR_NOT_LOCKED) ){
  33852. pFile->lastErrno = lastErrno;
  33853. winLogError(SQLITE_IOERR_UNLOCK, pFile->lastErrno,
  33854. "winUnlockReadLock", pFile->zPath);
  33855. }
  33856. OSTRACE(("READ-UNLOCK file=%p, result=%d\n", pFile->h, res));
  33857. return res;
  33858. }
  33859. /*
  33860. ** Lock the file with the lock specified by parameter locktype - one
  33861. ** of the following:
  33862. **
  33863. ** (1) SHARED_LOCK
  33864. ** (2) RESERVED_LOCK
  33865. ** (3) PENDING_LOCK
  33866. ** (4) EXCLUSIVE_LOCK
  33867. **
  33868. ** Sometimes when requesting one lock state, additional lock states
  33869. ** are inserted in between. The locking might fail on one of the later
  33870. ** transitions leaving the lock state different from what it started but
  33871. ** still short of its goal. The following chart shows the allowed
  33872. ** transitions and the inserted intermediate states:
  33873. **
  33874. ** UNLOCKED -> SHARED
  33875. ** SHARED -> RESERVED
  33876. ** SHARED -> (PENDING) -> EXCLUSIVE
  33877. ** RESERVED -> (PENDING) -> EXCLUSIVE
  33878. ** PENDING -> EXCLUSIVE
  33879. **
  33880. ** This routine will only increase a lock. The winUnlock() routine
  33881. ** erases all locks at once and returns us immediately to locking level 0.
  33882. ** It is not possible to lower the locking level one step at a time. You
  33883. ** must go straight to locking level 0.
  33884. */
  33885. static int winLock(sqlite3_file *id, int locktype){
  33886. int rc = SQLITE_OK; /* Return code from subroutines */
  33887. int res = 1; /* Result of a Windows lock call */
  33888. int newLocktype; /* Set pFile->locktype to this value before exiting */
  33889. int gotPendingLock = 0;/* True if we acquired a PENDING lock this time */
  33890. winFile *pFile = (winFile*)id;
  33891. DWORD lastErrno = NO_ERROR;
  33892. assert( id!=0 );
  33893. OSTRACE(("LOCK file=%p, oldLock=%d(%d), newLock=%d\n",
  33894. pFile->h, pFile->locktype, pFile->sharedLockByte, locktype));
  33895. /* If there is already a lock of this type or more restrictive on the
  33896. ** OsFile, do nothing. Don't use the end_lock: exit path, as
  33897. ** sqlite3OsEnterMutex() hasn't been called yet.
  33898. */
  33899. if( pFile->locktype>=locktype ){
  33900. OSTRACE(("LOCK-HELD file=%p, rc=SQLITE_OK\n", pFile->h));
  33901. return SQLITE_OK;
  33902. }
  33903. /* Make sure the locking sequence is correct
  33904. */
  33905. assert( pFile->locktype!=NO_LOCK || locktype==SHARED_LOCK );
  33906. assert( locktype!=PENDING_LOCK );
  33907. assert( locktype!=RESERVED_LOCK || pFile->locktype==SHARED_LOCK );
  33908. /* Lock the PENDING_LOCK byte if we need to acquire a PENDING lock or
  33909. ** a SHARED lock. If we are acquiring a SHARED lock, the acquisition of
  33910. ** the PENDING_LOCK byte is temporary.
  33911. */
  33912. newLocktype = pFile->locktype;
  33913. if( (pFile->locktype==NO_LOCK)
  33914. || ( (locktype==EXCLUSIVE_LOCK)
  33915. && (pFile->locktype==RESERVED_LOCK))
  33916. ){
  33917. int cnt = 3;
  33918. while( cnt-->0 && (res = winLockFile(&pFile->h, SQLITE_LOCKFILE_FLAGS,
  33919. PENDING_BYTE, 0, 1, 0))==0 ){
  33920. /* Try 3 times to get the pending lock. This is needed to work
  33921. ** around problems caused by indexing and/or anti-virus software on
  33922. ** Windows systems.
  33923. ** If you are using this code as a model for alternative VFSes, do not
  33924. ** copy this retry logic. It is a hack intended for Windows only.
  33925. */
  33926. lastErrno = osGetLastError();
  33927. OSTRACE(("LOCK-PENDING-FAIL file=%p, count=%d, result=%d\n",
  33928. pFile->h, cnt, res));
  33929. if( lastErrno==ERROR_INVALID_HANDLE ){
  33930. pFile->lastErrno = lastErrno;
  33931. rc = SQLITE_IOERR_LOCK;
  33932. OSTRACE(("LOCK-FAIL file=%p, count=%d, rc=%s\n",
  33933. pFile->h, cnt, sqlite3ErrName(rc)));
  33934. return rc;
  33935. }
  33936. if( cnt ) sqlite3_win32_sleep(1);
  33937. }
  33938. gotPendingLock = res;
  33939. if( !res ){
  33940. lastErrno = osGetLastError();
  33941. }
  33942. }
  33943. /* Acquire a shared lock
  33944. */
  33945. if( locktype==SHARED_LOCK && res ){
  33946. assert( pFile->locktype==NO_LOCK );
  33947. res = winGetReadLock(pFile);
  33948. if( res ){
  33949. newLocktype = SHARED_LOCK;
  33950. }else{
  33951. lastErrno = osGetLastError();
  33952. }
  33953. }
  33954. /* Acquire a RESERVED lock
  33955. */
  33956. if( locktype==RESERVED_LOCK && res ){
  33957. assert( pFile->locktype==SHARED_LOCK );
  33958. res = winLockFile(&pFile->h, SQLITE_LOCKFILE_FLAGS, RESERVED_BYTE, 0, 1, 0);
  33959. if( res ){
  33960. newLocktype = RESERVED_LOCK;
  33961. }else{
  33962. lastErrno = osGetLastError();
  33963. }
  33964. }
  33965. /* Acquire a PENDING lock
  33966. */
  33967. if( locktype==EXCLUSIVE_LOCK && res ){
  33968. newLocktype = PENDING_LOCK;
  33969. gotPendingLock = 0;
  33970. }
  33971. /* Acquire an EXCLUSIVE lock
  33972. */
  33973. if( locktype==EXCLUSIVE_LOCK && res ){
  33974. assert( pFile->locktype>=SHARED_LOCK );
  33975. res = winUnlockReadLock(pFile);
  33976. res = winLockFile(&pFile->h, SQLITE_LOCKFILE_FLAGS, SHARED_FIRST, 0,
  33977. SHARED_SIZE, 0);
  33978. if( res ){
  33979. newLocktype = EXCLUSIVE_LOCK;
  33980. }else{
  33981. lastErrno = osGetLastError();
  33982. winGetReadLock(pFile);
  33983. }
  33984. }
  33985. /* If we are holding a PENDING lock that ought to be released, then
  33986. ** release it now.
  33987. */
  33988. if( gotPendingLock && locktype==SHARED_LOCK ){
  33989. winUnlockFile(&pFile->h, PENDING_BYTE, 0, 1, 0);
  33990. }
  33991. /* Update the state of the lock has held in the file descriptor then
  33992. ** return the appropriate result code.
  33993. */
  33994. if( res ){
  33995. rc = SQLITE_OK;
  33996. }else{
  33997. pFile->lastErrno = lastErrno;
  33998. rc = SQLITE_BUSY;
  33999. OSTRACE(("LOCK-FAIL file=%p, wanted=%d, got=%d\n",
  34000. pFile->h, locktype, newLocktype));
  34001. }
  34002. pFile->locktype = (u8)newLocktype;
  34003. OSTRACE(("LOCK file=%p, lock=%d, rc=%s\n",
  34004. pFile->h, pFile->locktype, sqlite3ErrName(rc)));
  34005. return rc;
  34006. }
  34007. /*
  34008. ** This routine checks if there is a RESERVED lock held on the specified
  34009. ** file by this or any other process. If such a lock is held, return
  34010. ** non-zero, otherwise zero.
  34011. */
  34012. static int winCheckReservedLock(sqlite3_file *id, int *pResOut){
  34013. int res;
  34014. winFile *pFile = (winFile*)id;
  34015. SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
  34016. OSTRACE(("TEST-WR-LOCK file=%p, pResOut=%p\n", pFile->h, pResOut));
  34017. assert( id!=0 );
  34018. if( pFile->locktype>=RESERVED_LOCK ){
  34019. res = 1;
  34020. OSTRACE(("TEST-WR-LOCK file=%p, result=%d (local)\n", pFile->h, res));
  34021. }else{
  34022. res = winLockFile(&pFile->h, SQLITE_LOCKFILEEX_FLAGS,RESERVED_BYTE, 0, 1, 0);
  34023. if( res ){
  34024. winUnlockFile(&pFile->h, RESERVED_BYTE, 0, 1, 0);
  34025. }
  34026. res = !res;
  34027. OSTRACE(("TEST-WR-LOCK file=%p, result=%d (remote)\n", pFile->h, res));
  34028. }
  34029. *pResOut = res;
  34030. OSTRACE(("TEST-WR-LOCK file=%p, pResOut=%p, *pResOut=%d, rc=SQLITE_OK\n",
  34031. pFile->h, pResOut, *pResOut));
  34032. return SQLITE_OK;
  34033. }
  34034. /*
  34035. ** Lower the locking level on file descriptor id to locktype. locktype
  34036. ** must be either NO_LOCK or SHARED_LOCK.
  34037. **
  34038. ** If the locking level of the file descriptor is already at or below
  34039. ** the requested locking level, this routine is a no-op.
  34040. **
  34041. ** It is not possible for this routine to fail if the second argument
  34042. ** is NO_LOCK. If the second argument is SHARED_LOCK then this routine
  34043. ** might return SQLITE_IOERR;
  34044. */
  34045. static int winUnlock(sqlite3_file *id, int locktype){
  34046. int type;
  34047. winFile *pFile = (winFile*)id;
  34048. int rc = SQLITE_OK;
  34049. assert( pFile!=0 );
  34050. assert( locktype<=SHARED_LOCK );
  34051. OSTRACE(("UNLOCK file=%p, oldLock=%d(%d), newLock=%d\n",
  34052. pFile->h, pFile->locktype, pFile->sharedLockByte, locktype));
  34053. type = pFile->locktype;
  34054. if( type>=EXCLUSIVE_LOCK ){
  34055. winUnlockFile(&pFile->h, SHARED_FIRST, 0, SHARED_SIZE, 0);
  34056. if( locktype==SHARED_LOCK && !winGetReadLock(pFile) ){
  34057. /* This should never happen. We should always be able to
  34058. ** reacquire the read lock */
  34059. rc = winLogError(SQLITE_IOERR_UNLOCK, osGetLastError(),
  34060. "winUnlock", pFile->zPath);
  34061. }
  34062. }
  34063. if( type>=RESERVED_LOCK ){
  34064. winUnlockFile(&pFile->h, RESERVED_BYTE, 0, 1, 0);
  34065. }
  34066. if( locktype==NO_LOCK && type>=SHARED_LOCK ){
  34067. winUnlockReadLock(pFile);
  34068. }
  34069. if( type>=PENDING_LOCK ){
  34070. winUnlockFile(&pFile->h, PENDING_BYTE, 0, 1, 0);
  34071. }
  34072. pFile->locktype = (u8)locktype;
  34073. OSTRACE(("UNLOCK file=%p, lock=%d, rc=%s\n",
  34074. pFile->h, pFile->locktype, sqlite3ErrName(rc)));
  34075. return rc;
  34076. }
  34077. /*
  34078. ** If *pArg is initially negative then this is a query. Set *pArg to
  34079. ** 1 or 0 depending on whether or not bit mask of pFile->ctrlFlags is set.
  34080. **
  34081. ** If *pArg is 0 or 1, then clear or set the mask bit of pFile->ctrlFlags.
  34082. */
  34083. static void winModeBit(winFile *pFile, unsigned char mask, int *pArg){
  34084. if( *pArg<0 ){
  34085. *pArg = (pFile->ctrlFlags & mask)!=0;
  34086. }else if( (*pArg)==0 ){
  34087. pFile->ctrlFlags &= ~mask;
  34088. }else{
  34089. pFile->ctrlFlags |= mask;
  34090. }
  34091. }
  34092. /* Forward references to VFS helper methods used for temporary files */
  34093. static int winGetTempname(sqlite3_vfs *, char **);
  34094. static int winIsDir(const void *);
  34095. static BOOL winIsDriveLetterAndColon(const char *);
  34096. /*
  34097. ** Control and query of the open file handle.
  34098. */
  34099. static int winFileControl(sqlite3_file *id, int op, void *pArg){
  34100. winFile *pFile = (winFile*)id;
  34101. OSTRACE(("FCNTL file=%p, op=%d, pArg=%p\n", pFile->h, op, pArg));
  34102. switch( op ){
  34103. case SQLITE_FCNTL_LOCKSTATE: {
  34104. *(int*)pArg = pFile->locktype;
  34105. OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
  34106. return SQLITE_OK;
  34107. }
  34108. case SQLITE_LAST_ERRNO: {
  34109. *(int*)pArg = (int)pFile->lastErrno;
  34110. OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
  34111. return SQLITE_OK;
  34112. }
  34113. case SQLITE_FCNTL_CHUNK_SIZE: {
  34114. pFile->szChunk = *(int *)pArg;
  34115. OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
  34116. return SQLITE_OK;
  34117. }
  34118. case SQLITE_FCNTL_SIZE_HINT: {
  34119. if( pFile->szChunk>0 ){
  34120. sqlite3_int64 oldSz;
  34121. int rc = winFileSize(id, &oldSz);
  34122. if( rc==SQLITE_OK ){
  34123. sqlite3_int64 newSz = *(sqlite3_int64*)pArg;
  34124. if( newSz>oldSz ){
  34125. SimulateIOErrorBenign(1);
  34126. rc = winTruncate(id, newSz);
  34127. SimulateIOErrorBenign(0);
  34128. }
  34129. }
  34130. OSTRACE(("FCNTL file=%p, rc=%s\n", pFile->h, sqlite3ErrName(rc)));
  34131. return rc;
  34132. }
  34133. OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
  34134. return SQLITE_OK;
  34135. }
  34136. case SQLITE_FCNTL_PERSIST_WAL: {
  34137. winModeBit(pFile, WINFILE_PERSIST_WAL, (int*)pArg);
  34138. OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
  34139. return SQLITE_OK;
  34140. }
  34141. case SQLITE_FCNTL_POWERSAFE_OVERWRITE: {
  34142. winModeBit(pFile, WINFILE_PSOW, (int*)pArg);
  34143. OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
  34144. return SQLITE_OK;
  34145. }
  34146. case SQLITE_FCNTL_VFSNAME: {
  34147. *(char**)pArg = sqlite3_mprintf("%s", pFile->pVfs->zName);
  34148. OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
  34149. return SQLITE_OK;
  34150. }
  34151. case SQLITE_FCNTL_WIN32_AV_RETRY: {
  34152. int *a = (int*)pArg;
  34153. if( a[0]>0 ){
  34154. winIoerrRetry = a[0];
  34155. }else{
  34156. a[0] = winIoerrRetry;
  34157. }
  34158. if( a[1]>0 ){
  34159. winIoerrRetryDelay = a[1];
  34160. }else{
  34161. a[1] = winIoerrRetryDelay;
  34162. }
  34163. OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
  34164. return SQLITE_OK;
  34165. }
  34166. #ifdef SQLITE_TEST
  34167. case SQLITE_FCNTL_WIN32_SET_HANDLE: {
  34168. LPHANDLE phFile = (LPHANDLE)pArg;
  34169. HANDLE hOldFile = pFile->h;
  34170. pFile->h = *phFile;
  34171. *phFile = hOldFile;
  34172. OSTRACE(("FCNTL oldFile=%p, newFile=%p, rc=SQLITE_OK\n",
  34173. hOldFile, pFile->h));
  34174. return SQLITE_OK;
  34175. }
  34176. #endif
  34177. case SQLITE_FCNTL_TEMPFILENAME: {
  34178. char *zTFile = 0;
  34179. int rc = winGetTempname(pFile->pVfs, &zTFile);
  34180. if( rc==SQLITE_OK ){
  34181. *(char**)pArg = zTFile;
  34182. }
  34183. OSTRACE(("FCNTL file=%p, rc=%s\n", pFile->h, sqlite3ErrName(rc)));
  34184. return rc;
  34185. }
  34186. #if SQLITE_MAX_MMAP_SIZE>0
  34187. case SQLITE_FCNTL_MMAP_SIZE: {
  34188. i64 newLimit = *(i64*)pArg;
  34189. int rc = SQLITE_OK;
  34190. if( newLimit>sqlite3GlobalConfig.mxMmap ){
  34191. newLimit = sqlite3GlobalConfig.mxMmap;
  34192. }
  34193. *(i64*)pArg = pFile->mmapSizeMax;
  34194. if( newLimit>=0 && newLimit!=pFile->mmapSizeMax && pFile->nFetchOut==0 ){
  34195. pFile->mmapSizeMax = newLimit;
  34196. if( pFile->mmapSize>0 ){
  34197. winUnmapfile(pFile);
  34198. rc = winMapfile(pFile, -1);
  34199. }
  34200. }
  34201. OSTRACE(("FCNTL file=%p, rc=%s\n", pFile->h, sqlite3ErrName(rc)));
  34202. return rc;
  34203. }
  34204. #endif
  34205. }
  34206. OSTRACE(("FCNTL file=%p, rc=SQLITE_NOTFOUND\n", pFile->h));
  34207. return SQLITE_NOTFOUND;
  34208. }
  34209. /*
  34210. ** Return the sector size in bytes of the underlying block device for
  34211. ** the specified file. This is almost always 512 bytes, but may be
  34212. ** larger for some devices.
  34213. **
  34214. ** SQLite code assumes this function cannot fail. It also assumes that
  34215. ** if two files are created in the same file-system directory (i.e.
  34216. ** a database and its journal file) that the sector size will be the
  34217. ** same for both.
  34218. */
  34219. static int winSectorSize(sqlite3_file *id){
  34220. (void)id;
  34221. return SQLITE_DEFAULT_SECTOR_SIZE;
  34222. }
  34223. /*
  34224. ** Return a vector of device characteristics.
  34225. */
  34226. static int winDeviceCharacteristics(sqlite3_file *id){
  34227. winFile *p = (winFile*)id;
  34228. return SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN |
  34229. ((p->ctrlFlags & WINFILE_PSOW)?SQLITE_IOCAP_POWERSAFE_OVERWRITE:0);
  34230. }
  34231. /*
  34232. ** Windows will only let you create file view mappings
  34233. ** on allocation size granularity boundaries.
  34234. ** During sqlite3_os_init() we do a GetSystemInfo()
  34235. ** to get the granularity size.
  34236. */
  34237. static SYSTEM_INFO winSysInfo;
  34238. #ifndef SQLITE_OMIT_WAL
  34239. /*
  34240. ** Helper functions to obtain and relinquish the global mutex. The
  34241. ** global mutex is used to protect the winLockInfo objects used by
  34242. ** this file, all of which may be shared by multiple threads.
  34243. **
  34244. ** Function winShmMutexHeld() is used to assert() that the global mutex
  34245. ** is held when required. This function is only used as part of assert()
  34246. ** statements. e.g.
  34247. **
  34248. ** winShmEnterMutex()
  34249. ** assert( winShmMutexHeld() );
  34250. ** winShmLeaveMutex()
  34251. */
  34252. static void winShmEnterMutex(void){
  34253. sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
  34254. }
  34255. static void winShmLeaveMutex(void){
  34256. sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
  34257. }
  34258. #ifndef NDEBUG
  34259. static int winShmMutexHeld(void) {
  34260. return sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
  34261. }
  34262. #endif
  34263. /*
  34264. ** Object used to represent a single file opened and mmapped to provide
  34265. ** shared memory. When multiple threads all reference the same
  34266. ** log-summary, each thread has its own winFile object, but they all
  34267. ** point to a single instance of this object. In other words, each
  34268. ** log-summary is opened only once per process.
  34269. **
  34270. ** winShmMutexHeld() must be true when creating or destroying
  34271. ** this object or while reading or writing the following fields:
  34272. **
  34273. ** nRef
  34274. ** pNext
  34275. **
  34276. ** The following fields are read-only after the object is created:
  34277. **
  34278. ** fid
  34279. ** zFilename
  34280. **
  34281. ** Either winShmNode.mutex must be held or winShmNode.nRef==0 and
  34282. ** winShmMutexHeld() is true when reading or writing any other field
  34283. ** in this structure.
  34284. **
  34285. */
  34286. struct winShmNode {
  34287. sqlite3_mutex *mutex; /* Mutex to access this object */
  34288. char *zFilename; /* Name of the file */
  34289. winFile hFile; /* File handle from winOpen */
  34290. int szRegion; /* Size of shared-memory regions */
  34291. int nRegion; /* Size of array apRegion */
  34292. struct ShmRegion {
  34293. HANDLE hMap; /* File handle from CreateFileMapping */
  34294. void *pMap;
  34295. } *aRegion;
  34296. DWORD lastErrno; /* The Windows errno from the last I/O error */
  34297. int nRef; /* Number of winShm objects pointing to this */
  34298. winShm *pFirst; /* All winShm objects pointing to this */
  34299. winShmNode *pNext; /* Next in list of all winShmNode objects */
  34300. #if defined(SQLITE_DEBUG) || defined(SQLITE_HAVE_OS_TRACE)
  34301. u8 nextShmId; /* Next available winShm.id value */
  34302. #endif
  34303. };
  34304. /*
  34305. ** A global array of all winShmNode objects.
  34306. **
  34307. ** The winShmMutexHeld() must be true while reading or writing this list.
  34308. */
  34309. static winShmNode *winShmNodeList = 0;
  34310. /*
  34311. ** Structure used internally by this VFS to record the state of an
  34312. ** open shared memory connection.
  34313. **
  34314. ** The following fields are initialized when this object is created and
  34315. ** are read-only thereafter:
  34316. **
  34317. ** winShm.pShmNode
  34318. ** winShm.id
  34319. **
  34320. ** All other fields are read/write. The winShm.pShmNode->mutex must be held
  34321. ** while accessing any read/write fields.
  34322. */
  34323. struct winShm {
  34324. winShmNode *pShmNode; /* The underlying winShmNode object */
  34325. winShm *pNext; /* Next winShm with the same winShmNode */
  34326. u8 hasMutex; /* True if holding the winShmNode mutex */
  34327. u16 sharedMask; /* Mask of shared locks held */
  34328. u16 exclMask; /* Mask of exclusive locks held */
  34329. #if defined(SQLITE_DEBUG) || defined(SQLITE_HAVE_OS_TRACE)
  34330. u8 id; /* Id of this connection with its winShmNode */
  34331. #endif
  34332. };
  34333. /*
  34334. ** Constants used for locking
  34335. */
  34336. #define WIN_SHM_BASE ((22+SQLITE_SHM_NLOCK)*4) /* first lock byte */
  34337. #define WIN_SHM_DMS (WIN_SHM_BASE+SQLITE_SHM_NLOCK) /* deadman switch */
  34338. /*
  34339. ** Apply advisory locks for all n bytes beginning at ofst.
  34340. */
  34341. #define _SHM_UNLCK 1
  34342. #define _SHM_RDLCK 2
  34343. #define _SHM_WRLCK 3
  34344. static int winShmSystemLock(
  34345. winShmNode *pFile, /* Apply locks to this open shared-memory segment */
  34346. int lockType, /* _SHM_UNLCK, _SHM_RDLCK, or _SHM_WRLCK */
  34347. int ofst, /* Offset to first byte to be locked/unlocked */
  34348. int nByte /* Number of bytes to lock or unlock */
  34349. ){
  34350. int rc = 0; /* Result code form Lock/UnlockFileEx() */
  34351. /* Access to the winShmNode object is serialized by the caller */
  34352. assert( sqlite3_mutex_held(pFile->mutex) || pFile->nRef==0 );
  34353. OSTRACE(("SHM-LOCK file=%p, lock=%d, offset=%d, size=%d\n",
  34354. pFile->hFile.h, lockType, ofst, nByte));
  34355. /* Release/Acquire the system-level lock */
  34356. if( lockType==_SHM_UNLCK ){
  34357. rc = winUnlockFile(&pFile->hFile.h, ofst, 0, nByte, 0);
  34358. }else{
  34359. /* Initialize the locking parameters */
  34360. DWORD dwFlags = LOCKFILE_FAIL_IMMEDIATELY;
  34361. if( lockType == _SHM_WRLCK ) dwFlags |= LOCKFILE_EXCLUSIVE_LOCK;
  34362. rc = winLockFile(&pFile->hFile.h, dwFlags, ofst, 0, nByte, 0);
  34363. }
  34364. if( rc!= 0 ){
  34365. rc = SQLITE_OK;
  34366. }else{
  34367. pFile->lastErrno = osGetLastError();
  34368. rc = SQLITE_BUSY;
  34369. }
  34370. OSTRACE(("SHM-LOCK file=%p, func=%s, errno=%lu, rc=%s\n",
  34371. pFile->hFile.h, (lockType == _SHM_UNLCK) ? "winUnlockFile" :
  34372. "winLockFile", pFile->lastErrno, sqlite3ErrName(rc)));
  34373. return rc;
  34374. }
  34375. /* Forward references to VFS methods */
  34376. static int winOpen(sqlite3_vfs*,const char*,sqlite3_file*,int,int*);
  34377. static int winDelete(sqlite3_vfs *,const char*,int);
  34378. /*
  34379. ** Purge the winShmNodeList list of all entries with winShmNode.nRef==0.
  34380. **
  34381. ** This is not a VFS shared-memory method; it is a utility function called
  34382. ** by VFS shared-memory methods.
  34383. */
  34384. static void winShmPurge(sqlite3_vfs *pVfs, int deleteFlag){
  34385. winShmNode **pp;
  34386. winShmNode *p;
  34387. assert( winShmMutexHeld() );
  34388. OSTRACE(("SHM-PURGE pid=%lu, deleteFlag=%d\n",
  34389. osGetCurrentProcessId(), deleteFlag));
  34390. pp = &winShmNodeList;
  34391. while( (p = *pp)!=0 ){
  34392. if( p->nRef==0 ){
  34393. int i;
  34394. if( p->mutex ){ sqlite3_mutex_free(p->mutex); }
  34395. for(i=0; i<p->nRegion; i++){
  34396. BOOL bRc = osUnmapViewOfFile(p->aRegion[i].pMap);
  34397. OSTRACE(("SHM-PURGE-UNMAP pid=%lu, region=%d, rc=%s\n",
  34398. osGetCurrentProcessId(), i, bRc ? "ok" : "failed"));
  34399. UNUSED_VARIABLE_VALUE(bRc);
  34400. bRc = osCloseHandle(p->aRegion[i].hMap);
  34401. OSTRACE(("SHM-PURGE-CLOSE pid=%lu, region=%d, rc=%s\n",
  34402. osGetCurrentProcessId(), i, bRc ? "ok" : "failed"));
  34403. UNUSED_VARIABLE_VALUE(bRc);
  34404. }
  34405. if( p->hFile.h!=NULL && p->hFile.h!=INVALID_HANDLE_VALUE ){
  34406. SimulateIOErrorBenign(1);
  34407. winClose((sqlite3_file *)&p->hFile);
  34408. SimulateIOErrorBenign(0);
  34409. }
  34410. if( deleteFlag ){
  34411. SimulateIOErrorBenign(1);
  34412. sqlite3BeginBenignMalloc();
  34413. winDelete(pVfs, p->zFilename, 0);
  34414. sqlite3EndBenignMalloc();
  34415. SimulateIOErrorBenign(0);
  34416. }
  34417. *pp = p->pNext;
  34418. sqlite3_free(p->aRegion);
  34419. sqlite3_free(p);
  34420. }else{
  34421. pp = &p->pNext;
  34422. }
  34423. }
  34424. }
  34425. /*
  34426. ** Open the shared-memory area associated with database file pDbFd.
  34427. **
  34428. ** When opening a new shared-memory file, if no other instances of that
  34429. ** file are currently open, in this process or in other processes, then
  34430. ** the file must be truncated to zero length or have its header cleared.
  34431. */
  34432. static int winOpenSharedMemory(winFile *pDbFd){
  34433. struct winShm *p; /* The connection to be opened */
  34434. struct winShmNode *pShmNode = 0; /* The underlying mmapped file */
  34435. int rc; /* Result code */
  34436. struct winShmNode *pNew; /* Newly allocated winShmNode */
  34437. int nName; /* Size of zName in bytes */
  34438. assert( pDbFd->pShm==0 ); /* Not previously opened */
  34439. /* Allocate space for the new sqlite3_shm object. Also speculatively
  34440. ** allocate space for a new winShmNode and filename.
  34441. */
  34442. p = sqlite3MallocZero( sizeof(*p) );
  34443. if( p==0 ) return SQLITE_IOERR_NOMEM;
  34444. nName = sqlite3Strlen30(pDbFd->zPath);
  34445. pNew = sqlite3MallocZero( sizeof(*pShmNode) + nName + 17 );
  34446. if( pNew==0 ){
  34447. sqlite3_free(p);
  34448. return SQLITE_IOERR_NOMEM;
  34449. }
  34450. pNew->zFilename = (char*)&pNew[1];
  34451. sqlite3_snprintf(nName+15, pNew->zFilename, "%s-shm", pDbFd->zPath);
  34452. sqlite3FileSuffix3(pDbFd->zPath, pNew->zFilename);
  34453. /* Look to see if there is an existing winShmNode that can be used.
  34454. ** If no matching winShmNode currently exists, create a new one.
  34455. */
  34456. winShmEnterMutex();
  34457. for(pShmNode = winShmNodeList; pShmNode; pShmNode=pShmNode->pNext){
  34458. /* TBD need to come up with better match here. Perhaps
  34459. ** use FILE_ID_BOTH_DIR_INFO Structure.
  34460. */
  34461. if( sqlite3StrICmp(pShmNode->zFilename, pNew->zFilename)==0 ) break;
  34462. }
  34463. if( pShmNode ){
  34464. sqlite3_free(pNew);
  34465. }else{
  34466. pShmNode = pNew;
  34467. pNew = 0;
  34468. ((winFile*)(&pShmNode->hFile))->h = INVALID_HANDLE_VALUE;
  34469. pShmNode->pNext = winShmNodeList;
  34470. winShmNodeList = pShmNode;
  34471. pShmNode->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
  34472. if( pShmNode->mutex==0 ){
  34473. rc = SQLITE_IOERR_NOMEM;
  34474. goto shm_open_err;
  34475. }
  34476. rc = winOpen(pDbFd->pVfs,
  34477. pShmNode->zFilename, /* Name of the file (UTF-8) */
  34478. (sqlite3_file*)&pShmNode->hFile, /* File handle here */
  34479. SQLITE_OPEN_WAL | SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE,
  34480. 0);
  34481. if( SQLITE_OK!=rc ){
  34482. goto shm_open_err;
  34483. }
  34484. /* Check to see if another process is holding the dead-man switch.
  34485. ** If not, truncate the file to zero length.
  34486. */
  34487. if( winShmSystemLock(pShmNode, _SHM_WRLCK, WIN_SHM_DMS, 1)==SQLITE_OK ){
  34488. rc = winTruncate((sqlite3_file *)&pShmNode->hFile, 0);
  34489. if( rc!=SQLITE_OK ){
  34490. rc = winLogError(SQLITE_IOERR_SHMOPEN, osGetLastError(),
  34491. "winOpenShm", pDbFd->zPath);
  34492. }
  34493. }
  34494. if( rc==SQLITE_OK ){
  34495. winShmSystemLock(pShmNode, _SHM_UNLCK, WIN_SHM_DMS, 1);
  34496. rc = winShmSystemLock(pShmNode, _SHM_RDLCK, WIN_SHM_DMS, 1);
  34497. }
  34498. if( rc ) goto shm_open_err;
  34499. }
  34500. /* Make the new connection a child of the winShmNode */
  34501. p->pShmNode = pShmNode;
  34502. #if defined(SQLITE_DEBUG) || defined(SQLITE_HAVE_OS_TRACE)
  34503. p->id = pShmNode->nextShmId++;
  34504. #endif
  34505. pShmNode->nRef++;
  34506. pDbFd->pShm = p;
  34507. winShmLeaveMutex();
  34508. /* The reference count on pShmNode has already been incremented under
  34509. ** the cover of the winShmEnterMutex() mutex and the pointer from the
  34510. ** new (struct winShm) object to the pShmNode has been set. All that is
  34511. ** left to do is to link the new object into the linked list starting
  34512. ** at pShmNode->pFirst. This must be done while holding the pShmNode->mutex
  34513. ** mutex.
  34514. */
  34515. sqlite3_mutex_enter(pShmNode->mutex);
  34516. p->pNext = pShmNode->pFirst;
  34517. pShmNode->pFirst = p;
  34518. sqlite3_mutex_leave(pShmNode->mutex);
  34519. return SQLITE_OK;
  34520. /* Jump here on any error */
  34521. shm_open_err:
  34522. winShmSystemLock(pShmNode, _SHM_UNLCK, WIN_SHM_DMS, 1);
  34523. winShmPurge(pDbFd->pVfs, 0); /* This call frees pShmNode if required */
  34524. sqlite3_free(p);
  34525. sqlite3_free(pNew);
  34526. winShmLeaveMutex();
  34527. return rc;
  34528. }
  34529. /*
  34530. ** Close a connection to shared-memory. Delete the underlying
  34531. ** storage if deleteFlag is true.
  34532. */
  34533. static int winShmUnmap(
  34534. sqlite3_file *fd, /* Database holding shared memory */
  34535. int deleteFlag /* Delete after closing if true */
  34536. ){
  34537. winFile *pDbFd; /* Database holding shared-memory */
  34538. winShm *p; /* The connection to be closed */
  34539. winShmNode *pShmNode; /* The underlying shared-memory file */
  34540. winShm **pp; /* For looping over sibling connections */
  34541. pDbFd = (winFile*)fd;
  34542. p = pDbFd->pShm;
  34543. if( p==0 ) return SQLITE_OK;
  34544. pShmNode = p->pShmNode;
  34545. /* Remove connection p from the set of connections associated
  34546. ** with pShmNode */
  34547. sqlite3_mutex_enter(pShmNode->mutex);
  34548. for(pp=&pShmNode->pFirst; (*pp)!=p; pp = &(*pp)->pNext){}
  34549. *pp = p->pNext;
  34550. /* Free the connection p */
  34551. sqlite3_free(p);
  34552. pDbFd->pShm = 0;
  34553. sqlite3_mutex_leave(pShmNode->mutex);
  34554. /* If pShmNode->nRef has reached 0, then close the underlying
  34555. ** shared-memory file, too */
  34556. winShmEnterMutex();
  34557. assert( pShmNode->nRef>0 );
  34558. pShmNode->nRef--;
  34559. if( pShmNode->nRef==0 ){
  34560. winShmPurge(pDbFd->pVfs, deleteFlag);
  34561. }
  34562. winShmLeaveMutex();
  34563. return SQLITE_OK;
  34564. }
  34565. /*
  34566. ** Change the lock state for a shared-memory segment.
  34567. */
  34568. static int winShmLock(
  34569. sqlite3_file *fd, /* Database file holding the shared memory */
  34570. int ofst, /* First lock to acquire or release */
  34571. int n, /* Number of locks to acquire or release */
  34572. int flags /* What to do with the lock */
  34573. ){
  34574. winFile *pDbFd = (winFile*)fd; /* Connection holding shared memory */
  34575. winShm *p = pDbFd->pShm; /* The shared memory being locked */
  34576. winShm *pX; /* For looping over all siblings */
  34577. winShmNode *pShmNode = p->pShmNode;
  34578. int rc = SQLITE_OK; /* Result code */
  34579. u16 mask; /* Mask of locks to take or release */
  34580. assert( ofst>=0 && ofst+n<=SQLITE_SHM_NLOCK );
  34581. assert( n>=1 );
  34582. assert( flags==(SQLITE_SHM_LOCK | SQLITE_SHM_SHARED)
  34583. || flags==(SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE)
  34584. || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED)
  34585. || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE) );
  34586. assert( n==1 || (flags & SQLITE_SHM_EXCLUSIVE)!=0 );
  34587. mask = (u16)((1U<<(ofst+n)) - (1U<<ofst));
  34588. assert( n>1 || mask==(1<<ofst) );
  34589. sqlite3_mutex_enter(pShmNode->mutex);
  34590. if( flags & SQLITE_SHM_UNLOCK ){
  34591. u16 allMask = 0; /* Mask of locks held by siblings */
  34592. /* See if any siblings hold this same lock */
  34593. for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
  34594. if( pX==p ) continue;
  34595. assert( (pX->exclMask & (p->exclMask|p->sharedMask))==0 );
  34596. allMask |= pX->sharedMask;
  34597. }
  34598. /* Unlock the system-level locks */
  34599. if( (mask & allMask)==0 ){
  34600. rc = winShmSystemLock(pShmNode, _SHM_UNLCK, ofst+WIN_SHM_BASE, n);
  34601. }else{
  34602. rc = SQLITE_OK;
  34603. }
  34604. /* Undo the local locks */
  34605. if( rc==SQLITE_OK ){
  34606. p->exclMask &= ~mask;
  34607. p->sharedMask &= ~mask;
  34608. }
  34609. }else if( flags & SQLITE_SHM_SHARED ){
  34610. u16 allShared = 0; /* Union of locks held by connections other than "p" */
  34611. /* Find out which shared locks are already held by sibling connections.
  34612. ** If any sibling already holds an exclusive lock, go ahead and return
  34613. ** SQLITE_BUSY.
  34614. */
  34615. for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
  34616. if( (pX->exclMask & mask)!=0 ){
  34617. rc = SQLITE_BUSY;
  34618. break;
  34619. }
  34620. allShared |= pX->sharedMask;
  34621. }
  34622. /* Get shared locks at the system level, if necessary */
  34623. if( rc==SQLITE_OK ){
  34624. if( (allShared & mask)==0 ){
  34625. rc = winShmSystemLock(pShmNode, _SHM_RDLCK, ofst+WIN_SHM_BASE, n);
  34626. }else{
  34627. rc = SQLITE_OK;
  34628. }
  34629. }
  34630. /* Get the local shared locks */
  34631. if( rc==SQLITE_OK ){
  34632. p->sharedMask |= mask;
  34633. }
  34634. }else{
  34635. /* Make sure no sibling connections hold locks that will block this
  34636. ** lock. If any do, return SQLITE_BUSY right away.
  34637. */
  34638. for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
  34639. if( (pX->exclMask & mask)!=0 || (pX->sharedMask & mask)!=0 ){
  34640. rc = SQLITE_BUSY;
  34641. break;
  34642. }
  34643. }
  34644. /* Get the exclusive locks at the system level. Then if successful
  34645. ** also mark the local connection as being locked.
  34646. */
  34647. if( rc==SQLITE_OK ){
  34648. rc = winShmSystemLock(pShmNode, _SHM_WRLCK, ofst+WIN_SHM_BASE, n);
  34649. if( rc==SQLITE_OK ){
  34650. assert( (p->sharedMask & mask)==0 );
  34651. p->exclMask |= mask;
  34652. }
  34653. }
  34654. }
  34655. sqlite3_mutex_leave(pShmNode->mutex);
  34656. OSTRACE(("SHM-LOCK pid=%lu, id=%d, sharedMask=%03x, exclMask=%03x, rc=%s\n",
  34657. osGetCurrentProcessId(), p->id, p->sharedMask, p->exclMask,
  34658. sqlite3ErrName(rc)));
  34659. return rc;
  34660. }
  34661. /*
  34662. ** Implement a memory barrier or memory fence on shared memory.
  34663. **
  34664. ** All loads and stores begun before the barrier must complete before
  34665. ** any load or store begun after the barrier.
  34666. */
  34667. static void winShmBarrier(
  34668. sqlite3_file *fd /* Database holding the shared memory */
  34669. ){
  34670. UNUSED_PARAMETER(fd);
  34671. /* MemoryBarrier(); // does not work -- do not know why not */
  34672. winShmEnterMutex();
  34673. winShmLeaveMutex();
  34674. }
  34675. /*
  34676. ** This function is called to obtain a pointer to region iRegion of the
  34677. ** shared-memory associated with the database file fd. Shared-memory regions
  34678. ** are numbered starting from zero. Each shared-memory region is szRegion
  34679. ** bytes in size.
  34680. **
  34681. ** If an error occurs, an error code is returned and *pp is set to NULL.
  34682. **
  34683. ** Otherwise, if the isWrite parameter is 0 and the requested shared-memory
  34684. ** region has not been allocated (by any client, including one running in a
  34685. ** separate process), then *pp is set to NULL and SQLITE_OK returned. If
  34686. ** isWrite is non-zero and the requested shared-memory region has not yet
  34687. ** been allocated, it is allocated by this function.
  34688. **
  34689. ** If the shared-memory region has already been allocated or is allocated by
  34690. ** this call as described above, then it is mapped into this processes
  34691. ** address space (if it is not already), *pp is set to point to the mapped
  34692. ** memory and SQLITE_OK returned.
  34693. */
  34694. static int winShmMap(
  34695. sqlite3_file *fd, /* Handle open on database file */
  34696. int iRegion, /* Region to retrieve */
  34697. int szRegion, /* Size of regions */
  34698. int isWrite, /* True to extend file if necessary */
  34699. void volatile **pp /* OUT: Mapped memory */
  34700. ){
  34701. winFile *pDbFd = (winFile*)fd;
  34702. winShm *pShm = pDbFd->pShm;
  34703. winShmNode *pShmNode;
  34704. int rc = SQLITE_OK;
  34705. if( !pShm ){
  34706. rc = winOpenSharedMemory(pDbFd);
  34707. if( rc!=SQLITE_OK ) return rc;
  34708. pShm = pDbFd->pShm;
  34709. }
  34710. pShmNode = pShm->pShmNode;
  34711. sqlite3_mutex_enter(pShmNode->mutex);
  34712. assert( szRegion==pShmNode->szRegion || pShmNode->nRegion==0 );
  34713. if( pShmNode->nRegion<=iRegion ){
  34714. struct ShmRegion *apNew; /* New aRegion[] array */
  34715. int nByte = (iRegion+1)*szRegion; /* Minimum required file size */
  34716. sqlite3_int64 sz; /* Current size of wal-index file */
  34717. pShmNode->szRegion = szRegion;
  34718. /* The requested region is not mapped into this processes address space.
  34719. ** Check to see if it has been allocated (i.e. if the wal-index file is
  34720. ** large enough to contain the requested region).
  34721. */
  34722. rc = winFileSize((sqlite3_file *)&pShmNode->hFile, &sz);
  34723. if( rc!=SQLITE_OK ){
  34724. rc = winLogError(SQLITE_IOERR_SHMSIZE, osGetLastError(),
  34725. "winShmMap1", pDbFd->zPath);
  34726. goto shmpage_out;
  34727. }
  34728. if( sz<nByte ){
  34729. /* The requested memory region does not exist. If isWrite is set to
  34730. ** zero, exit early. *pp will be set to NULL and SQLITE_OK returned.
  34731. **
  34732. ** Alternatively, if isWrite is non-zero, use ftruncate() to allocate
  34733. ** the requested memory region.
  34734. */
  34735. if( !isWrite ) goto shmpage_out;
  34736. rc = winTruncate((sqlite3_file *)&pShmNode->hFile, nByte);
  34737. if( rc!=SQLITE_OK ){
  34738. rc = winLogError(SQLITE_IOERR_SHMSIZE, osGetLastError(),
  34739. "winShmMap2", pDbFd->zPath);
  34740. goto shmpage_out;
  34741. }
  34742. }
  34743. /* Map the requested memory region into this processes address space. */
  34744. apNew = (struct ShmRegion *)sqlite3_realloc64(
  34745. pShmNode->aRegion, (iRegion+1)*sizeof(apNew[0])
  34746. );
  34747. if( !apNew ){
  34748. rc = SQLITE_IOERR_NOMEM;
  34749. goto shmpage_out;
  34750. }
  34751. pShmNode->aRegion = apNew;
  34752. while( pShmNode->nRegion<=iRegion ){
  34753. HANDLE hMap = NULL; /* file-mapping handle */
  34754. void *pMap = 0; /* Mapped memory region */
  34755. #if SQLITE_OS_WINRT
  34756. hMap = osCreateFileMappingFromApp(pShmNode->hFile.h,
  34757. NULL, PAGE_READWRITE, nByte, NULL
  34758. );
  34759. #elif defined(SQLITE_WIN32_HAS_WIDE)
  34760. hMap = osCreateFileMappingW(pShmNode->hFile.h,
  34761. NULL, PAGE_READWRITE, 0, nByte, NULL
  34762. );
  34763. #elif defined(SQLITE_WIN32_HAS_ANSI)
  34764. hMap = osCreateFileMappingA(pShmNode->hFile.h,
  34765. NULL, PAGE_READWRITE, 0, nByte, NULL
  34766. );
  34767. #endif
  34768. OSTRACE(("SHM-MAP-CREATE pid=%lu, region=%d, size=%d, rc=%s\n",
  34769. osGetCurrentProcessId(), pShmNode->nRegion, nByte,
  34770. hMap ? "ok" : "failed"));
  34771. if( hMap ){
  34772. int iOffset = pShmNode->nRegion*szRegion;
  34773. int iOffsetShift = iOffset % winSysInfo.dwAllocationGranularity;
  34774. #if SQLITE_OS_WINRT
  34775. pMap = osMapViewOfFileFromApp(hMap, FILE_MAP_WRITE | FILE_MAP_READ,
  34776. iOffset - iOffsetShift, szRegion + iOffsetShift
  34777. );
  34778. #else
  34779. pMap = osMapViewOfFile(hMap, FILE_MAP_WRITE | FILE_MAP_READ,
  34780. 0, iOffset - iOffsetShift, szRegion + iOffsetShift
  34781. );
  34782. #endif
  34783. OSTRACE(("SHM-MAP-MAP pid=%lu, region=%d, offset=%d, size=%d, rc=%s\n",
  34784. osGetCurrentProcessId(), pShmNode->nRegion, iOffset,
  34785. szRegion, pMap ? "ok" : "failed"));
  34786. }
  34787. if( !pMap ){
  34788. pShmNode->lastErrno = osGetLastError();
  34789. rc = winLogError(SQLITE_IOERR_SHMMAP, pShmNode->lastErrno,
  34790. "winShmMap3", pDbFd->zPath);
  34791. if( hMap ) osCloseHandle(hMap);
  34792. goto shmpage_out;
  34793. }
  34794. pShmNode->aRegion[pShmNode->nRegion].pMap = pMap;
  34795. pShmNode->aRegion[pShmNode->nRegion].hMap = hMap;
  34796. pShmNode->nRegion++;
  34797. }
  34798. }
  34799. shmpage_out:
  34800. if( pShmNode->nRegion>iRegion ){
  34801. int iOffset = iRegion*szRegion;
  34802. int iOffsetShift = iOffset % winSysInfo.dwAllocationGranularity;
  34803. char *p = (char *)pShmNode->aRegion[iRegion].pMap;
  34804. *pp = (void *)&p[iOffsetShift];
  34805. }else{
  34806. *pp = 0;
  34807. }
  34808. sqlite3_mutex_leave(pShmNode->mutex);
  34809. return rc;
  34810. }
  34811. #else
  34812. # define winShmMap 0
  34813. # define winShmLock 0
  34814. # define winShmBarrier 0
  34815. # define winShmUnmap 0
  34816. #endif /* #ifndef SQLITE_OMIT_WAL */
  34817. /*
  34818. ** Cleans up the mapped region of the specified file, if any.
  34819. */
  34820. #if SQLITE_MAX_MMAP_SIZE>0
  34821. static int winUnmapfile(winFile *pFile){
  34822. assert( pFile!=0 );
  34823. OSTRACE(("UNMAP-FILE pid=%lu, pFile=%p, hMap=%p, pMapRegion=%p, "
  34824. "mmapSize=%lld, mmapSizeActual=%lld, mmapSizeMax=%lld\n",
  34825. osGetCurrentProcessId(), pFile, pFile->hMap, pFile->pMapRegion,
  34826. pFile->mmapSize, pFile->mmapSizeActual, pFile->mmapSizeMax));
  34827. if( pFile->pMapRegion ){
  34828. if( !osUnmapViewOfFile(pFile->pMapRegion) ){
  34829. pFile->lastErrno = osGetLastError();
  34830. OSTRACE(("UNMAP-FILE pid=%lu, pFile=%p, pMapRegion=%p, "
  34831. "rc=SQLITE_IOERR_MMAP\n", osGetCurrentProcessId(), pFile,
  34832. pFile->pMapRegion));
  34833. return winLogError(SQLITE_IOERR_MMAP, pFile->lastErrno,
  34834. "winUnmapfile1", pFile->zPath);
  34835. }
  34836. pFile->pMapRegion = 0;
  34837. pFile->mmapSize = 0;
  34838. pFile->mmapSizeActual = 0;
  34839. }
  34840. if( pFile->hMap!=NULL ){
  34841. if( !osCloseHandle(pFile->hMap) ){
  34842. pFile->lastErrno = osGetLastError();
  34843. OSTRACE(("UNMAP-FILE pid=%lu, pFile=%p, hMap=%p, rc=SQLITE_IOERR_MMAP\n",
  34844. osGetCurrentProcessId(), pFile, pFile->hMap));
  34845. return winLogError(SQLITE_IOERR_MMAP, pFile->lastErrno,
  34846. "winUnmapfile2", pFile->zPath);
  34847. }
  34848. pFile->hMap = NULL;
  34849. }
  34850. OSTRACE(("UNMAP-FILE pid=%lu, pFile=%p, rc=SQLITE_OK\n",
  34851. osGetCurrentProcessId(), pFile));
  34852. return SQLITE_OK;
  34853. }
  34854. /*
  34855. ** Memory map or remap the file opened by file-descriptor pFd (if the file
  34856. ** is already mapped, the existing mapping is replaced by the new). Or, if
  34857. ** there already exists a mapping for this file, and there are still
  34858. ** outstanding xFetch() references to it, this function is a no-op.
  34859. **
  34860. ** If parameter nByte is non-negative, then it is the requested size of
  34861. ** the mapping to create. Otherwise, if nByte is less than zero, then the
  34862. ** requested size is the size of the file on disk. The actual size of the
  34863. ** created mapping is either the requested size or the value configured
  34864. ** using SQLITE_FCNTL_MMAP_SIZE, whichever is smaller.
  34865. **
  34866. ** SQLITE_OK is returned if no error occurs (even if the mapping is not
  34867. ** recreated as a result of outstanding references) or an SQLite error
  34868. ** code otherwise.
  34869. */
  34870. static int winMapfile(winFile *pFd, sqlite3_int64 nByte){
  34871. sqlite3_int64 nMap = nByte;
  34872. int rc;
  34873. assert( nMap>=0 || pFd->nFetchOut==0 );
  34874. OSTRACE(("MAP-FILE pid=%lu, pFile=%p, size=%lld\n",
  34875. osGetCurrentProcessId(), pFd, nByte));
  34876. if( pFd->nFetchOut>0 ) return SQLITE_OK;
  34877. if( nMap<0 ){
  34878. rc = winFileSize((sqlite3_file*)pFd, &nMap);
  34879. if( rc ){
  34880. OSTRACE(("MAP-FILE pid=%lu, pFile=%p, rc=SQLITE_IOERR_FSTAT\n",
  34881. osGetCurrentProcessId(), pFd));
  34882. return SQLITE_IOERR_FSTAT;
  34883. }
  34884. }
  34885. if( nMap>pFd->mmapSizeMax ){
  34886. nMap = pFd->mmapSizeMax;
  34887. }
  34888. nMap &= ~(sqlite3_int64)(winSysInfo.dwPageSize - 1);
  34889. if( nMap==0 && pFd->mmapSize>0 ){
  34890. winUnmapfile(pFd);
  34891. }
  34892. if( nMap!=pFd->mmapSize ){
  34893. void *pNew = 0;
  34894. DWORD protect = PAGE_READONLY;
  34895. DWORD flags = FILE_MAP_READ;
  34896. winUnmapfile(pFd);
  34897. if( (pFd->ctrlFlags & WINFILE_RDONLY)==0 ){
  34898. protect = PAGE_READWRITE;
  34899. flags |= FILE_MAP_WRITE;
  34900. }
  34901. #if SQLITE_OS_WINRT
  34902. pFd->hMap = osCreateFileMappingFromApp(pFd->h, NULL, protect, nMap, NULL);
  34903. #elif defined(SQLITE_WIN32_HAS_WIDE)
  34904. pFd->hMap = osCreateFileMappingW(pFd->h, NULL, protect,
  34905. (DWORD)((nMap>>32) & 0xffffffff),
  34906. (DWORD)(nMap & 0xffffffff), NULL);
  34907. #elif defined(SQLITE_WIN32_HAS_ANSI)
  34908. pFd->hMap = osCreateFileMappingA(pFd->h, NULL, protect,
  34909. (DWORD)((nMap>>32) & 0xffffffff),
  34910. (DWORD)(nMap & 0xffffffff), NULL);
  34911. #endif
  34912. if( pFd->hMap==NULL ){
  34913. pFd->lastErrno = osGetLastError();
  34914. rc = winLogError(SQLITE_IOERR_MMAP, pFd->lastErrno,
  34915. "winMapfile1", pFd->zPath);
  34916. /* Log the error, but continue normal operation using xRead/xWrite */
  34917. OSTRACE(("MAP-FILE-CREATE pid=%lu, pFile=%p, rc=%s\n",
  34918. osGetCurrentProcessId(), pFd, sqlite3ErrName(rc)));
  34919. return SQLITE_OK;
  34920. }
  34921. assert( (nMap % winSysInfo.dwPageSize)==0 );
  34922. assert( sizeof(SIZE_T)==sizeof(sqlite3_int64) || nMap<=0xffffffff );
  34923. #if SQLITE_OS_WINRT
  34924. pNew = osMapViewOfFileFromApp(pFd->hMap, flags, 0, (SIZE_T)nMap);
  34925. #else
  34926. pNew = osMapViewOfFile(pFd->hMap, flags, 0, 0, (SIZE_T)nMap);
  34927. #endif
  34928. if( pNew==NULL ){
  34929. osCloseHandle(pFd->hMap);
  34930. pFd->hMap = NULL;
  34931. pFd->lastErrno = osGetLastError();
  34932. rc = winLogError(SQLITE_IOERR_MMAP, pFd->lastErrno,
  34933. "winMapfile2", pFd->zPath);
  34934. /* Log the error, but continue normal operation using xRead/xWrite */
  34935. OSTRACE(("MAP-FILE-MAP pid=%lu, pFile=%p, rc=%s\n",
  34936. osGetCurrentProcessId(), pFd, sqlite3ErrName(rc)));
  34937. return SQLITE_OK;
  34938. }
  34939. pFd->pMapRegion = pNew;
  34940. pFd->mmapSize = nMap;
  34941. pFd->mmapSizeActual = nMap;
  34942. }
  34943. OSTRACE(("MAP-FILE pid=%lu, pFile=%p, rc=SQLITE_OK\n",
  34944. osGetCurrentProcessId(), pFd));
  34945. return SQLITE_OK;
  34946. }
  34947. #endif /* SQLITE_MAX_MMAP_SIZE>0 */
  34948. /*
  34949. ** If possible, return a pointer to a mapping of file fd starting at offset
  34950. ** iOff. The mapping must be valid for at least nAmt bytes.
  34951. **
  34952. ** If such a pointer can be obtained, store it in *pp and return SQLITE_OK.
  34953. ** Or, if one cannot but no error occurs, set *pp to 0 and return SQLITE_OK.
  34954. ** Finally, if an error does occur, return an SQLite error code. The final
  34955. ** value of *pp is undefined in this case.
  34956. **
  34957. ** If this function does return a pointer, the caller must eventually
  34958. ** release the reference by calling winUnfetch().
  34959. */
  34960. static int winFetch(sqlite3_file *fd, i64 iOff, int nAmt, void **pp){
  34961. #if SQLITE_MAX_MMAP_SIZE>0
  34962. winFile *pFd = (winFile*)fd; /* The underlying database file */
  34963. #endif
  34964. *pp = 0;
  34965. OSTRACE(("FETCH pid=%lu, pFile=%p, offset=%lld, amount=%d, pp=%p\n",
  34966. osGetCurrentProcessId(), fd, iOff, nAmt, pp));
  34967. #if SQLITE_MAX_MMAP_SIZE>0
  34968. if( pFd->mmapSizeMax>0 ){
  34969. if( pFd->pMapRegion==0 ){
  34970. int rc = winMapfile(pFd, -1);
  34971. if( rc!=SQLITE_OK ){
  34972. OSTRACE(("FETCH pid=%lu, pFile=%p, rc=%s\n",
  34973. osGetCurrentProcessId(), pFd, sqlite3ErrName(rc)));
  34974. return rc;
  34975. }
  34976. }
  34977. if( pFd->mmapSize >= iOff+nAmt ){
  34978. *pp = &((u8 *)pFd->pMapRegion)[iOff];
  34979. pFd->nFetchOut++;
  34980. }
  34981. }
  34982. #endif
  34983. OSTRACE(("FETCH pid=%lu, pFile=%p, pp=%p, *pp=%p, rc=SQLITE_OK\n",
  34984. osGetCurrentProcessId(), fd, pp, *pp));
  34985. return SQLITE_OK;
  34986. }
  34987. /*
  34988. ** If the third argument is non-NULL, then this function releases a
  34989. ** reference obtained by an earlier call to winFetch(). The second
  34990. ** argument passed to this function must be the same as the corresponding
  34991. ** argument that was passed to the winFetch() invocation.
  34992. **
  34993. ** Or, if the third argument is NULL, then this function is being called
  34994. ** to inform the VFS layer that, according to POSIX, any existing mapping
  34995. ** may now be invalid and should be unmapped.
  34996. */
  34997. static int winUnfetch(sqlite3_file *fd, i64 iOff, void *p){
  34998. #if SQLITE_MAX_MMAP_SIZE>0
  34999. winFile *pFd = (winFile*)fd; /* The underlying database file */
  35000. /* If p==0 (unmap the entire file) then there must be no outstanding
  35001. ** xFetch references. Or, if p!=0 (meaning it is an xFetch reference),
  35002. ** then there must be at least one outstanding. */
  35003. assert( (p==0)==(pFd->nFetchOut==0) );
  35004. /* If p!=0, it must match the iOff value. */
  35005. assert( p==0 || p==&((u8 *)pFd->pMapRegion)[iOff] );
  35006. OSTRACE(("UNFETCH pid=%lu, pFile=%p, offset=%lld, p=%p\n",
  35007. osGetCurrentProcessId(), pFd, iOff, p));
  35008. if( p ){
  35009. pFd->nFetchOut--;
  35010. }else{
  35011. /* FIXME: If Windows truly always prevents truncating or deleting a
  35012. ** file while a mapping is held, then the following winUnmapfile() call
  35013. ** is unnecessary can be omitted - potentially improving
  35014. ** performance. */
  35015. winUnmapfile(pFd);
  35016. }
  35017. assert( pFd->nFetchOut>=0 );
  35018. #endif
  35019. OSTRACE(("UNFETCH pid=%lu, pFile=%p, rc=SQLITE_OK\n",
  35020. osGetCurrentProcessId(), fd));
  35021. return SQLITE_OK;
  35022. }
  35023. /*
  35024. ** Here ends the implementation of all sqlite3_file methods.
  35025. **
  35026. ********************** End sqlite3_file Methods *******************************
  35027. ******************************************************************************/
  35028. /*
  35029. ** This vector defines all the methods that can operate on an
  35030. ** sqlite3_file for win32.
  35031. */
  35032. static const sqlite3_io_methods winIoMethod = {
  35033. 3, /* iVersion */
  35034. winClose, /* xClose */
  35035. winRead, /* xRead */
  35036. winWrite, /* xWrite */
  35037. winTruncate, /* xTruncate */
  35038. winSync, /* xSync */
  35039. winFileSize, /* xFileSize */
  35040. winLock, /* xLock */
  35041. winUnlock, /* xUnlock */
  35042. winCheckReservedLock, /* xCheckReservedLock */
  35043. winFileControl, /* xFileControl */
  35044. winSectorSize, /* xSectorSize */
  35045. winDeviceCharacteristics, /* xDeviceCharacteristics */
  35046. winShmMap, /* xShmMap */
  35047. winShmLock, /* xShmLock */
  35048. winShmBarrier, /* xShmBarrier */
  35049. winShmUnmap, /* xShmUnmap */
  35050. winFetch, /* xFetch */
  35051. winUnfetch /* xUnfetch */
  35052. };
  35053. /****************************************************************************
  35054. **************************** sqlite3_vfs methods ****************************
  35055. **
  35056. ** This division contains the implementation of methods on the
  35057. ** sqlite3_vfs object.
  35058. */
  35059. #if defined(__CYGWIN__)
  35060. /*
  35061. ** Convert a filename from whatever the underlying operating system
  35062. ** supports for filenames into UTF-8. Space to hold the result is
  35063. ** obtained from malloc and must be freed by the calling function.
  35064. */
  35065. static char *winConvertToUtf8Filename(const void *zFilename){
  35066. char *zConverted = 0;
  35067. if( osIsNT() ){
  35068. zConverted = winUnicodeToUtf8(zFilename);
  35069. }
  35070. #ifdef SQLITE_WIN32_HAS_ANSI
  35071. else{
  35072. zConverted = sqlite3_win32_mbcs_to_utf8(zFilename);
  35073. }
  35074. #endif
  35075. /* caller will handle out of memory */
  35076. return zConverted;
  35077. }
  35078. #endif
  35079. /*
  35080. ** Convert a UTF-8 filename into whatever form the underlying
  35081. ** operating system wants filenames in. Space to hold the result
  35082. ** is obtained from malloc and must be freed by the calling
  35083. ** function.
  35084. */
  35085. static void *winConvertFromUtf8Filename(const char *zFilename){
  35086. void *zConverted = 0;
  35087. if( osIsNT() ){
  35088. zConverted = winUtf8ToUnicode(zFilename);
  35089. }
  35090. #ifdef SQLITE_WIN32_HAS_ANSI
  35091. else{
  35092. zConverted = sqlite3_win32_utf8_to_mbcs(zFilename);
  35093. }
  35094. #endif
  35095. /* caller will handle out of memory */
  35096. return zConverted;
  35097. }
  35098. /*
  35099. ** This function returns non-zero if the specified UTF-8 string buffer
  35100. ** ends with a directory separator character or one was successfully
  35101. ** added to it.
  35102. */
  35103. static int winMakeEndInDirSep(int nBuf, char *zBuf){
  35104. if( zBuf ){
  35105. int nLen = sqlite3Strlen30(zBuf);
  35106. if( nLen>0 ){
  35107. if( winIsDirSep(zBuf[nLen-1]) ){
  35108. return 1;
  35109. }else if( nLen+1<nBuf ){
  35110. zBuf[nLen] = winGetDirSep();
  35111. zBuf[nLen+1] = '\0';
  35112. return 1;
  35113. }
  35114. }
  35115. }
  35116. return 0;
  35117. }
  35118. /*
  35119. ** Create a temporary file name and store the resulting pointer into pzBuf.
  35120. ** The pointer returned in pzBuf must be freed via sqlite3_free().
  35121. */
  35122. static int winGetTempname(sqlite3_vfs *pVfs, char **pzBuf){
  35123. static char zChars[] =
  35124. "abcdefghijklmnopqrstuvwxyz"
  35125. "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
  35126. "0123456789";
  35127. size_t i, j;
  35128. int nPre = sqlite3Strlen30(SQLITE_TEMP_FILE_PREFIX);
  35129. int nMax, nBuf, nDir, nLen;
  35130. char *zBuf;
  35131. /* It's odd to simulate an io-error here, but really this is just
  35132. ** using the io-error infrastructure to test that SQLite handles this
  35133. ** function failing.
  35134. */
  35135. SimulateIOError( return SQLITE_IOERR );
  35136. /* Allocate a temporary buffer to store the fully qualified file
  35137. ** name for the temporary file. If this fails, we cannot continue.
  35138. */
  35139. nMax = pVfs->mxPathname; nBuf = nMax + 2;
  35140. zBuf = sqlite3MallocZero( nBuf );
  35141. if( !zBuf ){
  35142. OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
  35143. return SQLITE_IOERR_NOMEM;
  35144. }
  35145. /* Figure out the effective temporary directory. First, check if one
  35146. ** has been explicitly set by the application; otherwise, use the one
  35147. ** configured by the operating system.
  35148. */
  35149. nDir = nMax - (nPre + 15);
  35150. assert( nDir>0 );
  35151. if( sqlite3_temp_directory ){
  35152. int nDirLen = sqlite3Strlen30(sqlite3_temp_directory);
  35153. if( nDirLen>0 ){
  35154. if( !winIsDirSep(sqlite3_temp_directory[nDirLen-1]) ){
  35155. nDirLen++;
  35156. }
  35157. if( nDirLen>nDir ){
  35158. sqlite3_free(zBuf);
  35159. OSTRACE(("TEMP-FILENAME rc=SQLITE_ERROR\n"));
  35160. return winLogError(SQLITE_ERROR, 0, "winGetTempname1", 0);
  35161. }
  35162. sqlite3_snprintf(nMax, zBuf, "%s", sqlite3_temp_directory);
  35163. }
  35164. }
  35165. #if defined(__CYGWIN__)
  35166. else{
  35167. static const char *azDirs[] = {
  35168. 0, /* getenv("SQLITE_TMPDIR") */
  35169. 0, /* getenv("TMPDIR") */
  35170. 0, /* getenv("TMP") */
  35171. 0, /* getenv("TEMP") */
  35172. 0, /* getenv("USERPROFILE") */
  35173. "/var/tmp",
  35174. "/usr/tmp",
  35175. "/tmp",
  35176. ".",
  35177. 0 /* List terminator */
  35178. };
  35179. unsigned int i;
  35180. const char *zDir = 0;
  35181. if( !azDirs[0] ) azDirs[0] = getenv("SQLITE_TMPDIR");
  35182. if( !azDirs[1] ) azDirs[1] = getenv("TMPDIR");
  35183. if( !azDirs[2] ) azDirs[2] = getenv("TMP");
  35184. if( !azDirs[3] ) azDirs[3] = getenv("TEMP");
  35185. if( !azDirs[4] ) azDirs[4] = getenv("USERPROFILE");
  35186. for(i=0; i<sizeof(azDirs)/sizeof(azDirs[0]); zDir=azDirs[i++]){
  35187. void *zConverted;
  35188. if( zDir==0 ) continue;
  35189. /* If the path starts with a drive letter followed by the colon
  35190. ** character, assume it is already a native Win32 path; otherwise,
  35191. ** it must be converted to a native Win32 path via the Cygwin API
  35192. ** prior to using it.
  35193. */
  35194. if( winIsDriveLetterAndColon(zDir) ){
  35195. zConverted = winConvertFromUtf8Filename(zDir);
  35196. if( !zConverted ){
  35197. sqlite3_free(zBuf);
  35198. OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
  35199. return SQLITE_IOERR_NOMEM;
  35200. }
  35201. if( winIsDir(zConverted) ){
  35202. sqlite3_snprintf(nMax, zBuf, "%s", zDir);
  35203. sqlite3_free(zConverted);
  35204. break;
  35205. }
  35206. sqlite3_free(zConverted);
  35207. }else{
  35208. zConverted = sqlite3MallocZero( nMax+1 );
  35209. if( !zConverted ){
  35210. sqlite3_free(zBuf);
  35211. OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
  35212. return SQLITE_IOERR_NOMEM;
  35213. }
  35214. if( cygwin_conv_path(
  35215. osIsNT() ? CCP_POSIX_TO_WIN_W : CCP_POSIX_TO_WIN_A, zDir,
  35216. zConverted, nMax+1)<0 ){
  35217. sqlite3_free(zConverted);
  35218. sqlite3_free(zBuf);
  35219. OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_CONVPATH\n"));
  35220. return winLogError(SQLITE_IOERR_CONVPATH, (DWORD)errno,
  35221. "winGetTempname2", zDir);
  35222. }
  35223. if( winIsDir(zConverted) ){
  35224. /* At this point, we know the candidate directory exists and should
  35225. ** be used. However, we may need to convert the string containing
  35226. ** its name into UTF-8 (i.e. if it is UTF-16 right now).
  35227. */
  35228. char *zUtf8 = winConvertToUtf8Filename(zConverted);
  35229. if( !zUtf8 ){
  35230. sqlite3_free(zConverted);
  35231. sqlite3_free(zBuf);
  35232. OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
  35233. return SQLITE_IOERR_NOMEM;
  35234. }
  35235. sqlite3_snprintf(nMax, zBuf, "%s", zUtf8);
  35236. sqlite3_free(zUtf8);
  35237. sqlite3_free(zConverted);
  35238. break;
  35239. }
  35240. sqlite3_free(zConverted);
  35241. }
  35242. }
  35243. }
  35244. #elif !SQLITE_OS_WINRT && !defined(__CYGWIN__)
  35245. else if( osIsNT() ){
  35246. char *zMulti;
  35247. LPWSTR zWidePath = sqlite3MallocZero( nMax*sizeof(WCHAR) );
  35248. if( !zWidePath ){
  35249. sqlite3_free(zBuf);
  35250. OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
  35251. return SQLITE_IOERR_NOMEM;
  35252. }
  35253. if( osGetTempPathW(nMax, zWidePath)==0 ){
  35254. sqlite3_free(zWidePath);
  35255. sqlite3_free(zBuf);
  35256. OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_GETTEMPPATH\n"));
  35257. return winLogError(SQLITE_IOERR_GETTEMPPATH, osGetLastError(),
  35258. "winGetTempname2", 0);
  35259. }
  35260. zMulti = winUnicodeToUtf8(zWidePath);
  35261. if( zMulti ){
  35262. sqlite3_snprintf(nMax, zBuf, "%s", zMulti);
  35263. sqlite3_free(zMulti);
  35264. sqlite3_free(zWidePath);
  35265. }else{
  35266. sqlite3_free(zWidePath);
  35267. sqlite3_free(zBuf);
  35268. OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
  35269. return SQLITE_IOERR_NOMEM;
  35270. }
  35271. }
  35272. #ifdef SQLITE_WIN32_HAS_ANSI
  35273. else{
  35274. char *zUtf8;
  35275. char *zMbcsPath = sqlite3MallocZero( nMax );
  35276. if( !zMbcsPath ){
  35277. sqlite3_free(zBuf);
  35278. OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
  35279. return SQLITE_IOERR_NOMEM;
  35280. }
  35281. if( osGetTempPathA(nMax, zMbcsPath)==0 ){
  35282. sqlite3_free(zBuf);
  35283. OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_GETTEMPPATH\n"));
  35284. return winLogError(SQLITE_IOERR_GETTEMPPATH, osGetLastError(),
  35285. "winGetTempname3", 0);
  35286. }
  35287. zUtf8 = sqlite3_win32_mbcs_to_utf8(zMbcsPath);
  35288. if( zUtf8 ){
  35289. sqlite3_snprintf(nMax, zBuf, "%s", zUtf8);
  35290. sqlite3_free(zUtf8);
  35291. }else{
  35292. sqlite3_free(zBuf);
  35293. OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
  35294. return SQLITE_IOERR_NOMEM;
  35295. }
  35296. }
  35297. #endif /* SQLITE_WIN32_HAS_ANSI */
  35298. #endif /* !SQLITE_OS_WINRT */
  35299. /*
  35300. ** Check to make sure the temporary directory ends with an appropriate
  35301. ** separator. If it does not and there is not enough space left to add
  35302. ** one, fail.
  35303. */
  35304. if( !winMakeEndInDirSep(nDir+1, zBuf) ){
  35305. sqlite3_free(zBuf);
  35306. OSTRACE(("TEMP-FILENAME rc=SQLITE_ERROR\n"));
  35307. return winLogError(SQLITE_ERROR, 0, "winGetTempname4", 0);
  35308. }
  35309. /*
  35310. ** Check that the output buffer is large enough for the temporary file
  35311. ** name in the following format:
  35312. **
  35313. ** "<temporary_directory>/etilqs_XXXXXXXXXXXXXXX\0\0"
  35314. **
  35315. ** If not, return SQLITE_ERROR. The number 17 is used here in order to
  35316. ** account for the space used by the 15 character random suffix and the
  35317. ** two trailing NUL characters. The final directory separator character
  35318. ** has already added if it was not already present.
  35319. */
  35320. nLen = sqlite3Strlen30(zBuf);
  35321. if( (nLen + nPre + 17) > nBuf ){
  35322. sqlite3_free(zBuf);
  35323. OSTRACE(("TEMP-FILENAME rc=SQLITE_ERROR\n"));
  35324. return winLogError(SQLITE_ERROR, 0, "winGetTempname5", 0);
  35325. }
  35326. sqlite3_snprintf(nBuf-16-nLen, zBuf+nLen, SQLITE_TEMP_FILE_PREFIX);
  35327. j = sqlite3Strlen30(zBuf);
  35328. sqlite3_randomness(15, &zBuf[j]);
  35329. for(i=0; i<15; i++, j++){
  35330. zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
  35331. }
  35332. zBuf[j] = 0;
  35333. zBuf[j+1] = 0;
  35334. *pzBuf = zBuf;
  35335. OSTRACE(("TEMP-FILENAME name=%s, rc=SQLITE_OK\n", zBuf));
  35336. return SQLITE_OK;
  35337. }
  35338. /*
  35339. ** Return TRUE if the named file is really a directory. Return false if
  35340. ** it is something other than a directory, or if there is any kind of memory
  35341. ** allocation failure.
  35342. */
  35343. static int winIsDir(const void *zConverted){
  35344. DWORD attr;
  35345. int rc = 0;
  35346. DWORD lastErrno;
  35347. if( osIsNT() ){
  35348. int cnt = 0;
  35349. WIN32_FILE_ATTRIBUTE_DATA sAttrData;
  35350. memset(&sAttrData, 0, sizeof(sAttrData));
  35351. while( !(rc = osGetFileAttributesExW((LPCWSTR)zConverted,
  35352. GetFileExInfoStandard,
  35353. &sAttrData)) && winRetryIoerr(&cnt, &lastErrno) ){}
  35354. if( !rc ){
  35355. return 0; /* Invalid name? */
  35356. }
  35357. attr = sAttrData.dwFileAttributes;
  35358. #if SQLITE_OS_WINCE==0
  35359. }else{
  35360. attr = osGetFileAttributesA((char*)zConverted);
  35361. #endif
  35362. }
  35363. return (attr!=INVALID_FILE_ATTRIBUTES) && (attr&FILE_ATTRIBUTE_DIRECTORY);
  35364. }
  35365. /*
  35366. ** Open a file.
  35367. */
  35368. static int winOpen(
  35369. sqlite3_vfs *pVfs, /* Used to get maximum path name length */
  35370. const char *zName, /* Name of the file (UTF-8) */
  35371. sqlite3_file *id, /* Write the SQLite file handle here */
  35372. int flags, /* Open mode flags */
  35373. int *pOutFlags /* Status return flags */
  35374. ){
  35375. HANDLE h;
  35376. DWORD lastErrno = 0;
  35377. DWORD dwDesiredAccess;
  35378. DWORD dwShareMode;
  35379. DWORD dwCreationDisposition;
  35380. DWORD dwFlagsAndAttributes = 0;
  35381. #if SQLITE_OS_WINCE
  35382. int isTemp = 0;
  35383. #endif
  35384. winFile *pFile = (winFile*)id;
  35385. void *zConverted; /* Filename in OS encoding */
  35386. const char *zUtf8Name = zName; /* Filename in UTF-8 encoding */
  35387. int cnt = 0;
  35388. /* If argument zPath is a NULL pointer, this function is required to open
  35389. ** a temporary file. Use this buffer to store the file name in.
  35390. */
  35391. char *zTmpname = 0; /* For temporary filename, if necessary. */
  35392. int rc = SQLITE_OK; /* Function Return Code */
  35393. #if !defined(NDEBUG) || SQLITE_OS_WINCE
  35394. int eType = flags&0xFFFFFF00; /* Type of file to open */
  35395. #endif
  35396. int isExclusive = (flags & SQLITE_OPEN_EXCLUSIVE);
  35397. int isDelete = (flags & SQLITE_OPEN_DELETEONCLOSE);
  35398. int isCreate = (flags & SQLITE_OPEN_CREATE);
  35399. int isReadonly = (flags & SQLITE_OPEN_READONLY);
  35400. int isReadWrite = (flags & SQLITE_OPEN_READWRITE);
  35401. #ifndef NDEBUG
  35402. int isOpenJournal = (isCreate && (
  35403. eType==SQLITE_OPEN_MASTER_JOURNAL
  35404. || eType==SQLITE_OPEN_MAIN_JOURNAL
  35405. || eType==SQLITE_OPEN_WAL
  35406. ));
  35407. #endif
  35408. OSTRACE(("OPEN name=%s, pFile=%p, flags=%x, pOutFlags=%p\n",
  35409. zUtf8Name, id, flags, pOutFlags));
  35410. /* Check the following statements are true:
  35411. **
  35412. ** (a) Exactly one of the READWRITE and READONLY flags must be set, and
  35413. ** (b) if CREATE is set, then READWRITE must also be set, and
  35414. ** (c) if EXCLUSIVE is set, then CREATE must also be set.
  35415. ** (d) if DELETEONCLOSE is set, then CREATE must also be set.
  35416. */
  35417. assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
  35418. assert(isCreate==0 || isReadWrite);
  35419. assert(isExclusive==0 || isCreate);
  35420. assert(isDelete==0 || isCreate);
  35421. /* The main DB, main journal, WAL file and master journal are never
  35422. ** automatically deleted. Nor are they ever temporary files. */
  35423. assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB );
  35424. assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL );
  35425. assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MASTER_JOURNAL );
  35426. assert( (!isDelete && zName) || eType!=SQLITE_OPEN_WAL );
  35427. /* Assert that the upper layer has set one of the "file-type" flags. */
  35428. assert( eType==SQLITE_OPEN_MAIN_DB || eType==SQLITE_OPEN_TEMP_DB
  35429. || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL
  35430. || eType==SQLITE_OPEN_SUBJOURNAL || eType==SQLITE_OPEN_MASTER_JOURNAL
  35431. || eType==SQLITE_OPEN_TRANSIENT_DB || eType==SQLITE_OPEN_WAL
  35432. );
  35433. assert( pFile!=0 );
  35434. memset(pFile, 0, sizeof(winFile));
  35435. pFile->h = INVALID_HANDLE_VALUE;
  35436. #if SQLITE_OS_WINRT
  35437. if( !zUtf8Name && !sqlite3_temp_directory ){
  35438. sqlite3_log(SQLITE_ERROR,
  35439. "sqlite3_temp_directory variable should be set for WinRT");
  35440. }
  35441. #endif
  35442. /* If the second argument to this function is NULL, generate a
  35443. ** temporary file name to use
  35444. */
  35445. if( !zUtf8Name ){
  35446. assert( isDelete && !isOpenJournal );
  35447. rc = winGetTempname(pVfs, &zTmpname);
  35448. if( rc!=SQLITE_OK ){
  35449. OSTRACE(("OPEN name=%s, rc=%s", zUtf8Name, sqlite3ErrName(rc)));
  35450. return rc;
  35451. }
  35452. zUtf8Name = zTmpname;
  35453. }
  35454. /* Database filenames are double-zero terminated if they are not
  35455. ** URIs with parameters. Hence, they can always be passed into
  35456. ** sqlite3_uri_parameter().
  35457. */
  35458. assert( (eType!=SQLITE_OPEN_MAIN_DB) || (flags & SQLITE_OPEN_URI) ||
  35459. zUtf8Name[sqlite3Strlen30(zUtf8Name)+1]==0 );
  35460. /* Convert the filename to the system encoding. */
  35461. zConverted = winConvertFromUtf8Filename(zUtf8Name);
  35462. if( zConverted==0 ){
  35463. sqlite3_free(zTmpname);
  35464. OSTRACE(("OPEN name=%s, rc=SQLITE_IOERR_NOMEM", zUtf8Name));
  35465. return SQLITE_IOERR_NOMEM;
  35466. }
  35467. if( winIsDir(zConverted) ){
  35468. sqlite3_free(zConverted);
  35469. sqlite3_free(zTmpname);
  35470. OSTRACE(("OPEN name=%s, rc=SQLITE_CANTOPEN_ISDIR", zUtf8Name));
  35471. return SQLITE_CANTOPEN_ISDIR;
  35472. }
  35473. if( isReadWrite ){
  35474. dwDesiredAccess = GENERIC_READ | GENERIC_WRITE;
  35475. }else{
  35476. dwDesiredAccess = GENERIC_READ;
  35477. }
  35478. /* SQLITE_OPEN_EXCLUSIVE is used to make sure that a new file is
  35479. ** created. SQLite doesn't use it to indicate "exclusive access"
  35480. ** as it is usually understood.
  35481. */
  35482. if( isExclusive ){
  35483. /* Creates a new file, only if it does not already exist. */
  35484. /* If the file exists, it fails. */
  35485. dwCreationDisposition = CREATE_NEW;
  35486. }else if( isCreate ){
  35487. /* Open existing file, or create if it doesn't exist */
  35488. dwCreationDisposition = OPEN_ALWAYS;
  35489. }else{
  35490. /* Opens a file, only if it exists. */
  35491. dwCreationDisposition = OPEN_EXISTING;
  35492. }
  35493. dwShareMode = FILE_SHARE_READ | FILE_SHARE_WRITE;
  35494. if( isDelete ){
  35495. #if SQLITE_OS_WINCE
  35496. dwFlagsAndAttributes = FILE_ATTRIBUTE_HIDDEN;
  35497. isTemp = 1;
  35498. #else
  35499. dwFlagsAndAttributes = FILE_ATTRIBUTE_TEMPORARY
  35500. | FILE_ATTRIBUTE_HIDDEN
  35501. | FILE_FLAG_DELETE_ON_CLOSE;
  35502. #endif
  35503. }else{
  35504. dwFlagsAndAttributes = FILE_ATTRIBUTE_NORMAL;
  35505. }
  35506. /* Reports from the internet are that performance is always
  35507. ** better if FILE_FLAG_RANDOM_ACCESS is used. Ticket #2699. */
  35508. #if SQLITE_OS_WINCE
  35509. dwFlagsAndAttributes |= FILE_FLAG_RANDOM_ACCESS;
  35510. #endif
  35511. if( osIsNT() ){
  35512. #if SQLITE_OS_WINRT
  35513. CREATEFILE2_EXTENDED_PARAMETERS extendedParameters;
  35514. extendedParameters.dwSize = sizeof(CREATEFILE2_EXTENDED_PARAMETERS);
  35515. extendedParameters.dwFileAttributes =
  35516. dwFlagsAndAttributes & FILE_ATTRIBUTE_MASK;
  35517. extendedParameters.dwFileFlags = dwFlagsAndAttributes & FILE_FLAG_MASK;
  35518. extendedParameters.dwSecurityQosFlags = SECURITY_ANONYMOUS;
  35519. extendedParameters.lpSecurityAttributes = NULL;
  35520. extendedParameters.hTemplateFile = NULL;
  35521. while( (h = osCreateFile2((LPCWSTR)zConverted,
  35522. dwDesiredAccess,
  35523. dwShareMode,
  35524. dwCreationDisposition,
  35525. &extendedParameters))==INVALID_HANDLE_VALUE &&
  35526. winRetryIoerr(&cnt, &lastErrno) ){
  35527. /* Noop */
  35528. }
  35529. #else
  35530. while( (h = osCreateFileW((LPCWSTR)zConverted,
  35531. dwDesiredAccess,
  35532. dwShareMode, NULL,
  35533. dwCreationDisposition,
  35534. dwFlagsAndAttributes,
  35535. NULL))==INVALID_HANDLE_VALUE &&
  35536. winRetryIoerr(&cnt, &lastErrno) ){
  35537. /* Noop */
  35538. }
  35539. #endif
  35540. }
  35541. #ifdef SQLITE_WIN32_HAS_ANSI
  35542. else{
  35543. while( (h = osCreateFileA((LPCSTR)zConverted,
  35544. dwDesiredAccess,
  35545. dwShareMode, NULL,
  35546. dwCreationDisposition,
  35547. dwFlagsAndAttributes,
  35548. NULL))==INVALID_HANDLE_VALUE &&
  35549. winRetryIoerr(&cnt, &lastErrno) ){
  35550. /* Noop */
  35551. }
  35552. }
  35553. #endif
  35554. winLogIoerr(cnt, __LINE__);
  35555. OSTRACE(("OPEN file=%p, name=%s, access=%lx, rc=%s\n", h, zUtf8Name,
  35556. dwDesiredAccess, (h==INVALID_HANDLE_VALUE) ? "failed" : "ok"));
  35557. if( h==INVALID_HANDLE_VALUE ){
  35558. pFile->lastErrno = lastErrno;
  35559. winLogError(SQLITE_CANTOPEN, pFile->lastErrno, "winOpen", zUtf8Name);
  35560. sqlite3_free(zConverted);
  35561. sqlite3_free(zTmpname);
  35562. if( isReadWrite && !isExclusive ){
  35563. return winOpen(pVfs, zName, id,
  35564. ((flags|SQLITE_OPEN_READONLY) &
  35565. ~(SQLITE_OPEN_CREATE|SQLITE_OPEN_READWRITE)),
  35566. pOutFlags);
  35567. }else{
  35568. return SQLITE_CANTOPEN_BKPT;
  35569. }
  35570. }
  35571. if( pOutFlags ){
  35572. if( isReadWrite ){
  35573. *pOutFlags = SQLITE_OPEN_READWRITE;
  35574. }else{
  35575. *pOutFlags = SQLITE_OPEN_READONLY;
  35576. }
  35577. }
  35578. OSTRACE(("OPEN file=%p, name=%s, access=%lx, pOutFlags=%p, *pOutFlags=%d, "
  35579. "rc=%s\n", h, zUtf8Name, dwDesiredAccess, pOutFlags, pOutFlags ?
  35580. *pOutFlags : 0, (h==INVALID_HANDLE_VALUE) ? "failed" : "ok"));
  35581. #if SQLITE_OS_WINCE
  35582. if( isReadWrite && eType==SQLITE_OPEN_MAIN_DB
  35583. && (rc = winceCreateLock(zName, pFile))!=SQLITE_OK
  35584. ){
  35585. osCloseHandle(h);
  35586. sqlite3_free(zConverted);
  35587. sqlite3_free(zTmpname);
  35588. OSTRACE(("OPEN-CE-LOCK name=%s, rc=%s\n", zName, sqlite3ErrName(rc)));
  35589. return rc;
  35590. }
  35591. if( isTemp ){
  35592. pFile->zDeleteOnClose = zConverted;
  35593. }else
  35594. #endif
  35595. {
  35596. sqlite3_free(zConverted);
  35597. }
  35598. sqlite3_free(zTmpname);
  35599. pFile->pMethod = &winIoMethod;
  35600. pFile->pVfs = pVfs;
  35601. pFile->h = h;
  35602. if( isReadonly ){
  35603. pFile->ctrlFlags |= WINFILE_RDONLY;
  35604. }
  35605. if( sqlite3_uri_boolean(zName, "psow", SQLITE_POWERSAFE_OVERWRITE) ){
  35606. pFile->ctrlFlags |= WINFILE_PSOW;
  35607. }
  35608. pFile->lastErrno = NO_ERROR;
  35609. pFile->zPath = zName;
  35610. #if SQLITE_MAX_MMAP_SIZE>0
  35611. pFile->hMap = NULL;
  35612. pFile->pMapRegion = 0;
  35613. pFile->mmapSize = 0;
  35614. pFile->mmapSizeActual = 0;
  35615. pFile->mmapSizeMax = sqlite3GlobalConfig.szMmap;
  35616. #endif
  35617. OpenCounter(+1);
  35618. return rc;
  35619. }
  35620. /*
  35621. ** Delete the named file.
  35622. **
  35623. ** Note that Windows does not allow a file to be deleted if some other
  35624. ** process has it open. Sometimes a virus scanner or indexing program
  35625. ** will open a journal file shortly after it is created in order to do
  35626. ** whatever it does. While this other process is holding the
  35627. ** file open, we will be unable to delete it. To work around this
  35628. ** problem, we delay 100 milliseconds and try to delete again. Up
  35629. ** to MX_DELETION_ATTEMPTs deletion attempts are run before giving
  35630. ** up and returning an error.
  35631. */
  35632. static int winDelete(
  35633. sqlite3_vfs *pVfs, /* Not used on win32 */
  35634. const char *zFilename, /* Name of file to delete */
  35635. int syncDir /* Not used on win32 */
  35636. ){
  35637. int cnt = 0;
  35638. int rc;
  35639. DWORD attr;
  35640. DWORD lastErrno = 0;
  35641. void *zConverted;
  35642. UNUSED_PARAMETER(pVfs);
  35643. UNUSED_PARAMETER(syncDir);
  35644. SimulateIOError(return SQLITE_IOERR_DELETE);
  35645. OSTRACE(("DELETE name=%s, syncDir=%d\n", zFilename, syncDir));
  35646. zConverted = winConvertFromUtf8Filename(zFilename);
  35647. if( zConverted==0 ){
  35648. OSTRACE(("DELETE name=%s, rc=SQLITE_IOERR_NOMEM\n", zFilename));
  35649. return SQLITE_IOERR_NOMEM;
  35650. }
  35651. if( osIsNT() ){
  35652. do {
  35653. #if SQLITE_OS_WINRT
  35654. WIN32_FILE_ATTRIBUTE_DATA sAttrData;
  35655. memset(&sAttrData, 0, sizeof(sAttrData));
  35656. if ( osGetFileAttributesExW(zConverted, GetFileExInfoStandard,
  35657. &sAttrData) ){
  35658. attr = sAttrData.dwFileAttributes;
  35659. }else{
  35660. lastErrno = osGetLastError();
  35661. if( lastErrno==ERROR_FILE_NOT_FOUND
  35662. || lastErrno==ERROR_PATH_NOT_FOUND ){
  35663. rc = SQLITE_IOERR_DELETE_NOENT; /* Already gone? */
  35664. }else{
  35665. rc = SQLITE_ERROR;
  35666. }
  35667. break;
  35668. }
  35669. #else
  35670. attr = osGetFileAttributesW(zConverted);
  35671. #endif
  35672. if ( attr==INVALID_FILE_ATTRIBUTES ){
  35673. lastErrno = osGetLastError();
  35674. if( lastErrno==ERROR_FILE_NOT_FOUND
  35675. || lastErrno==ERROR_PATH_NOT_FOUND ){
  35676. rc = SQLITE_IOERR_DELETE_NOENT; /* Already gone? */
  35677. }else{
  35678. rc = SQLITE_ERROR;
  35679. }
  35680. break;
  35681. }
  35682. if ( attr&FILE_ATTRIBUTE_DIRECTORY ){
  35683. rc = SQLITE_ERROR; /* Files only. */
  35684. break;
  35685. }
  35686. if ( osDeleteFileW(zConverted) ){
  35687. rc = SQLITE_OK; /* Deleted OK. */
  35688. break;
  35689. }
  35690. if ( !winRetryIoerr(&cnt, &lastErrno) ){
  35691. rc = SQLITE_ERROR; /* No more retries. */
  35692. break;
  35693. }
  35694. } while(1);
  35695. }
  35696. #ifdef SQLITE_WIN32_HAS_ANSI
  35697. else{
  35698. do {
  35699. attr = osGetFileAttributesA(zConverted);
  35700. if ( attr==INVALID_FILE_ATTRIBUTES ){
  35701. lastErrno = osGetLastError();
  35702. if( lastErrno==ERROR_FILE_NOT_FOUND
  35703. || lastErrno==ERROR_PATH_NOT_FOUND ){
  35704. rc = SQLITE_IOERR_DELETE_NOENT; /* Already gone? */
  35705. }else{
  35706. rc = SQLITE_ERROR;
  35707. }
  35708. break;
  35709. }
  35710. if ( attr&FILE_ATTRIBUTE_DIRECTORY ){
  35711. rc = SQLITE_ERROR; /* Files only. */
  35712. break;
  35713. }
  35714. if ( osDeleteFileA(zConverted) ){
  35715. rc = SQLITE_OK; /* Deleted OK. */
  35716. break;
  35717. }
  35718. if ( !winRetryIoerr(&cnt, &lastErrno) ){
  35719. rc = SQLITE_ERROR; /* No more retries. */
  35720. break;
  35721. }
  35722. } while(1);
  35723. }
  35724. #endif
  35725. if( rc && rc!=SQLITE_IOERR_DELETE_NOENT ){
  35726. rc = winLogError(SQLITE_IOERR_DELETE, lastErrno, "winDelete", zFilename);
  35727. }else{
  35728. winLogIoerr(cnt, __LINE__);
  35729. }
  35730. sqlite3_free(zConverted);
  35731. OSTRACE(("DELETE name=%s, rc=%s\n", zFilename, sqlite3ErrName(rc)));
  35732. return rc;
  35733. }
  35734. /*
  35735. ** Check the existence and status of a file.
  35736. */
  35737. static int winAccess(
  35738. sqlite3_vfs *pVfs, /* Not used on win32 */
  35739. const char *zFilename, /* Name of file to check */
  35740. int flags, /* Type of test to make on this file */
  35741. int *pResOut /* OUT: Result */
  35742. ){
  35743. DWORD attr;
  35744. int rc = 0;
  35745. DWORD lastErrno = 0;
  35746. void *zConverted;
  35747. UNUSED_PARAMETER(pVfs);
  35748. SimulateIOError( return SQLITE_IOERR_ACCESS; );
  35749. OSTRACE(("ACCESS name=%s, flags=%x, pResOut=%p\n",
  35750. zFilename, flags, pResOut));
  35751. zConverted = winConvertFromUtf8Filename(zFilename);
  35752. if( zConverted==0 ){
  35753. OSTRACE(("ACCESS name=%s, rc=SQLITE_IOERR_NOMEM\n", zFilename));
  35754. return SQLITE_IOERR_NOMEM;
  35755. }
  35756. if( osIsNT() ){
  35757. int cnt = 0;
  35758. WIN32_FILE_ATTRIBUTE_DATA sAttrData;
  35759. memset(&sAttrData, 0, sizeof(sAttrData));
  35760. while( !(rc = osGetFileAttributesExW((LPCWSTR)zConverted,
  35761. GetFileExInfoStandard,
  35762. &sAttrData)) && winRetryIoerr(&cnt, &lastErrno) ){}
  35763. if( rc ){
  35764. /* For an SQLITE_ACCESS_EXISTS query, treat a zero-length file
  35765. ** as if it does not exist.
  35766. */
  35767. if( flags==SQLITE_ACCESS_EXISTS
  35768. && sAttrData.nFileSizeHigh==0
  35769. && sAttrData.nFileSizeLow==0 ){
  35770. attr = INVALID_FILE_ATTRIBUTES;
  35771. }else{
  35772. attr = sAttrData.dwFileAttributes;
  35773. }
  35774. }else{
  35775. winLogIoerr(cnt, __LINE__);
  35776. if( lastErrno!=ERROR_FILE_NOT_FOUND && lastErrno!=ERROR_PATH_NOT_FOUND ){
  35777. sqlite3_free(zConverted);
  35778. return winLogError(SQLITE_IOERR_ACCESS, lastErrno, "winAccess",
  35779. zFilename);
  35780. }else{
  35781. attr = INVALID_FILE_ATTRIBUTES;
  35782. }
  35783. }
  35784. }
  35785. #ifdef SQLITE_WIN32_HAS_ANSI
  35786. else{
  35787. attr = osGetFileAttributesA((char*)zConverted);
  35788. }
  35789. #endif
  35790. sqlite3_free(zConverted);
  35791. switch( flags ){
  35792. case SQLITE_ACCESS_READ:
  35793. case SQLITE_ACCESS_EXISTS:
  35794. rc = attr!=INVALID_FILE_ATTRIBUTES;
  35795. break;
  35796. case SQLITE_ACCESS_READWRITE:
  35797. rc = attr!=INVALID_FILE_ATTRIBUTES &&
  35798. (attr & FILE_ATTRIBUTE_READONLY)==0;
  35799. break;
  35800. default:
  35801. assert(!"Invalid flags argument");
  35802. }
  35803. *pResOut = rc;
  35804. OSTRACE(("ACCESS name=%s, pResOut=%p, *pResOut=%d, rc=SQLITE_OK\n",
  35805. zFilename, pResOut, *pResOut));
  35806. return SQLITE_OK;
  35807. }
  35808. /*
  35809. ** Returns non-zero if the specified path name starts with a drive letter
  35810. ** followed by a colon character.
  35811. */
  35812. static BOOL winIsDriveLetterAndColon(
  35813. const char *zPathname
  35814. ){
  35815. return ( sqlite3Isalpha(zPathname[0]) && zPathname[1]==':' );
  35816. }
  35817. /*
  35818. ** Returns non-zero if the specified path name should be used verbatim. If
  35819. ** non-zero is returned from this function, the calling function must simply
  35820. ** use the provided path name verbatim -OR- resolve it into a full path name
  35821. ** using the GetFullPathName Win32 API function (if available).
  35822. */
  35823. static BOOL winIsVerbatimPathname(
  35824. const char *zPathname
  35825. ){
  35826. /*
  35827. ** If the path name starts with a forward slash or a backslash, it is either
  35828. ** a legal UNC name, a volume relative path, or an absolute path name in the
  35829. ** "Unix" format on Windows. There is no easy way to differentiate between
  35830. ** the final two cases; therefore, we return the safer return value of TRUE
  35831. ** so that callers of this function will simply use it verbatim.
  35832. */
  35833. if ( winIsDirSep(zPathname[0]) ){
  35834. return TRUE;
  35835. }
  35836. /*
  35837. ** If the path name starts with a letter and a colon it is either a volume
  35838. ** relative path or an absolute path. Callers of this function must not
  35839. ** attempt to treat it as a relative path name (i.e. they should simply use
  35840. ** it verbatim).
  35841. */
  35842. if ( winIsDriveLetterAndColon(zPathname) ){
  35843. return TRUE;
  35844. }
  35845. /*
  35846. ** If we get to this point, the path name should almost certainly be a purely
  35847. ** relative one (i.e. not a UNC name, not absolute, and not volume relative).
  35848. */
  35849. return FALSE;
  35850. }
  35851. /*
  35852. ** Turn a relative pathname into a full pathname. Write the full
  35853. ** pathname into zOut[]. zOut[] will be at least pVfs->mxPathname
  35854. ** bytes in size.
  35855. */
  35856. static int winFullPathname(
  35857. sqlite3_vfs *pVfs, /* Pointer to vfs object */
  35858. const char *zRelative, /* Possibly relative input path */
  35859. int nFull, /* Size of output buffer in bytes */
  35860. char *zFull /* Output buffer */
  35861. ){
  35862. #if defined(__CYGWIN__)
  35863. SimulateIOError( return SQLITE_ERROR );
  35864. UNUSED_PARAMETER(nFull);
  35865. assert( nFull>=pVfs->mxPathname );
  35866. if ( sqlite3_data_directory && !winIsVerbatimPathname(zRelative) ){
  35867. /*
  35868. ** NOTE: We are dealing with a relative path name and the data
  35869. ** directory has been set. Therefore, use it as the basis
  35870. ** for converting the relative path name to an absolute
  35871. ** one by prepending the data directory and a slash.
  35872. */
  35873. char *zOut = sqlite3MallocZero( pVfs->mxPathname+1 );
  35874. if( !zOut ){
  35875. return SQLITE_IOERR_NOMEM;
  35876. }
  35877. if( cygwin_conv_path(
  35878. (osIsNT() ? CCP_POSIX_TO_WIN_W : CCP_POSIX_TO_WIN_A) |
  35879. CCP_RELATIVE, zRelative, zOut, pVfs->mxPathname+1)<0 ){
  35880. sqlite3_free(zOut);
  35881. return winLogError(SQLITE_CANTOPEN_CONVPATH, (DWORD)errno,
  35882. "winFullPathname1", zRelative);
  35883. }else{
  35884. char *zUtf8 = winConvertToUtf8Filename(zOut);
  35885. if( !zUtf8 ){
  35886. sqlite3_free(zOut);
  35887. return SQLITE_IOERR_NOMEM;
  35888. }
  35889. sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s%c%s",
  35890. sqlite3_data_directory, winGetDirSep(), zUtf8);
  35891. sqlite3_free(zUtf8);
  35892. sqlite3_free(zOut);
  35893. }
  35894. }else{
  35895. char *zOut = sqlite3MallocZero( pVfs->mxPathname+1 );
  35896. if( !zOut ){
  35897. return SQLITE_IOERR_NOMEM;
  35898. }
  35899. if( cygwin_conv_path(
  35900. (osIsNT() ? CCP_POSIX_TO_WIN_W : CCP_POSIX_TO_WIN_A),
  35901. zRelative, zOut, pVfs->mxPathname+1)<0 ){
  35902. sqlite3_free(zOut);
  35903. return winLogError(SQLITE_CANTOPEN_CONVPATH, (DWORD)errno,
  35904. "winFullPathname2", zRelative);
  35905. }else{
  35906. char *zUtf8 = winConvertToUtf8Filename(zOut);
  35907. if( !zUtf8 ){
  35908. sqlite3_free(zOut);
  35909. return SQLITE_IOERR_NOMEM;
  35910. }
  35911. sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s", zUtf8);
  35912. sqlite3_free(zUtf8);
  35913. sqlite3_free(zOut);
  35914. }
  35915. }
  35916. return SQLITE_OK;
  35917. #endif
  35918. #if (SQLITE_OS_WINCE || SQLITE_OS_WINRT) && !defined(__CYGWIN__)
  35919. SimulateIOError( return SQLITE_ERROR );
  35920. /* WinCE has no concept of a relative pathname, or so I am told. */
  35921. /* WinRT has no way to convert a relative path to an absolute one. */
  35922. if ( sqlite3_data_directory && !winIsVerbatimPathname(zRelative) ){
  35923. /*
  35924. ** NOTE: We are dealing with a relative path name and the data
  35925. ** directory has been set. Therefore, use it as the basis
  35926. ** for converting the relative path name to an absolute
  35927. ** one by prepending the data directory and a backslash.
  35928. */
  35929. sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s%c%s",
  35930. sqlite3_data_directory, winGetDirSep(), zRelative);
  35931. }else{
  35932. sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s", zRelative);
  35933. }
  35934. return SQLITE_OK;
  35935. #endif
  35936. #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && !defined(__CYGWIN__)
  35937. DWORD nByte;
  35938. void *zConverted;
  35939. char *zOut;
  35940. /* If this path name begins with "/X:", where "X" is any alphabetic
  35941. ** character, discard the initial "/" from the pathname.
  35942. */
  35943. if( zRelative[0]=='/' && winIsDriveLetterAndColon(zRelative+1) ){
  35944. zRelative++;
  35945. }
  35946. /* It's odd to simulate an io-error here, but really this is just
  35947. ** using the io-error infrastructure to test that SQLite handles this
  35948. ** function failing. This function could fail if, for example, the
  35949. ** current working directory has been unlinked.
  35950. */
  35951. SimulateIOError( return SQLITE_ERROR );
  35952. if ( sqlite3_data_directory && !winIsVerbatimPathname(zRelative) ){
  35953. /*
  35954. ** NOTE: We are dealing with a relative path name and the data
  35955. ** directory has been set. Therefore, use it as the basis
  35956. ** for converting the relative path name to an absolute
  35957. ** one by prepending the data directory and a backslash.
  35958. */
  35959. sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s%c%s",
  35960. sqlite3_data_directory, winGetDirSep(), zRelative);
  35961. return SQLITE_OK;
  35962. }
  35963. zConverted = winConvertFromUtf8Filename(zRelative);
  35964. if( zConverted==0 ){
  35965. return SQLITE_IOERR_NOMEM;
  35966. }
  35967. if( osIsNT() ){
  35968. LPWSTR zTemp;
  35969. nByte = osGetFullPathNameW((LPCWSTR)zConverted, 0, 0, 0);
  35970. if( nByte==0 ){
  35971. sqlite3_free(zConverted);
  35972. return winLogError(SQLITE_CANTOPEN_FULLPATH, osGetLastError(),
  35973. "winFullPathname1", zRelative);
  35974. }
  35975. nByte += 3;
  35976. zTemp = sqlite3MallocZero( nByte*sizeof(zTemp[0]) );
  35977. if( zTemp==0 ){
  35978. sqlite3_free(zConverted);
  35979. return SQLITE_IOERR_NOMEM;
  35980. }
  35981. nByte = osGetFullPathNameW((LPCWSTR)zConverted, nByte, zTemp, 0);
  35982. if( nByte==0 ){
  35983. sqlite3_free(zConverted);
  35984. sqlite3_free(zTemp);
  35985. return winLogError(SQLITE_CANTOPEN_FULLPATH, osGetLastError(),
  35986. "winFullPathname2", zRelative);
  35987. }
  35988. sqlite3_free(zConverted);
  35989. zOut = winUnicodeToUtf8(zTemp);
  35990. sqlite3_free(zTemp);
  35991. }
  35992. #ifdef SQLITE_WIN32_HAS_ANSI
  35993. else{
  35994. char *zTemp;
  35995. nByte = osGetFullPathNameA((char*)zConverted, 0, 0, 0);
  35996. if( nByte==0 ){
  35997. sqlite3_free(zConverted);
  35998. return winLogError(SQLITE_CANTOPEN_FULLPATH, osGetLastError(),
  35999. "winFullPathname3", zRelative);
  36000. }
  36001. nByte += 3;
  36002. zTemp = sqlite3MallocZero( nByte*sizeof(zTemp[0]) );
  36003. if( zTemp==0 ){
  36004. sqlite3_free(zConverted);
  36005. return SQLITE_IOERR_NOMEM;
  36006. }
  36007. nByte = osGetFullPathNameA((char*)zConverted, nByte, zTemp, 0);
  36008. if( nByte==0 ){
  36009. sqlite3_free(zConverted);
  36010. sqlite3_free(zTemp);
  36011. return winLogError(SQLITE_CANTOPEN_FULLPATH, osGetLastError(),
  36012. "winFullPathname4", zRelative);
  36013. }
  36014. sqlite3_free(zConverted);
  36015. zOut = sqlite3_win32_mbcs_to_utf8(zTemp);
  36016. sqlite3_free(zTemp);
  36017. }
  36018. #endif
  36019. if( zOut ){
  36020. sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s", zOut);
  36021. sqlite3_free(zOut);
  36022. return SQLITE_OK;
  36023. }else{
  36024. return SQLITE_IOERR_NOMEM;
  36025. }
  36026. #endif
  36027. }
  36028. #ifndef SQLITE_OMIT_LOAD_EXTENSION
  36029. /*
  36030. ** Interfaces for opening a shared library, finding entry points
  36031. ** within the shared library, and closing the shared library.
  36032. */
  36033. static void *winDlOpen(sqlite3_vfs *pVfs, const char *zFilename){
  36034. HANDLE h;
  36035. #if defined(__CYGWIN__)
  36036. int nFull = pVfs->mxPathname+1;
  36037. char *zFull = sqlite3MallocZero( nFull );
  36038. void *zConverted = 0;
  36039. if( zFull==0 ){
  36040. OSTRACE(("DLOPEN name=%s, handle=%p\n", zFilename, (void*)0));
  36041. return 0;
  36042. }
  36043. if( winFullPathname(pVfs, zFilename, nFull, zFull)!=SQLITE_OK ){
  36044. sqlite3_free(zFull);
  36045. OSTRACE(("DLOPEN name=%s, handle=%p\n", zFilename, (void*)0));
  36046. return 0;
  36047. }
  36048. zConverted = winConvertFromUtf8Filename(zFull);
  36049. sqlite3_free(zFull);
  36050. #else
  36051. void *zConverted = winConvertFromUtf8Filename(zFilename);
  36052. UNUSED_PARAMETER(pVfs);
  36053. #endif
  36054. if( zConverted==0 ){
  36055. OSTRACE(("DLOPEN name=%s, handle=%p\n", zFilename, (void*)0));
  36056. return 0;
  36057. }
  36058. if( osIsNT() ){
  36059. #if SQLITE_OS_WINRT
  36060. h = osLoadPackagedLibrary((LPCWSTR)zConverted, 0);
  36061. #else
  36062. h = osLoadLibraryW((LPCWSTR)zConverted);
  36063. #endif
  36064. }
  36065. #ifdef SQLITE_WIN32_HAS_ANSI
  36066. else{
  36067. h = osLoadLibraryA((char*)zConverted);
  36068. }
  36069. #endif
  36070. OSTRACE(("DLOPEN name=%s, handle=%p\n", zFilename, (void*)h));
  36071. sqlite3_free(zConverted);
  36072. return (void*)h;
  36073. }
  36074. static void winDlError(sqlite3_vfs *pVfs, int nBuf, char *zBufOut){
  36075. UNUSED_PARAMETER(pVfs);
  36076. winGetLastErrorMsg(osGetLastError(), nBuf, zBufOut);
  36077. }
  36078. static void (*winDlSym(sqlite3_vfs *pVfs,void *pH,const char *zSym))(void){
  36079. FARPROC proc;
  36080. UNUSED_PARAMETER(pVfs);
  36081. proc = osGetProcAddressA((HANDLE)pH, zSym);
  36082. OSTRACE(("DLSYM handle=%p, symbol=%s, address=%p\n",
  36083. (void*)pH, zSym, (void*)proc));
  36084. return (void(*)(void))proc;
  36085. }
  36086. static void winDlClose(sqlite3_vfs *pVfs, void *pHandle){
  36087. UNUSED_PARAMETER(pVfs);
  36088. osFreeLibrary((HANDLE)pHandle);
  36089. OSTRACE(("DLCLOSE handle=%p\n", (void*)pHandle));
  36090. }
  36091. #else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
  36092. #define winDlOpen 0
  36093. #define winDlError 0
  36094. #define winDlSym 0
  36095. #define winDlClose 0
  36096. #endif
  36097. /*
  36098. ** Write up to nBuf bytes of randomness into zBuf.
  36099. */
  36100. static int winRandomness(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
  36101. int n = 0;
  36102. UNUSED_PARAMETER(pVfs);
  36103. #if defined(SQLITE_TEST) || defined(SQLITE_OMIT_RANDOMNESS)
  36104. n = nBuf;
  36105. memset(zBuf, 0, nBuf);
  36106. #else
  36107. if( sizeof(SYSTEMTIME)<=nBuf-n ){
  36108. SYSTEMTIME x;
  36109. osGetSystemTime(&x);
  36110. memcpy(&zBuf[n], &x, sizeof(x));
  36111. n += sizeof(x);
  36112. }
  36113. if( sizeof(DWORD)<=nBuf-n ){
  36114. DWORD pid = osGetCurrentProcessId();
  36115. memcpy(&zBuf[n], &pid, sizeof(pid));
  36116. n += sizeof(pid);
  36117. }
  36118. #if SQLITE_OS_WINRT
  36119. if( sizeof(ULONGLONG)<=nBuf-n ){
  36120. ULONGLONG cnt = osGetTickCount64();
  36121. memcpy(&zBuf[n], &cnt, sizeof(cnt));
  36122. n += sizeof(cnt);
  36123. }
  36124. #else
  36125. if( sizeof(DWORD)<=nBuf-n ){
  36126. DWORD cnt = osGetTickCount();
  36127. memcpy(&zBuf[n], &cnt, sizeof(cnt));
  36128. n += sizeof(cnt);
  36129. }
  36130. #endif
  36131. if( sizeof(LARGE_INTEGER)<=nBuf-n ){
  36132. LARGE_INTEGER i;
  36133. osQueryPerformanceCounter(&i);
  36134. memcpy(&zBuf[n], &i, sizeof(i));
  36135. n += sizeof(i);
  36136. }
  36137. #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && SQLITE_WIN32_USE_UUID
  36138. if( sizeof(UUID)<=nBuf-n ){
  36139. UUID id;
  36140. memset(&id, 0, sizeof(UUID));
  36141. osUuidCreate(&id);
  36142. memcpy(zBuf, &id, sizeof(UUID));
  36143. n += sizeof(UUID);
  36144. }
  36145. if( sizeof(UUID)<=nBuf-n ){
  36146. UUID id;
  36147. memset(&id, 0, sizeof(UUID));
  36148. osUuidCreateSequential(&id);
  36149. memcpy(zBuf, &id, sizeof(UUID));
  36150. n += sizeof(UUID);
  36151. }
  36152. #endif
  36153. #endif /* defined(SQLITE_TEST) || defined(SQLITE_ZERO_PRNG_SEED) */
  36154. return n;
  36155. }
  36156. /*
  36157. ** Sleep for a little while. Return the amount of time slept.
  36158. */
  36159. static int winSleep(sqlite3_vfs *pVfs, int microsec){
  36160. sqlite3_win32_sleep((microsec+999)/1000);
  36161. UNUSED_PARAMETER(pVfs);
  36162. return ((microsec+999)/1000)*1000;
  36163. }
  36164. /*
  36165. ** The following variable, if set to a non-zero value, is interpreted as
  36166. ** the number of seconds since 1970 and is used to set the result of
  36167. ** sqlite3OsCurrentTime() during testing.
  36168. */
  36169. #ifdef SQLITE_TEST
  36170. SQLITE_API int sqlite3_current_time = 0; /* Fake system time in seconds since 1970. */
  36171. #endif
  36172. /*
  36173. ** Find the current time (in Universal Coordinated Time). Write into *piNow
  36174. ** the current time and date as a Julian Day number times 86_400_000. In
  36175. ** other words, write into *piNow the number of milliseconds since the Julian
  36176. ** epoch of noon in Greenwich on November 24, 4714 B.C according to the
  36177. ** proleptic Gregorian calendar.
  36178. **
  36179. ** On success, return SQLITE_OK. Return SQLITE_ERROR if the time and date
  36180. ** cannot be found.
  36181. */
  36182. static int winCurrentTimeInt64(sqlite3_vfs *pVfs, sqlite3_int64 *piNow){
  36183. /* FILETIME structure is a 64-bit value representing the number of
  36184. 100-nanosecond intervals since January 1, 1601 (= JD 2305813.5).
  36185. */
  36186. FILETIME ft;
  36187. static const sqlite3_int64 winFiletimeEpoch = 23058135*(sqlite3_int64)8640000;
  36188. #ifdef SQLITE_TEST
  36189. static const sqlite3_int64 unixEpoch = 24405875*(sqlite3_int64)8640000;
  36190. #endif
  36191. /* 2^32 - to avoid use of LL and warnings in gcc */
  36192. static const sqlite3_int64 max32BitValue =
  36193. (sqlite3_int64)2000000000 + (sqlite3_int64)2000000000 +
  36194. (sqlite3_int64)294967296;
  36195. #if SQLITE_OS_WINCE
  36196. SYSTEMTIME time;
  36197. osGetSystemTime(&time);
  36198. /* if SystemTimeToFileTime() fails, it returns zero. */
  36199. if (!osSystemTimeToFileTime(&time,&ft)){
  36200. return SQLITE_ERROR;
  36201. }
  36202. #else
  36203. osGetSystemTimeAsFileTime( &ft );
  36204. #endif
  36205. *piNow = winFiletimeEpoch +
  36206. ((((sqlite3_int64)ft.dwHighDateTime)*max32BitValue) +
  36207. (sqlite3_int64)ft.dwLowDateTime)/(sqlite3_int64)10000;
  36208. #ifdef SQLITE_TEST
  36209. if( sqlite3_current_time ){
  36210. *piNow = 1000*(sqlite3_int64)sqlite3_current_time + unixEpoch;
  36211. }
  36212. #endif
  36213. UNUSED_PARAMETER(pVfs);
  36214. return SQLITE_OK;
  36215. }
  36216. /*
  36217. ** Find the current time (in Universal Coordinated Time). Write the
  36218. ** current time and date as a Julian Day number into *prNow and
  36219. ** return 0. Return 1 if the time and date cannot be found.
  36220. */
  36221. static int winCurrentTime(sqlite3_vfs *pVfs, double *prNow){
  36222. int rc;
  36223. sqlite3_int64 i;
  36224. rc = winCurrentTimeInt64(pVfs, &i);
  36225. if( !rc ){
  36226. *prNow = i/86400000.0;
  36227. }
  36228. return rc;
  36229. }
  36230. /*
  36231. ** The idea is that this function works like a combination of
  36232. ** GetLastError() and FormatMessage() on Windows (or errno and
  36233. ** strerror_r() on Unix). After an error is returned by an OS
  36234. ** function, SQLite calls this function with zBuf pointing to
  36235. ** a buffer of nBuf bytes. The OS layer should populate the
  36236. ** buffer with a nul-terminated UTF-8 encoded error message
  36237. ** describing the last IO error to have occurred within the calling
  36238. ** thread.
  36239. **
  36240. ** If the error message is too large for the supplied buffer,
  36241. ** it should be truncated. The return value of xGetLastError
  36242. ** is zero if the error message fits in the buffer, or non-zero
  36243. ** otherwise (if the message was truncated). If non-zero is returned,
  36244. ** then it is not necessary to include the nul-terminator character
  36245. ** in the output buffer.
  36246. **
  36247. ** Not supplying an error message will have no adverse effect
  36248. ** on SQLite. It is fine to have an implementation that never
  36249. ** returns an error message:
  36250. **
  36251. ** int xGetLastError(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
  36252. ** assert(zBuf[0]=='\0');
  36253. ** return 0;
  36254. ** }
  36255. **
  36256. ** However if an error message is supplied, it will be incorporated
  36257. ** by sqlite into the error message available to the user using
  36258. ** sqlite3_errmsg(), possibly making IO errors easier to debug.
  36259. */
  36260. static int winGetLastError(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
  36261. UNUSED_PARAMETER(pVfs);
  36262. return winGetLastErrorMsg(osGetLastError(), nBuf, zBuf);
  36263. }
  36264. /*
  36265. ** Initialize and deinitialize the operating system interface.
  36266. */
  36267. SQLITE_API int SQLITE_STDCALL sqlite3_os_init(void){
  36268. static sqlite3_vfs winVfs = {
  36269. 3, /* iVersion */
  36270. sizeof(winFile), /* szOsFile */
  36271. SQLITE_WIN32_MAX_PATH_BYTES, /* mxPathname */
  36272. 0, /* pNext */
  36273. "win32", /* zName */
  36274. 0, /* pAppData */
  36275. winOpen, /* xOpen */
  36276. winDelete, /* xDelete */
  36277. winAccess, /* xAccess */
  36278. winFullPathname, /* xFullPathname */
  36279. winDlOpen, /* xDlOpen */
  36280. winDlError, /* xDlError */
  36281. winDlSym, /* xDlSym */
  36282. winDlClose, /* xDlClose */
  36283. winRandomness, /* xRandomness */
  36284. winSleep, /* xSleep */
  36285. winCurrentTime, /* xCurrentTime */
  36286. winGetLastError, /* xGetLastError */
  36287. winCurrentTimeInt64, /* xCurrentTimeInt64 */
  36288. winSetSystemCall, /* xSetSystemCall */
  36289. winGetSystemCall, /* xGetSystemCall */
  36290. winNextSystemCall, /* xNextSystemCall */
  36291. };
  36292. #if defined(SQLITE_WIN32_HAS_WIDE)
  36293. static sqlite3_vfs winLongPathVfs = {
  36294. 3, /* iVersion */
  36295. sizeof(winFile), /* szOsFile */
  36296. SQLITE_WINNT_MAX_PATH_BYTES, /* mxPathname */
  36297. 0, /* pNext */
  36298. "win32-longpath", /* zName */
  36299. 0, /* pAppData */
  36300. winOpen, /* xOpen */
  36301. winDelete, /* xDelete */
  36302. winAccess, /* xAccess */
  36303. winFullPathname, /* xFullPathname */
  36304. winDlOpen, /* xDlOpen */
  36305. winDlError, /* xDlError */
  36306. winDlSym, /* xDlSym */
  36307. winDlClose, /* xDlClose */
  36308. winRandomness, /* xRandomness */
  36309. winSleep, /* xSleep */
  36310. winCurrentTime, /* xCurrentTime */
  36311. winGetLastError, /* xGetLastError */
  36312. winCurrentTimeInt64, /* xCurrentTimeInt64 */
  36313. winSetSystemCall, /* xSetSystemCall */
  36314. winGetSystemCall, /* xGetSystemCall */
  36315. winNextSystemCall, /* xNextSystemCall */
  36316. };
  36317. #endif
  36318. /* Double-check that the aSyscall[] array has been constructed
  36319. ** correctly. See ticket [bb3a86e890c8e96ab] */
  36320. assert( ArraySize(aSyscall)==80 );
  36321. /* get memory map allocation granularity */
  36322. memset(&winSysInfo, 0, sizeof(SYSTEM_INFO));
  36323. #if SQLITE_OS_WINRT
  36324. osGetNativeSystemInfo(&winSysInfo);
  36325. #else
  36326. osGetSystemInfo(&winSysInfo);
  36327. #endif
  36328. assert( winSysInfo.dwAllocationGranularity>0 );
  36329. assert( winSysInfo.dwPageSize>0 );
  36330. sqlite3_vfs_register(&winVfs, 1);
  36331. #if defined(SQLITE_WIN32_HAS_WIDE)
  36332. sqlite3_vfs_register(&winLongPathVfs, 0);
  36333. #endif
  36334. return SQLITE_OK;
  36335. }
  36336. SQLITE_API int SQLITE_STDCALL sqlite3_os_end(void){
  36337. #if SQLITE_OS_WINRT
  36338. if( sleepObj!=NULL ){
  36339. osCloseHandle(sleepObj);
  36340. sleepObj = NULL;
  36341. }
  36342. #endif
  36343. return SQLITE_OK;
  36344. }
  36345. #endif /* SQLITE_OS_WIN */
  36346. /************** End of os_win.c **********************************************/
  36347. /************** Begin file bitvec.c ******************************************/
  36348. /*
  36349. ** 2008 February 16
  36350. **
  36351. ** The author disclaims copyright to this source code. In place of
  36352. ** a legal notice, here is a blessing:
  36353. **
  36354. ** May you do good and not evil.
  36355. ** May you find forgiveness for yourself and forgive others.
  36356. ** May you share freely, never taking more than you give.
  36357. **
  36358. *************************************************************************
  36359. ** This file implements an object that represents a fixed-length
  36360. ** bitmap. Bits are numbered starting with 1.
  36361. **
  36362. ** A bitmap is used to record which pages of a database file have been
  36363. ** journalled during a transaction, or which pages have the "dont-write"
  36364. ** property. Usually only a few pages are meet either condition.
  36365. ** So the bitmap is usually sparse and has low cardinality.
  36366. ** But sometimes (for example when during a DROP of a large table) most
  36367. ** or all of the pages in a database can get journalled. In those cases,
  36368. ** the bitmap becomes dense with high cardinality. The algorithm needs
  36369. ** to handle both cases well.
  36370. **
  36371. ** The size of the bitmap is fixed when the object is created.
  36372. **
  36373. ** All bits are clear when the bitmap is created. Individual bits
  36374. ** may be set or cleared one at a time.
  36375. **
  36376. ** Test operations are about 100 times more common that set operations.
  36377. ** Clear operations are exceedingly rare. There are usually between
  36378. ** 5 and 500 set operations per Bitvec object, though the number of sets can
  36379. ** sometimes grow into tens of thousands or larger. The size of the
  36380. ** Bitvec object is the number of pages in the database file at the
  36381. ** start of a transaction, and is thus usually less than a few thousand,
  36382. ** but can be as large as 2 billion for a really big database.
  36383. */
  36384. /* Size of the Bitvec structure in bytes. */
  36385. #define BITVEC_SZ 512
  36386. /* Round the union size down to the nearest pointer boundary, since that's how
  36387. ** it will be aligned within the Bitvec struct. */
  36388. #define BITVEC_USIZE (((BITVEC_SZ-(3*sizeof(u32)))/sizeof(Bitvec*))*sizeof(Bitvec*))
  36389. /* Type of the array "element" for the bitmap representation.
  36390. ** Should be a power of 2, and ideally, evenly divide into BITVEC_USIZE.
  36391. ** Setting this to the "natural word" size of your CPU may improve
  36392. ** performance. */
  36393. #define BITVEC_TELEM u8
  36394. /* Size, in bits, of the bitmap element. */
  36395. #define BITVEC_SZELEM 8
  36396. /* Number of elements in a bitmap array. */
  36397. #define BITVEC_NELEM (BITVEC_USIZE/sizeof(BITVEC_TELEM))
  36398. /* Number of bits in the bitmap array. */
  36399. #define BITVEC_NBIT (BITVEC_NELEM*BITVEC_SZELEM)
  36400. /* Number of u32 values in hash table. */
  36401. #define BITVEC_NINT (BITVEC_USIZE/sizeof(u32))
  36402. /* Maximum number of entries in hash table before
  36403. ** sub-dividing and re-hashing. */
  36404. #define BITVEC_MXHASH (BITVEC_NINT/2)
  36405. /* Hashing function for the aHash representation.
  36406. ** Empirical testing showed that the *37 multiplier
  36407. ** (an arbitrary prime)in the hash function provided
  36408. ** no fewer collisions than the no-op *1. */
  36409. #define BITVEC_HASH(X) (((X)*1)%BITVEC_NINT)
  36410. #define BITVEC_NPTR (BITVEC_USIZE/sizeof(Bitvec *))
  36411. /*
  36412. ** A bitmap is an instance of the following structure.
  36413. **
  36414. ** This bitmap records the existence of zero or more bits
  36415. ** with values between 1 and iSize, inclusive.
  36416. **
  36417. ** There are three possible representations of the bitmap.
  36418. ** If iSize<=BITVEC_NBIT, then Bitvec.u.aBitmap[] is a straight
  36419. ** bitmap. The least significant bit is bit 1.
  36420. **
  36421. ** If iSize>BITVEC_NBIT and iDivisor==0 then Bitvec.u.aHash[] is
  36422. ** a hash table that will hold up to BITVEC_MXHASH distinct values.
  36423. **
  36424. ** Otherwise, the value i is redirected into one of BITVEC_NPTR
  36425. ** sub-bitmaps pointed to by Bitvec.u.apSub[]. Each subbitmap
  36426. ** handles up to iDivisor separate values of i. apSub[0] holds
  36427. ** values between 1 and iDivisor. apSub[1] holds values between
  36428. ** iDivisor+1 and 2*iDivisor. apSub[N] holds values between
  36429. ** N*iDivisor+1 and (N+1)*iDivisor. Each subbitmap is normalized
  36430. ** to hold deal with values between 1 and iDivisor.
  36431. */
  36432. struct Bitvec {
  36433. u32 iSize; /* Maximum bit index. Max iSize is 4,294,967,296. */
  36434. u32 nSet; /* Number of bits that are set - only valid for aHash
  36435. ** element. Max is BITVEC_NINT. For BITVEC_SZ of 512,
  36436. ** this would be 125. */
  36437. u32 iDivisor; /* Number of bits handled by each apSub[] entry. */
  36438. /* Should >=0 for apSub element. */
  36439. /* Max iDivisor is max(u32) / BITVEC_NPTR + 1. */
  36440. /* For a BITVEC_SZ of 512, this would be 34,359,739. */
  36441. union {
  36442. BITVEC_TELEM aBitmap[BITVEC_NELEM]; /* Bitmap representation */
  36443. u32 aHash[BITVEC_NINT]; /* Hash table representation */
  36444. Bitvec *apSub[BITVEC_NPTR]; /* Recursive representation */
  36445. } u;
  36446. };
  36447. /*
  36448. ** Create a new bitmap object able to handle bits between 0 and iSize,
  36449. ** inclusive. Return a pointer to the new object. Return NULL if
  36450. ** malloc fails.
  36451. */
  36452. SQLITE_PRIVATE Bitvec *sqlite3BitvecCreate(u32 iSize){
  36453. Bitvec *p;
  36454. assert( sizeof(*p)==BITVEC_SZ );
  36455. p = sqlite3MallocZero( sizeof(*p) );
  36456. if( p ){
  36457. p->iSize = iSize;
  36458. }
  36459. return p;
  36460. }
  36461. /*
  36462. ** Check to see if the i-th bit is set. Return true or false.
  36463. ** If p is NULL (if the bitmap has not been created) or if
  36464. ** i is out of range, then return false.
  36465. */
  36466. SQLITE_PRIVATE int sqlite3BitvecTest(Bitvec *p, u32 i){
  36467. if( p==0 ) return 0;
  36468. if( i>p->iSize || i==0 ) return 0;
  36469. i--;
  36470. while( p->iDivisor ){
  36471. u32 bin = i/p->iDivisor;
  36472. i = i%p->iDivisor;
  36473. p = p->u.apSub[bin];
  36474. if (!p) {
  36475. return 0;
  36476. }
  36477. }
  36478. if( p->iSize<=BITVEC_NBIT ){
  36479. return (p->u.aBitmap[i/BITVEC_SZELEM] & (1<<(i&(BITVEC_SZELEM-1))))!=0;
  36480. } else{
  36481. u32 h = BITVEC_HASH(i++);
  36482. while( p->u.aHash[h] ){
  36483. if( p->u.aHash[h]==i ) return 1;
  36484. h = (h+1) % BITVEC_NINT;
  36485. }
  36486. return 0;
  36487. }
  36488. }
  36489. /*
  36490. ** Set the i-th bit. Return 0 on success and an error code if
  36491. ** anything goes wrong.
  36492. **
  36493. ** This routine might cause sub-bitmaps to be allocated. Failing
  36494. ** to get the memory needed to hold the sub-bitmap is the only
  36495. ** that can go wrong with an insert, assuming p and i are valid.
  36496. **
  36497. ** The calling function must ensure that p is a valid Bitvec object
  36498. ** and that the value for "i" is within range of the Bitvec object.
  36499. ** Otherwise the behavior is undefined.
  36500. */
  36501. SQLITE_PRIVATE int sqlite3BitvecSet(Bitvec *p, u32 i){
  36502. u32 h;
  36503. if( p==0 ) return SQLITE_OK;
  36504. assert( i>0 );
  36505. assert( i<=p->iSize );
  36506. i--;
  36507. while((p->iSize > BITVEC_NBIT) && p->iDivisor) {
  36508. u32 bin = i/p->iDivisor;
  36509. i = i%p->iDivisor;
  36510. if( p->u.apSub[bin]==0 ){
  36511. p->u.apSub[bin] = sqlite3BitvecCreate( p->iDivisor );
  36512. if( p->u.apSub[bin]==0 ) return SQLITE_NOMEM;
  36513. }
  36514. p = p->u.apSub[bin];
  36515. }
  36516. if( p->iSize<=BITVEC_NBIT ){
  36517. p->u.aBitmap[i/BITVEC_SZELEM] |= 1 << (i&(BITVEC_SZELEM-1));
  36518. return SQLITE_OK;
  36519. }
  36520. h = BITVEC_HASH(i++);
  36521. /* if there wasn't a hash collision, and this doesn't */
  36522. /* completely fill the hash, then just add it without */
  36523. /* worring about sub-dividing and re-hashing. */
  36524. if( !p->u.aHash[h] ){
  36525. if (p->nSet<(BITVEC_NINT-1)) {
  36526. goto bitvec_set_end;
  36527. } else {
  36528. goto bitvec_set_rehash;
  36529. }
  36530. }
  36531. /* there was a collision, check to see if it's already */
  36532. /* in hash, if not, try to find a spot for it */
  36533. do {
  36534. if( p->u.aHash[h]==i ) return SQLITE_OK;
  36535. h++;
  36536. if( h>=BITVEC_NINT ) h = 0;
  36537. } while( p->u.aHash[h] );
  36538. /* we didn't find it in the hash. h points to the first */
  36539. /* available free spot. check to see if this is going to */
  36540. /* make our hash too "full". */
  36541. bitvec_set_rehash:
  36542. if( p->nSet>=BITVEC_MXHASH ){
  36543. unsigned int j;
  36544. int rc;
  36545. u32 *aiValues = sqlite3StackAllocRaw(0, sizeof(p->u.aHash));
  36546. if( aiValues==0 ){
  36547. return SQLITE_NOMEM;
  36548. }else{
  36549. memcpy(aiValues, p->u.aHash, sizeof(p->u.aHash));
  36550. memset(p->u.apSub, 0, sizeof(p->u.apSub));
  36551. p->iDivisor = (p->iSize + BITVEC_NPTR - 1)/BITVEC_NPTR;
  36552. rc = sqlite3BitvecSet(p, i);
  36553. for(j=0; j<BITVEC_NINT; j++){
  36554. if( aiValues[j] ) rc |= sqlite3BitvecSet(p, aiValues[j]);
  36555. }
  36556. sqlite3StackFree(0, aiValues);
  36557. return rc;
  36558. }
  36559. }
  36560. bitvec_set_end:
  36561. p->nSet++;
  36562. p->u.aHash[h] = i;
  36563. return SQLITE_OK;
  36564. }
  36565. /*
  36566. ** Clear the i-th bit.
  36567. **
  36568. ** pBuf must be a pointer to at least BITVEC_SZ bytes of temporary storage
  36569. ** that BitvecClear can use to rebuilt its hash table.
  36570. */
  36571. SQLITE_PRIVATE void sqlite3BitvecClear(Bitvec *p, u32 i, void *pBuf){
  36572. if( p==0 ) return;
  36573. assert( i>0 );
  36574. i--;
  36575. while( p->iDivisor ){
  36576. u32 bin = i/p->iDivisor;
  36577. i = i%p->iDivisor;
  36578. p = p->u.apSub[bin];
  36579. if (!p) {
  36580. return;
  36581. }
  36582. }
  36583. if( p->iSize<=BITVEC_NBIT ){
  36584. p->u.aBitmap[i/BITVEC_SZELEM] &= ~(1 << (i&(BITVEC_SZELEM-1)));
  36585. }else{
  36586. unsigned int j;
  36587. u32 *aiValues = pBuf;
  36588. memcpy(aiValues, p->u.aHash, sizeof(p->u.aHash));
  36589. memset(p->u.aHash, 0, sizeof(p->u.aHash));
  36590. p->nSet = 0;
  36591. for(j=0; j<BITVEC_NINT; j++){
  36592. if( aiValues[j] && aiValues[j]!=(i+1) ){
  36593. u32 h = BITVEC_HASH(aiValues[j]-1);
  36594. p->nSet++;
  36595. while( p->u.aHash[h] ){
  36596. h++;
  36597. if( h>=BITVEC_NINT ) h = 0;
  36598. }
  36599. p->u.aHash[h] = aiValues[j];
  36600. }
  36601. }
  36602. }
  36603. }
  36604. /*
  36605. ** Destroy a bitmap object. Reclaim all memory used.
  36606. */
  36607. SQLITE_PRIVATE void sqlite3BitvecDestroy(Bitvec *p){
  36608. if( p==0 ) return;
  36609. if( p->iDivisor ){
  36610. unsigned int i;
  36611. for(i=0; i<BITVEC_NPTR; i++){
  36612. sqlite3BitvecDestroy(p->u.apSub[i]);
  36613. }
  36614. }
  36615. sqlite3_free(p);
  36616. }
  36617. /*
  36618. ** Return the value of the iSize parameter specified when Bitvec *p
  36619. ** was created.
  36620. */
  36621. SQLITE_PRIVATE u32 sqlite3BitvecSize(Bitvec *p){
  36622. return p->iSize;
  36623. }
  36624. #ifndef SQLITE_OMIT_BUILTIN_TEST
  36625. /*
  36626. ** Let V[] be an array of unsigned characters sufficient to hold
  36627. ** up to N bits. Let I be an integer between 0 and N. 0<=I<N.
  36628. ** Then the following macros can be used to set, clear, or test
  36629. ** individual bits within V.
  36630. */
  36631. #define SETBIT(V,I) V[I>>3] |= (1<<(I&7))
  36632. #define CLEARBIT(V,I) V[I>>3] &= ~(1<<(I&7))
  36633. #define TESTBIT(V,I) (V[I>>3]&(1<<(I&7)))!=0
  36634. /*
  36635. ** This routine runs an extensive test of the Bitvec code.
  36636. **
  36637. ** The input is an array of integers that acts as a program
  36638. ** to test the Bitvec. The integers are opcodes followed
  36639. ** by 0, 1, or 3 operands, depending on the opcode. Another
  36640. ** opcode follows immediately after the last operand.
  36641. **
  36642. ** There are 6 opcodes numbered from 0 through 5. 0 is the
  36643. ** "halt" opcode and causes the test to end.
  36644. **
  36645. ** 0 Halt and return the number of errors
  36646. ** 1 N S X Set N bits beginning with S and incrementing by X
  36647. ** 2 N S X Clear N bits beginning with S and incrementing by X
  36648. ** 3 N Set N randomly chosen bits
  36649. ** 4 N Clear N randomly chosen bits
  36650. ** 5 N S X Set N bits from S increment X in array only, not in bitvec
  36651. **
  36652. ** The opcodes 1 through 4 perform set and clear operations are performed
  36653. ** on both a Bitvec object and on a linear array of bits obtained from malloc.
  36654. ** Opcode 5 works on the linear array only, not on the Bitvec.
  36655. ** Opcode 5 is used to deliberately induce a fault in order to
  36656. ** confirm that error detection works.
  36657. **
  36658. ** At the conclusion of the test the linear array is compared
  36659. ** against the Bitvec object. If there are any differences,
  36660. ** an error is returned. If they are the same, zero is returned.
  36661. **
  36662. ** If a memory allocation error occurs, return -1.
  36663. */
  36664. SQLITE_PRIVATE int sqlite3BitvecBuiltinTest(int sz, int *aOp){
  36665. Bitvec *pBitvec = 0;
  36666. unsigned char *pV = 0;
  36667. int rc = -1;
  36668. int i, nx, pc, op;
  36669. void *pTmpSpace;
  36670. /* Allocate the Bitvec to be tested and a linear array of
  36671. ** bits to act as the reference */
  36672. pBitvec = sqlite3BitvecCreate( sz );
  36673. pV = sqlite3MallocZero( (sz+7)/8 + 1 );
  36674. pTmpSpace = sqlite3_malloc64(BITVEC_SZ);
  36675. if( pBitvec==0 || pV==0 || pTmpSpace==0 ) goto bitvec_end;
  36676. /* NULL pBitvec tests */
  36677. sqlite3BitvecSet(0, 1);
  36678. sqlite3BitvecClear(0, 1, pTmpSpace);
  36679. /* Run the program */
  36680. pc = 0;
  36681. while( (op = aOp[pc])!=0 ){
  36682. switch( op ){
  36683. case 1:
  36684. case 2:
  36685. case 5: {
  36686. nx = 4;
  36687. i = aOp[pc+2] - 1;
  36688. aOp[pc+2] += aOp[pc+3];
  36689. break;
  36690. }
  36691. case 3:
  36692. case 4:
  36693. default: {
  36694. nx = 2;
  36695. sqlite3_randomness(sizeof(i), &i);
  36696. break;
  36697. }
  36698. }
  36699. if( (--aOp[pc+1]) > 0 ) nx = 0;
  36700. pc += nx;
  36701. i = (i & 0x7fffffff)%sz;
  36702. if( (op & 1)!=0 ){
  36703. SETBIT(pV, (i+1));
  36704. if( op!=5 ){
  36705. if( sqlite3BitvecSet(pBitvec, i+1) ) goto bitvec_end;
  36706. }
  36707. }else{
  36708. CLEARBIT(pV, (i+1));
  36709. sqlite3BitvecClear(pBitvec, i+1, pTmpSpace);
  36710. }
  36711. }
  36712. /* Test to make sure the linear array exactly matches the
  36713. ** Bitvec object. Start with the assumption that they do
  36714. ** match (rc==0). Change rc to non-zero if a discrepancy
  36715. ** is found.
  36716. */
  36717. rc = sqlite3BitvecTest(0,0) + sqlite3BitvecTest(pBitvec, sz+1)
  36718. + sqlite3BitvecTest(pBitvec, 0)
  36719. + (sqlite3BitvecSize(pBitvec) - sz);
  36720. for(i=1; i<=sz; i++){
  36721. if( (TESTBIT(pV,i))!=sqlite3BitvecTest(pBitvec,i) ){
  36722. rc = i;
  36723. break;
  36724. }
  36725. }
  36726. /* Free allocated structure */
  36727. bitvec_end:
  36728. sqlite3_free(pTmpSpace);
  36729. sqlite3_free(pV);
  36730. sqlite3BitvecDestroy(pBitvec);
  36731. return rc;
  36732. }
  36733. #endif /* SQLITE_OMIT_BUILTIN_TEST */
  36734. /************** End of bitvec.c **********************************************/
  36735. /************** Begin file pcache.c ******************************************/
  36736. /*
  36737. ** 2008 August 05
  36738. **
  36739. ** The author disclaims copyright to this source code. In place of
  36740. ** a legal notice, here is a blessing:
  36741. **
  36742. ** May you do good and not evil.
  36743. ** May you find forgiveness for yourself and forgive others.
  36744. ** May you share freely, never taking more than you give.
  36745. **
  36746. *************************************************************************
  36747. ** This file implements that page cache.
  36748. */
  36749. /*
  36750. ** A complete page cache is an instance of this structure.
  36751. */
  36752. struct PCache {
  36753. PgHdr *pDirty, *pDirtyTail; /* List of dirty pages in LRU order */
  36754. PgHdr *pSynced; /* Last synced page in dirty page list */
  36755. int nRef; /* Number of referenced pages */
  36756. int szCache; /* Configured cache size */
  36757. int szPage; /* Size of every page in this cache */
  36758. int szExtra; /* Size of extra space for each page */
  36759. u8 bPurgeable; /* True if pages are on backing store */
  36760. u8 eCreate; /* eCreate value for for xFetch() */
  36761. int (*xStress)(void*,PgHdr*); /* Call to try make a page clean */
  36762. void *pStress; /* Argument to xStress */
  36763. sqlite3_pcache *pCache; /* Pluggable cache module */
  36764. PgHdr *pPage1; /* Reference to page 1 */
  36765. };
  36766. /********************************** Linked List Management ********************/
  36767. /* Allowed values for second argument to pcacheManageDirtyList() */
  36768. #define PCACHE_DIRTYLIST_REMOVE 1 /* Remove pPage from dirty list */
  36769. #define PCACHE_DIRTYLIST_ADD 2 /* Add pPage to the dirty list */
  36770. #define PCACHE_DIRTYLIST_FRONT 3 /* Move pPage to the front of the list */
  36771. /*
  36772. ** Manage pPage's participation on the dirty list. Bits of the addRemove
  36773. ** argument determines what operation to do. The 0x01 bit means first
  36774. ** remove pPage from the dirty list. The 0x02 means add pPage back to
  36775. ** the dirty list. Doing both moves pPage to the front of the dirty list.
  36776. */
  36777. static void pcacheManageDirtyList(PgHdr *pPage, u8 addRemove){
  36778. PCache *p = pPage->pCache;
  36779. if( addRemove & PCACHE_DIRTYLIST_REMOVE ){
  36780. assert( pPage->pDirtyNext || pPage==p->pDirtyTail );
  36781. assert( pPage->pDirtyPrev || pPage==p->pDirty );
  36782. /* Update the PCache1.pSynced variable if necessary. */
  36783. if( p->pSynced==pPage ){
  36784. PgHdr *pSynced = pPage->pDirtyPrev;
  36785. while( pSynced && (pSynced->flags&PGHDR_NEED_SYNC) ){
  36786. pSynced = pSynced->pDirtyPrev;
  36787. }
  36788. p->pSynced = pSynced;
  36789. }
  36790. if( pPage->pDirtyNext ){
  36791. pPage->pDirtyNext->pDirtyPrev = pPage->pDirtyPrev;
  36792. }else{
  36793. assert( pPage==p->pDirtyTail );
  36794. p->pDirtyTail = pPage->pDirtyPrev;
  36795. }
  36796. if( pPage->pDirtyPrev ){
  36797. pPage->pDirtyPrev->pDirtyNext = pPage->pDirtyNext;
  36798. }else{
  36799. assert( pPage==p->pDirty );
  36800. p->pDirty = pPage->pDirtyNext;
  36801. if( p->pDirty==0 && p->bPurgeable ){
  36802. assert( p->eCreate==1 );
  36803. p->eCreate = 2;
  36804. }
  36805. }
  36806. pPage->pDirtyNext = 0;
  36807. pPage->pDirtyPrev = 0;
  36808. }
  36809. if( addRemove & PCACHE_DIRTYLIST_ADD ){
  36810. assert( pPage->pDirtyNext==0 && pPage->pDirtyPrev==0 && p->pDirty!=pPage );
  36811. pPage->pDirtyNext = p->pDirty;
  36812. if( pPage->pDirtyNext ){
  36813. assert( pPage->pDirtyNext->pDirtyPrev==0 );
  36814. pPage->pDirtyNext->pDirtyPrev = pPage;
  36815. }else{
  36816. p->pDirtyTail = pPage;
  36817. if( p->bPurgeable ){
  36818. assert( p->eCreate==2 );
  36819. p->eCreate = 1;
  36820. }
  36821. }
  36822. p->pDirty = pPage;
  36823. if( !p->pSynced && 0==(pPage->flags&PGHDR_NEED_SYNC) ){
  36824. p->pSynced = pPage;
  36825. }
  36826. }
  36827. }
  36828. /*
  36829. ** Wrapper around the pluggable caches xUnpin method. If the cache is
  36830. ** being used for an in-memory database, this function is a no-op.
  36831. */
  36832. static void pcacheUnpin(PgHdr *p){
  36833. if( p->pCache->bPurgeable ){
  36834. if( p->pgno==1 ){
  36835. p->pCache->pPage1 = 0;
  36836. }
  36837. sqlite3GlobalConfig.pcache2.xUnpin(p->pCache->pCache, p->pPage, 0);
  36838. }
  36839. }
  36840. /*
  36841. ** Compute the number of pages of cache requested. p->szCache is the
  36842. ** cache size requested by the "PRAGMA cache_size" statement.
  36843. **
  36844. **
  36845. */
  36846. static int numberOfCachePages(PCache *p){
  36847. if( p->szCache>=0 ){
  36848. /* IMPLEMENTATION-OF: R-42059-47211 If the argument N is positive then the
  36849. ** suggested cache size is set to N. */
  36850. return p->szCache;
  36851. }else{
  36852. /* IMPLEMENTATION-OF: R-61436-13639 If the argument N is negative, then
  36853. ** the number of cache pages is adjusted to use approximately abs(N*1024)
  36854. ** bytes of memory. */
  36855. return (int)((-1024*(i64)p->szCache)/(p->szPage+p->szExtra));
  36856. }
  36857. }
  36858. /*************************************************** General Interfaces ******
  36859. **
  36860. ** Initialize and shutdown the page cache subsystem. Neither of these
  36861. ** functions are threadsafe.
  36862. */
  36863. SQLITE_PRIVATE int sqlite3PcacheInitialize(void){
  36864. if( sqlite3GlobalConfig.pcache2.xInit==0 ){
  36865. /* IMPLEMENTATION-OF: R-26801-64137 If the xInit() method is NULL, then the
  36866. ** built-in default page cache is used instead of the application defined
  36867. ** page cache. */
  36868. sqlite3PCacheSetDefault();
  36869. }
  36870. return sqlite3GlobalConfig.pcache2.xInit(sqlite3GlobalConfig.pcache2.pArg);
  36871. }
  36872. SQLITE_PRIVATE void sqlite3PcacheShutdown(void){
  36873. if( sqlite3GlobalConfig.pcache2.xShutdown ){
  36874. /* IMPLEMENTATION-OF: R-26000-56589 The xShutdown() method may be NULL. */
  36875. sqlite3GlobalConfig.pcache2.xShutdown(sqlite3GlobalConfig.pcache2.pArg);
  36876. }
  36877. }
  36878. /*
  36879. ** Return the size in bytes of a PCache object.
  36880. */
  36881. SQLITE_PRIVATE int sqlite3PcacheSize(void){ return sizeof(PCache); }
  36882. /*
  36883. ** Create a new PCache object. Storage space to hold the object
  36884. ** has already been allocated and is passed in as the p pointer.
  36885. ** The caller discovers how much space needs to be allocated by
  36886. ** calling sqlite3PcacheSize().
  36887. */
  36888. SQLITE_PRIVATE int sqlite3PcacheOpen(
  36889. int szPage, /* Size of every page */
  36890. int szExtra, /* Extra space associated with each page */
  36891. int bPurgeable, /* True if pages are on backing store */
  36892. int (*xStress)(void*,PgHdr*),/* Call to try to make pages clean */
  36893. void *pStress, /* Argument to xStress */
  36894. PCache *p /* Preallocated space for the PCache */
  36895. ){
  36896. memset(p, 0, sizeof(PCache));
  36897. p->szPage = 1;
  36898. p->szExtra = szExtra;
  36899. p->bPurgeable = bPurgeable;
  36900. p->eCreate = 2;
  36901. p->xStress = xStress;
  36902. p->pStress = pStress;
  36903. p->szCache = 100;
  36904. return sqlite3PcacheSetPageSize(p, szPage);
  36905. }
  36906. /*
  36907. ** Change the page size for PCache object. The caller must ensure that there
  36908. ** are no outstanding page references when this function is called.
  36909. */
  36910. SQLITE_PRIVATE int sqlite3PcacheSetPageSize(PCache *pCache, int szPage){
  36911. assert( pCache->nRef==0 && pCache->pDirty==0 );
  36912. if( pCache->szPage ){
  36913. sqlite3_pcache *pNew;
  36914. pNew = sqlite3GlobalConfig.pcache2.xCreate(
  36915. szPage, pCache->szExtra + ROUND8(sizeof(PgHdr)),
  36916. pCache->bPurgeable
  36917. );
  36918. if( pNew==0 ) return SQLITE_NOMEM;
  36919. sqlite3GlobalConfig.pcache2.xCachesize(pNew, numberOfCachePages(pCache));
  36920. if( pCache->pCache ){
  36921. sqlite3GlobalConfig.pcache2.xDestroy(pCache->pCache);
  36922. }
  36923. pCache->pCache = pNew;
  36924. pCache->pPage1 = 0;
  36925. pCache->szPage = szPage;
  36926. }
  36927. return SQLITE_OK;
  36928. }
  36929. /*
  36930. ** Try to obtain a page from the cache.
  36931. **
  36932. ** This routine returns a pointer to an sqlite3_pcache_page object if
  36933. ** such an object is already in cache, or if a new one is created.
  36934. ** This routine returns a NULL pointer if the object was not in cache
  36935. ** and could not be created.
  36936. **
  36937. ** The createFlags should be 0 to check for existing pages and should
  36938. ** be 3 (not 1, but 3) to try to create a new page.
  36939. **
  36940. ** If the createFlag is 0, then NULL is always returned if the page
  36941. ** is not already in the cache. If createFlag is 1, then a new page
  36942. ** is created only if that can be done without spilling dirty pages
  36943. ** and without exceeding the cache size limit.
  36944. **
  36945. ** The caller needs to invoke sqlite3PcacheFetchFinish() to properly
  36946. ** initialize the sqlite3_pcache_page object and convert it into a
  36947. ** PgHdr object. The sqlite3PcacheFetch() and sqlite3PcacheFetchFinish()
  36948. ** routines are split this way for performance reasons. When separated
  36949. ** they can both (usually) operate without having to push values to
  36950. ** the stack on entry and pop them back off on exit, which saves a
  36951. ** lot of pushing and popping.
  36952. */
  36953. SQLITE_PRIVATE sqlite3_pcache_page *sqlite3PcacheFetch(
  36954. PCache *pCache, /* Obtain the page from this cache */
  36955. Pgno pgno, /* Page number to obtain */
  36956. int createFlag /* If true, create page if it does not exist already */
  36957. ){
  36958. int eCreate;
  36959. assert( pCache!=0 );
  36960. assert( pCache->pCache!=0 );
  36961. assert( createFlag==3 || createFlag==0 );
  36962. assert( pgno>0 );
  36963. /* eCreate defines what to do if the page does not exist.
  36964. ** 0 Do not allocate a new page. (createFlag==0)
  36965. ** 1 Allocate a new page if doing so is inexpensive.
  36966. ** (createFlag==1 AND bPurgeable AND pDirty)
  36967. ** 2 Allocate a new page even it doing so is difficult.
  36968. ** (createFlag==1 AND !(bPurgeable AND pDirty)
  36969. */
  36970. eCreate = createFlag & pCache->eCreate;
  36971. assert( eCreate==0 || eCreate==1 || eCreate==2 );
  36972. assert( createFlag==0 || pCache->eCreate==eCreate );
  36973. assert( createFlag==0 || eCreate==1+(!pCache->bPurgeable||!pCache->pDirty) );
  36974. return sqlite3GlobalConfig.pcache2.xFetch(pCache->pCache, pgno, eCreate);
  36975. }
  36976. /*
  36977. ** If the sqlite3PcacheFetch() routine is unable to allocate a new
  36978. ** page because new clean pages are available for reuse and the cache
  36979. ** size limit has been reached, then this routine can be invoked to
  36980. ** try harder to allocate a page. This routine might invoke the stress
  36981. ** callback to spill dirty pages to the journal. It will then try to
  36982. ** allocate the new page and will only fail to allocate a new page on
  36983. ** an OOM error.
  36984. **
  36985. ** This routine should be invoked only after sqlite3PcacheFetch() fails.
  36986. */
  36987. SQLITE_PRIVATE int sqlite3PcacheFetchStress(
  36988. PCache *pCache, /* Obtain the page from this cache */
  36989. Pgno pgno, /* Page number to obtain */
  36990. sqlite3_pcache_page **ppPage /* Write result here */
  36991. ){
  36992. PgHdr *pPg;
  36993. if( pCache->eCreate==2 ) return 0;
  36994. /* Find a dirty page to write-out and recycle. First try to find a
  36995. ** page that does not require a journal-sync (one with PGHDR_NEED_SYNC
  36996. ** cleared), but if that is not possible settle for any other
  36997. ** unreferenced dirty page.
  36998. */
  36999. for(pPg=pCache->pSynced;
  37000. pPg && (pPg->nRef || (pPg->flags&PGHDR_NEED_SYNC));
  37001. pPg=pPg->pDirtyPrev
  37002. );
  37003. pCache->pSynced = pPg;
  37004. if( !pPg ){
  37005. for(pPg=pCache->pDirtyTail; pPg && pPg->nRef; pPg=pPg->pDirtyPrev);
  37006. }
  37007. if( pPg ){
  37008. int rc;
  37009. #ifdef SQLITE_LOG_CACHE_SPILL
  37010. sqlite3_log(SQLITE_FULL,
  37011. "spill page %d making room for %d - cache used: %d/%d",
  37012. pPg->pgno, pgno,
  37013. sqlite3GlobalConfig.pcache.xPagecount(pCache->pCache),
  37014. numberOfCachePages(pCache));
  37015. #endif
  37016. rc = pCache->xStress(pCache->pStress, pPg);
  37017. if( rc!=SQLITE_OK && rc!=SQLITE_BUSY ){
  37018. return rc;
  37019. }
  37020. }
  37021. *ppPage = sqlite3GlobalConfig.pcache2.xFetch(pCache->pCache, pgno, 2);
  37022. return *ppPage==0 ? SQLITE_NOMEM : SQLITE_OK;
  37023. }
  37024. /*
  37025. ** This is a helper routine for sqlite3PcacheFetchFinish()
  37026. **
  37027. ** In the uncommon case where the page being fetched has not been
  37028. ** initialized, this routine is invoked to do the initialization.
  37029. ** This routine is broken out into a separate function since it
  37030. ** requires extra stack manipulation that can be avoided in the common
  37031. ** case.
  37032. */
  37033. static SQLITE_NOINLINE PgHdr *pcacheFetchFinishWithInit(
  37034. PCache *pCache, /* Obtain the page from this cache */
  37035. Pgno pgno, /* Page number obtained */
  37036. sqlite3_pcache_page *pPage /* Page obtained by prior PcacheFetch() call */
  37037. ){
  37038. PgHdr *pPgHdr;
  37039. assert( pPage!=0 );
  37040. pPgHdr = (PgHdr*)pPage->pExtra;
  37041. assert( pPgHdr->pPage==0 );
  37042. memset(pPgHdr, 0, sizeof(PgHdr));
  37043. pPgHdr->pPage = pPage;
  37044. pPgHdr->pData = pPage->pBuf;
  37045. pPgHdr->pExtra = (void *)&pPgHdr[1];
  37046. memset(pPgHdr->pExtra, 0, pCache->szExtra);
  37047. pPgHdr->pCache = pCache;
  37048. pPgHdr->pgno = pgno;
  37049. return sqlite3PcacheFetchFinish(pCache,pgno,pPage);
  37050. }
  37051. /*
  37052. ** This routine converts the sqlite3_pcache_page object returned by
  37053. ** sqlite3PcacheFetch() into an initialized PgHdr object. This routine
  37054. ** must be called after sqlite3PcacheFetch() in order to get a usable
  37055. ** result.
  37056. */
  37057. SQLITE_PRIVATE PgHdr *sqlite3PcacheFetchFinish(
  37058. PCache *pCache, /* Obtain the page from this cache */
  37059. Pgno pgno, /* Page number obtained */
  37060. sqlite3_pcache_page *pPage /* Page obtained by prior PcacheFetch() call */
  37061. ){
  37062. PgHdr *pPgHdr;
  37063. if( pPage==0 ) return 0;
  37064. pPgHdr = (PgHdr *)pPage->pExtra;
  37065. if( !pPgHdr->pPage ){
  37066. return pcacheFetchFinishWithInit(pCache, pgno, pPage);
  37067. }
  37068. if( 0==pPgHdr->nRef ){
  37069. pCache->nRef++;
  37070. }
  37071. pPgHdr->nRef++;
  37072. if( pgno==1 ){
  37073. pCache->pPage1 = pPgHdr;
  37074. }
  37075. return pPgHdr;
  37076. }
  37077. /*
  37078. ** Decrement the reference count on a page. If the page is clean and the
  37079. ** reference count drops to 0, then it is made eligible for recycling.
  37080. */
  37081. SQLITE_PRIVATE void SQLITE_NOINLINE sqlite3PcacheRelease(PgHdr *p){
  37082. assert( p->nRef>0 );
  37083. p->nRef--;
  37084. if( p->nRef==0 ){
  37085. p->pCache->nRef--;
  37086. if( (p->flags&PGHDR_DIRTY)==0 ){
  37087. pcacheUnpin(p);
  37088. }else if( p->pDirtyPrev!=0 ){
  37089. /* Move the page to the head of the dirty list. */
  37090. pcacheManageDirtyList(p, PCACHE_DIRTYLIST_FRONT);
  37091. }
  37092. }
  37093. }
  37094. /*
  37095. ** Increase the reference count of a supplied page by 1.
  37096. */
  37097. SQLITE_PRIVATE void sqlite3PcacheRef(PgHdr *p){
  37098. assert(p->nRef>0);
  37099. p->nRef++;
  37100. }
  37101. /*
  37102. ** Drop a page from the cache. There must be exactly one reference to the
  37103. ** page. This function deletes that reference, so after it returns the
  37104. ** page pointed to by p is invalid.
  37105. */
  37106. SQLITE_PRIVATE void sqlite3PcacheDrop(PgHdr *p){
  37107. assert( p->nRef==1 );
  37108. if( p->flags&PGHDR_DIRTY ){
  37109. pcacheManageDirtyList(p, PCACHE_DIRTYLIST_REMOVE);
  37110. }
  37111. p->pCache->nRef--;
  37112. if( p->pgno==1 ){
  37113. p->pCache->pPage1 = 0;
  37114. }
  37115. sqlite3GlobalConfig.pcache2.xUnpin(p->pCache->pCache, p->pPage, 1);
  37116. }
  37117. /*
  37118. ** Make sure the page is marked as dirty. If it isn't dirty already,
  37119. ** make it so.
  37120. */
  37121. SQLITE_PRIVATE void sqlite3PcacheMakeDirty(PgHdr *p){
  37122. p->flags &= ~PGHDR_DONT_WRITE;
  37123. assert( p->nRef>0 );
  37124. if( 0==(p->flags & PGHDR_DIRTY) ){
  37125. p->flags |= PGHDR_DIRTY;
  37126. pcacheManageDirtyList(p, PCACHE_DIRTYLIST_ADD);
  37127. }
  37128. }
  37129. /*
  37130. ** Make sure the page is marked as clean. If it isn't clean already,
  37131. ** make it so.
  37132. */
  37133. SQLITE_PRIVATE void sqlite3PcacheMakeClean(PgHdr *p){
  37134. if( (p->flags & PGHDR_DIRTY) ){
  37135. pcacheManageDirtyList(p, PCACHE_DIRTYLIST_REMOVE);
  37136. p->flags &= ~(PGHDR_DIRTY|PGHDR_NEED_SYNC);
  37137. if( p->nRef==0 ){
  37138. pcacheUnpin(p);
  37139. }
  37140. }
  37141. }
  37142. /*
  37143. ** Make every page in the cache clean.
  37144. */
  37145. SQLITE_PRIVATE void sqlite3PcacheCleanAll(PCache *pCache){
  37146. PgHdr *p;
  37147. while( (p = pCache->pDirty)!=0 ){
  37148. sqlite3PcacheMakeClean(p);
  37149. }
  37150. }
  37151. /*
  37152. ** Clear the PGHDR_NEED_SYNC flag from all dirty pages.
  37153. */
  37154. SQLITE_PRIVATE void sqlite3PcacheClearSyncFlags(PCache *pCache){
  37155. PgHdr *p;
  37156. for(p=pCache->pDirty; p; p=p->pDirtyNext){
  37157. p->flags &= ~PGHDR_NEED_SYNC;
  37158. }
  37159. pCache->pSynced = pCache->pDirtyTail;
  37160. }
  37161. /*
  37162. ** Change the page number of page p to newPgno.
  37163. */
  37164. SQLITE_PRIVATE void sqlite3PcacheMove(PgHdr *p, Pgno newPgno){
  37165. PCache *pCache = p->pCache;
  37166. assert( p->nRef>0 );
  37167. assert( newPgno>0 );
  37168. sqlite3GlobalConfig.pcache2.xRekey(pCache->pCache, p->pPage, p->pgno,newPgno);
  37169. p->pgno = newPgno;
  37170. if( (p->flags&PGHDR_DIRTY) && (p->flags&PGHDR_NEED_SYNC) ){
  37171. pcacheManageDirtyList(p, PCACHE_DIRTYLIST_FRONT);
  37172. }
  37173. }
  37174. /*
  37175. ** Drop every cache entry whose page number is greater than "pgno". The
  37176. ** caller must ensure that there are no outstanding references to any pages
  37177. ** other than page 1 with a page number greater than pgno.
  37178. **
  37179. ** If there is a reference to page 1 and the pgno parameter passed to this
  37180. ** function is 0, then the data area associated with page 1 is zeroed, but
  37181. ** the page object is not dropped.
  37182. */
  37183. SQLITE_PRIVATE void sqlite3PcacheTruncate(PCache *pCache, Pgno pgno){
  37184. if( pCache->pCache ){
  37185. PgHdr *p;
  37186. PgHdr *pNext;
  37187. for(p=pCache->pDirty; p; p=pNext){
  37188. pNext = p->pDirtyNext;
  37189. /* This routine never gets call with a positive pgno except right
  37190. ** after sqlite3PcacheCleanAll(). So if there are dirty pages,
  37191. ** it must be that pgno==0.
  37192. */
  37193. assert( p->pgno>0 );
  37194. if( ALWAYS(p->pgno>pgno) ){
  37195. assert( p->flags&PGHDR_DIRTY );
  37196. sqlite3PcacheMakeClean(p);
  37197. }
  37198. }
  37199. if( pgno==0 && pCache->pPage1 ){
  37200. memset(pCache->pPage1->pData, 0, pCache->szPage);
  37201. pgno = 1;
  37202. }
  37203. sqlite3GlobalConfig.pcache2.xTruncate(pCache->pCache, pgno+1);
  37204. }
  37205. }
  37206. /*
  37207. ** Close a cache.
  37208. */
  37209. SQLITE_PRIVATE void sqlite3PcacheClose(PCache *pCache){
  37210. assert( pCache->pCache!=0 );
  37211. sqlite3GlobalConfig.pcache2.xDestroy(pCache->pCache);
  37212. }
  37213. /*
  37214. ** Discard the contents of the cache.
  37215. */
  37216. SQLITE_PRIVATE void sqlite3PcacheClear(PCache *pCache){
  37217. sqlite3PcacheTruncate(pCache, 0);
  37218. }
  37219. /*
  37220. ** Merge two lists of pages connected by pDirty and in pgno order.
  37221. ** Do not both fixing the pDirtyPrev pointers.
  37222. */
  37223. static PgHdr *pcacheMergeDirtyList(PgHdr *pA, PgHdr *pB){
  37224. PgHdr result, *pTail;
  37225. pTail = &result;
  37226. while( pA && pB ){
  37227. if( pA->pgno<pB->pgno ){
  37228. pTail->pDirty = pA;
  37229. pTail = pA;
  37230. pA = pA->pDirty;
  37231. }else{
  37232. pTail->pDirty = pB;
  37233. pTail = pB;
  37234. pB = pB->pDirty;
  37235. }
  37236. }
  37237. if( pA ){
  37238. pTail->pDirty = pA;
  37239. }else if( pB ){
  37240. pTail->pDirty = pB;
  37241. }else{
  37242. pTail->pDirty = 0;
  37243. }
  37244. return result.pDirty;
  37245. }
  37246. /*
  37247. ** Sort the list of pages in accending order by pgno. Pages are
  37248. ** connected by pDirty pointers. The pDirtyPrev pointers are
  37249. ** corrupted by this sort.
  37250. **
  37251. ** Since there cannot be more than 2^31 distinct pages in a database,
  37252. ** there cannot be more than 31 buckets required by the merge sorter.
  37253. ** One extra bucket is added to catch overflow in case something
  37254. ** ever changes to make the previous sentence incorrect.
  37255. */
  37256. #define N_SORT_BUCKET 32
  37257. static PgHdr *pcacheSortDirtyList(PgHdr *pIn){
  37258. PgHdr *a[N_SORT_BUCKET], *p;
  37259. int i;
  37260. memset(a, 0, sizeof(a));
  37261. while( pIn ){
  37262. p = pIn;
  37263. pIn = p->pDirty;
  37264. p->pDirty = 0;
  37265. for(i=0; ALWAYS(i<N_SORT_BUCKET-1); i++){
  37266. if( a[i]==0 ){
  37267. a[i] = p;
  37268. break;
  37269. }else{
  37270. p = pcacheMergeDirtyList(a[i], p);
  37271. a[i] = 0;
  37272. }
  37273. }
  37274. if( NEVER(i==N_SORT_BUCKET-1) ){
  37275. /* To get here, there need to be 2^(N_SORT_BUCKET) elements in
  37276. ** the input list. But that is impossible.
  37277. */
  37278. a[i] = pcacheMergeDirtyList(a[i], p);
  37279. }
  37280. }
  37281. p = a[0];
  37282. for(i=1; i<N_SORT_BUCKET; i++){
  37283. p = pcacheMergeDirtyList(p, a[i]);
  37284. }
  37285. return p;
  37286. }
  37287. /*
  37288. ** Return a list of all dirty pages in the cache, sorted by page number.
  37289. */
  37290. SQLITE_PRIVATE PgHdr *sqlite3PcacheDirtyList(PCache *pCache){
  37291. PgHdr *p;
  37292. for(p=pCache->pDirty; p; p=p->pDirtyNext){
  37293. p->pDirty = p->pDirtyNext;
  37294. }
  37295. return pcacheSortDirtyList(pCache->pDirty);
  37296. }
  37297. /*
  37298. ** Return the total number of referenced pages held by the cache.
  37299. */
  37300. SQLITE_PRIVATE int sqlite3PcacheRefCount(PCache *pCache){
  37301. return pCache->nRef;
  37302. }
  37303. /*
  37304. ** Return the number of references to the page supplied as an argument.
  37305. */
  37306. SQLITE_PRIVATE int sqlite3PcachePageRefcount(PgHdr *p){
  37307. return p->nRef;
  37308. }
  37309. /*
  37310. ** Return the total number of pages in the cache.
  37311. */
  37312. SQLITE_PRIVATE int sqlite3PcachePagecount(PCache *pCache){
  37313. assert( pCache->pCache!=0 );
  37314. return sqlite3GlobalConfig.pcache2.xPagecount(pCache->pCache);
  37315. }
  37316. #ifdef SQLITE_TEST
  37317. /*
  37318. ** Get the suggested cache-size value.
  37319. */
  37320. SQLITE_PRIVATE int sqlite3PcacheGetCachesize(PCache *pCache){
  37321. return numberOfCachePages(pCache);
  37322. }
  37323. #endif
  37324. /*
  37325. ** Set the suggested cache-size value.
  37326. */
  37327. SQLITE_PRIVATE void sqlite3PcacheSetCachesize(PCache *pCache, int mxPage){
  37328. assert( pCache->pCache!=0 );
  37329. pCache->szCache = mxPage;
  37330. sqlite3GlobalConfig.pcache2.xCachesize(pCache->pCache,
  37331. numberOfCachePages(pCache));
  37332. }
  37333. /*
  37334. ** Free up as much memory as possible from the page cache.
  37335. */
  37336. SQLITE_PRIVATE void sqlite3PcacheShrink(PCache *pCache){
  37337. assert( pCache->pCache!=0 );
  37338. sqlite3GlobalConfig.pcache2.xShrink(pCache->pCache);
  37339. }
  37340. /*
  37341. ** Return the size of the header added by this middleware layer
  37342. ** in the page-cache hierarchy.
  37343. */
  37344. SQLITE_PRIVATE int sqlite3HeaderSizePcache(void){ return ROUND8(sizeof(PgHdr)); }
  37345. #if defined(SQLITE_CHECK_PAGES) || defined(SQLITE_DEBUG)
  37346. /*
  37347. ** For all dirty pages currently in the cache, invoke the specified
  37348. ** callback. This is only used if the SQLITE_CHECK_PAGES macro is
  37349. ** defined.
  37350. */
  37351. SQLITE_PRIVATE void sqlite3PcacheIterateDirty(PCache *pCache, void (*xIter)(PgHdr *)){
  37352. PgHdr *pDirty;
  37353. for(pDirty=pCache->pDirty; pDirty; pDirty=pDirty->pDirtyNext){
  37354. xIter(pDirty);
  37355. }
  37356. }
  37357. #endif
  37358. /************** End of pcache.c **********************************************/
  37359. /************** Begin file pcache1.c *****************************************/
  37360. /*
  37361. ** 2008 November 05
  37362. **
  37363. ** The author disclaims copyright to this source code. In place of
  37364. ** a legal notice, here is a blessing:
  37365. **
  37366. ** May you do good and not evil.
  37367. ** May you find forgiveness for yourself and forgive others.
  37368. ** May you share freely, never taking more than you give.
  37369. **
  37370. *************************************************************************
  37371. **
  37372. ** This file implements the default page cache implementation (the
  37373. ** sqlite3_pcache interface). It also contains part of the implementation
  37374. ** of the SQLITE_CONFIG_PAGECACHE and sqlite3_release_memory() features.
  37375. ** If the default page cache implementation is overridden, then neither of
  37376. ** these two features are available.
  37377. */
  37378. typedef struct PCache1 PCache1;
  37379. typedef struct PgHdr1 PgHdr1;
  37380. typedef struct PgFreeslot PgFreeslot;
  37381. typedef struct PGroup PGroup;
  37382. /* Each page cache (or PCache) belongs to a PGroup. A PGroup is a set
  37383. ** of one or more PCaches that are able to recycle each other's unpinned
  37384. ** pages when they are under memory pressure. A PGroup is an instance of
  37385. ** the following object.
  37386. **
  37387. ** This page cache implementation works in one of two modes:
  37388. **
  37389. ** (1) Every PCache is the sole member of its own PGroup. There is
  37390. ** one PGroup per PCache.
  37391. **
  37392. ** (2) There is a single global PGroup that all PCaches are a member
  37393. ** of.
  37394. **
  37395. ** Mode 1 uses more memory (since PCache instances are not able to rob
  37396. ** unused pages from other PCaches) but it also operates without a mutex,
  37397. ** and is therefore often faster. Mode 2 requires a mutex in order to be
  37398. ** threadsafe, but recycles pages more efficiently.
  37399. **
  37400. ** For mode (1), PGroup.mutex is NULL. For mode (2) there is only a single
  37401. ** PGroup which is the pcache1.grp global variable and its mutex is
  37402. ** SQLITE_MUTEX_STATIC_LRU.
  37403. */
  37404. struct PGroup {
  37405. sqlite3_mutex *mutex; /* MUTEX_STATIC_LRU or NULL */
  37406. unsigned int nMaxPage; /* Sum of nMax for purgeable caches */
  37407. unsigned int nMinPage; /* Sum of nMin for purgeable caches */
  37408. unsigned int mxPinned; /* nMaxpage + 10 - nMinPage */
  37409. unsigned int nCurrentPage; /* Number of purgeable pages allocated */
  37410. PgHdr1 *pLruHead, *pLruTail; /* LRU list of unpinned pages */
  37411. };
  37412. /* Each page cache is an instance of the following object. Every
  37413. ** open database file (including each in-memory database and each
  37414. ** temporary or transient database) has a single page cache which
  37415. ** is an instance of this object.
  37416. **
  37417. ** Pointers to structures of this type are cast and returned as
  37418. ** opaque sqlite3_pcache* handles.
  37419. */
  37420. struct PCache1 {
  37421. /* Cache configuration parameters. Page size (szPage) and the purgeable
  37422. ** flag (bPurgeable) are set when the cache is created. nMax may be
  37423. ** modified at any time by a call to the pcache1Cachesize() method.
  37424. ** The PGroup mutex must be held when accessing nMax.
  37425. */
  37426. PGroup *pGroup; /* PGroup this cache belongs to */
  37427. int szPage; /* Size of allocated pages in bytes */
  37428. int szExtra; /* Size of extra space in bytes */
  37429. int bPurgeable; /* True if cache is purgeable */
  37430. unsigned int nMin; /* Minimum number of pages reserved */
  37431. unsigned int nMax; /* Configured "cache_size" value */
  37432. unsigned int n90pct; /* nMax*9/10 */
  37433. unsigned int iMaxKey; /* Largest key seen since xTruncate() */
  37434. /* Hash table of all pages. The following variables may only be accessed
  37435. ** when the accessor is holding the PGroup mutex.
  37436. */
  37437. unsigned int nRecyclable; /* Number of pages in the LRU list */
  37438. unsigned int nPage; /* Total number of pages in apHash */
  37439. unsigned int nHash; /* Number of slots in apHash[] */
  37440. PgHdr1 **apHash; /* Hash table for fast lookup by key */
  37441. };
  37442. /*
  37443. ** Each cache entry is represented by an instance of the following
  37444. ** structure. Unless SQLITE_PCACHE_SEPARATE_HEADER is defined, a buffer of
  37445. ** PgHdr1.pCache->szPage bytes is allocated directly before this structure
  37446. ** in memory.
  37447. */
  37448. struct PgHdr1 {
  37449. sqlite3_pcache_page page;
  37450. unsigned int iKey; /* Key value (page number) */
  37451. u8 isPinned; /* Page in use, not on the LRU list */
  37452. PgHdr1 *pNext; /* Next in hash table chain */
  37453. PCache1 *pCache; /* Cache that currently owns this page */
  37454. PgHdr1 *pLruNext; /* Next in LRU list of unpinned pages */
  37455. PgHdr1 *pLruPrev; /* Previous in LRU list of unpinned pages */
  37456. };
  37457. /*
  37458. ** Free slots in the allocator used to divide up the buffer provided using
  37459. ** the SQLITE_CONFIG_PAGECACHE mechanism.
  37460. */
  37461. struct PgFreeslot {
  37462. PgFreeslot *pNext; /* Next free slot */
  37463. };
  37464. /*
  37465. ** Global data used by this cache.
  37466. */
  37467. static SQLITE_WSD struct PCacheGlobal {
  37468. PGroup grp; /* The global PGroup for mode (2) */
  37469. /* Variables related to SQLITE_CONFIG_PAGECACHE settings. The
  37470. ** szSlot, nSlot, pStart, pEnd, nReserve, and isInit values are all
  37471. ** fixed at sqlite3_initialize() time and do not require mutex protection.
  37472. ** The nFreeSlot and pFree values do require mutex protection.
  37473. */
  37474. int isInit; /* True if initialized */
  37475. int szSlot; /* Size of each free slot */
  37476. int nSlot; /* The number of pcache slots */
  37477. int nReserve; /* Try to keep nFreeSlot above this */
  37478. void *pStart, *pEnd; /* Bounds of pagecache malloc range */
  37479. /* Above requires no mutex. Use mutex below for variable that follow. */
  37480. sqlite3_mutex *mutex; /* Mutex for accessing the following: */
  37481. PgFreeslot *pFree; /* Free page blocks */
  37482. int nFreeSlot; /* Number of unused pcache slots */
  37483. /* The following value requires a mutex to change. We skip the mutex on
  37484. ** reading because (1) most platforms read a 32-bit integer atomically and
  37485. ** (2) even if an incorrect value is read, no great harm is done since this
  37486. ** is really just an optimization. */
  37487. int bUnderPressure; /* True if low on PAGECACHE memory */
  37488. } pcache1_g;
  37489. /*
  37490. ** All code in this file should access the global structure above via the
  37491. ** alias "pcache1". This ensures that the WSD emulation is used when
  37492. ** compiling for systems that do not support real WSD.
  37493. */
  37494. #define pcache1 (GLOBAL(struct PCacheGlobal, pcache1_g))
  37495. /*
  37496. ** Macros to enter and leave the PCache LRU mutex.
  37497. */
  37498. #define pcache1EnterMutex(X) sqlite3_mutex_enter((X)->mutex)
  37499. #define pcache1LeaveMutex(X) sqlite3_mutex_leave((X)->mutex)
  37500. /******************************************************************************/
  37501. /******** Page Allocation/SQLITE_CONFIG_PCACHE Related Functions **************/
  37502. /*
  37503. ** This function is called during initialization if a static buffer is
  37504. ** supplied to use for the page-cache by passing the SQLITE_CONFIG_PAGECACHE
  37505. ** verb to sqlite3_config(). Parameter pBuf points to an allocation large
  37506. ** enough to contain 'n' buffers of 'sz' bytes each.
  37507. **
  37508. ** This routine is called from sqlite3_initialize() and so it is guaranteed
  37509. ** to be serialized already. There is no need for further mutexing.
  37510. */
  37511. SQLITE_PRIVATE void sqlite3PCacheBufferSetup(void *pBuf, int sz, int n){
  37512. if( pcache1.isInit ){
  37513. PgFreeslot *p;
  37514. sz = ROUNDDOWN8(sz);
  37515. pcache1.szSlot = sz;
  37516. pcache1.nSlot = pcache1.nFreeSlot = n;
  37517. pcache1.nReserve = n>90 ? 10 : (n/10 + 1);
  37518. pcache1.pStart = pBuf;
  37519. pcache1.pFree = 0;
  37520. pcache1.bUnderPressure = 0;
  37521. while( n-- ){
  37522. p = (PgFreeslot*)pBuf;
  37523. p->pNext = pcache1.pFree;
  37524. pcache1.pFree = p;
  37525. pBuf = (void*)&((char*)pBuf)[sz];
  37526. }
  37527. pcache1.pEnd = pBuf;
  37528. }
  37529. }
  37530. /*
  37531. ** Malloc function used within this file to allocate space from the buffer
  37532. ** configured using sqlite3_config(SQLITE_CONFIG_PAGECACHE) option. If no
  37533. ** such buffer exists or there is no space left in it, this function falls
  37534. ** back to sqlite3Malloc().
  37535. **
  37536. ** Multiple threads can run this routine at the same time. Global variables
  37537. ** in pcache1 need to be protected via mutex.
  37538. */
  37539. static void *pcache1Alloc(int nByte){
  37540. void *p = 0;
  37541. assert( sqlite3_mutex_notheld(pcache1.grp.mutex) );
  37542. if( nByte<=pcache1.szSlot ){
  37543. sqlite3_mutex_enter(pcache1.mutex);
  37544. p = (PgHdr1 *)pcache1.pFree;
  37545. if( p ){
  37546. pcache1.pFree = pcache1.pFree->pNext;
  37547. pcache1.nFreeSlot--;
  37548. pcache1.bUnderPressure = pcache1.nFreeSlot<pcache1.nReserve;
  37549. assert( pcache1.nFreeSlot>=0 );
  37550. sqlite3StatusSet(SQLITE_STATUS_PAGECACHE_SIZE, nByte);
  37551. sqlite3StatusUp(SQLITE_STATUS_PAGECACHE_USED, 1);
  37552. }
  37553. sqlite3_mutex_leave(pcache1.mutex);
  37554. }
  37555. if( p==0 ){
  37556. /* Memory is not available in the SQLITE_CONFIG_PAGECACHE pool. Get
  37557. ** it from sqlite3Malloc instead.
  37558. */
  37559. p = sqlite3Malloc(nByte);
  37560. #ifndef SQLITE_DISABLE_PAGECACHE_OVERFLOW_STATS
  37561. if( p ){
  37562. int sz = sqlite3MallocSize(p);
  37563. sqlite3_mutex_enter(pcache1.mutex);
  37564. sqlite3StatusSet(SQLITE_STATUS_PAGECACHE_SIZE, nByte);
  37565. sqlite3StatusUp(SQLITE_STATUS_PAGECACHE_OVERFLOW, sz);
  37566. sqlite3_mutex_leave(pcache1.mutex);
  37567. }
  37568. #endif
  37569. sqlite3MemdebugSetType(p, MEMTYPE_PCACHE);
  37570. }
  37571. return p;
  37572. }
  37573. /*
  37574. ** Free an allocated buffer obtained from pcache1Alloc().
  37575. */
  37576. static int pcache1Free(void *p){
  37577. int nFreed = 0;
  37578. if( p==0 ) return 0;
  37579. if( p>=pcache1.pStart && p<pcache1.pEnd ){
  37580. PgFreeslot *pSlot;
  37581. sqlite3_mutex_enter(pcache1.mutex);
  37582. sqlite3StatusDown(SQLITE_STATUS_PAGECACHE_USED, 1);
  37583. pSlot = (PgFreeslot*)p;
  37584. pSlot->pNext = pcache1.pFree;
  37585. pcache1.pFree = pSlot;
  37586. pcache1.nFreeSlot++;
  37587. pcache1.bUnderPressure = pcache1.nFreeSlot<pcache1.nReserve;
  37588. assert( pcache1.nFreeSlot<=pcache1.nSlot );
  37589. sqlite3_mutex_leave(pcache1.mutex);
  37590. }else{
  37591. assert( sqlite3MemdebugHasType(p, MEMTYPE_PCACHE) );
  37592. sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
  37593. nFreed = sqlite3MallocSize(p);
  37594. #ifndef SQLITE_DISABLE_PAGECACHE_OVERFLOW_STATS
  37595. sqlite3_mutex_enter(pcache1.mutex);
  37596. sqlite3StatusDown(SQLITE_STATUS_PAGECACHE_OVERFLOW, nFreed);
  37597. sqlite3_mutex_leave(pcache1.mutex);
  37598. #endif
  37599. sqlite3_free(p);
  37600. }
  37601. return nFreed;
  37602. }
  37603. #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
  37604. /*
  37605. ** Return the size of a pcache allocation
  37606. */
  37607. static int pcache1MemSize(void *p){
  37608. if( p>=pcache1.pStart && p<pcache1.pEnd ){
  37609. return pcache1.szSlot;
  37610. }else{
  37611. int iSize;
  37612. assert( sqlite3MemdebugHasType(p, MEMTYPE_PCACHE) );
  37613. sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
  37614. iSize = sqlite3MallocSize(p);
  37615. sqlite3MemdebugSetType(p, MEMTYPE_PCACHE);
  37616. return iSize;
  37617. }
  37618. }
  37619. #endif /* SQLITE_ENABLE_MEMORY_MANAGEMENT */
  37620. /*
  37621. ** Allocate a new page object initially associated with cache pCache.
  37622. */
  37623. static PgHdr1 *pcache1AllocPage(PCache1 *pCache){
  37624. PgHdr1 *p = 0;
  37625. void *pPg;
  37626. /* The group mutex must be released before pcache1Alloc() is called. This
  37627. ** is because it may call sqlite3_release_memory(), which assumes that
  37628. ** this mutex is not held. */
  37629. assert( sqlite3_mutex_held(pCache->pGroup->mutex) );
  37630. pcache1LeaveMutex(pCache->pGroup);
  37631. #ifdef SQLITE_PCACHE_SEPARATE_HEADER
  37632. pPg = pcache1Alloc(pCache->szPage);
  37633. p = sqlite3Malloc(sizeof(PgHdr1) + pCache->szExtra);
  37634. if( !pPg || !p ){
  37635. pcache1Free(pPg);
  37636. sqlite3_free(p);
  37637. pPg = 0;
  37638. }
  37639. #else
  37640. pPg = pcache1Alloc(ROUND8(sizeof(PgHdr1)) + pCache->szPage + pCache->szExtra);
  37641. p = (PgHdr1 *)&((u8 *)pPg)[pCache->szPage];
  37642. #endif
  37643. pcache1EnterMutex(pCache->pGroup);
  37644. if( pPg ){
  37645. p->page.pBuf = pPg;
  37646. p->page.pExtra = &p[1];
  37647. if( pCache->bPurgeable ){
  37648. pCache->pGroup->nCurrentPage++;
  37649. }
  37650. return p;
  37651. }
  37652. return 0;
  37653. }
  37654. /*
  37655. ** Free a page object allocated by pcache1AllocPage().
  37656. **
  37657. ** The pointer is allowed to be NULL, which is prudent. But it turns out
  37658. ** that the current implementation happens to never call this routine
  37659. ** with a NULL pointer, so we mark the NULL test with ALWAYS().
  37660. */
  37661. static void pcache1FreePage(PgHdr1 *p){
  37662. if( ALWAYS(p) ){
  37663. PCache1 *pCache = p->pCache;
  37664. assert( sqlite3_mutex_held(p->pCache->pGroup->mutex) );
  37665. pcache1Free(p->page.pBuf);
  37666. #ifdef SQLITE_PCACHE_SEPARATE_HEADER
  37667. sqlite3_free(p);
  37668. #endif
  37669. if( pCache->bPurgeable ){
  37670. pCache->pGroup->nCurrentPage--;
  37671. }
  37672. }
  37673. }
  37674. /*
  37675. ** Malloc function used by SQLite to obtain space from the buffer configured
  37676. ** using sqlite3_config(SQLITE_CONFIG_PAGECACHE) option. If no such buffer
  37677. ** exists, this function falls back to sqlite3Malloc().
  37678. */
  37679. SQLITE_PRIVATE void *sqlite3PageMalloc(int sz){
  37680. return pcache1Alloc(sz);
  37681. }
  37682. /*
  37683. ** Free an allocated buffer obtained from sqlite3PageMalloc().
  37684. */
  37685. SQLITE_PRIVATE void sqlite3PageFree(void *p){
  37686. pcache1Free(p);
  37687. }
  37688. /*
  37689. ** Return true if it desirable to avoid allocating a new page cache
  37690. ** entry.
  37691. **
  37692. ** If memory was allocated specifically to the page cache using
  37693. ** SQLITE_CONFIG_PAGECACHE but that memory has all been used, then
  37694. ** it is desirable to avoid allocating a new page cache entry because
  37695. ** presumably SQLITE_CONFIG_PAGECACHE was suppose to be sufficient
  37696. ** for all page cache needs and we should not need to spill the
  37697. ** allocation onto the heap.
  37698. **
  37699. ** Or, the heap is used for all page cache memory but the heap is
  37700. ** under memory pressure, then again it is desirable to avoid
  37701. ** allocating a new page cache entry in order to avoid stressing
  37702. ** the heap even further.
  37703. */
  37704. static int pcache1UnderMemoryPressure(PCache1 *pCache){
  37705. if( pcache1.nSlot && (pCache->szPage+pCache->szExtra)<=pcache1.szSlot ){
  37706. return pcache1.bUnderPressure;
  37707. }else{
  37708. return sqlite3HeapNearlyFull();
  37709. }
  37710. }
  37711. /******************************************************************************/
  37712. /******** General Implementation Functions ************************************/
  37713. /*
  37714. ** This function is used to resize the hash table used by the cache passed
  37715. ** as the first argument.
  37716. **
  37717. ** The PCache mutex must be held when this function is called.
  37718. */
  37719. static void pcache1ResizeHash(PCache1 *p){
  37720. PgHdr1 **apNew;
  37721. unsigned int nNew;
  37722. unsigned int i;
  37723. assert( sqlite3_mutex_held(p->pGroup->mutex) );
  37724. nNew = p->nHash*2;
  37725. if( nNew<256 ){
  37726. nNew = 256;
  37727. }
  37728. pcache1LeaveMutex(p->pGroup);
  37729. if( p->nHash ){ sqlite3BeginBenignMalloc(); }
  37730. apNew = (PgHdr1 **)sqlite3MallocZero(sizeof(PgHdr1 *)*nNew);
  37731. if( p->nHash ){ sqlite3EndBenignMalloc(); }
  37732. pcache1EnterMutex(p->pGroup);
  37733. if( apNew ){
  37734. for(i=0; i<p->nHash; i++){
  37735. PgHdr1 *pPage;
  37736. PgHdr1 *pNext = p->apHash[i];
  37737. while( (pPage = pNext)!=0 ){
  37738. unsigned int h = pPage->iKey % nNew;
  37739. pNext = pPage->pNext;
  37740. pPage->pNext = apNew[h];
  37741. apNew[h] = pPage;
  37742. }
  37743. }
  37744. sqlite3_free(p->apHash);
  37745. p->apHash = apNew;
  37746. p->nHash = nNew;
  37747. }
  37748. }
  37749. /*
  37750. ** This function is used internally to remove the page pPage from the
  37751. ** PGroup LRU list, if is part of it. If pPage is not part of the PGroup
  37752. ** LRU list, then this function is a no-op.
  37753. **
  37754. ** The PGroup mutex must be held when this function is called.
  37755. */
  37756. static void pcache1PinPage(PgHdr1 *pPage){
  37757. PCache1 *pCache;
  37758. PGroup *pGroup;
  37759. assert( pPage!=0 );
  37760. assert( pPage->isPinned==0 );
  37761. pCache = pPage->pCache;
  37762. pGroup = pCache->pGroup;
  37763. assert( pPage->pLruNext || pPage==pGroup->pLruTail );
  37764. assert( pPage->pLruPrev || pPage==pGroup->pLruHead );
  37765. assert( sqlite3_mutex_held(pGroup->mutex) );
  37766. if( pPage->pLruPrev ){
  37767. pPage->pLruPrev->pLruNext = pPage->pLruNext;
  37768. }else{
  37769. pGroup->pLruHead = pPage->pLruNext;
  37770. }
  37771. if( pPage->pLruNext ){
  37772. pPage->pLruNext->pLruPrev = pPage->pLruPrev;
  37773. }else{
  37774. pGroup->pLruTail = pPage->pLruPrev;
  37775. }
  37776. pPage->pLruNext = 0;
  37777. pPage->pLruPrev = 0;
  37778. pPage->isPinned = 1;
  37779. pCache->nRecyclable--;
  37780. }
  37781. /*
  37782. ** Remove the page supplied as an argument from the hash table
  37783. ** (PCache1.apHash structure) that it is currently stored in.
  37784. **
  37785. ** The PGroup mutex must be held when this function is called.
  37786. */
  37787. static void pcache1RemoveFromHash(PgHdr1 *pPage){
  37788. unsigned int h;
  37789. PCache1 *pCache = pPage->pCache;
  37790. PgHdr1 **pp;
  37791. assert( sqlite3_mutex_held(pCache->pGroup->mutex) );
  37792. h = pPage->iKey % pCache->nHash;
  37793. for(pp=&pCache->apHash[h]; (*pp)!=pPage; pp=&(*pp)->pNext);
  37794. *pp = (*pp)->pNext;
  37795. pCache->nPage--;
  37796. }
  37797. /*
  37798. ** If there are currently more than nMaxPage pages allocated, try
  37799. ** to recycle pages to reduce the number allocated to nMaxPage.
  37800. */
  37801. static void pcache1EnforceMaxPage(PGroup *pGroup){
  37802. assert( sqlite3_mutex_held(pGroup->mutex) );
  37803. while( pGroup->nCurrentPage>pGroup->nMaxPage && pGroup->pLruTail ){
  37804. PgHdr1 *p = pGroup->pLruTail;
  37805. assert( p->pCache->pGroup==pGroup );
  37806. assert( p->isPinned==0 );
  37807. pcache1PinPage(p);
  37808. pcache1RemoveFromHash(p);
  37809. pcache1FreePage(p);
  37810. }
  37811. }
  37812. /*
  37813. ** Discard all pages from cache pCache with a page number (key value)
  37814. ** greater than or equal to iLimit. Any pinned pages that meet this
  37815. ** criteria are unpinned before they are discarded.
  37816. **
  37817. ** The PCache mutex must be held when this function is called.
  37818. */
  37819. static void pcache1TruncateUnsafe(
  37820. PCache1 *pCache, /* The cache to truncate */
  37821. unsigned int iLimit /* Drop pages with this pgno or larger */
  37822. ){
  37823. TESTONLY( unsigned int nPage = 0; ) /* To assert pCache->nPage is correct */
  37824. unsigned int h;
  37825. assert( sqlite3_mutex_held(pCache->pGroup->mutex) );
  37826. for(h=0; h<pCache->nHash; h++){
  37827. PgHdr1 **pp = &pCache->apHash[h];
  37828. PgHdr1 *pPage;
  37829. while( (pPage = *pp)!=0 ){
  37830. if( pPage->iKey>=iLimit ){
  37831. pCache->nPage--;
  37832. *pp = pPage->pNext;
  37833. if( !pPage->isPinned ) pcache1PinPage(pPage);
  37834. pcache1FreePage(pPage);
  37835. }else{
  37836. pp = &pPage->pNext;
  37837. TESTONLY( nPage++; )
  37838. }
  37839. }
  37840. }
  37841. assert( pCache->nPage==nPage );
  37842. }
  37843. /******************************************************************************/
  37844. /******** sqlite3_pcache Methods **********************************************/
  37845. /*
  37846. ** Implementation of the sqlite3_pcache.xInit method.
  37847. */
  37848. static int pcache1Init(void *NotUsed){
  37849. UNUSED_PARAMETER(NotUsed);
  37850. assert( pcache1.isInit==0 );
  37851. memset(&pcache1, 0, sizeof(pcache1));
  37852. if( sqlite3GlobalConfig.bCoreMutex ){
  37853. pcache1.grp.mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_LRU);
  37854. pcache1.mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_PMEM);
  37855. }
  37856. pcache1.grp.mxPinned = 10;
  37857. pcache1.isInit = 1;
  37858. return SQLITE_OK;
  37859. }
  37860. /*
  37861. ** Implementation of the sqlite3_pcache.xShutdown method.
  37862. ** Note that the static mutex allocated in xInit does
  37863. ** not need to be freed.
  37864. */
  37865. static void pcache1Shutdown(void *NotUsed){
  37866. UNUSED_PARAMETER(NotUsed);
  37867. assert( pcache1.isInit!=0 );
  37868. memset(&pcache1, 0, sizeof(pcache1));
  37869. }
  37870. /* forward declaration */
  37871. static void pcache1Destroy(sqlite3_pcache *p);
  37872. /*
  37873. ** Implementation of the sqlite3_pcache.xCreate method.
  37874. **
  37875. ** Allocate a new cache.
  37876. */
  37877. static sqlite3_pcache *pcache1Create(int szPage, int szExtra, int bPurgeable){
  37878. PCache1 *pCache; /* The newly created page cache */
  37879. PGroup *pGroup; /* The group the new page cache will belong to */
  37880. int sz; /* Bytes of memory required to allocate the new cache */
  37881. /*
  37882. ** The separateCache variable is true if each PCache has its own private
  37883. ** PGroup. In other words, separateCache is true for mode (1) where no
  37884. ** mutexing is required.
  37885. **
  37886. ** * Always use a unified cache (mode-2) if ENABLE_MEMORY_MANAGEMENT
  37887. **
  37888. ** * Always use a unified cache in single-threaded applications
  37889. **
  37890. ** * Otherwise (if multi-threaded and ENABLE_MEMORY_MANAGEMENT is off)
  37891. ** use separate caches (mode-1)
  37892. */
  37893. #if defined(SQLITE_ENABLE_MEMORY_MANAGEMENT) || SQLITE_THREADSAFE==0
  37894. const int separateCache = 0;
  37895. #else
  37896. int separateCache = sqlite3GlobalConfig.bCoreMutex>0;
  37897. #endif
  37898. assert( (szPage & (szPage-1))==0 && szPage>=512 && szPage<=65536 );
  37899. assert( szExtra < 300 );
  37900. sz = sizeof(PCache1) + sizeof(PGroup)*separateCache;
  37901. pCache = (PCache1 *)sqlite3MallocZero(sz);
  37902. if( pCache ){
  37903. if( separateCache ){
  37904. pGroup = (PGroup*)&pCache[1];
  37905. pGroup->mxPinned = 10;
  37906. }else{
  37907. pGroup = &pcache1.grp;
  37908. }
  37909. pCache->pGroup = pGroup;
  37910. pCache->szPage = szPage;
  37911. pCache->szExtra = szExtra;
  37912. pCache->bPurgeable = (bPurgeable ? 1 : 0);
  37913. pcache1EnterMutex(pGroup);
  37914. pcache1ResizeHash(pCache);
  37915. if( bPurgeable ){
  37916. pCache->nMin = 10;
  37917. pGroup->nMinPage += pCache->nMin;
  37918. pGroup->mxPinned = pGroup->nMaxPage + 10 - pGroup->nMinPage;
  37919. }
  37920. pcache1LeaveMutex(pGroup);
  37921. if( pCache->nHash==0 ){
  37922. pcache1Destroy((sqlite3_pcache*)pCache);
  37923. pCache = 0;
  37924. }
  37925. }
  37926. return (sqlite3_pcache *)pCache;
  37927. }
  37928. /*
  37929. ** Implementation of the sqlite3_pcache.xCachesize method.
  37930. **
  37931. ** Configure the cache_size limit for a cache.
  37932. */
  37933. static void pcache1Cachesize(sqlite3_pcache *p, int nMax){
  37934. PCache1 *pCache = (PCache1 *)p;
  37935. if( pCache->bPurgeable ){
  37936. PGroup *pGroup = pCache->pGroup;
  37937. pcache1EnterMutex(pGroup);
  37938. pGroup->nMaxPage += (nMax - pCache->nMax);
  37939. pGroup->mxPinned = pGroup->nMaxPage + 10 - pGroup->nMinPage;
  37940. pCache->nMax = nMax;
  37941. pCache->n90pct = pCache->nMax*9/10;
  37942. pcache1EnforceMaxPage(pGroup);
  37943. pcache1LeaveMutex(pGroup);
  37944. }
  37945. }
  37946. /*
  37947. ** Implementation of the sqlite3_pcache.xShrink method.
  37948. **
  37949. ** Free up as much memory as possible.
  37950. */
  37951. static void pcache1Shrink(sqlite3_pcache *p){
  37952. PCache1 *pCache = (PCache1*)p;
  37953. if( pCache->bPurgeable ){
  37954. PGroup *pGroup = pCache->pGroup;
  37955. int savedMaxPage;
  37956. pcache1EnterMutex(pGroup);
  37957. savedMaxPage = pGroup->nMaxPage;
  37958. pGroup->nMaxPage = 0;
  37959. pcache1EnforceMaxPage(pGroup);
  37960. pGroup->nMaxPage = savedMaxPage;
  37961. pcache1LeaveMutex(pGroup);
  37962. }
  37963. }
  37964. /*
  37965. ** Implementation of the sqlite3_pcache.xPagecount method.
  37966. */
  37967. static int pcache1Pagecount(sqlite3_pcache *p){
  37968. int n;
  37969. PCache1 *pCache = (PCache1*)p;
  37970. pcache1EnterMutex(pCache->pGroup);
  37971. n = pCache->nPage;
  37972. pcache1LeaveMutex(pCache->pGroup);
  37973. return n;
  37974. }
  37975. /*
  37976. ** Implement steps 3, 4, and 5 of the pcache1Fetch() algorithm described
  37977. ** in the header of the pcache1Fetch() procedure.
  37978. **
  37979. ** This steps are broken out into a separate procedure because they are
  37980. ** usually not needed, and by avoiding the stack initialization required
  37981. ** for these steps, the main pcache1Fetch() procedure can run faster.
  37982. */
  37983. static SQLITE_NOINLINE PgHdr1 *pcache1FetchStage2(
  37984. PCache1 *pCache,
  37985. unsigned int iKey,
  37986. int createFlag
  37987. ){
  37988. unsigned int nPinned;
  37989. PGroup *pGroup = pCache->pGroup;
  37990. PgHdr1 *pPage = 0;
  37991. /* Step 3: Abort if createFlag is 1 but the cache is nearly full */
  37992. assert( pCache->nPage >= pCache->nRecyclable );
  37993. nPinned = pCache->nPage - pCache->nRecyclable;
  37994. assert( pGroup->mxPinned == pGroup->nMaxPage + 10 - pGroup->nMinPage );
  37995. assert( pCache->n90pct == pCache->nMax*9/10 );
  37996. if( createFlag==1 && (
  37997. nPinned>=pGroup->mxPinned
  37998. || nPinned>=pCache->n90pct
  37999. || (pcache1UnderMemoryPressure(pCache) && pCache->nRecyclable<nPinned)
  38000. )){
  38001. return 0;
  38002. }
  38003. if( pCache->nPage>=pCache->nHash ) pcache1ResizeHash(pCache);
  38004. assert( pCache->nHash>0 && pCache->apHash );
  38005. /* Step 4. Try to recycle a page. */
  38006. if( pCache->bPurgeable && pGroup->pLruTail && (
  38007. (pCache->nPage+1>=pCache->nMax)
  38008. || pGroup->nCurrentPage>=pGroup->nMaxPage
  38009. || pcache1UnderMemoryPressure(pCache)
  38010. )){
  38011. PCache1 *pOther;
  38012. pPage = pGroup->pLruTail;
  38013. assert( pPage->isPinned==0 );
  38014. pcache1RemoveFromHash(pPage);
  38015. pcache1PinPage(pPage);
  38016. pOther = pPage->pCache;
  38017. /* We want to verify that szPage and szExtra are the same for pOther
  38018. ** and pCache. Assert that we can verify this by comparing sums. */
  38019. assert( (pCache->szPage & (pCache->szPage-1))==0 && pCache->szPage>=512 );
  38020. assert( pCache->szExtra<512 );
  38021. assert( (pOther->szPage & (pOther->szPage-1))==0 && pOther->szPage>=512 );
  38022. assert( pOther->szExtra<512 );
  38023. if( pOther->szPage+pOther->szExtra != pCache->szPage+pCache->szExtra ){
  38024. pcache1FreePage(pPage);
  38025. pPage = 0;
  38026. }else{
  38027. pGroup->nCurrentPage -= (pOther->bPurgeable - pCache->bPurgeable);
  38028. }
  38029. }
  38030. /* Step 5. If a usable page buffer has still not been found,
  38031. ** attempt to allocate a new one.
  38032. */
  38033. if( !pPage ){
  38034. if( createFlag==1 ) sqlite3BeginBenignMalloc();
  38035. pPage = pcache1AllocPage(pCache);
  38036. if( createFlag==1 ) sqlite3EndBenignMalloc();
  38037. }
  38038. if( pPage ){
  38039. unsigned int h = iKey % pCache->nHash;
  38040. pCache->nPage++;
  38041. pPage->iKey = iKey;
  38042. pPage->pNext = pCache->apHash[h];
  38043. pPage->pCache = pCache;
  38044. pPage->pLruPrev = 0;
  38045. pPage->pLruNext = 0;
  38046. pPage->isPinned = 1;
  38047. *(void **)pPage->page.pExtra = 0;
  38048. pCache->apHash[h] = pPage;
  38049. if( iKey>pCache->iMaxKey ){
  38050. pCache->iMaxKey = iKey;
  38051. }
  38052. }
  38053. return pPage;
  38054. }
  38055. /*
  38056. ** Implementation of the sqlite3_pcache.xFetch method.
  38057. **
  38058. ** Fetch a page by key value.
  38059. **
  38060. ** Whether or not a new page may be allocated by this function depends on
  38061. ** the value of the createFlag argument. 0 means do not allocate a new
  38062. ** page. 1 means allocate a new page if space is easily available. 2
  38063. ** means to try really hard to allocate a new page.
  38064. **
  38065. ** For a non-purgeable cache (a cache used as the storage for an in-memory
  38066. ** database) there is really no difference between createFlag 1 and 2. So
  38067. ** the calling function (pcache.c) will never have a createFlag of 1 on
  38068. ** a non-purgeable cache.
  38069. **
  38070. ** There are three different approaches to obtaining space for a page,
  38071. ** depending on the value of parameter createFlag (which may be 0, 1 or 2).
  38072. **
  38073. ** 1. Regardless of the value of createFlag, the cache is searched for a
  38074. ** copy of the requested page. If one is found, it is returned.
  38075. **
  38076. ** 2. If createFlag==0 and the page is not already in the cache, NULL is
  38077. ** returned.
  38078. **
  38079. ** 3. If createFlag is 1, and the page is not already in the cache, then
  38080. ** return NULL (do not allocate a new page) if any of the following
  38081. ** conditions are true:
  38082. **
  38083. ** (a) the number of pages pinned by the cache is greater than
  38084. ** PCache1.nMax, or
  38085. **
  38086. ** (b) the number of pages pinned by the cache is greater than
  38087. ** the sum of nMax for all purgeable caches, less the sum of
  38088. ** nMin for all other purgeable caches, or
  38089. **
  38090. ** 4. If none of the first three conditions apply and the cache is marked
  38091. ** as purgeable, and if one of the following is true:
  38092. **
  38093. ** (a) The number of pages allocated for the cache is already
  38094. ** PCache1.nMax, or
  38095. **
  38096. ** (b) The number of pages allocated for all purgeable caches is
  38097. ** already equal to or greater than the sum of nMax for all
  38098. ** purgeable caches,
  38099. **
  38100. ** (c) The system is under memory pressure and wants to avoid
  38101. ** unnecessary pages cache entry allocations
  38102. **
  38103. ** then attempt to recycle a page from the LRU list. If it is the right
  38104. ** size, return the recycled buffer. Otherwise, free the buffer and
  38105. ** proceed to step 5.
  38106. **
  38107. ** 5. Otherwise, allocate and return a new page buffer.
  38108. */
  38109. static sqlite3_pcache_page *pcache1Fetch(
  38110. sqlite3_pcache *p,
  38111. unsigned int iKey,
  38112. int createFlag
  38113. ){
  38114. PCache1 *pCache = (PCache1 *)p;
  38115. PgHdr1 *pPage = 0;
  38116. assert( offsetof(PgHdr1,page)==0 );
  38117. assert( pCache->bPurgeable || createFlag!=1 );
  38118. assert( pCache->bPurgeable || pCache->nMin==0 );
  38119. assert( pCache->bPurgeable==0 || pCache->nMin==10 );
  38120. assert( pCache->nMin==0 || pCache->bPurgeable );
  38121. assert( pCache->nHash>0 );
  38122. pcache1EnterMutex(pCache->pGroup);
  38123. /* Step 1: Search the hash table for an existing entry. */
  38124. pPage = pCache->apHash[iKey % pCache->nHash];
  38125. while( pPage && pPage->iKey!=iKey ){ pPage = pPage->pNext; }
  38126. /* Step 2: Abort if no existing page is found and createFlag is 0 */
  38127. if( pPage ){
  38128. if( !pPage->isPinned ) pcache1PinPage(pPage);
  38129. }else if( createFlag ){
  38130. /* Steps 3, 4, and 5 implemented by this subroutine */
  38131. pPage = pcache1FetchStage2(pCache, iKey, createFlag);
  38132. }
  38133. assert( pPage==0 || pCache->iMaxKey>=iKey );
  38134. pcache1LeaveMutex(pCache->pGroup);
  38135. return (sqlite3_pcache_page*)pPage;
  38136. }
  38137. /*
  38138. ** Implementation of the sqlite3_pcache.xUnpin method.
  38139. **
  38140. ** Mark a page as unpinned (eligible for asynchronous recycling).
  38141. */
  38142. static void pcache1Unpin(
  38143. sqlite3_pcache *p,
  38144. sqlite3_pcache_page *pPg,
  38145. int reuseUnlikely
  38146. ){
  38147. PCache1 *pCache = (PCache1 *)p;
  38148. PgHdr1 *pPage = (PgHdr1 *)pPg;
  38149. PGroup *pGroup = pCache->pGroup;
  38150. assert( pPage->pCache==pCache );
  38151. pcache1EnterMutex(pGroup);
  38152. /* It is an error to call this function if the page is already
  38153. ** part of the PGroup LRU list.
  38154. */
  38155. assert( pPage->pLruPrev==0 && pPage->pLruNext==0 );
  38156. assert( pGroup->pLruHead!=pPage && pGroup->pLruTail!=pPage );
  38157. assert( pPage->isPinned==1 );
  38158. if( reuseUnlikely || pGroup->nCurrentPage>pGroup->nMaxPage ){
  38159. pcache1RemoveFromHash(pPage);
  38160. pcache1FreePage(pPage);
  38161. }else{
  38162. /* Add the page to the PGroup LRU list. */
  38163. if( pGroup->pLruHead ){
  38164. pGroup->pLruHead->pLruPrev = pPage;
  38165. pPage->pLruNext = pGroup->pLruHead;
  38166. pGroup->pLruHead = pPage;
  38167. }else{
  38168. pGroup->pLruTail = pPage;
  38169. pGroup->pLruHead = pPage;
  38170. }
  38171. pCache->nRecyclable++;
  38172. pPage->isPinned = 0;
  38173. }
  38174. pcache1LeaveMutex(pCache->pGroup);
  38175. }
  38176. /*
  38177. ** Implementation of the sqlite3_pcache.xRekey method.
  38178. */
  38179. static void pcache1Rekey(
  38180. sqlite3_pcache *p,
  38181. sqlite3_pcache_page *pPg,
  38182. unsigned int iOld,
  38183. unsigned int iNew
  38184. ){
  38185. PCache1 *pCache = (PCache1 *)p;
  38186. PgHdr1 *pPage = (PgHdr1 *)pPg;
  38187. PgHdr1 **pp;
  38188. unsigned int h;
  38189. assert( pPage->iKey==iOld );
  38190. assert( pPage->pCache==pCache );
  38191. pcache1EnterMutex(pCache->pGroup);
  38192. h = iOld%pCache->nHash;
  38193. pp = &pCache->apHash[h];
  38194. while( (*pp)!=pPage ){
  38195. pp = &(*pp)->pNext;
  38196. }
  38197. *pp = pPage->pNext;
  38198. h = iNew%pCache->nHash;
  38199. pPage->iKey = iNew;
  38200. pPage->pNext = pCache->apHash[h];
  38201. pCache->apHash[h] = pPage;
  38202. if( iNew>pCache->iMaxKey ){
  38203. pCache->iMaxKey = iNew;
  38204. }
  38205. pcache1LeaveMutex(pCache->pGroup);
  38206. }
  38207. /*
  38208. ** Implementation of the sqlite3_pcache.xTruncate method.
  38209. **
  38210. ** Discard all unpinned pages in the cache with a page number equal to
  38211. ** or greater than parameter iLimit. Any pinned pages with a page number
  38212. ** equal to or greater than iLimit are implicitly unpinned.
  38213. */
  38214. static void pcache1Truncate(sqlite3_pcache *p, unsigned int iLimit){
  38215. PCache1 *pCache = (PCache1 *)p;
  38216. pcache1EnterMutex(pCache->pGroup);
  38217. if( iLimit<=pCache->iMaxKey ){
  38218. pcache1TruncateUnsafe(pCache, iLimit);
  38219. pCache->iMaxKey = iLimit-1;
  38220. }
  38221. pcache1LeaveMutex(pCache->pGroup);
  38222. }
  38223. /*
  38224. ** Implementation of the sqlite3_pcache.xDestroy method.
  38225. **
  38226. ** Destroy a cache allocated using pcache1Create().
  38227. */
  38228. static void pcache1Destroy(sqlite3_pcache *p){
  38229. PCache1 *pCache = (PCache1 *)p;
  38230. PGroup *pGroup = pCache->pGroup;
  38231. assert( pCache->bPurgeable || (pCache->nMax==0 && pCache->nMin==0) );
  38232. pcache1EnterMutex(pGroup);
  38233. pcache1TruncateUnsafe(pCache, 0);
  38234. assert( pGroup->nMaxPage >= pCache->nMax );
  38235. pGroup->nMaxPage -= pCache->nMax;
  38236. assert( pGroup->nMinPage >= pCache->nMin );
  38237. pGroup->nMinPage -= pCache->nMin;
  38238. pGroup->mxPinned = pGroup->nMaxPage + 10 - pGroup->nMinPage;
  38239. pcache1EnforceMaxPage(pGroup);
  38240. pcache1LeaveMutex(pGroup);
  38241. sqlite3_free(pCache->apHash);
  38242. sqlite3_free(pCache);
  38243. }
  38244. /*
  38245. ** This function is called during initialization (sqlite3_initialize()) to
  38246. ** install the default pluggable cache module, assuming the user has not
  38247. ** already provided an alternative.
  38248. */
  38249. SQLITE_PRIVATE void sqlite3PCacheSetDefault(void){
  38250. static const sqlite3_pcache_methods2 defaultMethods = {
  38251. 1, /* iVersion */
  38252. 0, /* pArg */
  38253. pcache1Init, /* xInit */
  38254. pcache1Shutdown, /* xShutdown */
  38255. pcache1Create, /* xCreate */
  38256. pcache1Cachesize, /* xCachesize */
  38257. pcache1Pagecount, /* xPagecount */
  38258. pcache1Fetch, /* xFetch */
  38259. pcache1Unpin, /* xUnpin */
  38260. pcache1Rekey, /* xRekey */
  38261. pcache1Truncate, /* xTruncate */
  38262. pcache1Destroy, /* xDestroy */
  38263. pcache1Shrink /* xShrink */
  38264. };
  38265. sqlite3_config(SQLITE_CONFIG_PCACHE2, &defaultMethods);
  38266. }
  38267. /*
  38268. ** Return the size of the header on each page of this PCACHE implementation.
  38269. */
  38270. SQLITE_PRIVATE int sqlite3HeaderSizePcache1(void){ return ROUND8(sizeof(PgHdr1)); }
  38271. /*
  38272. ** Return the global mutex used by this PCACHE implementation. The
  38273. ** sqlite3_status() routine needs access to this mutex.
  38274. */
  38275. SQLITE_PRIVATE sqlite3_mutex *sqlite3Pcache1Mutex(void){
  38276. return pcache1.mutex;
  38277. }
  38278. #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
  38279. /*
  38280. ** This function is called to free superfluous dynamically allocated memory
  38281. ** held by the pager system. Memory in use by any SQLite pager allocated
  38282. ** by the current thread may be sqlite3_free()ed.
  38283. **
  38284. ** nReq is the number of bytes of memory required. Once this much has
  38285. ** been released, the function returns. The return value is the total number
  38286. ** of bytes of memory released.
  38287. */
  38288. SQLITE_PRIVATE int sqlite3PcacheReleaseMemory(int nReq){
  38289. int nFree = 0;
  38290. assert( sqlite3_mutex_notheld(pcache1.grp.mutex) );
  38291. assert( sqlite3_mutex_notheld(pcache1.mutex) );
  38292. if( pcache1.pStart==0 ){
  38293. PgHdr1 *p;
  38294. pcache1EnterMutex(&pcache1.grp);
  38295. while( (nReq<0 || nFree<nReq) && ((p=pcache1.grp.pLruTail)!=0) ){
  38296. nFree += pcache1MemSize(p->page.pBuf);
  38297. #ifdef SQLITE_PCACHE_SEPARATE_HEADER
  38298. nFree += sqlite3MemSize(p);
  38299. #endif
  38300. assert( p->isPinned==0 );
  38301. pcache1PinPage(p);
  38302. pcache1RemoveFromHash(p);
  38303. pcache1FreePage(p);
  38304. }
  38305. pcache1LeaveMutex(&pcache1.grp);
  38306. }
  38307. return nFree;
  38308. }
  38309. #endif /* SQLITE_ENABLE_MEMORY_MANAGEMENT */
  38310. #ifdef SQLITE_TEST
  38311. /*
  38312. ** This function is used by test procedures to inspect the internal state
  38313. ** of the global cache.
  38314. */
  38315. SQLITE_PRIVATE void sqlite3PcacheStats(
  38316. int *pnCurrent, /* OUT: Total number of pages cached */
  38317. int *pnMax, /* OUT: Global maximum cache size */
  38318. int *pnMin, /* OUT: Sum of PCache1.nMin for purgeable caches */
  38319. int *pnRecyclable /* OUT: Total number of pages available for recycling */
  38320. ){
  38321. PgHdr1 *p;
  38322. int nRecyclable = 0;
  38323. for(p=pcache1.grp.pLruHead; p; p=p->pLruNext){
  38324. assert( p->isPinned==0 );
  38325. nRecyclable++;
  38326. }
  38327. *pnCurrent = pcache1.grp.nCurrentPage;
  38328. *pnMax = (int)pcache1.grp.nMaxPage;
  38329. *pnMin = (int)pcache1.grp.nMinPage;
  38330. *pnRecyclable = nRecyclable;
  38331. }
  38332. #endif
  38333. /************** End of pcache1.c *********************************************/
  38334. /************** Begin file rowset.c ******************************************/
  38335. /*
  38336. ** 2008 December 3
  38337. **
  38338. ** The author disclaims copyright to this source code. In place of
  38339. ** a legal notice, here is a blessing:
  38340. **
  38341. ** May you do good and not evil.
  38342. ** May you find forgiveness for yourself and forgive others.
  38343. ** May you share freely, never taking more than you give.
  38344. **
  38345. *************************************************************************
  38346. **
  38347. ** This module implements an object we call a "RowSet".
  38348. **
  38349. ** The RowSet object is a collection of rowids. Rowids
  38350. ** are inserted into the RowSet in an arbitrary order. Inserts
  38351. ** can be intermixed with tests to see if a given rowid has been
  38352. ** previously inserted into the RowSet.
  38353. **
  38354. ** After all inserts are finished, it is possible to extract the
  38355. ** elements of the RowSet in sorted order. Once this extraction
  38356. ** process has started, no new elements may be inserted.
  38357. **
  38358. ** Hence, the primitive operations for a RowSet are:
  38359. **
  38360. ** CREATE
  38361. ** INSERT
  38362. ** TEST
  38363. ** SMALLEST
  38364. ** DESTROY
  38365. **
  38366. ** The CREATE and DESTROY primitives are the constructor and destructor,
  38367. ** obviously. The INSERT primitive adds a new element to the RowSet.
  38368. ** TEST checks to see if an element is already in the RowSet. SMALLEST
  38369. ** extracts the least value from the RowSet.
  38370. **
  38371. ** The INSERT primitive might allocate additional memory. Memory is
  38372. ** allocated in chunks so most INSERTs do no allocation. There is an
  38373. ** upper bound on the size of allocated memory. No memory is freed
  38374. ** until DESTROY.
  38375. **
  38376. ** The TEST primitive includes a "batch" number. The TEST primitive
  38377. ** will only see elements that were inserted before the last change
  38378. ** in the batch number. In other words, if an INSERT occurs between
  38379. ** two TESTs where the TESTs have the same batch nubmer, then the
  38380. ** value added by the INSERT will not be visible to the second TEST.
  38381. ** The initial batch number is zero, so if the very first TEST contains
  38382. ** a non-zero batch number, it will see all prior INSERTs.
  38383. **
  38384. ** No INSERTs may occurs after a SMALLEST. An assertion will fail if
  38385. ** that is attempted.
  38386. **
  38387. ** The cost of an INSERT is roughly constant. (Sometimes new memory
  38388. ** has to be allocated on an INSERT.) The cost of a TEST with a new
  38389. ** batch number is O(NlogN) where N is the number of elements in the RowSet.
  38390. ** The cost of a TEST using the same batch number is O(logN). The cost
  38391. ** of the first SMALLEST is O(NlogN). Second and subsequent SMALLEST
  38392. ** primitives are constant time. The cost of DESTROY is O(N).
  38393. **
  38394. ** There is an added cost of O(N) when switching between TEST and
  38395. ** SMALLEST primitives.
  38396. */
  38397. /*
  38398. ** Target size for allocation chunks.
  38399. */
  38400. #define ROWSET_ALLOCATION_SIZE 1024
  38401. /*
  38402. ** The number of rowset entries per allocation chunk.
  38403. */
  38404. #define ROWSET_ENTRY_PER_CHUNK \
  38405. ((ROWSET_ALLOCATION_SIZE-8)/sizeof(struct RowSetEntry))
  38406. /*
  38407. ** Each entry in a RowSet is an instance of the following object.
  38408. **
  38409. ** This same object is reused to store a linked list of trees of RowSetEntry
  38410. ** objects. In that alternative use, pRight points to the next entry
  38411. ** in the list, pLeft points to the tree, and v is unused. The
  38412. ** RowSet.pForest value points to the head of this forest list.
  38413. */
  38414. struct RowSetEntry {
  38415. i64 v; /* ROWID value for this entry */
  38416. struct RowSetEntry *pRight; /* Right subtree (larger entries) or list */
  38417. struct RowSetEntry *pLeft; /* Left subtree (smaller entries) */
  38418. };
  38419. /*
  38420. ** RowSetEntry objects are allocated in large chunks (instances of the
  38421. ** following structure) to reduce memory allocation overhead. The
  38422. ** chunks are kept on a linked list so that they can be deallocated
  38423. ** when the RowSet is destroyed.
  38424. */
  38425. struct RowSetChunk {
  38426. struct RowSetChunk *pNextChunk; /* Next chunk on list of them all */
  38427. struct RowSetEntry aEntry[ROWSET_ENTRY_PER_CHUNK]; /* Allocated entries */
  38428. };
  38429. /*
  38430. ** A RowSet in an instance of the following structure.
  38431. **
  38432. ** A typedef of this structure if found in sqliteInt.h.
  38433. */
  38434. struct RowSet {
  38435. struct RowSetChunk *pChunk; /* List of all chunk allocations */
  38436. sqlite3 *db; /* The database connection */
  38437. struct RowSetEntry *pEntry; /* List of entries using pRight */
  38438. struct RowSetEntry *pLast; /* Last entry on the pEntry list */
  38439. struct RowSetEntry *pFresh; /* Source of new entry objects */
  38440. struct RowSetEntry *pForest; /* List of binary trees of entries */
  38441. u16 nFresh; /* Number of objects on pFresh */
  38442. u16 rsFlags; /* Various flags */
  38443. int iBatch; /* Current insert batch */
  38444. };
  38445. /*
  38446. ** Allowed values for RowSet.rsFlags
  38447. */
  38448. #define ROWSET_SORTED 0x01 /* True if RowSet.pEntry is sorted */
  38449. #define ROWSET_NEXT 0x02 /* True if sqlite3RowSetNext() has been called */
  38450. /*
  38451. ** Turn bulk memory into a RowSet object. N bytes of memory
  38452. ** are available at pSpace. The db pointer is used as a memory context
  38453. ** for any subsequent allocations that need to occur.
  38454. ** Return a pointer to the new RowSet object.
  38455. **
  38456. ** It must be the case that N is sufficient to make a Rowset. If not
  38457. ** an assertion fault occurs.
  38458. **
  38459. ** If N is larger than the minimum, use the surplus as an initial
  38460. ** allocation of entries available to be filled.
  38461. */
  38462. SQLITE_PRIVATE RowSet *sqlite3RowSetInit(sqlite3 *db, void *pSpace, unsigned int N){
  38463. RowSet *p;
  38464. assert( N >= ROUND8(sizeof(*p)) );
  38465. p = pSpace;
  38466. p->pChunk = 0;
  38467. p->db = db;
  38468. p->pEntry = 0;
  38469. p->pLast = 0;
  38470. p->pForest = 0;
  38471. p->pFresh = (struct RowSetEntry*)(ROUND8(sizeof(*p)) + (char*)p);
  38472. p->nFresh = (u16)((N - ROUND8(sizeof(*p)))/sizeof(struct RowSetEntry));
  38473. p->rsFlags = ROWSET_SORTED;
  38474. p->iBatch = 0;
  38475. return p;
  38476. }
  38477. /*
  38478. ** Deallocate all chunks from a RowSet. This frees all memory that
  38479. ** the RowSet has allocated over its lifetime. This routine is
  38480. ** the destructor for the RowSet.
  38481. */
  38482. SQLITE_PRIVATE void sqlite3RowSetClear(RowSet *p){
  38483. struct RowSetChunk *pChunk, *pNextChunk;
  38484. for(pChunk=p->pChunk; pChunk; pChunk = pNextChunk){
  38485. pNextChunk = pChunk->pNextChunk;
  38486. sqlite3DbFree(p->db, pChunk);
  38487. }
  38488. p->pChunk = 0;
  38489. p->nFresh = 0;
  38490. p->pEntry = 0;
  38491. p->pLast = 0;
  38492. p->pForest = 0;
  38493. p->rsFlags = ROWSET_SORTED;
  38494. }
  38495. /*
  38496. ** Allocate a new RowSetEntry object that is associated with the
  38497. ** given RowSet. Return a pointer to the new and completely uninitialized
  38498. ** objected.
  38499. **
  38500. ** In an OOM situation, the RowSet.db->mallocFailed flag is set and this
  38501. ** routine returns NULL.
  38502. */
  38503. static struct RowSetEntry *rowSetEntryAlloc(RowSet *p){
  38504. assert( p!=0 );
  38505. if( p->nFresh==0 ){
  38506. struct RowSetChunk *pNew;
  38507. pNew = sqlite3DbMallocRaw(p->db, sizeof(*pNew));
  38508. if( pNew==0 ){
  38509. return 0;
  38510. }
  38511. pNew->pNextChunk = p->pChunk;
  38512. p->pChunk = pNew;
  38513. p->pFresh = pNew->aEntry;
  38514. p->nFresh = ROWSET_ENTRY_PER_CHUNK;
  38515. }
  38516. p->nFresh--;
  38517. return p->pFresh++;
  38518. }
  38519. /*
  38520. ** Insert a new value into a RowSet.
  38521. **
  38522. ** The mallocFailed flag of the database connection is set if a
  38523. ** memory allocation fails.
  38524. */
  38525. SQLITE_PRIVATE void sqlite3RowSetInsert(RowSet *p, i64 rowid){
  38526. struct RowSetEntry *pEntry; /* The new entry */
  38527. struct RowSetEntry *pLast; /* The last prior entry */
  38528. /* This routine is never called after sqlite3RowSetNext() */
  38529. assert( p!=0 && (p->rsFlags & ROWSET_NEXT)==0 );
  38530. pEntry = rowSetEntryAlloc(p);
  38531. if( pEntry==0 ) return;
  38532. pEntry->v = rowid;
  38533. pEntry->pRight = 0;
  38534. pLast = p->pLast;
  38535. if( pLast ){
  38536. if( (p->rsFlags & ROWSET_SORTED)!=0 && rowid<=pLast->v ){
  38537. p->rsFlags &= ~ROWSET_SORTED;
  38538. }
  38539. pLast->pRight = pEntry;
  38540. }else{
  38541. p->pEntry = pEntry;
  38542. }
  38543. p->pLast = pEntry;
  38544. }
  38545. /*
  38546. ** Merge two lists of RowSetEntry objects. Remove duplicates.
  38547. **
  38548. ** The input lists are connected via pRight pointers and are
  38549. ** assumed to each already be in sorted order.
  38550. */
  38551. static struct RowSetEntry *rowSetEntryMerge(
  38552. struct RowSetEntry *pA, /* First sorted list to be merged */
  38553. struct RowSetEntry *pB /* Second sorted list to be merged */
  38554. ){
  38555. struct RowSetEntry head;
  38556. struct RowSetEntry *pTail;
  38557. pTail = &head;
  38558. while( pA && pB ){
  38559. assert( pA->pRight==0 || pA->v<=pA->pRight->v );
  38560. assert( pB->pRight==0 || pB->v<=pB->pRight->v );
  38561. if( pA->v<pB->v ){
  38562. pTail->pRight = pA;
  38563. pA = pA->pRight;
  38564. pTail = pTail->pRight;
  38565. }else if( pB->v<pA->v ){
  38566. pTail->pRight = pB;
  38567. pB = pB->pRight;
  38568. pTail = pTail->pRight;
  38569. }else{
  38570. pA = pA->pRight;
  38571. }
  38572. }
  38573. if( pA ){
  38574. assert( pA->pRight==0 || pA->v<=pA->pRight->v );
  38575. pTail->pRight = pA;
  38576. }else{
  38577. assert( pB==0 || pB->pRight==0 || pB->v<=pB->pRight->v );
  38578. pTail->pRight = pB;
  38579. }
  38580. return head.pRight;
  38581. }
  38582. /*
  38583. ** Sort all elements on the list of RowSetEntry objects into order of
  38584. ** increasing v.
  38585. */
  38586. static struct RowSetEntry *rowSetEntrySort(struct RowSetEntry *pIn){
  38587. unsigned int i;
  38588. struct RowSetEntry *pNext, *aBucket[40];
  38589. memset(aBucket, 0, sizeof(aBucket));
  38590. while( pIn ){
  38591. pNext = pIn->pRight;
  38592. pIn->pRight = 0;
  38593. for(i=0; aBucket[i]; i++){
  38594. pIn = rowSetEntryMerge(aBucket[i], pIn);
  38595. aBucket[i] = 0;
  38596. }
  38597. aBucket[i] = pIn;
  38598. pIn = pNext;
  38599. }
  38600. pIn = 0;
  38601. for(i=0; i<sizeof(aBucket)/sizeof(aBucket[0]); i++){
  38602. pIn = rowSetEntryMerge(pIn, aBucket[i]);
  38603. }
  38604. return pIn;
  38605. }
  38606. /*
  38607. ** The input, pIn, is a binary tree (or subtree) of RowSetEntry objects.
  38608. ** Convert this tree into a linked list connected by the pRight pointers
  38609. ** and return pointers to the first and last elements of the new list.
  38610. */
  38611. static void rowSetTreeToList(
  38612. struct RowSetEntry *pIn, /* Root of the input tree */
  38613. struct RowSetEntry **ppFirst, /* Write head of the output list here */
  38614. struct RowSetEntry **ppLast /* Write tail of the output list here */
  38615. ){
  38616. assert( pIn!=0 );
  38617. if( pIn->pLeft ){
  38618. struct RowSetEntry *p;
  38619. rowSetTreeToList(pIn->pLeft, ppFirst, &p);
  38620. p->pRight = pIn;
  38621. }else{
  38622. *ppFirst = pIn;
  38623. }
  38624. if( pIn->pRight ){
  38625. rowSetTreeToList(pIn->pRight, &pIn->pRight, ppLast);
  38626. }else{
  38627. *ppLast = pIn;
  38628. }
  38629. assert( (*ppLast)->pRight==0 );
  38630. }
  38631. /*
  38632. ** Convert a sorted list of elements (connected by pRight) into a binary
  38633. ** tree with depth of iDepth. A depth of 1 means the tree contains a single
  38634. ** node taken from the head of *ppList. A depth of 2 means a tree with
  38635. ** three nodes. And so forth.
  38636. **
  38637. ** Use as many entries from the input list as required and update the
  38638. ** *ppList to point to the unused elements of the list. If the input
  38639. ** list contains too few elements, then construct an incomplete tree
  38640. ** and leave *ppList set to NULL.
  38641. **
  38642. ** Return a pointer to the root of the constructed binary tree.
  38643. */
  38644. static struct RowSetEntry *rowSetNDeepTree(
  38645. struct RowSetEntry **ppList,
  38646. int iDepth
  38647. ){
  38648. struct RowSetEntry *p; /* Root of the new tree */
  38649. struct RowSetEntry *pLeft; /* Left subtree */
  38650. if( *ppList==0 ){
  38651. return 0;
  38652. }
  38653. if( iDepth==1 ){
  38654. p = *ppList;
  38655. *ppList = p->pRight;
  38656. p->pLeft = p->pRight = 0;
  38657. return p;
  38658. }
  38659. pLeft = rowSetNDeepTree(ppList, iDepth-1);
  38660. p = *ppList;
  38661. if( p==0 ){
  38662. return pLeft;
  38663. }
  38664. p->pLeft = pLeft;
  38665. *ppList = p->pRight;
  38666. p->pRight = rowSetNDeepTree(ppList, iDepth-1);
  38667. return p;
  38668. }
  38669. /*
  38670. ** Convert a sorted list of elements into a binary tree. Make the tree
  38671. ** as deep as it needs to be in order to contain the entire list.
  38672. */
  38673. static struct RowSetEntry *rowSetListToTree(struct RowSetEntry *pList){
  38674. int iDepth; /* Depth of the tree so far */
  38675. struct RowSetEntry *p; /* Current tree root */
  38676. struct RowSetEntry *pLeft; /* Left subtree */
  38677. assert( pList!=0 );
  38678. p = pList;
  38679. pList = p->pRight;
  38680. p->pLeft = p->pRight = 0;
  38681. for(iDepth=1; pList; iDepth++){
  38682. pLeft = p;
  38683. p = pList;
  38684. pList = p->pRight;
  38685. p->pLeft = pLeft;
  38686. p->pRight = rowSetNDeepTree(&pList, iDepth);
  38687. }
  38688. return p;
  38689. }
  38690. /*
  38691. ** Take all the entries on p->pEntry and on the trees in p->pForest and
  38692. ** sort them all together into one big ordered list on p->pEntry.
  38693. **
  38694. ** This routine should only be called once in the life of a RowSet.
  38695. */
  38696. static void rowSetToList(RowSet *p){
  38697. /* This routine is called only once */
  38698. assert( p!=0 && (p->rsFlags & ROWSET_NEXT)==0 );
  38699. if( (p->rsFlags & ROWSET_SORTED)==0 ){
  38700. p->pEntry = rowSetEntrySort(p->pEntry);
  38701. }
  38702. /* While this module could theoretically support it, sqlite3RowSetNext()
  38703. ** is never called after sqlite3RowSetText() for the same RowSet. So
  38704. ** there is never a forest to deal with. Should this change, simply
  38705. ** remove the assert() and the #if 0. */
  38706. assert( p->pForest==0 );
  38707. #if 0
  38708. while( p->pForest ){
  38709. struct RowSetEntry *pTree = p->pForest->pLeft;
  38710. if( pTree ){
  38711. struct RowSetEntry *pHead, *pTail;
  38712. rowSetTreeToList(pTree, &pHead, &pTail);
  38713. p->pEntry = rowSetEntryMerge(p->pEntry, pHead);
  38714. }
  38715. p->pForest = p->pForest->pRight;
  38716. }
  38717. #endif
  38718. p->rsFlags |= ROWSET_NEXT; /* Verify this routine is never called again */
  38719. }
  38720. /*
  38721. ** Extract the smallest element from the RowSet.
  38722. ** Write the element into *pRowid. Return 1 on success. Return
  38723. ** 0 if the RowSet is already empty.
  38724. **
  38725. ** After this routine has been called, the sqlite3RowSetInsert()
  38726. ** routine may not be called again.
  38727. */
  38728. SQLITE_PRIVATE int sqlite3RowSetNext(RowSet *p, i64 *pRowid){
  38729. assert( p!=0 );
  38730. /* Merge the forest into a single sorted list on first call */
  38731. if( (p->rsFlags & ROWSET_NEXT)==0 ) rowSetToList(p);
  38732. /* Return the next entry on the list */
  38733. if( p->pEntry ){
  38734. *pRowid = p->pEntry->v;
  38735. p->pEntry = p->pEntry->pRight;
  38736. if( p->pEntry==0 ){
  38737. sqlite3RowSetClear(p);
  38738. }
  38739. return 1;
  38740. }else{
  38741. return 0;
  38742. }
  38743. }
  38744. /*
  38745. ** Check to see if element iRowid was inserted into the rowset as
  38746. ** part of any insert batch prior to iBatch. Return 1 or 0.
  38747. **
  38748. ** If this is the first test of a new batch and if there exist entries
  38749. ** on pRowSet->pEntry, then sort those entries into the forest at
  38750. ** pRowSet->pForest so that they can be tested.
  38751. */
  38752. SQLITE_PRIVATE int sqlite3RowSetTest(RowSet *pRowSet, int iBatch, sqlite3_int64 iRowid){
  38753. struct RowSetEntry *p, *pTree;
  38754. /* This routine is never called after sqlite3RowSetNext() */
  38755. assert( pRowSet!=0 && (pRowSet->rsFlags & ROWSET_NEXT)==0 );
  38756. /* Sort entries into the forest on the first test of a new batch
  38757. */
  38758. if( iBatch!=pRowSet->iBatch ){
  38759. p = pRowSet->pEntry;
  38760. if( p ){
  38761. struct RowSetEntry **ppPrevTree = &pRowSet->pForest;
  38762. if( (pRowSet->rsFlags & ROWSET_SORTED)==0 ){
  38763. p = rowSetEntrySort(p);
  38764. }
  38765. for(pTree = pRowSet->pForest; pTree; pTree=pTree->pRight){
  38766. ppPrevTree = &pTree->pRight;
  38767. if( pTree->pLeft==0 ){
  38768. pTree->pLeft = rowSetListToTree(p);
  38769. break;
  38770. }else{
  38771. struct RowSetEntry *pAux, *pTail;
  38772. rowSetTreeToList(pTree->pLeft, &pAux, &pTail);
  38773. pTree->pLeft = 0;
  38774. p = rowSetEntryMerge(pAux, p);
  38775. }
  38776. }
  38777. if( pTree==0 ){
  38778. *ppPrevTree = pTree = rowSetEntryAlloc(pRowSet);
  38779. if( pTree ){
  38780. pTree->v = 0;
  38781. pTree->pRight = 0;
  38782. pTree->pLeft = rowSetListToTree(p);
  38783. }
  38784. }
  38785. pRowSet->pEntry = 0;
  38786. pRowSet->pLast = 0;
  38787. pRowSet->rsFlags |= ROWSET_SORTED;
  38788. }
  38789. pRowSet->iBatch = iBatch;
  38790. }
  38791. /* Test to see if the iRowid value appears anywhere in the forest.
  38792. ** Return 1 if it does and 0 if not.
  38793. */
  38794. for(pTree = pRowSet->pForest; pTree; pTree=pTree->pRight){
  38795. p = pTree->pLeft;
  38796. while( p ){
  38797. if( p->v<iRowid ){
  38798. p = p->pRight;
  38799. }else if( p->v>iRowid ){
  38800. p = p->pLeft;
  38801. }else{
  38802. return 1;
  38803. }
  38804. }
  38805. }
  38806. return 0;
  38807. }
  38808. /************** End of rowset.c **********************************************/
  38809. /************** Begin file pager.c *******************************************/
  38810. /*
  38811. ** 2001 September 15
  38812. **
  38813. ** The author disclaims copyright to this source code. In place of
  38814. ** a legal notice, here is a blessing:
  38815. **
  38816. ** May you do good and not evil.
  38817. ** May you find forgiveness for yourself and forgive others.
  38818. ** May you share freely, never taking more than you give.
  38819. **
  38820. *************************************************************************
  38821. ** This is the implementation of the page cache subsystem or "pager".
  38822. **
  38823. ** The pager is used to access a database disk file. It implements
  38824. ** atomic commit and rollback through the use of a journal file that
  38825. ** is separate from the database file. The pager also implements file
  38826. ** locking to prevent two processes from writing the same database
  38827. ** file simultaneously, or one process from reading the database while
  38828. ** another is writing.
  38829. */
  38830. #ifndef SQLITE_OMIT_DISKIO
  38831. /************** Include wal.h in the middle of pager.c ***********************/
  38832. /************** Begin file wal.h *********************************************/
  38833. /*
  38834. ** 2010 February 1
  38835. **
  38836. ** The author disclaims copyright to this source code. In place of
  38837. ** a legal notice, here is a blessing:
  38838. **
  38839. ** May you do good and not evil.
  38840. ** May you find forgiveness for yourself and forgive others.
  38841. ** May you share freely, never taking more than you give.
  38842. **
  38843. *************************************************************************
  38844. ** This header file defines the interface to the write-ahead logging
  38845. ** system. Refer to the comments below and the header comment attached to
  38846. ** the implementation of each function in log.c for further details.
  38847. */
  38848. #ifndef _WAL_H_
  38849. #define _WAL_H_
  38850. /* Additional values that can be added to the sync_flags argument of
  38851. ** sqlite3WalFrames():
  38852. */
  38853. #define WAL_SYNC_TRANSACTIONS 0x20 /* Sync at the end of each transaction */
  38854. #define SQLITE_SYNC_MASK 0x13 /* Mask off the SQLITE_SYNC_* values */
  38855. #ifdef SQLITE_OMIT_WAL
  38856. # define sqlite3WalOpen(x,y,z) 0
  38857. # define sqlite3WalLimit(x,y)
  38858. # define sqlite3WalClose(w,x,y,z) 0
  38859. # define sqlite3WalBeginReadTransaction(y,z) 0
  38860. # define sqlite3WalEndReadTransaction(z)
  38861. # define sqlite3WalDbsize(y) 0
  38862. # define sqlite3WalBeginWriteTransaction(y) 0
  38863. # define sqlite3WalEndWriteTransaction(x) 0
  38864. # define sqlite3WalUndo(x,y,z) 0
  38865. # define sqlite3WalSavepoint(y,z)
  38866. # define sqlite3WalSavepointUndo(y,z) 0
  38867. # define sqlite3WalFrames(u,v,w,x,y,z) 0
  38868. # define sqlite3WalCheckpoint(r,s,t,u,v,w,x,y,z) 0
  38869. # define sqlite3WalCallback(z) 0
  38870. # define sqlite3WalExclusiveMode(y,z) 0
  38871. # define sqlite3WalHeapMemory(z) 0
  38872. # define sqlite3WalFramesize(z) 0
  38873. # define sqlite3WalFindFrame(x,y,z) 0
  38874. #else
  38875. #define WAL_SAVEPOINT_NDATA 4
  38876. /* Connection to a write-ahead log (WAL) file.
  38877. ** There is one object of this type for each pager.
  38878. */
  38879. typedef struct Wal Wal;
  38880. /* Open and close a connection to a write-ahead log. */
  38881. SQLITE_PRIVATE int sqlite3WalOpen(sqlite3_vfs*, sqlite3_file*, const char *, int, i64, Wal**);
  38882. SQLITE_PRIVATE int sqlite3WalClose(Wal *pWal, int sync_flags, int, u8 *);
  38883. /* Set the limiting size of a WAL file. */
  38884. SQLITE_PRIVATE void sqlite3WalLimit(Wal*, i64);
  38885. /* Used by readers to open (lock) and close (unlock) a snapshot. A
  38886. ** snapshot is like a read-transaction. It is the state of the database
  38887. ** at an instant in time. sqlite3WalOpenSnapshot gets a read lock and
  38888. ** preserves the current state even if the other threads or processes
  38889. ** write to or checkpoint the WAL. sqlite3WalCloseSnapshot() closes the
  38890. ** transaction and releases the lock.
  38891. */
  38892. SQLITE_PRIVATE int sqlite3WalBeginReadTransaction(Wal *pWal, int *);
  38893. SQLITE_PRIVATE void sqlite3WalEndReadTransaction(Wal *pWal);
  38894. /* Read a page from the write-ahead log, if it is present. */
  38895. SQLITE_PRIVATE int sqlite3WalFindFrame(Wal *, Pgno, u32 *);
  38896. SQLITE_PRIVATE int sqlite3WalReadFrame(Wal *, u32, int, u8 *);
  38897. /* If the WAL is not empty, return the size of the database. */
  38898. SQLITE_PRIVATE Pgno sqlite3WalDbsize(Wal *pWal);
  38899. /* Obtain or release the WRITER lock. */
  38900. SQLITE_PRIVATE int sqlite3WalBeginWriteTransaction(Wal *pWal);
  38901. SQLITE_PRIVATE int sqlite3WalEndWriteTransaction(Wal *pWal);
  38902. /* Undo any frames written (but not committed) to the log */
  38903. SQLITE_PRIVATE int sqlite3WalUndo(Wal *pWal, int (*xUndo)(void *, Pgno), void *pUndoCtx);
  38904. /* Return an integer that records the current (uncommitted) write
  38905. ** position in the WAL */
  38906. SQLITE_PRIVATE void sqlite3WalSavepoint(Wal *pWal, u32 *aWalData);
  38907. /* Move the write position of the WAL back to iFrame. Called in
  38908. ** response to a ROLLBACK TO command. */
  38909. SQLITE_PRIVATE int sqlite3WalSavepointUndo(Wal *pWal, u32 *aWalData);
  38910. /* Write a frame or frames to the log. */
  38911. SQLITE_PRIVATE int sqlite3WalFrames(Wal *pWal, int, PgHdr *, Pgno, int, int);
  38912. /* Copy pages from the log to the database file */
  38913. SQLITE_PRIVATE int sqlite3WalCheckpoint(
  38914. Wal *pWal, /* Write-ahead log connection */
  38915. int eMode, /* One of PASSIVE, FULL and RESTART */
  38916. int (*xBusy)(void*), /* Function to call when busy */
  38917. void *pBusyArg, /* Context argument for xBusyHandler */
  38918. int sync_flags, /* Flags to sync db file with (or 0) */
  38919. int nBuf, /* Size of buffer nBuf */
  38920. u8 *zBuf, /* Temporary buffer to use */
  38921. int *pnLog, /* OUT: Number of frames in WAL */
  38922. int *pnCkpt /* OUT: Number of backfilled frames in WAL */
  38923. );
  38924. /* Return the value to pass to a sqlite3_wal_hook callback, the
  38925. ** number of frames in the WAL at the point of the last commit since
  38926. ** sqlite3WalCallback() was called. If no commits have occurred since
  38927. ** the last call, then return 0.
  38928. */
  38929. SQLITE_PRIVATE int sqlite3WalCallback(Wal *pWal);
  38930. /* Tell the wal layer that an EXCLUSIVE lock has been obtained (or released)
  38931. ** by the pager layer on the database file.
  38932. */
  38933. SQLITE_PRIVATE int sqlite3WalExclusiveMode(Wal *pWal, int op);
  38934. /* Return true if the argument is non-NULL and the WAL module is using
  38935. ** heap-memory for the wal-index. Otherwise, if the argument is NULL or the
  38936. ** WAL module is using shared-memory, return false.
  38937. */
  38938. SQLITE_PRIVATE int sqlite3WalHeapMemory(Wal *pWal);
  38939. #ifdef SQLITE_ENABLE_ZIPVFS
  38940. /* If the WAL file is not empty, return the number of bytes of content
  38941. ** stored in each frame (i.e. the db page-size when the WAL was created).
  38942. */
  38943. SQLITE_PRIVATE int sqlite3WalFramesize(Wal *pWal);
  38944. #endif
  38945. #endif /* ifndef SQLITE_OMIT_WAL */
  38946. #endif /* _WAL_H_ */
  38947. /************** End of wal.h *************************************************/
  38948. /************** Continuing where we left off in pager.c **********************/
  38949. /******************* NOTES ON THE DESIGN OF THE PAGER ************************
  38950. **
  38951. ** This comment block describes invariants that hold when using a rollback
  38952. ** journal. These invariants do not apply for journal_mode=WAL,
  38953. ** journal_mode=MEMORY, or journal_mode=OFF.
  38954. **
  38955. ** Within this comment block, a page is deemed to have been synced
  38956. ** automatically as soon as it is written when PRAGMA synchronous=OFF.
  38957. ** Otherwise, the page is not synced until the xSync method of the VFS
  38958. ** is called successfully on the file containing the page.
  38959. **
  38960. ** Definition: A page of the database file is said to be "overwriteable" if
  38961. ** one or more of the following are true about the page:
  38962. **
  38963. ** (a) The original content of the page as it was at the beginning of
  38964. ** the transaction has been written into the rollback journal and
  38965. ** synced.
  38966. **
  38967. ** (b) The page was a freelist leaf page at the start of the transaction.
  38968. **
  38969. ** (c) The page number is greater than the largest page that existed in
  38970. ** the database file at the start of the transaction.
  38971. **
  38972. ** (1) A page of the database file is never overwritten unless one of the
  38973. ** following are true:
  38974. **
  38975. ** (a) The page and all other pages on the same sector are overwriteable.
  38976. **
  38977. ** (b) The atomic page write optimization is enabled, and the entire
  38978. ** transaction other than the update of the transaction sequence
  38979. ** number consists of a single page change.
  38980. **
  38981. ** (2) The content of a page written into the rollback journal exactly matches
  38982. ** both the content in the database when the rollback journal was written
  38983. ** and the content in the database at the beginning of the current
  38984. ** transaction.
  38985. **
  38986. ** (3) Writes to the database file are an integer multiple of the page size
  38987. ** in length and are aligned on a page boundary.
  38988. **
  38989. ** (4) Reads from the database file are either aligned on a page boundary and
  38990. ** an integer multiple of the page size in length or are taken from the
  38991. ** first 100 bytes of the database file.
  38992. **
  38993. ** (5) All writes to the database file are synced prior to the rollback journal
  38994. ** being deleted, truncated, or zeroed.
  38995. **
  38996. ** (6) If a master journal file is used, then all writes to the database file
  38997. ** are synced prior to the master journal being deleted.
  38998. **
  38999. ** Definition: Two databases (or the same database at two points it time)
  39000. ** are said to be "logically equivalent" if they give the same answer to
  39001. ** all queries. Note in particular the content of freelist leaf
  39002. ** pages can be changed arbitrarily without affecting the logical equivalence
  39003. ** of the database.
  39004. **
  39005. ** (7) At any time, if any subset, including the empty set and the total set,
  39006. ** of the unsynced changes to a rollback journal are removed and the
  39007. ** journal is rolled back, the resulting database file will be logically
  39008. ** equivalent to the database file at the beginning of the transaction.
  39009. **
  39010. ** (8) When a transaction is rolled back, the xTruncate method of the VFS
  39011. ** is called to restore the database file to the same size it was at
  39012. ** the beginning of the transaction. (In some VFSes, the xTruncate
  39013. ** method is a no-op, but that does not change the fact the SQLite will
  39014. ** invoke it.)
  39015. **
  39016. ** (9) Whenever the database file is modified, at least one bit in the range
  39017. ** of bytes from 24 through 39 inclusive will be changed prior to releasing
  39018. ** the EXCLUSIVE lock, thus signaling other connections on the same
  39019. ** database to flush their caches.
  39020. **
  39021. ** (10) The pattern of bits in bytes 24 through 39 shall not repeat in less
  39022. ** than one billion transactions.
  39023. **
  39024. ** (11) A database file is well-formed at the beginning and at the conclusion
  39025. ** of every transaction.
  39026. **
  39027. ** (12) An EXCLUSIVE lock is held on the database file when writing to
  39028. ** the database file.
  39029. **
  39030. ** (13) A SHARED lock is held on the database file while reading any
  39031. ** content out of the database file.
  39032. **
  39033. ******************************************************************************/
  39034. /*
  39035. ** Macros for troubleshooting. Normally turned off
  39036. */
  39037. #if 0
  39038. int sqlite3PagerTrace=1; /* True to enable tracing */
  39039. #define sqlite3DebugPrintf printf
  39040. #define PAGERTRACE(X) if( sqlite3PagerTrace ){ sqlite3DebugPrintf X; }
  39041. #else
  39042. #define PAGERTRACE(X)
  39043. #endif
  39044. /*
  39045. ** The following two macros are used within the PAGERTRACE() macros above
  39046. ** to print out file-descriptors.
  39047. **
  39048. ** PAGERID() takes a pointer to a Pager struct as its argument. The
  39049. ** associated file-descriptor is returned. FILEHANDLEID() takes an sqlite3_file
  39050. ** struct as its argument.
  39051. */
  39052. #define PAGERID(p) ((int)(p->fd))
  39053. #define FILEHANDLEID(fd) ((int)fd)
  39054. /*
  39055. ** The Pager.eState variable stores the current 'state' of a pager. A
  39056. ** pager may be in any one of the seven states shown in the following
  39057. ** state diagram.
  39058. **
  39059. ** OPEN <------+------+
  39060. ** | | |
  39061. ** V | |
  39062. ** +---------> READER-------+ |
  39063. ** | | |
  39064. ** | V |
  39065. ** |<-------WRITER_LOCKED------> ERROR
  39066. ** | | ^
  39067. ** | V |
  39068. ** |<------WRITER_CACHEMOD-------->|
  39069. ** | | |
  39070. ** | V |
  39071. ** |<-------WRITER_DBMOD---------->|
  39072. ** | | |
  39073. ** | V |
  39074. ** +<------WRITER_FINISHED-------->+
  39075. **
  39076. **
  39077. ** List of state transitions and the C [function] that performs each:
  39078. **
  39079. ** OPEN -> READER [sqlite3PagerSharedLock]
  39080. ** READER -> OPEN [pager_unlock]
  39081. **
  39082. ** READER -> WRITER_LOCKED [sqlite3PagerBegin]
  39083. ** WRITER_LOCKED -> WRITER_CACHEMOD [pager_open_journal]
  39084. ** WRITER_CACHEMOD -> WRITER_DBMOD [syncJournal]
  39085. ** WRITER_DBMOD -> WRITER_FINISHED [sqlite3PagerCommitPhaseOne]
  39086. ** WRITER_*** -> READER [pager_end_transaction]
  39087. **
  39088. ** WRITER_*** -> ERROR [pager_error]
  39089. ** ERROR -> OPEN [pager_unlock]
  39090. **
  39091. **
  39092. ** OPEN:
  39093. **
  39094. ** The pager starts up in this state. Nothing is guaranteed in this
  39095. ** state - the file may or may not be locked and the database size is
  39096. ** unknown. The database may not be read or written.
  39097. **
  39098. ** * No read or write transaction is active.
  39099. ** * Any lock, or no lock at all, may be held on the database file.
  39100. ** * The dbSize, dbOrigSize and dbFileSize variables may not be trusted.
  39101. **
  39102. ** READER:
  39103. **
  39104. ** In this state all the requirements for reading the database in
  39105. ** rollback (non-WAL) mode are met. Unless the pager is (or recently
  39106. ** was) in exclusive-locking mode, a user-level read transaction is
  39107. ** open. The database size is known in this state.
  39108. **
  39109. ** A connection running with locking_mode=normal enters this state when
  39110. ** it opens a read-transaction on the database and returns to state
  39111. ** OPEN after the read-transaction is completed. However a connection
  39112. ** running in locking_mode=exclusive (including temp databases) remains in
  39113. ** this state even after the read-transaction is closed. The only way
  39114. ** a locking_mode=exclusive connection can transition from READER to OPEN
  39115. ** is via the ERROR state (see below).
  39116. **
  39117. ** * A read transaction may be active (but a write-transaction cannot).
  39118. ** * A SHARED or greater lock is held on the database file.
  39119. ** * The dbSize variable may be trusted (even if a user-level read
  39120. ** transaction is not active). The dbOrigSize and dbFileSize variables
  39121. ** may not be trusted at this point.
  39122. ** * If the database is a WAL database, then the WAL connection is open.
  39123. ** * Even if a read-transaction is not open, it is guaranteed that
  39124. ** there is no hot-journal in the file-system.
  39125. **
  39126. ** WRITER_LOCKED:
  39127. **
  39128. ** The pager moves to this state from READER when a write-transaction
  39129. ** is first opened on the database. In WRITER_LOCKED state, all locks
  39130. ** required to start a write-transaction are held, but no actual
  39131. ** modifications to the cache or database have taken place.
  39132. **
  39133. ** In rollback mode, a RESERVED or (if the transaction was opened with
  39134. ** BEGIN EXCLUSIVE) EXCLUSIVE lock is obtained on the database file when
  39135. ** moving to this state, but the journal file is not written to or opened
  39136. ** to in this state. If the transaction is committed or rolled back while
  39137. ** in WRITER_LOCKED state, all that is required is to unlock the database
  39138. ** file.
  39139. **
  39140. ** IN WAL mode, WalBeginWriteTransaction() is called to lock the log file.
  39141. ** If the connection is running with locking_mode=exclusive, an attempt
  39142. ** is made to obtain an EXCLUSIVE lock on the database file.
  39143. **
  39144. ** * A write transaction is active.
  39145. ** * If the connection is open in rollback-mode, a RESERVED or greater
  39146. ** lock is held on the database file.
  39147. ** * If the connection is open in WAL-mode, a WAL write transaction
  39148. ** is open (i.e. sqlite3WalBeginWriteTransaction() has been successfully
  39149. ** called).
  39150. ** * The dbSize, dbOrigSize and dbFileSize variables are all valid.
  39151. ** * The contents of the pager cache have not been modified.
  39152. ** * The journal file may or may not be open.
  39153. ** * Nothing (not even the first header) has been written to the journal.
  39154. **
  39155. ** WRITER_CACHEMOD:
  39156. **
  39157. ** A pager moves from WRITER_LOCKED state to this state when a page is
  39158. ** first modified by the upper layer. In rollback mode the journal file
  39159. ** is opened (if it is not already open) and a header written to the
  39160. ** start of it. The database file on disk has not been modified.
  39161. **
  39162. ** * A write transaction is active.
  39163. ** * A RESERVED or greater lock is held on the database file.
  39164. ** * The journal file is open and the first header has been written
  39165. ** to it, but the header has not been synced to disk.
  39166. ** * The contents of the page cache have been modified.
  39167. **
  39168. ** WRITER_DBMOD:
  39169. **
  39170. ** The pager transitions from WRITER_CACHEMOD into WRITER_DBMOD state
  39171. ** when it modifies the contents of the database file. WAL connections
  39172. ** never enter this state (since they do not modify the database file,
  39173. ** just the log file).
  39174. **
  39175. ** * A write transaction is active.
  39176. ** * An EXCLUSIVE or greater lock is held on the database file.
  39177. ** * The journal file is open and the first header has been written
  39178. ** and synced to disk.
  39179. ** * The contents of the page cache have been modified (and possibly
  39180. ** written to disk).
  39181. **
  39182. ** WRITER_FINISHED:
  39183. **
  39184. ** It is not possible for a WAL connection to enter this state.
  39185. **
  39186. ** A rollback-mode pager changes to WRITER_FINISHED state from WRITER_DBMOD
  39187. ** state after the entire transaction has been successfully written into the
  39188. ** database file. In this state the transaction may be committed simply
  39189. ** by finalizing the journal file. Once in WRITER_FINISHED state, it is
  39190. ** not possible to modify the database further. At this point, the upper
  39191. ** layer must either commit or rollback the transaction.
  39192. **
  39193. ** * A write transaction is active.
  39194. ** * An EXCLUSIVE or greater lock is held on the database file.
  39195. ** * All writing and syncing of journal and database data has finished.
  39196. ** If no error occurred, all that remains is to finalize the journal to
  39197. ** commit the transaction. If an error did occur, the caller will need
  39198. ** to rollback the transaction.
  39199. **
  39200. ** ERROR:
  39201. **
  39202. ** The ERROR state is entered when an IO or disk-full error (including
  39203. ** SQLITE_IOERR_NOMEM) occurs at a point in the code that makes it
  39204. ** difficult to be sure that the in-memory pager state (cache contents,
  39205. ** db size etc.) are consistent with the contents of the file-system.
  39206. **
  39207. ** Temporary pager files may enter the ERROR state, but in-memory pagers
  39208. ** cannot.
  39209. **
  39210. ** For example, if an IO error occurs while performing a rollback,
  39211. ** the contents of the page-cache may be left in an inconsistent state.
  39212. ** At this point it would be dangerous to change back to READER state
  39213. ** (as usually happens after a rollback). Any subsequent readers might
  39214. ** report database corruption (due to the inconsistent cache), and if
  39215. ** they upgrade to writers, they may inadvertently corrupt the database
  39216. ** file. To avoid this hazard, the pager switches into the ERROR state
  39217. ** instead of READER following such an error.
  39218. **
  39219. ** Once it has entered the ERROR state, any attempt to use the pager
  39220. ** to read or write data returns an error. Eventually, once all
  39221. ** outstanding transactions have been abandoned, the pager is able to
  39222. ** transition back to OPEN state, discarding the contents of the
  39223. ** page-cache and any other in-memory state at the same time. Everything
  39224. ** is reloaded from disk (and, if necessary, hot-journal rollback peformed)
  39225. ** when a read-transaction is next opened on the pager (transitioning
  39226. ** the pager into READER state). At that point the system has recovered
  39227. ** from the error.
  39228. **
  39229. ** Specifically, the pager jumps into the ERROR state if:
  39230. **
  39231. ** 1. An error occurs while attempting a rollback. This happens in
  39232. ** function sqlite3PagerRollback().
  39233. **
  39234. ** 2. An error occurs while attempting to finalize a journal file
  39235. ** following a commit in function sqlite3PagerCommitPhaseTwo().
  39236. **
  39237. ** 3. An error occurs while attempting to write to the journal or
  39238. ** database file in function pagerStress() in order to free up
  39239. ** memory.
  39240. **
  39241. ** In other cases, the error is returned to the b-tree layer. The b-tree
  39242. ** layer then attempts a rollback operation. If the error condition
  39243. ** persists, the pager enters the ERROR state via condition (1) above.
  39244. **
  39245. ** Condition (3) is necessary because it can be triggered by a read-only
  39246. ** statement executed within a transaction. In this case, if the error
  39247. ** code were simply returned to the user, the b-tree layer would not
  39248. ** automatically attempt a rollback, as it assumes that an error in a
  39249. ** read-only statement cannot leave the pager in an internally inconsistent
  39250. ** state.
  39251. **
  39252. ** * The Pager.errCode variable is set to something other than SQLITE_OK.
  39253. ** * There are one or more outstanding references to pages (after the
  39254. ** last reference is dropped the pager should move back to OPEN state).
  39255. ** * The pager is not an in-memory pager.
  39256. **
  39257. **
  39258. ** Notes:
  39259. **
  39260. ** * A pager is never in WRITER_DBMOD or WRITER_FINISHED state if the
  39261. ** connection is open in WAL mode. A WAL connection is always in one
  39262. ** of the first four states.
  39263. **
  39264. ** * Normally, a connection open in exclusive mode is never in PAGER_OPEN
  39265. ** state. There are two exceptions: immediately after exclusive-mode has
  39266. ** been turned on (and before any read or write transactions are
  39267. ** executed), and when the pager is leaving the "error state".
  39268. **
  39269. ** * See also: assert_pager_state().
  39270. */
  39271. #define PAGER_OPEN 0
  39272. #define PAGER_READER 1
  39273. #define PAGER_WRITER_LOCKED 2
  39274. #define PAGER_WRITER_CACHEMOD 3
  39275. #define PAGER_WRITER_DBMOD 4
  39276. #define PAGER_WRITER_FINISHED 5
  39277. #define PAGER_ERROR 6
  39278. /*
  39279. ** The Pager.eLock variable is almost always set to one of the
  39280. ** following locking-states, according to the lock currently held on
  39281. ** the database file: NO_LOCK, SHARED_LOCK, RESERVED_LOCK or EXCLUSIVE_LOCK.
  39282. ** This variable is kept up to date as locks are taken and released by
  39283. ** the pagerLockDb() and pagerUnlockDb() wrappers.
  39284. **
  39285. ** If the VFS xLock() or xUnlock() returns an error other than SQLITE_BUSY
  39286. ** (i.e. one of the SQLITE_IOERR subtypes), it is not clear whether or not
  39287. ** the operation was successful. In these circumstances pagerLockDb() and
  39288. ** pagerUnlockDb() take a conservative approach - eLock is always updated
  39289. ** when unlocking the file, and only updated when locking the file if the
  39290. ** VFS call is successful. This way, the Pager.eLock variable may be set
  39291. ** to a less exclusive (lower) value than the lock that is actually held
  39292. ** at the system level, but it is never set to a more exclusive value.
  39293. **
  39294. ** This is usually safe. If an xUnlock fails or appears to fail, there may
  39295. ** be a few redundant xLock() calls or a lock may be held for longer than
  39296. ** required, but nothing really goes wrong.
  39297. **
  39298. ** The exception is when the database file is unlocked as the pager moves
  39299. ** from ERROR to OPEN state. At this point there may be a hot-journal file
  39300. ** in the file-system that needs to be rolled back (as part of an OPEN->SHARED
  39301. ** transition, by the same pager or any other). If the call to xUnlock()
  39302. ** fails at this point and the pager is left holding an EXCLUSIVE lock, this
  39303. ** can confuse the call to xCheckReservedLock() call made later as part
  39304. ** of hot-journal detection.
  39305. **
  39306. ** xCheckReservedLock() is defined as returning true "if there is a RESERVED
  39307. ** lock held by this process or any others". So xCheckReservedLock may
  39308. ** return true because the caller itself is holding an EXCLUSIVE lock (but
  39309. ** doesn't know it because of a previous error in xUnlock). If this happens
  39310. ** a hot-journal may be mistaken for a journal being created by an active
  39311. ** transaction in another process, causing SQLite to read from the database
  39312. ** without rolling it back.
  39313. **
  39314. ** To work around this, if a call to xUnlock() fails when unlocking the
  39315. ** database in the ERROR state, Pager.eLock is set to UNKNOWN_LOCK. It
  39316. ** is only changed back to a real locking state after a successful call
  39317. ** to xLock(EXCLUSIVE). Also, the code to do the OPEN->SHARED state transition
  39318. ** omits the check for a hot-journal if Pager.eLock is set to UNKNOWN_LOCK
  39319. ** lock. Instead, it assumes a hot-journal exists and obtains an EXCLUSIVE
  39320. ** lock on the database file before attempting to roll it back. See function
  39321. ** PagerSharedLock() for more detail.
  39322. **
  39323. ** Pager.eLock may only be set to UNKNOWN_LOCK when the pager is in
  39324. ** PAGER_OPEN state.
  39325. */
  39326. #define UNKNOWN_LOCK (EXCLUSIVE_LOCK+1)
  39327. /*
  39328. ** A macro used for invoking the codec if there is one
  39329. */
  39330. #ifdef SQLITE_HAS_CODEC
  39331. # define CODEC1(P,D,N,X,E) \
  39332. if( P->xCodec && P->xCodec(P->pCodec,D,N,X)==0 ){ E; }
  39333. # define CODEC2(P,D,N,X,E,O) \
  39334. if( P->xCodec==0 ){ O=(char*)D; }else \
  39335. if( (O=(char*)(P->xCodec(P->pCodec,D,N,X)))==0 ){ E; }
  39336. #else
  39337. # define CODEC1(P,D,N,X,E) /* NO-OP */
  39338. # define CODEC2(P,D,N,X,E,O) O=(char*)D
  39339. #endif
  39340. /*
  39341. ** The maximum allowed sector size. 64KiB. If the xSectorsize() method
  39342. ** returns a value larger than this, then MAX_SECTOR_SIZE is used instead.
  39343. ** This could conceivably cause corruption following a power failure on
  39344. ** such a system. This is currently an undocumented limit.
  39345. */
  39346. #define MAX_SECTOR_SIZE 0x10000
  39347. /*
  39348. ** An instance of the following structure is allocated for each active
  39349. ** savepoint and statement transaction in the system. All such structures
  39350. ** are stored in the Pager.aSavepoint[] array, which is allocated and
  39351. ** resized using sqlite3Realloc().
  39352. **
  39353. ** When a savepoint is created, the PagerSavepoint.iHdrOffset field is
  39354. ** set to 0. If a journal-header is written into the main journal while
  39355. ** the savepoint is active, then iHdrOffset is set to the byte offset
  39356. ** immediately following the last journal record written into the main
  39357. ** journal before the journal-header. This is required during savepoint
  39358. ** rollback (see pagerPlaybackSavepoint()).
  39359. */
  39360. typedef struct PagerSavepoint PagerSavepoint;
  39361. struct PagerSavepoint {
  39362. i64 iOffset; /* Starting offset in main journal */
  39363. i64 iHdrOffset; /* See above */
  39364. Bitvec *pInSavepoint; /* Set of pages in this savepoint */
  39365. Pgno nOrig; /* Original number of pages in file */
  39366. Pgno iSubRec; /* Index of first record in sub-journal */
  39367. #ifndef SQLITE_OMIT_WAL
  39368. u32 aWalData[WAL_SAVEPOINT_NDATA]; /* WAL savepoint context */
  39369. #endif
  39370. };
  39371. /*
  39372. ** Bits of the Pager.doNotSpill flag. See further description below.
  39373. */
  39374. #define SPILLFLAG_OFF 0x01 /* Never spill cache. Set via pragma */
  39375. #define SPILLFLAG_ROLLBACK 0x02 /* Current rolling back, so do not spill */
  39376. #define SPILLFLAG_NOSYNC 0x04 /* Spill is ok, but do not sync */
  39377. /*
  39378. ** An open page cache is an instance of struct Pager. A description of
  39379. ** some of the more important member variables follows:
  39380. **
  39381. ** eState
  39382. **
  39383. ** The current 'state' of the pager object. See the comment and state
  39384. ** diagram above for a description of the pager state.
  39385. **
  39386. ** eLock
  39387. **
  39388. ** For a real on-disk database, the current lock held on the database file -
  39389. ** NO_LOCK, SHARED_LOCK, RESERVED_LOCK or EXCLUSIVE_LOCK.
  39390. **
  39391. ** For a temporary or in-memory database (neither of which require any
  39392. ** locks), this variable is always set to EXCLUSIVE_LOCK. Since such
  39393. ** databases always have Pager.exclusiveMode==1, this tricks the pager
  39394. ** logic into thinking that it already has all the locks it will ever
  39395. ** need (and no reason to release them).
  39396. **
  39397. ** In some (obscure) circumstances, this variable may also be set to
  39398. ** UNKNOWN_LOCK. See the comment above the #define of UNKNOWN_LOCK for
  39399. ** details.
  39400. **
  39401. ** changeCountDone
  39402. **
  39403. ** This boolean variable is used to make sure that the change-counter
  39404. ** (the 4-byte header field at byte offset 24 of the database file) is
  39405. ** not updated more often than necessary.
  39406. **
  39407. ** It is set to true when the change-counter field is updated, which
  39408. ** can only happen if an exclusive lock is held on the database file.
  39409. ** It is cleared (set to false) whenever an exclusive lock is
  39410. ** relinquished on the database file. Each time a transaction is committed,
  39411. ** The changeCountDone flag is inspected. If it is true, the work of
  39412. ** updating the change-counter is omitted for the current transaction.
  39413. **
  39414. ** This mechanism means that when running in exclusive mode, a connection
  39415. ** need only update the change-counter once, for the first transaction
  39416. ** committed.
  39417. **
  39418. ** setMaster
  39419. **
  39420. ** When PagerCommitPhaseOne() is called to commit a transaction, it may
  39421. ** (or may not) specify a master-journal name to be written into the
  39422. ** journal file before it is synced to disk.
  39423. **
  39424. ** Whether or not a journal file contains a master-journal pointer affects
  39425. ** the way in which the journal file is finalized after the transaction is
  39426. ** committed or rolled back when running in "journal_mode=PERSIST" mode.
  39427. ** If a journal file does not contain a master-journal pointer, it is
  39428. ** finalized by overwriting the first journal header with zeroes. If
  39429. ** it does contain a master-journal pointer the journal file is finalized
  39430. ** by truncating it to zero bytes, just as if the connection were
  39431. ** running in "journal_mode=truncate" mode.
  39432. **
  39433. ** Journal files that contain master journal pointers cannot be finalized
  39434. ** simply by overwriting the first journal-header with zeroes, as the
  39435. ** master journal pointer could interfere with hot-journal rollback of any
  39436. ** subsequently interrupted transaction that reuses the journal file.
  39437. **
  39438. ** The flag is cleared as soon as the journal file is finalized (either
  39439. ** by PagerCommitPhaseTwo or PagerRollback). If an IO error prevents the
  39440. ** journal file from being successfully finalized, the setMaster flag
  39441. ** is cleared anyway (and the pager will move to ERROR state).
  39442. **
  39443. ** doNotSpill
  39444. **
  39445. ** This variables control the behavior of cache-spills (calls made by
  39446. ** the pcache module to the pagerStress() routine to write cached data
  39447. ** to the file-system in order to free up memory).
  39448. **
  39449. ** When bits SPILLFLAG_OFF or SPILLFLAG_ROLLBACK of doNotSpill are set,
  39450. ** writing to the database from pagerStress() is disabled altogether.
  39451. ** The SPILLFLAG_ROLLBACK case is done in a very obscure case that
  39452. ** comes up during savepoint rollback that requires the pcache module
  39453. ** to allocate a new page to prevent the journal file from being written
  39454. ** while it is being traversed by code in pager_playback(). The SPILLFLAG_OFF
  39455. ** case is a user preference.
  39456. **
  39457. ** If the SPILLFLAG_NOSYNC bit is set, writing to the database from pagerStress()
  39458. ** is permitted, but syncing the journal file is not. This flag is set
  39459. ** by sqlite3PagerWrite() when the file-system sector-size is larger than
  39460. ** the database page-size in order to prevent a journal sync from happening
  39461. ** in between the journalling of two pages on the same sector.
  39462. **
  39463. ** subjInMemory
  39464. **
  39465. ** This is a boolean variable. If true, then any required sub-journal
  39466. ** is opened as an in-memory journal file. If false, then in-memory
  39467. ** sub-journals are only used for in-memory pager files.
  39468. **
  39469. ** This variable is updated by the upper layer each time a new
  39470. ** write-transaction is opened.
  39471. **
  39472. ** dbSize, dbOrigSize, dbFileSize
  39473. **
  39474. ** Variable dbSize is set to the number of pages in the database file.
  39475. ** It is valid in PAGER_READER and higher states (all states except for
  39476. ** OPEN and ERROR).
  39477. **
  39478. ** dbSize is set based on the size of the database file, which may be
  39479. ** larger than the size of the database (the value stored at offset
  39480. ** 28 of the database header by the btree). If the size of the file
  39481. ** is not an integer multiple of the page-size, the value stored in
  39482. ** dbSize is rounded down (i.e. a 5KB file with 2K page-size has dbSize==2).
  39483. ** Except, any file that is greater than 0 bytes in size is considered
  39484. ** to have at least one page. (i.e. a 1KB file with 2K page-size leads
  39485. ** to dbSize==1).
  39486. **
  39487. ** During a write-transaction, if pages with page-numbers greater than
  39488. ** dbSize are modified in the cache, dbSize is updated accordingly.
  39489. ** Similarly, if the database is truncated using PagerTruncateImage(),
  39490. ** dbSize is updated.
  39491. **
  39492. ** Variables dbOrigSize and dbFileSize are valid in states
  39493. ** PAGER_WRITER_LOCKED and higher. dbOrigSize is a copy of the dbSize
  39494. ** variable at the start of the transaction. It is used during rollback,
  39495. ** and to determine whether or not pages need to be journalled before
  39496. ** being modified.
  39497. **
  39498. ** Throughout a write-transaction, dbFileSize contains the size of
  39499. ** the file on disk in pages. It is set to a copy of dbSize when the
  39500. ** write-transaction is first opened, and updated when VFS calls are made
  39501. ** to write or truncate the database file on disk.
  39502. **
  39503. ** The only reason the dbFileSize variable is required is to suppress
  39504. ** unnecessary calls to xTruncate() after committing a transaction. If,
  39505. ** when a transaction is committed, the dbFileSize variable indicates
  39506. ** that the database file is larger than the database image (Pager.dbSize),
  39507. ** pager_truncate() is called. The pager_truncate() call uses xFilesize()
  39508. ** to measure the database file on disk, and then truncates it if required.
  39509. ** dbFileSize is not used when rolling back a transaction. In this case
  39510. ** pager_truncate() is called unconditionally (which means there may be
  39511. ** a call to xFilesize() that is not strictly required). In either case,
  39512. ** pager_truncate() may cause the file to become smaller or larger.
  39513. **
  39514. ** dbHintSize
  39515. **
  39516. ** The dbHintSize variable is used to limit the number of calls made to
  39517. ** the VFS xFileControl(FCNTL_SIZE_HINT) method.
  39518. **
  39519. ** dbHintSize is set to a copy of the dbSize variable when a
  39520. ** write-transaction is opened (at the same time as dbFileSize and
  39521. ** dbOrigSize). If the xFileControl(FCNTL_SIZE_HINT) method is called,
  39522. ** dbHintSize is increased to the number of pages that correspond to the
  39523. ** size-hint passed to the method call. See pager_write_pagelist() for
  39524. ** details.
  39525. **
  39526. ** errCode
  39527. **
  39528. ** The Pager.errCode variable is only ever used in PAGER_ERROR state. It
  39529. ** is set to zero in all other states. In PAGER_ERROR state, Pager.errCode
  39530. ** is always set to SQLITE_FULL, SQLITE_IOERR or one of the SQLITE_IOERR_XXX
  39531. ** sub-codes.
  39532. */
  39533. struct Pager {
  39534. sqlite3_vfs *pVfs; /* OS functions to use for IO */
  39535. u8 exclusiveMode; /* Boolean. True if locking_mode==EXCLUSIVE */
  39536. u8 journalMode; /* One of the PAGER_JOURNALMODE_* values */
  39537. u8 useJournal; /* Use a rollback journal on this file */
  39538. u8 noSync; /* Do not sync the journal if true */
  39539. u8 fullSync; /* Do extra syncs of the journal for robustness */
  39540. u8 ckptSyncFlags; /* SYNC_NORMAL or SYNC_FULL for checkpoint */
  39541. u8 walSyncFlags; /* SYNC_NORMAL or SYNC_FULL for wal writes */
  39542. u8 syncFlags; /* SYNC_NORMAL or SYNC_FULL otherwise */
  39543. u8 tempFile; /* zFilename is a temporary or immutable file */
  39544. u8 noLock; /* Do not lock (except in WAL mode) */
  39545. u8 readOnly; /* True for a read-only database */
  39546. u8 memDb; /* True to inhibit all file I/O */
  39547. /**************************************************************************
  39548. ** The following block contains those class members that change during
  39549. ** routine operation. Class members not in this block are either fixed
  39550. ** when the pager is first created or else only change when there is a
  39551. ** significant mode change (such as changing the page_size, locking_mode,
  39552. ** or the journal_mode). From another view, these class members describe
  39553. ** the "state" of the pager, while other class members describe the
  39554. ** "configuration" of the pager.
  39555. */
  39556. u8 eState; /* Pager state (OPEN, READER, WRITER_LOCKED..) */
  39557. u8 eLock; /* Current lock held on database file */
  39558. u8 changeCountDone; /* Set after incrementing the change-counter */
  39559. u8 setMaster; /* True if a m-j name has been written to jrnl */
  39560. u8 doNotSpill; /* Do not spill the cache when non-zero */
  39561. u8 subjInMemory; /* True to use in-memory sub-journals */
  39562. u8 bUseFetch; /* True to use xFetch() */
  39563. u8 hasBeenUsed; /* True if any content previously read from this pager*/
  39564. Pgno dbSize; /* Number of pages in the database */
  39565. Pgno dbOrigSize; /* dbSize before the current transaction */
  39566. Pgno dbFileSize; /* Number of pages in the database file */
  39567. Pgno dbHintSize; /* Value passed to FCNTL_SIZE_HINT call */
  39568. int errCode; /* One of several kinds of errors */
  39569. int nRec; /* Pages journalled since last j-header written */
  39570. u32 cksumInit; /* Quasi-random value added to every checksum */
  39571. u32 nSubRec; /* Number of records written to sub-journal */
  39572. Bitvec *pInJournal; /* One bit for each page in the database file */
  39573. sqlite3_file *fd; /* File descriptor for database */
  39574. sqlite3_file *jfd; /* File descriptor for main journal */
  39575. sqlite3_file *sjfd; /* File descriptor for sub-journal */
  39576. i64 journalOff; /* Current write offset in the journal file */
  39577. i64 journalHdr; /* Byte offset to previous journal header */
  39578. sqlite3_backup *pBackup; /* Pointer to list of ongoing backup processes */
  39579. PagerSavepoint *aSavepoint; /* Array of active savepoints */
  39580. int nSavepoint; /* Number of elements in aSavepoint[] */
  39581. u32 iDataVersion; /* Changes whenever database content changes */
  39582. char dbFileVers[16]; /* Changes whenever database file changes */
  39583. int nMmapOut; /* Number of mmap pages currently outstanding */
  39584. sqlite3_int64 szMmap; /* Desired maximum mmap size */
  39585. PgHdr *pMmapFreelist; /* List of free mmap page headers (pDirty) */
  39586. /*
  39587. ** End of the routinely-changing class members
  39588. ***************************************************************************/
  39589. u16 nExtra; /* Add this many bytes to each in-memory page */
  39590. i16 nReserve; /* Number of unused bytes at end of each page */
  39591. u32 vfsFlags; /* Flags for sqlite3_vfs.xOpen() */
  39592. u32 sectorSize; /* Assumed sector size during rollback */
  39593. int pageSize; /* Number of bytes in a page */
  39594. Pgno mxPgno; /* Maximum allowed size of the database */
  39595. i64 journalSizeLimit; /* Size limit for persistent journal files */
  39596. char *zFilename; /* Name of the database file */
  39597. char *zJournal; /* Name of the journal file */
  39598. int (*xBusyHandler)(void*); /* Function to call when busy */
  39599. void *pBusyHandlerArg; /* Context argument for xBusyHandler */
  39600. int aStat[3]; /* Total cache hits, misses and writes */
  39601. #ifdef SQLITE_TEST
  39602. int nRead; /* Database pages read */
  39603. #endif
  39604. void (*xReiniter)(DbPage*); /* Call this routine when reloading pages */
  39605. #ifdef SQLITE_HAS_CODEC
  39606. void *(*xCodec)(void*,void*,Pgno,int); /* Routine for en/decoding data */
  39607. void (*xCodecSizeChng)(void*,int,int); /* Notify of page size changes */
  39608. void (*xCodecFree)(void*); /* Destructor for the codec */
  39609. void *pCodec; /* First argument to xCodec... methods */
  39610. #endif
  39611. char *pTmpSpace; /* Pager.pageSize bytes of space for tmp use */
  39612. PCache *pPCache; /* Pointer to page cache object */
  39613. #ifndef SQLITE_OMIT_WAL
  39614. Wal *pWal; /* Write-ahead log used by "journal_mode=wal" */
  39615. char *zWal; /* File name for write-ahead log */
  39616. #endif
  39617. };
  39618. /*
  39619. ** Indexes for use with Pager.aStat[]. The Pager.aStat[] array contains
  39620. ** the values accessed by passing SQLITE_DBSTATUS_CACHE_HIT, CACHE_MISS
  39621. ** or CACHE_WRITE to sqlite3_db_status().
  39622. */
  39623. #define PAGER_STAT_HIT 0
  39624. #define PAGER_STAT_MISS 1
  39625. #define PAGER_STAT_WRITE 2
  39626. /*
  39627. ** The following global variables hold counters used for
  39628. ** testing purposes only. These variables do not exist in
  39629. ** a non-testing build. These variables are not thread-safe.
  39630. */
  39631. #ifdef SQLITE_TEST
  39632. SQLITE_API int sqlite3_pager_readdb_count = 0; /* Number of full pages read from DB */
  39633. SQLITE_API int sqlite3_pager_writedb_count = 0; /* Number of full pages written to DB */
  39634. SQLITE_API int sqlite3_pager_writej_count = 0; /* Number of pages written to journal */
  39635. # define PAGER_INCR(v) v++
  39636. #else
  39637. # define PAGER_INCR(v)
  39638. #endif
  39639. /*
  39640. ** Journal files begin with the following magic string. The data
  39641. ** was obtained from /dev/random. It is used only as a sanity check.
  39642. **
  39643. ** Since version 2.8.0, the journal format contains additional sanity
  39644. ** checking information. If the power fails while the journal is being
  39645. ** written, semi-random garbage data might appear in the journal
  39646. ** file after power is restored. If an attempt is then made
  39647. ** to roll the journal back, the database could be corrupted. The additional
  39648. ** sanity checking data is an attempt to discover the garbage in the
  39649. ** journal and ignore it.
  39650. **
  39651. ** The sanity checking information for the new journal format consists
  39652. ** of a 32-bit checksum on each page of data. The checksum covers both
  39653. ** the page number and the pPager->pageSize bytes of data for the page.
  39654. ** This cksum is initialized to a 32-bit random value that appears in the
  39655. ** journal file right after the header. The random initializer is important,
  39656. ** because garbage data that appears at the end of a journal is likely
  39657. ** data that was once in other files that have now been deleted. If the
  39658. ** garbage data came from an obsolete journal file, the checksums might
  39659. ** be correct. But by initializing the checksum to random value which
  39660. ** is different for every journal, we minimize that risk.
  39661. */
  39662. static const unsigned char aJournalMagic[] = {
  39663. 0xd9, 0xd5, 0x05, 0xf9, 0x20, 0xa1, 0x63, 0xd7,
  39664. };
  39665. /*
  39666. ** The size of the of each page record in the journal is given by
  39667. ** the following macro.
  39668. */
  39669. #define JOURNAL_PG_SZ(pPager) ((pPager->pageSize) + 8)
  39670. /*
  39671. ** The journal header size for this pager. This is usually the same
  39672. ** size as a single disk sector. See also setSectorSize().
  39673. */
  39674. #define JOURNAL_HDR_SZ(pPager) (pPager->sectorSize)
  39675. /*
  39676. ** The macro MEMDB is true if we are dealing with an in-memory database.
  39677. ** We do this as a macro so that if the SQLITE_OMIT_MEMORYDB macro is set,
  39678. ** the value of MEMDB will be a constant and the compiler will optimize
  39679. ** out code that would never execute.
  39680. */
  39681. #ifdef SQLITE_OMIT_MEMORYDB
  39682. # define MEMDB 0
  39683. #else
  39684. # define MEMDB pPager->memDb
  39685. #endif
  39686. /*
  39687. ** The macro USEFETCH is true if we are allowed to use the xFetch and xUnfetch
  39688. ** interfaces to access the database using memory-mapped I/O.
  39689. */
  39690. #if SQLITE_MAX_MMAP_SIZE>0
  39691. # define USEFETCH(x) ((x)->bUseFetch)
  39692. #else
  39693. # define USEFETCH(x) 0
  39694. #endif
  39695. /*
  39696. ** The maximum legal page number is (2^31 - 1).
  39697. */
  39698. #define PAGER_MAX_PGNO 2147483647
  39699. /*
  39700. ** The argument to this macro is a file descriptor (type sqlite3_file*).
  39701. ** Return 0 if it is not open, or non-zero (but not 1) if it is.
  39702. **
  39703. ** This is so that expressions can be written as:
  39704. **
  39705. ** if( isOpen(pPager->jfd) ){ ...
  39706. **
  39707. ** instead of
  39708. **
  39709. ** if( pPager->jfd->pMethods ){ ...
  39710. */
  39711. #define isOpen(pFd) ((pFd)->pMethods)
  39712. /*
  39713. ** Return true if this pager uses a write-ahead log instead of the usual
  39714. ** rollback journal. Otherwise false.
  39715. */
  39716. #ifndef SQLITE_OMIT_WAL
  39717. static int pagerUseWal(Pager *pPager){
  39718. return (pPager->pWal!=0);
  39719. }
  39720. #else
  39721. # define pagerUseWal(x) 0
  39722. # define pagerRollbackWal(x) 0
  39723. # define pagerWalFrames(v,w,x,y) 0
  39724. # define pagerOpenWalIfPresent(z) SQLITE_OK
  39725. # define pagerBeginReadTransaction(z) SQLITE_OK
  39726. #endif
  39727. #ifndef NDEBUG
  39728. /*
  39729. ** Usage:
  39730. **
  39731. ** assert( assert_pager_state(pPager) );
  39732. **
  39733. ** This function runs many asserts to try to find inconsistencies in
  39734. ** the internal state of the Pager object.
  39735. */
  39736. static int assert_pager_state(Pager *p){
  39737. Pager *pPager = p;
  39738. /* State must be valid. */
  39739. assert( p->eState==PAGER_OPEN
  39740. || p->eState==PAGER_READER
  39741. || p->eState==PAGER_WRITER_LOCKED
  39742. || p->eState==PAGER_WRITER_CACHEMOD
  39743. || p->eState==PAGER_WRITER_DBMOD
  39744. || p->eState==PAGER_WRITER_FINISHED
  39745. || p->eState==PAGER_ERROR
  39746. );
  39747. /* Regardless of the current state, a temp-file connection always behaves
  39748. ** as if it has an exclusive lock on the database file. It never updates
  39749. ** the change-counter field, so the changeCountDone flag is always set.
  39750. */
  39751. assert( p->tempFile==0 || p->eLock==EXCLUSIVE_LOCK );
  39752. assert( p->tempFile==0 || pPager->changeCountDone );
  39753. /* If the useJournal flag is clear, the journal-mode must be "OFF".
  39754. ** And if the journal-mode is "OFF", the journal file must not be open.
  39755. */
  39756. assert( p->journalMode==PAGER_JOURNALMODE_OFF || p->useJournal );
  39757. assert( p->journalMode!=PAGER_JOURNALMODE_OFF || !isOpen(p->jfd) );
  39758. /* Check that MEMDB implies noSync. And an in-memory journal. Since
  39759. ** this means an in-memory pager performs no IO at all, it cannot encounter
  39760. ** either SQLITE_IOERR or SQLITE_FULL during rollback or while finalizing
  39761. ** a journal file. (although the in-memory journal implementation may
  39762. ** return SQLITE_IOERR_NOMEM while the journal file is being written). It
  39763. ** is therefore not possible for an in-memory pager to enter the ERROR
  39764. ** state.
  39765. */
  39766. if( MEMDB ){
  39767. assert( p->noSync );
  39768. assert( p->journalMode==PAGER_JOURNALMODE_OFF
  39769. || p->journalMode==PAGER_JOURNALMODE_MEMORY
  39770. );
  39771. assert( p->eState!=PAGER_ERROR && p->eState!=PAGER_OPEN );
  39772. assert( pagerUseWal(p)==0 );
  39773. }
  39774. /* If changeCountDone is set, a RESERVED lock or greater must be held
  39775. ** on the file.
  39776. */
  39777. assert( pPager->changeCountDone==0 || pPager->eLock>=RESERVED_LOCK );
  39778. assert( p->eLock!=PENDING_LOCK );
  39779. switch( p->eState ){
  39780. case PAGER_OPEN:
  39781. assert( !MEMDB );
  39782. assert( pPager->errCode==SQLITE_OK );
  39783. assert( sqlite3PcacheRefCount(pPager->pPCache)==0 || pPager->tempFile );
  39784. break;
  39785. case PAGER_READER:
  39786. assert( pPager->errCode==SQLITE_OK );
  39787. assert( p->eLock!=UNKNOWN_LOCK );
  39788. assert( p->eLock>=SHARED_LOCK );
  39789. break;
  39790. case PAGER_WRITER_LOCKED:
  39791. assert( p->eLock!=UNKNOWN_LOCK );
  39792. assert( pPager->errCode==SQLITE_OK );
  39793. if( !pagerUseWal(pPager) ){
  39794. assert( p->eLock>=RESERVED_LOCK );
  39795. }
  39796. assert( pPager->dbSize==pPager->dbOrigSize );
  39797. assert( pPager->dbOrigSize==pPager->dbFileSize );
  39798. assert( pPager->dbOrigSize==pPager->dbHintSize );
  39799. assert( pPager->setMaster==0 );
  39800. break;
  39801. case PAGER_WRITER_CACHEMOD:
  39802. assert( p->eLock!=UNKNOWN_LOCK );
  39803. assert( pPager->errCode==SQLITE_OK );
  39804. if( !pagerUseWal(pPager) ){
  39805. /* It is possible that if journal_mode=wal here that neither the
  39806. ** journal file nor the WAL file are open. This happens during
  39807. ** a rollback transaction that switches from journal_mode=off
  39808. ** to journal_mode=wal.
  39809. */
  39810. assert( p->eLock>=RESERVED_LOCK );
  39811. assert( isOpen(p->jfd)
  39812. || p->journalMode==PAGER_JOURNALMODE_OFF
  39813. || p->journalMode==PAGER_JOURNALMODE_WAL
  39814. );
  39815. }
  39816. assert( pPager->dbOrigSize==pPager->dbFileSize );
  39817. assert( pPager->dbOrigSize==pPager->dbHintSize );
  39818. break;
  39819. case PAGER_WRITER_DBMOD:
  39820. assert( p->eLock==EXCLUSIVE_LOCK );
  39821. assert( pPager->errCode==SQLITE_OK );
  39822. assert( !pagerUseWal(pPager) );
  39823. assert( p->eLock>=EXCLUSIVE_LOCK );
  39824. assert( isOpen(p->jfd)
  39825. || p->journalMode==PAGER_JOURNALMODE_OFF
  39826. || p->journalMode==PAGER_JOURNALMODE_WAL
  39827. );
  39828. assert( pPager->dbOrigSize<=pPager->dbHintSize );
  39829. break;
  39830. case PAGER_WRITER_FINISHED:
  39831. assert( p->eLock==EXCLUSIVE_LOCK );
  39832. assert( pPager->errCode==SQLITE_OK );
  39833. assert( !pagerUseWal(pPager) );
  39834. assert( isOpen(p->jfd)
  39835. || p->journalMode==PAGER_JOURNALMODE_OFF
  39836. || p->journalMode==PAGER_JOURNALMODE_WAL
  39837. );
  39838. break;
  39839. case PAGER_ERROR:
  39840. /* There must be at least one outstanding reference to the pager if
  39841. ** in ERROR state. Otherwise the pager should have already dropped
  39842. ** back to OPEN state.
  39843. */
  39844. assert( pPager->errCode!=SQLITE_OK );
  39845. assert( sqlite3PcacheRefCount(pPager->pPCache)>0 );
  39846. break;
  39847. }
  39848. return 1;
  39849. }
  39850. #endif /* ifndef NDEBUG */
  39851. #ifdef SQLITE_DEBUG
  39852. /*
  39853. ** Return a pointer to a human readable string in a static buffer
  39854. ** containing the state of the Pager object passed as an argument. This
  39855. ** is intended to be used within debuggers. For example, as an alternative
  39856. ** to "print *pPager" in gdb:
  39857. **
  39858. ** (gdb) printf "%s", print_pager_state(pPager)
  39859. */
  39860. static char *print_pager_state(Pager *p){
  39861. static char zRet[1024];
  39862. sqlite3_snprintf(1024, zRet,
  39863. "Filename: %s\n"
  39864. "State: %s errCode=%d\n"
  39865. "Lock: %s\n"
  39866. "Locking mode: locking_mode=%s\n"
  39867. "Journal mode: journal_mode=%s\n"
  39868. "Backing store: tempFile=%d memDb=%d useJournal=%d\n"
  39869. "Journal: journalOff=%lld journalHdr=%lld\n"
  39870. "Size: dbsize=%d dbOrigSize=%d dbFileSize=%d\n"
  39871. , p->zFilename
  39872. , p->eState==PAGER_OPEN ? "OPEN" :
  39873. p->eState==PAGER_READER ? "READER" :
  39874. p->eState==PAGER_WRITER_LOCKED ? "WRITER_LOCKED" :
  39875. p->eState==PAGER_WRITER_CACHEMOD ? "WRITER_CACHEMOD" :
  39876. p->eState==PAGER_WRITER_DBMOD ? "WRITER_DBMOD" :
  39877. p->eState==PAGER_WRITER_FINISHED ? "WRITER_FINISHED" :
  39878. p->eState==PAGER_ERROR ? "ERROR" : "?error?"
  39879. , (int)p->errCode
  39880. , p->eLock==NO_LOCK ? "NO_LOCK" :
  39881. p->eLock==RESERVED_LOCK ? "RESERVED" :
  39882. p->eLock==EXCLUSIVE_LOCK ? "EXCLUSIVE" :
  39883. p->eLock==SHARED_LOCK ? "SHARED" :
  39884. p->eLock==UNKNOWN_LOCK ? "UNKNOWN" : "?error?"
  39885. , p->exclusiveMode ? "exclusive" : "normal"
  39886. , p->journalMode==PAGER_JOURNALMODE_MEMORY ? "memory" :
  39887. p->journalMode==PAGER_JOURNALMODE_OFF ? "off" :
  39888. p->journalMode==PAGER_JOURNALMODE_DELETE ? "delete" :
  39889. p->journalMode==PAGER_JOURNALMODE_PERSIST ? "persist" :
  39890. p->journalMode==PAGER_JOURNALMODE_TRUNCATE ? "truncate" :
  39891. p->journalMode==PAGER_JOURNALMODE_WAL ? "wal" : "?error?"
  39892. , (int)p->tempFile, (int)p->memDb, (int)p->useJournal
  39893. , p->journalOff, p->journalHdr
  39894. , (int)p->dbSize, (int)p->dbOrigSize, (int)p->dbFileSize
  39895. );
  39896. return zRet;
  39897. }
  39898. #endif
  39899. /*
  39900. ** Return true if it is necessary to write page *pPg into the sub-journal.
  39901. ** A page needs to be written into the sub-journal if there exists one
  39902. ** or more open savepoints for which:
  39903. **
  39904. ** * The page-number is less than or equal to PagerSavepoint.nOrig, and
  39905. ** * The bit corresponding to the page-number is not set in
  39906. ** PagerSavepoint.pInSavepoint.
  39907. */
  39908. static int subjRequiresPage(PgHdr *pPg){
  39909. Pager *pPager = pPg->pPager;
  39910. PagerSavepoint *p;
  39911. Pgno pgno = pPg->pgno;
  39912. int i;
  39913. for(i=0; i<pPager->nSavepoint; i++){
  39914. p = &pPager->aSavepoint[i];
  39915. if( p->nOrig>=pgno && 0==sqlite3BitvecTest(p->pInSavepoint, pgno) ){
  39916. return 1;
  39917. }
  39918. }
  39919. return 0;
  39920. }
  39921. /*
  39922. ** Return true if the page is already in the journal file.
  39923. */
  39924. static int pageInJournal(Pager *pPager, PgHdr *pPg){
  39925. return sqlite3BitvecTest(pPager->pInJournal, pPg->pgno);
  39926. }
  39927. /*
  39928. ** Read a 32-bit integer from the given file descriptor. Store the integer
  39929. ** that is read in *pRes. Return SQLITE_OK if everything worked, or an
  39930. ** error code is something goes wrong.
  39931. **
  39932. ** All values are stored on disk as big-endian.
  39933. */
  39934. static int read32bits(sqlite3_file *fd, i64 offset, u32 *pRes){
  39935. unsigned char ac[4];
  39936. int rc = sqlite3OsRead(fd, ac, sizeof(ac), offset);
  39937. if( rc==SQLITE_OK ){
  39938. *pRes = sqlite3Get4byte(ac);
  39939. }
  39940. return rc;
  39941. }
  39942. /*
  39943. ** Write a 32-bit integer into a string buffer in big-endian byte order.
  39944. */
  39945. #define put32bits(A,B) sqlite3Put4byte((u8*)A,B)
  39946. /*
  39947. ** Write a 32-bit integer into the given file descriptor. Return SQLITE_OK
  39948. ** on success or an error code is something goes wrong.
  39949. */
  39950. static int write32bits(sqlite3_file *fd, i64 offset, u32 val){
  39951. char ac[4];
  39952. put32bits(ac, val);
  39953. return sqlite3OsWrite(fd, ac, 4, offset);
  39954. }
  39955. /*
  39956. ** Unlock the database file to level eLock, which must be either NO_LOCK
  39957. ** or SHARED_LOCK. Regardless of whether or not the call to xUnlock()
  39958. ** succeeds, set the Pager.eLock variable to match the (attempted) new lock.
  39959. **
  39960. ** Except, if Pager.eLock is set to UNKNOWN_LOCK when this function is
  39961. ** called, do not modify it. See the comment above the #define of
  39962. ** UNKNOWN_LOCK for an explanation of this.
  39963. */
  39964. static int pagerUnlockDb(Pager *pPager, int eLock){
  39965. int rc = SQLITE_OK;
  39966. assert( !pPager->exclusiveMode || pPager->eLock==eLock );
  39967. assert( eLock==NO_LOCK || eLock==SHARED_LOCK );
  39968. assert( eLock!=NO_LOCK || pagerUseWal(pPager)==0 );
  39969. if( isOpen(pPager->fd) ){
  39970. assert( pPager->eLock>=eLock );
  39971. rc = pPager->noLock ? SQLITE_OK : sqlite3OsUnlock(pPager->fd, eLock);
  39972. if( pPager->eLock!=UNKNOWN_LOCK ){
  39973. pPager->eLock = (u8)eLock;
  39974. }
  39975. IOTRACE(("UNLOCK %p %d\n", pPager, eLock))
  39976. }
  39977. return rc;
  39978. }
  39979. /*
  39980. ** Lock the database file to level eLock, which must be either SHARED_LOCK,
  39981. ** RESERVED_LOCK or EXCLUSIVE_LOCK. If the caller is successful, set the
  39982. ** Pager.eLock variable to the new locking state.
  39983. **
  39984. ** Except, if Pager.eLock is set to UNKNOWN_LOCK when this function is
  39985. ** called, do not modify it unless the new locking state is EXCLUSIVE_LOCK.
  39986. ** See the comment above the #define of UNKNOWN_LOCK for an explanation
  39987. ** of this.
  39988. */
  39989. static int pagerLockDb(Pager *pPager, int eLock){
  39990. int rc = SQLITE_OK;
  39991. assert( eLock==SHARED_LOCK || eLock==RESERVED_LOCK || eLock==EXCLUSIVE_LOCK );
  39992. if( pPager->eLock<eLock || pPager->eLock==UNKNOWN_LOCK ){
  39993. rc = pPager->noLock ? SQLITE_OK : sqlite3OsLock(pPager->fd, eLock);
  39994. if( rc==SQLITE_OK && (pPager->eLock!=UNKNOWN_LOCK||eLock==EXCLUSIVE_LOCK) ){
  39995. pPager->eLock = (u8)eLock;
  39996. IOTRACE(("LOCK %p %d\n", pPager, eLock))
  39997. }
  39998. }
  39999. return rc;
  40000. }
  40001. /*
  40002. ** This function determines whether or not the atomic-write optimization
  40003. ** can be used with this pager. The optimization can be used if:
  40004. **
  40005. ** (a) the value returned by OsDeviceCharacteristics() indicates that
  40006. ** a database page may be written atomically, and
  40007. ** (b) the value returned by OsSectorSize() is less than or equal
  40008. ** to the page size.
  40009. **
  40010. ** The optimization is also always enabled for temporary files. It is
  40011. ** an error to call this function if pPager is opened on an in-memory
  40012. ** database.
  40013. **
  40014. ** If the optimization cannot be used, 0 is returned. If it can be used,
  40015. ** then the value returned is the size of the journal file when it
  40016. ** contains rollback data for exactly one page.
  40017. */
  40018. #ifdef SQLITE_ENABLE_ATOMIC_WRITE
  40019. static int jrnlBufferSize(Pager *pPager){
  40020. assert( !MEMDB );
  40021. if( !pPager->tempFile ){
  40022. int dc; /* Device characteristics */
  40023. int nSector; /* Sector size */
  40024. int szPage; /* Page size */
  40025. assert( isOpen(pPager->fd) );
  40026. dc = sqlite3OsDeviceCharacteristics(pPager->fd);
  40027. nSector = pPager->sectorSize;
  40028. szPage = pPager->pageSize;
  40029. assert(SQLITE_IOCAP_ATOMIC512==(512>>8));
  40030. assert(SQLITE_IOCAP_ATOMIC64K==(65536>>8));
  40031. if( 0==(dc&(SQLITE_IOCAP_ATOMIC|(szPage>>8)) || nSector>szPage) ){
  40032. return 0;
  40033. }
  40034. }
  40035. return JOURNAL_HDR_SZ(pPager) + JOURNAL_PG_SZ(pPager);
  40036. }
  40037. #endif
  40038. /*
  40039. ** If SQLITE_CHECK_PAGES is defined then we do some sanity checking
  40040. ** on the cache using a hash function. This is used for testing
  40041. ** and debugging only.
  40042. */
  40043. #ifdef SQLITE_CHECK_PAGES
  40044. /*
  40045. ** Return a 32-bit hash of the page data for pPage.
  40046. */
  40047. static u32 pager_datahash(int nByte, unsigned char *pData){
  40048. u32 hash = 0;
  40049. int i;
  40050. for(i=0; i<nByte; i++){
  40051. hash = (hash*1039) + pData[i];
  40052. }
  40053. return hash;
  40054. }
  40055. static u32 pager_pagehash(PgHdr *pPage){
  40056. return pager_datahash(pPage->pPager->pageSize, (unsigned char *)pPage->pData);
  40057. }
  40058. static void pager_set_pagehash(PgHdr *pPage){
  40059. pPage->pageHash = pager_pagehash(pPage);
  40060. }
  40061. /*
  40062. ** The CHECK_PAGE macro takes a PgHdr* as an argument. If SQLITE_CHECK_PAGES
  40063. ** is defined, and NDEBUG is not defined, an assert() statement checks
  40064. ** that the page is either dirty or still matches the calculated page-hash.
  40065. */
  40066. #define CHECK_PAGE(x) checkPage(x)
  40067. static void checkPage(PgHdr *pPg){
  40068. Pager *pPager = pPg->pPager;
  40069. assert( pPager->eState!=PAGER_ERROR );
  40070. assert( (pPg->flags&PGHDR_DIRTY) || pPg->pageHash==pager_pagehash(pPg) );
  40071. }
  40072. #else
  40073. #define pager_datahash(X,Y) 0
  40074. #define pager_pagehash(X) 0
  40075. #define pager_set_pagehash(X)
  40076. #define CHECK_PAGE(x)
  40077. #endif /* SQLITE_CHECK_PAGES */
  40078. /*
  40079. ** When this is called the journal file for pager pPager must be open.
  40080. ** This function attempts to read a master journal file name from the
  40081. ** end of the file and, if successful, copies it into memory supplied
  40082. ** by the caller. See comments above writeMasterJournal() for the format
  40083. ** used to store a master journal file name at the end of a journal file.
  40084. **
  40085. ** zMaster must point to a buffer of at least nMaster bytes allocated by
  40086. ** the caller. This should be sqlite3_vfs.mxPathname+1 (to ensure there is
  40087. ** enough space to write the master journal name). If the master journal
  40088. ** name in the journal is longer than nMaster bytes (including a
  40089. ** nul-terminator), then this is handled as if no master journal name
  40090. ** were present in the journal.
  40091. **
  40092. ** If a master journal file name is present at the end of the journal
  40093. ** file, then it is copied into the buffer pointed to by zMaster. A
  40094. ** nul-terminator byte is appended to the buffer following the master
  40095. ** journal file name.
  40096. **
  40097. ** If it is determined that no master journal file name is present
  40098. ** zMaster[0] is set to 0 and SQLITE_OK returned.
  40099. **
  40100. ** If an error occurs while reading from the journal file, an SQLite
  40101. ** error code is returned.
  40102. */
  40103. static int readMasterJournal(sqlite3_file *pJrnl, char *zMaster, u32 nMaster){
  40104. int rc; /* Return code */
  40105. u32 len; /* Length in bytes of master journal name */
  40106. i64 szJ; /* Total size in bytes of journal file pJrnl */
  40107. u32 cksum; /* MJ checksum value read from journal */
  40108. u32 u; /* Unsigned loop counter */
  40109. unsigned char aMagic[8]; /* A buffer to hold the magic header */
  40110. zMaster[0] = '\0';
  40111. if( SQLITE_OK!=(rc = sqlite3OsFileSize(pJrnl, &szJ))
  40112. || szJ<16
  40113. || SQLITE_OK!=(rc = read32bits(pJrnl, szJ-16, &len))
  40114. || len>=nMaster
  40115. || len==0
  40116. || SQLITE_OK!=(rc = read32bits(pJrnl, szJ-12, &cksum))
  40117. || SQLITE_OK!=(rc = sqlite3OsRead(pJrnl, aMagic, 8, szJ-8))
  40118. || memcmp(aMagic, aJournalMagic, 8)
  40119. || SQLITE_OK!=(rc = sqlite3OsRead(pJrnl, zMaster, len, szJ-16-len))
  40120. ){
  40121. return rc;
  40122. }
  40123. /* See if the checksum matches the master journal name */
  40124. for(u=0; u<len; u++){
  40125. cksum -= zMaster[u];
  40126. }
  40127. if( cksum ){
  40128. /* If the checksum doesn't add up, then one or more of the disk sectors
  40129. ** containing the master journal filename is corrupted. This means
  40130. ** definitely roll back, so just return SQLITE_OK and report a (nul)
  40131. ** master-journal filename.
  40132. */
  40133. len = 0;
  40134. }
  40135. zMaster[len] = '\0';
  40136. return SQLITE_OK;
  40137. }
  40138. /*
  40139. ** Return the offset of the sector boundary at or immediately
  40140. ** following the value in pPager->journalOff, assuming a sector
  40141. ** size of pPager->sectorSize bytes.
  40142. **
  40143. ** i.e for a sector size of 512:
  40144. **
  40145. ** Pager.journalOff Return value
  40146. ** ---------------------------------------
  40147. ** 0 0
  40148. ** 512 512
  40149. ** 100 512
  40150. ** 2000 2048
  40151. **
  40152. */
  40153. static i64 journalHdrOffset(Pager *pPager){
  40154. i64 offset = 0;
  40155. i64 c = pPager->journalOff;
  40156. if( c ){
  40157. offset = ((c-1)/JOURNAL_HDR_SZ(pPager) + 1) * JOURNAL_HDR_SZ(pPager);
  40158. }
  40159. assert( offset%JOURNAL_HDR_SZ(pPager)==0 );
  40160. assert( offset>=c );
  40161. assert( (offset-c)<JOURNAL_HDR_SZ(pPager) );
  40162. return offset;
  40163. }
  40164. /*
  40165. ** The journal file must be open when this function is called.
  40166. **
  40167. ** This function is a no-op if the journal file has not been written to
  40168. ** within the current transaction (i.e. if Pager.journalOff==0).
  40169. **
  40170. ** If doTruncate is non-zero or the Pager.journalSizeLimit variable is
  40171. ** set to 0, then truncate the journal file to zero bytes in size. Otherwise,
  40172. ** zero the 28-byte header at the start of the journal file. In either case,
  40173. ** if the pager is not in no-sync mode, sync the journal file immediately
  40174. ** after writing or truncating it.
  40175. **
  40176. ** If Pager.journalSizeLimit is set to a positive, non-zero value, and
  40177. ** following the truncation or zeroing described above the size of the
  40178. ** journal file in bytes is larger than this value, then truncate the
  40179. ** journal file to Pager.journalSizeLimit bytes. The journal file does
  40180. ** not need to be synced following this operation.
  40181. **
  40182. ** If an IO error occurs, abandon processing and return the IO error code.
  40183. ** Otherwise, return SQLITE_OK.
  40184. */
  40185. static int zeroJournalHdr(Pager *pPager, int doTruncate){
  40186. int rc = SQLITE_OK; /* Return code */
  40187. assert( isOpen(pPager->jfd) );
  40188. if( pPager->journalOff ){
  40189. const i64 iLimit = pPager->journalSizeLimit; /* Local cache of jsl */
  40190. IOTRACE(("JZEROHDR %p\n", pPager))
  40191. if( doTruncate || iLimit==0 ){
  40192. rc = sqlite3OsTruncate(pPager->jfd, 0);
  40193. }else{
  40194. static const char zeroHdr[28] = {0};
  40195. rc = sqlite3OsWrite(pPager->jfd, zeroHdr, sizeof(zeroHdr), 0);
  40196. }
  40197. if( rc==SQLITE_OK && !pPager->noSync ){
  40198. rc = sqlite3OsSync(pPager->jfd, SQLITE_SYNC_DATAONLY|pPager->syncFlags);
  40199. }
  40200. /* At this point the transaction is committed but the write lock
  40201. ** is still held on the file. If there is a size limit configured for
  40202. ** the persistent journal and the journal file currently consumes more
  40203. ** space than that limit allows for, truncate it now. There is no need
  40204. ** to sync the file following this operation.
  40205. */
  40206. if( rc==SQLITE_OK && iLimit>0 ){
  40207. i64 sz;
  40208. rc = sqlite3OsFileSize(pPager->jfd, &sz);
  40209. if( rc==SQLITE_OK && sz>iLimit ){
  40210. rc = sqlite3OsTruncate(pPager->jfd, iLimit);
  40211. }
  40212. }
  40213. }
  40214. return rc;
  40215. }
  40216. /*
  40217. ** The journal file must be open when this routine is called. A journal
  40218. ** header (JOURNAL_HDR_SZ bytes) is written into the journal file at the
  40219. ** current location.
  40220. **
  40221. ** The format for the journal header is as follows:
  40222. ** - 8 bytes: Magic identifying journal format.
  40223. ** - 4 bytes: Number of records in journal, or -1 no-sync mode is on.
  40224. ** - 4 bytes: Random number used for page hash.
  40225. ** - 4 bytes: Initial database page count.
  40226. ** - 4 bytes: Sector size used by the process that wrote this journal.
  40227. ** - 4 bytes: Database page size.
  40228. **
  40229. ** Followed by (JOURNAL_HDR_SZ - 28) bytes of unused space.
  40230. */
  40231. static int writeJournalHdr(Pager *pPager){
  40232. int rc = SQLITE_OK; /* Return code */
  40233. char *zHeader = pPager->pTmpSpace; /* Temporary space used to build header */
  40234. u32 nHeader = (u32)pPager->pageSize;/* Size of buffer pointed to by zHeader */
  40235. u32 nWrite; /* Bytes of header sector written */
  40236. int ii; /* Loop counter */
  40237. assert( isOpen(pPager->jfd) ); /* Journal file must be open. */
  40238. if( nHeader>JOURNAL_HDR_SZ(pPager) ){
  40239. nHeader = JOURNAL_HDR_SZ(pPager);
  40240. }
  40241. /* If there are active savepoints and any of them were created
  40242. ** since the most recent journal header was written, update the
  40243. ** PagerSavepoint.iHdrOffset fields now.
  40244. */
  40245. for(ii=0; ii<pPager->nSavepoint; ii++){
  40246. if( pPager->aSavepoint[ii].iHdrOffset==0 ){
  40247. pPager->aSavepoint[ii].iHdrOffset = pPager->journalOff;
  40248. }
  40249. }
  40250. pPager->journalHdr = pPager->journalOff = journalHdrOffset(pPager);
  40251. /*
  40252. ** Write the nRec Field - the number of page records that follow this
  40253. ** journal header. Normally, zero is written to this value at this time.
  40254. ** After the records are added to the journal (and the journal synced,
  40255. ** if in full-sync mode), the zero is overwritten with the true number
  40256. ** of records (see syncJournal()).
  40257. **
  40258. ** A faster alternative is to write 0xFFFFFFFF to the nRec field. When
  40259. ** reading the journal this value tells SQLite to assume that the
  40260. ** rest of the journal file contains valid page records. This assumption
  40261. ** is dangerous, as if a failure occurred whilst writing to the journal
  40262. ** file it may contain some garbage data. There are two scenarios
  40263. ** where this risk can be ignored:
  40264. **
  40265. ** * When the pager is in no-sync mode. Corruption can follow a
  40266. ** power failure in this case anyway.
  40267. **
  40268. ** * When the SQLITE_IOCAP_SAFE_APPEND flag is set. This guarantees
  40269. ** that garbage data is never appended to the journal file.
  40270. */
  40271. assert( isOpen(pPager->fd) || pPager->noSync );
  40272. if( pPager->noSync || (pPager->journalMode==PAGER_JOURNALMODE_MEMORY)
  40273. || (sqlite3OsDeviceCharacteristics(pPager->fd)&SQLITE_IOCAP_SAFE_APPEND)
  40274. ){
  40275. memcpy(zHeader, aJournalMagic, sizeof(aJournalMagic));
  40276. put32bits(&zHeader[sizeof(aJournalMagic)], 0xffffffff);
  40277. }else{
  40278. memset(zHeader, 0, sizeof(aJournalMagic)+4);
  40279. }
  40280. /* The random check-hash initializer */
  40281. sqlite3_randomness(sizeof(pPager->cksumInit), &pPager->cksumInit);
  40282. put32bits(&zHeader[sizeof(aJournalMagic)+4], pPager->cksumInit);
  40283. /* The initial database size */
  40284. put32bits(&zHeader[sizeof(aJournalMagic)+8], pPager->dbOrigSize);
  40285. /* The assumed sector size for this process */
  40286. put32bits(&zHeader[sizeof(aJournalMagic)+12], pPager->sectorSize);
  40287. /* The page size */
  40288. put32bits(&zHeader[sizeof(aJournalMagic)+16], pPager->pageSize);
  40289. /* Initializing the tail of the buffer is not necessary. Everything
  40290. ** works find if the following memset() is omitted. But initializing
  40291. ** the memory prevents valgrind from complaining, so we are willing to
  40292. ** take the performance hit.
  40293. */
  40294. memset(&zHeader[sizeof(aJournalMagic)+20], 0,
  40295. nHeader-(sizeof(aJournalMagic)+20));
  40296. /* In theory, it is only necessary to write the 28 bytes that the
  40297. ** journal header consumes to the journal file here. Then increment the
  40298. ** Pager.journalOff variable by JOURNAL_HDR_SZ so that the next
  40299. ** record is written to the following sector (leaving a gap in the file
  40300. ** that will be implicitly filled in by the OS).
  40301. **
  40302. ** However it has been discovered that on some systems this pattern can
  40303. ** be significantly slower than contiguously writing data to the file,
  40304. ** even if that means explicitly writing data to the block of
  40305. ** (JOURNAL_HDR_SZ - 28) bytes that will not be used. So that is what
  40306. ** is done.
  40307. **
  40308. ** The loop is required here in case the sector-size is larger than the
  40309. ** database page size. Since the zHeader buffer is only Pager.pageSize
  40310. ** bytes in size, more than one call to sqlite3OsWrite() may be required
  40311. ** to populate the entire journal header sector.
  40312. */
  40313. for(nWrite=0; rc==SQLITE_OK&&nWrite<JOURNAL_HDR_SZ(pPager); nWrite+=nHeader){
  40314. IOTRACE(("JHDR %p %lld %d\n", pPager, pPager->journalHdr, nHeader))
  40315. rc = sqlite3OsWrite(pPager->jfd, zHeader, nHeader, pPager->journalOff);
  40316. assert( pPager->journalHdr <= pPager->journalOff );
  40317. pPager->journalOff += nHeader;
  40318. }
  40319. return rc;
  40320. }
  40321. /*
  40322. ** The journal file must be open when this is called. A journal header file
  40323. ** (JOURNAL_HDR_SZ bytes) is read from the current location in the journal
  40324. ** file. The current location in the journal file is given by
  40325. ** pPager->journalOff. See comments above function writeJournalHdr() for
  40326. ** a description of the journal header format.
  40327. **
  40328. ** If the header is read successfully, *pNRec is set to the number of
  40329. ** page records following this header and *pDbSize is set to the size of the
  40330. ** database before the transaction began, in pages. Also, pPager->cksumInit
  40331. ** is set to the value read from the journal header. SQLITE_OK is returned
  40332. ** in this case.
  40333. **
  40334. ** If the journal header file appears to be corrupted, SQLITE_DONE is
  40335. ** returned and *pNRec and *PDbSize are undefined. If JOURNAL_HDR_SZ bytes
  40336. ** cannot be read from the journal file an error code is returned.
  40337. */
  40338. static int readJournalHdr(
  40339. Pager *pPager, /* Pager object */
  40340. int isHot,
  40341. i64 journalSize, /* Size of the open journal file in bytes */
  40342. u32 *pNRec, /* OUT: Value read from the nRec field */
  40343. u32 *pDbSize /* OUT: Value of original database size field */
  40344. ){
  40345. int rc; /* Return code */
  40346. unsigned char aMagic[8]; /* A buffer to hold the magic header */
  40347. i64 iHdrOff; /* Offset of journal header being read */
  40348. assert( isOpen(pPager->jfd) ); /* Journal file must be open. */
  40349. /* Advance Pager.journalOff to the start of the next sector. If the
  40350. ** journal file is too small for there to be a header stored at this
  40351. ** point, return SQLITE_DONE.
  40352. */
  40353. pPager->journalOff = journalHdrOffset(pPager);
  40354. if( pPager->journalOff+JOURNAL_HDR_SZ(pPager) > journalSize ){
  40355. return SQLITE_DONE;
  40356. }
  40357. iHdrOff = pPager->journalOff;
  40358. /* Read in the first 8 bytes of the journal header. If they do not match
  40359. ** the magic string found at the start of each journal header, return
  40360. ** SQLITE_DONE. If an IO error occurs, return an error code. Otherwise,
  40361. ** proceed.
  40362. */
  40363. if( isHot || iHdrOff!=pPager->journalHdr ){
  40364. rc = sqlite3OsRead(pPager->jfd, aMagic, sizeof(aMagic), iHdrOff);
  40365. if( rc ){
  40366. return rc;
  40367. }
  40368. if( memcmp(aMagic, aJournalMagic, sizeof(aMagic))!=0 ){
  40369. return SQLITE_DONE;
  40370. }
  40371. }
  40372. /* Read the first three 32-bit fields of the journal header: The nRec
  40373. ** field, the checksum-initializer and the database size at the start
  40374. ** of the transaction. Return an error code if anything goes wrong.
  40375. */
  40376. if( SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+8, pNRec))
  40377. || SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+12, &pPager->cksumInit))
  40378. || SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+16, pDbSize))
  40379. ){
  40380. return rc;
  40381. }
  40382. if( pPager->journalOff==0 ){
  40383. u32 iPageSize; /* Page-size field of journal header */
  40384. u32 iSectorSize; /* Sector-size field of journal header */
  40385. /* Read the page-size and sector-size journal header fields. */
  40386. if( SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+20, &iSectorSize))
  40387. || SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+24, &iPageSize))
  40388. ){
  40389. return rc;
  40390. }
  40391. /* Versions of SQLite prior to 3.5.8 set the page-size field of the
  40392. ** journal header to zero. In this case, assume that the Pager.pageSize
  40393. ** variable is already set to the correct page size.
  40394. */
  40395. if( iPageSize==0 ){
  40396. iPageSize = pPager->pageSize;
  40397. }
  40398. /* Check that the values read from the page-size and sector-size fields
  40399. ** are within range. To be 'in range', both values need to be a power
  40400. ** of two greater than or equal to 512 or 32, and not greater than their
  40401. ** respective compile time maximum limits.
  40402. */
  40403. if( iPageSize<512 || iSectorSize<32
  40404. || iPageSize>SQLITE_MAX_PAGE_SIZE || iSectorSize>MAX_SECTOR_SIZE
  40405. || ((iPageSize-1)&iPageSize)!=0 || ((iSectorSize-1)&iSectorSize)!=0
  40406. ){
  40407. /* If the either the page-size or sector-size in the journal-header is
  40408. ** invalid, then the process that wrote the journal-header must have
  40409. ** crashed before the header was synced. In this case stop reading
  40410. ** the journal file here.
  40411. */
  40412. return SQLITE_DONE;
  40413. }
  40414. /* Update the page-size to match the value read from the journal.
  40415. ** Use a testcase() macro to make sure that malloc failure within
  40416. ** PagerSetPagesize() is tested.
  40417. */
  40418. rc = sqlite3PagerSetPagesize(pPager, &iPageSize, -1);
  40419. testcase( rc!=SQLITE_OK );
  40420. /* Update the assumed sector-size to match the value used by
  40421. ** the process that created this journal. If this journal was
  40422. ** created by a process other than this one, then this routine
  40423. ** is being called from within pager_playback(). The local value
  40424. ** of Pager.sectorSize is restored at the end of that routine.
  40425. */
  40426. pPager->sectorSize = iSectorSize;
  40427. }
  40428. pPager->journalOff += JOURNAL_HDR_SZ(pPager);
  40429. return rc;
  40430. }
  40431. /*
  40432. ** Write the supplied master journal name into the journal file for pager
  40433. ** pPager at the current location. The master journal name must be the last
  40434. ** thing written to a journal file. If the pager is in full-sync mode, the
  40435. ** journal file descriptor is advanced to the next sector boundary before
  40436. ** anything is written. The format is:
  40437. **
  40438. ** + 4 bytes: PAGER_MJ_PGNO.
  40439. ** + N bytes: Master journal filename in utf-8.
  40440. ** + 4 bytes: N (length of master journal name in bytes, no nul-terminator).
  40441. ** + 4 bytes: Master journal name checksum.
  40442. ** + 8 bytes: aJournalMagic[].
  40443. **
  40444. ** The master journal page checksum is the sum of the bytes in the master
  40445. ** journal name, where each byte is interpreted as a signed 8-bit integer.
  40446. **
  40447. ** If zMaster is a NULL pointer (occurs for a single database transaction),
  40448. ** this call is a no-op.
  40449. */
  40450. static int writeMasterJournal(Pager *pPager, const char *zMaster){
  40451. int rc; /* Return code */
  40452. int nMaster; /* Length of string zMaster */
  40453. i64 iHdrOff; /* Offset of header in journal file */
  40454. i64 jrnlSize; /* Size of journal file on disk */
  40455. u32 cksum = 0; /* Checksum of string zMaster */
  40456. assert( pPager->setMaster==0 );
  40457. assert( !pagerUseWal(pPager) );
  40458. if( !zMaster
  40459. || pPager->journalMode==PAGER_JOURNALMODE_MEMORY
  40460. || !isOpen(pPager->jfd)
  40461. ){
  40462. return SQLITE_OK;
  40463. }
  40464. pPager->setMaster = 1;
  40465. assert( pPager->journalHdr <= pPager->journalOff );
  40466. /* Calculate the length in bytes and the checksum of zMaster */
  40467. for(nMaster=0; zMaster[nMaster]; nMaster++){
  40468. cksum += zMaster[nMaster];
  40469. }
  40470. /* If in full-sync mode, advance to the next disk sector before writing
  40471. ** the master journal name. This is in case the previous page written to
  40472. ** the journal has already been synced.
  40473. */
  40474. if( pPager->fullSync ){
  40475. pPager->journalOff = journalHdrOffset(pPager);
  40476. }
  40477. iHdrOff = pPager->journalOff;
  40478. /* Write the master journal data to the end of the journal file. If
  40479. ** an error occurs, return the error code to the caller.
  40480. */
  40481. if( (0 != (rc = write32bits(pPager->jfd, iHdrOff, PAGER_MJ_PGNO(pPager))))
  40482. || (0 != (rc = sqlite3OsWrite(pPager->jfd, zMaster, nMaster, iHdrOff+4)))
  40483. || (0 != (rc = write32bits(pPager->jfd, iHdrOff+4+nMaster, nMaster)))
  40484. || (0 != (rc = write32bits(pPager->jfd, iHdrOff+4+nMaster+4, cksum)))
  40485. || (0 != (rc = sqlite3OsWrite(pPager->jfd, aJournalMagic, 8, iHdrOff+4+nMaster+8)))
  40486. ){
  40487. return rc;
  40488. }
  40489. pPager->journalOff += (nMaster+20);
  40490. /* If the pager is in peristent-journal mode, then the physical
  40491. ** journal-file may extend past the end of the master-journal name
  40492. ** and 8 bytes of magic data just written to the file. This is
  40493. ** dangerous because the code to rollback a hot-journal file
  40494. ** will not be able to find the master-journal name to determine
  40495. ** whether or not the journal is hot.
  40496. **
  40497. ** Easiest thing to do in this scenario is to truncate the journal
  40498. ** file to the required size.
  40499. */
  40500. if( SQLITE_OK==(rc = sqlite3OsFileSize(pPager->jfd, &jrnlSize))
  40501. && jrnlSize>pPager->journalOff
  40502. ){
  40503. rc = sqlite3OsTruncate(pPager->jfd, pPager->journalOff);
  40504. }
  40505. return rc;
  40506. }
  40507. /*
  40508. ** Discard the entire contents of the in-memory page-cache.
  40509. */
  40510. static void pager_reset(Pager *pPager){
  40511. pPager->iDataVersion++;
  40512. sqlite3BackupRestart(pPager->pBackup);
  40513. sqlite3PcacheClear(pPager->pPCache);
  40514. }
  40515. /*
  40516. ** Return the pPager->iDataVersion value
  40517. */
  40518. SQLITE_PRIVATE u32 sqlite3PagerDataVersion(Pager *pPager){
  40519. assert( pPager->eState>PAGER_OPEN );
  40520. return pPager->iDataVersion;
  40521. }
  40522. /*
  40523. ** Free all structures in the Pager.aSavepoint[] array and set both
  40524. ** Pager.aSavepoint and Pager.nSavepoint to zero. Close the sub-journal
  40525. ** if it is open and the pager is not in exclusive mode.
  40526. */
  40527. static void releaseAllSavepoints(Pager *pPager){
  40528. int ii; /* Iterator for looping through Pager.aSavepoint */
  40529. for(ii=0; ii<pPager->nSavepoint; ii++){
  40530. sqlite3BitvecDestroy(pPager->aSavepoint[ii].pInSavepoint);
  40531. }
  40532. if( !pPager->exclusiveMode || sqlite3IsMemJournal(pPager->sjfd) ){
  40533. sqlite3OsClose(pPager->sjfd);
  40534. }
  40535. sqlite3_free(pPager->aSavepoint);
  40536. pPager->aSavepoint = 0;
  40537. pPager->nSavepoint = 0;
  40538. pPager->nSubRec = 0;
  40539. }
  40540. /*
  40541. ** Set the bit number pgno in the PagerSavepoint.pInSavepoint
  40542. ** bitvecs of all open savepoints. Return SQLITE_OK if successful
  40543. ** or SQLITE_NOMEM if a malloc failure occurs.
  40544. */
  40545. static int addToSavepointBitvecs(Pager *pPager, Pgno pgno){
  40546. int ii; /* Loop counter */
  40547. int rc = SQLITE_OK; /* Result code */
  40548. for(ii=0; ii<pPager->nSavepoint; ii++){
  40549. PagerSavepoint *p = &pPager->aSavepoint[ii];
  40550. if( pgno<=p->nOrig ){
  40551. rc |= sqlite3BitvecSet(p->pInSavepoint, pgno);
  40552. testcase( rc==SQLITE_NOMEM );
  40553. assert( rc==SQLITE_OK || rc==SQLITE_NOMEM );
  40554. }
  40555. }
  40556. return rc;
  40557. }
  40558. /*
  40559. ** This function is a no-op if the pager is in exclusive mode and not
  40560. ** in the ERROR state. Otherwise, it switches the pager to PAGER_OPEN
  40561. ** state.
  40562. **
  40563. ** If the pager is not in exclusive-access mode, the database file is
  40564. ** completely unlocked. If the file is unlocked and the file-system does
  40565. ** not exhibit the UNDELETABLE_WHEN_OPEN property, the journal file is
  40566. ** closed (if it is open).
  40567. **
  40568. ** If the pager is in ERROR state when this function is called, the
  40569. ** contents of the pager cache are discarded before switching back to
  40570. ** the OPEN state. Regardless of whether the pager is in exclusive-mode
  40571. ** or not, any journal file left in the file-system will be treated
  40572. ** as a hot-journal and rolled back the next time a read-transaction
  40573. ** is opened (by this or by any other connection).
  40574. */
  40575. static void pager_unlock(Pager *pPager){
  40576. assert( pPager->eState==PAGER_READER
  40577. || pPager->eState==PAGER_OPEN
  40578. || pPager->eState==PAGER_ERROR
  40579. );
  40580. sqlite3BitvecDestroy(pPager->pInJournal);
  40581. pPager->pInJournal = 0;
  40582. releaseAllSavepoints(pPager);
  40583. if( pagerUseWal(pPager) ){
  40584. assert( !isOpen(pPager->jfd) );
  40585. sqlite3WalEndReadTransaction(pPager->pWal);
  40586. pPager->eState = PAGER_OPEN;
  40587. }else if( !pPager->exclusiveMode ){
  40588. int rc; /* Error code returned by pagerUnlockDb() */
  40589. int iDc = isOpen(pPager->fd)?sqlite3OsDeviceCharacteristics(pPager->fd):0;
  40590. /* If the operating system support deletion of open files, then
  40591. ** close the journal file when dropping the database lock. Otherwise
  40592. ** another connection with journal_mode=delete might delete the file
  40593. ** out from under us.
  40594. */
  40595. assert( (PAGER_JOURNALMODE_MEMORY & 5)!=1 );
  40596. assert( (PAGER_JOURNALMODE_OFF & 5)!=1 );
  40597. assert( (PAGER_JOURNALMODE_WAL & 5)!=1 );
  40598. assert( (PAGER_JOURNALMODE_DELETE & 5)!=1 );
  40599. assert( (PAGER_JOURNALMODE_TRUNCATE & 5)==1 );
  40600. assert( (PAGER_JOURNALMODE_PERSIST & 5)==1 );
  40601. if( 0==(iDc & SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN)
  40602. || 1!=(pPager->journalMode & 5)
  40603. ){
  40604. sqlite3OsClose(pPager->jfd);
  40605. }
  40606. /* If the pager is in the ERROR state and the call to unlock the database
  40607. ** file fails, set the current lock to UNKNOWN_LOCK. See the comment
  40608. ** above the #define for UNKNOWN_LOCK for an explanation of why this
  40609. ** is necessary.
  40610. */
  40611. rc = pagerUnlockDb(pPager, NO_LOCK);
  40612. if( rc!=SQLITE_OK && pPager->eState==PAGER_ERROR ){
  40613. pPager->eLock = UNKNOWN_LOCK;
  40614. }
  40615. /* The pager state may be changed from PAGER_ERROR to PAGER_OPEN here
  40616. ** without clearing the error code. This is intentional - the error
  40617. ** code is cleared and the cache reset in the block below.
  40618. */
  40619. assert( pPager->errCode || pPager->eState!=PAGER_ERROR );
  40620. pPager->changeCountDone = 0;
  40621. pPager->eState = PAGER_OPEN;
  40622. }
  40623. /* If Pager.errCode is set, the contents of the pager cache cannot be
  40624. ** trusted. Now that there are no outstanding references to the pager,
  40625. ** it can safely move back to PAGER_OPEN state. This happens in both
  40626. ** normal and exclusive-locking mode.
  40627. */
  40628. if( pPager->errCode ){
  40629. assert( !MEMDB );
  40630. pager_reset(pPager);
  40631. pPager->changeCountDone = pPager->tempFile;
  40632. pPager->eState = PAGER_OPEN;
  40633. pPager->errCode = SQLITE_OK;
  40634. if( USEFETCH(pPager) ) sqlite3OsUnfetch(pPager->fd, 0, 0);
  40635. }
  40636. pPager->journalOff = 0;
  40637. pPager->journalHdr = 0;
  40638. pPager->setMaster = 0;
  40639. }
  40640. /*
  40641. ** This function is called whenever an IOERR or FULL error that requires
  40642. ** the pager to transition into the ERROR state may ahve occurred.
  40643. ** The first argument is a pointer to the pager structure, the second
  40644. ** the error-code about to be returned by a pager API function. The
  40645. ** value returned is a copy of the second argument to this function.
  40646. **
  40647. ** If the second argument is SQLITE_FULL, SQLITE_IOERR or one of the
  40648. ** IOERR sub-codes, the pager enters the ERROR state and the error code
  40649. ** is stored in Pager.errCode. While the pager remains in the ERROR state,
  40650. ** all major API calls on the Pager will immediately return Pager.errCode.
  40651. **
  40652. ** The ERROR state indicates that the contents of the pager-cache
  40653. ** cannot be trusted. This state can be cleared by completely discarding
  40654. ** the contents of the pager-cache. If a transaction was active when
  40655. ** the persistent error occurred, then the rollback journal may need
  40656. ** to be replayed to restore the contents of the database file (as if
  40657. ** it were a hot-journal).
  40658. */
  40659. static int pager_error(Pager *pPager, int rc){
  40660. int rc2 = rc & 0xff;
  40661. assert( rc==SQLITE_OK || !MEMDB );
  40662. assert(
  40663. pPager->errCode==SQLITE_FULL ||
  40664. pPager->errCode==SQLITE_OK ||
  40665. (pPager->errCode & 0xff)==SQLITE_IOERR
  40666. );
  40667. if( rc2==SQLITE_FULL || rc2==SQLITE_IOERR ){
  40668. pPager->errCode = rc;
  40669. pPager->eState = PAGER_ERROR;
  40670. }
  40671. return rc;
  40672. }
  40673. static int pager_truncate(Pager *pPager, Pgno nPage);
  40674. /*
  40675. ** This routine ends a transaction. A transaction is usually ended by
  40676. ** either a COMMIT or a ROLLBACK operation. This routine may be called
  40677. ** after rollback of a hot-journal, or if an error occurs while opening
  40678. ** the journal file or writing the very first journal-header of a
  40679. ** database transaction.
  40680. **
  40681. ** This routine is never called in PAGER_ERROR state. If it is called
  40682. ** in PAGER_NONE or PAGER_SHARED state and the lock held is less
  40683. ** exclusive than a RESERVED lock, it is a no-op.
  40684. **
  40685. ** Otherwise, any active savepoints are released.
  40686. **
  40687. ** If the journal file is open, then it is "finalized". Once a journal
  40688. ** file has been finalized it is not possible to use it to roll back a
  40689. ** transaction. Nor will it be considered to be a hot-journal by this
  40690. ** or any other database connection. Exactly how a journal is finalized
  40691. ** depends on whether or not the pager is running in exclusive mode and
  40692. ** the current journal-mode (Pager.journalMode value), as follows:
  40693. **
  40694. ** journalMode==MEMORY
  40695. ** Journal file descriptor is simply closed. This destroys an
  40696. ** in-memory journal.
  40697. **
  40698. ** journalMode==TRUNCATE
  40699. ** Journal file is truncated to zero bytes in size.
  40700. **
  40701. ** journalMode==PERSIST
  40702. ** The first 28 bytes of the journal file are zeroed. This invalidates
  40703. ** the first journal header in the file, and hence the entire journal
  40704. ** file. An invalid journal file cannot be rolled back.
  40705. **
  40706. ** journalMode==DELETE
  40707. ** The journal file is closed and deleted using sqlite3OsDelete().
  40708. **
  40709. ** If the pager is running in exclusive mode, this method of finalizing
  40710. ** the journal file is never used. Instead, if the journalMode is
  40711. ** DELETE and the pager is in exclusive mode, the method described under
  40712. ** journalMode==PERSIST is used instead.
  40713. **
  40714. ** After the journal is finalized, the pager moves to PAGER_READER state.
  40715. ** If running in non-exclusive rollback mode, the lock on the file is
  40716. ** downgraded to a SHARED_LOCK.
  40717. **
  40718. ** SQLITE_OK is returned if no error occurs. If an error occurs during
  40719. ** any of the IO operations to finalize the journal file or unlock the
  40720. ** database then the IO error code is returned to the user. If the
  40721. ** operation to finalize the journal file fails, then the code still
  40722. ** tries to unlock the database file if not in exclusive mode. If the
  40723. ** unlock operation fails as well, then the first error code related
  40724. ** to the first error encountered (the journal finalization one) is
  40725. ** returned.
  40726. */
  40727. static int pager_end_transaction(Pager *pPager, int hasMaster, int bCommit){
  40728. int rc = SQLITE_OK; /* Error code from journal finalization operation */
  40729. int rc2 = SQLITE_OK; /* Error code from db file unlock operation */
  40730. /* Do nothing if the pager does not have an open write transaction
  40731. ** or at least a RESERVED lock. This function may be called when there
  40732. ** is no write-transaction active but a RESERVED or greater lock is
  40733. ** held under two circumstances:
  40734. **
  40735. ** 1. After a successful hot-journal rollback, it is called with
  40736. ** eState==PAGER_NONE and eLock==EXCLUSIVE_LOCK.
  40737. **
  40738. ** 2. If a connection with locking_mode=exclusive holding an EXCLUSIVE
  40739. ** lock switches back to locking_mode=normal and then executes a
  40740. ** read-transaction, this function is called with eState==PAGER_READER
  40741. ** and eLock==EXCLUSIVE_LOCK when the read-transaction is closed.
  40742. */
  40743. assert( assert_pager_state(pPager) );
  40744. assert( pPager->eState!=PAGER_ERROR );
  40745. if( pPager->eState<PAGER_WRITER_LOCKED && pPager->eLock<RESERVED_LOCK ){
  40746. return SQLITE_OK;
  40747. }
  40748. releaseAllSavepoints(pPager);
  40749. assert( isOpen(pPager->jfd) || pPager->pInJournal==0 );
  40750. if( isOpen(pPager->jfd) ){
  40751. assert( !pagerUseWal(pPager) );
  40752. /* Finalize the journal file. */
  40753. if( sqlite3IsMemJournal(pPager->jfd) ){
  40754. assert( pPager->journalMode==PAGER_JOURNALMODE_MEMORY );
  40755. sqlite3OsClose(pPager->jfd);
  40756. }else if( pPager->journalMode==PAGER_JOURNALMODE_TRUNCATE ){
  40757. if( pPager->journalOff==0 ){
  40758. rc = SQLITE_OK;
  40759. }else{
  40760. rc = sqlite3OsTruncate(pPager->jfd, 0);
  40761. if( rc==SQLITE_OK && pPager->fullSync ){
  40762. /* Make sure the new file size is written into the inode right away.
  40763. ** Otherwise the journal might resurrect following a power loss and
  40764. ** cause the last transaction to roll back. See
  40765. ** https://bugzilla.mozilla.org/show_bug.cgi?id=1072773
  40766. */
  40767. rc = sqlite3OsSync(pPager->jfd, pPager->syncFlags);
  40768. }
  40769. }
  40770. pPager->journalOff = 0;
  40771. }else if( pPager->journalMode==PAGER_JOURNALMODE_PERSIST
  40772. || (pPager->exclusiveMode && pPager->journalMode!=PAGER_JOURNALMODE_WAL)
  40773. ){
  40774. rc = zeroJournalHdr(pPager, hasMaster);
  40775. pPager->journalOff = 0;
  40776. }else{
  40777. /* This branch may be executed with Pager.journalMode==MEMORY if
  40778. ** a hot-journal was just rolled back. In this case the journal
  40779. ** file should be closed and deleted. If this connection writes to
  40780. ** the database file, it will do so using an in-memory journal.
  40781. */
  40782. int bDelete = (!pPager->tempFile && sqlite3JournalExists(pPager->jfd));
  40783. assert( pPager->journalMode==PAGER_JOURNALMODE_DELETE
  40784. || pPager->journalMode==PAGER_JOURNALMODE_MEMORY
  40785. || pPager->journalMode==PAGER_JOURNALMODE_WAL
  40786. );
  40787. sqlite3OsClose(pPager->jfd);
  40788. if( bDelete ){
  40789. rc = sqlite3OsDelete(pPager->pVfs, pPager->zJournal, 0);
  40790. }
  40791. }
  40792. }
  40793. #ifdef SQLITE_CHECK_PAGES
  40794. sqlite3PcacheIterateDirty(pPager->pPCache, pager_set_pagehash);
  40795. if( pPager->dbSize==0 && sqlite3PcacheRefCount(pPager->pPCache)>0 ){
  40796. PgHdr *p = sqlite3PagerLookup(pPager, 1);
  40797. if( p ){
  40798. p->pageHash = 0;
  40799. sqlite3PagerUnrefNotNull(p);
  40800. }
  40801. }
  40802. #endif
  40803. sqlite3BitvecDestroy(pPager->pInJournal);
  40804. pPager->pInJournal = 0;
  40805. pPager->nRec = 0;
  40806. sqlite3PcacheCleanAll(pPager->pPCache);
  40807. sqlite3PcacheTruncate(pPager->pPCache, pPager->dbSize);
  40808. if( pagerUseWal(pPager) ){
  40809. /* Drop the WAL write-lock, if any. Also, if the connection was in
  40810. ** locking_mode=exclusive mode but is no longer, drop the EXCLUSIVE
  40811. ** lock held on the database file.
  40812. */
  40813. rc2 = sqlite3WalEndWriteTransaction(pPager->pWal);
  40814. assert( rc2==SQLITE_OK );
  40815. }else if( rc==SQLITE_OK && bCommit && pPager->dbFileSize>pPager->dbSize ){
  40816. /* This branch is taken when committing a transaction in rollback-journal
  40817. ** mode if the database file on disk is larger than the database image.
  40818. ** At this point the journal has been finalized and the transaction
  40819. ** successfully committed, but the EXCLUSIVE lock is still held on the
  40820. ** file. So it is safe to truncate the database file to its minimum
  40821. ** required size. */
  40822. assert( pPager->eLock==EXCLUSIVE_LOCK );
  40823. rc = pager_truncate(pPager, pPager->dbSize);
  40824. }
  40825. if( rc==SQLITE_OK && bCommit && isOpen(pPager->fd) ){
  40826. rc = sqlite3OsFileControl(pPager->fd, SQLITE_FCNTL_COMMIT_PHASETWO, 0);
  40827. if( rc==SQLITE_NOTFOUND ) rc = SQLITE_OK;
  40828. }
  40829. if( !pPager->exclusiveMode
  40830. && (!pagerUseWal(pPager) || sqlite3WalExclusiveMode(pPager->pWal, 0))
  40831. ){
  40832. rc2 = pagerUnlockDb(pPager, SHARED_LOCK);
  40833. pPager->changeCountDone = 0;
  40834. }
  40835. pPager->eState = PAGER_READER;
  40836. pPager->setMaster = 0;
  40837. return (rc==SQLITE_OK?rc2:rc);
  40838. }
  40839. /*
  40840. ** Execute a rollback if a transaction is active and unlock the
  40841. ** database file.
  40842. **
  40843. ** If the pager has already entered the ERROR state, do not attempt
  40844. ** the rollback at this time. Instead, pager_unlock() is called. The
  40845. ** call to pager_unlock() will discard all in-memory pages, unlock
  40846. ** the database file and move the pager back to OPEN state. If this
  40847. ** means that there is a hot-journal left in the file-system, the next
  40848. ** connection to obtain a shared lock on the pager (which may be this one)
  40849. ** will roll it back.
  40850. **
  40851. ** If the pager has not already entered the ERROR state, but an IO or
  40852. ** malloc error occurs during a rollback, then this will itself cause
  40853. ** the pager to enter the ERROR state. Which will be cleared by the
  40854. ** call to pager_unlock(), as described above.
  40855. */
  40856. static void pagerUnlockAndRollback(Pager *pPager){
  40857. if( pPager->eState!=PAGER_ERROR && pPager->eState!=PAGER_OPEN ){
  40858. assert( assert_pager_state(pPager) );
  40859. if( pPager->eState>=PAGER_WRITER_LOCKED ){
  40860. sqlite3BeginBenignMalloc();
  40861. sqlite3PagerRollback(pPager);
  40862. sqlite3EndBenignMalloc();
  40863. }else if( !pPager->exclusiveMode ){
  40864. assert( pPager->eState==PAGER_READER );
  40865. pager_end_transaction(pPager, 0, 0);
  40866. }
  40867. }
  40868. pager_unlock(pPager);
  40869. }
  40870. /*
  40871. ** Parameter aData must point to a buffer of pPager->pageSize bytes
  40872. ** of data. Compute and return a checksum based ont the contents of the
  40873. ** page of data and the current value of pPager->cksumInit.
  40874. **
  40875. ** This is not a real checksum. It is really just the sum of the
  40876. ** random initial value (pPager->cksumInit) and every 200th byte
  40877. ** of the page data, starting with byte offset (pPager->pageSize%200).
  40878. ** Each byte is interpreted as an 8-bit unsigned integer.
  40879. **
  40880. ** Changing the formula used to compute this checksum results in an
  40881. ** incompatible journal file format.
  40882. **
  40883. ** If journal corruption occurs due to a power failure, the most likely
  40884. ** scenario is that one end or the other of the record will be changed.
  40885. ** It is much less likely that the two ends of the journal record will be
  40886. ** correct and the middle be corrupt. Thus, this "checksum" scheme,
  40887. ** though fast and simple, catches the mostly likely kind of corruption.
  40888. */
  40889. static u32 pager_cksum(Pager *pPager, const u8 *aData){
  40890. u32 cksum = pPager->cksumInit; /* Checksum value to return */
  40891. int i = pPager->pageSize-200; /* Loop counter */
  40892. while( i>0 ){
  40893. cksum += aData[i];
  40894. i -= 200;
  40895. }
  40896. return cksum;
  40897. }
  40898. /*
  40899. ** Report the current page size and number of reserved bytes back
  40900. ** to the codec.
  40901. */
  40902. #ifdef SQLITE_HAS_CODEC
  40903. static void pagerReportSize(Pager *pPager){
  40904. if( pPager->xCodecSizeChng ){
  40905. pPager->xCodecSizeChng(pPager->pCodec, pPager->pageSize,
  40906. (int)pPager->nReserve);
  40907. }
  40908. }
  40909. #else
  40910. # define pagerReportSize(X) /* No-op if we do not support a codec */
  40911. #endif
  40912. /*
  40913. ** Read a single page from either the journal file (if isMainJrnl==1) or
  40914. ** from the sub-journal (if isMainJrnl==0) and playback that page.
  40915. ** The page begins at offset *pOffset into the file. The *pOffset
  40916. ** value is increased to the start of the next page in the journal.
  40917. **
  40918. ** The main rollback journal uses checksums - the statement journal does
  40919. ** not.
  40920. **
  40921. ** If the page number of the page record read from the (sub-)journal file
  40922. ** is greater than the current value of Pager.dbSize, then playback is
  40923. ** skipped and SQLITE_OK is returned.
  40924. **
  40925. ** If pDone is not NULL, then it is a record of pages that have already
  40926. ** been played back. If the page at *pOffset has already been played back
  40927. ** (if the corresponding pDone bit is set) then skip the playback.
  40928. ** Make sure the pDone bit corresponding to the *pOffset page is set
  40929. ** prior to returning.
  40930. **
  40931. ** If the page record is successfully read from the (sub-)journal file
  40932. ** and played back, then SQLITE_OK is returned. If an IO error occurs
  40933. ** while reading the record from the (sub-)journal file or while writing
  40934. ** to the database file, then the IO error code is returned. If data
  40935. ** is successfully read from the (sub-)journal file but appears to be
  40936. ** corrupted, SQLITE_DONE is returned. Data is considered corrupted in
  40937. ** two circumstances:
  40938. **
  40939. ** * If the record page-number is illegal (0 or PAGER_MJ_PGNO), or
  40940. ** * If the record is being rolled back from the main journal file
  40941. ** and the checksum field does not match the record content.
  40942. **
  40943. ** Neither of these two scenarios are possible during a savepoint rollback.
  40944. **
  40945. ** If this is a savepoint rollback, then memory may have to be dynamically
  40946. ** allocated by this function. If this is the case and an allocation fails,
  40947. ** SQLITE_NOMEM is returned.
  40948. */
  40949. static int pager_playback_one_page(
  40950. Pager *pPager, /* The pager being played back */
  40951. i64 *pOffset, /* Offset of record to playback */
  40952. Bitvec *pDone, /* Bitvec of pages already played back */
  40953. int isMainJrnl, /* 1 -> main journal. 0 -> sub-journal. */
  40954. int isSavepnt /* True for a savepoint rollback */
  40955. ){
  40956. int rc;
  40957. PgHdr *pPg; /* An existing page in the cache */
  40958. Pgno pgno; /* The page number of a page in journal */
  40959. u32 cksum; /* Checksum used for sanity checking */
  40960. char *aData; /* Temporary storage for the page */
  40961. sqlite3_file *jfd; /* The file descriptor for the journal file */
  40962. int isSynced; /* True if journal page is synced */
  40963. assert( (isMainJrnl&~1)==0 ); /* isMainJrnl is 0 or 1 */
  40964. assert( (isSavepnt&~1)==0 ); /* isSavepnt is 0 or 1 */
  40965. assert( isMainJrnl || pDone ); /* pDone always used on sub-journals */
  40966. assert( isSavepnt || pDone==0 ); /* pDone never used on non-savepoint */
  40967. aData = pPager->pTmpSpace;
  40968. assert( aData ); /* Temp storage must have already been allocated */
  40969. assert( pagerUseWal(pPager)==0 || (!isMainJrnl && isSavepnt) );
  40970. /* Either the state is greater than PAGER_WRITER_CACHEMOD (a transaction
  40971. ** or savepoint rollback done at the request of the caller) or this is
  40972. ** a hot-journal rollback. If it is a hot-journal rollback, the pager
  40973. ** is in state OPEN and holds an EXCLUSIVE lock. Hot-journal rollback
  40974. ** only reads from the main journal, not the sub-journal.
  40975. */
  40976. assert( pPager->eState>=PAGER_WRITER_CACHEMOD
  40977. || (pPager->eState==PAGER_OPEN && pPager->eLock==EXCLUSIVE_LOCK)
  40978. );
  40979. assert( pPager->eState>=PAGER_WRITER_CACHEMOD || isMainJrnl );
  40980. /* Read the page number and page data from the journal or sub-journal
  40981. ** file. Return an error code to the caller if an IO error occurs.
  40982. */
  40983. jfd = isMainJrnl ? pPager->jfd : pPager->sjfd;
  40984. rc = read32bits(jfd, *pOffset, &pgno);
  40985. if( rc!=SQLITE_OK ) return rc;
  40986. rc = sqlite3OsRead(jfd, (u8*)aData, pPager->pageSize, (*pOffset)+4);
  40987. if( rc!=SQLITE_OK ) return rc;
  40988. *pOffset += pPager->pageSize + 4 + isMainJrnl*4;
  40989. /* Sanity checking on the page. This is more important that I originally
  40990. ** thought. If a power failure occurs while the journal is being written,
  40991. ** it could cause invalid data to be written into the journal. We need to
  40992. ** detect this invalid data (with high probability) and ignore it.
  40993. */
  40994. if( pgno==0 || pgno==PAGER_MJ_PGNO(pPager) ){
  40995. assert( !isSavepnt );
  40996. return SQLITE_DONE;
  40997. }
  40998. if( pgno>(Pgno)pPager->dbSize || sqlite3BitvecTest(pDone, pgno) ){
  40999. return SQLITE_OK;
  41000. }
  41001. if( isMainJrnl ){
  41002. rc = read32bits(jfd, (*pOffset)-4, &cksum);
  41003. if( rc ) return rc;
  41004. if( !isSavepnt && pager_cksum(pPager, (u8*)aData)!=cksum ){
  41005. return SQLITE_DONE;
  41006. }
  41007. }
  41008. /* If this page has already been played by before during the current
  41009. ** rollback, then don't bother to play it back again.
  41010. */
  41011. if( pDone && (rc = sqlite3BitvecSet(pDone, pgno))!=SQLITE_OK ){
  41012. return rc;
  41013. }
  41014. /* When playing back page 1, restore the nReserve setting
  41015. */
  41016. if( pgno==1 && pPager->nReserve!=((u8*)aData)[20] ){
  41017. pPager->nReserve = ((u8*)aData)[20];
  41018. pagerReportSize(pPager);
  41019. }
  41020. /* If the pager is in CACHEMOD state, then there must be a copy of this
  41021. ** page in the pager cache. In this case just update the pager cache,
  41022. ** not the database file. The page is left marked dirty in this case.
  41023. **
  41024. ** An exception to the above rule: If the database is in no-sync mode
  41025. ** and a page is moved during an incremental vacuum then the page may
  41026. ** not be in the pager cache. Later: if a malloc() or IO error occurs
  41027. ** during a Movepage() call, then the page may not be in the cache
  41028. ** either. So the condition described in the above paragraph is not
  41029. ** assert()able.
  41030. **
  41031. ** If in WRITER_DBMOD, WRITER_FINISHED or OPEN state, then we update the
  41032. ** pager cache if it exists and the main file. The page is then marked
  41033. ** not dirty. Since this code is only executed in PAGER_OPEN state for
  41034. ** a hot-journal rollback, it is guaranteed that the page-cache is empty
  41035. ** if the pager is in OPEN state.
  41036. **
  41037. ** Ticket #1171: The statement journal might contain page content that is
  41038. ** different from the page content at the start of the transaction.
  41039. ** This occurs when a page is changed prior to the start of a statement
  41040. ** then changed again within the statement. When rolling back such a
  41041. ** statement we must not write to the original database unless we know
  41042. ** for certain that original page contents are synced into the main rollback
  41043. ** journal. Otherwise, a power loss might leave modified data in the
  41044. ** database file without an entry in the rollback journal that can
  41045. ** restore the database to its original form. Two conditions must be
  41046. ** met before writing to the database files. (1) the database must be
  41047. ** locked. (2) we know that the original page content is fully synced
  41048. ** in the main journal either because the page is not in cache or else
  41049. ** the page is marked as needSync==0.
  41050. **
  41051. ** 2008-04-14: When attempting to vacuum a corrupt database file, it
  41052. ** is possible to fail a statement on a database that does not yet exist.
  41053. ** Do not attempt to write if database file has never been opened.
  41054. */
  41055. if( pagerUseWal(pPager) ){
  41056. pPg = 0;
  41057. }else{
  41058. pPg = sqlite3PagerLookup(pPager, pgno);
  41059. }
  41060. assert( pPg || !MEMDB );
  41061. assert( pPager->eState!=PAGER_OPEN || pPg==0 );
  41062. PAGERTRACE(("PLAYBACK %d page %d hash(%08x) %s\n",
  41063. PAGERID(pPager), pgno, pager_datahash(pPager->pageSize, (u8*)aData),
  41064. (isMainJrnl?"main-journal":"sub-journal")
  41065. ));
  41066. if( isMainJrnl ){
  41067. isSynced = pPager->noSync || (*pOffset <= pPager->journalHdr);
  41068. }else{
  41069. isSynced = (pPg==0 || 0==(pPg->flags & PGHDR_NEED_SYNC));
  41070. }
  41071. if( isOpen(pPager->fd)
  41072. && (pPager->eState>=PAGER_WRITER_DBMOD || pPager->eState==PAGER_OPEN)
  41073. && isSynced
  41074. ){
  41075. i64 ofst = (pgno-1)*(i64)pPager->pageSize;
  41076. testcase( !isSavepnt && pPg!=0 && (pPg->flags&PGHDR_NEED_SYNC)!=0 );
  41077. assert( !pagerUseWal(pPager) );
  41078. rc = sqlite3OsWrite(pPager->fd, (u8 *)aData, pPager->pageSize, ofst);
  41079. if( pgno>pPager->dbFileSize ){
  41080. pPager->dbFileSize = pgno;
  41081. }
  41082. if( pPager->pBackup ){
  41083. CODEC1(pPager, aData, pgno, 3, rc=SQLITE_NOMEM);
  41084. sqlite3BackupUpdate(pPager->pBackup, pgno, (u8*)aData);
  41085. CODEC2(pPager, aData, pgno, 7, rc=SQLITE_NOMEM, aData);
  41086. }
  41087. }else if( !isMainJrnl && pPg==0 ){
  41088. /* If this is a rollback of a savepoint and data was not written to
  41089. ** the database and the page is not in-memory, there is a potential
  41090. ** problem. When the page is next fetched by the b-tree layer, it
  41091. ** will be read from the database file, which may or may not be
  41092. ** current.
  41093. **
  41094. ** There are a couple of different ways this can happen. All are quite
  41095. ** obscure. When running in synchronous mode, this can only happen
  41096. ** if the page is on the free-list at the start of the transaction, then
  41097. ** populated, then moved using sqlite3PagerMovepage().
  41098. **
  41099. ** The solution is to add an in-memory page to the cache containing
  41100. ** the data just read from the sub-journal. Mark the page as dirty
  41101. ** and if the pager requires a journal-sync, then mark the page as
  41102. ** requiring a journal-sync before it is written.
  41103. */
  41104. assert( isSavepnt );
  41105. assert( (pPager->doNotSpill & SPILLFLAG_ROLLBACK)==0 );
  41106. pPager->doNotSpill |= SPILLFLAG_ROLLBACK;
  41107. rc = sqlite3PagerAcquire(pPager, pgno, &pPg, 1);
  41108. assert( (pPager->doNotSpill & SPILLFLAG_ROLLBACK)!=0 );
  41109. pPager->doNotSpill &= ~SPILLFLAG_ROLLBACK;
  41110. if( rc!=SQLITE_OK ) return rc;
  41111. pPg->flags &= ~PGHDR_NEED_READ;
  41112. sqlite3PcacheMakeDirty(pPg);
  41113. }
  41114. if( pPg ){
  41115. /* No page should ever be explicitly rolled back that is in use, except
  41116. ** for page 1 which is held in use in order to keep the lock on the
  41117. ** database active. However such a page may be rolled back as a result
  41118. ** of an internal error resulting in an automatic call to
  41119. ** sqlite3PagerRollback().
  41120. */
  41121. void *pData;
  41122. pData = pPg->pData;
  41123. memcpy(pData, (u8*)aData, pPager->pageSize);
  41124. pPager->xReiniter(pPg);
  41125. if( isMainJrnl && (!isSavepnt || *pOffset<=pPager->journalHdr) ){
  41126. /* If the contents of this page were just restored from the main
  41127. ** journal file, then its content must be as they were when the
  41128. ** transaction was first opened. In this case we can mark the page
  41129. ** as clean, since there will be no need to write it out to the
  41130. ** database.
  41131. **
  41132. ** There is one exception to this rule. If the page is being rolled
  41133. ** back as part of a savepoint (or statement) rollback from an
  41134. ** unsynced portion of the main journal file, then it is not safe
  41135. ** to mark the page as clean. This is because marking the page as
  41136. ** clean will clear the PGHDR_NEED_SYNC flag. Since the page is
  41137. ** already in the journal file (recorded in Pager.pInJournal) and
  41138. ** the PGHDR_NEED_SYNC flag is cleared, if the page is written to
  41139. ** again within this transaction, it will be marked as dirty but
  41140. ** the PGHDR_NEED_SYNC flag will not be set. It could then potentially
  41141. ** be written out into the database file before its journal file
  41142. ** segment is synced. If a crash occurs during or following this,
  41143. ** database corruption may ensue.
  41144. */
  41145. assert( !pagerUseWal(pPager) );
  41146. sqlite3PcacheMakeClean(pPg);
  41147. }
  41148. pager_set_pagehash(pPg);
  41149. /* If this was page 1, then restore the value of Pager.dbFileVers.
  41150. ** Do this before any decoding. */
  41151. if( pgno==1 ){
  41152. memcpy(&pPager->dbFileVers, &((u8*)pData)[24],sizeof(pPager->dbFileVers));
  41153. }
  41154. /* Decode the page just read from disk */
  41155. CODEC1(pPager, pData, pPg->pgno, 3, rc=SQLITE_NOMEM);
  41156. sqlite3PcacheRelease(pPg);
  41157. }
  41158. return rc;
  41159. }
  41160. /*
  41161. ** Parameter zMaster is the name of a master journal file. A single journal
  41162. ** file that referred to the master journal file has just been rolled back.
  41163. ** This routine checks if it is possible to delete the master journal file,
  41164. ** and does so if it is.
  41165. **
  41166. ** Argument zMaster may point to Pager.pTmpSpace. So that buffer is not
  41167. ** available for use within this function.
  41168. **
  41169. ** When a master journal file is created, it is populated with the names
  41170. ** of all of its child journals, one after another, formatted as utf-8
  41171. ** encoded text. The end of each child journal file is marked with a
  41172. ** nul-terminator byte (0x00). i.e. the entire contents of a master journal
  41173. ** file for a transaction involving two databases might be:
  41174. **
  41175. ** "/home/bill/a.db-journal\x00/home/bill/b.db-journal\x00"
  41176. **
  41177. ** A master journal file may only be deleted once all of its child
  41178. ** journals have been rolled back.
  41179. **
  41180. ** This function reads the contents of the master-journal file into
  41181. ** memory and loops through each of the child journal names. For
  41182. ** each child journal, it checks if:
  41183. **
  41184. ** * if the child journal exists, and if so
  41185. ** * if the child journal contains a reference to master journal
  41186. ** file zMaster
  41187. **
  41188. ** If a child journal can be found that matches both of the criteria
  41189. ** above, this function returns without doing anything. Otherwise, if
  41190. ** no such child journal can be found, file zMaster is deleted from
  41191. ** the file-system using sqlite3OsDelete().
  41192. **
  41193. ** If an IO error within this function, an error code is returned. This
  41194. ** function allocates memory by calling sqlite3Malloc(). If an allocation
  41195. ** fails, SQLITE_NOMEM is returned. Otherwise, if no IO or malloc errors
  41196. ** occur, SQLITE_OK is returned.
  41197. **
  41198. ** TODO: This function allocates a single block of memory to load
  41199. ** the entire contents of the master journal file. This could be
  41200. ** a couple of kilobytes or so - potentially larger than the page
  41201. ** size.
  41202. */
  41203. static int pager_delmaster(Pager *pPager, const char *zMaster){
  41204. sqlite3_vfs *pVfs = pPager->pVfs;
  41205. int rc; /* Return code */
  41206. sqlite3_file *pMaster; /* Malloc'd master-journal file descriptor */
  41207. sqlite3_file *pJournal; /* Malloc'd child-journal file descriptor */
  41208. char *zMasterJournal = 0; /* Contents of master journal file */
  41209. i64 nMasterJournal; /* Size of master journal file */
  41210. char *zJournal; /* Pointer to one journal within MJ file */
  41211. char *zMasterPtr; /* Space to hold MJ filename from a journal file */
  41212. int nMasterPtr; /* Amount of space allocated to zMasterPtr[] */
  41213. /* Allocate space for both the pJournal and pMaster file descriptors.
  41214. ** If successful, open the master journal file for reading.
  41215. */
  41216. pMaster = (sqlite3_file *)sqlite3MallocZero(pVfs->szOsFile * 2);
  41217. pJournal = (sqlite3_file *)(((u8 *)pMaster) + pVfs->szOsFile);
  41218. if( !pMaster ){
  41219. rc = SQLITE_NOMEM;
  41220. }else{
  41221. const int flags = (SQLITE_OPEN_READONLY|SQLITE_OPEN_MASTER_JOURNAL);
  41222. rc = sqlite3OsOpen(pVfs, zMaster, pMaster, flags, 0);
  41223. }
  41224. if( rc!=SQLITE_OK ) goto delmaster_out;
  41225. /* Load the entire master journal file into space obtained from
  41226. ** sqlite3_malloc() and pointed to by zMasterJournal. Also obtain
  41227. ** sufficient space (in zMasterPtr) to hold the names of master
  41228. ** journal files extracted from regular rollback-journals.
  41229. */
  41230. rc = sqlite3OsFileSize(pMaster, &nMasterJournal);
  41231. if( rc!=SQLITE_OK ) goto delmaster_out;
  41232. nMasterPtr = pVfs->mxPathname+1;
  41233. zMasterJournal = sqlite3Malloc(nMasterJournal + nMasterPtr + 1);
  41234. if( !zMasterJournal ){
  41235. rc = SQLITE_NOMEM;
  41236. goto delmaster_out;
  41237. }
  41238. zMasterPtr = &zMasterJournal[nMasterJournal+1];
  41239. rc = sqlite3OsRead(pMaster, zMasterJournal, (int)nMasterJournal, 0);
  41240. if( rc!=SQLITE_OK ) goto delmaster_out;
  41241. zMasterJournal[nMasterJournal] = 0;
  41242. zJournal = zMasterJournal;
  41243. while( (zJournal-zMasterJournal)<nMasterJournal ){
  41244. int exists;
  41245. rc = sqlite3OsAccess(pVfs, zJournal, SQLITE_ACCESS_EXISTS, &exists);
  41246. if( rc!=SQLITE_OK ){
  41247. goto delmaster_out;
  41248. }
  41249. if( exists ){
  41250. /* One of the journals pointed to by the master journal exists.
  41251. ** Open it and check if it points at the master journal. If
  41252. ** so, return without deleting the master journal file.
  41253. */
  41254. int c;
  41255. int flags = (SQLITE_OPEN_READONLY|SQLITE_OPEN_MAIN_JOURNAL);
  41256. rc = sqlite3OsOpen(pVfs, zJournal, pJournal, flags, 0);
  41257. if( rc!=SQLITE_OK ){
  41258. goto delmaster_out;
  41259. }
  41260. rc = readMasterJournal(pJournal, zMasterPtr, nMasterPtr);
  41261. sqlite3OsClose(pJournal);
  41262. if( rc!=SQLITE_OK ){
  41263. goto delmaster_out;
  41264. }
  41265. c = zMasterPtr[0]!=0 && strcmp(zMasterPtr, zMaster)==0;
  41266. if( c ){
  41267. /* We have a match. Do not delete the master journal file. */
  41268. goto delmaster_out;
  41269. }
  41270. }
  41271. zJournal += (sqlite3Strlen30(zJournal)+1);
  41272. }
  41273. sqlite3OsClose(pMaster);
  41274. rc = sqlite3OsDelete(pVfs, zMaster, 0);
  41275. delmaster_out:
  41276. sqlite3_free(zMasterJournal);
  41277. if( pMaster ){
  41278. sqlite3OsClose(pMaster);
  41279. assert( !isOpen(pJournal) );
  41280. sqlite3_free(pMaster);
  41281. }
  41282. return rc;
  41283. }
  41284. /*
  41285. ** This function is used to change the actual size of the database
  41286. ** file in the file-system. This only happens when committing a transaction,
  41287. ** or rolling back a transaction (including rolling back a hot-journal).
  41288. **
  41289. ** If the main database file is not open, or the pager is not in either
  41290. ** DBMOD or OPEN state, this function is a no-op. Otherwise, the size
  41291. ** of the file is changed to nPage pages (nPage*pPager->pageSize bytes).
  41292. ** If the file on disk is currently larger than nPage pages, then use the VFS
  41293. ** xTruncate() method to truncate it.
  41294. **
  41295. ** Or, it might be the case that the file on disk is smaller than
  41296. ** nPage pages. Some operating system implementations can get confused if
  41297. ** you try to truncate a file to some size that is larger than it
  41298. ** currently is, so detect this case and write a single zero byte to
  41299. ** the end of the new file instead.
  41300. **
  41301. ** If successful, return SQLITE_OK. If an IO error occurs while modifying
  41302. ** the database file, return the error code to the caller.
  41303. */
  41304. static int pager_truncate(Pager *pPager, Pgno nPage){
  41305. int rc = SQLITE_OK;
  41306. assert( pPager->eState!=PAGER_ERROR );
  41307. assert( pPager->eState!=PAGER_READER );
  41308. if( isOpen(pPager->fd)
  41309. && (pPager->eState>=PAGER_WRITER_DBMOD || pPager->eState==PAGER_OPEN)
  41310. ){
  41311. i64 currentSize, newSize;
  41312. int szPage = pPager->pageSize;
  41313. assert( pPager->eLock==EXCLUSIVE_LOCK );
  41314. /* TODO: Is it safe to use Pager.dbFileSize here? */
  41315. rc = sqlite3OsFileSize(pPager->fd, &currentSize);
  41316. newSize = szPage*(i64)nPage;
  41317. if( rc==SQLITE_OK && currentSize!=newSize ){
  41318. if( currentSize>newSize ){
  41319. rc = sqlite3OsTruncate(pPager->fd, newSize);
  41320. }else if( (currentSize+szPage)<=newSize ){
  41321. char *pTmp = pPager->pTmpSpace;
  41322. memset(pTmp, 0, szPage);
  41323. testcase( (newSize-szPage) == currentSize );
  41324. testcase( (newSize-szPage) > currentSize );
  41325. rc = sqlite3OsWrite(pPager->fd, pTmp, szPage, newSize-szPage);
  41326. }
  41327. if( rc==SQLITE_OK ){
  41328. pPager->dbFileSize = nPage;
  41329. }
  41330. }
  41331. }
  41332. return rc;
  41333. }
  41334. /*
  41335. ** Return a sanitized version of the sector-size of OS file pFile. The
  41336. ** return value is guaranteed to lie between 32 and MAX_SECTOR_SIZE.
  41337. */
  41338. SQLITE_PRIVATE int sqlite3SectorSize(sqlite3_file *pFile){
  41339. int iRet = sqlite3OsSectorSize(pFile);
  41340. if( iRet<32 ){
  41341. iRet = 512;
  41342. }else if( iRet>MAX_SECTOR_SIZE ){
  41343. assert( MAX_SECTOR_SIZE>=512 );
  41344. iRet = MAX_SECTOR_SIZE;
  41345. }
  41346. return iRet;
  41347. }
  41348. /*
  41349. ** Set the value of the Pager.sectorSize variable for the given
  41350. ** pager based on the value returned by the xSectorSize method
  41351. ** of the open database file. The sector size will be used
  41352. ** to determine the size and alignment of journal header and
  41353. ** master journal pointers within created journal files.
  41354. **
  41355. ** For temporary files the effective sector size is always 512 bytes.
  41356. **
  41357. ** Otherwise, for non-temporary files, the effective sector size is
  41358. ** the value returned by the xSectorSize() method rounded up to 32 if
  41359. ** it is less than 32, or rounded down to MAX_SECTOR_SIZE if it
  41360. ** is greater than MAX_SECTOR_SIZE.
  41361. **
  41362. ** If the file has the SQLITE_IOCAP_POWERSAFE_OVERWRITE property, then set
  41363. ** the effective sector size to its minimum value (512). The purpose of
  41364. ** pPager->sectorSize is to define the "blast radius" of bytes that
  41365. ** might change if a crash occurs while writing to a single byte in
  41366. ** that range. But with POWERSAFE_OVERWRITE, the blast radius is zero
  41367. ** (that is what POWERSAFE_OVERWRITE means), so we minimize the sector
  41368. ** size. For backwards compatibility of the rollback journal file format,
  41369. ** we cannot reduce the effective sector size below 512.
  41370. */
  41371. static void setSectorSize(Pager *pPager){
  41372. assert( isOpen(pPager->fd) || pPager->tempFile );
  41373. if( pPager->tempFile
  41374. || (sqlite3OsDeviceCharacteristics(pPager->fd) &
  41375. SQLITE_IOCAP_POWERSAFE_OVERWRITE)!=0
  41376. ){
  41377. /* Sector size doesn't matter for temporary files. Also, the file
  41378. ** may not have been opened yet, in which case the OsSectorSize()
  41379. ** call will segfault. */
  41380. pPager->sectorSize = 512;
  41381. }else{
  41382. pPager->sectorSize = sqlite3SectorSize(pPager->fd);
  41383. }
  41384. }
  41385. /*
  41386. ** Playback the journal and thus restore the database file to
  41387. ** the state it was in before we started making changes.
  41388. **
  41389. ** The journal file format is as follows:
  41390. **
  41391. ** (1) 8 byte prefix. A copy of aJournalMagic[].
  41392. ** (2) 4 byte big-endian integer which is the number of valid page records
  41393. ** in the journal. If this value is 0xffffffff, then compute the
  41394. ** number of page records from the journal size.
  41395. ** (3) 4 byte big-endian integer which is the initial value for the
  41396. ** sanity checksum.
  41397. ** (4) 4 byte integer which is the number of pages to truncate the
  41398. ** database to during a rollback.
  41399. ** (5) 4 byte big-endian integer which is the sector size. The header
  41400. ** is this many bytes in size.
  41401. ** (6) 4 byte big-endian integer which is the page size.
  41402. ** (7) zero padding out to the next sector size.
  41403. ** (8) Zero or more pages instances, each as follows:
  41404. ** + 4 byte page number.
  41405. ** + pPager->pageSize bytes of data.
  41406. ** + 4 byte checksum
  41407. **
  41408. ** When we speak of the journal header, we mean the first 7 items above.
  41409. ** Each entry in the journal is an instance of the 8th item.
  41410. **
  41411. ** Call the value from the second bullet "nRec". nRec is the number of
  41412. ** valid page entries in the journal. In most cases, you can compute the
  41413. ** value of nRec from the size of the journal file. But if a power
  41414. ** failure occurred while the journal was being written, it could be the
  41415. ** case that the size of the journal file had already been increased but
  41416. ** the extra entries had not yet made it safely to disk. In such a case,
  41417. ** the value of nRec computed from the file size would be too large. For
  41418. ** that reason, we always use the nRec value in the header.
  41419. **
  41420. ** If the nRec value is 0xffffffff it means that nRec should be computed
  41421. ** from the file size. This value is used when the user selects the
  41422. ** no-sync option for the journal. A power failure could lead to corruption
  41423. ** in this case. But for things like temporary table (which will be
  41424. ** deleted when the power is restored) we don't care.
  41425. **
  41426. ** If the file opened as the journal file is not a well-formed
  41427. ** journal file then all pages up to the first corrupted page are rolled
  41428. ** back (or no pages if the journal header is corrupted). The journal file
  41429. ** is then deleted and SQLITE_OK returned, just as if no corruption had
  41430. ** been encountered.
  41431. **
  41432. ** If an I/O or malloc() error occurs, the journal-file is not deleted
  41433. ** and an error code is returned.
  41434. **
  41435. ** The isHot parameter indicates that we are trying to rollback a journal
  41436. ** that might be a hot journal. Or, it could be that the journal is
  41437. ** preserved because of JOURNALMODE_PERSIST or JOURNALMODE_TRUNCATE.
  41438. ** If the journal really is hot, reset the pager cache prior rolling
  41439. ** back any content. If the journal is merely persistent, no reset is
  41440. ** needed.
  41441. */
  41442. static int pager_playback(Pager *pPager, int isHot){
  41443. sqlite3_vfs *pVfs = pPager->pVfs;
  41444. i64 szJ; /* Size of the journal file in bytes */
  41445. u32 nRec; /* Number of Records in the journal */
  41446. u32 u; /* Unsigned loop counter */
  41447. Pgno mxPg = 0; /* Size of the original file in pages */
  41448. int rc; /* Result code of a subroutine */
  41449. int res = 1; /* Value returned by sqlite3OsAccess() */
  41450. char *zMaster = 0; /* Name of master journal file if any */
  41451. int needPagerReset; /* True to reset page prior to first page rollback */
  41452. int nPlayback = 0; /* Total number of pages restored from journal */
  41453. /* Figure out how many records are in the journal. Abort early if
  41454. ** the journal is empty.
  41455. */
  41456. assert( isOpen(pPager->jfd) );
  41457. rc = sqlite3OsFileSize(pPager->jfd, &szJ);
  41458. if( rc!=SQLITE_OK ){
  41459. goto end_playback;
  41460. }
  41461. /* Read the master journal name from the journal, if it is present.
  41462. ** If a master journal file name is specified, but the file is not
  41463. ** present on disk, then the journal is not hot and does not need to be
  41464. ** played back.
  41465. **
  41466. ** TODO: Technically the following is an error because it assumes that
  41467. ** buffer Pager.pTmpSpace is (mxPathname+1) bytes or larger. i.e. that
  41468. ** (pPager->pageSize >= pPager->pVfs->mxPathname+1). Using os_unix.c,
  41469. ** mxPathname is 512, which is the same as the minimum allowable value
  41470. ** for pageSize.
  41471. */
  41472. zMaster = pPager->pTmpSpace;
  41473. rc = readMasterJournal(pPager->jfd, zMaster, pPager->pVfs->mxPathname+1);
  41474. if( rc==SQLITE_OK && zMaster[0] ){
  41475. rc = sqlite3OsAccess(pVfs, zMaster, SQLITE_ACCESS_EXISTS, &res);
  41476. }
  41477. zMaster = 0;
  41478. if( rc!=SQLITE_OK || !res ){
  41479. goto end_playback;
  41480. }
  41481. pPager->journalOff = 0;
  41482. needPagerReset = isHot;
  41483. /* This loop terminates either when a readJournalHdr() or
  41484. ** pager_playback_one_page() call returns SQLITE_DONE or an IO error
  41485. ** occurs.
  41486. */
  41487. while( 1 ){
  41488. /* Read the next journal header from the journal file. If there are
  41489. ** not enough bytes left in the journal file for a complete header, or
  41490. ** it is corrupted, then a process must have failed while writing it.
  41491. ** This indicates nothing more needs to be rolled back.
  41492. */
  41493. rc = readJournalHdr(pPager, isHot, szJ, &nRec, &mxPg);
  41494. if( rc!=SQLITE_OK ){
  41495. if( rc==SQLITE_DONE ){
  41496. rc = SQLITE_OK;
  41497. }
  41498. goto end_playback;
  41499. }
  41500. /* If nRec is 0xffffffff, then this journal was created by a process
  41501. ** working in no-sync mode. This means that the rest of the journal
  41502. ** file consists of pages, there are no more journal headers. Compute
  41503. ** the value of nRec based on this assumption.
  41504. */
  41505. if( nRec==0xffffffff ){
  41506. assert( pPager->journalOff==JOURNAL_HDR_SZ(pPager) );
  41507. nRec = (int)((szJ - JOURNAL_HDR_SZ(pPager))/JOURNAL_PG_SZ(pPager));
  41508. }
  41509. /* If nRec is 0 and this rollback is of a transaction created by this
  41510. ** process and if this is the final header in the journal, then it means
  41511. ** that this part of the journal was being filled but has not yet been
  41512. ** synced to disk. Compute the number of pages based on the remaining
  41513. ** size of the file.
  41514. **
  41515. ** The third term of the test was added to fix ticket #2565.
  41516. ** When rolling back a hot journal, nRec==0 always means that the next
  41517. ** chunk of the journal contains zero pages to be rolled back. But
  41518. ** when doing a ROLLBACK and the nRec==0 chunk is the last chunk in
  41519. ** the journal, it means that the journal might contain additional
  41520. ** pages that need to be rolled back and that the number of pages
  41521. ** should be computed based on the journal file size.
  41522. */
  41523. if( nRec==0 && !isHot &&
  41524. pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff ){
  41525. nRec = (int)((szJ - pPager->journalOff) / JOURNAL_PG_SZ(pPager));
  41526. }
  41527. /* If this is the first header read from the journal, truncate the
  41528. ** database file back to its original size.
  41529. */
  41530. if( pPager->journalOff==JOURNAL_HDR_SZ(pPager) ){
  41531. rc = pager_truncate(pPager, mxPg);
  41532. if( rc!=SQLITE_OK ){
  41533. goto end_playback;
  41534. }
  41535. pPager->dbSize = mxPg;
  41536. }
  41537. /* Copy original pages out of the journal and back into the
  41538. ** database file and/or page cache.
  41539. */
  41540. for(u=0; u<nRec; u++){
  41541. if( needPagerReset ){
  41542. pager_reset(pPager);
  41543. needPagerReset = 0;
  41544. }
  41545. rc = pager_playback_one_page(pPager,&pPager->journalOff,0,1,0);
  41546. if( rc==SQLITE_OK ){
  41547. nPlayback++;
  41548. }else{
  41549. if( rc==SQLITE_DONE ){
  41550. pPager->journalOff = szJ;
  41551. break;
  41552. }else if( rc==SQLITE_IOERR_SHORT_READ ){
  41553. /* If the journal has been truncated, simply stop reading and
  41554. ** processing the journal. This might happen if the journal was
  41555. ** not completely written and synced prior to a crash. In that
  41556. ** case, the database should have never been written in the
  41557. ** first place so it is OK to simply abandon the rollback. */
  41558. rc = SQLITE_OK;
  41559. goto end_playback;
  41560. }else{
  41561. /* If we are unable to rollback, quit and return the error
  41562. ** code. This will cause the pager to enter the error state
  41563. ** so that no further harm will be done. Perhaps the next
  41564. ** process to come along will be able to rollback the database.
  41565. */
  41566. goto end_playback;
  41567. }
  41568. }
  41569. }
  41570. }
  41571. /*NOTREACHED*/
  41572. assert( 0 );
  41573. end_playback:
  41574. /* Following a rollback, the database file should be back in its original
  41575. ** state prior to the start of the transaction, so invoke the
  41576. ** SQLITE_FCNTL_DB_UNCHANGED file-control method to disable the
  41577. ** assertion that the transaction counter was modified.
  41578. */
  41579. #ifdef SQLITE_DEBUG
  41580. if( pPager->fd->pMethods ){
  41581. sqlite3OsFileControlHint(pPager->fd,SQLITE_FCNTL_DB_UNCHANGED,0);
  41582. }
  41583. #endif
  41584. /* If this playback is happening automatically as a result of an IO or
  41585. ** malloc error that occurred after the change-counter was updated but
  41586. ** before the transaction was committed, then the change-counter
  41587. ** modification may just have been reverted. If this happens in exclusive
  41588. ** mode, then subsequent transactions performed by the connection will not
  41589. ** update the change-counter at all. This may lead to cache inconsistency
  41590. ** problems for other processes at some point in the future. So, just
  41591. ** in case this has happened, clear the changeCountDone flag now.
  41592. */
  41593. pPager->changeCountDone = pPager->tempFile;
  41594. if( rc==SQLITE_OK ){
  41595. zMaster = pPager->pTmpSpace;
  41596. rc = readMasterJournal(pPager->jfd, zMaster, pPager->pVfs->mxPathname+1);
  41597. testcase( rc!=SQLITE_OK );
  41598. }
  41599. if( rc==SQLITE_OK
  41600. && (pPager->eState>=PAGER_WRITER_DBMOD || pPager->eState==PAGER_OPEN)
  41601. ){
  41602. rc = sqlite3PagerSync(pPager, 0);
  41603. }
  41604. if( rc==SQLITE_OK ){
  41605. rc = pager_end_transaction(pPager, zMaster[0]!='\0', 0);
  41606. testcase( rc!=SQLITE_OK );
  41607. }
  41608. if( rc==SQLITE_OK && zMaster[0] && res ){
  41609. /* If there was a master journal and this routine will return success,
  41610. ** see if it is possible to delete the master journal.
  41611. */
  41612. rc = pager_delmaster(pPager, zMaster);
  41613. testcase( rc!=SQLITE_OK );
  41614. }
  41615. if( isHot && nPlayback ){
  41616. sqlite3_log(SQLITE_NOTICE_RECOVER_ROLLBACK, "recovered %d pages from %s",
  41617. nPlayback, pPager->zJournal);
  41618. }
  41619. /* The Pager.sectorSize variable may have been updated while rolling
  41620. ** back a journal created by a process with a different sector size
  41621. ** value. Reset it to the correct value for this process.
  41622. */
  41623. setSectorSize(pPager);
  41624. return rc;
  41625. }
  41626. /*
  41627. ** Read the content for page pPg out of the database file and into
  41628. ** pPg->pData. A shared lock or greater must be held on the database
  41629. ** file before this function is called.
  41630. **
  41631. ** If page 1 is read, then the value of Pager.dbFileVers[] is set to
  41632. ** the value read from the database file.
  41633. **
  41634. ** If an IO error occurs, then the IO error is returned to the caller.
  41635. ** Otherwise, SQLITE_OK is returned.
  41636. */
  41637. static int readDbPage(PgHdr *pPg, u32 iFrame){
  41638. Pager *pPager = pPg->pPager; /* Pager object associated with page pPg */
  41639. Pgno pgno = pPg->pgno; /* Page number to read */
  41640. int rc = SQLITE_OK; /* Return code */
  41641. int pgsz = pPager->pageSize; /* Number of bytes to read */
  41642. assert( pPager->eState>=PAGER_READER && !MEMDB );
  41643. assert( isOpen(pPager->fd) );
  41644. #ifndef SQLITE_OMIT_WAL
  41645. if( iFrame ){
  41646. /* Try to pull the page from the write-ahead log. */
  41647. rc = sqlite3WalReadFrame(pPager->pWal, iFrame, pgsz, pPg->pData);
  41648. }else
  41649. #endif
  41650. {
  41651. i64 iOffset = (pgno-1)*(i64)pPager->pageSize;
  41652. rc = sqlite3OsRead(pPager->fd, pPg->pData, pgsz, iOffset);
  41653. if( rc==SQLITE_IOERR_SHORT_READ ){
  41654. rc = SQLITE_OK;
  41655. }
  41656. }
  41657. if( pgno==1 ){
  41658. if( rc ){
  41659. /* If the read is unsuccessful, set the dbFileVers[] to something
  41660. ** that will never be a valid file version. dbFileVers[] is a copy
  41661. ** of bytes 24..39 of the database. Bytes 28..31 should always be
  41662. ** zero or the size of the database in page. Bytes 32..35 and 35..39
  41663. ** should be page numbers which are never 0xffffffff. So filling
  41664. ** pPager->dbFileVers[] with all 0xff bytes should suffice.
  41665. **
  41666. ** For an encrypted database, the situation is more complex: bytes
  41667. ** 24..39 of the database are white noise. But the probability of
  41668. ** white noise equaling 16 bytes of 0xff is vanishingly small so
  41669. ** we should still be ok.
  41670. */
  41671. memset(pPager->dbFileVers, 0xff, sizeof(pPager->dbFileVers));
  41672. }else{
  41673. u8 *dbFileVers = &((u8*)pPg->pData)[24];
  41674. memcpy(&pPager->dbFileVers, dbFileVers, sizeof(pPager->dbFileVers));
  41675. }
  41676. }
  41677. CODEC1(pPager, pPg->pData, pgno, 3, rc = SQLITE_NOMEM);
  41678. PAGER_INCR(sqlite3_pager_readdb_count);
  41679. PAGER_INCR(pPager->nRead);
  41680. IOTRACE(("PGIN %p %d\n", pPager, pgno));
  41681. PAGERTRACE(("FETCH %d page %d hash(%08x)\n",
  41682. PAGERID(pPager), pgno, pager_pagehash(pPg)));
  41683. return rc;
  41684. }
  41685. /*
  41686. ** Update the value of the change-counter at offsets 24 and 92 in
  41687. ** the header and the sqlite version number at offset 96.
  41688. **
  41689. ** This is an unconditional update. See also the pager_incr_changecounter()
  41690. ** routine which only updates the change-counter if the update is actually
  41691. ** needed, as determined by the pPager->changeCountDone state variable.
  41692. */
  41693. static void pager_write_changecounter(PgHdr *pPg){
  41694. u32 change_counter;
  41695. /* Increment the value just read and write it back to byte 24. */
  41696. change_counter = sqlite3Get4byte((u8*)pPg->pPager->dbFileVers)+1;
  41697. put32bits(((char*)pPg->pData)+24, change_counter);
  41698. /* Also store the SQLite version number in bytes 96..99 and in
  41699. ** bytes 92..95 store the change counter for which the version number
  41700. ** is valid. */
  41701. put32bits(((char*)pPg->pData)+92, change_counter);
  41702. put32bits(((char*)pPg->pData)+96, SQLITE_VERSION_NUMBER);
  41703. }
  41704. #ifndef SQLITE_OMIT_WAL
  41705. /*
  41706. ** This function is invoked once for each page that has already been
  41707. ** written into the log file when a WAL transaction is rolled back.
  41708. ** Parameter iPg is the page number of said page. The pCtx argument
  41709. ** is actually a pointer to the Pager structure.
  41710. **
  41711. ** If page iPg is present in the cache, and has no outstanding references,
  41712. ** it is discarded. Otherwise, if there are one or more outstanding
  41713. ** references, the page content is reloaded from the database. If the
  41714. ** attempt to reload content from the database is required and fails,
  41715. ** return an SQLite error code. Otherwise, SQLITE_OK.
  41716. */
  41717. static int pagerUndoCallback(void *pCtx, Pgno iPg){
  41718. int rc = SQLITE_OK;
  41719. Pager *pPager = (Pager *)pCtx;
  41720. PgHdr *pPg;
  41721. assert( pagerUseWal(pPager) );
  41722. pPg = sqlite3PagerLookup(pPager, iPg);
  41723. if( pPg ){
  41724. if( sqlite3PcachePageRefcount(pPg)==1 ){
  41725. sqlite3PcacheDrop(pPg);
  41726. }else{
  41727. u32 iFrame = 0;
  41728. rc = sqlite3WalFindFrame(pPager->pWal, pPg->pgno, &iFrame);
  41729. if( rc==SQLITE_OK ){
  41730. rc = readDbPage(pPg, iFrame);
  41731. }
  41732. if( rc==SQLITE_OK ){
  41733. pPager->xReiniter(pPg);
  41734. }
  41735. sqlite3PagerUnrefNotNull(pPg);
  41736. }
  41737. }
  41738. /* Normally, if a transaction is rolled back, any backup processes are
  41739. ** updated as data is copied out of the rollback journal and into the
  41740. ** database. This is not generally possible with a WAL database, as
  41741. ** rollback involves simply truncating the log file. Therefore, if one
  41742. ** or more frames have already been written to the log (and therefore
  41743. ** also copied into the backup databases) as part of this transaction,
  41744. ** the backups must be restarted.
  41745. */
  41746. sqlite3BackupRestart(pPager->pBackup);
  41747. return rc;
  41748. }
  41749. /*
  41750. ** This function is called to rollback a transaction on a WAL database.
  41751. */
  41752. static int pagerRollbackWal(Pager *pPager){
  41753. int rc; /* Return Code */
  41754. PgHdr *pList; /* List of dirty pages to revert */
  41755. /* For all pages in the cache that are currently dirty or have already
  41756. ** been written (but not committed) to the log file, do one of the
  41757. ** following:
  41758. **
  41759. ** + Discard the cached page (if refcount==0), or
  41760. ** + Reload page content from the database (if refcount>0).
  41761. */
  41762. pPager->dbSize = pPager->dbOrigSize;
  41763. rc = sqlite3WalUndo(pPager->pWal, pagerUndoCallback, (void *)pPager);
  41764. pList = sqlite3PcacheDirtyList(pPager->pPCache);
  41765. while( pList && rc==SQLITE_OK ){
  41766. PgHdr *pNext = pList->pDirty;
  41767. rc = pagerUndoCallback((void *)pPager, pList->pgno);
  41768. pList = pNext;
  41769. }
  41770. return rc;
  41771. }
  41772. /*
  41773. ** This function is a wrapper around sqlite3WalFrames(). As well as logging
  41774. ** the contents of the list of pages headed by pList (connected by pDirty),
  41775. ** this function notifies any active backup processes that the pages have
  41776. ** changed.
  41777. **
  41778. ** The list of pages passed into this routine is always sorted by page number.
  41779. ** Hence, if page 1 appears anywhere on the list, it will be the first page.
  41780. */
  41781. static int pagerWalFrames(
  41782. Pager *pPager, /* Pager object */
  41783. PgHdr *pList, /* List of frames to log */
  41784. Pgno nTruncate, /* Database size after this commit */
  41785. int isCommit /* True if this is a commit */
  41786. ){
  41787. int rc; /* Return code */
  41788. int nList; /* Number of pages in pList */
  41789. PgHdr *p; /* For looping over pages */
  41790. assert( pPager->pWal );
  41791. assert( pList );
  41792. #ifdef SQLITE_DEBUG
  41793. /* Verify that the page list is in accending order */
  41794. for(p=pList; p && p->pDirty; p=p->pDirty){
  41795. assert( p->pgno < p->pDirty->pgno );
  41796. }
  41797. #endif
  41798. assert( pList->pDirty==0 || isCommit );
  41799. if( isCommit ){
  41800. /* If a WAL transaction is being committed, there is no point in writing
  41801. ** any pages with page numbers greater than nTruncate into the WAL file.
  41802. ** They will never be read by any client. So remove them from the pDirty
  41803. ** list here. */
  41804. PgHdr **ppNext = &pList;
  41805. nList = 0;
  41806. for(p=pList; (*ppNext = p)!=0; p=p->pDirty){
  41807. if( p->pgno<=nTruncate ){
  41808. ppNext = &p->pDirty;
  41809. nList++;
  41810. }
  41811. }
  41812. assert( pList );
  41813. }else{
  41814. nList = 1;
  41815. }
  41816. pPager->aStat[PAGER_STAT_WRITE] += nList;
  41817. if( pList->pgno==1 ) pager_write_changecounter(pList);
  41818. rc = sqlite3WalFrames(pPager->pWal,
  41819. pPager->pageSize, pList, nTruncate, isCommit, pPager->walSyncFlags
  41820. );
  41821. if( rc==SQLITE_OK && pPager->pBackup ){
  41822. for(p=pList; p; p=p->pDirty){
  41823. sqlite3BackupUpdate(pPager->pBackup, p->pgno, (u8 *)p->pData);
  41824. }
  41825. }
  41826. #ifdef SQLITE_CHECK_PAGES
  41827. pList = sqlite3PcacheDirtyList(pPager->pPCache);
  41828. for(p=pList; p; p=p->pDirty){
  41829. pager_set_pagehash(p);
  41830. }
  41831. #endif
  41832. return rc;
  41833. }
  41834. /*
  41835. ** Begin a read transaction on the WAL.
  41836. **
  41837. ** This routine used to be called "pagerOpenSnapshot()" because it essentially
  41838. ** makes a snapshot of the database at the current point in time and preserves
  41839. ** that snapshot for use by the reader in spite of concurrently changes by
  41840. ** other writers or checkpointers.
  41841. */
  41842. static int pagerBeginReadTransaction(Pager *pPager){
  41843. int rc; /* Return code */
  41844. int changed = 0; /* True if cache must be reset */
  41845. assert( pagerUseWal(pPager) );
  41846. assert( pPager->eState==PAGER_OPEN || pPager->eState==PAGER_READER );
  41847. /* sqlite3WalEndReadTransaction() was not called for the previous
  41848. ** transaction in locking_mode=EXCLUSIVE. So call it now. If we
  41849. ** are in locking_mode=NORMAL and EndRead() was previously called,
  41850. ** the duplicate call is harmless.
  41851. */
  41852. sqlite3WalEndReadTransaction(pPager->pWal);
  41853. rc = sqlite3WalBeginReadTransaction(pPager->pWal, &changed);
  41854. if( rc!=SQLITE_OK || changed ){
  41855. pager_reset(pPager);
  41856. if( USEFETCH(pPager) ) sqlite3OsUnfetch(pPager->fd, 0, 0);
  41857. }
  41858. return rc;
  41859. }
  41860. #endif
  41861. /*
  41862. ** This function is called as part of the transition from PAGER_OPEN
  41863. ** to PAGER_READER state to determine the size of the database file
  41864. ** in pages (assuming the page size currently stored in Pager.pageSize).
  41865. **
  41866. ** If no error occurs, SQLITE_OK is returned and the size of the database
  41867. ** in pages is stored in *pnPage. Otherwise, an error code (perhaps
  41868. ** SQLITE_IOERR_FSTAT) is returned and *pnPage is left unmodified.
  41869. */
  41870. static int pagerPagecount(Pager *pPager, Pgno *pnPage){
  41871. Pgno nPage; /* Value to return via *pnPage */
  41872. /* Query the WAL sub-system for the database size. The WalDbsize()
  41873. ** function returns zero if the WAL is not open (i.e. Pager.pWal==0), or
  41874. ** if the database size is not available. The database size is not
  41875. ** available from the WAL sub-system if the log file is empty or
  41876. ** contains no valid committed transactions.
  41877. */
  41878. assert( pPager->eState==PAGER_OPEN );
  41879. assert( pPager->eLock>=SHARED_LOCK );
  41880. nPage = sqlite3WalDbsize(pPager->pWal);
  41881. /* If the database size was not available from the WAL sub-system,
  41882. ** determine it based on the size of the database file. If the size
  41883. ** of the database file is not an integer multiple of the page-size,
  41884. ** round down to the nearest page. Except, any file larger than 0
  41885. ** bytes in size is considered to contain at least one page.
  41886. */
  41887. if( nPage==0 ){
  41888. i64 n = 0; /* Size of db file in bytes */
  41889. assert( isOpen(pPager->fd) || pPager->tempFile );
  41890. if( isOpen(pPager->fd) ){
  41891. int rc = sqlite3OsFileSize(pPager->fd, &n);
  41892. if( rc!=SQLITE_OK ){
  41893. return rc;
  41894. }
  41895. }
  41896. nPage = (Pgno)((n+pPager->pageSize-1) / pPager->pageSize);
  41897. }
  41898. /* If the current number of pages in the file is greater than the
  41899. ** configured maximum pager number, increase the allowed limit so
  41900. ** that the file can be read.
  41901. */
  41902. if( nPage>pPager->mxPgno ){
  41903. pPager->mxPgno = (Pgno)nPage;
  41904. }
  41905. *pnPage = nPage;
  41906. return SQLITE_OK;
  41907. }
  41908. #ifndef SQLITE_OMIT_WAL
  41909. /*
  41910. ** Check if the *-wal file that corresponds to the database opened by pPager
  41911. ** exists if the database is not empy, or verify that the *-wal file does
  41912. ** not exist (by deleting it) if the database file is empty.
  41913. **
  41914. ** If the database is not empty and the *-wal file exists, open the pager
  41915. ** in WAL mode. If the database is empty or if no *-wal file exists and
  41916. ** if no error occurs, make sure Pager.journalMode is not set to
  41917. ** PAGER_JOURNALMODE_WAL.
  41918. **
  41919. ** Return SQLITE_OK or an error code.
  41920. **
  41921. ** The caller must hold a SHARED lock on the database file to call this
  41922. ** function. Because an EXCLUSIVE lock on the db file is required to delete
  41923. ** a WAL on a none-empty database, this ensures there is no race condition
  41924. ** between the xAccess() below and an xDelete() being executed by some
  41925. ** other connection.
  41926. */
  41927. static int pagerOpenWalIfPresent(Pager *pPager){
  41928. int rc = SQLITE_OK;
  41929. assert( pPager->eState==PAGER_OPEN );
  41930. assert( pPager->eLock>=SHARED_LOCK );
  41931. if( !pPager->tempFile ){
  41932. int isWal; /* True if WAL file exists */
  41933. Pgno nPage; /* Size of the database file */
  41934. rc = pagerPagecount(pPager, &nPage);
  41935. if( rc ) return rc;
  41936. if( nPage==0 ){
  41937. rc = sqlite3OsDelete(pPager->pVfs, pPager->zWal, 0);
  41938. if( rc==SQLITE_IOERR_DELETE_NOENT ) rc = SQLITE_OK;
  41939. isWal = 0;
  41940. }else{
  41941. rc = sqlite3OsAccess(
  41942. pPager->pVfs, pPager->zWal, SQLITE_ACCESS_EXISTS, &isWal
  41943. );
  41944. }
  41945. if( rc==SQLITE_OK ){
  41946. if( isWal ){
  41947. testcase( sqlite3PcachePagecount(pPager->pPCache)==0 );
  41948. rc = sqlite3PagerOpenWal(pPager, 0);
  41949. }else if( pPager->journalMode==PAGER_JOURNALMODE_WAL ){
  41950. pPager->journalMode = PAGER_JOURNALMODE_DELETE;
  41951. }
  41952. }
  41953. }
  41954. return rc;
  41955. }
  41956. #endif
  41957. /*
  41958. ** Playback savepoint pSavepoint. Or, if pSavepoint==NULL, then playback
  41959. ** the entire master journal file. The case pSavepoint==NULL occurs when
  41960. ** a ROLLBACK TO command is invoked on a SAVEPOINT that is a transaction
  41961. ** savepoint.
  41962. **
  41963. ** When pSavepoint is not NULL (meaning a non-transaction savepoint is
  41964. ** being rolled back), then the rollback consists of up to three stages,
  41965. ** performed in the order specified:
  41966. **
  41967. ** * Pages are played back from the main journal starting at byte
  41968. ** offset PagerSavepoint.iOffset and continuing to
  41969. ** PagerSavepoint.iHdrOffset, or to the end of the main journal
  41970. ** file if PagerSavepoint.iHdrOffset is zero.
  41971. **
  41972. ** * If PagerSavepoint.iHdrOffset is not zero, then pages are played
  41973. ** back starting from the journal header immediately following
  41974. ** PagerSavepoint.iHdrOffset to the end of the main journal file.
  41975. **
  41976. ** * Pages are then played back from the sub-journal file, starting
  41977. ** with the PagerSavepoint.iSubRec and continuing to the end of
  41978. ** the journal file.
  41979. **
  41980. ** Throughout the rollback process, each time a page is rolled back, the
  41981. ** corresponding bit is set in a bitvec structure (variable pDone in the
  41982. ** implementation below). This is used to ensure that a page is only
  41983. ** rolled back the first time it is encountered in either journal.
  41984. **
  41985. ** If pSavepoint is NULL, then pages are only played back from the main
  41986. ** journal file. There is no need for a bitvec in this case.
  41987. **
  41988. ** In either case, before playback commences the Pager.dbSize variable
  41989. ** is reset to the value that it held at the start of the savepoint
  41990. ** (or transaction). No page with a page-number greater than this value
  41991. ** is played back. If one is encountered it is simply skipped.
  41992. */
  41993. static int pagerPlaybackSavepoint(Pager *pPager, PagerSavepoint *pSavepoint){
  41994. i64 szJ; /* Effective size of the main journal */
  41995. i64 iHdrOff; /* End of first segment of main-journal records */
  41996. int rc = SQLITE_OK; /* Return code */
  41997. Bitvec *pDone = 0; /* Bitvec to ensure pages played back only once */
  41998. assert( pPager->eState!=PAGER_ERROR );
  41999. assert( pPager->eState>=PAGER_WRITER_LOCKED );
  42000. /* Allocate a bitvec to use to store the set of pages rolled back */
  42001. if( pSavepoint ){
  42002. pDone = sqlite3BitvecCreate(pSavepoint->nOrig);
  42003. if( !pDone ){
  42004. return SQLITE_NOMEM;
  42005. }
  42006. }
  42007. /* Set the database size back to the value it was before the savepoint
  42008. ** being reverted was opened.
  42009. */
  42010. pPager->dbSize = pSavepoint ? pSavepoint->nOrig : pPager->dbOrigSize;
  42011. pPager->changeCountDone = pPager->tempFile;
  42012. if( !pSavepoint && pagerUseWal(pPager) ){
  42013. return pagerRollbackWal(pPager);
  42014. }
  42015. /* Use pPager->journalOff as the effective size of the main rollback
  42016. ** journal. The actual file might be larger than this in
  42017. ** PAGER_JOURNALMODE_TRUNCATE or PAGER_JOURNALMODE_PERSIST. But anything
  42018. ** past pPager->journalOff is off-limits to us.
  42019. */
  42020. szJ = pPager->journalOff;
  42021. assert( pagerUseWal(pPager)==0 || szJ==0 );
  42022. /* Begin by rolling back records from the main journal starting at
  42023. ** PagerSavepoint.iOffset and continuing to the next journal header.
  42024. ** There might be records in the main journal that have a page number
  42025. ** greater than the current database size (pPager->dbSize) but those
  42026. ** will be skipped automatically. Pages are added to pDone as they
  42027. ** are played back.
  42028. */
  42029. if( pSavepoint && !pagerUseWal(pPager) ){
  42030. iHdrOff = pSavepoint->iHdrOffset ? pSavepoint->iHdrOffset : szJ;
  42031. pPager->journalOff = pSavepoint->iOffset;
  42032. while( rc==SQLITE_OK && pPager->journalOff<iHdrOff ){
  42033. rc = pager_playback_one_page(pPager, &pPager->journalOff, pDone, 1, 1);
  42034. }
  42035. assert( rc!=SQLITE_DONE );
  42036. }else{
  42037. pPager->journalOff = 0;
  42038. }
  42039. /* Continue rolling back records out of the main journal starting at
  42040. ** the first journal header seen and continuing until the effective end
  42041. ** of the main journal file. Continue to skip out-of-range pages and
  42042. ** continue adding pages rolled back to pDone.
  42043. */
  42044. while( rc==SQLITE_OK && pPager->journalOff<szJ ){
  42045. u32 ii; /* Loop counter */
  42046. u32 nJRec = 0; /* Number of Journal Records */
  42047. u32 dummy;
  42048. rc = readJournalHdr(pPager, 0, szJ, &nJRec, &dummy);
  42049. assert( rc!=SQLITE_DONE );
  42050. /*
  42051. ** The "pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff"
  42052. ** test is related to ticket #2565. See the discussion in the
  42053. ** pager_playback() function for additional information.
  42054. */
  42055. if( nJRec==0
  42056. && pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff
  42057. ){
  42058. nJRec = (u32)((szJ - pPager->journalOff)/JOURNAL_PG_SZ(pPager));
  42059. }
  42060. for(ii=0; rc==SQLITE_OK && ii<nJRec && pPager->journalOff<szJ; ii++){
  42061. rc = pager_playback_one_page(pPager, &pPager->journalOff, pDone, 1, 1);
  42062. }
  42063. assert( rc!=SQLITE_DONE );
  42064. }
  42065. assert( rc!=SQLITE_OK || pPager->journalOff>=szJ );
  42066. /* Finally, rollback pages from the sub-journal. Page that were
  42067. ** previously rolled back out of the main journal (and are hence in pDone)
  42068. ** will be skipped. Out-of-range pages are also skipped.
  42069. */
  42070. if( pSavepoint ){
  42071. u32 ii; /* Loop counter */
  42072. i64 offset = (i64)pSavepoint->iSubRec*(4+pPager->pageSize);
  42073. if( pagerUseWal(pPager) ){
  42074. rc = sqlite3WalSavepointUndo(pPager->pWal, pSavepoint->aWalData);
  42075. }
  42076. for(ii=pSavepoint->iSubRec; rc==SQLITE_OK && ii<pPager->nSubRec; ii++){
  42077. assert( offset==(i64)ii*(4+pPager->pageSize) );
  42078. rc = pager_playback_one_page(pPager, &offset, pDone, 0, 1);
  42079. }
  42080. assert( rc!=SQLITE_DONE );
  42081. }
  42082. sqlite3BitvecDestroy(pDone);
  42083. if( rc==SQLITE_OK ){
  42084. pPager->journalOff = szJ;
  42085. }
  42086. return rc;
  42087. }
  42088. /*
  42089. ** Change the maximum number of in-memory pages that are allowed.
  42090. */
  42091. SQLITE_PRIVATE void sqlite3PagerSetCachesize(Pager *pPager, int mxPage){
  42092. sqlite3PcacheSetCachesize(pPager->pPCache, mxPage);
  42093. }
  42094. /*
  42095. ** Invoke SQLITE_FCNTL_MMAP_SIZE based on the current value of szMmap.
  42096. */
  42097. static void pagerFixMaplimit(Pager *pPager){
  42098. #if SQLITE_MAX_MMAP_SIZE>0
  42099. sqlite3_file *fd = pPager->fd;
  42100. if( isOpen(fd) && fd->pMethods->iVersion>=3 ){
  42101. sqlite3_int64 sz;
  42102. sz = pPager->szMmap;
  42103. pPager->bUseFetch = (sz>0);
  42104. sqlite3OsFileControlHint(pPager->fd, SQLITE_FCNTL_MMAP_SIZE, &sz);
  42105. }
  42106. #endif
  42107. }
  42108. /*
  42109. ** Change the maximum size of any memory mapping made of the database file.
  42110. */
  42111. SQLITE_PRIVATE void sqlite3PagerSetMmapLimit(Pager *pPager, sqlite3_int64 szMmap){
  42112. pPager->szMmap = szMmap;
  42113. pagerFixMaplimit(pPager);
  42114. }
  42115. /*
  42116. ** Free as much memory as possible from the pager.
  42117. */
  42118. SQLITE_PRIVATE void sqlite3PagerShrink(Pager *pPager){
  42119. sqlite3PcacheShrink(pPager->pPCache);
  42120. }
  42121. /*
  42122. ** Adjust settings of the pager to those specified in the pgFlags parameter.
  42123. **
  42124. ** The "level" in pgFlags & PAGER_SYNCHRONOUS_MASK sets the robustness
  42125. ** of the database to damage due to OS crashes or power failures by
  42126. ** changing the number of syncs()s when writing the journals.
  42127. ** There are three levels:
  42128. **
  42129. ** OFF sqlite3OsSync() is never called. This is the default
  42130. ** for temporary and transient files.
  42131. **
  42132. ** NORMAL The journal is synced once before writes begin on the
  42133. ** database. This is normally adequate protection, but
  42134. ** it is theoretically possible, though very unlikely,
  42135. ** that an inopertune power failure could leave the journal
  42136. ** in a state which would cause damage to the database
  42137. ** when it is rolled back.
  42138. **
  42139. ** FULL The journal is synced twice before writes begin on the
  42140. ** database (with some additional information - the nRec field
  42141. ** of the journal header - being written in between the two
  42142. ** syncs). If we assume that writing a
  42143. ** single disk sector is atomic, then this mode provides
  42144. ** assurance that the journal will not be corrupted to the
  42145. ** point of causing damage to the database during rollback.
  42146. **
  42147. ** The above is for a rollback-journal mode. For WAL mode, OFF continues
  42148. ** to mean that no syncs ever occur. NORMAL means that the WAL is synced
  42149. ** prior to the start of checkpoint and that the database file is synced
  42150. ** at the conclusion of the checkpoint if the entire content of the WAL
  42151. ** was written back into the database. But no sync operations occur for
  42152. ** an ordinary commit in NORMAL mode with WAL. FULL means that the WAL
  42153. ** file is synced following each commit operation, in addition to the
  42154. ** syncs associated with NORMAL.
  42155. **
  42156. ** Do not confuse synchronous=FULL with SQLITE_SYNC_FULL. The
  42157. ** SQLITE_SYNC_FULL macro means to use the MacOSX-style full-fsync
  42158. ** using fcntl(F_FULLFSYNC). SQLITE_SYNC_NORMAL means to do an
  42159. ** ordinary fsync() call. There is no difference between SQLITE_SYNC_FULL
  42160. ** and SQLITE_SYNC_NORMAL on platforms other than MacOSX. But the
  42161. ** synchronous=FULL versus synchronous=NORMAL setting determines when
  42162. ** the xSync primitive is called and is relevant to all platforms.
  42163. **
  42164. ** Numeric values associated with these states are OFF==1, NORMAL=2,
  42165. ** and FULL=3.
  42166. */
  42167. #ifndef SQLITE_OMIT_PAGER_PRAGMAS
  42168. SQLITE_PRIVATE void sqlite3PagerSetFlags(
  42169. Pager *pPager, /* The pager to set safety level for */
  42170. unsigned pgFlags /* Various flags */
  42171. ){
  42172. unsigned level = pgFlags & PAGER_SYNCHRONOUS_MASK;
  42173. assert( level>=1 && level<=3 );
  42174. pPager->noSync = (level==1 || pPager->tempFile) ?1:0;
  42175. pPager->fullSync = (level==3 && !pPager->tempFile) ?1:0;
  42176. if( pPager->noSync ){
  42177. pPager->syncFlags = 0;
  42178. pPager->ckptSyncFlags = 0;
  42179. }else if( pgFlags & PAGER_FULLFSYNC ){
  42180. pPager->syncFlags = SQLITE_SYNC_FULL;
  42181. pPager->ckptSyncFlags = SQLITE_SYNC_FULL;
  42182. }else if( pgFlags & PAGER_CKPT_FULLFSYNC ){
  42183. pPager->syncFlags = SQLITE_SYNC_NORMAL;
  42184. pPager->ckptSyncFlags = SQLITE_SYNC_FULL;
  42185. }else{
  42186. pPager->syncFlags = SQLITE_SYNC_NORMAL;
  42187. pPager->ckptSyncFlags = SQLITE_SYNC_NORMAL;
  42188. }
  42189. pPager->walSyncFlags = pPager->syncFlags;
  42190. if( pPager->fullSync ){
  42191. pPager->walSyncFlags |= WAL_SYNC_TRANSACTIONS;
  42192. }
  42193. if( pgFlags & PAGER_CACHESPILL ){
  42194. pPager->doNotSpill &= ~SPILLFLAG_OFF;
  42195. }else{
  42196. pPager->doNotSpill |= SPILLFLAG_OFF;
  42197. }
  42198. }
  42199. #endif
  42200. /*
  42201. ** The following global variable is incremented whenever the library
  42202. ** attempts to open a temporary file. This information is used for
  42203. ** testing and analysis only.
  42204. */
  42205. #ifdef SQLITE_TEST
  42206. SQLITE_API int sqlite3_opentemp_count = 0;
  42207. #endif
  42208. /*
  42209. ** Open a temporary file.
  42210. **
  42211. ** Write the file descriptor into *pFile. Return SQLITE_OK on success
  42212. ** or some other error code if we fail. The OS will automatically
  42213. ** delete the temporary file when it is closed.
  42214. **
  42215. ** The flags passed to the VFS layer xOpen() call are those specified
  42216. ** by parameter vfsFlags ORed with the following:
  42217. **
  42218. ** SQLITE_OPEN_READWRITE
  42219. ** SQLITE_OPEN_CREATE
  42220. ** SQLITE_OPEN_EXCLUSIVE
  42221. ** SQLITE_OPEN_DELETEONCLOSE
  42222. */
  42223. static int pagerOpentemp(
  42224. Pager *pPager, /* The pager object */
  42225. sqlite3_file *pFile, /* Write the file descriptor here */
  42226. int vfsFlags /* Flags passed through to the VFS */
  42227. ){
  42228. int rc; /* Return code */
  42229. #ifdef SQLITE_TEST
  42230. sqlite3_opentemp_count++; /* Used for testing and analysis only */
  42231. #endif
  42232. vfsFlags |= SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE |
  42233. SQLITE_OPEN_EXCLUSIVE | SQLITE_OPEN_DELETEONCLOSE;
  42234. rc = sqlite3OsOpen(pPager->pVfs, 0, pFile, vfsFlags, 0);
  42235. assert( rc!=SQLITE_OK || isOpen(pFile) );
  42236. return rc;
  42237. }
  42238. /*
  42239. ** Set the busy handler function.
  42240. **
  42241. ** The pager invokes the busy-handler if sqlite3OsLock() returns
  42242. ** SQLITE_BUSY when trying to upgrade from no-lock to a SHARED lock,
  42243. ** or when trying to upgrade from a RESERVED lock to an EXCLUSIVE
  42244. ** lock. It does *not* invoke the busy handler when upgrading from
  42245. ** SHARED to RESERVED, or when upgrading from SHARED to EXCLUSIVE
  42246. ** (which occurs during hot-journal rollback). Summary:
  42247. **
  42248. ** Transition | Invokes xBusyHandler
  42249. ** --------------------------------------------------------
  42250. ** NO_LOCK -> SHARED_LOCK | Yes
  42251. ** SHARED_LOCK -> RESERVED_LOCK | No
  42252. ** SHARED_LOCK -> EXCLUSIVE_LOCK | No
  42253. ** RESERVED_LOCK -> EXCLUSIVE_LOCK | Yes
  42254. **
  42255. ** If the busy-handler callback returns non-zero, the lock is
  42256. ** retried. If it returns zero, then the SQLITE_BUSY error is
  42257. ** returned to the caller of the pager API function.
  42258. */
  42259. SQLITE_PRIVATE void sqlite3PagerSetBusyhandler(
  42260. Pager *pPager, /* Pager object */
  42261. int (*xBusyHandler)(void *), /* Pointer to busy-handler function */
  42262. void *pBusyHandlerArg /* Argument to pass to xBusyHandler */
  42263. ){
  42264. pPager->xBusyHandler = xBusyHandler;
  42265. pPager->pBusyHandlerArg = pBusyHandlerArg;
  42266. if( isOpen(pPager->fd) ){
  42267. void **ap = (void **)&pPager->xBusyHandler;
  42268. assert( ((int(*)(void *))(ap[0]))==xBusyHandler );
  42269. assert( ap[1]==pBusyHandlerArg );
  42270. sqlite3OsFileControlHint(pPager->fd, SQLITE_FCNTL_BUSYHANDLER, (void *)ap);
  42271. }
  42272. }
  42273. /*
  42274. ** Change the page size used by the Pager object. The new page size
  42275. ** is passed in *pPageSize.
  42276. **
  42277. ** If the pager is in the error state when this function is called, it
  42278. ** is a no-op. The value returned is the error state error code (i.e.
  42279. ** one of SQLITE_IOERR, an SQLITE_IOERR_xxx sub-code or SQLITE_FULL).
  42280. **
  42281. ** Otherwise, if all of the following are true:
  42282. **
  42283. ** * the new page size (value of *pPageSize) is valid (a power
  42284. ** of two between 512 and SQLITE_MAX_PAGE_SIZE, inclusive), and
  42285. **
  42286. ** * there are no outstanding page references, and
  42287. **
  42288. ** * the database is either not an in-memory database or it is
  42289. ** an in-memory database that currently consists of zero pages.
  42290. **
  42291. ** then the pager object page size is set to *pPageSize.
  42292. **
  42293. ** If the page size is changed, then this function uses sqlite3PagerMalloc()
  42294. ** to obtain a new Pager.pTmpSpace buffer. If this allocation attempt
  42295. ** fails, SQLITE_NOMEM is returned and the page size remains unchanged.
  42296. ** In all other cases, SQLITE_OK is returned.
  42297. **
  42298. ** If the page size is not changed, either because one of the enumerated
  42299. ** conditions above is not true, the pager was in error state when this
  42300. ** function was called, or because the memory allocation attempt failed,
  42301. ** then *pPageSize is set to the old, retained page size before returning.
  42302. */
  42303. SQLITE_PRIVATE int sqlite3PagerSetPagesize(Pager *pPager, u32 *pPageSize, int nReserve){
  42304. int rc = SQLITE_OK;
  42305. /* It is not possible to do a full assert_pager_state() here, as this
  42306. ** function may be called from within PagerOpen(), before the state
  42307. ** of the Pager object is internally consistent.
  42308. **
  42309. ** At one point this function returned an error if the pager was in
  42310. ** PAGER_ERROR state. But since PAGER_ERROR state guarantees that
  42311. ** there is at least one outstanding page reference, this function
  42312. ** is a no-op for that case anyhow.
  42313. */
  42314. u32 pageSize = *pPageSize;
  42315. assert( pageSize==0 || (pageSize>=512 && pageSize<=SQLITE_MAX_PAGE_SIZE) );
  42316. if( (pPager->memDb==0 || pPager->dbSize==0)
  42317. && sqlite3PcacheRefCount(pPager->pPCache)==0
  42318. && pageSize && pageSize!=(u32)pPager->pageSize
  42319. ){
  42320. char *pNew = NULL; /* New temp space */
  42321. i64 nByte = 0;
  42322. if( pPager->eState>PAGER_OPEN && isOpen(pPager->fd) ){
  42323. rc = sqlite3OsFileSize(pPager->fd, &nByte);
  42324. }
  42325. if( rc==SQLITE_OK ){
  42326. pNew = (char *)sqlite3PageMalloc(pageSize);
  42327. if( !pNew ) rc = SQLITE_NOMEM;
  42328. }
  42329. if( rc==SQLITE_OK ){
  42330. pager_reset(pPager);
  42331. rc = sqlite3PcacheSetPageSize(pPager->pPCache, pageSize);
  42332. }
  42333. if( rc==SQLITE_OK ){
  42334. sqlite3PageFree(pPager->pTmpSpace);
  42335. pPager->pTmpSpace = pNew;
  42336. pPager->dbSize = (Pgno)((nByte+pageSize-1)/pageSize);
  42337. pPager->pageSize = pageSize;
  42338. }else{
  42339. sqlite3PageFree(pNew);
  42340. }
  42341. }
  42342. *pPageSize = pPager->pageSize;
  42343. if( rc==SQLITE_OK ){
  42344. if( nReserve<0 ) nReserve = pPager->nReserve;
  42345. assert( nReserve>=0 && nReserve<1000 );
  42346. pPager->nReserve = (i16)nReserve;
  42347. pagerReportSize(pPager);
  42348. pagerFixMaplimit(pPager);
  42349. }
  42350. return rc;
  42351. }
  42352. /*
  42353. ** Return a pointer to the "temporary page" buffer held internally
  42354. ** by the pager. This is a buffer that is big enough to hold the
  42355. ** entire content of a database page. This buffer is used internally
  42356. ** during rollback and will be overwritten whenever a rollback
  42357. ** occurs. But other modules are free to use it too, as long as
  42358. ** no rollbacks are happening.
  42359. */
  42360. SQLITE_PRIVATE void *sqlite3PagerTempSpace(Pager *pPager){
  42361. return pPager->pTmpSpace;
  42362. }
  42363. /*
  42364. ** Attempt to set the maximum database page count if mxPage is positive.
  42365. ** Make no changes if mxPage is zero or negative. And never reduce the
  42366. ** maximum page count below the current size of the database.
  42367. **
  42368. ** Regardless of mxPage, return the current maximum page count.
  42369. */
  42370. SQLITE_PRIVATE int sqlite3PagerMaxPageCount(Pager *pPager, int mxPage){
  42371. if( mxPage>0 ){
  42372. pPager->mxPgno = mxPage;
  42373. }
  42374. assert( pPager->eState!=PAGER_OPEN ); /* Called only by OP_MaxPgcnt */
  42375. assert( pPager->mxPgno>=pPager->dbSize ); /* OP_MaxPgcnt enforces this */
  42376. return pPager->mxPgno;
  42377. }
  42378. /*
  42379. ** The following set of routines are used to disable the simulated
  42380. ** I/O error mechanism. These routines are used to avoid simulated
  42381. ** errors in places where we do not care about errors.
  42382. **
  42383. ** Unless -DSQLITE_TEST=1 is used, these routines are all no-ops
  42384. ** and generate no code.
  42385. */
  42386. #ifdef SQLITE_TEST
  42387. SQLITE_API extern int sqlite3_io_error_pending;
  42388. SQLITE_API extern int sqlite3_io_error_hit;
  42389. static int saved_cnt;
  42390. void disable_simulated_io_errors(void){
  42391. saved_cnt = sqlite3_io_error_pending;
  42392. sqlite3_io_error_pending = -1;
  42393. }
  42394. void enable_simulated_io_errors(void){
  42395. sqlite3_io_error_pending = saved_cnt;
  42396. }
  42397. #else
  42398. # define disable_simulated_io_errors()
  42399. # define enable_simulated_io_errors()
  42400. #endif
  42401. /*
  42402. ** Read the first N bytes from the beginning of the file into memory
  42403. ** that pDest points to.
  42404. **
  42405. ** If the pager was opened on a transient file (zFilename==""), or
  42406. ** opened on a file less than N bytes in size, the output buffer is
  42407. ** zeroed and SQLITE_OK returned. The rationale for this is that this
  42408. ** function is used to read database headers, and a new transient or
  42409. ** zero sized database has a header than consists entirely of zeroes.
  42410. **
  42411. ** If any IO error apart from SQLITE_IOERR_SHORT_READ is encountered,
  42412. ** the error code is returned to the caller and the contents of the
  42413. ** output buffer undefined.
  42414. */
  42415. SQLITE_PRIVATE int sqlite3PagerReadFileheader(Pager *pPager, int N, unsigned char *pDest){
  42416. int rc = SQLITE_OK;
  42417. memset(pDest, 0, N);
  42418. assert( isOpen(pPager->fd) || pPager->tempFile );
  42419. /* This routine is only called by btree immediately after creating
  42420. ** the Pager object. There has not been an opportunity to transition
  42421. ** to WAL mode yet.
  42422. */
  42423. assert( !pagerUseWal(pPager) );
  42424. if( isOpen(pPager->fd) ){
  42425. IOTRACE(("DBHDR %p 0 %d\n", pPager, N))
  42426. rc = sqlite3OsRead(pPager->fd, pDest, N, 0);
  42427. if( rc==SQLITE_IOERR_SHORT_READ ){
  42428. rc = SQLITE_OK;
  42429. }
  42430. }
  42431. return rc;
  42432. }
  42433. /*
  42434. ** This function may only be called when a read-transaction is open on
  42435. ** the pager. It returns the total number of pages in the database.
  42436. **
  42437. ** However, if the file is between 1 and <page-size> bytes in size, then
  42438. ** this is considered a 1 page file.
  42439. */
  42440. SQLITE_PRIVATE void sqlite3PagerPagecount(Pager *pPager, int *pnPage){
  42441. assert( pPager->eState>=PAGER_READER );
  42442. assert( pPager->eState!=PAGER_WRITER_FINISHED );
  42443. *pnPage = (int)pPager->dbSize;
  42444. }
  42445. /*
  42446. ** Try to obtain a lock of type locktype on the database file. If
  42447. ** a similar or greater lock is already held, this function is a no-op
  42448. ** (returning SQLITE_OK immediately).
  42449. **
  42450. ** Otherwise, attempt to obtain the lock using sqlite3OsLock(). Invoke
  42451. ** the busy callback if the lock is currently not available. Repeat
  42452. ** until the busy callback returns false or until the attempt to
  42453. ** obtain the lock succeeds.
  42454. **
  42455. ** Return SQLITE_OK on success and an error code if we cannot obtain
  42456. ** the lock. If the lock is obtained successfully, set the Pager.state
  42457. ** variable to locktype before returning.
  42458. */
  42459. static int pager_wait_on_lock(Pager *pPager, int locktype){
  42460. int rc; /* Return code */
  42461. /* Check that this is either a no-op (because the requested lock is
  42462. ** already held), or one of the transitions that the busy-handler
  42463. ** may be invoked during, according to the comment above
  42464. ** sqlite3PagerSetBusyhandler().
  42465. */
  42466. assert( (pPager->eLock>=locktype)
  42467. || (pPager->eLock==NO_LOCK && locktype==SHARED_LOCK)
  42468. || (pPager->eLock==RESERVED_LOCK && locktype==EXCLUSIVE_LOCK)
  42469. );
  42470. do {
  42471. rc = pagerLockDb(pPager, locktype);
  42472. }while( rc==SQLITE_BUSY && pPager->xBusyHandler(pPager->pBusyHandlerArg) );
  42473. return rc;
  42474. }
  42475. /*
  42476. ** Function assertTruncateConstraint(pPager) checks that one of the
  42477. ** following is true for all dirty pages currently in the page-cache:
  42478. **
  42479. ** a) The page number is less than or equal to the size of the
  42480. ** current database image, in pages, OR
  42481. **
  42482. ** b) if the page content were written at this time, it would not
  42483. ** be necessary to write the current content out to the sub-journal
  42484. ** (as determined by function subjRequiresPage()).
  42485. **
  42486. ** If the condition asserted by this function were not true, and the
  42487. ** dirty page were to be discarded from the cache via the pagerStress()
  42488. ** routine, pagerStress() would not write the current page content to
  42489. ** the database file. If a savepoint transaction were rolled back after
  42490. ** this happened, the correct behavior would be to restore the current
  42491. ** content of the page. However, since this content is not present in either
  42492. ** the database file or the portion of the rollback journal and
  42493. ** sub-journal rolled back the content could not be restored and the
  42494. ** database image would become corrupt. It is therefore fortunate that
  42495. ** this circumstance cannot arise.
  42496. */
  42497. #if defined(SQLITE_DEBUG)
  42498. static void assertTruncateConstraintCb(PgHdr *pPg){
  42499. assert( pPg->flags&PGHDR_DIRTY );
  42500. assert( !subjRequiresPage(pPg) || pPg->pgno<=pPg->pPager->dbSize );
  42501. }
  42502. static void assertTruncateConstraint(Pager *pPager){
  42503. sqlite3PcacheIterateDirty(pPager->pPCache, assertTruncateConstraintCb);
  42504. }
  42505. #else
  42506. # define assertTruncateConstraint(pPager)
  42507. #endif
  42508. /*
  42509. ** Truncate the in-memory database file image to nPage pages. This
  42510. ** function does not actually modify the database file on disk. It
  42511. ** just sets the internal state of the pager object so that the
  42512. ** truncation will be done when the current transaction is committed.
  42513. **
  42514. ** This function is only called right before committing a transaction.
  42515. ** Once this function has been called, the transaction must either be
  42516. ** rolled back or committed. It is not safe to call this function and
  42517. ** then continue writing to the database.
  42518. */
  42519. SQLITE_PRIVATE void sqlite3PagerTruncateImage(Pager *pPager, Pgno nPage){
  42520. assert( pPager->dbSize>=nPage );
  42521. assert( pPager->eState>=PAGER_WRITER_CACHEMOD );
  42522. pPager->dbSize = nPage;
  42523. /* At one point the code here called assertTruncateConstraint() to
  42524. ** ensure that all pages being truncated away by this operation are,
  42525. ** if one or more savepoints are open, present in the savepoint
  42526. ** journal so that they can be restored if the savepoint is rolled
  42527. ** back. This is no longer necessary as this function is now only
  42528. ** called right before committing a transaction. So although the
  42529. ** Pager object may still have open savepoints (Pager.nSavepoint!=0),
  42530. ** they cannot be rolled back. So the assertTruncateConstraint() call
  42531. ** is no longer correct. */
  42532. }
  42533. /*
  42534. ** This function is called before attempting a hot-journal rollback. It
  42535. ** syncs the journal file to disk, then sets pPager->journalHdr to the
  42536. ** size of the journal file so that the pager_playback() routine knows
  42537. ** that the entire journal file has been synced.
  42538. **
  42539. ** Syncing a hot-journal to disk before attempting to roll it back ensures
  42540. ** that if a power-failure occurs during the rollback, the process that
  42541. ** attempts rollback following system recovery sees the same journal
  42542. ** content as this process.
  42543. **
  42544. ** If everything goes as planned, SQLITE_OK is returned. Otherwise,
  42545. ** an SQLite error code.
  42546. */
  42547. static int pagerSyncHotJournal(Pager *pPager){
  42548. int rc = SQLITE_OK;
  42549. if( !pPager->noSync ){
  42550. rc = sqlite3OsSync(pPager->jfd, SQLITE_SYNC_NORMAL);
  42551. }
  42552. if( rc==SQLITE_OK ){
  42553. rc = sqlite3OsFileSize(pPager->jfd, &pPager->journalHdr);
  42554. }
  42555. return rc;
  42556. }
  42557. /*
  42558. ** Obtain a reference to a memory mapped page object for page number pgno.
  42559. ** The new object will use the pointer pData, obtained from xFetch().
  42560. ** If successful, set *ppPage to point to the new page reference
  42561. ** and return SQLITE_OK. Otherwise, return an SQLite error code and set
  42562. ** *ppPage to zero.
  42563. **
  42564. ** Page references obtained by calling this function should be released
  42565. ** by calling pagerReleaseMapPage().
  42566. */
  42567. static int pagerAcquireMapPage(
  42568. Pager *pPager, /* Pager object */
  42569. Pgno pgno, /* Page number */
  42570. void *pData, /* xFetch()'d data for this page */
  42571. PgHdr **ppPage /* OUT: Acquired page object */
  42572. ){
  42573. PgHdr *p; /* Memory mapped page to return */
  42574. if( pPager->pMmapFreelist ){
  42575. *ppPage = p = pPager->pMmapFreelist;
  42576. pPager->pMmapFreelist = p->pDirty;
  42577. p->pDirty = 0;
  42578. memset(p->pExtra, 0, pPager->nExtra);
  42579. }else{
  42580. *ppPage = p = (PgHdr *)sqlite3MallocZero(sizeof(PgHdr) + pPager->nExtra);
  42581. if( p==0 ){
  42582. sqlite3OsUnfetch(pPager->fd, (i64)(pgno-1) * pPager->pageSize, pData);
  42583. return SQLITE_NOMEM;
  42584. }
  42585. p->pExtra = (void *)&p[1];
  42586. p->flags = PGHDR_MMAP;
  42587. p->nRef = 1;
  42588. p->pPager = pPager;
  42589. }
  42590. assert( p->pExtra==(void *)&p[1] );
  42591. assert( p->pPage==0 );
  42592. assert( p->flags==PGHDR_MMAP );
  42593. assert( p->pPager==pPager );
  42594. assert( p->nRef==1 );
  42595. p->pgno = pgno;
  42596. p->pData = pData;
  42597. pPager->nMmapOut++;
  42598. return SQLITE_OK;
  42599. }
  42600. /*
  42601. ** Release a reference to page pPg. pPg must have been returned by an
  42602. ** earlier call to pagerAcquireMapPage().
  42603. */
  42604. static void pagerReleaseMapPage(PgHdr *pPg){
  42605. Pager *pPager = pPg->pPager;
  42606. pPager->nMmapOut--;
  42607. pPg->pDirty = pPager->pMmapFreelist;
  42608. pPager->pMmapFreelist = pPg;
  42609. assert( pPager->fd->pMethods->iVersion>=3 );
  42610. sqlite3OsUnfetch(pPager->fd, (i64)(pPg->pgno-1)*pPager->pageSize, pPg->pData);
  42611. }
  42612. /*
  42613. ** Free all PgHdr objects stored in the Pager.pMmapFreelist list.
  42614. */
  42615. static void pagerFreeMapHdrs(Pager *pPager){
  42616. PgHdr *p;
  42617. PgHdr *pNext;
  42618. for(p=pPager->pMmapFreelist; p; p=pNext){
  42619. pNext = p->pDirty;
  42620. sqlite3_free(p);
  42621. }
  42622. }
  42623. /*
  42624. ** Shutdown the page cache. Free all memory and close all files.
  42625. **
  42626. ** If a transaction was in progress when this routine is called, that
  42627. ** transaction is rolled back. All outstanding pages are invalidated
  42628. ** and their memory is freed. Any attempt to use a page associated
  42629. ** with this page cache after this function returns will likely
  42630. ** result in a coredump.
  42631. **
  42632. ** This function always succeeds. If a transaction is active an attempt
  42633. ** is made to roll it back. If an error occurs during the rollback
  42634. ** a hot journal may be left in the filesystem but no error is returned
  42635. ** to the caller.
  42636. */
  42637. SQLITE_PRIVATE int sqlite3PagerClose(Pager *pPager){
  42638. u8 *pTmp = (u8 *)pPager->pTmpSpace;
  42639. assert( assert_pager_state(pPager) );
  42640. disable_simulated_io_errors();
  42641. sqlite3BeginBenignMalloc();
  42642. pagerFreeMapHdrs(pPager);
  42643. /* pPager->errCode = 0; */
  42644. pPager->exclusiveMode = 0;
  42645. #ifndef SQLITE_OMIT_WAL
  42646. sqlite3WalClose(pPager->pWal, pPager->ckptSyncFlags, pPager->pageSize, pTmp);
  42647. pPager->pWal = 0;
  42648. #endif
  42649. pager_reset(pPager);
  42650. if( MEMDB ){
  42651. pager_unlock(pPager);
  42652. }else{
  42653. /* If it is open, sync the journal file before calling UnlockAndRollback.
  42654. ** If this is not done, then an unsynced portion of the open journal
  42655. ** file may be played back into the database. If a power failure occurs
  42656. ** while this is happening, the database could become corrupt.
  42657. **
  42658. ** If an error occurs while trying to sync the journal, shift the pager
  42659. ** into the ERROR state. This causes UnlockAndRollback to unlock the
  42660. ** database and close the journal file without attempting to roll it
  42661. ** back or finalize it. The next database user will have to do hot-journal
  42662. ** rollback before accessing the database file.
  42663. */
  42664. if( isOpen(pPager->jfd) ){
  42665. pager_error(pPager, pagerSyncHotJournal(pPager));
  42666. }
  42667. pagerUnlockAndRollback(pPager);
  42668. }
  42669. sqlite3EndBenignMalloc();
  42670. enable_simulated_io_errors();
  42671. PAGERTRACE(("CLOSE %d\n", PAGERID(pPager)));
  42672. IOTRACE(("CLOSE %p\n", pPager))
  42673. sqlite3OsClose(pPager->jfd);
  42674. sqlite3OsClose(pPager->fd);
  42675. sqlite3PageFree(pTmp);
  42676. sqlite3PcacheClose(pPager->pPCache);
  42677. #ifdef SQLITE_HAS_CODEC
  42678. if( pPager->xCodecFree ) pPager->xCodecFree(pPager->pCodec);
  42679. #endif
  42680. assert( !pPager->aSavepoint && !pPager->pInJournal );
  42681. assert( !isOpen(pPager->jfd) && !isOpen(pPager->sjfd) );
  42682. sqlite3_free(pPager);
  42683. return SQLITE_OK;
  42684. }
  42685. #if !defined(NDEBUG) || defined(SQLITE_TEST)
  42686. /*
  42687. ** Return the page number for page pPg.
  42688. */
  42689. SQLITE_PRIVATE Pgno sqlite3PagerPagenumber(DbPage *pPg){
  42690. return pPg->pgno;
  42691. }
  42692. #endif
  42693. /*
  42694. ** Increment the reference count for page pPg.
  42695. */
  42696. SQLITE_PRIVATE void sqlite3PagerRef(DbPage *pPg){
  42697. sqlite3PcacheRef(pPg);
  42698. }
  42699. /*
  42700. ** Sync the journal. In other words, make sure all the pages that have
  42701. ** been written to the journal have actually reached the surface of the
  42702. ** disk and can be restored in the event of a hot-journal rollback.
  42703. **
  42704. ** If the Pager.noSync flag is set, then this function is a no-op.
  42705. ** Otherwise, the actions required depend on the journal-mode and the
  42706. ** device characteristics of the file-system, as follows:
  42707. **
  42708. ** * If the journal file is an in-memory journal file, no action need
  42709. ** be taken.
  42710. **
  42711. ** * Otherwise, if the device does not support the SAFE_APPEND property,
  42712. ** then the nRec field of the most recently written journal header
  42713. ** is updated to contain the number of journal records that have
  42714. ** been written following it. If the pager is operating in full-sync
  42715. ** mode, then the journal file is synced before this field is updated.
  42716. **
  42717. ** * If the device does not support the SEQUENTIAL property, then
  42718. ** journal file is synced.
  42719. **
  42720. ** Or, in pseudo-code:
  42721. **
  42722. ** if( NOT <in-memory journal> ){
  42723. ** if( NOT SAFE_APPEND ){
  42724. ** if( <full-sync mode> ) xSync(<journal file>);
  42725. ** <update nRec field>
  42726. ** }
  42727. ** if( NOT SEQUENTIAL ) xSync(<journal file>);
  42728. ** }
  42729. **
  42730. ** If successful, this routine clears the PGHDR_NEED_SYNC flag of every
  42731. ** page currently held in memory before returning SQLITE_OK. If an IO
  42732. ** error is encountered, then the IO error code is returned to the caller.
  42733. */
  42734. static int syncJournal(Pager *pPager, int newHdr){
  42735. int rc; /* Return code */
  42736. assert( pPager->eState==PAGER_WRITER_CACHEMOD
  42737. || pPager->eState==PAGER_WRITER_DBMOD
  42738. );
  42739. assert( assert_pager_state(pPager) );
  42740. assert( !pagerUseWal(pPager) );
  42741. rc = sqlite3PagerExclusiveLock(pPager);
  42742. if( rc!=SQLITE_OK ) return rc;
  42743. if( !pPager->noSync ){
  42744. assert( !pPager->tempFile );
  42745. if( isOpen(pPager->jfd) && pPager->journalMode!=PAGER_JOURNALMODE_MEMORY ){
  42746. const int iDc = sqlite3OsDeviceCharacteristics(pPager->fd);
  42747. assert( isOpen(pPager->jfd) );
  42748. if( 0==(iDc&SQLITE_IOCAP_SAFE_APPEND) ){
  42749. /* This block deals with an obscure problem. If the last connection
  42750. ** that wrote to this database was operating in persistent-journal
  42751. ** mode, then the journal file may at this point actually be larger
  42752. ** than Pager.journalOff bytes. If the next thing in the journal
  42753. ** file happens to be a journal-header (written as part of the
  42754. ** previous connection's transaction), and a crash or power-failure
  42755. ** occurs after nRec is updated but before this connection writes
  42756. ** anything else to the journal file (or commits/rolls back its
  42757. ** transaction), then SQLite may become confused when doing the
  42758. ** hot-journal rollback following recovery. It may roll back all
  42759. ** of this connections data, then proceed to rolling back the old,
  42760. ** out-of-date data that follows it. Database corruption.
  42761. **
  42762. ** To work around this, if the journal file does appear to contain
  42763. ** a valid header following Pager.journalOff, then write a 0x00
  42764. ** byte to the start of it to prevent it from being recognized.
  42765. **
  42766. ** Variable iNextHdrOffset is set to the offset at which this
  42767. ** problematic header will occur, if it exists. aMagic is used
  42768. ** as a temporary buffer to inspect the first couple of bytes of
  42769. ** the potential journal header.
  42770. */
  42771. i64 iNextHdrOffset;
  42772. u8 aMagic[8];
  42773. u8 zHeader[sizeof(aJournalMagic)+4];
  42774. memcpy(zHeader, aJournalMagic, sizeof(aJournalMagic));
  42775. put32bits(&zHeader[sizeof(aJournalMagic)], pPager->nRec);
  42776. iNextHdrOffset = journalHdrOffset(pPager);
  42777. rc = sqlite3OsRead(pPager->jfd, aMagic, 8, iNextHdrOffset);
  42778. if( rc==SQLITE_OK && 0==memcmp(aMagic, aJournalMagic, 8) ){
  42779. static const u8 zerobyte = 0;
  42780. rc = sqlite3OsWrite(pPager->jfd, &zerobyte, 1, iNextHdrOffset);
  42781. }
  42782. if( rc!=SQLITE_OK && rc!=SQLITE_IOERR_SHORT_READ ){
  42783. return rc;
  42784. }
  42785. /* Write the nRec value into the journal file header. If in
  42786. ** full-synchronous mode, sync the journal first. This ensures that
  42787. ** all data has really hit the disk before nRec is updated to mark
  42788. ** it as a candidate for rollback.
  42789. **
  42790. ** This is not required if the persistent media supports the
  42791. ** SAFE_APPEND property. Because in this case it is not possible
  42792. ** for garbage data to be appended to the file, the nRec field
  42793. ** is populated with 0xFFFFFFFF when the journal header is written
  42794. ** and never needs to be updated.
  42795. */
  42796. if( pPager->fullSync && 0==(iDc&SQLITE_IOCAP_SEQUENTIAL) ){
  42797. PAGERTRACE(("SYNC journal of %d\n", PAGERID(pPager)));
  42798. IOTRACE(("JSYNC %p\n", pPager))
  42799. rc = sqlite3OsSync(pPager->jfd, pPager->syncFlags);
  42800. if( rc!=SQLITE_OK ) return rc;
  42801. }
  42802. IOTRACE(("JHDR %p %lld\n", pPager, pPager->journalHdr));
  42803. rc = sqlite3OsWrite(
  42804. pPager->jfd, zHeader, sizeof(zHeader), pPager->journalHdr
  42805. );
  42806. if( rc!=SQLITE_OK ) return rc;
  42807. }
  42808. if( 0==(iDc&SQLITE_IOCAP_SEQUENTIAL) ){
  42809. PAGERTRACE(("SYNC journal of %d\n", PAGERID(pPager)));
  42810. IOTRACE(("JSYNC %p\n", pPager))
  42811. rc = sqlite3OsSync(pPager->jfd, pPager->syncFlags|
  42812. (pPager->syncFlags==SQLITE_SYNC_FULL?SQLITE_SYNC_DATAONLY:0)
  42813. );
  42814. if( rc!=SQLITE_OK ) return rc;
  42815. }
  42816. pPager->journalHdr = pPager->journalOff;
  42817. if( newHdr && 0==(iDc&SQLITE_IOCAP_SAFE_APPEND) ){
  42818. pPager->nRec = 0;
  42819. rc = writeJournalHdr(pPager);
  42820. if( rc!=SQLITE_OK ) return rc;
  42821. }
  42822. }else{
  42823. pPager->journalHdr = pPager->journalOff;
  42824. }
  42825. }
  42826. /* Unless the pager is in noSync mode, the journal file was just
  42827. ** successfully synced. Either way, clear the PGHDR_NEED_SYNC flag on
  42828. ** all pages.
  42829. */
  42830. sqlite3PcacheClearSyncFlags(pPager->pPCache);
  42831. pPager->eState = PAGER_WRITER_DBMOD;
  42832. assert( assert_pager_state(pPager) );
  42833. return SQLITE_OK;
  42834. }
  42835. /*
  42836. ** The argument is the first in a linked list of dirty pages connected
  42837. ** by the PgHdr.pDirty pointer. This function writes each one of the
  42838. ** in-memory pages in the list to the database file. The argument may
  42839. ** be NULL, representing an empty list. In this case this function is
  42840. ** a no-op.
  42841. **
  42842. ** The pager must hold at least a RESERVED lock when this function
  42843. ** is called. Before writing anything to the database file, this lock
  42844. ** is upgraded to an EXCLUSIVE lock. If the lock cannot be obtained,
  42845. ** SQLITE_BUSY is returned and no data is written to the database file.
  42846. **
  42847. ** If the pager is a temp-file pager and the actual file-system file
  42848. ** is not yet open, it is created and opened before any data is
  42849. ** written out.
  42850. **
  42851. ** Once the lock has been upgraded and, if necessary, the file opened,
  42852. ** the pages are written out to the database file in list order. Writing
  42853. ** a page is skipped if it meets either of the following criteria:
  42854. **
  42855. ** * The page number is greater than Pager.dbSize, or
  42856. ** * The PGHDR_DONT_WRITE flag is set on the page.
  42857. **
  42858. ** If writing out a page causes the database file to grow, Pager.dbFileSize
  42859. ** is updated accordingly. If page 1 is written out, then the value cached
  42860. ** in Pager.dbFileVers[] is updated to match the new value stored in
  42861. ** the database file.
  42862. **
  42863. ** If everything is successful, SQLITE_OK is returned. If an IO error
  42864. ** occurs, an IO error code is returned. Or, if the EXCLUSIVE lock cannot
  42865. ** be obtained, SQLITE_BUSY is returned.
  42866. */
  42867. static int pager_write_pagelist(Pager *pPager, PgHdr *pList){
  42868. int rc = SQLITE_OK; /* Return code */
  42869. /* This function is only called for rollback pagers in WRITER_DBMOD state. */
  42870. assert( !pagerUseWal(pPager) );
  42871. assert( pPager->eState==PAGER_WRITER_DBMOD );
  42872. assert( pPager->eLock==EXCLUSIVE_LOCK );
  42873. /* If the file is a temp-file has not yet been opened, open it now. It
  42874. ** is not possible for rc to be other than SQLITE_OK if this branch
  42875. ** is taken, as pager_wait_on_lock() is a no-op for temp-files.
  42876. */
  42877. if( !isOpen(pPager->fd) ){
  42878. assert( pPager->tempFile && rc==SQLITE_OK );
  42879. rc = pagerOpentemp(pPager, pPager->fd, pPager->vfsFlags);
  42880. }
  42881. /* Before the first write, give the VFS a hint of what the final
  42882. ** file size will be.
  42883. */
  42884. assert( rc!=SQLITE_OK || isOpen(pPager->fd) );
  42885. if( rc==SQLITE_OK
  42886. && pPager->dbHintSize<pPager->dbSize
  42887. && (pList->pDirty || pList->pgno>pPager->dbHintSize)
  42888. ){
  42889. sqlite3_int64 szFile = pPager->pageSize * (sqlite3_int64)pPager->dbSize;
  42890. sqlite3OsFileControlHint(pPager->fd, SQLITE_FCNTL_SIZE_HINT, &szFile);
  42891. pPager->dbHintSize = pPager->dbSize;
  42892. }
  42893. while( rc==SQLITE_OK && pList ){
  42894. Pgno pgno = pList->pgno;
  42895. /* If there are dirty pages in the page cache with page numbers greater
  42896. ** than Pager.dbSize, this means sqlite3PagerTruncateImage() was called to
  42897. ** make the file smaller (presumably by auto-vacuum code). Do not write
  42898. ** any such pages to the file.
  42899. **
  42900. ** Also, do not write out any page that has the PGHDR_DONT_WRITE flag
  42901. ** set (set by sqlite3PagerDontWrite()).
  42902. */
  42903. if( pgno<=pPager->dbSize && 0==(pList->flags&PGHDR_DONT_WRITE) ){
  42904. i64 offset = (pgno-1)*(i64)pPager->pageSize; /* Offset to write */
  42905. char *pData; /* Data to write */
  42906. assert( (pList->flags&PGHDR_NEED_SYNC)==0 );
  42907. if( pList->pgno==1 ) pager_write_changecounter(pList);
  42908. /* Encode the database */
  42909. CODEC2(pPager, pList->pData, pgno, 6, return SQLITE_NOMEM, pData);
  42910. /* Write out the page data. */
  42911. rc = sqlite3OsWrite(pPager->fd, pData, pPager->pageSize, offset);
  42912. /* If page 1 was just written, update Pager.dbFileVers to match
  42913. ** the value now stored in the database file. If writing this
  42914. ** page caused the database file to grow, update dbFileSize.
  42915. */
  42916. if( pgno==1 ){
  42917. memcpy(&pPager->dbFileVers, &pData[24], sizeof(pPager->dbFileVers));
  42918. }
  42919. if( pgno>pPager->dbFileSize ){
  42920. pPager->dbFileSize = pgno;
  42921. }
  42922. pPager->aStat[PAGER_STAT_WRITE]++;
  42923. /* Update any backup objects copying the contents of this pager. */
  42924. sqlite3BackupUpdate(pPager->pBackup, pgno, (u8*)pList->pData);
  42925. PAGERTRACE(("STORE %d page %d hash(%08x)\n",
  42926. PAGERID(pPager), pgno, pager_pagehash(pList)));
  42927. IOTRACE(("PGOUT %p %d\n", pPager, pgno));
  42928. PAGER_INCR(sqlite3_pager_writedb_count);
  42929. }else{
  42930. PAGERTRACE(("NOSTORE %d page %d\n", PAGERID(pPager), pgno));
  42931. }
  42932. pager_set_pagehash(pList);
  42933. pList = pList->pDirty;
  42934. }
  42935. return rc;
  42936. }
  42937. /*
  42938. ** Ensure that the sub-journal file is open. If it is already open, this
  42939. ** function is a no-op.
  42940. **
  42941. ** SQLITE_OK is returned if everything goes according to plan. An
  42942. ** SQLITE_IOERR_XXX error code is returned if a call to sqlite3OsOpen()
  42943. ** fails.
  42944. */
  42945. static int openSubJournal(Pager *pPager){
  42946. int rc = SQLITE_OK;
  42947. if( !isOpen(pPager->sjfd) ){
  42948. if( pPager->journalMode==PAGER_JOURNALMODE_MEMORY || pPager->subjInMemory ){
  42949. sqlite3MemJournalOpen(pPager->sjfd);
  42950. }else{
  42951. rc = pagerOpentemp(pPager, pPager->sjfd, SQLITE_OPEN_SUBJOURNAL);
  42952. }
  42953. }
  42954. return rc;
  42955. }
  42956. /*
  42957. ** Append a record of the current state of page pPg to the sub-journal.
  42958. ** It is the callers responsibility to use subjRequiresPage() to check
  42959. ** that it is really required before calling this function.
  42960. **
  42961. ** If successful, set the bit corresponding to pPg->pgno in the bitvecs
  42962. ** for all open savepoints before returning.
  42963. **
  42964. ** This function returns SQLITE_OK if everything is successful, an IO
  42965. ** error code if the attempt to write to the sub-journal fails, or
  42966. ** SQLITE_NOMEM if a malloc fails while setting a bit in a savepoint
  42967. ** bitvec.
  42968. */
  42969. static int subjournalPage(PgHdr *pPg){
  42970. int rc = SQLITE_OK;
  42971. Pager *pPager = pPg->pPager;
  42972. if( pPager->journalMode!=PAGER_JOURNALMODE_OFF ){
  42973. /* Open the sub-journal, if it has not already been opened */
  42974. assert( pPager->useJournal );
  42975. assert( isOpen(pPager->jfd) || pagerUseWal(pPager) );
  42976. assert( isOpen(pPager->sjfd) || pPager->nSubRec==0 );
  42977. assert( pagerUseWal(pPager)
  42978. || pageInJournal(pPager, pPg)
  42979. || pPg->pgno>pPager->dbOrigSize
  42980. );
  42981. rc = openSubJournal(pPager);
  42982. /* If the sub-journal was opened successfully (or was already open),
  42983. ** write the journal record into the file. */
  42984. if( rc==SQLITE_OK ){
  42985. void *pData = pPg->pData;
  42986. i64 offset = (i64)pPager->nSubRec*(4+pPager->pageSize);
  42987. char *pData2;
  42988. CODEC2(pPager, pData, pPg->pgno, 7, return SQLITE_NOMEM, pData2);
  42989. PAGERTRACE(("STMT-JOURNAL %d page %d\n", PAGERID(pPager), pPg->pgno));
  42990. rc = write32bits(pPager->sjfd, offset, pPg->pgno);
  42991. if( rc==SQLITE_OK ){
  42992. rc = sqlite3OsWrite(pPager->sjfd, pData2, pPager->pageSize, offset+4);
  42993. }
  42994. }
  42995. }
  42996. if( rc==SQLITE_OK ){
  42997. pPager->nSubRec++;
  42998. assert( pPager->nSavepoint>0 );
  42999. rc = addToSavepointBitvecs(pPager, pPg->pgno);
  43000. }
  43001. return rc;
  43002. }
  43003. /*
  43004. ** This function is called by the pcache layer when it has reached some
  43005. ** soft memory limit. The first argument is a pointer to a Pager object
  43006. ** (cast as a void*). The pager is always 'purgeable' (not an in-memory
  43007. ** database). The second argument is a reference to a page that is
  43008. ** currently dirty but has no outstanding references. The page
  43009. ** is always associated with the Pager object passed as the first
  43010. ** argument.
  43011. **
  43012. ** The job of this function is to make pPg clean by writing its contents
  43013. ** out to the database file, if possible. This may involve syncing the
  43014. ** journal file.
  43015. **
  43016. ** If successful, sqlite3PcacheMakeClean() is called on the page and
  43017. ** SQLITE_OK returned. If an IO error occurs while trying to make the
  43018. ** page clean, the IO error code is returned. If the page cannot be
  43019. ** made clean for some other reason, but no error occurs, then SQLITE_OK
  43020. ** is returned by sqlite3PcacheMakeClean() is not called.
  43021. */
  43022. static int pagerStress(void *p, PgHdr *pPg){
  43023. Pager *pPager = (Pager *)p;
  43024. int rc = SQLITE_OK;
  43025. assert( pPg->pPager==pPager );
  43026. assert( pPg->flags&PGHDR_DIRTY );
  43027. /* The doNotSpill NOSYNC bit is set during times when doing a sync of
  43028. ** journal (and adding a new header) is not allowed. This occurs
  43029. ** during calls to sqlite3PagerWrite() while trying to journal multiple
  43030. ** pages belonging to the same sector.
  43031. **
  43032. ** The doNotSpill ROLLBACK and OFF bits inhibits all cache spilling
  43033. ** regardless of whether or not a sync is required. This is set during
  43034. ** a rollback or by user request, respectively.
  43035. **
  43036. ** Spilling is also prohibited when in an error state since that could
  43037. ** lead to database corruption. In the current implementation it
  43038. ** is impossible for sqlite3PcacheFetch() to be called with createFlag==3
  43039. ** while in the error state, hence it is impossible for this routine to
  43040. ** be called in the error state. Nevertheless, we include a NEVER()
  43041. ** test for the error state as a safeguard against future changes.
  43042. */
  43043. if( NEVER(pPager->errCode) ) return SQLITE_OK;
  43044. testcase( pPager->doNotSpill & SPILLFLAG_ROLLBACK );
  43045. testcase( pPager->doNotSpill & SPILLFLAG_OFF );
  43046. testcase( pPager->doNotSpill & SPILLFLAG_NOSYNC );
  43047. if( pPager->doNotSpill
  43048. && ((pPager->doNotSpill & (SPILLFLAG_ROLLBACK|SPILLFLAG_OFF))!=0
  43049. || (pPg->flags & PGHDR_NEED_SYNC)!=0)
  43050. ){
  43051. return SQLITE_OK;
  43052. }
  43053. pPg->pDirty = 0;
  43054. if( pagerUseWal(pPager) ){
  43055. /* Write a single frame for this page to the log. */
  43056. if( subjRequiresPage(pPg) ){
  43057. rc = subjournalPage(pPg);
  43058. }
  43059. if( rc==SQLITE_OK ){
  43060. rc = pagerWalFrames(pPager, pPg, 0, 0);
  43061. }
  43062. }else{
  43063. /* Sync the journal file if required. */
  43064. if( pPg->flags&PGHDR_NEED_SYNC
  43065. || pPager->eState==PAGER_WRITER_CACHEMOD
  43066. ){
  43067. rc = syncJournal(pPager, 1);
  43068. }
  43069. /* If the page number of this page is larger than the current size of
  43070. ** the database image, it may need to be written to the sub-journal.
  43071. ** This is because the call to pager_write_pagelist() below will not
  43072. ** actually write data to the file in this case.
  43073. **
  43074. ** Consider the following sequence of events:
  43075. **
  43076. ** BEGIN;
  43077. ** <journal page X>
  43078. ** <modify page X>
  43079. ** SAVEPOINT sp;
  43080. ** <shrink database file to Y pages>
  43081. ** pagerStress(page X)
  43082. ** ROLLBACK TO sp;
  43083. **
  43084. ** If (X>Y), then when pagerStress is called page X will not be written
  43085. ** out to the database file, but will be dropped from the cache. Then,
  43086. ** following the "ROLLBACK TO sp" statement, reading page X will read
  43087. ** data from the database file. This will be the copy of page X as it
  43088. ** was when the transaction started, not as it was when "SAVEPOINT sp"
  43089. ** was executed.
  43090. **
  43091. ** The solution is to write the current data for page X into the
  43092. ** sub-journal file now (if it is not already there), so that it will
  43093. ** be restored to its current value when the "ROLLBACK TO sp" is
  43094. ** executed.
  43095. */
  43096. if( NEVER(
  43097. rc==SQLITE_OK && pPg->pgno>pPager->dbSize && subjRequiresPage(pPg)
  43098. ) ){
  43099. rc = subjournalPage(pPg);
  43100. }
  43101. /* Write the contents of the page out to the database file. */
  43102. if( rc==SQLITE_OK ){
  43103. assert( (pPg->flags&PGHDR_NEED_SYNC)==0 );
  43104. rc = pager_write_pagelist(pPager, pPg);
  43105. }
  43106. }
  43107. /* Mark the page as clean. */
  43108. if( rc==SQLITE_OK ){
  43109. PAGERTRACE(("STRESS %d page %d\n", PAGERID(pPager), pPg->pgno));
  43110. sqlite3PcacheMakeClean(pPg);
  43111. }
  43112. return pager_error(pPager, rc);
  43113. }
  43114. /*
  43115. ** Allocate and initialize a new Pager object and put a pointer to it
  43116. ** in *ppPager. The pager should eventually be freed by passing it
  43117. ** to sqlite3PagerClose().
  43118. **
  43119. ** The zFilename argument is the path to the database file to open.
  43120. ** If zFilename is NULL then a randomly-named temporary file is created
  43121. ** and used as the file to be cached. Temporary files are be deleted
  43122. ** automatically when they are closed. If zFilename is ":memory:" then
  43123. ** all information is held in cache. It is never written to disk.
  43124. ** This can be used to implement an in-memory database.
  43125. **
  43126. ** The nExtra parameter specifies the number of bytes of space allocated
  43127. ** along with each page reference. This space is available to the user
  43128. ** via the sqlite3PagerGetExtra() API.
  43129. **
  43130. ** The flags argument is used to specify properties that affect the
  43131. ** operation of the pager. It should be passed some bitwise combination
  43132. ** of the PAGER_* flags.
  43133. **
  43134. ** The vfsFlags parameter is a bitmask to pass to the flags parameter
  43135. ** of the xOpen() method of the supplied VFS when opening files.
  43136. **
  43137. ** If the pager object is allocated and the specified file opened
  43138. ** successfully, SQLITE_OK is returned and *ppPager set to point to
  43139. ** the new pager object. If an error occurs, *ppPager is set to NULL
  43140. ** and error code returned. This function may return SQLITE_NOMEM
  43141. ** (sqlite3Malloc() is used to allocate memory), SQLITE_CANTOPEN or
  43142. ** various SQLITE_IO_XXX errors.
  43143. */
  43144. SQLITE_PRIVATE int sqlite3PagerOpen(
  43145. sqlite3_vfs *pVfs, /* The virtual file system to use */
  43146. Pager **ppPager, /* OUT: Return the Pager structure here */
  43147. const char *zFilename, /* Name of the database file to open */
  43148. int nExtra, /* Extra bytes append to each in-memory page */
  43149. int flags, /* flags controlling this file */
  43150. int vfsFlags, /* flags passed through to sqlite3_vfs.xOpen() */
  43151. void (*xReinit)(DbPage*) /* Function to reinitialize pages */
  43152. ){
  43153. u8 *pPtr;
  43154. Pager *pPager = 0; /* Pager object to allocate and return */
  43155. int rc = SQLITE_OK; /* Return code */
  43156. int tempFile = 0; /* True for temp files (incl. in-memory files) */
  43157. int memDb = 0; /* True if this is an in-memory file */
  43158. int readOnly = 0; /* True if this is a read-only file */
  43159. int journalFileSize; /* Bytes to allocate for each journal fd */
  43160. char *zPathname = 0; /* Full path to database file */
  43161. int nPathname = 0; /* Number of bytes in zPathname */
  43162. int useJournal = (flags & PAGER_OMIT_JOURNAL)==0; /* False to omit journal */
  43163. int pcacheSize = sqlite3PcacheSize(); /* Bytes to allocate for PCache */
  43164. u32 szPageDflt = SQLITE_DEFAULT_PAGE_SIZE; /* Default page size */
  43165. const char *zUri = 0; /* URI args to copy */
  43166. int nUri = 0; /* Number of bytes of URI args at *zUri */
  43167. /* Figure out how much space is required for each journal file-handle
  43168. ** (there are two of them, the main journal and the sub-journal). This
  43169. ** is the maximum space required for an in-memory journal file handle
  43170. ** and a regular journal file-handle. Note that a "regular journal-handle"
  43171. ** may be a wrapper capable of caching the first portion of the journal
  43172. ** file in memory to implement the atomic-write optimization (see
  43173. ** source file journal.c).
  43174. */
  43175. if( sqlite3JournalSize(pVfs)>sqlite3MemJournalSize() ){
  43176. journalFileSize = ROUND8(sqlite3JournalSize(pVfs));
  43177. }else{
  43178. journalFileSize = ROUND8(sqlite3MemJournalSize());
  43179. }
  43180. /* Set the output variable to NULL in case an error occurs. */
  43181. *ppPager = 0;
  43182. #ifndef SQLITE_OMIT_MEMORYDB
  43183. if( flags & PAGER_MEMORY ){
  43184. memDb = 1;
  43185. if( zFilename && zFilename[0] ){
  43186. zPathname = sqlite3DbStrDup(0, zFilename);
  43187. if( zPathname==0 ) return SQLITE_NOMEM;
  43188. nPathname = sqlite3Strlen30(zPathname);
  43189. zFilename = 0;
  43190. }
  43191. }
  43192. #endif
  43193. /* Compute and store the full pathname in an allocated buffer pointed
  43194. ** to by zPathname, length nPathname. Or, if this is a temporary file,
  43195. ** leave both nPathname and zPathname set to 0.
  43196. */
  43197. if( zFilename && zFilename[0] ){
  43198. const char *z;
  43199. nPathname = pVfs->mxPathname+1;
  43200. zPathname = sqlite3DbMallocRaw(0, nPathname*2);
  43201. if( zPathname==0 ){
  43202. return SQLITE_NOMEM;
  43203. }
  43204. zPathname[0] = 0; /* Make sure initialized even if FullPathname() fails */
  43205. rc = sqlite3OsFullPathname(pVfs, zFilename, nPathname, zPathname);
  43206. nPathname = sqlite3Strlen30(zPathname);
  43207. z = zUri = &zFilename[sqlite3Strlen30(zFilename)+1];
  43208. while( *z ){
  43209. z += sqlite3Strlen30(z)+1;
  43210. z += sqlite3Strlen30(z)+1;
  43211. }
  43212. nUri = (int)(&z[1] - zUri);
  43213. assert( nUri>=0 );
  43214. if( rc==SQLITE_OK && nPathname+8>pVfs->mxPathname ){
  43215. /* This branch is taken when the journal path required by
  43216. ** the database being opened will be more than pVfs->mxPathname
  43217. ** bytes in length. This means the database cannot be opened,
  43218. ** as it will not be possible to open the journal file or even
  43219. ** check for a hot-journal before reading.
  43220. */
  43221. rc = SQLITE_CANTOPEN_BKPT;
  43222. }
  43223. if( rc!=SQLITE_OK ){
  43224. sqlite3DbFree(0, zPathname);
  43225. return rc;
  43226. }
  43227. }
  43228. /* Allocate memory for the Pager structure, PCache object, the
  43229. ** three file descriptors, the database file name and the journal
  43230. ** file name. The layout in memory is as follows:
  43231. **
  43232. ** Pager object (sizeof(Pager) bytes)
  43233. ** PCache object (sqlite3PcacheSize() bytes)
  43234. ** Database file handle (pVfs->szOsFile bytes)
  43235. ** Sub-journal file handle (journalFileSize bytes)
  43236. ** Main journal file handle (journalFileSize bytes)
  43237. ** Database file name (nPathname+1 bytes)
  43238. ** Journal file name (nPathname+8+1 bytes)
  43239. */
  43240. pPtr = (u8 *)sqlite3MallocZero(
  43241. ROUND8(sizeof(*pPager)) + /* Pager structure */
  43242. ROUND8(pcacheSize) + /* PCache object */
  43243. ROUND8(pVfs->szOsFile) + /* The main db file */
  43244. journalFileSize * 2 + /* The two journal files */
  43245. nPathname + 1 + nUri + /* zFilename */
  43246. nPathname + 8 + 2 /* zJournal */
  43247. #ifndef SQLITE_OMIT_WAL
  43248. + nPathname + 4 + 2 /* zWal */
  43249. #endif
  43250. );
  43251. assert( EIGHT_BYTE_ALIGNMENT(SQLITE_INT_TO_PTR(journalFileSize)) );
  43252. if( !pPtr ){
  43253. sqlite3DbFree(0, zPathname);
  43254. return SQLITE_NOMEM;
  43255. }
  43256. pPager = (Pager*)(pPtr);
  43257. pPager->pPCache = (PCache*)(pPtr += ROUND8(sizeof(*pPager)));
  43258. pPager->fd = (sqlite3_file*)(pPtr += ROUND8(pcacheSize));
  43259. pPager->sjfd = (sqlite3_file*)(pPtr += ROUND8(pVfs->szOsFile));
  43260. pPager->jfd = (sqlite3_file*)(pPtr += journalFileSize);
  43261. pPager->zFilename = (char*)(pPtr += journalFileSize);
  43262. assert( EIGHT_BYTE_ALIGNMENT(pPager->jfd) );
  43263. /* Fill in the Pager.zFilename and Pager.zJournal buffers, if required. */
  43264. if( zPathname ){
  43265. assert( nPathname>0 );
  43266. pPager->zJournal = (char*)(pPtr += nPathname + 1 + nUri);
  43267. memcpy(pPager->zFilename, zPathname, nPathname);
  43268. if( nUri ) memcpy(&pPager->zFilename[nPathname+1], zUri, nUri);
  43269. memcpy(pPager->zJournal, zPathname, nPathname);
  43270. memcpy(&pPager->zJournal[nPathname], "-journal\000", 8+2);
  43271. sqlite3FileSuffix3(pPager->zFilename, pPager->zJournal);
  43272. #ifndef SQLITE_OMIT_WAL
  43273. pPager->zWal = &pPager->zJournal[nPathname+8+1];
  43274. memcpy(pPager->zWal, zPathname, nPathname);
  43275. memcpy(&pPager->zWal[nPathname], "-wal\000", 4+1);
  43276. sqlite3FileSuffix3(pPager->zFilename, pPager->zWal);
  43277. #endif
  43278. sqlite3DbFree(0, zPathname);
  43279. }
  43280. pPager->pVfs = pVfs;
  43281. pPager->vfsFlags = vfsFlags;
  43282. /* Open the pager file.
  43283. */
  43284. if( zFilename && zFilename[0] ){
  43285. int fout = 0; /* VFS flags returned by xOpen() */
  43286. rc = sqlite3OsOpen(pVfs, pPager->zFilename, pPager->fd, vfsFlags, &fout);
  43287. assert( !memDb );
  43288. readOnly = (fout&SQLITE_OPEN_READONLY);
  43289. /* If the file was successfully opened for read/write access,
  43290. ** choose a default page size in case we have to create the
  43291. ** database file. The default page size is the maximum of:
  43292. **
  43293. ** + SQLITE_DEFAULT_PAGE_SIZE,
  43294. ** + The value returned by sqlite3OsSectorSize()
  43295. ** + The largest page size that can be written atomically.
  43296. */
  43297. if( rc==SQLITE_OK ){
  43298. int iDc = sqlite3OsDeviceCharacteristics(pPager->fd);
  43299. if( !readOnly ){
  43300. setSectorSize(pPager);
  43301. assert(SQLITE_DEFAULT_PAGE_SIZE<=SQLITE_MAX_DEFAULT_PAGE_SIZE);
  43302. if( szPageDflt<pPager->sectorSize ){
  43303. if( pPager->sectorSize>SQLITE_MAX_DEFAULT_PAGE_SIZE ){
  43304. szPageDflt = SQLITE_MAX_DEFAULT_PAGE_SIZE;
  43305. }else{
  43306. szPageDflt = (u32)pPager->sectorSize;
  43307. }
  43308. }
  43309. #ifdef SQLITE_ENABLE_ATOMIC_WRITE
  43310. {
  43311. int ii;
  43312. assert(SQLITE_IOCAP_ATOMIC512==(512>>8));
  43313. assert(SQLITE_IOCAP_ATOMIC64K==(65536>>8));
  43314. assert(SQLITE_MAX_DEFAULT_PAGE_SIZE<=65536);
  43315. for(ii=szPageDflt; ii<=SQLITE_MAX_DEFAULT_PAGE_SIZE; ii=ii*2){
  43316. if( iDc&(SQLITE_IOCAP_ATOMIC|(ii>>8)) ){
  43317. szPageDflt = ii;
  43318. }
  43319. }
  43320. }
  43321. #endif
  43322. }
  43323. pPager->noLock = sqlite3_uri_boolean(zFilename, "nolock", 0);
  43324. if( (iDc & SQLITE_IOCAP_IMMUTABLE)!=0
  43325. || sqlite3_uri_boolean(zFilename, "immutable", 0) ){
  43326. vfsFlags |= SQLITE_OPEN_READONLY;
  43327. goto act_like_temp_file;
  43328. }
  43329. }
  43330. }else{
  43331. /* If a temporary file is requested, it is not opened immediately.
  43332. ** In this case we accept the default page size and delay actually
  43333. ** opening the file until the first call to OsWrite().
  43334. **
  43335. ** This branch is also run for an in-memory database. An in-memory
  43336. ** database is the same as a temp-file that is never written out to
  43337. ** disk and uses an in-memory rollback journal.
  43338. **
  43339. ** This branch also runs for files marked as immutable.
  43340. */
  43341. act_like_temp_file:
  43342. tempFile = 1;
  43343. pPager->eState = PAGER_READER; /* Pretend we already have a lock */
  43344. pPager->eLock = EXCLUSIVE_LOCK; /* Pretend we are in EXCLUSIVE locking mode */
  43345. pPager->noLock = 1; /* Do no locking */
  43346. readOnly = (vfsFlags&SQLITE_OPEN_READONLY);
  43347. }
  43348. /* The following call to PagerSetPagesize() serves to set the value of
  43349. ** Pager.pageSize and to allocate the Pager.pTmpSpace buffer.
  43350. */
  43351. if( rc==SQLITE_OK ){
  43352. assert( pPager->memDb==0 );
  43353. rc = sqlite3PagerSetPagesize(pPager, &szPageDflt, -1);
  43354. testcase( rc!=SQLITE_OK );
  43355. }
  43356. /* Initialize the PCache object. */
  43357. if( rc==SQLITE_OK ){
  43358. assert( nExtra<1000 );
  43359. nExtra = ROUND8(nExtra);
  43360. rc = sqlite3PcacheOpen(szPageDflt, nExtra, !memDb,
  43361. !memDb?pagerStress:0, (void *)pPager, pPager->pPCache);
  43362. }
  43363. /* If an error occurred above, free the Pager structure and close the file.
  43364. */
  43365. if( rc!=SQLITE_OK ){
  43366. sqlite3OsClose(pPager->fd);
  43367. sqlite3PageFree(pPager->pTmpSpace);
  43368. sqlite3_free(pPager);
  43369. return rc;
  43370. }
  43371. PAGERTRACE(("OPEN %d %s\n", FILEHANDLEID(pPager->fd), pPager->zFilename));
  43372. IOTRACE(("OPEN %p %s\n", pPager, pPager->zFilename))
  43373. pPager->useJournal = (u8)useJournal;
  43374. /* pPager->stmtOpen = 0; */
  43375. /* pPager->stmtInUse = 0; */
  43376. /* pPager->nRef = 0; */
  43377. /* pPager->stmtSize = 0; */
  43378. /* pPager->stmtJSize = 0; */
  43379. /* pPager->nPage = 0; */
  43380. pPager->mxPgno = SQLITE_MAX_PAGE_COUNT;
  43381. /* pPager->state = PAGER_UNLOCK; */
  43382. /* pPager->errMask = 0; */
  43383. pPager->tempFile = (u8)tempFile;
  43384. assert( tempFile==PAGER_LOCKINGMODE_NORMAL
  43385. || tempFile==PAGER_LOCKINGMODE_EXCLUSIVE );
  43386. assert( PAGER_LOCKINGMODE_EXCLUSIVE==1 );
  43387. pPager->exclusiveMode = (u8)tempFile;
  43388. pPager->changeCountDone = pPager->tempFile;
  43389. pPager->memDb = (u8)memDb;
  43390. pPager->readOnly = (u8)readOnly;
  43391. assert( useJournal || pPager->tempFile );
  43392. pPager->noSync = pPager->tempFile;
  43393. if( pPager->noSync ){
  43394. assert( pPager->fullSync==0 );
  43395. assert( pPager->syncFlags==0 );
  43396. assert( pPager->walSyncFlags==0 );
  43397. assert( pPager->ckptSyncFlags==0 );
  43398. }else{
  43399. pPager->fullSync = 1;
  43400. pPager->syncFlags = SQLITE_SYNC_NORMAL;
  43401. pPager->walSyncFlags = SQLITE_SYNC_NORMAL | WAL_SYNC_TRANSACTIONS;
  43402. pPager->ckptSyncFlags = SQLITE_SYNC_NORMAL;
  43403. }
  43404. /* pPager->pFirst = 0; */
  43405. /* pPager->pFirstSynced = 0; */
  43406. /* pPager->pLast = 0; */
  43407. pPager->nExtra = (u16)nExtra;
  43408. pPager->journalSizeLimit = SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT;
  43409. assert( isOpen(pPager->fd) || tempFile );
  43410. setSectorSize(pPager);
  43411. if( !useJournal ){
  43412. pPager->journalMode = PAGER_JOURNALMODE_OFF;
  43413. }else if( memDb ){
  43414. pPager->journalMode = PAGER_JOURNALMODE_MEMORY;
  43415. }
  43416. /* pPager->xBusyHandler = 0; */
  43417. /* pPager->pBusyHandlerArg = 0; */
  43418. pPager->xReiniter = xReinit;
  43419. /* memset(pPager->aHash, 0, sizeof(pPager->aHash)); */
  43420. /* pPager->szMmap = SQLITE_DEFAULT_MMAP_SIZE // will be set by btree.c */
  43421. *ppPager = pPager;
  43422. return SQLITE_OK;
  43423. }
  43424. /* Verify that the database file has not be deleted or renamed out from
  43425. ** under the pager. Return SQLITE_OK if the database is still were it ought
  43426. ** to be on disk. Return non-zero (SQLITE_READONLY_DBMOVED or some other error
  43427. ** code from sqlite3OsAccess()) if the database has gone missing.
  43428. */
  43429. static int databaseIsUnmoved(Pager *pPager){
  43430. int bHasMoved = 0;
  43431. int rc;
  43432. if( pPager->tempFile ) return SQLITE_OK;
  43433. if( pPager->dbSize==0 ) return SQLITE_OK;
  43434. assert( pPager->zFilename && pPager->zFilename[0] );
  43435. rc = sqlite3OsFileControl(pPager->fd, SQLITE_FCNTL_HAS_MOVED, &bHasMoved);
  43436. if( rc==SQLITE_NOTFOUND ){
  43437. /* If the HAS_MOVED file-control is unimplemented, assume that the file
  43438. ** has not been moved. That is the historical behavior of SQLite: prior to
  43439. ** version 3.8.3, it never checked */
  43440. rc = SQLITE_OK;
  43441. }else if( rc==SQLITE_OK && bHasMoved ){
  43442. rc = SQLITE_READONLY_DBMOVED;
  43443. }
  43444. return rc;
  43445. }
  43446. /*
  43447. ** This function is called after transitioning from PAGER_UNLOCK to
  43448. ** PAGER_SHARED state. It tests if there is a hot journal present in
  43449. ** the file-system for the given pager. A hot journal is one that
  43450. ** needs to be played back. According to this function, a hot-journal
  43451. ** file exists if the following criteria are met:
  43452. **
  43453. ** * The journal file exists in the file system, and
  43454. ** * No process holds a RESERVED or greater lock on the database file, and
  43455. ** * The database file itself is greater than 0 bytes in size, and
  43456. ** * The first byte of the journal file exists and is not 0x00.
  43457. **
  43458. ** If the current size of the database file is 0 but a journal file
  43459. ** exists, that is probably an old journal left over from a prior
  43460. ** database with the same name. In this case the journal file is
  43461. ** just deleted using OsDelete, *pExists is set to 0 and SQLITE_OK
  43462. ** is returned.
  43463. **
  43464. ** This routine does not check if there is a master journal filename
  43465. ** at the end of the file. If there is, and that master journal file
  43466. ** does not exist, then the journal file is not really hot. In this
  43467. ** case this routine will return a false-positive. The pager_playback()
  43468. ** routine will discover that the journal file is not really hot and
  43469. ** will not roll it back.
  43470. **
  43471. ** If a hot-journal file is found to exist, *pExists is set to 1 and
  43472. ** SQLITE_OK returned. If no hot-journal file is present, *pExists is
  43473. ** set to 0 and SQLITE_OK returned. If an IO error occurs while trying
  43474. ** to determine whether or not a hot-journal file exists, the IO error
  43475. ** code is returned and the value of *pExists is undefined.
  43476. */
  43477. static int hasHotJournal(Pager *pPager, int *pExists){
  43478. sqlite3_vfs * const pVfs = pPager->pVfs;
  43479. int rc = SQLITE_OK; /* Return code */
  43480. int exists = 1; /* True if a journal file is present */
  43481. int jrnlOpen = !!isOpen(pPager->jfd);
  43482. assert( pPager->useJournal );
  43483. assert( isOpen(pPager->fd) );
  43484. assert( pPager->eState==PAGER_OPEN );
  43485. assert( jrnlOpen==0 || ( sqlite3OsDeviceCharacteristics(pPager->jfd) &
  43486. SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN
  43487. ));
  43488. *pExists = 0;
  43489. if( !jrnlOpen ){
  43490. rc = sqlite3OsAccess(pVfs, pPager->zJournal, SQLITE_ACCESS_EXISTS, &exists);
  43491. }
  43492. if( rc==SQLITE_OK && exists ){
  43493. int locked = 0; /* True if some process holds a RESERVED lock */
  43494. /* Race condition here: Another process might have been holding the
  43495. ** the RESERVED lock and have a journal open at the sqlite3OsAccess()
  43496. ** call above, but then delete the journal and drop the lock before
  43497. ** we get to the following sqlite3OsCheckReservedLock() call. If that
  43498. ** is the case, this routine might think there is a hot journal when
  43499. ** in fact there is none. This results in a false-positive which will
  43500. ** be dealt with by the playback routine. Ticket #3883.
  43501. */
  43502. rc = sqlite3OsCheckReservedLock(pPager->fd, &locked);
  43503. if( rc==SQLITE_OK && !locked ){
  43504. Pgno nPage; /* Number of pages in database file */
  43505. rc = pagerPagecount(pPager, &nPage);
  43506. if( rc==SQLITE_OK ){
  43507. /* If the database is zero pages in size, that means that either (1) the
  43508. ** journal is a remnant from a prior database with the same name where
  43509. ** the database file but not the journal was deleted, or (2) the initial
  43510. ** transaction that populates a new database is being rolled back.
  43511. ** In either case, the journal file can be deleted. However, take care
  43512. ** not to delete the journal file if it is already open due to
  43513. ** journal_mode=PERSIST.
  43514. */
  43515. if( nPage==0 && !jrnlOpen ){
  43516. sqlite3BeginBenignMalloc();
  43517. if( pagerLockDb(pPager, RESERVED_LOCK)==SQLITE_OK ){
  43518. sqlite3OsDelete(pVfs, pPager->zJournal, 0);
  43519. if( !pPager->exclusiveMode ) pagerUnlockDb(pPager, SHARED_LOCK);
  43520. }
  43521. sqlite3EndBenignMalloc();
  43522. }else{
  43523. /* The journal file exists and no other connection has a reserved
  43524. ** or greater lock on the database file. Now check that there is
  43525. ** at least one non-zero bytes at the start of the journal file.
  43526. ** If there is, then we consider this journal to be hot. If not,
  43527. ** it can be ignored.
  43528. */
  43529. if( !jrnlOpen ){
  43530. int f = SQLITE_OPEN_READONLY|SQLITE_OPEN_MAIN_JOURNAL;
  43531. rc = sqlite3OsOpen(pVfs, pPager->zJournal, pPager->jfd, f, &f);
  43532. }
  43533. if( rc==SQLITE_OK ){
  43534. u8 first = 0;
  43535. rc = sqlite3OsRead(pPager->jfd, (void *)&first, 1, 0);
  43536. if( rc==SQLITE_IOERR_SHORT_READ ){
  43537. rc = SQLITE_OK;
  43538. }
  43539. if( !jrnlOpen ){
  43540. sqlite3OsClose(pPager->jfd);
  43541. }
  43542. *pExists = (first!=0);
  43543. }else if( rc==SQLITE_CANTOPEN ){
  43544. /* If we cannot open the rollback journal file in order to see if
  43545. ** it has a zero header, that might be due to an I/O error, or
  43546. ** it might be due to the race condition described above and in
  43547. ** ticket #3883. Either way, assume that the journal is hot.
  43548. ** This might be a false positive. But if it is, then the
  43549. ** automatic journal playback and recovery mechanism will deal
  43550. ** with it under an EXCLUSIVE lock where we do not need to
  43551. ** worry so much with race conditions.
  43552. */
  43553. *pExists = 1;
  43554. rc = SQLITE_OK;
  43555. }
  43556. }
  43557. }
  43558. }
  43559. }
  43560. return rc;
  43561. }
  43562. /*
  43563. ** This function is called to obtain a shared lock on the database file.
  43564. ** It is illegal to call sqlite3PagerAcquire() until after this function
  43565. ** has been successfully called. If a shared-lock is already held when
  43566. ** this function is called, it is a no-op.
  43567. **
  43568. ** The following operations are also performed by this function.
  43569. **
  43570. ** 1) If the pager is currently in PAGER_OPEN state (no lock held
  43571. ** on the database file), then an attempt is made to obtain a
  43572. ** SHARED lock on the database file. Immediately after obtaining
  43573. ** the SHARED lock, the file-system is checked for a hot-journal,
  43574. ** which is played back if present. Following any hot-journal
  43575. ** rollback, the contents of the cache are validated by checking
  43576. ** the 'change-counter' field of the database file header and
  43577. ** discarded if they are found to be invalid.
  43578. **
  43579. ** 2) If the pager is running in exclusive-mode, and there are currently
  43580. ** no outstanding references to any pages, and is in the error state,
  43581. ** then an attempt is made to clear the error state by discarding
  43582. ** the contents of the page cache and rolling back any open journal
  43583. ** file.
  43584. **
  43585. ** If everything is successful, SQLITE_OK is returned. If an IO error
  43586. ** occurs while locking the database, checking for a hot-journal file or
  43587. ** rolling back a journal file, the IO error code is returned.
  43588. */
  43589. SQLITE_PRIVATE int sqlite3PagerSharedLock(Pager *pPager){
  43590. int rc = SQLITE_OK; /* Return code */
  43591. /* This routine is only called from b-tree and only when there are no
  43592. ** outstanding pages. This implies that the pager state should either
  43593. ** be OPEN or READER. READER is only possible if the pager is or was in
  43594. ** exclusive access mode.
  43595. */
  43596. assert( sqlite3PcacheRefCount(pPager->pPCache)==0 );
  43597. assert( assert_pager_state(pPager) );
  43598. assert( pPager->eState==PAGER_OPEN || pPager->eState==PAGER_READER );
  43599. if( NEVER(MEMDB && pPager->errCode) ){ return pPager->errCode; }
  43600. if( !pagerUseWal(pPager) && pPager->eState==PAGER_OPEN ){
  43601. int bHotJournal = 1; /* True if there exists a hot journal-file */
  43602. assert( !MEMDB );
  43603. rc = pager_wait_on_lock(pPager, SHARED_LOCK);
  43604. if( rc!=SQLITE_OK ){
  43605. assert( pPager->eLock==NO_LOCK || pPager->eLock==UNKNOWN_LOCK );
  43606. goto failed;
  43607. }
  43608. /* If a journal file exists, and there is no RESERVED lock on the
  43609. ** database file, then it either needs to be played back or deleted.
  43610. */
  43611. if( pPager->eLock<=SHARED_LOCK ){
  43612. rc = hasHotJournal(pPager, &bHotJournal);
  43613. }
  43614. if( rc!=SQLITE_OK ){
  43615. goto failed;
  43616. }
  43617. if( bHotJournal ){
  43618. if( pPager->readOnly ){
  43619. rc = SQLITE_READONLY_ROLLBACK;
  43620. goto failed;
  43621. }
  43622. /* Get an EXCLUSIVE lock on the database file. At this point it is
  43623. ** important that a RESERVED lock is not obtained on the way to the
  43624. ** EXCLUSIVE lock. If it were, another process might open the
  43625. ** database file, detect the RESERVED lock, and conclude that the
  43626. ** database is safe to read while this process is still rolling the
  43627. ** hot-journal back.
  43628. **
  43629. ** Because the intermediate RESERVED lock is not requested, any
  43630. ** other process attempting to access the database file will get to
  43631. ** this point in the code and fail to obtain its own EXCLUSIVE lock
  43632. ** on the database file.
  43633. **
  43634. ** Unless the pager is in locking_mode=exclusive mode, the lock is
  43635. ** downgraded to SHARED_LOCK before this function returns.
  43636. */
  43637. rc = pagerLockDb(pPager, EXCLUSIVE_LOCK);
  43638. if( rc!=SQLITE_OK ){
  43639. goto failed;
  43640. }
  43641. /* If it is not already open and the file exists on disk, open the
  43642. ** journal for read/write access. Write access is required because
  43643. ** in exclusive-access mode the file descriptor will be kept open
  43644. ** and possibly used for a transaction later on. Also, write-access
  43645. ** is usually required to finalize the journal in journal_mode=persist
  43646. ** mode (and also for journal_mode=truncate on some systems).
  43647. **
  43648. ** If the journal does not exist, it usually means that some
  43649. ** other connection managed to get in and roll it back before
  43650. ** this connection obtained the exclusive lock above. Or, it
  43651. ** may mean that the pager was in the error-state when this
  43652. ** function was called and the journal file does not exist.
  43653. */
  43654. if( !isOpen(pPager->jfd) ){
  43655. sqlite3_vfs * const pVfs = pPager->pVfs;
  43656. int bExists; /* True if journal file exists */
  43657. rc = sqlite3OsAccess(
  43658. pVfs, pPager->zJournal, SQLITE_ACCESS_EXISTS, &bExists);
  43659. if( rc==SQLITE_OK && bExists ){
  43660. int fout = 0;
  43661. int f = SQLITE_OPEN_READWRITE|SQLITE_OPEN_MAIN_JOURNAL;
  43662. assert( !pPager->tempFile );
  43663. rc = sqlite3OsOpen(pVfs, pPager->zJournal, pPager->jfd, f, &fout);
  43664. assert( rc!=SQLITE_OK || isOpen(pPager->jfd) );
  43665. if( rc==SQLITE_OK && fout&SQLITE_OPEN_READONLY ){
  43666. rc = SQLITE_CANTOPEN_BKPT;
  43667. sqlite3OsClose(pPager->jfd);
  43668. }
  43669. }
  43670. }
  43671. /* Playback and delete the journal. Drop the database write
  43672. ** lock and reacquire the read lock. Purge the cache before
  43673. ** playing back the hot-journal so that we don't end up with
  43674. ** an inconsistent cache. Sync the hot journal before playing
  43675. ** it back since the process that crashed and left the hot journal
  43676. ** probably did not sync it and we are required to always sync
  43677. ** the journal before playing it back.
  43678. */
  43679. if( isOpen(pPager->jfd) ){
  43680. assert( rc==SQLITE_OK );
  43681. rc = pagerSyncHotJournal(pPager);
  43682. if( rc==SQLITE_OK ){
  43683. rc = pager_playback(pPager, 1);
  43684. pPager->eState = PAGER_OPEN;
  43685. }
  43686. }else if( !pPager->exclusiveMode ){
  43687. pagerUnlockDb(pPager, SHARED_LOCK);
  43688. }
  43689. if( rc!=SQLITE_OK ){
  43690. /* This branch is taken if an error occurs while trying to open
  43691. ** or roll back a hot-journal while holding an EXCLUSIVE lock. The
  43692. ** pager_unlock() routine will be called before returning to unlock
  43693. ** the file. If the unlock attempt fails, then Pager.eLock must be
  43694. ** set to UNKNOWN_LOCK (see the comment above the #define for
  43695. ** UNKNOWN_LOCK above for an explanation).
  43696. **
  43697. ** In order to get pager_unlock() to do this, set Pager.eState to
  43698. ** PAGER_ERROR now. This is not actually counted as a transition
  43699. ** to ERROR state in the state diagram at the top of this file,
  43700. ** since we know that the same call to pager_unlock() will very
  43701. ** shortly transition the pager object to the OPEN state. Calling
  43702. ** assert_pager_state() would fail now, as it should not be possible
  43703. ** to be in ERROR state when there are zero outstanding page
  43704. ** references.
  43705. */
  43706. pager_error(pPager, rc);
  43707. goto failed;
  43708. }
  43709. assert( pPager->eState==PAGER_OPEN );
  43710. assert( (pPager->eLock==SHARED_LOCK)
  43711. || (pPager->exclusiveMode && pPager->eLock>SHARED_LOCK)
  43712. );
  43713. }
  43714. if( !pPager->tempFile && pPager->hasBeenUsed ){
  43715. /* The shared-lock has just been acquired then check to
  43716. ** see if the database has been modified. If the database has changed,
  43717. ** flush the cache. The pPager->hasBeenUsed flag prevents this from
  43718. ** occurring on the very first access to a file, in order to save a
  43719. ** single unnecessary sqlite3OsRead() call at the start-up.
  43720. **
  43721. ** Database changes is detected by looking at 15 bytes beginning
  43722. ** at offset 24 into the file. The first 4 of these 16 bytes are
  43723. ** a 32-bit counter that is incremented with each change. The
  43724. ** other bytes change randomly with each file change when
  43725. ** a codec is in use.
  43726. **
  43727. ** There is a vanishingly small chance that a change will not be
  43728. ** detected. The chance of an undetected change is so small that
  43729. ** it can be neglected.
  43730. */
  43731. Pgno nPage = 0;
  43732. char dbFileVers[sizeof(pPager->dbFileVers)];
  43733. rc = pagerPagecount(pPager, &nPage);
  43734. if( rc ) goto failed;
  43735. if( nPage>0 ){
  43736. IOTRACE(("CKVERS %p %d\n", pPager, sizeof(dbFileVers)));
  43737. rc = sqlite3OsRead(pPager->fd, &dbFileVers, sizeof(dbFileVers), 24);
  43738. if( rc!=SQLITE_OK && rc!=SQLITE_IOERR_SHORT_READ ){
  43739. goto failed;
  43740. }
  43741. }else{
  43742. memset(dbFileVers, 0, sizeof(dbFileVers));
  43743. }
  43744. if( memcmp(pPager->dbFileVers, dbFileVers, sizeof(dbFileVers))!=0 ){
  43745. pager_reset(pPager);
  43746. /* Unmap the database file. It is possible that external processes
  43747. ** may have truncated the database file and then extended it back
  43748. ** to its original size while this process was not holding a lock.
  43749. ** In this case there may exist a Pager.pMap mapping that appears
  43750. ** to be the right size but is not actually valid. Avoid this
  43751. ** possibility by unmapping the db here. */
  43752. if( USEFETCH(pPager) ){
  43753. sqlite3OsUnfetch(pPager->fd, 0, 0);
  43754. }
  43755. }
  43756. }
  43757. /* If there is a WAL file in the file-system, open this database in WAL
  43758. ** mode. Otherwise, the following function call is a no-op.
  43759. */
  43760. rc = pagerOpenWalIfPresent(pPager);
  43761. #ifndef SQLITE_OMIT_WAL
  43762. assert( pPager->pWal==0 || rc==SQLITE_OK );
  43763. #endif
  43764. }
  43765. if( pagerUseWal(pPager) ){
  43766. assert( rc==SQLITE_OK );
  43767. rc = pagerBeginReadTransaction(pPager);
  43768. }
  43769. if( pPager->eState==PAGER_OPEN && rc==SQLITE_OK ){
  43770. rc = pagerPagecount(pPager, &pPager->dbSize);
  43771. }
  43772. failed:
  43773. if( rc!=SQLITE_OK ){
  43774. assert( !MEMDB );
  43775. pager_unlock(pPager);
  43776. assert( pPager->eState==PAGER_OPEN );
  43777. }else{
  43778. pPager->eState = PAGER_READER;
  43779. }
  43780. return rc;
  43781. }
  43782. /*
  43783. ** If the reference count has reached zero, rollback any active
  43784. ** transaction and unlock the pager.
  43785. **
  43786. ** Except, in locking_mode=EXCLUSIVE when there is nothing to in
  43787. ** the rollback journal, the unlock is not performed and there is
  43788. ** nothing to rollback, so this routine is a no-op.
  43789. */
  43790. static void pagerUnlockIfUnused(Pager *pPager){
  43791. if( pPager->nMmapOut==0 && (sqlite3PcacheRefCount(pPager->pPCache)==0) ){
  43792. pagerUnlockAndRollback(pPager);
  43793. }
  43794. }
  43795. /*
  43796. ** Acquire a reference to page number pgno in pager pPager (a page
  43797. ** reference has type DbPage*). If the requested reference is
  43798. ** successfully obtained, it is copied to *ppPage and SQLITE_OK returned.
  43799. **
  43800. ** If the requested page is already in the cache, it is returned.
  43801. ** Otherwise, a new page object is allocated and populated with data
  43802. ** read from the database file. In some cases, the pcache module may
  43803. ** choose not to allocate a new page object and may reuse an existing
  43804. ** object with no outstanding references.
  43805. **
  43806. ** The extra data appended to a page is always initialized to zeros the
  43807. ** first time a page is loaded into memory. If the page requested is
  43808. ** already in the cache when this function is called, then the extra
  43809. ** data is left as it was when the page object was last used.
  43810. **
  43811. ** If the database image is smaller than the requested page or if a
  43812. ** non-zero value is passed as the noContent parameter and the
  43813. ** requested page is not already stored in the cache, then no
  43814. ** actual disk read occurs. In this case the memory image of the
  43815. ** page is initialized to all zeros.
  43816. **
  43817. ** If noContent is true, it means that we do not care about the contents
  43818. ** of the page. This occurs in two scenarios:
  43819. **
  43820. ** a) When reading a free-list leaf page from the database, and
  43821. **
  43822. ** b) When a savepoint is being rolled back and we need to load
  43823. ** a new page into the cache to be filled with the data read
  43824. ** from the savepoint journal.
  43825. **
  43826. ** If noContent is true, then the data returned is zeroed instead of
  43827. ** being read from the database. Additionally, the bits corresponding
  43828. ** to pgno in Pager.pInJournal (bitvec of pages already written to the
  43829. ** journal file) and the PagerSavepoint.pInSavepoint bitvecs of any open
  43830. ** savepoints are set. This means if the page is made writable at any
  43831. ** point in the future, using a call to sqlite3PagerWrite(), its contents
  43832. ** will not be journaled. This saves IO.
  43833. **
  43834. ** The acquisition might fail for several reasons. In all cases,
  43835. ** an appropriate error code is returned and *ppPage is set to NULL.
  43836. **
  43837. ** See also sqlite3PagerLookup(). Both this routine and Lookup() attempt
  43838. ** to find a page in the in-memory cache first. If the page is not already
  43839. ** in memory, this routine goes to disk to read it in whereas Lookup()
  43840. ** just returns 0. This routine acquires a read-lock the first time it
  43841. ** has to go to disk, and could also playback an old journal if necessary.
  43842. ** Since Lookup() never goes to disk, it never has to deal with locks
  43843. ** or journal files.
  43844. */
  43845. SQLITE_PRIVATE int sqlite3PagerAcquire(
  43846. Pager *pPager, /* The pager open on the database file */
  43847. Pgno pgno, /* Page number to fetch */
  43848. DbPage **ppPage, /* Write a pointer to the page here */
  43849. int flags /* PAGER_GET_XXX flags */
  43850. ){
  43851. int rc = SQLITE_OK;
  43852. PgHdr *pPg = 0;
  43853. u32 iFrame = 0; /* Frame to read from WAL file */
  43854. const int noContent = (flags & PAGER_GET_NOCONTENT);
  43855. /* It is acceptable to use a read-only (mmap) page for any page except
  43856. ** page 1 if there is no write-transaction open or the ACQUIRE_READONLY
  43857. ** flag was specified by the caller. And so long as the db is not a
  43858. ** temporary or in-memory database. */
  43859. const int bMmapOk = (pgno!=1 && USEFETCH(pPager)
  43860. && (pPager->eState==PAGER_READER || (flags & PAGER_GET_READONLY))
  43861. #ifdef SQLITE_HAS_CODEC
  43862. && pPager->xCodec==0
  43863. #endif
  43864. );
  43865. assert( pPager->eState>=PAGER_READER );
  43866. assert( assert_pager_state(pPager) );
  43867. assert( noContent==0 || bMmapOk==0 );
  43868. if( pgno==0 ){
  43869. return SQLITE_CORRUPT_BKPT;
  43870. }
  43871. pPager->hasBeenUsed = 1;
  43872. /* If the pager is in the error state, return an error immediately.
  43873. ** Otherwise, request the page from the PCache layer. */
  43874. if( pPager->errCode!=SQLITE_OK ){
  43875. rc = pPager->errCode;
  43876. }else{
  43877. if( bMmapOk && pagerUseWal(pPager) ){
  43878. rc = sqlite3WalFindFrame(pPager->pWal, pgno, &iFrame);
  43879. if( rc!=SQLITE_OK ) goto pager_acquire_err;
  43880. }
  43881. if( bMmapOk && iFrame==0 ){
  43882. void *pData = 0;
  43883. rc = sqlite3OsFetch(pPager->fd,
  43884. (i64)(pgno-1) * pPager->pageSize, pPager->pageSize, &pData
  43885. );
  43886. if( rc==SQLITE_OK && pData ){
  43887. if( pPager->eState>PAGER_READER ){
  43888. pPg = sqlite3PagerLookup(pPager, pgno);
  43889. }
  43890. if( pPg==0 ){
  43891. rc = pagerAcquireMapPage(pPager, pgno, pData, &pPg);
  43892. }else{
  43893. sqlite3OsUnfetch(pPager->fd, (i64)(pgno-1)*pPager->pageSize, pData);
  43894. }
  43895. if( pPg ){
  43896. assert( rc==SQLITE_OK );
  43897. *ppPage = pPg;
  43898. return SQLITE_OK;
  43899. }
  43900. }
  43901. if( rc!=SQLITE_OK ){
  43902. goto pager_acquire_err;
  43903. }
  43904. }
  43905. {
  43906. sqlite3_pcache_page *pBase;
  43907. pBase = sqlite3PcacheFetch(pPager->pPCache, pgno, 3);
  43908. if( pBase==0 ){
  43909. rc = sqlite3PcacheFetchStress(pPager->pPCache, pgno, &pBase);
  43910. if( rc!=SQLITE_OK ) goto pager_acquire_err;
  43911. }
  43912. pPg = *ppPage = sqlite3PcacheFetchFinish(pPager->pPCache, pgno, pBase);
  43913. if( pPg==0 ) rc = SQLITE_NOMEM;
  43914. }
  43915. }
  43916. if( rc!=SQLITE_OK ){
  43917. /* Either the call to sqlite3PcacheFetch() returned an error or the
  43918. ** pager was already in the error-state when this function was called.
  43919. ** Set pPg to 0 and jump to the exception handler. */
  43920. pPg = 0;
  43921. goto pager_acquire_err;
  43922. }
  43923. assert( (*ppPage)->pgno==pgno );
  43924. assert( (*ppPage)->pPager==pPager || (*ppPage)->pPager==0 );
  43925. if( (*ppPage)->pPager && !noContent ){
  43926. /* In this case the pcache already contains an initialized copy of
  43927. ** the page. Return without further ado. */
  43928. assert( pgno<=PAGER_MAX_PGNO && pgno!=PAGER_MJ_PGNO(pPager) );
  43929. pPager->aStat[PAGER_STAT_HIT]++;
  43930. return SQLITE_OK;
  43931. }else{
  43932. /* The pager cache has created a new page. Its content needs to
  43933. ** be initialized. */
  43934. pPg = *ppPage;
  43935. pPg->pPager = pPager;
  43936. /* The maximum page number is 2^31. Return SQLITE_CORRUPT if a page
  43937. ** number greater than this, or the unused locking-page, is requested. */
  43938. if( pgno>PAGER_MAX_PGNO || pgno==PAGER_MJ_PGNO(pPager) ){
  43939. rc = SQLITE_CORRUPT_BKPT;
  43940. goto pager_acquire_err;
  43941. }
  43942. if( MEMDB || pPager->dbSize<pgno || noContent || !isOpen(pPager->fd) ){
  43943. if( pgno>pPager->mxPgno ){
  43944. rc = SQLITE_FULL;
  43945. goto pager_acquire_err;
  43946. }
  43947. if( noContent ){
  43948. /* Failure to set the bits in the InJournal bit-vectors is benign.
  43949. ** It merely means that we might do some extra work to journal a
  43950. ** page that does not need to be journaled. Nevertheless, be sure
  43951. ** to test the case where a malloc error occurs while trying to set
  43952. ** a bit in a bit vector.
  43953. */
  43954. sqlite3BeginBenignMalloc();
  43955. if( pgno<=pPager->dbOrigSize ){
  43956. TESTONLY( rc = ) sqlite3BitvecSet(pPager->pInJournal, pgno);
  43957. testcase( rc==SQLITE_NOMEM );
  43958. }
  43959. TESTONLY( rc = ) addToSavepointBitvecs(pPager, pgno);
  43960. testcase( rc==SQLITE_NOMEM );
  43961. sqlite3EndBenignMalloc();
  43962. }
  43963. memset(pPg->pData, 0, pPager->pageSize);
  43964. IOTRACE(("ZERO %p %d\n", pPager, pgno));
  43965. }else{
  43966. if( pagerUseWal(pPager) && bMmapOk==0 ){
  43967. rc = sqlite3WalFindFrame(pPager->pWal, pgno, &iFrame);
  43968. if( rc!=SQLITE_OK ) goto pager_acquire_err;
  43969. }
  43970. assert( pPg->pPager==pPager );
  43971. pPager->aStat[PAGER_STAT_MISS]++;
  43972. rc = readDbPage(pPg, iFrame);
  43973. if( rc!=SQLITE_OK ){
  43974. goto pager_acquire_err;
  43975. }
  43976. }
  43977. pager_set_pagehash(pPg);
  43978. }
  43979. return SQLITE_OK;
  43980. pager_acquire_err:
  43981. assert( rc!=SQLITE_OK );
  43982. if( pPg ){
  43983. sqlite3PcacheDrop(pPg);
  43984. }
  43985. pagerUnlockIfUnused(pPager);
  43986. *ppPage = 0;
  43987. return rc;
  43988. }
  43989. /*
  43990. ** Acquire a page if it is already in the in-memory cache. Do
  43991. ** not read the page from disk. Return a pointer to the page,
  43992. ** or 0 if the page is not in cache.
  43993. **
  43994. ** See also sqlite3PagerGet(). The difference between this routine
  43995. ** and sqlite3PagerGet() is that _get() will go to the disk and read
  43996. ** in the page if the page is not already in cache. This routine
  43997. ** returns NULL if the page is not in cache or if a disk I/O error
  43998. ** has ever happened.
  43999. */
  44000. SQLITE_PRIVATE DbPage *sqlite3PagerLookup(Pager *pPager, Pgno pgno){
  44001. sqlite3_pcache_page *pPage;
  44002. assert( pPager!=0 );
  44003. assert( pgno!=0 );
  44004. assert( pPager->pPCache!=0 );
  44005. pPage = sqlite3PcacheFetch(pPager->pPCache, pgno, 0);
  44006. assert( pPage==0 || pPager->hasBeenUsed );
  44007. return sqlite3PcacheFetchFinish(pPager->pPCache, pgno, pPage);
  44008. }
  44009. /*
  44010. ** Release a page reference.
  44011. **
  44012. ** If the number of references to the page drop to zero, then the
  44013. ** page is added to the LRU list. When all references to all pages
  44014. ** are released, a rollback occurs and the lock on the database is
  44015. ** removed.
  44016. */
  44017. SQLITE_PRIVATE void sqlite3PagerUnrefNotNull(DbPage *pPg){
  44018. Pager *pPager;
  44019. assert( pPg!=0 );
  44020. pPager = pPg->pPager;
  44021. if( pPg->flags & PGHDR_MMAP ){
  44022. pagerReleaseMapPage(pPg);
  44023. }else{
  44024. sqlite3PcacheRelease(pPg);
  44025. }
  44026. pagerUnlockIfUnused(pPager);
  44027. }
  44028. SQLITE_PRIVATE void sqlite3PagerUnref(DbPage *pPg){
  44029. if( pPg ) sqlite3PagerUnrefNotNull(pPg);
  44030. }
  44031. /*
  44032. ** This function is called at the start of every write transaction.
  44033. ** There must already be a RESERVED or EXCLUSIVE lock on the database
  44034. ** file when this routine is called.
  44035. **
  44036. ** Open the journal file for pager pPager and write a journal header
  44037. ** to the start of it. If there are active savepoints, open the sub-journal
  44038. ** as well. This function is only used when the journal file is being
  44039. ** opened to write a rollback log for a transaction. It is not used
  44040. ** when opening a hot journal file to roll it back.
  44041. **
  44042. ** If the journal file is already open (as it may be in exclusive mode),
  44043. ** then this function just writes a journal header to the start of the
  44044. ** already open file.
  44045. **
  44046. ** Whether or not the journal file is opened by this function, the
  44047. ** Pager.pInJournal bitvec structure is allocated.
  44048. **
  44049. ** Return SQLITE_OK if everything is successful. Otherwise, return
  44050. ** SQLITE_NOMEM if the attempt to allocate Pager.pInJournal fails, or
  44051. ** an IO error code if opening or writing the journal file fails.
  44052. */
  44053. static int pager_open_journal(Pager *pPager){
  44054. int rc = SQLITE_OK; /* Return code */
  44055. sqlite3_vfs * const pVfs = pPager->pVfs; /* Local cache of vfs pointer */
  44056. assert( pPager->eState==PAGER_WRITER_LOCKED );
  44057. assert( assert_pager_state(pPager) );
  44058. assert( pPager->pInJournal==0 );
  44059. /* If already in the error state, this function is a no-op. But on
  44060. ** the other hand, this routine is never called if we are already in
  44061. ** an error state. */
  44062. if( NEVER(pPager->errCode) ) return pPager->errCode;
  44063. if( !pagerUseWal(pPager) && pPager->journalMode!=PAGER_JOURNALMODE_OFF ){
  44064. pPager->pInJournal = sqlite3BitvecCreate(pPager->dbSize);
  44065. if( pPager->pInJournal==0 ){
  44066. return SQLITE_NOMEM;
  44067. }
  44068. /* Open the journal file if it is not already open. */
  44069. if( !isOpen(pPager->jfd) ){
  44070. if( pPager->journalMode==PAGER_JOURNALMODE_MEMORY ){
  44071. sqlite3MemJournalOpen(pPager->jfd);
  44072. }else{
  44073. const int flags = /* VFS flags to open journal file */
  44074. SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|
  44075. (pPager->tempFile ?
  44076. (SQLITE_OPEN_DELETEONCLOSE|SQLITE_OPEN_TEMP_JOURNAL):
  44077. (SQLITE_OPEN_MAIN_JOURNAL)
  44078. );
  44079. /* Verify that the database still has the same name as it did when
  44080. ** it was originally opened. */
  44081. rc = databaseIsUnmoved(pPager);
  44082. if( rc==SQLITE_OK ){
  44083. #ifdef SQLITE_ENABLE_ATOMIC_WRITE
  44084. rc = sqlite3JournalOpen(
  44085. pVfs, pPager->zJournal, pPager->jfd, flags, jrnlBufferSize(pPager)
  44086. );
  44087. #else
  44088. rc = sqlite3OsOpen(pVfs, pPager->zJournal, pPager->jfd, flags, 0);
  44089. #endif
  44090. }
  44091. }
  44092. assert( rc!=SQLITE_OK || isOpen(pPager->jfd) );
  44093. }
  44094. /* Write the first journal header to the journal file and open
  44095. ** the sub-journal if necessary.
  44096. */
  44097. if( rc==SQLITE_OK ){
  44098. /* TODO: Check if all of these are really required. */
  44099. pPager->nRec = 0;
  44100. pPager->journalOff = 0;
  44101. pPager->setMaster = 0;
  44102. pPager->journalHdr = 0;
  44103. rc = writeJournalHdr(pPager);
  44104. }
  44105. }
  44106. if( rc!=SQLITE_OK ){
  44107. sqlite3BitvecDestroy(pPager->pInJournal);
  44108. pPager->pInJournal = 0;
  44109. }else{
  44110. assert( pPager->eState==PAGER_WRITER_LOCKED );
  44111. pPager->eState = PAGER_WRITER_CACHEMOD;
  44112. }
  44113. return rc;
  44114. }
  44115. /*
  44116. ** Begin a write-transaction on the specified pager object. If a
  44117. ** write-transaction has already been opened, this function is a no-op.
  44118. **
  44119. ** If the exFlag argument is false, then acquire at least a RESERVED
  44120. ** lock on the database file. If exFlag is true, then acquire at least
  44121. ** an EXCLUSIVE lock. If such a lock is already held, no locking
  44122. ** functions need be called.
  44123. **
  44124. ** If the subjInMemory argument is non-zero, then any sub-journal opened
  44125. ** within this transaction will be opened as an in-memory file. This
  44126. ** has no effect if the sub-journal is already opened (as it may be when
  44127. ** running in exclusive mode) or if the transaction does not require a
  44128. ** sub-journal. If the subjInMemory argument is zero, then any required
  44129. ** sub-journal is implemented in-memory if pPager is an in-memory database,
  44130. ** or using a temporary file otherwise.
  44131. */
  44132. SQLITE_PRIVATE int sqlite3PagerBegin(Pager *pPager, int exFlag, int subjInMemory){
  44133. int rc = SQLITE_OK;
  44134. if( pPager->errCode ) return pPager->errCode;
  44135. assert( pPager->eState>=PAGER_READER && pPager->eState<PAGER_ERROR );
  44136. pPager->subjInMemory = (u8)subjInMemory;
  44137. if( ALWAYS(pPager->eState==PAGER_READER) ){
  44138. assert( pPager->pInJournal==0 );
  44139. if( pagerUseWal(pPager) ){
  44140. /* If the pager is configured to use locking_mode=exclusive, and an
  44141. ** exclusive lock on the database is not already held, obtain it now.
  44142. */
  44143. if( pPager->exclusiveMode && sqlite3WalExclusiveMode(pPager->pWal, -1) ){
  44144. rc = pagerLockDb(pPager, EXCLUSIVE_LOCK);
  44145. if( rc!=SQLITE_OK ){
  44146. return rc;
  44147. }
  44148. sqlite3WalExclusiveMode(pPager->pWal, 1);
  44149. }
  44150. /* Grab the write lock on the log file. If successful, upgrade to
  44151. ** PAGER_RESERVED state. Otherwise, return an error code to the caller.
  44152. ** The busy-handler is not invoked if another connection already
  44153. ** holds the write-lock. If possible, the upper layer will call it.
  44154. */
  44155. rc = sqlite3WalBeginWriteTransaction(pPager->pWal);
  44156. }else{
  44157. /* Obtain a RESERVED lock on the database file. If the exFlag parameter
  44158. ** is true, then immediately upgrade this to an EXCLUSIVE lock. The
  44159. ** busy-handler callback can be used when upgrading to the EXCLUSIVE
  44160. ** lock, but not when obtaining the RESERVED lock.
  44161. */
  44162. rc = pagerLockDb(pPager, RESERVED_LOCK);
  44163. if( rc==SQLITE_OK && exFlag ){
  44164. rc = pager_wait_on_lock(pPager, EXCLUSIVE_LOCK);
  44165. }
  44166. }
  44167. if( rc==SQLITE_OK ){
  44168. /* Change to WRITER_LOCKED state.
  44169. **
  44170. ** WAL mode sets Pager.eState to PAGER_WRITER_LOCKED or CACHEMOD
  44171. ** when it has an open transaction, but never to DBMOD or FINISHED.
  44172. ** This is because in those states the code to roll back savepoint
  44173. ** transactions may copy data from the sub-journal into the database
  44174. ** file as well as into the page cache. Which would be incorrect in
  44175. ** WAL mode.
  44176. */
  44177. pPager->eState = PAGER_WRITER_LOCKED;
  44178. pPager->dbHintSize = pPager->dbSize;
  44179. pPager->dbFileSize = pPager->dbSize;
  44180. pPager->dbOrigSize = pPager->dbSize;
  44181. pPager->journalOff = 0;
  44182. }
  44183. assert( rc==SQLITE_OK || pPager->eState==PAGER_READER );
  44184. assert( rc!=SQLITE_OK || pPager->eState==PAGER_WRITER_LOCKED );
  44185. assert( assert_pager_state(pPager) );
  44186. }
  44187. PAGERTRACE(("TRANSACTION %d\n", PAGERID(pPager)));
  44188. return rc;
  44189. }
  44190. /*
  44191. ** Mark a single data page as writeable. The page is written into the
  44192. ** main journal or sub-journal as required. If the page is written into
  44193. ** one of the journals, the corresponding bit is set in the
  44194. ** Pager.pInJournal bitvec and the PagerSavepoint.pInSavepoint bitvecs
  44195. ** of any open savepoints as appropriate.
  44196. */
  44197. static int pager_write(PgHdr *pPg){
  44198. Pager *pPager = pPg->pPager;
  44199. int rc = SQLITE_OK;
  44200. int inJournal;
  44201. /* This routine is not called unless a write-transaction has already
  44202. ** been started. The journal file may or may not be open at this point.
  44203. ** It is never called in the ERROR state.
  44204. */
  44205. assert( pPager->eState==PAGER_WRITER_LOCKED
  44206. || pPager->eState==PAGER_WRITER_CACHEMOD
  44207. || pPager->eState==PAGER_WRITER_DBMOD
  44208. );
  44209. assert( assert_pager_state(pPager) );
  44210. assert( pPager->errCode==0 );
  44211. assert( pPager->readOnly==0 );
  44212. CHECK_PAGE(pPg);
  44213. /* The journal file needs to be opened. Higher level routines have already
  44214. ** obtained the necessary locks to begin the write-transaction, but the
  44215. ** rollback journal might not yet be open. Open it now if this is the case.
  44216. **
  44217. ** This is done before calling sqlite3PcacheMakeDirty() on the page.
  44218. ** Otherwise, if it were done after calling sqlite3PcacheMakeDirty(), then
  44219. ** an error might occur and the pager would end up in WRITER_LOCKED state
  44220. ** with pages marked as dirty in the cache.
  44221. */
  44222. if( pPager->eState==PAGER_WRITER_LOCKED ){
  44223. rc = pager_open_journal(pPager);
  44224. if( rc!=SQLITE_OK ) return rc;
  44225. }
  44226. assert( pPager->eState>=PAGER_WRITER_CACHEMOD );
  44227. assert( assert_pager_state(pPager) );
  44228. /* Mark the page as dirty. If the page has already been written
  44229. ** to the journal then we can return right away.
  44230. */
  44231. sqlite3PcacheMakeDirty(pPg);
  44232. inJournal = pageInJournal(pPager, pPg);
  44233. if( inJournal && (pPager->nSavepoint==0 || !subjRequiresPage(pPg)) ){
  44234. assert( !pagerUseWal(pPager) );
  44235. }else{
  44236. /* The transaction journal now exists and we have a RESERVED or an
  44237. ** EXCLUSIVE lock on the main database file. Write the current page to
  44238. ** the transaction journal if it is not there already.
  44239. */
  44240. if( !inJournal && !pagerUseWal(pPager) ){
  44241. assert( pagerUseWal(pPager)==0 );
  44242. if( pPg->pgno<=pPager->dbOrigSize && isOpen(pPager->jfd) ){
  44243. u32 cksum;
  44244. char *pData2;
  44245. i64 iOff = pPager->journalOff;
  44246. /* We should never write to the journal file the page that
  44247. ** contains the database locks. The following assert verifies
  44248. ** that we do not. */
  44249. assert( pPg->pgno!=PAGER_MJ_PGNO(pPager) );
  44250. assert( pPager->journalHdr<=pPager->journalOff );
  44251. CODEC2(pPager, pPg->pData, pPg->pgno, 7, return SQLITE_NOMEM, pData2);
  44252. cksum = pager_cksum(pPager, (u8*)pData2);
  44253. /* Even if an IO or diskfull error occurs while journalling the
  44254. ** page in the block above, set the need-sync flag for the page.
  44255. ** Otherwise, when the transaction is rolled back, the logic in
  44256. ** playback_one_page() will think that the page needs to be restored
  44257. ** in the database file. And if an IO error occurs while doing so,
  44258. ** then corruption may follow.
  44259. */
  44260. pPg->flags |= PGHDR_NEED_SYNC;
  44261. rc = write32bits(pPager->jfd, iOff, pPg->pgno);
  44262. if( rc!=SQLITE_OK ) return rc;
  44263. rc = sqlite3OsWrite(pPager->jfd, pData2, pPager->pageSize, iOff+4);
  44264. if( rc!=SQLITE_OK ) return rc;
  44265. rc = write32bits(pPager->jfd, iOff+pPager->pageSize+4, cksum);
  44266. if( rc!=SQLITE_OK ) return rc;
  44267. IOTRACE(("JOUT %p %d %lld %d\n", pPager, pPg->pgno,
  44268. pPager->journalOff, pPager->pageSize));
  44269. PAGER_INCR(sqlite3_pager_writej_count);
  44270. PAGERTRACE(("JOURNAL %d page %d needSync=%d hash(%08x)\n",
  44271. PAGERID(pPager), pPg->pgno,
  44272. ((pPg->flags&PGHDR_NEED_SYNC)?1:0), pager_pagehash(pPg)));
  44273. pPager->journalOff += 8 + pPager->pageSize;
  44274. pPager->nRec++;
  44275. assert( pPager->pInJournal!=0 );
  44276. rc = sqlite3BitvecSet(pPager->pInJournal, pPg->pgno);
  44277. testcase( rc==SQLITE_NOMEM );
  44278. assert( rc==SQLITE_OK || rc==SQLITE_NOMEM );
  44279. rc |= addToSavepointBitvecs(pPager, pPg->pgno);
  44280. if( rc!=SQLITE_OK ){
  44281. assert( rc==SQLITE_NOMEM );
  44282. return rc;
  44283. }
  44284. }else{
  44285. if( pPager->eState!=PAGER_WRITER_DBMOD ){
  44286. pPg->flags |= PGHDR_NEED_SYNC;
  44287. }
  44288. PAGERTRACE(("APPEND %d page %d needSync=%d\n",
  44289. PAGERID(pPager), pPg->pgno,
  44290. ((pPg->flags&PGHDR_NEED_SYNC)?1:0)));
  44291. }
  44292. }
  44293. /* If the statement journal is open and the page is not in it,
  44294. ** then write the current page to the statement journal. Note that
  44295. ** the statement journal format differs from the standard journal format
  44296. ** in that it omits the checksums and the header.
  44297. */
  44298. if( pPager->nSavepoint>0 && subjRequiresPage(pPg) ){
  44299. rc = subjournalPage(pPg);
  44300. }
  44301. }
  44302. /* Update the database size and return.
  44303. */
  44304. if( pPager->dbSize<pPg->pgno ){
  44305. pPager->dbSize = pPg->pgno;
  44306. }
  44307. return rc;
  44308. }
  44309. /*
  44310. ** This is a variant of sqlite3PagerWrite() that runs when the sector size
  44311. ** is larger than the page size. SQLite makes the (reasonable) assumption that
  44312. ** all bytes of a sector are written together by hardware. Hence, all bytes of
  44313. ** a sector need to be journalled in case of a power loss in the middle of
  44314. ** a write.
  44315. **
  44316. ** Usually, the sector size is less than or equal to the page size, in which
  44317. ** case pages can be individually written. This routine only runs in the exceptional
  44318. ** case where the page size is smaller than the sector size.
  44319. */
  44320. static SQLITE_NOINLINE int pagerWriteLargeSector(PgHdr *pPg){
  44321. int rc = SQLITE_OK; /* Return code */
  44322. Pgno nPageCount; /* Total number of pages in database file */
  44323. Pgno pg1; /* First page of the sector pPg is located on. */
  44324. int nPage = 0; /* Number of pages starting at pg1 to journal */
  44325. int ii; /* Loop counter */
  44326. int needSync = 0; /* True if any page has PGHDR_NEED_SYNC */
  44327. Pager *pPager = pPg->pPager; /* The pager that owns pPg */
  44328. Pgno nPagePerSector = (pPager->sectorSize/pPager->pageSize);
  44329. /* Set the doNotSpill NOSYNC bit to 1. This is because we cannot allow
  44330. ** a journal header to be written between the pages journaled by
  44331. ** this function.
  44332. */
  44333. assert( !MEMDB );
  44334. assert( (pPager->doNotSpill & SPILLFLAG_NOSYNC)==0 );
  44335. pPager->doNotSpill |= SPILLFLAG_NOSYNC;
  44336. /* This trick assumes that both the page-size and sector-size are
  44337. ** an integer power of 2. It sets variable pg1 to the identifier
  44338. ** of the first page of the sector pPg is located on.
  44339. */
  44340. pg1 = ((pPg->pgno-1) & ~(nPagePerSector-1)) + 1;
  44341. nPageCount = pPager->dbSize;
  44342. if( pPg->pgno>nPageCount ){
  44343. nPage = (pPg->pgno - pg1)+1;
  44344. }else if( (pg1+nPagePerSector-1)>nPageCount ){
  44345. nPage = nPageCount+1-pg1;
  44346. }else{
  44347. nPage = nPagePerSector;
  44348. }
  44349. assert(nPage>0);
  44350. assert(pg1<=pPg->pgno);
  44351. assert((pg1+nPage)>pPg->pgno);
  44352. for(ii=0; ii<nPage && rc==SQLITE_OK; ii++){
  44353. Pgno pg = pg1+ii;
  44354. PgHdr *pPage;
  44355. if( pg==pPg->pgno || !sqlite3BitvecTest(pPager->pInJournal, pg) ){
  44356. if( pg!=PAGER_MJ_PGNO(pPager) ){
  44357. rc = sqlite3PagerGet(pPager, pg, &pPage);
  44358. if( rc==SQLITE_OK ){
  44359. rc = pager_write(pPage);
  44360. if( pPage->flags&PGHDR_NEED_SYNC ){
  44361. needSync = 1;
  44362. }
  44363. sqlite3PagerUnrefNotNull(pPage);
  44364. }
  44365. }
  44366. }else if( (pPage = sqlite3PagerLookup(pPager, pg))!=0 ){
  44367. if( pPage->flags&PGHDR_NEED_SYNC ){
  44368. needSync = 1;
  44369. }
  44370. sqlite3PagerUnrefNotNull(pPage);
  44371. }
  44372. }
  44373. /* If the PGHDR_NEED_SYNC flag is set for any of the nPage pages
  44374. ** starting at pg1, then it needs to be set for all of them. Because
  44375. ** writing to any of these nPage pages may damage the others, the
  44376. ** journal file must contain sync()ed copies of all of them
  44377. ** before any of them can be written out to the database file.
  44378. */
  44379. if( rc==SQLITE_OK && needSync ){
  44380. assert( !MEMDB );
  44381. for(ii=0; ii<nPage; ii++){
  44382. PgHdr *pPage = sqlite3PagerLookup(pPager, pg1+ii);
  44383. if( pPage ){
  44384. pPage->flags |= PGHDR_NEED_SYNC;
  44385. sqlite3PagerUnrefNotNull(pPage);
  44386. }
  44387. }
  44388. }
  44389. assert( (pPager->doNotSpill & SPILLFLAG_NOSYNC)!=0 );
  44390. pPager->doNotSpill &= ~SPILLFLAG_NOSYNC;
  44391. return rc;
  44392. }
  44393. /*
  44394. ** Mark a data page as writeable. This routine must be called before
  44395. ** making changes to a page. The caller must check the return value
  44396. ** of this function and be careful not to change any page data unless
  44397. ** this routine returns SQLITE_OK.
  44398. **
  44399. ** The difference between this function and pager_write() is that this
  44400. ** function also deals with the special case where 2 or more pages
  44401. ** fit on a single disk sector. In this case all co-resident pages
  44402. ** must have been written to the journal file before returning.
  44403. **
  44404. ** If an error occurs, SQLITE_NOMEM or an IO error code is returned
  44405. ** as appropriate. Otherwise, SQLITE_OK.
  44406. */
  44407. SQLITE_PRIVATE int sqlite3PagerWrite(PgHdr *pPg){
  44408. assert( (pPg->flags & PGHDR_MMAP)==0 );
  44409. assert( pPg->pPager->eState>=PAGER_WRITER_LOCKED );
  44410. assert( pPg->pPager->eState!=PAGER_ERROR );
  44411. assert( assert_pager_state(pPg->pPager) );
  44412. if( pPg->pPager->sectorSize > (u32)pPg->pPager->pageSize ){
  44413. return pagerWriteLargeSector(pPg);
  44414. }else{
  44415. return pager_write(pPg);
  44416. }
  44417. }
  44418. /*
  44419. ** Return TRUE if the page given in the argument was previously passed
  44420. ** to sqlite3PagerWrite(). In other words, return TRUE if it is ok
  44421. ** to change the content of the page.
  44422. */
  44423. #ifndef NDEBUG
  44424. SQLITE_PRIVATE int sqlite3PagerIswriteable(DbPage *pPg){
  44425. return pPg->flags&PGHDR_DIRTY;
  44426. }
  44427. #endif
  44428. /*
  44429. ** A call to this routine tells the pager that it is not necessary to
  44430. ** write the information on page pPg back to the disk, even though
  44431. ** that page might be marked as dirty. This happens, for example, when
  44432. ** the page has been added as a leaf of the freelist and so its
  44433. ** content no longer matters.
  44434. **
  44435. ** The overlying software layer calls this routine when all of the data
  44436. ** on the given page is unused. The pager marks the page as clean so
  44437. ** that it does not get written to disk.
  44438. **
  44439. ** Tests show that this optimization can quadruple the speed of large
  44440. ** DELETE operations.
  44441. */
  44442. SQLITE_PRIVATE void sqlite3PagerDontWrite(PgHdr *pPg){
  44443. Pager *pPager = pPg->pPager;
  44444. if( (pPg->flags&PGHDR_DIRTY) && pPager->nSavepoint==0 ){
  44445. PAGERTRACE(("DONT_WRITE page %d of %d\n", pPg->pgno, PAGERID(pPager)));
  44446. IOTRACE(("CLEAN %p %d\n", pPager, pPg->pgno))
  44447. pPg->flags |= PGHDR_DONT_WRITE;
  44448. pager_set_pagehash(pPg);
  44449. }
  44450. }
  44451. /*
  44452. ** This routine is called to increment the value of the database file
  44453. ** change-counter, stored as a 4-byte big-endian integer starting at
  44454. ** byte offset 24 of the pager file. The secondary change counter at
  44455. ** 92 is also updated, as is the SQLite version number at offset 96.
  44456. **
  44457. ** But this only happens if the pPager->changeCountDone flag is false.
  44458. ** To avoid excess churning of page 1, the update only happens once.
  44459. ** See also the pager_write_changecounter() routine that does an
  44460. ** unconditional update of the change counters.
  44461. **
  44462. ** If the isDirectMode flag is zero, then this is done by calling
  44463. ** sqlite3PagerWrite() on page 1, then modifying the contents of the
  44464. ** page data. In this case the file will be updated when the current
  44465. ** transaction is committed.
  44466. **
  44467. ** The isDirectMode flag may only be non-zero if the library was compiled
  44468. ** with the SQLITE_ENABLE_ATOMIC_WRITE macro defined. In this case,
  44469. ** if isDirect is non-zero, then the database file is updated directly
  44470. ** by writing an updated version of page 1 using a call to the
  44471. ** sqlite3OsWrite() function.
  44472. */
  44473. static int pager_incr_changecounter(Pager *pPager, int isDirectMode){
  44474. int rc = SQLITE_OK;
  44475. assert( pPager->eState==PAGER_WRITER_CACHEMOD
  44476. || pPager->eState==PAGER_WRITER_DBMOD
  44477. );
  44478. assert( assert_pager_state(pPager) );
  44479. /* Declare and initialize constant integer 'isDirect'. If the
  44480. ** atomic-write optimization is enabled in this build, then isDirect
  44481. ** is initialized to the value passed as the isDirectMode parameter
  44482. ** to this function. Otherwise, it is always set to zero.
  44483. **
  44484. ** The idea is that if the atomic-write optimization is not
  44485. ** enabled at compile time, the compiler can omit the tests of
  44486. ** 'isDirect' below, as well as the block enclosed in the
  44487. ** "if( isDirect )" condition.
  44488. */
  44489. #ifndef SQLITE_ENABLE_ATOMIC_WRITE
  44490. # define DIRECT_MODE 0
  44491. assert( isDirectMode==0 );
  44492. UNUSED_PARAMETER(isDirectMode);
  44493. #else
  44494. # define DIRECT_MODE isDirectMode
  44495. #endif
  44496. if( !pPager->changeCountDone && ALWAYS(pPager->dbSize>0) ){
  44497. PgHdr *pPgHdr; /* Reference to page 1 */
  44498. assert( !pPager->tempFile && isOpen(pPager->fd) );
  44499. /* Open page 1 of the file for writing. */
  44500. rc = sqlite3PagerGet(pPager, 1, &pPgHdr);
  44501. assert( pPgHdr==0 || rc==SQLITE_OK );
  44502. /* If page one was fetched successfully, and this function is not
  44503. ** operating in direct-mode, make page 1 writable. When not in
  44504. ** direct mode, page 1 is always held in cache and hence the PagerGet()
  44505. ** above is always successful - hence the ALWAYS on rc==SQLITE_OK.
  44506. */
  44507. if( !DIRECT_MODE && ALWAYS(rc==SQLITE_OK) ){
  44508. rc = sqlite3PagerWrite(pPgHdr);
  44509. }
  44510. if( rc==SQLITE_OK ){
  44511. /* Actually do the update of the change counter */
  44512. pager_write_changecounter(pPgHdr);
  44513. /* If running in direct mode, write the contents of page 1 to the file. */
  44514. if( DIRECT_MODE ){
  44515. const void *zBuf;
  44516. assert( pPager->dbFileSize>0 );
  44517. CODEC2(pPager, pPgHdr->pData, 1, 6, rc=SQLITE_NOMEM, zBuf);
  44518. if( rc==SQLITE_OK ){
  44519. rc = sqlite3OsWrite(pPager->fd, zBuf, pPager->pageSize, 0);
  44520. pPager->aStat[PAGER_STAT_WRITE]++;
  44521. }
  44522. if( rc==SQLITE_OK ){
  44523. /* Update the pager's copy of the change-counter. Otherwise, the
  44524. ** next time a read transaction is opened the cache will be
  44525. ** flushed (as the change-counter values will not match). */
  44526. const void *pCopy = (const void *)&((const char *)zBuf)[24];
  44527. memcpy(&pPager->dbFileVers, pCopy, sizeof(pPager->dbFileVers));
  44528. pPager->changeCountDone = 1;
  44529. }
  44530. }else{
  44531. pPager->changeCountDone = 1;
  44532. }
  44533. }
  44534. /* Release the page reference. */
  44535. sqlite3PagerUnref(pPgHdr);
  44536. }
  44537. return rc;
  44538. }
  44539. /*
  44540. ** Sync the database file to disk. This is a no-op for in-memory databases
  44541. ** or pages with the Pager.noSync flag set.
  44542. **
  44543. ** If successful, or if called on a pager for which it is a no-op, this
  44544. ** function returns SQLITE_OK. Otherwise, an IO error code is returned.
  44545. */
  44546. SQLITE_PRIVATE int sqlite3PagerSync(Pager *pPager, const char *zMaster){
  44547. int rc = SQLITE_OK;
  44548. if( isOpen(pPager->fd) ){
  44549. void *pArg = (void*)zMaster;
  44550. rc = sqlite3OsFileControl(pPager->fd, SQLITE_FCNTL_SYNC, pArg);
  44551. if( rc==SQLITE_NOTFOUND ) rc = SQLITE_OK;
  44552. }
  44553. if( rc==SQLITE_OK && !pPager->noSync ){
  44554. assert( !MEMDB );
  44555. rc = sqlite3OsSync(pPager->fd, pPager->syncFlags);
  44556. }
  44557. return rc;
  44558. }
  44559. /*
  44560. ** This function may only be called while a write-transaction is active in
  44561. ** rollback. If the connection is in WAL mode, this call is a no-op.
  44562. ** Otherwise, if the connection does not already have an EXCLUSIVE lock on
  44563. ** the database file, an attempt is made to obtain one.
  44564. **
  44565. ** If the EXCLUSIVE lock is already held or the attempt to obtain it is
  44566. ** successful, or the connection is in WAL mode, SQLITE_OK is returned.
  44567. ** Otherwise, either SQLITE_BUSY or an SQLITE_IOERR_XXX error code is
  44568. ** returned.
  44569. */
  44570. SQLITE_PRIVATE int sqlite3PagerExclusiveLock(Pager *pPager){
  44571. int rc = SQLITE_OK;
  44572. assert( pPager->eState==PAGER_WRITER_CACHEMOD
  44573. || pPager->eState==PAGER_WRITER_DBMOD
  44574. || pPager->eState==PAGER_WRITER_LOCKED
  44575. );
  44576. assert( assert_pager_state(pPager) );
  44577. if( 0==pagerUseWal(pPager) ){
  44578. rc = pager_wait_on_lock(pPager, EXCLUSIVE_LOCK);
  44579. }
  44580. return rc;
  44581. }
  44582. /*
  44583. ** Sync the database file for the pager pPager. zMaster points to the name
  44584. ** of a master journal file that should be written into the individual
  44585. ** journal file. zMaster may be NULL, which is interpreted as no master
  44586. ** journal (a single database transaction).
  44587. **
  44588. ** This routine ensures that:
  44589. **
  44590. ** * The database file change-counter is updated,
  44591. ** * the journal is synced (unless the atomic-write optimization is used),
  44592. ** * all dirty pages are written to the database file,
  44593. ** * the database file is truncated (if required), and
  44594. ** * the database file synced.
  44595. **
  44596. ** The only thing that remains to commit the transaction is to finalize
  44597. ** (delete, truncate or zero the first part of) the journal file (or
  44598. ** delete the master journal file if specified).
  44599. **
  44600. ** Note that if zMaster==NULL, this does not overwrite a previous value
  44601. ** passed to an sqlite3PagerCommitPhaseOne() call.
  44602. **
  44603. ** If the final parameter - noSync - is true, then the database file itself
  44604. ** is not synced. The caller must call sqlite3PagerSync() directly to
  44605. ** sync the database file before calling CommitPhaseTwo() to delete the
  44606. ** journal file in this case.
  44607. */
  44608. SQLITE_PRIVATE int sqlite3PagerCommitPhaseOne(
  44609. Pager *pPager, /* Pager object */
  44610. const char *zMaster, /* If not NULL, the master journal name */
  44611. int noSync /* True to omit the xSync on the db file */
  44612. ){
  44613. int rc = SQLITE_OK; /* Return code */
  44614. assert( pPager->eState==PAGER_WRITER_LOCKED
  44615. || pPager->eState==PAGER_WRITER_CACHEMOD
  44616. || pPager->eState==PAGER_WRITER_DBMOD
  44617. || pPager->eState==PAGER_ERROR
  44618. );
  44619. assert( assert_pager_state(pPager) );
  44620. /* If a prior error occurred, report that error again. */
  44621. if( NEVER(pPager->errCode) ) return pPager->errCode;
  44622. PAGERTRACE(("DATABASE SYNC: File=%s zMaster=%s nSize=%d\n",
  44623. pPager->zFilename, zMaster, pPager->dbSize));
  44624. /* If no database changes have been made, return early. */
  44625. if( pPager->eState<PAGER_WRITER_CACHEMOD ) return SQLITE_OK;
  44626. if( MEMDB ){
  44627. /* If this is an in-memory db, or no pages have been written to, or this
  44628. ** function has already been called, it is mostly a no-op. However, any
  44629. ** backup in progress needs to be restarted.
  44630. */
  44631. sqlite3BackupRestart(pPager->pBackup);
  44632. }else{
  44633. if( pagerUseWal(pPager) ){
  44634. PgHdr *pList = sqlite3PcacheDirtyList(pPager->pPCache);
  44635. PgHdr *pPageOne = 0;
  44636. if( pList==0 ){
  44637. /* Must have at least one page for the WAL commit flag.
  44638. ** Ticket [2d1a5c67dfc2363e44f29d9bbd57f] 2011-05-18 */
  44639. rc = sqlite3PagerGet(pPager, 1, &pPageOne);
  44640. pList = pPageOne;
  44641. pList->pDirty = 0;
  44642. }
  44643. assert( rc==SQLITE_OK );
  44644. if( ALWAYS(pList) ){
  44645. rc = pagerWalFrames(pPager, pList, pPager->dbSize, 1);
  44646. }
  44647. sqlite3PagerUnref(pPageOne);
  44648. if( rc==SQLITE_OK ){
  44649. sqlite3PcacheCleanAll(pPager->pPCache);
  44650. }
  44651. }else{
  44652. /* The following block updates the change-counter. Exactly how it
  44653. ** does this depends on whether or not the atomic-update optimization
  44654. ** was enabled at compile time, and if this transaction meets the
  44655. ** runtime criteria to use the operation:
  44656. **
  44657. ** * The file-system supports the atomic-write property for
  44658. ** blocks of size page-size, and
  44659. ** * This commit is not part of a multi-file transaction, and
  44660. ** * Exactly one page has been modified and store in the journal file.
  44661. **
  44662. ** If the optimization was not enabled at compile time, then the
  44663. ** pager_incr_changecounter() function is called to update the change
  44664. ** counter in 'indirect-mode'. If the optimization is compiled in but
  44665. ** is not applicable to this transaction, call sqlite3JournalCreate()
  44666. ** to make sure the journal file has actually been created, then call
  44667. ** pager_incr_changecounter() to update the change-counter in indirect
  44668. ** mode.
  44669. **
  44670. ** Otherwise, if the optimization is both enabled and applicable,
  44671. ** then call pager_incr_changecounter() to update the change-counter
  44672. ** in 'direct' mode. In this case the journal file will never be
  44673. ** created for this transaction.
  44674. */
  44675. #ifdef SQLITE_ENABLE_ATOMIC_WRITE
  44676. PgHdr *pPg;
  44677. assert( isOpen(pPager->jfd)
  44678. || pPager->journalMode==PAGER_JOURNALMODE_OFF
  44679. || pPager->journalMode==PAGER_JOURNALMODE_WAL
  44680. );
  44681. if( !zMaster && isOpen(pPager->jfd)
  44682. && pPager->journalOff==jrnlBufferSize(pPager)
  44683. && pPager->dbSize>=pPager->dbOrigSize
  44684. && (0==(pPg = sqlite3PcacheDirtyList(pPager->pPCache)) || 0==pPg->pDirty)
  44685. ){
  44686. /* Update the db file change counter via the direct-write method. The
  44687. ** following call will modify the in-memory representation of page 1
  44688. ** to include the updated change counter and then write page 1
  44689. ** directly to the database file. Because of the atomic-write
  44690. ** property of the host file-system, this is safe.
  44691. */
  44692. rc = pager_incr_changecounter(pPager, 1);
  44693. }else{
  44694. rc = sqlite3JournalCreate(pPager->jfd);
  44695. if( rc==SQLITE_OK ){
  44696. rc = pager_incr_changecounter(pPager, 0);
  44697. }
  44698. }
  44699. #else
  44700. rc = pager_incr_changecounter(pPager, 0);
  44701. #endif
  44702. if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
  44703. /* Write the master journal name into the journal file. If a master
  44704. ** journal file name has already been written to the journal file,
  44705. ** or if zMaster is NULL (no master journal), then this call is a no-op.
  44706. */
  44707. rc = writeMasterJournal(pPager, zMaster);
  44708. if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
  44709. /* Sync the journal file and write all dirty pages to the database.
  44710. ** If the atomic-update optimization is being used, this sync will not
  44711. ** create the journal file or perform any real IO.
  44712. **
  44713. ** Because the change-counter page was just modified, unless the
  44714. ** atomic-update optimization is used it is almost certain that the
  44715. ** journal requires a sync here. However, in locking_mode=exclusive
  44716. ** on a system under memory pressure it is just possible that this is
  44717. ** not the case. In this case it is likely enough that the redundant
  44718. ** xSync() call will be changed to a no-op by the OS anyhow.
  44719. */
  44720. rc = syncJournal(pPager, 0);
  44721. if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
  44722. rc = pager_write_pagelist(pPager,sqlite3PcacheDirtyList(pPager->pPCache));
  44723. if( rc!=SQLITE_OK ){
  44724. assert( rc!=SQLITE_IOERR_BLOCKED );
  44725. goto commit_phase_one_exit;
  44726. }
  44727. sqlite3PcacheCleanAll(pPager->pPCache);
  44728. /* If the file on disk is smaller than the database image, use
  44729. ** pager_truncate to grow the file here. This can happen if the database
  44730. ** image was extended as part of the current transaction and then the
  44731. ** last page in the db image moved to the free-list. In this case the
  44732. ** last page is never written out to disk, leaving the database file
  44733. ** undersized. Fix this now if it is the case. */
  44734. if( pPager->dbSize>pPager->dbFileSize ){
  44735. Pgno nNew = pPager->dbSize - (pPager->dbSize==PAGER_MJ_PGNO(pPager));
  44736. assert( pPager->eState==PAGER_WRITER_DBMOD );
  44737. rc = pager_truncate(pPager, nNew);
  44738. if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
  44739. }
  44740. /* Finally, sync the database file. */
  44741. if( !noSync ){
  44742. rc = sqlite3PagerSync(pPager, zMaster);
  44743. }
  44744. IOTRACE(("DBSYNC %p\n", pPager))
  44745. }
  44746. }
  44747. commit_phase_one_exit:
  44748. if( rc==SQLITE_OK && !pagerUseWal(pPager) ){
  44749. pPager->eState = PAGER_WRITER_FINISHED;
  44750. }
  44751. return rc;
  44752. }
  44753. /*
  44754. ** When this function is called, the database file has been completely
  44755. ** updated to reflect the changes made by the current transaction and
  44756. ** synced to disk. The journal file still exists in the file-system
  44757. ** though, and if a failure occurs at this point it will eventually
  44758. ** be used as a hot-journal and the current transaction rolled back.
  44759. **
  44760. ** This function finalizes the journal file, either by deleting,
  44761. ** truncating or partially zeroing it, so that it cannot be used
  44762. ** for hot-journal rollback. Once this is done the transaction is
  44763. ** irrevocably committed.
  44764. **
  44765. ** If an error occurs, an IO error code is returned and the pager
  44766. ** moves into the error state. Otherwise, SQLITE_OK is returned.
  44767. */
  44768. SQLITE_PRIVATE int sqlite3PagerCommitPhaseTwo(Pager *pPager){
  44769. int rc = SQLITE_OK; /* Return code */
  44770. /* This routine should not be called if a prior error has occurred.
  44771. ** But if (due to a coding error elsewhere in the system) it does get
  44772. ** called, just return the same error code without doing anything. */
  44773. if( NEVER(pPager->errCode) ) return pPager->errCode;
  44774. assert( pPager->eState==PAGER_WRITER_LOCKED
  44775. || pPager->eState==PAGER_WRITER_FINISHED
  44776. || (pagerUseWal(pPager) && pPager->eState==PAGER_WRITER_CACHEMOD)
  44777. );
  44778. assert( assert_pager_state(pPager) );
  44779. /* An optimization. If the database was not actually modified during
  44780. ** this transaction, the pager is running in exclusive-mode and is
  44781. ** using persistent journals, then this function is a no-op.
  44782. **
  44783. ** The start of the journal file currently contains a single journal
  44784. ** header with the nRec field set to 0. If such a journal is used as
  44785. ** a hot-journal during hot-journal rollback, 0 changes will be made
  44786. ** to the database file. So there is no need to zero the journal
  44787. ** header. Since the pager is in exclusive mode, there is no need
  44788. ** to drop any locks either.
  44789. */
  44790. if( pPager->eState==PAGER_WRITER_LOCKED
  44791. && pPager->exclusiveMode
  44792. && pPager->journalMode==PAGER_JOURNALMODE_PERSIST
  44793. ){
  44794. assert( pPager->journalOff==JOURNAL_HDR_SZ(pPager) || !pPager->journalOff );
  44795. pPager->eState = PAGER_READER;
  44796. return SQLITE_OK;
  44797. }
  44798. PAGERTRACE(("COMMIT %d\n", PAGERID(pPager)));
  44799. pPager->iDataVersion++;
  44800. rc = pager_end_transaction(pPager, pPager->setMaster, 1);
  44801. return pager_error(pPager, rc);
  44802. }
  44803. /*
  44804. ** If a write transaction is open, then all changes made within the
  44805. ** transaction are reverted and the current write-transaction is closed.
  44806. ** The pager falls back to PAGER_READER state if successful, or PAGER_ERROR
  44807. ** state if an error occurs.
  44808. **
  44809. ** If the pager is already in PAGER_ERROR state when this function is called,
  44810. ** it returns Pager.errCode immediately. No work is performed in this case.
  44811. **
  44812. ** Otherwise, in rollback mode, this function performs two functions:
  44813. **
  44814. ** 1) It rolls back the journal file, restoring all database file and
  44815. ** in-memory cache pages to the state they were in when the transaction
  44816. ** was opened, and
  44817. **
  44818. ** 2) It finalizes the journal file, so that it is not used for hot
  44819. ** rollback at any point in the future.
  44820. **
  44821. ** Finalization of the journal file (task 2) is only performed if the
  44822. ** rollback is successful.
  44823. **
  44824. ** In WAL mode, all cache-entries containing data modified within the
  44825. ** current transaction are either expelled from the cache or reverted to
  44826. ** their pre-transaction state by re-reading data from the database or
  44827. ** WAL files. The WAL transaction is then closed.
  44828. */
  44829. SQLITE_PRIVATE int sqlite3PagerRollback(Pager *pPager){
  44830. int rc = SQLITE_OK; /* Return code */
  44831. PAGERTRACE(("ROLLBACK %d\n", PAGERID(pPager)));
  44832. /* PagerRollback() is a no-op if called in READER or OPEN state. If
  44833. ** the pager is already in the ERROR state, the rollback is not
  44834. ** attempted here. Instead, the error code is returned to the caller.
  44835. */
  44836. assert( assert_pager_state(pPager) );
  44837. if( pPager->eState==PAGER_ERROR ) return pPager->errCode;
  44838. if( pPager->eState<=PAGER_READER ) return SQLITE_OK;
  44839. if( pagerUseWal(pPager) ){
  44840. int rc2;
  44841. rc = sqlite3PagerSavepoint(pPager, SAVEPOINT_ROLLBACK, -1);
  44842. rc2 = pager_end_transaction(pPager, pPager->setMaster, 0);
  44843. if( rc==SQLITE_OK ) rc = rc2;
  44844. }else if( !isOpen(pPager->jfd) || pPager->eState==PAGER_WRITER_LOCKED ){
  44845. int eState = pPager->eState;
  44846. rc = pager_end_transaction(pPager, 0, 0);
  44847. if( !MEMDB && eState>PAGER_WRITER_LOCKED ){
  44848. /* This can happen using journal_mode=off. Move the pager to the error
  44849. ** state to indicate that the contents of the cache may not be trusted.
  44850. ** Any active readers will get SQLITE_ABORT.
  44851. */
  44852. pPager->errCode = SQLITE_ABORT;
  44853. pPager->eState = PAGER_ERROR;
  44854. return rc;
  44855. }
  44856. }else{
  44857. rc = pager_playback(pPager, 0);
  44858. }
  44859. assert( pPager->eState==PAGER_READER || rc!=SQLITE_OK );
  44860. assert( rc==SQLITE_OK || rc==SQLITE_FULL || rc==SQLITE_CORRUPT
  44861. || rc==SQLITE_NOMEM || (rc&0xFF)==SQLITE_IOERR
  44862. || rc==SQLITE_CANTOPEN
  44863. );
  44864. /* If an error occurs during a ROLLBACK, we can no longer trust the pager
  44865. ** cache. So call pager_error() on the way out to make any error persistent.
  44866. */
  44867. return pager_error(pPager, rc);
  44868. }
  44869. /*
  44870. ** Return TRUE if the database file is opened read-only. Return FALSE
  44871. ** if the database is (in theory) writable.
  44872. */
  44873. SQLITE_PRIVATE u8 sqlite3PagerIsreadonly(Pager *pPager){
  44874. return pPager->readOnly;
  44875. }
  44876. /*
  44877. ** Return the number of references to the pager.
  44878. */
  44879. SQLITE_PRIVATE int sqlite3PagerRefcount(Pager *pPager){
  44880. return sqlite3PcacheRefCount(pPager->pPCache);
  44881. }
  44882. /*
  44883. ** Return the approximate number of bytes of memory currently
  44884. ** used by the pager and its associated cache.
  44885. */
  44886. SQLITE_PRIVATE int sqlite3PagerMemUsed(Pager *pPager){
  44887. int perPageSize = pPager->pageSize + pPager->nExtra + sizeof(PgHdr)
  44888. + 5*sizeof(void*);
  44889. return perPageSize*sqlite3PcachePagecount(pPager->pPCache)
  44890. + sqlite3MallocSize(pPager)
  44891. + pPager->pageSize;
  44892. }
  44893. /*
  44894. ** Return the number of references to the specified page.
  44895. */
  44896. SQLITE_PRIVATE int sqlite3PagerPageRefcount(DbPage *pPage){
  44897. return sqlite3PcachePageRefcount(pPage);
  44898. }
  44899. #ifdef SQLITE_TEST
  44900. /*
  44901. ** This routine is used for testing and analysis only.
  44902. */
  44903. SQLITE_PRIVATE int *sqlite3PagerStats(Pager *pPager){
  44904. static int a[11];
  44905. a[0] = sqlite3PcacheRefCount(pPager->pPCache);
  44906. a[1] = sqlite3PcachePagecount(pPager->pPCache);
  44907. a[2] = sqlite3PcacheGetCachesize(pPager->pPCache);
  44908. a[3] = pPager->eState==PAGER_OPEN ? -1 : (int) pPager->dbSize;
  44909. a[4] = pPager->eState;
  44910. a[5] = pPager->errCode;
  44911. a[6] = pPager->aStat[PAGER_STAT_HIT];
  44912. a[7] = pPager->aStat[PAGER_STAT_MISS];
  44913. a[8] = 0; /* Used to be pPager->nOvfl */
  44914. a[9] = pPager->nRead;
  44915. a[10] = pPager->aStat[PAGER_STAT_WRITE];
  44916. return a;
  44917. }
  44918. #endif
  44919. /*
  44920. ** Parameter eStat must be either SQLITE_DBSTATUS_CACHE_HIT or
  44921. ** SQLITE_DBSTATUS_CACHE_MISS. Before returning, *pnVal is incremented by the
  44922. ** current cache hit or miss count, according to the value of eStat. If the
  44923. ** reset parameter is non-zero, the cache hit or miss count is zeroed before
  44924. ** returning.
  44925. */
  44926. SQLITE_PRIVATE void sqlite3PagerCacheStat(Pager *pPager, int eStat, int reset, int *pnVal){
  44927. assert( eStat==SQLITE_DBSTATUS_CACHE_HIT
  44928. || eStat==SQLITE_DBSTATUS_CACHE_MISS
  44929. || eStat==SQLITE_DBSTATUS_CACHE_WRITE
  44930. );
  44931. assert( SQLITE_DBSTATUS_CACHE_HIT+1==SQLITE_DBSTATUS_CACHE_MISS );
  44932. assert( SQLITE_DBSTATUS_CACHE_HIT+2==SQLITE_DBSTATUS_CACHE_WRITE );
  44933. assert( PAGER_STAT_HIT==0 && PAGER_STAT_MISS==1 && PAGER_STAT_WRITE==2 );
  44934. *pnVal += pPager->aStat[eStat - SQLITE_DBSTATUS_CACHE_HIT];
  44935. if( reset ){
  44936. pPager->aStat[eStat - SQLITE_DBSTATUS_CACHE_HIT] = 0;
  44937. }
  44938. }
  44939. /*
  44940. ** Return true if this is an in-memory pager.
  44941. */
  44942. SQLITE_PRIVATE int sqlite3PagerIsMemdb(Pager *pPager){
  44943. return MEMDB;
  44944. }
  44945. /*
  44946. ** Check that there are at least nSavepoint savepoints open. If there are
  44947. ** currently less than nSavepoints open, then open one or more savepoints
  44948. ** to make up the difference. If the number of savepoints is already
  44949. ** equal to nSavepoint, then this function is a no-op.
  44950. **
  44951. ** If a memory allocation fails, SQLITE_NOMEM is returned. If an error
  44952. ** occurs while opening the sub-journal file, then an IO error code is
  44953. ** returned. Otherwise, SQLITE_OK.
  44954. */
  44955. SQLITE_PRIVATE int sqlite3PagerOpenSavepoint(Pager *pPager, int nSavepoint){
  44956. int rc = SQLITE_OK; /* Return code */
  44957. int nCurrent = pPager->nSavepoint; /* Current number of savepoints */
  44958. assert( pPager->eState>=PAGER_WRITER_LOCKED );
  44959. assert( assert_pager_state(pPager) );
  44960. if( nSavepoint>nCurrent && pPager->useJournal ){
  44961. int ii; /* Iterator variable */
  44962. PagerSavepoint *aNew; /* New Pager.aSavepoint array */
  44963. /* Grow the Pager.aSavepoint array using realloc(). Return SQLITE_NOMEM
  44964. ** if the allocation fails. Otherwise, zero the new portion in case a
  44965. ** malloc failure occurs while populating it in the for(...) loop below.
  44966. */
  44967. aNew = (PagerSavepoint *)sqlite3Realloc(
  44968. pPager->aSavepoint, sizeof(PagerSavepoint)*nSavepoint
  44969. );
  44970. if( !aNew ){
  44971. return SQLITE_NOMEM;
  44972. }
  44973. memset(&aNew[nCurrent], 0, (nSavepoint-nCurrent) * sizeof(PagerSavepoint));
  44974. pPager->aSavepoint = aNew;
  44975. /* Populate the PagerSavepoint structures just allocated. */
  44976. for(ii=nCurrent; ii<nSavepoint; ii++){
  44977. aNew[ii].nOrig = pPager->dbSize;
  44978. if( isOpen(pPager->jfd) && pPager->journalOff>0 ){
  44979. aNew[ii].iOffset = pPager->journalOff;
  44980. }else{
  44981. aNew[ii].iOffset = JOURNAL_HDR_SZ(pPager);
  44982. }
  44983. aNew[ii].iSubRec = pPager->nSubRec;
  44984. aNew[ii].pInSavepoint = sqlite3BitvecCreate(pPager->dbSize);
  44985. if( !aNew[ii].pInSavepoint ){
  44986. return SQLITE_NOMEM;
  44987. }
  44988. if( pagerUseWal(pPager) ){
  44989. sqlite3WalSavepoint(pPager->pWal, aNew[ii].aWalData);
  44990. }
  44991. pPager->nSavepoint = ii+1;
  44992. }
  44993. assert( pPager->nSavepoint==nSavepoint );
  44994. assertTruncateConstraint(pPager);
  44995. }
  44996. return rc;
  44997. }
  44998. /*
  44999. ** This function is called to rollback or release (commit) a savepoint.
  45000. ** The savepoint to release or rollback need not be the most recently
  45001. ** created savepoint.
  45002. **
  45003. ** Parameter op is always either SAVEPOINT_ROLLBACK or SAVEPOINT_RELEASE.
  45004. ** If it is SAVEPOINT_RELEASE, then release and destroy the savepoint with
  45005. ** index iSavepoint. If it is SAVEPOINT_ROLLBACK, then rollback all changes
  45006. ** that have occurred since the specified savepoint was created.
  45007. **
  45008. ** The savepoint to rollback or release is identified by parameter
  45009. ** iSavepoint. A value of 0 means to operate on the outermost savepoint
  45010. ** (the first created). A value of (Pager.nSavepoint-1) means operate
  45011. ** on the most recently created savepoint. If iSavepoint is greater than
  45012. ** (Pager.nSavepoint-1), then this function is a no-op.
  45013. **
  45014. ** If a negative value is passed to this function, then the current
  45015. ** transaction is rolled back. This is different to calling
  45016. ** sqlite3PagerRollback() because this function does not terminate
  45017. ** the transaction or unlock the database, it just restores the
  45018. ** contents of the database to its original state.
  45019. **
  45020. ** In any case, all savepoints with an index greater than iSavepoint
  45021. ** are destroyed. If this is a release operation (op==SAVEPOINT_RELEASE),
  45022. ** then savepoint iSavepoint is also destroyed.
  45023. **
  45024. ** This function may return SQLITE_NOMEM if a memory allocation fails,
  45025. ** or an IO error code if an IO error occurs while rolling back a
  45026. ** savepoint. If no errors occur, SQLITE_OK is returned.
  45027. */
  45028. SQLITE_PRIVATE int sqlite3PagerSavepoint(Pager *pPager, int op, int iSavepoint){
  45029. int rc = pPager->errCode; /* Return code */
  45030. assert( op==SAVEPOINT_RELEASE || op==SAVEPOINT_ROLLBACK );
  45031. assert( iSavepoint>=0 || op==SAVEPOINT_ROLLBACK );
  45032. if( rc==SQLITE_OK && iSavepoint<pPager->nSavepoint ){
  45033. int ii; /* Iterator variable */
  45034. int nNew; /* Number of remaining savepoints after this op. */
  45035. /* Figure out how many savepoints will still be active after this
  45036. ** operation. Store this value in nNew. Then free resources associated
  45037. ** with any savepoints that are destroyed by this operation.
  45038. */
  45039. nNew = iSavepoint + (( op==SAVEPOINT_RELEASE ) ? 0 : 1);
  45040. for(ii=nNew; ii<pPager->nSavepoint; ii++){
  45041. sqlite3BitvecDestroy(pPager->aSavepoint[ii].pInSavepoint);
  45042. }
  45043. pPager->nSavepoint = nNew;
  45044. /* If this is a release of the outermost savepoint, truncate
  45045. ** the sub-journal to zero bytes in size. */
  45046. if( op==SAVEPOINT_RELEASE ){
  45047. if( nNew==0 && isOpen(pPager->sjfd) ){
  45048. /* Only truncate if it is an in-memory sub-journal. */
  45049. if( sqlite3IsMemJournal(pPager->sjfd) ){
  45050. rc = sqlite3OsTruncate(pPager->sjfd, 0);
  45051. assert( rc==SQLITE_OK );
  45052. }
  45053. pPager->nSubRec = 0;
  45054. }
  45055. }
  45056. /* Else this is a rollback operation, playback the specified savepoint.
  45057. ** If this is a temp-file, it is possible that the journal file has
  45058. ** not yet been opened. In this case there have been no changes to
  45059. ** the database file, so the playback operation can be skipped.
  45060. */
  45061. else if( pagerUseWal(pPager) || isOpen(pPager->jfd) ){
  45062. PagerSavepoint *pSavepoint = (nNew==0)?0:&pPager->aSavepoint[nNew-1];
  45063. rc = pagerPlaybackSavepoint(pPager, pSavepoint);
  45064. assert(rc!=SQLITE_DONE);
  45065. }
  45066. }
  45067. return rc;
  45068. }
  45069. /*
  45070. ** Return the full pathname of the database file.
  45071. **
  45072. ** Except, if the pager is in-memory only, then return an empty string if
  45073. ** nullIfMemDb is true. This routine is called with nullIfMemDb==1 when
  45074. ** used to report the filename to the user, for compatibility with legacy
  45075. ** behavior. But when the Btree needs to know the filename for matching to
  45076. ** shared cache, it uses nullIfMemDb==0 so that in-memory databases can
  45077. ** participate in shared-cache.
  45078. */
  45079. SQLITE_PRIVATE const char *sqlite3PagerFilename(Pager *pPager, int nullIfMemDb){
  45080. return (nullIfMemDb && pPager->memDb) ? "" : pPager->zFilename;
  45081. }
  45082. /*
  45083. ** Return the VFS structure for the pager.
  45084. */
  45085. SQLITE_PRIVATE const sqlite3_vfs *sqlite3PagerVfs(Pager *pPager){
  45086. return pPager->pVfs;
  45087. }
  45088. /*
  45089. ** Return the file handle for the database file associated
  45090. ** with the pager. This might return NULL if the file has
  45091. ** not yet been opened.
  45092. */
  45093. SQLITE_PRIVATE sqlite3_file *sqlite3PagerFile(Pager *pPager){
  45094. return pPager->fd;
  45095. }
  45096. /*
  45097. ** Return the full pathname of the journal file.
  45098. */
  45099. SQLITE_PRIVATE const char *sqlite3PagerJournalname(Pager *pPager){
  45100. return pPager->zJournal;
  45101. }
  45102. /*
  45103. ** Return true if fsync() calls are disabled for this pager. Return FALSE
  45104. ** if fsync()s are executed normally.
  45105. */
  45106. SQLITE_PRIVATE int sqlite3PagerNosync(Pager *pPager){
  45107. return pPager->noSync;
  45108. }
  45109. #ifdef SQLITE_HAS_CODEC
  45110. /*
  45111. ** Set or retrieve the codec for this pager
  45112. */
  45113. SQLITE_PRIVATE void sqlite3PagerSetCodec(
  45114. Pager *pPager,
  45115. void *(*xCodec)(void*,void*,Pgno,int),
  45116. void (*xCodecSizeChng)(void*,int,int),
  45117. void (*xCodecFree)(void*),
  45118. void *pCodec
  45119. ){
  45120. if( pPager->xCodecFree ) pPager->xCodecFree(pPager->pCodec);
  45121. pPager->xCodec = pPager->memDb ? 0 : xCodec;
  45122. pPager->xCodecSizeChng = xCodecSizeChng;
  45123. pPager->xCodecFree = xCodecFree;
  45124. pPager->pCodec = pCodec;
  45125. pagerReportSize(pPager);
  45126. }
  45127. SQLITE_PRIVATE void *sqlite3PagerGetCodec(Pager *pPager){
  45128. return pPager->pCodec;
  45129. }
  45130. /*
  45131. ** This function is called by the wal module when writing page content
  45132. ** into the log file.
  45133. **
  45134. ** This function returns a pointer to a buffer containing the encrypted
  45135. ** page content. If a malloc fails, this function may return NULL.
  45136. */
  45137. SQLITE_PRIVATE void *sqlite3PagerCodec(PgHdr *pPg){
  45138. void *aData = 0;
  45139. CODEC2(pPg->pPager, pPg->pData, pPg->pgno, 6, return 0, aData);
  45140. return aData;
  45141. }
  45142. /*
  45143. ** Return the current pager state
  45144. */
  45145. SQLITE_PRIVATE int sqlite3PagerState(Pager *pPager){
  45146. return pPager->eState;
  45147. }
  45148. #endif /* SQLITE_HAS_CODEC */
  45149. #ifndef SQLITE_OMIT_AUTOVACUUM
  45150. /*
  45151. ** Move the page pPg to location pgno in the file.
  45152. **
  45153. ** There must be no references to the page previously located at
  45154. ** pgno (which we call pPgOld) though that page is allowed to be
  45155. ** in cache. If the page previously located at pgno is not already
  45156. ** in the rollback journal, it is not put there by by this routine.
  45157. **
  45158. ** References to the page pPg remain valid. Updating any
  45159. ** meta-data associated with pPg (i.e. data stored in the nExtra bytes
  45160. ** allocated along with the page) is the responsibility of the caller.
  45161. **
  45162. ** A transaction must be active when this routine is called. It used to be
  45163. ** required that a statement transaction was not active, but this restriction
  45164. ** has been removed (CREATE INDEX needs to move a page when a statement
  45165. ** transaction is active).
  45166. **
  45167. ** If the fourth argument, isCommit, is non-zero, then this page is being
  45168. ** moved as part of a database reorganization just before the transaction
  45169. ** is being committed. In this case, it is guaranteed that the database page
  45170. ** pPg refers to will not be written to again within this transaction.
  45171. **
  45172. ** This function may return SQLITE_NOMEM or an IO error code if an error
  45173. ** occurs. Otherwise, it returns SQLITE_OK.
  45174. */
  45175. SQLITE_PRIVATE int sqlite3PagerMovepage(Pager *pPager, DbPage *pPg, Pgno pgno, int isCommit){
  45176. PgHdr *pPgOld; /* The page being overwritten. */
  45177. Pgno needSyncPgno = 0; /* Old value of pPg->pgno, if sync is required */
  45178. int rc; /* Return code */
  45179. Pgno origPgno; /* The original page number */
  45180. assert( pPg->nRef>0 );
  45181. assert( pPager->eState==PAGER_WRITER_CACHEMOD
  45182. || pPager->eState==PAGER_WRITER_DBMOD
  45183. );
  45184. assert( assert_pager_state(pPager) );
  45185. /* In order to be able to rollback, an in-memory database must journal
  45186. ** the page we are moving from.
  45187. */
  45188. if( MEMDB ){
  45189. rc = sqlite3PagerWrite(pPg);
  45190. if( rc ) return rc;
  45191. }
  45192. /* If the page being moved is dirty and has not been saved by the latest
  45193. ** savepoint, then save the current contents of the page into the
  45194. ** sub-journal now. This is required to handle the following scenario:
  45195. **
  45196. ** BEGIN;
  45197. ** <journal page X, then modify it in memory>
  45198. ** SAVEPOINT one;
  45199. ** <Move page X to location Y>
  45200. ** ROLLBACK TO one;
  45201. **
  45202. ** If page X were not written to the sub-journal here, it would not
  45203. ** be possible to restore its contents when the "ROLLBACK TO one"
  45204. ** statement were is processed.
  45205. **
  45206. ** subjournalPage() may need to allocate space to store pPg->pgno into
  45207. ** one or more savepoint bitvecs. This is the reason this function
  45208. ** may return SQLITE_NOMEM.
  45209. */
  45210. if( pPg->flags&PGHDR_DIRTY
  45211. && subjRequiresPage(pPg)
  45212. && SQLITE_OK!=(rc = subjournalPage(pPg))
  45213. ){
  45214. return rc;
  45215. }
  45216. PAGERTRACE(("MOVE %d page %d (needSync=%d) moves to %d\n",
  45217. PAGERID(pPager), pPg->pgno, (pPg->flags&PGHDR_NEED_SYNC)?1:0, pgno));
  45218. IOTRACE(("MOVE %p %d %d\n", pPager, pPg->pgno, pgno))
  45219. /* If the journal needs to be sync()ed before page pPg->pgno can
  45220. ** be written to, store pPg->pgno in local variable needSyncPgno.
  45221. **
  45222. ** If the isCommit flag is set, there is no need to remember that
  45223. ** the journal needs to be sync()ed before database page pPg->pgno
  45224. ** can be written to. The caller has already promised not to write to it.
  45225. */
  45226. if( (pPg->flags&PGHDR_NEED_SYNC) && !isCommit ){
  45227. needSyncPgno = pPg->pgno;
  45228. assert( pPager->journalMode==PAGER_JOURNALMODE_OFF ||
  45229. pageInJournal(pPager, pPg) || pPg->pgno>pPager->dbOrigSize );
  45230. assert( pPg->flags&PGHDR_DIRTY );
  45231. }
  45232. /* If the cache contains a page with page-number pgno, remove it
  45233. ** from its hash chain. Also, if the PGHDR_NEED_SYNC flag was set for
  45234. ** page pgno before the 'move' operation, it needs to be retained
  45235. ** for the page moved there.
  45236. */
  45237. pPg->flags &= ~PGHDR_NEED_SYNC;
  45238. pPgOld = sqlite3PagerLookup(pPager, pgno);
  45239. assert( !pPgOld || pPgOld->nRef==1 );
  45240. if( pPgOld ){
  45241. pPg->flags |= (pPgOld->flags&PGHDR_NEED_SYNC);
  45242. if( MEMDB ){
  45243. /* Do not discard pages from an in-memory database since we might
  45244. ** need to rollback later. Just move the page out of the way. */
  45245. sqlite3PcacheMove(pPgOld, pPager->dbSize+1);
  45246. }else{
  45247. sqlite3PcacheDrop(pPgOld);
  45248. }
  45249. }
  45250. origPgno = pPg->pgno;
  45251. sqlite3PcacheMove(pPg, pgno);
  45252. sqlite3PcacheMakeDirty(pPg);
  45253. /* For an in-memory database, make sure the original page continues
  45254. ** to exist, in case the transaction needs to roll back. Use pPgOld
  45255. ** as the original page since it has already been allocated.
  45256. */
  45257. if( MEMDB ){
  45258. assert( pPgOld );
  45259. sqlite3PcacheMove(pPgOld, origPgno);
  45260. sqlite3PagerUnrefNotNull(pPgOld);
  45261. }
  45262. if( needSyncPgno ){
  45263. /* If needSyncPgno is non-zero, then the journal file needs to be
  45264. ** sync()ed before any data is written to database file page needSyncPgno.
  45265. ** Currently, no such page exists in the page-cache and the
  45266. ** "is journaled" bitvec flag has been set. This needs to be remedied by
  45267. ** loading the page into the pager-cache and setting the PGHDR_NEED_SYNC
  45268. ** flag.
  45269. **
  45270. ** If the attempt to load the page into the page-cache fails, (due
  45271. ** to a malloc() or IO failure), clear the bit in the pInJournal[]
  45272. ** array. Otherwise, if the page is loaded and written again in
  45273. ** this transaction, it may be written to the database file before
  45274. ** it is synced into the journal file. This way, it may end up in
  45275. ** the journal file twice, but that is not a problem.
  45276. */
  45277. PgHdr *pPgHdr;
  45278. rc = sqlite3PagerGet(pPager, needSyncPgno, &pPgHdr);
  45279. if( rc!=SQLITE_OK ){
  45280. if( needSyncPgno<=pPager->dbOrigSize ){
  45281. assert( pPager->pTmpSpace!=0 );
  45282. sqlite3BitvecClear(pPager->pInJournal, needSyncPgno, pPager->pTmpSpace);
  45283. }
  45284. return rc;
  45285. }
  45286. pPgHdr->flags |= PGHDR_NEED_SYNC;
  45287. sqlite3PcacheMakeDirty(pPgHdr);
  45288. sqlite3PagerUnrefNotNull(pPgHdr);
  45289. }
  45290. return SQLITE_OK;
  45291. }
  45292. #endif
  45293. /*
  45294. ** The page handle passed as the first argument refers to a dirty page
  45295. ** with a page number other than iNew. This function changes the page's
  45296. ** page number to iNew and sets the value of the PgHdr.flags field to
  45297. ** the value passed as the third parameter.
  45298. */
  45299. SQLITE_PRIVATE void sqlite3PagerRekey(DbPage *pPg, Pgno iNew, u16 flags){
  45300. assert( pPg->pgno!=iNew );
  45301. pPg->flags = flags;
  45302. sqlite3PcacheMove(pPg, iNew);
  45303. }
  45304. /*
  45305. ** Return a pointer to the data for the specified page.
  45306. */
  45307. SQLITE_PRIVATE void *sqlite3PagerGetData(DbPage *pPg){
  45308. assert( pPg->nRef>0 || pPg->pPager->memDb );
  45309. return pPg->pData;
  45310. }
  45311. /*
  45312. ** Return a pointer to the Pager.nExtra bytes of "extra" space
  45313. ** allocated along with the specified page.
  45314. */
  45315. SQLITE_PRIVATE void *sqlite3PagerGetExtra(DbPage *pPg){
  45316. return pPg->pExtra;
  45317. }
  45318. /*
  45319. ** Get/set the locking-mode for this pager. Parameter eMode must be one
  45320. ** of PAGER_LOCKINGMODE_QUERY, PAGER_LOCKINGMODE_NORMAL or
  45321. ** PAGER_LOCKINGMODE_EXCLUSIVE. If the parameter is not _QUERY, then
  45322. ** the locking-mode is set to the value specified.
  45323. **
  45324. ** The returned value is either PAGER_LOCKINGMODE_NORMAL or
  45325. ** PAGER_LOCKINGMODE_EXCLUSIVE, indicating the current (possibly updated)
  45326. ** locking-mode.
  45327. */
  45328. SQLITE_PRIVATE int sqlite3PagerLockingMode(Pager *pPager, int eMode){
  45329. assert( eMode==PAGER_LOCKINGMODE_QUERY
  45330. || eMode==PAGER_LOCKINGMODE_NORMAL
  45331. || eMode==PAGER_LOCKINGMODE_EXCLUSIVE );
  45332. assert( PAGER_LOCKINGMODE_QUERY<0 );
  45333. assert( PAGER_LOCKINGMODE_NORMAL>=0 && PAGER_LOCKINGMODE_EXCLUSIVE>=0 );
  45334. assert( pPager->exclusiveMode || 0==sqlite3WalHeapMemory(pPager->pWal) );
  45335. if( eMode>=0 && !pPager->tempFile && !sqlite3WalHeapMemory(pPager->pWal) ){
  45336. pPager->exclusiveMode = (u8)eMode;
  45337. }
  45338. return (int)pPager->exclusiveMode;
  45339. }
  45340. /*
  45341. ** Set the journal-mode for this pager. Parameter eMode must be one of:
  45342. **
  45343. ** PAGER_JOURNALMODE_DELETE
  45344. ** PAGER_JOURNALMODE_TRUNCATE
  45345. ** PAGER_JOURNALMODE_PERSIST
  45346. ** PAGER_JOURNALMODE_OFF
  45347. ** PAGER_JOURNALMODE_MEMORY
  45348. ** PAGER_JOURNALMODE_WAL
  45349. **
  45350. ** The journalmode is set to the value specified if the change is allowed.
  45351. ** The change may be disallowed for the following reasons:
  45352. **
  45353. ** * An in-memory database can only have its journal_mode set to _OFF
  45354. ** or _MEMORY.
  45355. **
  45356. ** * Temporary databases cannot have _WAL journalmode.
  45357. **
  45358. ** The returned indicate the current (possibly updated) journal-mode.
  45359. */
  45360. SQLITE_PRIVATE int sqlite3PagerSetJournalMode(Pager *pPager, int eMode){
  45361. u8 eOld = pPager->journalMode; /* Prior journalmode */
  45362. #ifdef SQLITE_DEBUG
  45363. /* The print_pager_state() routine is intended to be used by the debugger
  45364. ** only. We invoke it once here to suppress a compiler warning. */
  45365. print_pager_state(pPager);
  45366. #endif
  45367. /* The eMode parameter is always valid */
  45368. assert( eMode==PAGER_JOURNALMODE_DELETE
  45369. || eMode==PAGER_JOURNALMODE_TRUNCATE
  45370. || eMode==PAGER_JOURNALMODE_PERSIST
  45371. || eMode==PAGER_JOURNALMODE_OFF
  45372. || eMode==PAGER_JOURNALMODE_WAL
  45373. || eMode==PAGER_JOURNALMODE_MEMORY );
  45374. /* This routine is only called from the OP_JournalMode opcode, and
  45375. ** the logic there will never allow a temporary file to be changed
  45376. ** to WAL mode.
  45377. */
  45378. assert( pPager->tempFile==0 || eMode!=PAGER_JOURNALMODE_WAL );
  45379. /* Do allow the journalmode of an in-memory database to be set to
  45380. ** anything other than MEMORY or OFF
  45381. */
  45382. if( MEMDB ){
  45383. assert( eOld==PAGER_JOURNALMODE_MEMORY || eOld==PAGER_JOURNALMODE_OFF );
  45384. if( eMode!=PAGER_JOURNALMODE_MEMORY && eMode!=PAGER_JOURNALMODE_OFF ){
  45385. eMode = eOld;
  45386. }
  45387. }
  45388. if( eMode!=eOld ){
  45389. /* Change the journal mode. */
  45390. assert( pPager->eState!=PAGER_ERROR );
  45391. pPager->journalMode = (u8)eMode;
  45392. /* When transistioning from TRUNCATE or PERSIST to any other journal
  45393. ** mode except WAL, unless the pager is in locking_mode=exclusive mode,
  45394. ** delete the journal file.
  45395. */
  45396. assert( (PAGER_JOURNALMODE_TRUNCATE & 5)==1 );
  45397. assert( (PAGER_JOURNALMODE_PERSIST & 5)==1 );
  45398. assert( (PAGER_JOURNALMODE_DELETE & 5)==0 );
  45399. assert( (PAGER_JOURNALMODE_MEMORY & 5)==4 );
  45400. assert( (PAGER_JOURNALMODE_OFF & 5)==0 );
  45401. assert( (PAGER_JOURNALMODE_WAL & 5)==5 );
  45402. assert( isOpen(pPager->fd) || pPager->exclusiveMode );
  45403. if( !pPager->exclusiveMode && (eOld & 5)==1 && (eMode & 1)==0 ){
  45404. /* In this case we would like to delete the journal file. If it is
  45405. ** not possible, then that is not a problem. Deleting the journal file
  45406. ** here is an optimization only.
  45407. **
  45408. ** Before deleting the journal file, obtain a RESERVED lock on the
  45409. ** database file. This ensures that the journal file is not deleted
  45410. ** while it is in use by some other client.
  45411. */
  45412. sqlite3OsClose(pPager->jfd);
  45413. if( pPager->eLock>=RESERVED_LOCK ){
  45414. sqlite3OsDelete(pPager->pVfs, pPager->zJournal, 0);
  45415. }else{
  45416. int rc = SQLITE_OK;
  45417. int state = pPager->eState;
  45418. assert( state==PAGER_OPEN || state==PAGER_READER );
  45419. if( state==PAGER_OPEN ){
  45420. rc = sqlite3PagerSharedLock(pPager);
  45421. }
  45422. if( pPager->eState==PAGER_READER ){
  45423. assert( rc==SQLITE_OK );
  45424. rc = pagerLockDb(pPager, RESERVED_LOCK);
  45425. }
  45426. if( rc==SQLITE_OK ){
  45427. sqlite3OsDelete(pPager->pVfs, pPager->zJournal, 0);
  45428. }
  45429. if( rc==SQLITE_OK && state==PAGER_READER ){
  45430. pagerUnlockDb(pPager, SHARED_LOCK);
  45431. }else if( state==PAGER_OPEN ){
  45432. pager_unlock(pPager);
  45433. }
  45434. assert( state==pPager->eState );
  45435. }
  45436. }else if( eMode==PAGER_JOURNALMODE_OFF ){
  45437. sqlite3OsClose(pPager->jfd);
  45438. }
  45439. }
  45440. /* Return the new journal mode */
  45441. return (int)pPager->journalMode;
  45442. }
  45443. /*
  45444. ** Return the current journal mode.
  45445. */
  45446. SQLITE_PRIVATE int sqlite3PagerGetJournalMode(Pager *pPager){
  45447. return (int)pPager->journalMode;
  45448. }
  45449. /*
  45450. ** Return TRUE if the pager is in a state where it is OK to change the
  45451. ** journalmode. Journalmode changes can only happen when the database
  45452. ** is unmodified.
  45453. */
  45454. SQLITE_PRIVATE int sqlite3PagerOkToChangeJournalMode(Pager *pPager){
  45455. assert( assert_pager_state(pPager) );
  45456. if( pPager->eState>=PAGER_WRITER_CACHEMOD ) return 0;
  45457. if( NEVER(isOpen(pPager->jfd) && pPager->journalOff>0) ) return 0;
  45458. return 1;
  45459. }
  45460. /*
  45461. ** Get/set the size-limit used for persistent journal files.
  45462. **
  45463. ** Setting the size limit to -1 means no limit is enforced.
  45464. ** An attempt to set a limit smaller than -1 is a no-op.
  45465. */
  45466. SQLITE_PRIVATE i64 sqlite3PagerJournalSizeLimit(Pager *pPager, i64 iLimit){
  45467. if( iLimit>=-1 ){
  45468. pPager->journalSizeLimit = iLimit;
  45469. sqlite3WalLimit(pPager->pWal, iLimit);
  45470. }
  45471. return pPager->journalSizeLimit;
  45472. }
  45473. /*
  45474. ** Return a pointer to the pPager->pBackup variable. The backup module
  45475. ** in backup.c maintains the content of this variable. This module
  45476. ** uses it opaquely as an argument to sqlite3BackupRestart() and
  45477. ** sqlite3BackupUpdate() only.
  45478. */
  45479. SQLITE_PRIVATE sqlite3_backup **sqlite3PagerBackupPtr(Pager *pPager){
  45480. return &pPager->pBackup;
  45481. }
  45482. #ifndef SQLITE_OMIT_VACUUM
  45483. /*
  45484. ** Unless this is an in-memory or temporary database, clear the pager cache.
  45485. */
  45486. SQLITE_PRIVATE void sqlite3PagerClearCache(Pager *pPager){
  45487. if( !MEMDB && pPager->tempFile==0 ) pager_reset(pPager);
  45488. }
  45489. #endif
  45490. #ifndef SQLITE_OMIT_WAL
  45491. /*
  45492. ** This function is called when the user invokes "PRAGMA wal_checkpoint",
  45493. ** "PRAGMA wal_blocking_checkpoint" or calls the sqlite3_wal_checkpoint()
  45494. ** or wal_blocking_checkpoint() API functions.
  45495. **
  45496. ** Parameter eMode is one of SQLITE_CHECKPOINT_PASSIVE, FULL or RESTART.
  45497. */
  45498. SQLITE_PRIVATE int sqlite3PagerCheckpoint(Pager *pPager, int eMode, int *pnLog, int *pnCkpt){
  45499. int rc = SQLITE_OK;
  45500. if( pPager->pWal ){
  45501. rc = sqlite3WalCheckpoint(pPager->pWal, eMode,
  45502. (eMode==SQLITE_CHECKPOINT_PASSIVE ? 0 : pPager->xBusyHandler),
  45503. pPager->pBusyHandlerArg,
  45504. pPager->ckptSyncFlags, pPager->pageSize, (u8 *)pPager->pTmpSpace,
  45505. pnLog, pnCkpt
  45506. );
  45507. }
  45508. return rc;
  45509. }
  45510. SQLITE_PRIVATE int sqlite3PagerWalCallback(Pager *pPager){
  45511. return sqlite3WalCallback(pPager->pWal);
  45512. }
  45513. /*
  45514. ** Return true if the underlying VFS for the given pager supports the
  45515. ** primitives necessary for write-ahead logging.
  45516. */
  45517. SQLITE_PRIVATE int sqlite3PagerWalSupported(Pager *pPager){
  45518. const sqlite3_io_methods *pMethods = pPager->fd->pMethods;
  45519. return pPager->exclusiveMode || (pMethods->iVersion>=2 && pMethods->xShmMap);
  45520. }
  45521. /*
  45522. ** Attempt to take an exclusive lock on the database file. If a PENDING lock
  45523. ** is obtained instead, immediately release it.
  45524. */
  45525. static int pagerExclusiveLock(Pager *pPager){
  45526. int rc; /* Return code */
  45527. assert( pPager->eLock==SHARED_LOCK || pPager->eLock==EXCLUSIVE_LOCK );
  45528. rc = pagerLockDb(pPager, EXCLUSIVE_LOCK);
  45529. if( rc!=SQLITE_OK ){
  45530. /* If the attempt to grab the exclusive lock failed, release the
  45531. ** pending lock that may have been obtained instead. */
  45532. pagerUnlockDb(pPager, SHARED_LOCK);
  45533. }
  45534. return rc;
  45535. }
  45536. /*
  45537. ** Call sqlite3WalOpen() to open the WAL handle. If the pager is in
  45538. ** exclusive-locking mode when this function is called, take an EXCLUSIVE
  45539. ** lock on the database file and use heap-memory to store the wal-index
  45540. ** in. Otherwise, use the normal shared-memory.
  45541. */
  45542. static int pagerOpenWal(Pager *pPager){
  45543. int rc = SQLITE_OK;
  45544. assert( pPager->pWal==0 && pPager->tempFile==0 );
  45545. assert( pPager->eLock==SHARED_LOCK || pPager->eLock==EXCLUSIVE_LOCK );
  45546. /* If the pager is already in exclusive-mode, the WAL module will use
  45547. ** heap-memory for the wal-index instead of the VFS shared-memory
  45548. ** implementation. Take the exclusive lock now, before opening the WAL
  45549. ** file, to make sure this is safe.
  45550. */
  45551. if( pPager->exclusiveMode ){
  45552. rc = pagerExclusiveLock(pPager);
  45553. }
  45554. /* Open the connection to the log file. If this operation fails,
  45555. ** (e.g. due to malloc() failure), return an error code.
  45556. */
  45557. if( rc==SQLITE_OK ){
  45558. rc = sqlite3WalOpen(pPager->pVfs,
  45559. pPager->fd, pPager->zWal, pPager->exclusiveMode,
  45560. pPager->journalSizeLimit, &pPager->pWal
  45561. );
  45562. }
  45563. pagerFixMaplimit(pPager);
  45564. return rc;
  45565. }
  45566. /*
  45567. ** The caller must be holding a SHARED lock on the database file to call
  45568. ** this function.
  45569. **
  45570. ** If the pager passed as the first argument is open on a real database
  45571. ** file (not a temp file or an in-memory database), and the WAL file
  45572. ** is not already open, make an attempt to open it now. If successful,
  45573. ** return SQLITE_OK. If an error occurs or the VFS used by the pager does
  45574. ** not support the xShmXXX() methods, return an error code. *pbOpen is
  45575. ** not modified in either case.
  45576. **
  45577. ** If the pager is open on a temp-file (or in-memory database), or if
  45578. ** the WAL file is already open, set *pbOpen to 1 and return SQLITE_OK
  45579. ** without doing anything.
  45580. */
  45581. SQLITE_PRIVATE int sqlite3PagerOpenWal(
  45582. Pager *pPager, /* Pager object */
  45583. int *pbOpen /* OUT: Set to true if call is a no-op */
  45584. ){
  45585. int rc = SQLITE_OK; /* Return code */
  45586. assert( assert_pager_state(pPager) );
  45587. assert( pPager->eState==PAGER_OPEN || pbOpen );
  45588. assert( pPager->eState==PAGER_READER || !pbOpen );
  45589. assert( pbOpen==0 || *pbOpen==0 );
  45590. assert( pbOpen!=0 || (!pPager->tempFile && !pPager->pWal) );
  45591. if( !pPager->tempFile && !pPager->pWal ){
  45592. if( !sqlite3PagerWalSupported(pPager) ) return SQLITE_CANTOPEN;
  45593. /* Close any rollback journal previously open */
  45594. sqlite3OsClose(pPager->jfd);
  45595. rc = pagerOpenWal(pPager);
  45596. if( rc==SQLITE_OK ){
  45597. pPager->journalMode = PAGER_JOURNALMODE_WAL;
  45598. pPager->eState = PAGER_OPEN;
  45599. }
  45600. }else{
  45601. *pbOpen = 1;
  45602. }
  45603. return rc;
  45604. }
  45605. /*
  45606. ** This function is called to close the connection to the log file prior
  45607. ** to switching from WAL to rollback mode.
  45608. **
  45609. ** Before closing the log file, this function attempts to take an
  45610. ** EXCLUSIVE lock on the database file. If this cannot be obtained, an
  45611. ** error (SQLITE_BUSY) is returned and the log connection is not closed.
  45612. ** If successful, the EXCLUSIVE lock is not released before returning.
  45613. */
  45614. SQLITE_PRIVATE int sqlite3PagerCloseWal(Pager *pPager){
  45615. int rc = SQLITE_OK;
  45616. assert( pPager->journalMode==PAGER_JOURNALMODE_WAL );
  45617. /* If the log file is not already open, but does exist in the file-system,
  45618. ** it may need to be checkpointed before the connection can switch to
  45619. ** rollback mode. Open it now so this can happen.
  45620. */
  45621. if( !pPager->pWal ){
  45622. int logexists = 0;
  45623. rc = pagerLockDb(pPager, SHARED_LOCK);
  45624. if( rc==SQLITE_OK ){
  45625. rc = sqlite3OsAccess(
  45626. pPager->pVfs, pPager->zWal, SQLITE_ACCESS_EXISTS, &logexists
  45627. );
  45628. }
  45629. if( rc==SQLITE_OK && logexists ){
  45630. rc = pagerOpenWal(pPager);
  45631. }
  45632. }
  45633. /* Checkpoint and close the log. Because an EXCLUSIVE lock is held on
  45634. ** the database file, the log and log-summary files will be deleted.
  45635. */
  45636. if( rc==SQLITE_OK && pPager->pWal ){
  45637. rc = pagerExclusiveLock(pPager);
  45638. if( rc==SQLITE_OK ){
  45639. rc = sqlite3WalClose(pPager->pWal, pPager->ckptSyncFlags,
  45640. pPager->pageSize, (u8*)pPager->pTmpSpace);
  45641. pPager->pWal = 0;
  45642. pagerFixMaplimit(pPager);
  45643. }
  45644. }
  45645. return rc;
  45646. }
  45647. #endif /* !SQLITE_OMIT_WAL */
  45648. #ifdef SQLITE_ENABLE_ZIPVFS
  45649. /*
  45650. ** A read-lock must be held on the pager when this function is called. If
  45651. ** the pager is in WAL mode and the WAL file currently contains one or more
  45652. ** frames, return the size in bytes of the page images stored within the
  45653. ** WAL frames. Otherwise, if this is not a WAL database or the WAL file
  45654. ** is empty, return 0.
  45655. */
  45656. SQLITE_PRIVATE int sqlite3PagerWalFramesize(Pager *pPager){
  45657. assert( pPager->eState>=PAGER_READER );
  45658. return sqlite3WalFramesize(pPager->pWal);
  45659. }
  45660. #endif
  45661. #endif /* SQLITE_OMIT_DISKIO */
  45662. /************** End of pager.c ***********************************************/
  45663. /************** Begin file wal.c *********************************************/
  45664. /*
  45665. ** 2010 February 1
  45666. **
  45667. ** The author disclaims copyright to this source code. In place of
  45668. ** a legal notice, here is a blessing:
  45669. **
  45670. ** May you do good and not evil.
  45671. ** May you find forgiveness for yourself and forgive others.
  45672. ** May you share freely, never taking more than you give.
  45673. **
  45674. *************************************************************************
  45675. **
  45676. ** This file contains the implementation of a write-ahead log (WAL) used in
  45677. ** "journal_mode=WAL" mode.
  45678. **
  45679. ** WRITE-AHEAD LOG (WAL) FILE FORMAT
  45680. **
  45681. ** A WAL file consists of a header followed by zero or more "frames".
  45682. ** Each frame records the revised content of a single page from the
  45683. ** database file. All changes to the database are recorded by writing
  45684. ** frames into the WAL. Transactions commit when a frame is written that
  45685. ** contains a commit marker. A single WAL can and usually does record
  45686. ** multiple transactions. Periodically, the content of the WAL is
  45687. ** transferred back into the database file in an operation called a
  45688. ** "checkpoint".
  45689. **
  45690. ** A single WAL file can be used multiple times. In other words, the
  45691. ** WAL can fill up with frames and then be checkpointed and then new
  45692. ** frames can overwrite the old ones. A WAL always grows from beginning
  45693. ** toward the end. Checksums and counters attached to each frame are
  45694. ** used to determine which frames within the WAL are valid and which
  45695. ** are leftovers from prior checkpoints.
  45696. **
  45697. ** The WAL header is 32 bytes in size and consists of the following eight
  45698. ** big-endian 32-bit unsigned integer values:
  45699. **
  45700. ** 0: Magic number. 0x377f0682 or 0x377f0683
  45701. ** 4: File format version. Currently 3007000
  45702. ** 8: Database page size. Example: 1024
  45703. ** 12: Checkpoint sequence number
  45704. ** 16: Salt-1, random integer incremented with each checkpoint
  45705. ** 20: Salt-2, a different random integer changing with each ckpt
  45706. ** 24: Checksum-1 (first part of checksum for first 24 bytes of header).
  45707. ** 28: Checksum-2 (second part of checksum for first 24 bytes of header).
  45708. **
  45709. ** Immediately following the wal-header are zero or more frames. Each
  45710. ** frame consists of a 24-byte frame-header followed by a <page-size> bytes
  45711. ** of page data. The frame-header is six big-endian 32-bit unsigned
  45712. ** integer values, as follows:
  45713. **
  45714. ** 0: Page number.
  45715. ** 4: For commit records, the size of the database image in pages
  45716. ** after the commit. For all other records, zero.
  45717. ** 8: Salt-1 (copied from the header)
  45718. ** 12: Salt-2 (copied from the header)
  45719. ** 16: Checksum-1.
  45720. ** 20: Checksum-2.
  45721. **
  45722. ** A frame is considered valid if and only if the following conditions are
  45723. ** true:
  45724. **
  45725. ** (1) The salt-1 and salt-2 values in the frame-header match
  45726. ** salt values in the wal-header
  45727. **
  45728. ** (2) The checksum values in the final 8 bytes of the frame-header
  45729. ** exactly match the checksum computed consecutively on the
  45730. ** WAL header and the first 8 bytes and the content of all frames
  45731. ** up to and including the current frame.
  45732. **
  45733. ** The checksum is computed using 32-bit big-endian integers if the
  45734. ** magic number in the first 4 bytes of the WAL is 0x377f0683 and it
  45735. ** is computed using little-endian if the magic number is 0x377f0682.
  45736. ** The checksum values are always stored in the frame header in a
  45737. ** big-endian format regardless of which byte order is used to compute
  45738. ** the checksum. The checksum is computed by interpreting the input as
  45739. ** an even number of unsigned 32-bit integers: x[0] through x[N]. The
  45740. ** algorithm used for the checksum is as follows:
  45741. **
  45742. ** for i from 0 to n-1 step 2:
  45743. ** s0 += x[i] + s1;
  45744. ** s1 += x[i+1] + s0;
  45745. ** endfor
  45746. **
  45747. ** Note that s0 and s1 are both weighted checksums using fibonacci weights
  45748. ** in reverse order (the largest fibonacci weight occurs on the first element
  45749. ** of the sequence being summed.) The s1 value spans all 32-bit
  45750. ** terms of the sequence whereas s0 omits the final term.
  45751. **
  45752. ** On a checkpoint, the WAL is first VFS.xSync-ed, then valid content of the
  45753. ** WAL is transferred into the database, then the database is VFS.xSync-ed.
  45754. ** The VFS.xSync operations serve as write barriers - all writes launched
  45755. ** before the xSync must complete before any write that launches after the
  45756. ** xSync begins.
  45757. **
  45758. ** After each checkpoint, the salt-1 value is incremented and the salt-2
  45759. ** value is randomized. This prevents old and new frames in the WAL from
  45760. ** being considered valid at the same time and being checkpointing together
  45761. ** following a crash.
  45762. **
  45763. ** READER ALGORITHM
  45764. **
  45765. ** To read a page from the database (call it page number P), a reader
  45766. ** first checks the WAL to see if it contains page P. If so, then the
  45767. ** last valid instance of page P that is a followed by a commit frame
  45768. ** or is a commit frame itself becomes the value read. If the WAL
  45769. ** contains no copies of page P that are valid and which are a commit
  45770. ** frame or are followed by a commit frame, then page P is read from
  45771. ** the database file.
  45772. **
  45773. ** To start a read transaction, the reader records the index of the last
  45774. ** valid frame in the WAL. The reader uses this recorded "mxFrame" value
  45775. ** for all subsequent read operations. New transactions can be appended
  45776. ** to the WAL, but as long as the reader uses its original mxFrame value
  45777. ** and ignores the newly appended content, it will see a consistent snapshot
  45778. ** of the database from a single point in time. This technique allows
  45779. ** multiple concurrent readers to view different versions of the database
  45780. ** content simultaneously.
  45781. **
  45782. ** The reader algorithm in the previous paragraphs works correctly, but
  45783. ** because frames for page P can appear anywhere within the WAL, the
  45784. ** reader has to scan the entire WAL looking for page P frames. If the
  45785. ** WAL is large (multiple megabytes is typical) that scan can be slow,
  45786. ** and read performance suffers. To overcome this problem, a separate
  45787. ** data structure called the wal-index is maintained to expedite the
  45788. ** search for frames of a particular page.
  45789. **
  45790. ** WAL-INDEX FORMAT
  45791. **
  45792. ** Conceptually, the wal-index is shared memory, though VFS implementations
  45793. ** might choose to implement the wal-index using a mmapped file. Because
  45794. ** the wal-index is shared memory, SQLite does not support journal_mode=WAL
  45795. ** on a network filesystem. All users of the database must be able to
  45796. ** share memory.
  45797. **
  45798. ** The wal-index is transient. After a crash, the wal-index can (and should
  45799. ** be) reconstructed from the original WAL file. In fact, the VFS is required
  45800. ** to either truncate or zero the header of the wal-index when the last
  45801. ** connection to it closes. Because the wal-index is transient, it can
  45802. ** use an architecture-specific format; it does not have to be cross-platform.
  45803. ** Hence, unlike the database and WAL file formats which store all values
  45804. ** as big endian, the wal-index can store multi-byte values in the native
  45805. ** byte order of the host computer.
  45806. **
  45807. ** The purpose of the wal-index is to answer this question quickly: Given
  45808. ** a page number P and a maximum frame index M, return the index of the
  45809. ** last frame in the wal before frame M for page P in the WAL, or return
  45810. ** NULL if there are no frames for page P in the WAL prior to M.
  45811. **
  45812. ** The wal-index consists of a header region, followed by an one or
  45813. ** more index blocks.
  45814. **
  45815. ** The wal-index header contains the total number of frames within the WAL
  45816. ** in the mxFrame field.
  45817. **
  45818. ** Each index block except for the first contains information on
  45819. ** HASHTABLE_NPAGE frames. The first index block contains information on
  45820. ** HASHTABLE_NPAGE_ONE frames. The values of HASHTABLE_NPAGE_ONE and
  45821. ** HASHTABLE_NPAGE are selected so that together the wal-index header and
  45822. ** first index block are the same size as all other index blocks in the
  45823. ** wal-index.
  45824. **
  45825. ** Each index block contains two sections, a page-mapping that contains the
  45826. ** database page number associated with each wal frame, and a hash-table
  45827. ** that allows readers to query an index block for a specific page number.
  45828. ** The page-mapping is an array of HASHTABLE_NPAGE (or HASHTABLE_NPAGE_ONE
  45829. ** for the first index block) 32-bit page numbers. The first entry in the
  45830. ** first index-block contains the database page number corresponding to the
  45831. ** first frame in the WAL file. The first entry in the second index block
  45832. ** in the WAL file corresponds to the (HASHTABLE_NPAGE_ONE+1)th frame in
  45833. ** the log, and so on.
  45834. **
  45835. ** The last index block in a wal-index usually contains less than the full
  45836. ** complement of HASHTABLE_NPAGE (or HASHTABLE_NPAGE_ONE) page-numbers,
  45837. ** depending on the contents of the WAL file. This does not change the
  45838. ** allocated size of the page-mapping array - the page-mapping array merely
  45839. ** contains unused entries.
  45840. **
  45841. ** Even without using the hash table, the last frame for page P
  45842. ** can be found by scanning the page-mapping sections of each index block
  45843. ** starting with the last index block and moving toward the first, and
  45844. ** within each index block, starting at the end and moving toward the
  45845. ** beginning. The first entry that equals P corresponds to the frame
  45846. ** holding the content for that page.
  45847. **
  45848. ** The hash table consists of HASHTABLE_NSLOT 16-bit unsigned integers.
  45849. ** HASHTABLE_NSLOT = 2*HASHTABLE_NPAGE, and there is one entry in the
  45850. ** hash table for each page number in the mapping section, so the hash
  45851. ** table is never more than half full. The expected number of collisions
  45852. ** prior to finding a match is 1. Each entry of the hash table is an
  45853. ** 1-based index of an entry in the mapping section of the same
  45854. ** index block. Let K be the 1-based index of the largest entry in
  45855. ** the mapping section. (For index blocks other than the last, K will
  45856. ** always be exactly HASHTABLE_NPAGE (4096) and for the last index block
  45857. ** K will be (mxFrame%HASHTABLE_NPAGE).) Unused slots of the hash table
  45858. ** contain a value of 0.
  45859. **
  45860. ** To look for page P in the hash table, first compute a hash iKey on
  45861. ** P as follows:
  45862. **
  45863. ** iKey = (P * 383) % HASHTABLE_NSLOT
  45864. **
  45865. ** Then start scanning entries of the hash table, starting with iKey
  45866. ** (wrapping around to the beginning when the end of the hash table is
  45867. ** reached) until an unused hash slot is found. Let the first unused slot
  45868. ** be at index iUnused. (iUnused might be less than iKey if there was
  45869. ** wrap-around.) Because the hash table is never more than half full,
  45870. ** the search is guaranteed to eventually hit an unused entry. Let
  45871. ** iMax be the value between iKey and iUnused, closest to iUnused,
  45872. ** where aHash[iMax]==P. If there is no iMax entry (if there exists
  45873. ** no hash slot such that aHash[i]==p) then page P is not in the
  45874. ** current index block. Otherwise the iMax-th mapping entry of the
  45875. ** current index block corresponds to the last entry that references
  45876. ** page P.
  45877. **
  45878. ** A hash search begins with the last index block and moves toward the
  45879. ** first index block, looking for entries corresponding to page P. On
  45880. ** average, only two or three slots in each index block need to be
  45881. ** examined in order to either find the last entry for page P, or to
  45882. ** establish that no such entry exists in the block. Each index block
  45883. ** holds over 4000 entries. So two or three index blocks are sufficient
  45884. ** to cover a typical 10 megabyte WAL file, assuming 1K pages. 8 or 10
  45885. ** comparisons (on average) suffice to either locate a frame in the
  45886. ** WAL or to establish that the frame does not exist in the WAL. This
  45887. ** is much faster than scanning the entire 10MB WAL.
  45888. **
  45889. ** Note that entries are added in order of increasing K. Hence, one
  45890. ** reader might be using some value K0 and a second reader that started
  45891. ** at a later time (after additional transactions were added to the WAL
  45892. ** and to the wal-index) might be using a different value K1, where K1>K0.
  45893. ** Both readers can use the same hash table and mapping section to get
  45894. ** the correct result. There may be entries in the hash table with
  45895. ** K>K0 but to the first reader, those entries will appear to be unused
  45896. ** slots in the hash table and so the first reader will get an answer as
  45897. ** if no values greater than K0 had ever been inserted into the hash table
  45898. ** in the first place - which is what reader one wants. Meanwhile, the
  45899. ** second reader using K1 will see additional values that were inserted
  45900. ** later, which is exactly what reader two wants.
  45901. **
  45902. ** When a rollback occurs, the value of K is decreased. Hash table entries
  45903. ** that correspond to frames greater than the new K value are removed
  45904. ** from the hash table at this point.
  45905. */
  45906. #ifndef SQLITE_OMIT_WAL
  45907. /*
  45908. ** Trace output macros
  45909. */
  45910. #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
  45911. SQLITE_PRIVATE int sqlite3WalTrace = 0;
  45912. # define WALTRACE(X) if(sqlite3WalTrace) sqlite3DebugPrintf X
  45913. #else
  45914. # define WALTRACE(X)
  45915. #endif
  45916. /*
  45917. ** The maximum (and only) versions of the wal and wal-index formats
  45918. ** that may be interpreted by this version of SQLite.
  45919. **
  45920. ** If a client begins recovering a WAL file and finds that (a) the checksum
  45921. ** values in the wal-header are correct and (b) the version field is not
  45922. ** WAL_MAX_VERSION, recovery fails and SQLite returns SQLITE_CANTOPEN.
  45923. **
  45924. ** Similarly, if a client successfully reads a wal-index header (i.e. the
  45925. ** checksum test is successful) and finds that the version field is not
  45926. ** WALINDEX_MAX_VERSION, then no read-transaction is opened and SQLite
  45927. ** returns SQLITE_CANTOPEN.
  45928. */
  45929. #define WAL_MAX_VERSION 3007000
  45930. #define WALINDEX_MAX_VERSION 3007000
  45931. /*
  45932. ** Indices of various locking bytes. WAL_NREADER is the number
  45933. ** of available reader locks and should be at least 3.
  45934. */
  45935. #define WAL_WRITE_LOCK 0
  45936. #define WAL_ALL_BUT_WRITE 1
  45937. #define WAL_CKPT_LOCK 1
  45938. #define WAL_RECOVER_LOCK 2
  45939. #define WAL_READ_LOCK(I) (3+(I))
  45940. #define WAL_NREADER (SQLITE_SHM_NLOCK-3)
  45941. /* Object declarations */
  45942. typedef struct WalIndexHdr WalIndexHdr;
  45943. typedef struct WalIterator WalIterator;
  45944. typedef struct WalCkptInfo WalCkptInfo;
  45945. /*
  45946. ** The following object holds a copy of the wal-index header content.
  45947. **
  45948. ** The actual header in the wal-index consists of two copies of this
  45949. ** object.
  45950. **
  45951. ** The szPage value can be any power of 2 between 512 and 32768, inclusive.
  45952. ** Or it can be 1 to represent a 65536-byte page. The latter case was
  45953. ** added in 3.7.1 when support for 64K pages was added.
  45954. */
  45955. struct WalIndexHdr {
  45956. u32 iVersion; /* Wal-index version */
  45957. u32 unused; /* Unused (padding) field */
  45958. u32 iChange; /* Counter incremented each transaction */
  45959. u8 isInit; /* 1 when initialized */
  45960. u8 bigEndCksum; /* True if checksums in WAL are big-endian */
  45961. u16 szPage; /* Database page size in bytes. 1==64K */
  45962. u32 mxFrame; /* Index of last valid frame in the WAL */
  45963. u32 nPage; /* Size of database in pages */
  45964. u32 aFrameCksum[2]; /* Checksum of last frame in log */
  45965. u32 aSalt[2]; /* Two salt values copied from WAL header */
  45966. u32 aCksum[2]; /* Checksum over all prior fields */
  45967. };
  45968. /*
  45969. ** A copy of the following object occurs in the wal-index immediately
  45970. ** following the second copy of the WalIndexHdr. This object stores
  45971. ** information used by checkpoint.
  45972. **
  45973. ** nBackfill is the number of frames in the WAL that have been written
  45974. ** back into the database. (We call the act of moving content from WAL to
  45975. ** database "backfilling".) The nBackfill number is never greater than
  45976. ** WalIndexHdr.mxFrame. nBackfill can only be increased by threads
  45977. ** holding the WAL_CKPT_LOCK lock (which includes a recovery thread).
  45978. ** However, a WAL_WRITE_LOCK thread can move the value of nBackfill from
  45979. ** mxFrame back to zero when the WAL is reset.
  45980. **
  45981. ** There is one entry in aReadMark[] for each reader lock. If a reader
  45982. ** holds read-lock K, then the value in aReadMark[K] is no greater than
  45983. ** the mxFrame for that reader. The value READMARK_NOT_USED (0xffffffff)
  45984. ** for any aReadMark[] means that entry is unused. aReadMark[0] is
  45985. ** a special case; its value is never used and it exists as a place-holder
  45986. ** to avoid having to offset aReadMark[] indexs by one. Readers holding
  45987. ** WAL_READ_LOCK(0) always ignore the entire WAL and read all content
  45988. ** directly from the database.
  45989. **
  45990. ** The value of aReadMark[K] may only be changed by a thread that
  45991. ** is holding an exclusive lock on WAL_READ_LOCK(K). Thus, the value of
  45992. ** aReadMark[K] cannot changed while there is a reader is using that mark
  45993. ** since the reader will be holding a shared lock on WAL_READ_LOCK(K).
  45994. **
  45995. ** The checkpointer may only transfer frames from WAL to database where
  45996. ** the frame numbers are less than or equal to every aReadMark[] that is
  45997. ** in use (that is, every aReadMark[j] for which there is a corresponding
  45998. ** WAL_READ_LOCK(j)). New readers (usually) pick the aReadMark[] with the
  45999. ** largest value and will increase an unused aReadMark[] to mxFrame if there
  46000. ** is not already an aReadMark[] equal to mxFrame. The exception to the
  46001. ** previous sentence is when nBackfill equals mxFrame (meaning that everything
  46002. ** in the WAL has been backfilled into the database) then new readers
  46003. ** will choose aReadMark[0] which has value 0 and hence such reader will
  46004. ** get all their all content directly from the database file and ignore
  46005. ** the WAL.
  46006. **
  46007. ** Writers normally append new frames to the end of the WAL. However,
  46008. ** if nBackfill equals mxFrame (meaning that all WAL content has been
  46009. ** written back into the database) and if no readers are using the WAL
  46010. ** (in other words, if there are no WAL_READ_LOCK(i) where i>0) then
  46011. ** the writer will first "reset" the WAL back to the beginning and start
  46012. ** writing new content beginning at frame 1.
  46013. **
  46014. ** We assume that 32-bit loads are atomic and so no locks are needed in
  46015. ** order to read from any aReadMark[] entries.
  46016. */
  46017. struct WalCkptInfo {
  46018. u32 nBackfill; /* Number of WAL frames backfilled into DB */
  46019. u32 aReadMark[WAL_NREADER]; /* Reader marks */
  46020. };
  46021. #define READMARK_NOT_USED 0xffffffff
  46022. /* A block of WALINDEX_LOCK_RESERVED bytes beginning at
  46023. ** WALINDEX_LOCK_OFFSET is reserved for locks. Since some systems
  46024. ** only support mandatory file-locks, we do not read or write data
  46025. ** from the region of the file on which locks are applied.
  46026. */
  46027. #define WALINDEX_LOCK_OFFSET (sizeof(WalIndexHdr)*2 + sizeof(WalCkptInfo))
  46028. #define WALINDEX_LOCK_RESERVED 16
  46029. #define WALINDEX_HDR_SIZE (WALINDEX_LOCK_OFFSET+WALINDEX_LOCK_RESERVED)
  46030. /* Size of header before each frame in wal */
  46031. #define WAL_FRAME_HDRSIZE 24
  46032. /* Size of write ahead log header, including checksum. */
  46033. /* #define WAL_HDRSIZE 24 */
  46034. #define WAL_HDRSIZE 32
  46035. /* WAL magic value. Either this value, or the same value with the least
  46036. ** significant bit also set (WAL_MAGIC | 0x00000001) is stored in 32-bit
  46037. ** big-endian format in the first 4 bytes of a WAL file.
  46038. **
  46039. ** If the LSB is set, then the checksums for each frame within the WAL
  46040. ** file are calculated by treating all data as an array of 32-bit
  46041. ** big-endian words. Otherwise, they are calculated by interpreting
  46042. ** all data as 32-bit little-endian words.
  46043. */
  46044. #define WAL_MAGIC 0x377f0682
  46045. /*
  46046. ** Return the offset of frame iFrame in the write-ahead log file,
  46047. ** assuming a database page size of szPage bytes. The offset returned
  46048. ** is to the start of the write-ahead log frame-header.
  46049. */
  46050. #define walFrameOffset(iFrame, szPage) ( \
  46051. WAL_HDRSIZE + ((iFrame)-1)*(i64)((szPage)+WAL_FRAME_HDRSIZE) \
  46052. )
  46053. /*
  46054. ** An open write-ahead log file is represented by an instance of the
  46055. ** following object.
  46056. */
  46057. struct Wal {
  46058. sqlite3_vfs *pVfs; /* The VFS used to create pDbFd */
  46059. sqlite3_file *pDbFd; /* File handle for the database file */
  46060. sqlite3_file *pWalFd; /* File handle for WAL file */
  46061. u32 iCallback; /* Value to pass to log callback (or 0) */
  46062. i64 mxWalSize; /* Truncate WAL to this size upon reset */
  46063. int nWiData; /* Size of array apWiData */
  46064. int szFirstBlock; /* Size of first block written to WAL file */
  46065. volatile u32 **apWiData; /* Pointer to wal-index content in memory */
  46066. u32 szPage; /* Database page size */
  46067. i16 readLock; /* Which read lock is being held. -1 for none */
  46068. u8 syncFlags; /* Flags to use to sync header writes */
  46069. u8 exclusiveMode; /* Non-zero if connection is in exclusive mode */
  46070. u8 writeLock; /* True if in a write transaction */
  46071. u8 ckptLock; /* True if holding a checkpoint lock */
  46072. u8 readOnly; /* WAL_RDWR, WAL_RDONLY, or WAL_SHM_RDONLY */
  46073. u8 truncateOnCommit; /* True to truncate WAL file on commit */
  46074. u8 syncHeader; /* Fsync the WAL header if true */
  46075. u8 padToSectorBoundary; /* Pad transactions out to the next sector */
  46076. WalIndexHdr hdr; /* Wal-index header for current transaction */
  46077. const char *zWalName; /* Name of WAL file */
  46078. u32 nCkpt; /* Checkpoint sequence counter in the wal-header */
  46079. #ifdef SQLITE_DEBUG
  46080. u8 lockError; /* True if a locking error has occurred */
  46081. #endif
  46082. };
  46083. /*
  46084. ** Candidate values for Wal.exclusiveMode.
  46085. */
  46086. #define WAL_NORMAL_MODE 0
  46087. #define WAL_EXCLUSIVE_MODE 1
  46088. #define WAL_HEAPMEMORY_MODE 2
  46089. /*
  46090. ** Possible values for WAL.readOnly
  46091. */
  46092. #define WAL_RDWR 0 /* Normal read/write connection */
  46093. #define WAL_RDONLY 1 /* The WAL file is readonly */
  46094. #define WAL_SHM_RDONLY 2 /* The SHM file is readonly */
  46095. /*
  46096. ** Each page of the wal-index mapping contains a hash-table made up of
  46097. ** an array of HASHTABLE_NSLOT elements of the following type.
  46098. */
  46099. typedef u16 ht_slot;
  46100. /*
  46101. ** This structure is used to implement an iterator that loops through
  46102. ** all frames in the WAL in database page order. Where two or more frames
  46103. ** correspond to the same database page, the iterator visits only the
  46104. ** frame most recently written to the WAL (in other words, the frame with
  46105. ** the largest index).
  46106. **
  46107. ** The internals of this structure are only accessed by:
  46108. **
  46109. ** walIteratorInit() - Create a new iterator,
  46110. ** walIteratorNext() - Step an iterator,
  46111. ** walIteratorFree() - Free an iterator.
  46112. **
  46113. ** This functionality is used by the checkpoint code (see walCheckpoint()).
  46114. */
  46115. struct WalIterator {
  46116. int iPrior; /* Last result returned from the iterator */
  46117. int nSegment; /* Number of entries in aSegment[] */
  46118. struct WalSegment {
  46119. int iNext; /* Next slot in aIndex[] not yet returned */
  46120. ht_slot *aIndex; /* i0, i1, i2... such that aPgno[iN] ascend */
  46121. u32 *aPgno; /* Array of page numbers. */
  46122. int nEntry; /* Nr. of entries in aPgno[] and aIndex[] */
  46123. int iZero; /* Frame number associated with aPgno[0] */
  46124. } aSegment[1]; /* One for every 32KB page in the wal-index */
  46125. };
  46126. /*
  46127. ** Define the parameters of the hash tables in the wal-index file. There
  46128. ** is a hash-table following every HASHTABLE_NPAGE page numbers in the
  46129. ** wal-index.
  46130. **
  46131. ** Changing any of these constants will alter the wal-index format and
  46132. ** create incompatibilities.
  46133. */
  46134. #define HASHTABLE_NPAGE 4096 /* Must be power of 2 */
  46135. #define HASHTABLE_HASH_1 383 /* Should be prime */
  46136. #define HASHTABLE_NSLOT (HASHTABLE_NPAGE*2) /* Must be a power of 2 */
  46137. /*
  46138. ** The block of page numbers associated with the first hash-table in a
  46139. ** wal-index is smaller than usual. This is so that there is a complete
  46140. ** hash-table on each aligned 32KB page of the wal-index.
  46141. */
  46142. #define HASHTABLE_NPAGE_ONE (HASHTABLE_NPAGE - (WALINDEX_HDR_SIZE/sizeof(u32)))
  46143. /* The wal-index is divided into pages of WALINDEX_PGSZ bytes each. */
  46144. #define WALINDEX_PGSZ ( \
  46145. sizeof(ht_slot)*HASHTABLE_NSLOT + HASHTABLE_NPAGE*sizeof(u32) \
  46146. )
  46147. /*
  46148. ** Obtain a pointer to the iPage'th page of the wal-index. The wal-index
  46149. ** is broken into pages of WALINDEX_PGSZ bytes. Wal-index pages are
  46150. ** numbered from zero.
  46151. **
  46152. ** If this call is successful, *ppPage is set to point to the wal-index
  46153. ** page and SQLITE_OK is returned. If an error (an OOM or VFS error) occurs,
  46154. ** then an SQLite error code is returned and *ppPage is set to 0.
  46155. */
  46156. static int walIndexPage(Wal *pWal, int iPage, volatile u32 **ppPage){
  46157. int rc = SQLITE_OK;
  46158. /* Enlarge the pWal->apWiData[] array if required */
  46159. if( pWal->nWiData<=iPage ){
  46160. int nByte = sizeof(u32*)*(iPage+1);
  46161. volatile u32 **apNew;
  46162. apNew = (volatile u32 **)sqlite3_realloc64((void *)pWal->apWiData, nByte);
  46163. if( !apNew ){
  46164. *ppPage = 0;
  46165. return SQLITE_NOMEM;
  46166. }
  46167. memset((void*)&apNew[pWal->nWiData], 0,
  46168. sizeof(u32*)*(iPage+1-pWal->nWiData));
  46169. pWal->apWiData = apNew;
  46170. pWal->nWiData = iPage+1;
  46171. }
  46172. /* Request a pointer to the required page from the VFS */
  46173. if( pWal->apWiData[iPage]==0 ){
  46174. if( pWal->exclusiveMode==WAL_HEAPMEMORY_MODE ){
  46175. pWal->apWiData[iPage] = (u32 volatile *)sqlite3MallocZero(WALINDEX_PGSZ);
  46176. if( !pWal->apWiData[iPage] ) rc = SQLITE_NOMEM;
  46177. }else{
  46178. rc = sqlite3OsShmMap(pWal->pDbFd, iPage, WALINDEX_PGSZ,
  46179. pWal->writeLock, (void volatile **)&pWal->apWiData[iPage]
  46180. );
  46181. if( rc==SQLITE_READONLY ){
  46182. pWal->readOnly |= WAL_SHM_RDONLY;
  46183. rc = SQLITE_OK;
  46184. }
  46185. }
  46186. }
  46187. *ppPage = pWal->apWiData[iPage];
  46188. assert( iPage==0 || *ppPage || rc!=SQLITE_OK );
  46189. return rc;
  46190. }
  46191. /*
  46192. ** Return a pointer to the WalCkptInfo structure in the wal-index.
  46193. */
  46194. static volatile WalCkptInfo *walCkptInfo(Wal *pWal){
  46195. assert( pWal->nWiData>0 && pWal->apWiData[0] );
  46196. return (volatile WalCkptInfo*)&(pWal->apWiData[0][sizeof(WalIndexHdr)/2]);
  46197. }
  46198. /*
  46199. ** Return a pointer to the WalIndexHdr structure in the wal-index.
  46200. */
  46201. static volatile WalIndexHdr *walIndexHdr(Wal *pWal){
  46202. assert( pWal->nWiData>0 && pWal->apWiData[0] );
  46203. return (volatile WalIndexHdr*)pWal->apWiData[0];
  46204. }
  46205. /*
  46206. ** The argument to this macro must be of type u32. On a little-endian
  46207. ** architecture, it returns the u32 value that results from interpreting
  46208. ** the 4 bytes as a big-endian value. On a big-endian architecture, it
  46209. ** returns the value that would be produced by interpreting the 4 bytes
  46210. ** of the input value as a little-endian integer.
  46211. */
  46212. #define BYTESWAP32(x) ( \
  46213. (((x)&0x000000FF)<<24) + (((x)&0x0000FF00)<<8) \
  46214. + (((x)&0x00FF0000)>>8) + (((x)&0xFF000000)>>24) \
  46215. )
  46216. /*
  46217. ** Generate or extend an 8 byte checksum based on the data in
  46218. ** array aByte[] and the initial values of aIn[0] and aIn[1] (or
  46219. ** initial values of 0 and 0 if aIn==NULL).
  46220. **
  46221. ** The checksum is written back into aOut[] before returning.
  46222. **
  46223. ** nByte must be a positive multiple of 8.
  46224. */
  46225. static void walChecksumBytes(
  46226. int nativeCksum, /* True for native byte-order, false for non-native */
  46227. u8 *a, /* Content to be checksummed */
  46228. int nByte, /* Bytes of content in a[]. Must be a multiple of 8. */
  46229. const u32 *aIn, /* Initial checksum value input */
  46230. u32 *aOut /* OUT: Final checksum value output */
  46231. ){
  46232. u32 s1, s2;
  46233. u32 *aData = (u32 *)a;
  46234. u32 *aEnd = (u32 *)&a[nByte];
  46235. if( aIn ){
  46236. s1 = aIn[0];
  46237. s2 = aIn[1];
  46238. }else{
  46239. s1 = s2 = 0;
  46240. }
  46241. assert( nByte>=8 );
  46242. assert( (nByte&0x00000007)==0 );
  46243. if( nativeCksum ){
  46244. do {
  46245. s1 += *aData++ + s2;
  46246. s2 += *aData++ + s1;
  46247. }while( aData<aEnd );
  46248. }else{
  46249. do {
  46250. s1 += BYTESWAP32(aData[0]) + s2;
  46251. s2 += BYTESWAP32(aData[1]) + s1;
  46252. aData += 2;
  46253. }while( aData<aEnd );
  46254. }
  46255. aOut[0] = s1;
  46256. aOut[1] = s2;
  46257. }
  46258. static void walShmBarrier(Wal *pWal){
  46259. if( pWal->exclusiveMode!=WAL_HEAPMEMORY_MODE ){
  46260. sqlite3OsShmBarrier(pWal->pDbFd);
  46261. }
  46262. }
  46263. /*
  46264. ** Write the header information in pWal->hdr into the wal-index.
  46265. **
  46266. ** The checksum on pWal->hdr is updated before it is written.
  46267. */
  46268. static void walIndexWriteHdr(Wal *pWal){
  46269. volatile WalIndexHdr *aHdr = walIndexHdr(pWal);
  46270. const int nCksum = offsetof(WalIndexHdr, aCksum);
  46271. assert( pWal->writeLock );
  46272. pWal->hdr.isInit = 1;
  46273. pWal->hdr.iVersion = WALINDEX_MAX_VERSION;
  46274. walChecksumBytes(1, (u8*)&pWal->hdr, nCksum, 0, pWal->hdr.aCksum);
  46275. memcpy((void *)&aHdr[1], (void *)&pWal->hdr, sizeof(WalIndexHdr));
  46276. walShmBarrier(pWal);
  46277. memcpy((void *)&aHdr[0], (void *)&pWal->hdr, sizeof(WalIndexHdr));
  46278. }
  46279. /*
  46280. ** This function encodes a single frame header and writes it to a buffer
  46281. ** supplied by the caller. A frame-header is made up of a series of
  46282. ** 4-byte big-endian integers, as follows:
  46283. **
  46284. ** 0: Page number.
  46285. ** 4: For commit records, the size of the database image in pages
  46286. ** after the commit. For all other records, zero.
  46287. ** 8: Salt-1 (copied from the wal-header)
  46288. ** 12: Salt-2 (copied from the wal-header)
  46289. ** 16: Checksum-1.
  46290. ** 20: Checksum-2.
  46291. */
  46292. static void walEncodeFrame(
  46293. Wal *pWal, /* The write-ahead log */
  46294. u32 iPage, /* Database page number for frame */
  46295. u32 nTruncate, /* New db size (or 0 for non-commit frames) */
  46296. u8 *aData, /* Pointer to page data */
  46297. u8 *aFrame /* OUT: Write encoded frame here */
  46298. ){
  46299. int nativeCksum; /* True for native byte-order checksums */
  46300. u32 *aCksum = pWal->hdr.aFrameCksum;
  46301. assert( WAL_FRAME_HDRSIZE==24 );
  46302. sqlite3Put4byte(&aFrame[0], iPage);
  46303. sqlite3Put4byte(&aFrame[4], nTruncate);
  46304. memcpy(&aFrame[8], pWal->hdr.aSalt, 8);
  46305. nativeCksum = (pWal->hdr.bigEndCksum==SQLITE_BIGENDIAN);
  46306. walChecksumBytes(nativeCksum, aFrame, 8, aCksum, aCksum);
  46307. walChecksumBytes(nativeCksum, aData, pWal->szPage, aCksum, aCksum);
  46308. sqlite3Put4byte(&aFrame[16], aCksum[0]);
  46309. sqlite3Put4byte(&aFrame[20], aCksum[1]);
  46310. }
  46311. /*
  46312. ** Check to see if the frame with header in aFrame[] and content
  46313. ** in aData[] is valid. If it is a valid frame, fill *piPage and
  46314. ** *pnTruncate and return true. Return if the frame is not valid.
  46315. */
  46316. static int walDecodeFrame(
  46317. Wal *pWal, /* The write-ahead log */
  46318. u32 *piPage, /* OUT: Database page number for frame */
  46319. u32 *pnTruncate, /* OUT: New db size (or 0 if not commit) */
  46320. u8 *aData, /* Pointer to page data (for checksum) */
  46321. u8 *aFrame /* Frame data */
  46322. ){
  46323. int nativeCksum; /* True for native byte-order checksums */
  46324. u32 *aCksum = pWal->hdr.aFrameCksum;
  46325. u32 pgno; /* Page number of the frame */
  46326. assert( WAL_FRAME_HDRSIZE==24 );
  46327. /* A frame is only valid if the salt values in the frame-header
  46328. ** match the salt values in the wal-header.
  46329. */
  46330. if( memcmp(&pWal->hdr.aSalt, &aFrame[8], 8)!=0 ){
  46331. return 0;
  46332. }
  46333. /* A frame is only valid if the page number is creater than zero.
  46334. */
  46335. pgno = sqlite3Get4byte(&aFrame[0]);
  46336. if( pgno==0 ){
  46337. return 0;
  46338. }
  46339. /* A frame is only valid if a checksum of the WAL header,
  46340. ** all prior frams, the first 16 bytes of this frame-header,
  46341. ** and the frame-data matches the checksum in the last 8
  46342. ** bytes of this frame-header.
  46343. */
  46344. nativeCksum = (pWal->hdr.bigEndCksum==SQLITE_BIGENDIAN);
  46345. walChecksumBytes(nativeCksum, aFrame, 8, aCksum, aCksum);
  46346. walChecksumBytes(nativeCksum, aData, pWal->szPage, aCksum, aCksum);
  46347. if( aCksum[0]!=sqlite3Get4byte(&aFrame[16])
  46348. || aCksum[1]!=sqlite3Get4byte(&aFrame[20])
  46349. ){
  46350. /* Checksum failed. */
  46351. return 0;
  46352. }
  46353. /* If we reach this point, the frame is valid. Return the page number
  46354. ** and the new database size.
  46355. */
  46356. *piPage = pgno;
  46357. *pnTruncate = sqlite3Get4byte(&aFrame[4]);
  46358. return 1;
  46359. }
  46360. #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
  46361. /*
  46362. ** Names of locks. This routine is used to provide debugging output and is not
  46363. ** a part of an ordinary build.
  46364. */
  46365. static const char *walLockName(int lockIdx){
  46366. if( lockIdx==WAL_WRITE_LOCK ){
  46367. return "WRITE-LOCK";
  46368. }else if( lockIdx==WAL_CKPT_LOCK ){
  46369. return "CKPT-LOCK";
  46370. }else if( lockIdx==WAL_RECOVER_LOCK ){
  46371. return "RECOVER-LOCK";
  46372. }else{
  46373. static char zName[15];
  46374. sqlite3_snprintf(sizeof(zName), zName, "READ-LOCK[%d]",
  46375. lockIdx-WAL_READ_LOCK(0));
  46376. return zName;
  46377. }
  46378. }
  46379. #endif /*defined(SQLITE_TEST) || defined(SQLITE_DEBUG) */
  46380. /*
  46381. ** Set or release locks on the WAL. Locks are either shared or exclusive.
  46382. ** A lock cannot be moved directly between shared and exclusive - it must go
  46383. ** through the unlocked state first.
  46384. **
  46385. ** In locking_mode=EXCLUSIVE, all of these routines become no-ops.
  46386. */
  46387. static int walLockShared(Wal *pWal, int lockIdx){
  46388. int rc;
  46389. if( pWal->exclusiveMode ) return SQLITE_OK;
  46390. rc = sqlite3OsShmLock(pWal->pDbFd, lockIdx, 1,
  46391. SQLITE_SHM_LOCK | SQLITE_SHM_SHARED);
  46392. WALTRACE(("WAL%p: acquire SHARED-%s %s\n", pWal,
  46393. walLockName(lockIdx), rc ? "failed" : "ok"));
  46394. VVA_ONLY( pWal->lockError = (u8)(rc!=SQLITE_OK && rc!=SQLITE_BUSY); )
  46395. return rc;
  46396. }
  46397. static void walUnlockShared(Wal *pWal, int lockIdx){
  46398. if( pWal->exclusiveMode ) return;
  46399. (void)sqlite3OsShmLock(pWal->pDbFd, lockIdx, 1,
  46400. SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED);
  46401. WALTRACE(("WAL%p: release SHARED-%s\n", pWal, walLockName(lockIdx)));
  46402. }
  46403. static int walLockExclusive(Wal *pWal, int lockIdx, int n, int fBlock){
  46404. int rc;
  46405. if( pWal->exclusiveMode ) return SQLITE_OK;
  46406. if( fBlock ) sqlite3OsFileControl(pWal->pDbFd, SQLITE_FCNTL_WAL_BLOCK, 0);
  46407. rc = sqlite3OsShmLock(pWal->pDbFd, lockIdx, n,
  46408. SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE);
  46409. WALTRACE(("WAL%p: acquire EXCLUSIVE-%s cnt=%d %s\n", pWal,
  46410. walLockName(lockIdx), n, rc ? "failed" : "ok"));
  46411. VVA_ONLY( pWal->lockError = (u8)(rc!=SQLITE_OK && rc!=SQLITE_BUSY); )
  46412. return rc;
  46413. }
  46414. static void walUnlockExclusive(Wal *pWal, int lockIdx, int n){
  46415. if( pWal->exclusiveMode ) return;
  46416. (void)sqlite3OsShmLock(pWal->pDbFd, lockIdx, n,
  46417. SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE);
  46418. WALTRACE(("WAL%p: release EXCLUSIVE-%s cnt=%d\n", pWal,
  46419. walLockName(lockIdx), n));
  46420. }
  46421. /*
  46422. ** Compute a hash on a page number. The resulting hash value must land
  46423. ** between 0 and (HASHTABLE_NSLOT-1). The walHashNext() function advances
  46424. ** the hash to the next value in the event of a collision.
  46425. */
  46426. static int walHash(u32 iPage){
  46427. assert( iPage>0 );
  46428. assert( (HASHTABLE_NSLOT & (HASHTABLE_NSLOT-1))==0 );
  46429. return (iPage*HASHTABLE_HASH_1) & (HASHTABLE_NSLOT-1);
  46430. }
  46431. static int walNextHash(int iPriorHash){
  46432. return (iPriorHash+1)&(HASHTABLE_NSLOT-1);
  46433. }
  46434. /*
  46435. ** Return pointers to the hash table and page number array stored on
  46436. ** page iHash of the wal-index. The wal-index is broken into 32KB pages
  46437. ** numbered starting from 0.
  46438. **
  46439. ** Set output variable *paHash to point to the start of the hash table
  46440. ** in the wal-index file. Set *piZero to one less than the frame
  46441. ** number of the first frame indexed by this hash table. If a
  46442. ** slot in the hash table is set to N, it refers to frame number
  46443. ** (*piZero+N) in the log.
  46444. **
  46445. ** Finally, set *paPgno so that *paPgno[1] is the page number of the
  46446. ** first frame indexed by the hash table, frame (*piZero+1).
  46447. */
  46448. static int walHashGet(
  46449. Wal *pWal, /* WAL handle */
  46450. int iHash, /* Find the iHash'th table */
  46451. volatile ht_slot **paHash, /* OUT: Pointer to hash index */
  46452. volatile u32 **paPgno, /* OUT: Pointer to page number array */
  46453. u32 *piZero /* OUT: Frame associated with *paPgno[0] */
  46454. ){
  46455. int rc; /* Return code */
  46456. volatile u32 *aPgno;
  46457. rc = walIndexPage(pWal, iHash, &aPgno);
  46458. assert( rc==SQLITE_OK || iHash>0 );
  46459. if( rc==SQLITE_OK ){
  46460. u32 iZero;
  46461. volatile ht_slot *aHash;
  46462. aHash = (volatile ht_slot *)&aPgno[HASHTABLE_NPAGE];
  46463. if( iHash==0 ){
  46464. aPgno = &aPgno[WALINDEX_HDR_SIZE/sizeof(u32)];
  46465. iZero = 0;
  46466. }else{
  46467. iZero = HASHTABLE_NPAGE_ONE + (iHash-1)*HASHTABLE_NPAGE;
  46468. }
  46469. *paPgno = &aPgno[-1];
  46470. *paHash = aHash;
  46471. *piZero = iZero;
  46472. }
  46473. return rc;
  46474. }
  46475. /*
  46476. ** Return the number of the wal-index page that contains the hash-table
  46477. ** and page-number array that contain entries corresponding to WAL frame
  46478. ** iFrame. The wal-index is broken up into 32KB pages. Wal-index pages
  46479. ** are numbered starting from 0.
  46480. */
  46481. static int walFramePage(u32 iFrame){
  46482. int iHash = (iFrame+HASHTABLE_NPAGE-HASHTABLE_NPAGE_ONE-1) / HASHTABLE_NPAGE;
  46483. assert( (iHash==0 || iFrame>HASHTABLE_NPAGE_ONE)
  46484. && (iHash>=1 || iFrame<=HASHTABLE_NPAGE_ONE)
  46485. && (iHash<=1 || iFrame>(HASHTABLE_NPAGE_ONE+HASHTABLE_NPAGE))
  46486. && (iHash>=2 || iFrame<=HASHTABLE_NPAGE_ONE+HASHTABLE_NPAGE)
  46487. && (iHash<=2 || iFrame>(HASHTABLE_NPAGE_ONE+2*HASHTABLE_NPAGE))
  46488. );
  46489. return iHash;
  46490. }
  46491. /*
  46492. ** Return the page number associated with frame iFrame in this WAL.
  46493. */
  46494. static u32 walFramePgno(Wal *pWal, u32 iFrame){
  46495. int iHash = walFramePage(iFrame);
  46496. if( iHash==0 ){
  46497. return pWal->apWiData[0][WALINDEX_HDR_SIZE/sizeof(u32) + iFrame - 1];
  46498. }
  46499. return pWal->apWiData[iHash][(iFrame-1-HASHTABLE_NPAGE_ONE)%HASHTABLE_NPAGE];
  46500. }
  46501. /*
  46502. ** Remove entries from the hash table that point to WAL slots greater
  46503. ** than pWal->hdr.mxFrame.
  46504. **
  46505. ** This function is called whenever pWal->hdr.mxFrame is decreased due
  46506. ** to a rollback or savepoint.
  46507. **
  46508. ** At most only the hash table containing pWal->hdr.mxFrame needs to be
  46509. ** updated. Any later hash tables will be automatically cleared when
  46510. ** pWal->hdr.mxFrame advances to the point where those hash tables are
  46511. ** actually needed.
  46512. */
  46513. static void walCleanupHash(Wal *pWal){
  46514. volatile ht_slot *aHash = 0; /* Pointer to hash table to clear */
  46515. volatile u32 *aPgno = 0; /* Page number array for hash table */
  46516. u32 iZero = 0; /* frame == (aHash[x]+iZero) */
  46517. int iLimit = 0; /* Zero values greater than this */
  46518. int nByte; /* Number of bytes to zero in aPgno[] */
  46519. int i; /* Used to iterate through aHash[] */
  46520. assert( pWal->writeLock );
  46521. testcase( pWal->hdr.mxFrame==HASHTABLE_NPAGE_ONE-1 );
  46522. testcase( pWal->hdr.mxFrame==HASHTABLE_NPAGE_ONE );
  46523. testcase( pWal->hdr.mxFrame==HASHTABLE_NPAGE_ONE+1 );
  46524. if( pWal->hdr.mxFrame==0 ) return;
  46525. /* Obtain pointers to the hash-table and page-number array containing
  46526. ** the entry that corresponds to frame pWal->hdr.mxFrame. It is guaranteed
  46527. ** that the page said hash-table and array reside on is already mapped.
  46528. */
  46529. assert( pWal->nWiData>walFramePage(pWal->hdr.mxFrame) );
  46530. assert( pWal->apWiData[walFramePage(pWal->hdr.mxFrame)] );
  46531. walHashGet(pWal, walFramePage(pWal->hdr.mxFrame), &aHash, &aPgno, &iZero);
  46532. /* Zero all hash-table entries that correspond to frame numbers greater
  46533. ** than pWal->hdr.mxFrame.
  46534. */
  46535. iLimit = pWal->hdr.mxFrame - iZero;
  46536. assert( iLimit>0 );
  46537. for(i=0; i<HASHTABLE_NSLOT; i++){
  46538. if( aHash[i]>iLimit ){
  46539. aHash[i] = 0;
  46540. }
  46541. }
  46542. /* Zero the entries in the aPgno array that correspond to frames with
  46543. ** frame numbers greater than pWal->hdr.mxFrame.
  46544. */
  46545. nByte = (int)((char *)aHash - (char *)&aPgno[iLimit+1]);
  46546. memset((void *)&aPgno[iLimit+1], 0, nByte);
  46547. #ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
  46548. /* Verify that the every entry in the mapping region is still reachable
  46549. ** via the hash table even after the cleanup.
  46550. */
  46551. if( iLimit ){
  46552. int i; /* Loop counter */
  46553. int iKey; /* Hash key */
  46554. for(i=1; i<=iLimit; i++){
  46555. for(iKey=walHash(aPgno[i]); aHash[iKey]; iKey=walNextHash(iKey)){
  46556. if( aHash[iKey]==i ) break;
  46557. }
  46558. assert( aHash[iKey]==i );
  46559. }
  46560. }
  46561. #endif /* SQLITE_ENABLE_EXPENSIVE_ASSERT */
  46562. }
  46563. /*
  46564. ** Set an entry in the wal-index that will map database page number
  46565. ** pPage into WAL frame iFrame.
  46566. */
  46567. static int walIndexAppend(Wal *pWal, u32 iFrame, u32 iPage){
  46568. int rc; /* Return code */
  46569. u32 iZero = 0; /* One less than frame number of aPgno[1] */
  46570. volatile u32 *aPgno = 0; /* Page number array */
  46571. volatile ht_slot *aHash = 0; /* Hash table */
  46572. rc = walHashGet(pWal, walFramePage(iFrame), &aHash, &aPgno, &iZero);
  46573. /* Assuming the wal-index file was successfully mapped, populate the
  46574. ** page number array and hash table entry.
  46575. */
  46576. if( rc==SQLITE_OK ){
  46577. int iKey; /* Hash table key */
  46578. int idx; /* Value to write to hash-table slot */
  46579. int nCollide; /* Number of hash collisions */
  46580. idx = iFrame - iZero;
  46581. assert( idx <= HASHTABLE_NSLOT/2 + 1 );
  46582. /* If this is the first entry to be added to this hash-table, zero the
  46583. ** entire hash table and aPgno[] array before proceeding.
  46584. */
  46585. if( idx==1 ){
  46586. int nByte = (int)((u8 *)&aHash[HASHTABLE_NSLOT] - (u8 *)&aPgno[1]);
  46587. memset((void*)&aPgno[1], 0, nByte);
  46588. }
  46589. /* If the entry in aPgno[] is already set, then the previous writer
  46590. ** must have exited unexpectedly in the middle of a transaction (after
  46591. ** writing one or more dirty pages to the WAL to free up memory).
  46592. ** Remove the remnants of that writers uncommitted transaction from
  46593. ** the hash-table before writing any new entries.
  46594. */
  46595. if( aPgno[idx] ){
  46596. walCleanupHash(pWal);
  46597. assert( !aPgno[idx] );
  46598. }
  46599. /* Write the aPgno[] array entry and the hash-table slot. */
  46600. nCollide = idx;
  46601. for(iKey=walHash(iPage); aHash[iKey]; iKey=walNextHash(iKey)){
  46602. if( (nCollide--)==0 ) return SQLITE_CORRUPT_BKPT;
  46603. }
  46604. aPgno[idx] = iPage;
  46605. aHash[iKey] = (ht_slot)idx;
  46606. #ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
  46607. /* Verify that the number of entries in the hash table exactly equals
  46608. ** the number of entries in the mapping region.
  46609. */
  46610. {
  46611. int i; /* Loop counter */
  46612. int nEntry = 0; /* Number of entries in the hash table */
  46613. for(i=0; i<HASHTABLE_NSLOT; i++){ if( aHash[i] ) nEntry++; }
  46614. assert( nEntry==idx );
  46615. }
  46616. /* Verify that the every entry in the mapping region is reachable
  46617. ** via the hash table. This turns out to be a really, really expensive
  46618. ** thing to check, so only do this occasionally - not on every
  46619. ** iteration.
  46620. */
  46621. if( (idx&0x3ff)==0 ){
  46622. int i; /* Loop counter */
  46623. for(i=1; i<=idx; i++){
  46624. for(iKey=walHash(aPgno[i]); aHash[iKey]; iKey=walNextHash(iKey)){
  46625. if( aHash[iKey]==i ) break;
  46626. }
  46627. assert( aHash[iKey]==i );
  46628. }
  46629. }
  46630. #endif /* SQLITE_ENABLE_EXPENSIVE_ASSERT */
  46631. }
  46632. return rc;
  46633. }
  46634. /*
  46635. ** Recover the wal-index by reading the write-ahead log file.
  46636. **
  46637. ** This routine first tries to establish an exclusive lock on the
  46638. ** wal-index to prevent other threads/processes from doing anything
  46639. ** with the WAL or wal-index while recovery is running. The
  46640. ** WAL_RECOVER_LOCK is also held so that other threads will know
  46641. ** that this thread is running recovery. If unable to establish
  46642. ** the necessary locks, this routine returns SQLITE_BUSY.
  46643. */
  46644. static int walIndexRecover(Wal *pWal){
  46645. int rc; /* Return Code */
  46646. i64 nSize; /* Size of log file */
  46647. u32 aFrameCksum[2] = {0, 0};
  46648. int iLock; /* Lock offset to lock for checkpoint */
  46649. int nLock; /* Number of locks to hold */
  46650. /* Obtain an exclusive lock on all byte in the locking range not already
  46651. ** locked by the caller. The caller is guaranteed to have locked the
  46652. ** WAL_WRITE_LOCK byte, and may have also locked the WAL_CKPT_LOCK byte.
  46653. ** If successful, the same bytes that are locked here are unlocked before
  46654. ** this function returns.
  46655. */
  46656. assert( pWal->ckptLock==1 || pWal->ckptLock==0 );
  46657. assert( WAL_ALL_BUT_WRITE==WAL_WRITE_LOCK+1 );
  46658. assert( WAL_CKPT_LOCK==WAL_ALL_BUT_WRITE );
  46659. assert( pWal->writeLock );
  46660. iLock = WAL_ALL_BUT_WRITE + pWal->ckptLock;
  46661. nLock = SQLITE_SHM_NLOCK - iLock;
  46662. rc = walLockExclusive(pWal, iLock, nLock, 0);
  46663. if( rc ){
  46664. return rc;
  46665. }
  46666. WALTRACE(("WAL%p: recovery begin...\n", pWal));
  46667. memset(&pWal->hdr, 0, sizeof(WalIndexHdr));
  46668. rc = sqlite3OsFileSize(pWal->pWalFd, &nSize);
  46669. if( rc!=SQLITE_OK ){
  46670. goto recovery_error;
  46671. }
  46672. if( nSize>WAL_HDRSIZE ){
  46673. u8 aBuf[WAL_HDRSIZE]; /* Buffer to load WAL header into */
  46674. u8 *aFrame = 0; /* Malloc'd buffer to load entire frame */
  46675. int szFrame; /* Number of bytes in buffer aFrame[] */
  46676. u8 *aData; /* Pointer to data part of aFrame buffer */
  46677. int iFrame; /* Index of last frame read */
  46678. i64 iOffset; /* Next offset to read from log file */
  46679. int szPage; /* Page size according to the log */
  46680. u32 magic; /* Magic value read from WAL header */
  46681. u32 version; /* Magic value read from WAL header */
  46682. int isValid; /* True if this frame is valid */
  46683. /* Read in the WAL header. */
  46684. rc = sqlite3OsRead(pWal->pWalFd, aBuf, WAL_HDRSIZE, 0);
  46685. if( rc!=SQLITE_OK ){
  46686. goto recovery_error;
  46687. }
  46688. /* If the database page size is not a power of two, or is greater than
  46689. ** SQLITE_MAX_PAGE_SIZE, conclude that the WAL file contains no valid
  46690. ** data. Similarly, if the 'magic' value is invalid, ignore the whole
  46691. ** WAL file.
  46692. */
  46693. magic = sqlite3Get4byte(&aBuf[0]);
  46694. szPage = sqlite3Get4byte(&aBuf[8]);
  46695. if( (magic&0xFFFFFFFE)!=WAL_MAGIC
  46696. || szPage&(szPage-1)
  46697. || szPage>SQLITE_MAX_PAGE_SIZE
  46698. || szPage<512
  46699. ){
  46700. goto finished;
  46701. }
  46702. pWal->hdr.bigEndCksum = (u8)(magic&0x00000001);
  46703. pWal->szPage = szPage;
  46704. pWal->nCkpt = sqlite3Get4byte(&aBuf[12]);
  46705. memcpy(&pWal->hdr.aSalt, &aBuf[16], 8);
  46706. /* Verify that the WAL header checksum is correct */
  46707. walChecksumBytes(pWal->hdr.bigEndCksum==SQLITE_BIGENDIAN,
  46708. aBuf, WAL_HDRSIZE-2*4, 0, pWal->hdr.aFrameCksum
  46709. );
  46710. if( pWal->hdr.aFrameCksum[0]!=sqlite3Get4byte(&aBuf[24])
  46711. || pWal->hdr.aFrameCksum[1]!=sqlite3Get4byte(&aBuf[28])
  46712. ){
  46713. goto finished;
  46714. }
  46715. /* Verify that the version number on the WAL format is one that
  46716. ** are able to understand */
  46717. version = sqlite3Get4byte(&aBuf[4]);
  46718. if( version!=WAL_MAX_VERSION ){
  46719. rc = SQLITE_CANTOPEN_BKPT;
  46720. goto finished;
  46721. }
  46722. /* Malloc a buffer to read frames into. */
  46723. szFrame = szPage + WAL_FRAME_HDRSIZE;
  46724. aFrame = (u8 *)sqlite3_malloc64(szFrame);
  46725. if( !aFrame ){
  46726. rc = SQLITE_NOMEM;
  46727. goto recovery_error;
  46728. }
  46729. aData = &aFrame[WAL_FRAME_HDRSIZE];
  46730. /* Read all frames from the log file. */
  46731. iFrame = 0;
  46732. for(iOffset=WAL_HDRSIZE; (iOffset+szFrame)<=nSize; iOffset+=szFrame){
  46733. u32 pgno; /* Database page number for frame */
  46734. u32 nTruncate; /* dbsize field from frame header */
  46735. /* Read and decode the next log frame. */
  46736. iFrame++;
  46737. rc = sqlite3OsRead(pWal->pWalFd, aFrame, szFrame, iOffset);
  46738. if( rc!=SQLITE_OK ) break;
  46739. isValid = walDecodeFrame(pWal, &pgno, &nTruncate, aData, aFrame);
  46740. if( !isValid ) break;
  46741. rc = walIndexAppend(pWal, iFrame, pgno);
  46742. if( rc!=SQLITE_OK ) break;
  46743. /* If nTruncate is non-zero, this is a commit record. */
  46744. if( nTruncate ){
  46745. pWal->hdr.mxFrame = iFrame;
  46746. pWal->hdr.nPage = nTruncate;
  46747. pWal->hdr.szPage = (u16)((szPage&0xff00) | (szPage>>16));
  46748. testcase( szPage<=32768 );
  46749. testcase( szPage>=65536 );
  46750. aFrameCksum[0] = pWal->hdr.aFrameCksum[0];
  46751. aFrameCksum[1] = pWal->hdr.aFrameCksum[1];
  46752. }
  46753. }
  46754. sqlite3_free(aFrame);
  46755. }
  46756. finished:
  46757. if( rc==SQLITE_OK ){
  46758. volatile WalCkptInfo *pInfo;
  46759. int i;
  46760. pWal->hdr.aFrameCksum[0] = aFrameCksum[0];
  46761. pWal->hdr.aFrameCksum[1] = aFrameCksum[1];
  46762. walIndexWriteHdr(pWal);
  46763. /* Reset the checkpoint-header. This is safe because this thread is
  46764. ** currently holding locks that exclude all other readers, writers and
  46765. ** checkpointers.
  46766. */
  46767. pInfo = walCkptInfo(pWal);
  46768. pInfo->nBackfill = 0;
  46769. pInfo->aReadMark[0] = 0;
  46770. for(i=1; i<WAL_NREADER; i++) pInfo->aReadMark[i] = READMARK_NOT_USED;
  46771. if( pWal->hdr.mxFrame ) pInfo->aReadMark[1] = pWal->hdr.mxFrame;
  46772. /* If more than one frame was recovered from the log file, report an
  46773. ** event via sqlite3_log(). This is to help with identifying performance
  46774. ** problems caused by applications routinely shutting down without
  46775. ** checkpointing the log file.
  46776. */
  46777. if( pWal->hdr.nPage ){
  46778. sqlite3_log(SQLITE_NOTICE_RECOVER_WAL,
  46779. "recovered %d frames from WAL file %s",
  46780. pWal->hdr.mxFrame, pWal->zWalName
  46781. );
  46782. }
  46783. }
  46784. recovery_error:
  46785. WALTRACE(("WAL%p: recovery %s\n", pWal, rc ? "failed" : "ok"));
  46786. walUnlockExclusive(pWal, iLock, nLock);
  46787. return rc;
  46788. }
  46789. /*
  46790. ** Close an open wal-index.
  46791. */
  46792. static void walIndexClose(Wal *pWal, int isDelete){
  46793. if( pWal->exclusiveMode==WAL_HEAPMEMORY_MODE ){
  46794. int i;
  46795. for(i=0; i<pWal->nWiData; i++){
  46796. sqlite3_free((void *)pWal->apWiData[i]);
  46797. pWal->apWiData[i] = 0;
  46798. }
  46799. }else{
  46800. sqlite3OsShmUnmap(pWal->pDbFd, isDelete);
  46801. }
  46802. }
  46803. /*
  46804. ** Open a connection to the WAL file zWalName. The database file must
  46805. ** already be opened on connection pDbFd. The buffer that zWalName points
  46806. ** to must remain valid for the lifetime of the returned Wal* handle.
  46807. **
  46808. ** A SHARED lock should be held on the database file when this function
  46809. ** is called. The purpose of this SHARED lock is to prevent any other
  46810. ** client from unlinking the WAL or wal-index file. If another process
  46811. ** were to do this just after this client opened one of these files, the
  46812. ** system would be badly broken.
  46813. **
  46814. ** If the log file is successfully opened, SQLITE_OK is returned and
  46815. ** *ppWal is set to point to a new WAL handle. If an error occurs,
  46816. ** an SQLite error code is returned and *ppWal is left unmodified.
  46817. */
  46818. SQLITE_PRIVATE int sqlite3WalOpen(
  46819. sqlite3_vfs *pVfs, /* vfs module to open wal and wal-index */
  46820. sqlite3_file *pDbFd, /* The open database file */
  46821. const char *zWalName, /* Name of the WAL file */
  46822. int bNoShm, /* True to run in heap-memory mode */
  46823. i64 mxWalSize, /* Truncate WAL to this size on reset */
  46824. Wal **ppWal /* OUT: Allocated Wal handle */
  46825. ){
  46826. int rc; /* Return Code */
  46827. Wal *pRet; /* Object to allocate and return */
  46828. int flags; /* Flags passed to OsOpen() */
  46829. assert( zWalName && zWalName[0] );
  46830. assert( pDbFd );
  46831. /* In the amalgamation, the os_unix.c and os_win.c source files come before
  46832. ** this source file. Verify that the #defines of the locking byte offsets
  46833. ** in os_unix.c and os_win.c agree with the WALINDEX_LOCK_OFFSET value.
  46834. */
  46835. #ifdef WIN_SHM_BASE
  46836. assert( WIN_SHM_BASE==WALINDEX_LOCK_OFFSET );
  46837. #endif
  46838. #ifdef UNIX_SHM_BASE
  46839. assert( UNIX_SHM_BASE==WALINDEX_LOCK_OFFSET );
  46840. #endif
  46841. /* Allocate an instance of struct Wal to return. */
  46842. *ppWal = 0;
  46843. pRet = (Wal*)sqlite3MallocZero(sizeof(Wal) + pVfs->szOsFile);
  46844. if( !pRet ){
  46845. return SQLITE_NOMEM;
  46846. }
  46847. pRet->pVfs = pVfs;
  46848. pRet->pWalFd = (sqlite3_file *)&pRet[1];
  46849. pRet->pDbFd = pDbFd;
  46850. pRet->readLock = -1;
  46851. pRet->mxWalSize = mxWalSize;
  46852. pRet->zWalName = zWalName;
  46853. pRet->syncHeader = 1;
  46854. pRet->padToSectorBoundary = 1;
  46855. pRet->exclusiveMode = (bNoShm ? WAL_HEAPMEMORY_MODE: WAL_NORMAL_MODE);
  46856. /* Open file handle on the write-ahead log file. */
  46857. flags = (SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|SQLITE_OPEN_WAL);
  46858. rc = sqlite3OsOpen(pVfs, zWalName, pRet->pWalFd, flags, &flags);
  46859. if( rc==SQLITE_OK && flags&SQLITE_OPEN_READONLY ){
  46860. pRet->readOnly = WAL_RDONLY;
  46861. }
  46862. if( rc!=SQLITE_OK ){
  46863. walIndexClose(pRet, 0);
  46864. sqlite3OsClose(pRet->pWalFd);
  46865. sqlite3_free(pRet);
  46866. }else{
  46867. int iDC = sqlite3OsDeviceCharacteristics(pDbFd);
  46868. if( iDC & SQLITE_IOCAP_SEQUENTIAL ){ pRet->syncHeader = 0; }
  46869. if( iDC & SQLITE_IOCAP_POWERSAFE_OVERWRITE ){
  46870. pRet->padToSectorBoundary = 0;
  46871. }
  46872. *ppWal = pRet;
  46873. WALTRACE(("WAL%d: opened\n", pRet));
  46874. }
  46875. return rc;
  46876. }
  46877. /*
  46878. ** Change the size to which the WAL file is trucated on each reset.
  46879. */
  46880. SQLITE_PRIVATE void sqlite3WalLimit(Wal *pWal, i64 iLimit){
  46881. if( pWal ) pWal->mxWalSize = iLimit;
  46882. }
  46883. /*
  46884. ** Find the smallest page number out of all pages held in the WAL that
  46885. ** has not been returned by any prior invocation of this method on the
  46886. ** same WalIterator object. Write into *piFrame the frame index where
  46887. ** that page was last written into the WAL. Write into *piPage the page
  46888. ** number.
  46889. **
  46890. ** Return 0 on success. If there are no pages in the WAL with a page
  46891. ** number larger than *piPage, then return 1.
  46892. */
  46893. static int walIteratorNext(
  46894. WalIterator *p, /* Iterator */
  46895. u32 *piPage, /* OUT: The page number of the next page */
  46896. u32 *piFrame /* OUT: Wal frame index of next page */
  46897. ){
  46898. u32 iMin; /* Result pgno must be greater than iMin */
  46899. u32 iRet = 0xFFFFFFFF; /* 0xffffffff is never a valid page number */
  46900. int i; /* For looping through segments */
  46901. iMin = p->iPrior;
  46902. assert( iMin<0xffffffff );
  46903. for(i=p->nSegment-1; i>=0; i--){
  46904. struct WalSegment *pSegment = &p->aSegment[i];
  46905. while( pSegment->iNext<pSegment->nEntry ){
  46906. u32 iPg = pSegment->aPgno[pSegment->aIndex[pSegment->iNext]];
  46907. if( iPg>iMin ){
  46908. if( iPg<iRet ){
  46909. iRet = iPg;
  46910. *piFrame = pSegment->iZero + pSegment->aIndex[pSegment->iNext];
  46911. }
  46912. break;
  46913. }
  46914. pSegment->iNext++;
  46915. }
  46916. }
  46917. *piPage = p->iPrior = iRet;
  46918. return (iRet==0xFFFFFFFF);
  46919. }
  46920. /*
  46921. ** This function merges two sorted lists into a single sorted list.
  46922. **
  46923. ** aLeft[] and aRight[] are arrays of indices. The sort key is
  46924. ** aContent[aLeft[]] and aContent[aRight[]]. Upon entry, the following
  46925. ** is guaranteed for all J<K:
  46926. **
  46927. ** aContent[aLeft[J]] < aContent[aLeft[K]]
  46928. ** aContent[aRight[J]] < aContent[aRight[K]]
  46929. **
  46930. ** This routine overwrites aRight[] with a new (probably longer) sequence
  46931. ** of indices such that the aRight[] contains every index that appears in
  46932. ** either aLeft[] or the old aRight[] and such that the second condition
  46933. ** above is still met.
  46934. **
  46935. ** The aContent[aLeft[X]] values will be unique for all X. And the
  46936. ** aContent[aRight[X]] values will be unique too. But there might be
  46937. ** one or more combinations of X and Y such that
  46938. **
  46939. ** aLeft[X]!=aRight[Y] && aContent[aLeft[X]] == aContent[aRight[Y]]
  46940. **
  46941. ** When that happens, omit the aLeft[X] and use the aRight[Y] index.
  46942. */
  46943. static void walMerge(
  46944. const u32 *aContent, /* Pages in wal - keys for the sort */
  46945. ht_slot *aLeft, /* IN: Left hand input list */
  46946. int nLeft, /* IN: Elements in array *paLeft */
  46947. ht_slot **paRight, /* IN/OUT: Right hand input list */
  46948. int *pnRight, /* IN/OUT: Elements in *paRight */
  46949. ht_slot *aTmp /* Temporary buffer */
  46950. ){
  46951. int iLeft = 0; /* Current index in aLeft */
  46952. int iRight = 0; /* Current index in aRight */
  46953. int iOut = 0; /* Current index in output buffer */
  46954. int nRight = *pnRight;
  46955. ht_slot *aRight = *paRight;
  46956. assert( nLeft>0 && nRight>0 );
  46957. while( iRight<nRight || iLeft<nLeft ){
  46958. ht_slot logpage;
  46959. Pgno dbpage;
  46960. if( (iLeft<nLeft)
  46961. && (iRight>=nRight || aContent[aLeft[iLeft]]<aContent[aRight[iRight]])
  46962. ){
  46963. logpage = aLeft[iLeft++];
  46964. }else{
  46965. logpage = aRight[iRight++];
  46966. }
  46967. dbpage = aContent[logpage];
  46968. aTmp[iOut++] = logpage;
  46969. if( iLeft<nLeft && aContent[aLeft[iLeft]]==dbpage ) iLeft++;
  46970. assert( iLeft>=nLeft || aContent[aLeft[iLeft]]>dbpage );
  46971. assert( iRight>=nRight || aContent[aRight[iRight]]>dbpage );
  46972. }
  46973. *paRight = aLeft;
  46974. *pnRight = iOut;
  46975. memcpy(aLeft, aTmp, sizeof(aTmp[0])*iOut);
  46976. }
  46977. /*
  46978. ** Sort the elements in list aList using aContent[] as the sort key.
  46979. ** Remove elements with duplicate keys, preferring to keep the
  46980. ** larger aList[] values.
  46981. **
  46982. ** The aList[] entries are indices into aContent[]. The values in
  46983. ** aList[] are to be sorted so that for all J<K:
  46984. **
  46985. ** aContent[aList[J]] < aContent[aList[K]]
  46986. **
  46987. ** For any X and Y such that
  46988. **
  46989. ** aContent[aList[X]] == aContent[aList[Y]]
  46990. **
  46991. ** Keep the larger of the two values aList[X] and aList[Y] and discard
  46992. ** the smaller.
  46993. */
  46994. static void walMergesort(
  46995. const u32 *aContent, /* Pages in wal */
  46996. ht_slot *aBuffer, /* Buffer of at least *pnList items to use */
  46997. ht_slot *aList, /* IN/OUT: List to sort */
  46998. int *pnList /* IN/OUT: Number of elements in aList[] */
  46999. ){
  47000. struct Sublist {
  47001. int nList; /* Number of elements in aList */
  47002. ht_slot *aList; /* Pointer to sub-list content */
  47003. };
  47004. const int nList = *pnList; /* Size of input list */
  47005. int nMerge = 0; /* Number of elements in list aMerge */
  47006. ht_slot *aMerge = 0; /* List to be merged */
  47007. int iList; /* Index into input list */
  47008. int iSub = 0; /* Index into aSub array */
  47009. struct Sublist aSub[13]; /* Array of sub-lists */
  47010. memset(aSub, 0, sizeof(aSub));
  47011. assert( nList<=HASHTABLE_NPAGE && nList>0 );
  47012. assert( HASHTABLE_NPAGE==(1<<(ArraySize(aSub)-1)) );
  47013. for(iList=0; iList<nList; iList++){
  47014. nMerge = 1;
  47015. aMerge = &aList[iList];
  47016. for(iSub=0; iList & (1<<iSub); iSub++){
  47017. struct Sublist *p = &aSub[iSub];
  47018. assert( p->aList && p->nList<=(1<<iSub) );
  47019. assert( p->aList==&aList[iList&~((2<<iSub)-1)] );
  47020. walMerge(aContent, p->aList, p->nList, &aMerge, &nMerge, aBuffer);
  47021. }
  47022. aSub[iSub].aList = aMerge;
  47023. aSub[iSub].nList = nMerge;
  47024. }
  47025. for(iSub++; iSub<ArraySize(aSub); iSub++){
  47026. if( nList & (1<<iSub) ){
  47027. struct Sublist *p = &aSub[iSub];
  47028. assert( p->nList<=(1<<iSub) );
  47029. assert( p->aList==&aList[nList&~((2<<iSub)-1)] );
  47030. walMerge(aContent, p->aList, p->nList, &aMerge, &nMerge, aBuffer);
  47031. }
  47032. }
  47033. assert( aMerge==aList );
  47034. *pnList = nMerge;
  47035. #ifdef SQLITE_DEBUG
  47036. {
  47037. int i;
  47038. for(i=1; i<*pnList; i++){
  47039. assert( aContent[aList[i]] > aContent[aList[i-1]] );
  47040. }
  47041. }
  47042. #endif
  47043. }
  47044. /*
  47045. ** Free an iterator allocated by walIteratorInit().
  47046. */
  47047. static void walIteratorFree(WalIterator *p){
  47048. sqlite3_free(p);
  47049. }
  47050. /*
  47051. ** Construct a WalInterator object that can be used to loop over all
  47052. ** pages in the WAL in ascending order. The caller must hold the checkpoint
  47053. ** lock.
  47054. **
  47055. ** On success, make *pp point to the newly allocated WalInterator object
  47056. ** return SQLITE_OK. Otherwise, return an error code. If this routine
  47057. ** returns an error, the value of *pp is undefined.
  47058. **
  47059. ** The calling routine should invoke walIteratorFree() to destroy the
  47060. ** WalIterator object when it has finished with it.
  47061. */
  47062. static int walIteratorInit(Wal *pWal, WalIterator **pp){
  47063. WalIterator *p; /* Return value */
  47064. int nSegment; /* Number of segments to merge */
  47065. u32 iLast; /* Last frame in log */
  47066. int nByte; /* Number of bytes to allocate */
  47067. int i; /* Iterator variable */
  47068. ht_slot *aTmp; /* Temp space used by merge-sort */
  47069. int rc = SQLITE_OK; /* Return Code */
  47070. /* This routine only runs while holding the checkpoint lock. And
  47071. ** it only runs if there is actually content in the log (mxFrame>0).
  47072. */
  47073. assert( pWal->ckptLock && pWal->hdr.mxFrame>0 );
  47074. iLast = pWal->hdr.mxFrame;
  47075. /* Allocate space for the WalIterator object. */
  47076. nSegment = walFramePage(iLast) + 1;
  47077. nByte = sizeof(WalIterator)
  47078. + (nSegment-1)*sizeof(struct WalSegment)
  47079. + iLast*sizeof(ht_slot);
  47080. p = (WalIterator *)sqlite3_malloc64(nByte);
  47081. if( !p ){
  47082. return SQLITE_NOMEM;
  47083. }
  47084. memset(p, 0, nByte);
  47085. p->nSegment = nSegment;
  47086. /* Allocate temporary space used by the merge-sort routine. This block
  47087. ** of memory will be freed before this function returns.
  47088. */
  47089. aTmp = (ht_slot *)sqlite3_malloc64(
  47090. sizeof(ht_slot) * (iLast>HASHTABLE_NPAGE?HASHTABLE_NPAGE:iLast)
  47091. );
  47092. if( !aTmp ){
  47093. rc = SQLITE_NOMEM;
  47094. }
  47095. for(i=0; rc==SQLITE_OK && i<nSegment; i++){
  47096. volatile ht_slot *aHash;
  47097. u32 iZero;
  47098. volatile u32 *aPgno;
  47099. rc = walHashGet(pWal, i, &aHash, &aPgno, &iZero);
  47100. if( rc==SQLITE_OK ){
  47101. int j; /* Counter variable */
  47102. int nEntry; /* Number of entries in this segment */
  47103. ht_slot *aIndex; /* Sorted index for this segment */
  47104. aPgno++;
  47105. if( (i+1)==nSegment ){
  47106. nEntry = (int)(iLast - iZero);
  47107. }else{
  47108. nEntry = (int)((u32*)aHash - (u32*)aPgno);
  47109. }
  47110. aIndex = &((ht_slot *)&p->aSegment[p->nSegment])[iZero];
  47111. iZero++;
  47112. for(j=0; j<nEntry; j++){
  47113. aIndex[j] = (ht_slot)j;
  47114. }
  47115. walMergesort((u32 *)aPgno, aTmp, aIndex, &nEntry);
  47116. p->aSegment[i].iZero = iZero;
  47117. p->aSegment[i].nEntry = nEntry;
  47118. p->aSegment[i].aIndex = aIndex;
  47119. p->aSegment[i].aPgno = (u32 *)aPgno;
  47120. }
  47121. }
  47122. sqlite3_free(aTmp);
  47123. if( rc!=SQLITE_OK ){
  47124. walIteratorFree(p);
  47125. }
  47126. *pp = p;
  47127. return rc;
  47128. }
  47129. /*
  47130. ** Attempt to obtain the exclusive WAL lock defined by parameters lockIdx and
  47131. ** n. If the attempt fails and parameter xBusy is not NULL, then it is a
  47132. ** busy-handler function. Invoke it and retry the lock until either the
  47133. ** lock is successfully obtained or the busy-handler returns 0.
  47134. */
  47135. static int walBusyLock(
  47136. Wal *pWal, /* WAL connection */
  47137. int (*xBusy)(void*), /* Function to call when busy */
  47138. void *pBusyArg, /* Context argument for xBusyHandler */
  47139. int lockIdx, /* Offset of first byte to lock */
  47140. int n /* Number of bytes to lock */
  47141. ){
  47142. int rc;
  47143. do {
  47144. rc = walLockExclusive(pWal, lockIdx, n, 0);
  47145. }while( xBusy && rc==SQLITE_BUSY && xBusy(pBusyArg) );
  47146. return rc;
  47147. }
  47148. /*
  47149. ** The cache of the wal-index header must be valid to call this function.
  47150. ** Return the page-size in bytes used by the database.
  47151. */
  47152. static int walPagesize(Wal *pWal){
  47153. return (pWal->hdr.szPage&0xfe00) + ((pWal->hdr.szPage&0x0001)<<16);
  47154. }
  47155. /*
  47156. ** The following is guaranteed when this function is called:
  47157. **
  47158. ** a) the WRITER lock is held,
  47159. ** b) the entire log file has been checkpointed, and
  47160. ** c) any existing readers are reading exclusively from the database
  47161. ** file - there are no readers that may attempt to read a frame from
  47162. ** the log file.
  47163. **
  47164. ** This function updates the shared-memory structures so that the next
  47165. ** client to write to the database (which may be this one) does so by
  47166. ** writing frames into the start of the log file.
  47167. **
  47168. ** The value of parameter salt1 is used as the aSalt[1] value in the
  47169. ** new wal-index header. It should be passed a pseudo-random value (i.e.
  47170. ** one obtained from sqlite3_randomness()).
  47171. */
  47172. static void walRestartHdr(Wal *pWal, u32 salt1){
  47173. volatile WalCkptInfo *pInfo = walCkptInfo(pWal);
  47174. int i; /* Loop counter */
  47175. u32 *aSalt = pWal->hdr.aSalt; /* Big-endian salt values */
  47176. pWal->nCkpt++;
  47177. pWal->hdr.mxFrame = 0;
  47178. sqlite3Put4byte((u8*)&aSalt[0], 1 + sqlite3Get4byte((u8*)&aSalt[0]));
  47179. memcpy(&pWal->hdr.aSalt[1], &salt1, 4);
  47180. walIndexWriteHdr(pWal);
  47181. pInfo->nBackfill = 0;
  47182. pInfo->aReadMark[1] = 0;
  47183. for(i=2; i<WAL_NREADER; i++) pInfo->aReadMark[i] = READMARK_NOT_USED;
  47184. assert( pInfo->aReadMark[0]==0 );
  47185. }
  47186. /*
  47187. ** Copy as much content as we can from the WAL back into the database file
  47188. ** in response to an sqlite3_wal_checkpoint() request or the equivalent.
  47189. **
  47190. ** The amount of information copies from WAL to database might be limited
  47191. ** by active readers. This routine will never overwrite a database page
  47192. ** that a concurrent reader might be using.
  47193. **
  47194. ** All I/O barrier operations (a.k.a fsyncs) occur in this routine when
  47195. ** SQLite is in WAL-mode in synchronous=NORMAL. That means that if
  47196. ** checkpoints are always run by a background thread or background
  47197. ** process, foreground threads will never block on a lengthy fsync call.
  47198. **
  47199. ** Fsync is called on the WAL before writing content out of the WAL and
  47200. ** into the database. This ensures that if the new content is persistent
  47201. ** in the WAL and can be recovered following a power-loss or hard reset.
  47202. **
  47203. ** Fsync is also called on the database file if (and only if) the entire
  47204. ** WAL content is copied into the database file. This second fsync makes
  47205. ** it safe to delete the WAL since the new content will persist in the
  47206. ** database file.
  47207. **
  47208. ** This routine uses and updates the nBackfill field of the wal-index header.
  47209. ** This is the only routine that will increase the value of nBackfill.
  47210. ** (A WAL reset or recovery will revert nBackfill to zero, but not increase
  47211. ** its value.)
  47212. **
  47213. ** The caller must be holding sufficient locks to ensure that no other
  47214. ** checkpoint is running (in any other thread or process) at the same
  47215. ** time.
  47216. */
  47217. static int walCheckpoint(
  47218. Wal *pWal, /* Wal connection */
  47219. int eMode, /* One of PASSIVE, FULL or RESTART */
  47220. int (*xBusy)(void*), /* Function to call when busy */
  47221. void *pBusyArg, /* Context argument for xBusyHandler */
  47222. int sync_flags, /* Flags for OsSync() (or 0) */
  47223. u8 *zBuf /* Temporary buffer to use */
  47224. ){
  47225. int rc = SQLITE_OK; /* Return code */
  47226. int szPage; /* Database page-size */
  47227. WalIterator *pIter = 0; /* Wal iterator context */
  47228. u32 iDbpage = 0; /* Next database page to write */
  47229. u32 iFrame = 0; /* Wal frame containing data for iDbpage */
  47230. u32 mxSafeFrame; /* Max frame that can be backfilled */
  47231. u32 mxPage; /* Max database page to write */
  47232. int i; /* Loop counter */
  47233. volatile WalCkptInfo *pInfo; /* The checkpoint status information */
  47234. szPage = walPagesize(pWal);
  47235. testcase( szPage<=32768 );
  47236. testcase( szPage>=65536 );
  47237. pInfo = walCkptInfo(pWal);
  47238. if( pInfo->nBackfill<pWal->hdr.mxFrame ){
  47239. /* Allocate the iterator */
  47240. rc = walIteratorInit(pWal, &pIter);
  47241. if( rc!=SQLITE_OK ){
  47242. return rc;
  47243. }
  47244. assert( pIter );
  47245. /* EVIDENCE-OF: R-62920-47450 The busy-handler callback is never invoked
  47246. ** in the SQLITE_CHECKPOINT_PASSIVE mode. */
  47247. assert( eMode!=SQLITE_CHECKPOINT_PASSIVE || xBusy==0 );
  47248. /* Compute in mxSafeFrame the index of the last frame of the WAL that is
  47249. ** safe to write into the database. Frames beyond mxSafeFrame might
  47250. ** overwrite database pages that are in use by active readers and thus
  47251. ** cannot be backfilled from the WAL.
  47252. */
  47253. mxSafeFrame = pWal->hdr.mxFrame;
  47254. mxPage = pWal->hdr.nPage;
  47255. for(i=1; i<WAL_NREADER; i++){
  47256. /* Thread-sanitizer reports that the following is an unsafe read,
  47257. ** as some other thread may be in the process of updating the value
  47258. ** of the aReadMark[] slot. The assumption here is that if that is
  47259. ** happening, the other client may only be increasing the value,
  47260. ** not decreasing it. So assuming either that either the "old" or
  47261. ** "new" version of the value is read, and not some arbitrary value
  47262. ** that would never be written by a real client, things are still
  47263. ** safe. */
  47264. u32 y = pInfo->aReadMark[i];
  47265. if( mxSafeFrame>y ){
  47266. assert( y<=pWal->hdr.mxFrame );
  47267. rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_READ_LOCK(i), 1);
  47268. if( rc==SQLITE_OK ){
  47269. pInfo->aReadMark[i] = (i==1 ? mxSafeFrame : READMARK_NOT_USED);
  47270. walUnlockExclusive(pWal, WAL_READ_LOCK(i), 1);
  47271. }else if( rc==SQLITE_BUSY ){
  47272. mxSafeFrame = y;
  47273. xBusy = 0;
  47274. }else{
  47275. goto walcheckpoint_out;
  47276. }
  47277. }
  47278. }
  47279. if( pInfo->nBackfill<mxSafeFrame
  47280. && (rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_READ_LOCK(0),1))==SQLITE_OK
  47281. ){
  47282. i64 nSize; /* Current size of database file */
  47283. u32 nBackfill = pInfo->nBackfill;
  47284. /* Sync the WAL to disk */
  47285. if( sync_flags ){
  47286. rc = sqlite3OsSync(pWal->pWalFd, sync_flags);
  47287. }
  47288. /* If the database may grow as a result of this checkpoint, hint
  47289. ** about the eventual size of the db file to the VFS layer.
  47290. */
  47291. if( rc==SQLITE_OK ){
  47292. i64 nReq = ((i64)mxPage * szPage);
  47293. rc = sqlite3OsFileSize(pWal->pDbFd, &nSize);
  47294. if( rc==SQLITE_OK && nSize<nReq ){
  47295. sqlite3OsFileControlHint(pWal->pDbFd, SQLITE_FCNTL_SIZE_HINT, &nReq);
  47296. }
  47297. }
  47298. /* Iterate through the contents of the WAL, copying data to the db file */
  47299. while( rc==SQLITE_OK && 0==walIteratorNext(pIter, &iDbpage, &iFrame) ){
  47300. i64 iOffset;
  47301. assert( walFramePgno(pWal, iFrame)==iDbpage );
  47302. if( iFrame<=nBackfill || iFrame>mxSafeFrame || iDbpage>mxPage ){
  47303. continue;
  47304. }
  47305. iOffset = walFrameOffset(iFrame, szPage) + WAL_FRAME_HDRSIZE;
  47306. /* testcase( IS_BIG_INT(iOffset) ); // requires a 4GiB WAL file */
  47307. rc = sqlite3OsRead(pWal->pWalFd, zBuf, szPage, iOffset);
  47308. if( rc!=SQLITE_OK ) break;
  47309. iOffset = (iDbpage-1)*(i64)szPage;
  47310. testcase( IS_BIG_INT(iOffset) );
  47311. rc = sqlite3OsWrite(pWal->pDbFd, zBuf, szPage, iOffset);
  47312. if( rc!=SQLITE_OK ) break;
  47313. }
  47314. /* If work was actually accomplished... */
  47315. if( rc==SQLITE_OK ){
  47316. if( mxSafeFrame==walIndexHdr(pWal)->mxFrame ){
  47317. i64 szDb = pWal->hdr.nPage*(i64)szPage;
  47318. testcase( IS_BIG_INT(szDb) );
  47319. rc = sqlite3OsTruncate(pWal->pDbFd, szDb);
  47320. if( rc==SQLITE_OK && sync_flags ){
  47321. rc = sqlite3OsSync(pWal->pDbFd, sync_flags);
  47322. }
  47323. }
  47324. if( rc==SQLITE_OK ){
  47325. pInfo->nBackfill = mxSafeFrame;
  47326. }
  47327. }
  47328. /* Release the reader lock held while backfilling */
  47329. walUnlockExclusive(pWal, WAL_READ_LOCK(0), 1);
  47330. }
  47331. if( rc==SQLITE_BUSY ){
  47332. /* Reset the return code so as not to report a checkpoint failure
  47333. ** just because there are active readers. */
  47334. rc = SQLITE_OK;
  47335. }
  47336. }
  47337. /* If this is an SQLITE_CHECKPOINT_RESTART or TRUNCATE operation, and the
  47338. ** entire wal file has been copied into the database file, then block
  47339. ** until all readers have finished using the wal file. This ensures that
  47340. ** the next process to write to the database restarts the wal file.
  47341. */
  47342. if( rc==SQLITE_OK && eMode!=SQLITE_CHECKPOINT_PASSIVE ){
  47343. assert( pWal->writeLock );
  47344. if( pInfo->nBackfill<pWal->hdr.mxFrame ){
  47345. rc = SQLITE_BUSY;
  47346. }else if( eMode>=SQLITE_CHECKPOINT_RESTART ){
  47347. u32 salt1;
  47348. sqlite3_randomness(4, &salt1);
  47349. assert( pInfo->nBackfill==pWal->hdr.mxFrame );
  47350. rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_READ_LOCK(1), WAL_NREADER-1);
  47351. if( rc==SQLITE_OK ){
  47352. if( eMode==SQLITE_CHECKPOINT_TRUNCATE ){
  47353. /* IMPLEMENTATION-OF: R-44699-57140 This mode works the same way as
  47354. ** SQLITE_CHECKPOINT_RESTART with the addition that it also
  47355. ** truncates the log file to zero bytes just prior to a
  47356. ** successful return.
  47357. **
  47358. ** In theory, it might be safe to do this without updating the
  47359. ** wal-index header in shared memory, as all subsequent reader or
  47360. ** writer clients should see that the entire log file has been
  47361. ** checkpointed and behave accordingly. This seems unsafe though,
  47362. ** as it would leave the system in a state where the contents of
  47363. ** the wal-index header do not match the contents of the
  47364. ** file-system. To avoid this, update the wal-index header to
  47365. ** indicate that the log file contains zero valid frames. */
  47366. walRestartHdr(pWal, salt1);
  47367. rc = sqlite3OsTruncate(pWal->pWalFd, 0);
  47368. }
  47369. walUnlockExclusive(pWal, WAL_READ_LOCK(1), WAL_NREADER-1);
  47370. }
  47371. }
  47372. }
  47373. walcheckpoint_out:
  47374. walIteratorFree(pIter);
  47375. return rc;
  47376. }
  47377. /*
  47378. ** If the WAL file is currently larger than nMax bytes in size, truncate
  47379. ** it to exactly nMax bytes. If an error occurs while doing so, ignore it.
  47380. */
  47381. static void walLimitSize(Wal *pWal, i64 nMax){
  47382. i64 sz;
  47383. int rx;
  47384. sqlite3BeginBenignMalloc();
  47385. rx = sqlite3OsFileSize(pWal->pWalFd, &sz);
  47386. if( rx==SQLITE_OK && (sz > nMax ) ){
  47387. rx = sqlite3OsTruncate(pWal->pWalFd, nMax);
  47388. }
  47389. sqlite3EndBenignMalloc();
  47390. if( rx ){
  47391. sqlite3_log(rx, "cannot limit WAL size: %s", pWal->zWalName);
  47392. }
  47393. }
  47394. /*
  47395. ** Close a connection to a log file.
  47396. */
  47397. SQLITE_PRIVATE int sqlite3WalClose(
  47398. Wal *pWal, /* Wal to close */
  47399. int sync_flags, /* Flags to pass to OsSync() (or 0) */
  47400. int nBuf,
  47401. u8 *zBuf /* Buffer of at least nBuf bytes */
  47402. ){
  47403. int rc = SQLITE_OK;
  47404. if( pWal ){
  47405. int isDelete = 0; /* True to unlink wal and wal-index files */
  47406. /* If an EXCLUSIVE lock can be obtained on the database file (using the
  47407. ** ordinary, rollback-mode locking methods, this guarantees that the
  47408. ** connection associated with this log file is the only connection to
  47409. ** the database. In this case checkpoint the database and unlink both
  47410. ** the wal and wal-index files.
  47411. **
  47412. ** The EXCLUSIVE lock is not released before returning.
  47413. */
  47414. rc = sqlite3OsLock(pWal->pDbFd, SQLITE_LOCK_EXCLUSIVE);
  47415. if( rc==SQLITE_OK ){
  47416. if( pWal->exclusiveMode==WAL_NORMAL_MODE ){
  47417. pWal->exclusiveMode = WAL_EXCLUSIVE_MODE;
  47418. }
  47419. rc = sqlite3WalCheckpoint(
  47420. pWal, SQLITE_CHECKPOINT_PASSIVE, 0, 0, sync_flags, nBuf, zBuf, 0, 0
  47421. );
  47422. if( rc==SQLITE_OK ){
  47423. int bPersist = -1;
  47424. sqlite3OsFileControlHint(
  47425. pWal->pDbFd, SQLITE_FCNTL_PERSIST_WAL, &bPersist
  47426. );
  47427. if( bPersist!=1 ){
  47428. /* Try to delete the WAL file if the checkpoint completed and
  47429. ** fsyned (rc==SQLITE_OK) and if we are not in persistent-wal
  47430. ** mode (!bPersist) */
  47431. isDelete = 1;
  47432. }else if( pWal->mxWalSize>=0 ){
  47433. /* Try to truncate the WAL file to zero bytes if the checkpoint
  47434. ** completed and fsynced (rc==SQLITE_OK) and we are in persistent
  47435. ** WAL mode (bPersist) and if the PRAGMA journal_size_limit is a
  47436. ** non-negative value (pWal->mxWalSize>=0). Note that we truncate
  47437. ** to zero bytes as truncating to the journal_size_limit might
  47438. ** leave a corrupt WAL file on disk. */
  47439. walLimitSize(pWal, 0);
  47440. }
  47441. }
  47442. }
  47443. walIndexClose(pWal, isDelete);
  47444. sqlite3OsClose(pWal->pWalFd);
  47445. if( isDelete ){
  47446. sqlite3BeginBenignMalloc();
  47447. sqlite3OsDelete(pWal->pVfs, pWal->zWalName, 0);
  47448. sqlite3EndBenignMalloc();
  47449. }
  47450. WALTRACE(("WAL%p: closed\n", pWal));
  47451. sqlite3_free((void *)pWal->apWiData);
  47452. sqlite3_free(pWal);
  47453. }
  47454. return rc;
  47455. }
  47456. /*
  47457. ** Try to read the wal-index header. Return 0 on success and 1 if
  47458. ** there is a problem.
  47459. **
  47460. ** The wal-index is in shared memory. Another thread or process might
  47461. ** be writing the header at the same time this procedure is trying to
  47462. ** read it, which might result in inconsistency. A dirty read is detected
  47463. ** by verifying that both copies of the header are the same and also by
  47464. ** a checksum on the header.
  47465. **
  47466. ** If and only if the read is consistent and the header is different from
  47467. ** pWal->hdr, then pWal->hdr is updated to the content of the new header
  47468. ** and *pChanged is set to 1.
  47469. **
  47470. ** If the checksum cannot be verified return non-zero. If the header
  47471. ** is read successfully and the checksum verified, return zero.
  47472. */
  47473. static int walIndexTryHdr(Wal *pWal, int *pChanged){
  47474. u32 aCksum[2]; /* Checksum on the header content */
  47475. WalIndexHdr h1, h2; /* Two copies of the header content */
  47476. WalIndexHdr volatile *aHdr; /* Header in shared memory */
  47477. /* The first page of the wal-index must be mapped at this point. */
  47478. assert( pWal->nWiData>0 && pWal->apWiData[0] );
  47479. /* Read the header. This might happen concurrently with a write to the
  47480. ** same area of shared memory on a different CPU in a SMP,
  47481. ** meaning it is possible that an inconsistent snapshot is read
  47482. ** from the file. If this happens, return non-zero.
  47483. **
  47484. ** There are two copies of the header at the beginning of the wal-index.
  47485. ** When reading, read [0] first then [1]. Writes are in the reverse order.
  47486. ** Memory barriers are used to prevent the compiler or the hardware from
  47487. ** reordering the reads and writes.
  47488. */
  47489. aHdr = walIndexHdr(pWal);
  47490. memcpy(&h1, (void *)&aHdr[0], sizeof(h1));
  47491. walShmBarrier(pWal);
  47492. memcpy(&h2, (void *)&aHdr[1], sizeof(h2));
  47493. if( memcmp(&h1, &h2, sizeof(h1))!=0 ){
  47494. return 1; /* Dirty read */
  47495. }
  47496. if( h1.isInit==0 ){
  47497. return 1; /* Malformed header - probably all zeros */
  47498. }
  47499. walChecksumBytes(1, (u8*)&h1, sizeof(h1)-sizeof(h1.aCksum), 0, aCksum);
  47500. if( aCksum[0]!=h1.aCksum[0] || aCksum[1]!=h1.aCksum[1] ){
  47501. return 1; /* Checksum does not match */
  47502. }
  47503. if( memcmp(&pWal->hdr, &h1, sizeof(WalIndexHdr)) ){
  47504. *pChanged = 1;
  47505. memcpy(&pWal->hdr, &h1, sizeof(WalIndexHdr));
  47506. pWal->szPage = (pWal->hdr.szPage&0xfe00) + ((pWal->hdr.szPage&0x0001)<<16);
  47507. testcase( pWal->szPage<=32768 );
  47508. testcase( pWal->szPage>=65536 );
  47509. }
  47510. /* The header was successfully read. Return zero. */
  47511. return 0;
  47512. }
  47513. /*
  47514. ** Read the wal-index header from the wal-index and into pWal->hdr.
  47515. ** If the wal-header appears to be corrupt, try to reconstruct the
  47516. ** wal-index from the WAL before returning.
  47517. **
  47518. ** Set *pChanged to 1 if the wal-index header value in pWal->hdr is
  47519. ** changed by this operation. If pWal->hdr is unchanged, set *pChanged
  47520. ** to 0.
  47521. **
  47522. ** If the wal-index header is successfully read, return SQLITE_OK.
  47523. ** Otherwise an SQLite error code.
  47524. */
  47525. static int walIndexReadHdr(Wal *pWal, int *pChanged){
  47526. int rc; /* Return code */
  47527. int badHdr; /* True if a header read failed */
  47528. volatile u32 *page0; /* Chunk of wal-index containing header */
  47529. /* Ensure that page 0 of the wal-index (the page that contains the
  47530. ** wal-index header) is mapped. Return early if an error occurs here.
  47531. */
  47532. assert( pChanged );
  47533. rc = walIndexPage(pWal, 0, &page0);
  47534. if( rc!=SQLITE_OK ){
  47535. return rc;
  47536. };
  47537. assert( page0 || pWal->writeLock==0 );
  47538. /* If the first page of the wal-index has been mapped, try to read the
  47539. ** wal-index header immediately, without holding any lock. This usually
  47540. ** works, but may fail if the wal-index header is corrupt or currently
  47541. ** being modified by another thread or process.
  47542. */
  47543. badHdr = (page0 ? walIndexTryHdr(pWal, pChanged) : 1);
  47544. /* If the first attempt failed, it might have been due to a race
  47545. ** with a writer. So get a WRITE lock and try again.
  47546. */
  47547. assert( badHdr==0 || pWal->writeLock==0 );
  47548. if( badHdr ){
  47549. if( pWal->readOnly & WAL_SHM_RDONLY ){
  47550. if( SQLITE_OK==(rc = walLockShared(pWal, WAL_WRITE_LOCK)) ){
  47551. walUnlockShared(pWal, WAL_WRITE_LOCK);
  47552. rc = SQLITE_READONLY_RECOVERY;
  47553. }
  47554. }else if( SQLITE_OK==(rc = walLockExclusive(pWal, WAL_WRITE_LOCK, 1, 1)) ){
  47555. pWal->writeLock = 1;
  47556. if( SQLITE_OK==(rc = walIndexPage(pWal, 0, &page0)) ){
  47557. badHdr = walIndexTryHdr(pWal, pChanged);
  47558. if( badHdr ){
  47559. /* If the wal-index header is still malformed even while holding
  47560. ** a WRITE lock, it can only mean that the header is corrupted and
  47561. ** needs to be reconstructed. So run recovery to do exactly that.
  47562. */
  47563. rc = walIndexRecover(pWal);
  47564. *pChanged = 1;
  47565. }
  47566. }
  47567. pWal->writeLock = 0;
  47568. walUnlockExclusive(pWal, WAL_WRITE_LOCK, 1);
  47569. }
  47570. }
  47571. /* If the header is read successfully, check the version number to make
  47572. ** sure the wal-index was not constructed with some future format that
  47573. ** this version of SQLite cannot understand.
  47574. */
  47575. if( badHdr==0 && pWal->hdr.iVersion!=WALINDEX_MAX_VERSION ){
  47576. rc = SQLITE_CANTOPEN_BKPT;
  47577. }
  47578. return rc;
  47579. }
  47580. /*
  47581. ** This is the value that walTryBeginRead returns when it needs to
  47582. ** be retried.
  47583. */
  47584. #define WAL_RETRY (-1)
  47585. /*
  47586. ** Attempt to start a read transaction. This might fail due to a race or
  47587. ** other transient condition. When that happens, it returns WAL_RETRY to
  47588. ** indicate to the caller that it is safe to retry immediately.
  47589. **
  47590. ** On success return SQLITE_OK. On a permanent failure (such an
  47591. ** I/O error or an SQLITE_BUSY because another process is running
  47592. ** recovery) return a positive error code.
  47593. **
  47594. ** The useWal parameter is true to force the use of the WAL and disable
  47595. ** the case where the WAL is bypassed because it has been completely
  47596. ** checkpointed. If useWal==0 then this routine calls walIndexReadHdr()
  47597. ** to make a copy of the wal-index header into pWal->hdr. If the
  47598. ** wal-index header has changed, *pChanged is set to 1 (as an indication
  47599. ** to the caller that the local paget cache is obsolete and needs to be
  47600. ** flushed.) When useWal==1, the wal-index header is assumed to already
  47601. ** be loaded and the pChanged parameter is unused.
  47602. **
  47603. ** The caller must set the cnt parameter to the number of prior calls to
  47604. ** this routine during the current read attempt that returned WAL_RETRY.
  47605. ** This routine will start taking more aggressive measures to clear the
  47606. ** race conditions after multiple WAL_RETRY returns, and after an excessive
  47607. ** number of errors will ultimately return SQLITE_PROTOCOL. The
  47608. ** SQLITE_PROTOCOL return indicates that some other process has gone rogue
  47609. ** and is not honoring the locking protocol. There is a vanishingly small
  47610. ** chance that SQLITE_PROTOCOL could be returned because of a run of really
  47611. ** bad luck when there is lots of contention for the wal-index, but that
  47612. ** possibility is so small that it can be safely neglected, we believe.
  47613. **
  47614. ** On success, this routine obtains a read lock on
  47615. ** WAL_READ_LOCK(pWal->readLock). The pWal->readLock integer is
  47616. ** in the range 0 <= pWal->readLock < WAL_NREADER. If pWal->readLock==(-1)
  47617. ** that means the Wal does not hold any read lock. The reader must not
  47618. ** access any database page that is modified by a WAL frame up to and
  47619. ** including frame number aReadMark[pWal->readLock]. The reader will
  47620. ** use WAL frames up to and including pWal->hdr.mxFrame if pWal->readLock>0
  47621. ** Or if pWal->readLock==0, then the reader will ignore the WAL
  47622. ** completely and get all content directly from the database file.
  47623. ** If the useWal parameter is 1 then the WAL will never be ignored and
  47624. ** this routine will always set pWal->readLock>0 on success.
  47625. ** When the read transaction is completed, the caller must release the
  47626. ** lock on WAL_READ_LOCK(pWal->readLock) and set pWal->readLock to -1.
  47627. **
  47628. ** This routine uses the nBackfill and aReadMark[] fields of the header
  47629. ** to select a particular WAL_READ_LOCK() that strives to let the
  47630. ** checkpoint process do as much work as possible. This routine might
  47631. ** update values of the aReadMark[] array in the header, but if it does
  47632. ** so it takes care to hold an exclusive lock on the corresponding
  47633. ** WAL_READ_LOCK() while changing values.
  47634. */
  47635. static int walTryBeginRead(Wal *pWal, int *pChanged, int useWal, int cnt){
  47636. volatile WalCkptInfo *pInfo; /* Checkpoint information in wal-index */
  47637. u32 mxReadMark; /* Largest aReadMark[] value */
  47638. int mxI; /* Index of largest aReadMark[] value */
  47639. int i; /* Loop counter */
  47640. int rc = SQLITE_OK; /* Return code */
  47641. assert( pWal->readLock<0 ); /* Not currently locked */
  47642. /* Take steps to avoid spinning forever if there is a protocol error.
  47643. **
  47644. ** Circumstances that cause a RETRY should only last for the briefest
  47645. ** instances of time. No I/O or other system calls are done while the
  47646. ** locks are held, so the locks should not be held for very long. But
  47647. ** if we are unlucky, another process that is holding a lock might get
  47648. ** paged out or take a page-fault that is time-consuming to resolve,
  47649. ** during the few nanoseconds that it is holding the lock. In that case,
  47650. ** it might take longer than normal for the lock to free.
  47651. **
  47652. ** After 5 RETRYs, we begin calling sqlite3OsSleep(). The first few
  47653. ** calls to sqlite3OsSleep() have a delay of 1 microsecond. Really this
  47654. ** is more of a scheduler yield than an actual delay. But on the 10th
  47655. ** an subsequent retries, the delays start becoming longer and longer,
  47656. ** so that on the 100th (and last) RETRY we delay for 323 milliseconds.
  47657. ** The total delay time before giving up is less than 10 seconds.
  47658. */
  47659. if( cnt>5 ){
  47660. int nDelay = 1; /* Pause time in microseconds */
  47661. if( cnt>100 ){
  47662. VVA_ONLY( pWal->lockError = 1; )
  47663. return SQLITE_PROTOCOL;
  47664. }
  47665. if( cnt>=10 ) nDelay = (cnt-9)*(cnt-9)*39;
  47666. sqlite3OsSleep(pWal->pVfs, nDelay);
  47667. }
  47668. if( !useWal ){
  47669. rc = walIndexReadHdr(pWal, pChanged);
  47670. if( rc==SQLITE_BUSY ){
  47671. /* If there is not a recovery running in another thread or process
  47672. ** then convert BUSY errors to WAL_RETRY. If recovery is known to
  47673. ** be running, convert BUSY to BUSY_RECOVERY. There is a race here
  47674. ** which might cause WAL_RETRY to be returned even if BUSY_RECOVERY
  47675. ** would be technically correct. But the race is benign since with
  47676. ** WAL_RETRY this routine will be called again and will probably be
  47677. ** right on the second iteration.
  47678. */
  47679. if( pWal->apWiData[0]==0 ){
  47680. /* This branch is taken when the xShmMap() method returns SQLITE_BUSY.
  47681. ** We assume this is a transient condition, so return WAL_RETRY. The
  47682. ** xShmMap() implementation used by the default unix and win32 VFS
  47683. ** modules may return SQLITE_BUSY due to a race condition in the
  47684. ** code that determines whether or not the shared-memory region
  47685. ** must be zeroed before the requested page is returned.
  47686. */
  47687. rc = WAL_RETRY;
  47688. }else if( SQLITE_OK==(rc = walLockShared(pWal, WAL_RECOVER_LOCK)) ){
  47689. walUnlockShared(pWal, WAL_RECOVER_LOCK);
  47690. rc = WAL_RETRY;
  47691. }else if( rc==SQLITE_BUSY ){
  47692. rc = SQLITE_BUSY_RECOVERY;
  47693. }
  47694. }
  47695. if( rc!=SQLITE_OK ){
  47696. return rc;
  47697. }
  47698. }
  47699. pInfo = walCkptInfo(pWal);
  47700. if( !useWal && pInfo->nBackfill==pWal->hdr.mxFrame ){
  47701. /* The WAL has been completely backfilled (or it is empty).
  47702. ** and can be safely ignored.
  47703. */
  47704. rc = walLockShared(pWal, WAL_READ_LOCK(0));
  47705. walShmBarrier(pWal);
  47706. if( rc==SQLITE_OK ){
  47707. if( memcmp((void *)walIndexHdr(pWal), &pWal->hdr, sizeof(WalIndexHdr)) ){
  47708. /* It is not safe to allow the reader to continue here if frames
  47709. ** may have been appended to the log before READ_LOCK(0) was obtained.
  47710. ** When holding READ_LOCK(0), the reader ignores the entire log file,
  47711. ** which implies that the database file contains a trustworthy
  47712. ** snapshot. Since holding READ_LOCK(0) prevents a checkpoint from
  47713. ** happening, this is usually correct.
  47714. **
  47715. ** However, if frames have been appended to the log (or if the log
  47716. ** is wrapped and written for that matter) before the READ_LOCK(0)
  47717. ** is obtained, that is not necessarily true. A checkpointer may
  47718. ** have started to backfill the appended frames but crashed before
  47719. ** it finished. Leaving a corrupt image in the database file.
  47720. */
  47721. walUnlockShared(pWal, WAL_READ_LOCK(0));
  47722. return WAL_RETRY;
  47723. }
  47724. pWal->readLock = 0;
  47725. return SQLITE_OK;
  47726. }else if( rc!=SQLITE_BUSY ){
  47727. return rc;
  47728. }
  47729. }
  47730. /* If we get this far, it means that the reader will want to use
  47731. ** the WAL to get at content from recent commits. The job now is
  47732. ** to select one of the aReadMark[] entries that is closest to
  47733. ** but not exceeding pWal->hdr.mxFrame and lock that entry.
  47734. */
  47735. mxReadMark = 0;
  47736. mxI = 0;
  47737. for(i=1; i<WAL_NREADER; i++){
  47738. u32 thisMark = pInfo->aReadMark[i];
  47739. if( mxReadMark<=thisMark && thisMark<=pWal->hdr.mxFrame ){
  47740. assert( thisMark!=READMARK_NOT_USED );
  47741. mxReadMark = thisMark;
  47742. mxI = i;
  47743. }
  47744. }
  47745. /* There was once an "if" here. The extra "{" is to preserve indentation. */
  47746. {
  47747. if( (pWal->readOnly & WAL_SHM_RDONLY)==0
  47748. && (mxReadMark<pWal->hdr.mxFrame || mxI==0)
  47749. ){
  47750. for(i=1; i<WAL_NREADER; i++){
  47751. rc = walLockExclusive(pWal, WAL_READ_LOCK(i), 1, 0);
  47752. if( rc==SQLITE_OK ){
  47753. mxReadMark = pInfo->aReadMark[i] = pWal->hdr.mxFrame;
  47754. mxI = i;
  47755. walUnlockExclusive(pWal, WAL_READ_LOCK(i), 1);
  47756. break;
  47757. }else if( rc!=SQLITE_BUSY ){
  47758. return rc;
  47759. }
  47760. }
  47761. }
  47762. if( mxI==0 ){
  47763. assert( rc==SQLITE_BUSY || (pWal->readOnly & WAL_SHM_RDONLY)!=0 );
  47764. return rc==SQLITE_BUSY ? WAL_RETRY : SQLITE_READONLY_CANTLOCK;
  47765. }
  47766. rc = walLockShared(pWal, WAL_READ_LOCK(mxI));
  47767. if( rc ){
  47768. return rc==SQLITE_BUSY ? WAL_RETRY : rc;
  47769. }
  47770. /* Now that the read-lock has been obtained, check that neither the
  47771. ** value in the aReadMark[] array or the contents of the wal-index
  47772. ** header have changed.
  47773. **
  47774. ** It is necessary to check that the wal-index header did not change
  47775. ** between the time it was read and when the shared-lock was obtained
  47776. ** on WAL_READ_LOCK(mxI) was obtained to account for the possibility
  47777. ** that the log file may have been wrapped by a writer, or that frames
  47778. ** that occur later in the log than pWal->hdr.mxFrame may have been
  47779. ** copied into the database by a checkpointer. If either of these things
  47780. ** happened, then reading the database with the current value of
  47781. ** pWal->hdr.mxFrame risks reading a corrupted snapshot. So, retry
  47782. ** instead.
  47783. **
  47784. ** This does not guarantee that the copy of the wal-index header is up to
  47785. ** date before proceeding. That would not be possible without somehow
  47786. ** blocking writers. It only guarantees that a dangerous checkpoint or
  47787. ** log-wrap (either of which would require an exclusive lock on
  47788. ** WAL_READ_LOCK(mxI)) has not occurred since the snapshot was valid.
  47789. */
  47790. walShmBarrier(pWal);
  47791. if( pInfo->aReadMark[mxI]!=mxReadMark
  47792. || memcmp((void *)walIndexHdr(pWal), &pWal->hdr, sizeof(WalIndexHdr))
  47793. ){
  47794. walUnlockShared(pWal, WAL_READ_LOCK(mxI));
  47795. return WAL_RETRY;
  47796. }else{
  47797. assert( mxReadMark<=pWal->hdr.mxFrame );
  47798. pWal->readLock = (i16)mxI;
  47799. }
  47800. }
  47801. return rc;
  47802. }
  47803. /*
  47804. ** Begin a read transaction on the database.
  47805. **
  47806. ** This routine used to be called sqlite3OpenSnapshot() and with good reason:
  47807. ** it takes a snapshot of the state of the WAL and wal-index for the current
  47808. ** instant in time. The current thread will continue to use this snapshot.
  47809. ** Other threads might append new content to the WAL and wal-index but
  47810. ** that extra content is ignored by the current thread.
  47811. **
  47812. ** If the database contents have changes since the previous read
  47813. ** transaction, then *pChanged is set to 1 before returning. The
  47814. ** Pager layer will use this to know that is cache is stale and
  47815. ** needs to be flushed.
  47816. */
  47817. SQLITE_PRIVATE int sqlite3WalBeginReadTransaction(Wal *pWal, int *pChanged){
  47818. int rc; /* Return code */
  47819. int cnt = 0; /* Number of TryBeginRead attempts */
  47820. do{
  47821. rc = walTryBeginRead(pWal, pChanged, 0, ++cnt);
  47822. }while( rc==WAL_RETRY );
  47823. testcase( (rc&0xff)==SQLITE_BUSY );
  47824. testcase( (rc&0xff)==SQLITE_IOERR );
  47825. testcase( rc==SQLITE_PROTOCOL );
  47826. testcase( rc==SQLITE_OK );
  47827. return rc;
  47828. }
  47829. /*
  47830. ** Finish with a read transaction. All this does is release the
  47831. ** read-lock.
  47832. */
  47833. SQLITE_PRIVATE void sqlite3WalEndReadTransaction(Wal *pWal){
  47834. sqlite3WalEndWriteTransaction(pWal);
  47835. if( pWal->readLock>=0 ){
  47836. walUnlockShared(pWal, WAL_READ_LOCK(pWal->readLock));
  47837. pWal->readLock = -1;
  47838. }
  47839. }
  47840. /*
  47841. ** Search the wal file for page pgno. If found, set *piRead to the frame that
  47842. ** contains the page. Otherwise, if pgno is not in the wal file, set *piRead
  47843. ** to zero.
  47844. **
  47845. ** Return SQLITE_OK if successful, or an error code if an error occurs. If an
  47846. ** error does occur, the final value of *piRead is undefined.
  47847. */
  47848. SQLITE_PRIVATE int sqlite3WalFindFrame(
  47849. Wal *pWal, /* WAL handle */
  47850. Pgno pgno, /* Database page number to read data for */
  47851. u32 *piRead /* OUT: Frame number (or zero) */
  47852. ){
  47853. u32 iRead = 0; /* If !=0, WAL frame to return data from */
  47854. u32 iLast = pWal->hdr.mxFrame; /* Last page in WAL for this reader */
  47855. int iHash; /* Used to loop through N hash tables */
  47856. /* This routine is only be called from within a read transaction. */
  47857. assert( pWal->readLock>=0 || pWal->lockError );
  47858. /* If the "last page" field of the wal-index header snapshot is 0, then
  47859. ** no data will be read from the wal under any circumstances. Return early
  47860. ** in this case as an optimization. Likewise, if pWal->readLock==0,
  47861. ** then the WAL is ignored by the reader so return early, as if the
  47862. ** WAL were empty.
  47863. */
  47864. if( iLast==0 || pWal->readLock==0 ){
  47865. *piRead = 0;
  47866. return SQLITE_OK;
  47867. }
  47868. /* Search the hash table or tables for an entry matching page number
  47869. ** pgno. Each iteration of the following for() loop searches one
  47870. ** hash table (each hash table indexes up to HASHTABLE_NPAGE frames).
  47871. **
  47872. ** This code might run concurrently to the code in walIndexAppend()
  47873. ** that adds entries to the wal-index (and possibly to this hash
  47874. ** table). This means the value just read from the hash
  47875. ** slot (aHash[iKey]) may have been added before or after the
  47876. ** current read transaction was opened. Values added after the
  47877. ** read transaction was opened may have been written incorrectly -
  47878. ** i.e. these slots may contain garbage data. However, we assume
  47879. ** that any slots written before the current read transaction was
  47880. ** opened remain unmodified.
  47881. **
  47882. ** For the reasons above, the if(...) condition featured in the inner
  47883. ** loop of the following block is more stringent that would be required
  47884. ** if we had exclusive access to the hash-table:
  47885. **
  47886. ** (aPgno[iFrame]==pgno):
  47887. ** This condition filters out normal hash-table collisions.
  47888. **
  47889. ** (iFrame<=iLast):
  47890. ** This condition filters out entries that were added to the hash
  47891. ** table after the current read-transaction had started.
  47892. */
  47893. for(iHash=walFramePage(iLast); iHash>=0 && iRead==0; iHash--){
  47894. volatile ht_slot *aHash; /* Pointer to hash table */
  47895. volatile u32 *aPgno; /* Pointer to array of page numbers */
  47896. u32 iZero; /* Frame number corresponding to aPgno[0] */
  47897. int iKey; /* Hash slot index */
  47898. int nCollide; /* Number of hash collisions remaining */
  47899. int rc; /* Error code */
  47900. rc = walHashGet(pWal, iHash, &aHash, &aPgno, &iZero);
  47901. if( rc!=SQLITE_OK ){
  47902. return rc;
  47903. }
  47904. nCollide = HASHTABLE_NSLOT;
  47905. for(iKey=walHash(pgno); aHash[iKey]; iKey=walNextHash(iKey)){
  47906. u32 iFrame = aHash[iKey] + iZero;
  47907. if( iFrame<=iLast && aPgno[aHash[iKey]]==pgno ){
  47908. assert( iFrame>iRead || CORRUPT_DB );
  47909. iRead = iFrame;
  47910. }
  47911. if( (nCollide--)==0 ){
  47912. return SQLITE_CORRUPT_BKPT;
  47913. }
  47914. }
  47915. }
  47916. #ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
  47917. /* If expensive assert() statements are available, do a linear search
  47918. ** of the wal-index file content. Make sure the results agree with the
  47919. ** result obtained using the hash indexes above. */
  47920. {
  47921. u32 iRead2 = 0;
  47922. u32 iTest;
  47923. for(iTest=iLast; iTest>0; iTest--){
  47924. if( walFramePgno(pWal, iTest)==pgno ){
  47925. iRead2 = iTest;
  47926. break;
  47927. }
  47928. }
  47929. assert( iRead==iRead2 );
  47930. }
  47931. #endif
  47932. *piRead = iRead;
  47933. return SQLITE_OK;
  47934. }
  47935. /*
  47936. ** Read the contents of frame iRead from the wal file into buffer pOut
  47937. ** (which is nOut bytes in size). Return SQLITE_OK if successful, or an
  47938. ** error code otherwise.
  47939. */
  47940. SQLITE_PRIVATE int sqlite3WalReadFrame(
  47941. Wal *pWal, /* WAL handle */
  47942. u32 iRead, /* Frame to read */
  47943. int nOut, /* Size of buffer pOut in bytes */
  47944. u8 *pOut /* Buffer to write page data to */
  47945. ){
  47946. int sz;
  47947. i64 iOffset;
  47948. sz = pWal->hdr.szPage;
  47949. sz = (sz&0xfe00) + ((sz&0x0001)<<16);
  47950. testcase( sz<=32768 );
  47951. testcase( sz>=65536 );
  47952. iOffset = walFrameOffset(iRead, sz) + WAL_FRAME_HDRSIZE;
  47953. /* testcase( IS_BIG_INT(iOffset) ); // requires a 4GiB WAL */
  47954. return sqlite3OsRead(pWal->pWalFd, pOut, (nOut>sz ? sz : nOut), iOffset);
  47955. }
  47956. /*
  47957. ** Return the size of the database in pages (or zero, if unknown).
  47958. */
  47959. SQLITE_PRIVATE Pgno sqlite3WalDbsize(Wal *pWal){
  47960. if( pWal && ALWAYS(pWal->readLock>=0) ){
  47961. return pWal->hdr.nPage;
  47962. }
  47963. return 0;
  47964. }
  47965. /*
  47966. ** This function starts a write transaction on the WAL.
  47967. **
  47968. ** A read transaction must have already been started by a prior call
  47969. ** to sqlite3WalBeginReadTransaction().
  47970. **
  47971. ** If another thread or process has written into the database since
  47972. ** the read transaction was started, then it is not possible for this
  47973. ** thread to write as doing so would cause a fork. So this routine
  47974. ** returns SQLITE_BUSY in that case and no write transaction is started.
  47975. **
  47976. ** There can only be a single writer active at a time.
  47977. */
  47978. SQLITE_PRIVATE int sqlite3WalBeginWriteTransaction(Wal *pWal){
  47979. int rc;
  47980. /* Cannot start a write transaction without first holding a read
  47981. ** transaction. */
  47982. assert( pWal->readLock>=0 );
  47983. if( pWal->readOnly ){
  47984. return SQLITE_READONLY;
  47985. }
  47986. /* Only one writer allowed at a time. Get the write lock. Return
  47987. ** SQLITE_BUSY if unable.
  47988. */
  47989. rc = walLockExclusive(pWal, WAL_WRITE_LOCK, 1, 0);
  47990. if( rc ){
  47991. return rc;
  47992. }
  47993. pWal->writeLock = 1;
  47994. /* If another connection has written to the database file since the
  47995. ** time the read transaction on this connection was started, then
  47996. ** the write is disallowed.
  47997. */
  47998. if( memcmp(&pWal->hdr, (void *)walIndexHdr(pWal), sizeof(WalIndexHdr))!=0 ){
  47999. walUnlockExclusive(pWal, WAL_WRITE_LOCK, 1);
  48000. pWal->writeLock = 0;
  48001. rc = SQLITE_BUSY_SNAPSHOT;
  48002. }
  48003. return rc;
  48004. }
  48005. /*
  48006. ** End a write transaction. The commit has already been done. This
  48007. ** routine merely releases the lock.
  48008. */
  48009. SQLITE_PRIVATE int sqlite3WalEndWriteTransaction(Wal *pWal){
  48010. if( pWal->writeLock ){
  48011. walUnlockExclusive(pWal, WAL_WRITE_LOCK, 1);
  48012. pWal->writeLock = 0;
  48013. pWal->truncateOnCommit = 0;
  48014. }
  48015. return SQLITE_OK;
  48016. }
  48017. /*
  48018. ** If any data has been written (but not committed) to the log file, this
  48019. ** function moves the write-pointer back to the start of the transaction.
  48020. **
  48021. ** Additionally, the callback function is invoked for each frame written
  48022. ** to the WAL since the start of the transaction. If the callback returns
  48023. ** other than SQLITE_OK, it is not invoked again and the error code is
  48024. ** returned to the caller.
  48025. **
  48026. ** Otherwise, if the callback function does not return an error, this
  48027. ** function returns SQLITE_OK.
  48028. */
  48029. SQLITE_PRIVATE int sqlite3WalUndo(Wal *pWal, int (*xUndo)(void *, Pgno), void *pUndoCtx){
  48030. int rc = SQLITE_OK;
  48031. if( ALWAYS(pWal->writeLock) ){
  48032. Pgno iMax = pWal->hdr.mxFrame;
  48033. Pgno iFrame;
  48034. /* Restore the clients cache of the wal-index header to the state it
  48035. ** was in before the client began writing to the database.
  48036. */
  48037. memcpy(&pWal->hdr, (void *)walIndexHdr(pWal), sizeof(WalIndexHdr));
  48038. for(iFrame=pWal->hdr.mxFrame+1;
  48039. ALWAYS(rc==SQLITE_OK) && iFrame<=iMax;
  48040. iFrame++
  48041. ){
  48042. /* This call cannot fail. Unless the page for which the page number
  48043. ** is passed as the second argument is (a) in the cache and
  48044. ** (b) has an outstanding reference, then xUndo is either a no-op
  48045. ** (if (a) is false) or simply expels the page from the cache (if (b)
  48046. ** is false).
  48047. **
  48048. ** If the upper layer is doing a rollback, it is guaranteed that there
  48049. ** are no outstanding references to any page other than page 1. And
  48050. ** page 1 is never written to the log until the transaction is
  48051. ** committed. As a result, the call to xUndo may not fail.
  48052. */
  48053. assert( walFramePgno(pWal, iFrame)!=1 );
  48054. rc = xUndo(pUndoCtx, walFramePgno(pWal, iFrame));
  48055. }
  48056. if( iMax!=pWal->hdr.mxFrame ) walCleanupHash(pWal);
  48057. }
  48058. return rc;
  48059. }
  48060. /*
  48061. ** Argument aWalData must point to an array of WAL_SAVEPOINT_NDATA u32
  48062. ** values. This function populates the array with values required to
  48063. ** "rollback" the write position of the WAL handle back to the current
  48064. ** point in the event of a savepoint rollback (via WalSavepointUndo()).
  48065. */
  48066. SQLITE_PRIVATE void sqlite3WalSavepoint(Wal *pWal, u32 *aWalData){
  48067. assert( pWal->writeLock );
  48068. aWalData[0] = pWal->hdr.mxFrame;
  48069. aWalData[1] = pWal->hdr.aFrameCksum[0];
  48070. aWalData[2] = pWal->hdr.aFrameCksum[1];
  48071. aWalData[3] = pWal->nCkpt;
  48072. }
  48073. /*
  48074. ** Move the write position of the WAL back to the point identified by
  48075. ** the values in the aWalData[] array. aWalData must point to an array
  48076. ** of WAL_SAVEPOINT_NDATA u32 values that has been previously populated
  48077. ** by a call to WalSavepoint().
  48078. */
  48079. SQLITE_PRIVATE int sqlite3WalSavepointUndo(Wal *pWal, u32 *aWalData){
  48080. int rc = SQLITE_OK;
  48081. assert( pWal->writeLock );
  48082. assert( aWalData[3]!=pWal->nCkpt || aWalData[0]<=pWal->hdr.mxFrame );
  48083. if( aWalData[3]!=pWal->nCkpt ){
  48084. /* This savepoint was opened immediately after the write-transaction
  48085. ** was started. Right after that, the writer decided to wrap around
  48086. ** to the start of the log. Update the savepoint values to match.
  48087. */
  48088. aWalData[0] = 0;
  48089. aWalData[3] = pWal->nCkpt;
  48090. }
  48091. if( aWalData[0]<pWal->hdr.mxFrame ){
  48092. pWal->hdr.mxFrame = aWalData[0];
  48093. pWal->hdr.aFrameCksum[0] = aWalData[1];
  48094. pWal->hdr.aFrameCksum[1] = aWalData[2];
  48095. walCleanupHash(pWal);
  48096. }
  48097. return rc;
  48098. }
  48099. /*
  48100. ** This function is called just before writing a set of frames to the log
  48101. ** file (see sqlite3WalFrames()). It checks to see if, instead of appending
  48102. ** to the current log file, it is possible to overwrite the start of the
  48103. ** existing log file with the new frames (i.e. "reset" the log). If so,
  48104. ** it sets pWal->hdr.mxFrame to 0. Otherwise, pWal->hdr.mxFrame is left
  48105. ** unchanged.
  48106. **
  48107. ** SQLITE_OK is returned if no error is encountered (regardless of whether
  48108. ** or not pWal->hdr.mxFrame is modified). An SQLite error code is returned
  48109. ** if an error occurs.
  48110. */
  48111. static int walRestartLog(Wal *pWal){
  48112. int rc = SQLITE_OK;
  48113. int cnt;
  48114. if( pWal->readLock==0 ){
  48115. volatile WalCkptInfo *pInfo = walCkptInfo(pWal);
  48116. assert( pInfo->nBackfill==pWal->hdr.mxFrame );
  48117. if( pInfo->nBackfill>0 ){
  48118. u32 salt1;
  48119. sqlite3_randomness(4, &salt1);
  48120. rc = walLockExclusive(pWal, WAL_READ_LOCK(1), WAL_NREADER-1, 0);
  48121. if( rc==SQLITE_OK ){
  48122. /* If all readers are using WAL_READ_LOCK(0) (in other words if no
  48123. ** readers are currently using the WAL), then the transactions
  48124. ** frames will overwrite the start of the existing log. Update the
  48125. ** wal-index header to reflect this.
  48126. **
  48127. ** In theory it would be Ok to update the cache of the header only
  48128. ** at this point. But updating the actual wal-index header is also
  48129. ** safe and means there is no special case for sqlite3WalUndo()
  48130. ** to handle if this transaction is rolled back. */
  48131. walRestartHdr(pWal, salt1);
  48132. walUnlockExclusive(pWal, WAL_READ_LOCK(1), WAL_NREADER-1);
  48133. }else if( rc!=SQLITE_BUSY ){
  48134. return rc;
  48135. }
  48136. }
  48137. walUnlockShared(pWal, WAL_READ_LOCK(0));
  48138. pWal->readLock = -1;
  48139. cnt = 0;
  48140. do{
  48141. int notUsed;
  48142. rc = walTryBeginRead(pWal, &notUsed, 1, ++cnt);
  48143. }while( rc==WAL_RETRY );
  48144. assert( (rc&0xff)!=SQLITE_BUSY ); /* BUSY not possible when useWal==1 */
  48145. testcase( (rc&0xff)==SQLITE_IOERR );
  48146. testcase( rc==SQLITE_PROTOCOL );
  48147. testcase( rc==SQLITE_OK );
  48148. }
  48149. return rc;
  48150. }
  48151. /*
  48152. ** Information about the current state of the WAL file and where
  48153. ** the next fsync should occur - passed from sqlite3WalFrames() into
  48154. ** walWriteToLog().
  48155. */
  48156. typedef struct WalWriter {
  48157. Wal *pWal; /* The complete WAL information */
  48158. sqlite3_file *pFd; /* The WAL file to which we write */
  48159. sqlite3_int64 iSyncPoint; /* Fsync at this offset */
  48160. int syncFlags; /* Flags for the fsync */
  48161. int szPage; /* Size of one page */
  48162. } WalWriter;
  48163. /*
  48164. ** Write iAmt bytes of content into the WAL file beginning at iOffset.
  48165. ** Do a sync when crossing the p->iSyncPoint boundary.
  48166. **
  48167. ** In other words, if iSyncPoint is in between iOffset and iOffset+iAmt,
  48168. ** first write the part before iSyncPoint, then sync, then write the
  48169. ** rest.
  48170. */
  48171. static int walWriteToLog(
  48172. WalWriter *p, /* WAL to write to */
  48173. void *pContent, /* Content to be written */
  48174. int iAmt, /* Number of bytes to write */
  48175. sqlite3_int64 iOffset /* Start writing at this offset */
  48176. ){
  48177. int rc;
  48178. if( iOffset<p->iSyncPoint && iOffset+iAmt>=p->iSyncPoint ){
  48179. int iFirstAmt = (int)(p->iSyncPoint - iOffset);
  48180. rc = sqlite3OsWrite(p->pFd, pContent, iFirstAmt, iOffset);
  48181. if( rc ) return rc;
  48182. iOffset += iFirstAmt;
  48183. iAmt -= iFirstAmt;
  48184. pContent = (void*)(iFirstAmt + (char*)pContent);
  48185. assert( p->syncFlags & (SQLITE_SYNC_NORMAL|SQLITE_SYNC_FULL) );
  48186. rc = sqlite3OsSync(p->pFd, p->syncFlags & SQLITE_SYNC_MASK);
  48187. if( iAmt==0 || rc ) return rc;
  48188. }
  48189. rc = sqlite3OsWrite(p->pFd, pContent, iAmt, iOffset);
  48190. return rc;
  48191. }
  48192. /*
  48193. ** Write out a single frame of the WAL
  48194. */
  48195. static int walWriteOneFrame(
  48196. WalWriter *p, /* Where to write the frame */
  48197. PgHdr *pPage, /* The page of the frame to be written */
  48198. int nTruncate, /* The commit flag. Usually 0. >0 for commit */
  48199. sqlite3_int64 iOffset /* Byte offset at which to write */
  48200. ){
  48201. int rc; /* Result code from subfunctions */
  48202. void *pData; /* Data actually written */
  48203. u8 aFrame[WAL_FRAME_HDRSIZE]; /* Buffer to assemble frame-header in */
  48204. #if defined(SQLITE_HAS_CODEC)
  48205. if( (pData = sqlite3PagerCodec(pPage))==0 ) return SQLITE_NOMEM;
  48206. #else
  48207. pData = pPage->pData;
  48208. #endif
  48209. walEncodeFrame(p->pWal, pPage->pgno, nTruncate, pData, aFrame);
  48210. rc = walWriteToLog(p, aFrame, sizeof(aFrame), iOffset);
  48211. if( rc ) return rc;
  48212. /* Write the page data */
  48213. rc = walWriteToLog(p, pData, p->szPage, iOffset+sizeof(aFrame));
  48214. return rc;
  48215. }
  48216. /*
  48217. ** Write a set of frames to the log. The caller must hold the write-lock
  48218. ** on the log file (obtained using sqlite3WalBeginWriteTransaction()).
  48219. */
  48220. SQLITE_PRIVATE int sqlite3WalFrames(
  48221. Wal *pWal, /* Wal handle to write to */
  48222. int szPage, /* Database page-size in bytes */
  48223. PgHdr *pList, /* List of dirty pages to write */
  48224. Pgno nTruncate, /* Database size after this commit */
  48225. int isCommit, /* True if this is a commit */
  48226. int sync_flags /* Flags to pass to OsSync() (or 0) */
  48227. ){
  48228. int rc; /* Used to catch return codes */
  48229. u32 iFrame; /* Next frame address */
  48230. PgHdr *p; /* Iterator to run through pList with. */
  48231. PgHdr *pLast = 0; /* Last frame in list */
  48232. int nExtra = 0; /* Number of extra copies of last page */
  48233. int szFrame; /* The size of a single frame */
  48234. i64 iOffset; /* Next byte to write in WAL file */
  48235. WalWriter w; /* The writer */
  48236. assert( pList );
  48237. assert( pWal->writeLock );
  48238. /* If this frame set completes a transaction, then nTruncate>0. If
  48239. ** nTruncate==0 then this frame set does not complete the transaction. */
  48240. assert( (isCommit!=0)==(nTruncate!=0) );
  48241. #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
  48242. { int cnt; for(cnt=0, p=pList; p; p=p->pDirty, cnt++){}
  48243. WALTRACE(("WAL%p: frame write begin. %d frames. mxFrame=%d. %s\n",
  48244. pWal, cnt, pWal->hdr.mxFrame, isCommit ? "Commit" : "Spill"));
  48245. }
  48246. #endif
  48247. /* See if it is possible to write these frames into the start of the
  48248. ** log file, instead of appending to it at pWal->hdr.mxFrame.
  48249. */
  48250. if( SQLITE_OK!=(rc = walRestartLog(pWal)) ){
  48251. return rc;
  48252. }
  48253. /* If this is the first frame written into the log, write the WAL
  48254. ** header to the start of the WAL file. See comments at the top of
  48255. ** this source file for a description of the WAL header format.
  48256. */
  48257. iFrame = pWal->hdr.mxFrame;
  48258. if( iFrame==0 ){
  48259. u8 aWalHdr[WAL_HDRSIZE]; /* Buffer to assemble wal-header in */
  48260. u32 aCksum[2]; /* Checksum for wal-header */
  48261. sqlite3Put4byte(&aWalHdr[0], (WAL_MAGIC | SQLITE_BIGENDIAN));
  48262. sqlite3Put4byte(&aWalHdr[4], WAL_MAX_VERSION);
  48263. sqlite3Put4byte(&aWalHdr[8], szPage);
  48264. sqlite3Put4byte(&aWalHdr[12], pWal->nCkpt);
  48265. if( pWal->nCkpt==0 ) sqlite3_randomness(8, pWal->hdr.aSalt);
  48266. memcpy(&aWalHdr[16], pWal->hdr.aSalt, 8);
  48267. walChecksumBytes(1, aWalHdr, WAL_HDRSIZE-2*4, 0, aCksum);
  48268. sqlite3Put4byte(&aWalHdr[24], aCksum[0]);
  48269. sqlite3Put4byte(&aWalHdr[28], aCksum[1]);
  48270. pWal->szPage = szPage;
  48271. pWal->hdr.bigEndCksum = SQLITE_BIGENDIAN;
  48272. pWal->hdr.aFrameCksum[0] = aCksum[0];
  48273. pWal->hdr.aFrameCksum[1] = aCksum[1];
  48274. pWal->truncateOnCommit = 1;
  48275. rc = sqlite3OsWrite(pWal->pWalFd, aWalHdr, sizeof(aWalHdr), 0);
  48276. WALTRACE(("WAL%p: wal-header write %s\n", pWal, rc ? "failed" : "ok"));
  48277. if( rc!=SQLITE_OK ){
  48278. return rc;
  48279. }
  48280. /* Sync the header (unless SQLITE_IOCAP_SEQUENTIAL is true or unless
  48281. ** all syncing is turned off by PRAGMA synchronous=OFF). Otherwise
  48282. ** an out-of-order write following a WAL restart could result in
  48283. ** database corruption. See the ticket:
  48284. **
  48285. ** http://localhost:591/sqlite/info/ff5be73dee
  48286. */
  48287. if( pWal->syncHeader && sync_flags ){
  48288. rc = sqlite3OsSync(pWal->pWalFd, sync_flags & SQLITE_SYNC_MASK);
  48289. if( rc ) return rc;
  48290. }
  48291. }
  48292. assert( (int)pWal->szPage==szPage );
  48293. /* Setup information needed to write frames into the WAL */
  48294. w.pWal = pWal;
  48295. w.pFd = pWal->pWalFd;
  48296. w.iSyncPoint = 0;
  48297. w.syncFlags = sync_flags;
  48298. w.szPage = szPage;
  48299. iOffset = walFrameOffset(iFrame+1, szPage);
  48300. szFrame = szPage + WAL_FRAME_HDRSIZE;
  48301. /* Write all frames into the log file exactly once */
  48302. for(p=pList; p; p=p->pDirty){
  48303. int nDbSize; /* 0 normally. Positive == commit flag */
  48304. iFrame++;
  48305. assert( iOffset==walFrameOffset(iFrame, szPage) );
  48306. nDbSize = (isCommit && p->pDirty==0) ? nTruncate : 0;
  48307. rc = walWriteOneFrame(&w, p, nDbSize, iOffset);
  48308. if( rc ) return rc;
  48309. pLast = p;
  48310. iOffset += szFrame;
  48311. }
  48312. /* If this is the end of a transaction, then we might need to pad
  48313. ** the transaction and/or sync the WAL file.
  48314. **
  48315. ** Padding and syncing only occur if this set of frames complete a
  48316. ** transaction and if PRAGMA synchronous=FULL. If synchronous==NORMAL
  48317. ** or synchronous==OFF, then no padding or syncing are needed.
  48318. **
  48319. ** If SQLITE_IOCAP_POWERSAFE_OVERWRITE is defined, then padding is not
  48320. ** needed and only the sync is done. If padding is needed, then the
  48321. ** final frame is repeated (with its commit mark) until the next sector
  48322. ** boundary is crossed. Only the part of the WAL prior to the last
  48323. ** sector boundary is synced; the part of the last frame that extends
  48324. ** past the sector boundary is written after the sync.
  48325. */
  48326. if( isCommit && (sync_flags & WAL_SYNC_TRANSACTIONS)!=0 ){
  48327. if( pWal->padToSectorBoundary ){
  48328. int sectorSize = sqlite3SectorSize(pWal->pWalFd);
  48329. w.iSyncPoint = ((iOffset+sectorSize-1)/sectorSize)*sectorSize;
  48330. while( iOffset<w.iSyncPoint ){
  48331. rc = walWriteOneFrame(&w, pLast, nTruncate, iOffset);
  48332. if( rc ) return rc;
  48333. iOffset += szFrame;
  48334. nExtra++;
  48335. }
  48336. }else{
  48337. rc = sqlite3OsSync(w.pFd, sync_flags & SQLITE_SYNC_MASK);
  48338. }
  48339. }
  48340. /* If this frame set completes the first transaction in the WAL and
  48341. ** if PRAGMA journal_size_limit is set, then truncate the WAL to the
  48342. ** journal size limit, if possible.
  48343. */
  48344. if( isCommit && pWal->truncateOnCommit && pWal->mxWalSize>=0 ){
  48345. i64 sz = pWal->mxWalSize;
  48346. if( walFrameOffset(iFrame+nExtra+1, szPage)>pWal->mxWalSize ){
  48347. sz = walFrameOffset(iFrame+nExtra+1, szPage);
  48348. }
  48349. walLimitSize(pWal, sz);
  48350. pWal->truncateOnCommit = 0;
  48351. }
  48352. /* Append data to the wal-index. It is not necessary to lock the
  48353. ** wal-index to do this as the SQLITE_SHM_WRITE lock held on the wal-index
  48354. ** guarantees that there are no other writers, and no data that may
  48355. ** be in use by existing readers is being overwritten.
  48356. */
  48357. iFrame = pWal->hdr.mxFrame;
  48358. for(p=pList; p && rc==SQLITE_OK; p=p->pDirty){
  48359. iFrame++;
  48360. rc = walIndexAppend(pWal, iFrame, p->pgno);
  48361. }
  48362. while( rc==SQLITE_OK && nExtra>0 ){
  48363. iFrame++;
  48364. nExtra--;
  48365. rc = walIndexAppend(pWal, iFrame, pLast->pgno);
  48366. }
  48367. if( rc==SQLITE_OK ){
  48368. /* Update the private copy of the header. */
  48369. pWal->hdr.szPage = (u16)((szPage&0xff00) | (szPage>>16));
  48370. testcase( szPage<=32768 );
  48371. testcase( szPage>=65536 );
  48372. pWal->hdr.mxFrame = iFrame;
  48373. if( isCommit ){
  48374. pWal->hdr.iChange++;
  48375. pWal->hdr.nPage = nTruncate;
  48376. }
  48377. /* If this is a commit, update the wal-index header too. */
  48378. if( isCommit ){
  48379. walIndexWriteHdr(pWal);
  48380. pWal->iCallback = iFrame;
  48381. }
  48382. }
  48383. WALTRACE(("WAL%p: frame write %s\n", pWal, rc ? "failed" : "ok"));
  48384. return rc;
  48385. }
  48386. /*
  48387. ** This routine is called to implement sqlite3_wal_checkpoint() and
  48388. ** related interfaces.
  48389. **
  48390. ** Obtain a CHECKPOINT lock and then backfill as much information as
  48391. ** we can from WAL into the database.
  48392. **
  48393. ** If parameter xBusy is not NULL, it is a pointer to a busy-handler
  48394. ** callback. In this case this function runs a blocking checkpoint.
  48395. */
  48396. SQLITE_PRIVATE int sqlite3WalCheckpoint(
  48397. Wal *pWal, /* Wal connection */
  48398. int eMode, /* PASSIVE, FULL, RESTART, or TRUNCATE */
  48399. int (*xBusy)(void*), /* Function to call when busy */
  48400. void *pBusyArg, /* Context argument for xBusyHandler */
  48401. int sync_flags, /* Flags to sync db file with (or 0) */
  48402. int nBuf, /* Size of temporary buffer */
  48403. u8 *zBuf, /* Temporary buffer to use */
  48404. int *pnLog, /* OUT: Number of frames in WAL */
  48405. int *pnCkpt /* OUT: Number of backfilled frames in WAL */
  48406. ){
  48407. int rc; /* Return code */
  48408. int isChanged = 0; /* True if a new wal-index header is loaded */
  48409. int eMode2 = eMode; /* Mode to pass to walCheckpoint() */
  48410. int (*xBusy2)(void*) = xBusy; /* Busy handler for eMode2 */
  48411. assert( pWal->ckptLock==0 );
  48412. assert( pWal->writeLock==0 );
  48413. /* EVIDENCE-OF: R-62920-47450 The busy-handler callback is never invoked
  48414. ** in the SQLITE_CHECKPOINT_PASSIVE mode. */
  48415. assert( eMode!=SQLITE_CHECKPOINT_PASSIVE || xBusy==0 );
  48416. if( pWal->readOnly ) return SQLITE_READONLY;
  48417. WALTRACE(("WAL%p: checkpoint begins\n", pWal));
  48418. /* IMPLEMENTATION-OF: R-62028-47212 All calls obtain an exclusive
  48419. ** "checkpoint" lock on the database file. */
  48420. rc = walLockExclusive(pWal, WAL_CKPT_LOCK, 1, 0);
  48421. if( rc ){
  48422. /* EVIDENCE-OF: R-10421-19736 If any other process is running a
  48423. ** checkpoint operation at the same time, the lock cannot be obtained and
  48424. ** SQLITE_BUSY is returned.
  48425. ** EVIDENCE-OF: R-53820-33897 Even if there is a busy-handler configured,
  48426. ** it will not be invoked in this case.
  48427. */
  48428. testcase( rc==SQLITE_BUSY );
  48429. testcase( xBusy!=0 );
  48430. return rc;
  48431. }
  48432. pWal->ckptLock = 1;
  48433. /* IMPLEMENTATION-OF: R-59782-36818 The SQLITE_CHECKPOINT_FULL, RESTART and
  48434. ** TRUNCATE modes also obtain the exclusive "writer" lock on the database
  48435. ** file.
  48436. **
  48437. ** EVIDENCE-OF: R-60642-04082 If the writer lock cannot be obtained
  48438. ** immediately, and a busy-handler is configured, it is invoked and the
  48439. ** writer lock retried until either the busy-handler returns 0 or the
  48440. ** lock is successfully obtained.
  48441. */
  48442. if( eMode!=SQLITE_CHECKPOINT_PASSIVE ){
  48443. rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_WRITE_LOCK, 1);
  48444. if( rc==SQLITE_OK ){
  48445. pWal->writeLock = 1;
  48446. }else if( rc==SQLITE_BUSY ){
  48447. eMode2 = SQLITE_CHECKPOINT_PASSIVE;
  48448. xBusy2 = 0;
  48449. rc = SQLITE_OK;
  48450. }
  48451. }
  48452. /* Read the wal-index header. */
  48453. if( rc==SQLITE_OK ){
  48454. rc = walIndexReadHdr(pWal, &isChanged);
  48455. if( isChanged && pWal->pDbFd->pMethods->iVersion>=3 ){
  48456. sqlite3OsUnfetch(pWal->pDbFd, 0, 0);
  48457. }
  48458. }
  48459. /* Copy data from the log to the database file. */
  48460. if( rc==SQLITE_OK ){
  48461. if( pWal->hdr.mxFrame && walPagesize(pWal)!=nBuf ){
  48462. rc = SQLITE_CORRUPT_BKPT;
  48463. }else{
  48464. rc = walCheckpoint(pWal, eMode2, xBusy2, pBusyArg, sync_flags, zBuf);
  48465. }
  48466. /* If no error occurred, set the output variables. */
  48467. if( rc==SQLITE_OK || rc==SQLITE_BUSY ){
  48468. if( pnLog ) *pnLog = (int)pWal->hdr.mxFrame;
  48469. if( pnCkpt ) *pnCkpt = (int)(walCkptInfo(pWal)->nBackfill);
  48470. }
  48471. }
  48472. if( isChanged ){
  48473. /* If a new wal-index header was loaded before the checkpoint was
  48474. ** performed, then the pager-cache associated with pWal is now
  48475. ** out of date. So zero the cached wal-index header to ensure that
  48476. ** next time the pager opens a snapshot on this database it knows that
  48477. ** the cache needs to be reset.
  48478. */
  48479. memset(&pWal->hdr, 0, sizeof(WalIndexHdr));
  48480. }
  48481. /* Release the locks. */
  48482. sqlite3WalEndWriteTransaction(pWal);
  48483. walUnlockExclusive(pWal, WAL_CKPT_LOCK, 1);
  48484. pWal->ckptLock = 0;
  48485. WALTRACE(("WAL%p: checkpoint %s\n", pWal, rc ? "failed" : "ok"));
  48486. return (rc==SQLITE_OK && eMode!=eMode2 ? SQLITE_BUSY : rc);
  48487. }
  48488. /* Return the value to pass to a sqlite3_wal_hook callback, the
  48489. ** number of frames in the WAL at the point of the last commit since
  48490. ** sqlite3WalCallback() was called. If no commits have occurred since
  48491. ** the last call, then return 0.
  48492. */
  48493. SQLITE_PRIVATE int sqlite3WalCallback(Wal *pWal){
  48494. u32 ret = 0;
  48495. if( pWal ){
  48496. ret = pWal->iCallback;
  48497. pWal->iCallback = 0;
  48498. }
  48499. return (int)ret;
  48500. }
  48501. /*
  48502. ** This function is called to change the WAL subsystem into or out
  48503. ** of locking_mode=EXCLUSIVE.
  48504. **
  48505. ** If op is zero, then attempt to change from locking_mode=EXCLUSIVE
  48506. ** into locking_mode=NORMAL. This means that we must acquire a lock
  48507. ** on the pWal->readLock byte. If the WAL is already in locking_mode=NORMAL
  48508. ** or if the acquisition of the lock fails, then return 0. If the
  48509. ** transition out of exclusive-mode is successful, return 1. This
  48510. ** operation must occur while the pager is still holding the exclusive
  48511. ** lock on the main database file.
  48512. **
  48513. ** If op is one, then change from locking_mode=NORMAL into
  48514. ** locking_mode=EXCLUSIVE. This means that the pWal->readLock must
  48515. ** be released. Return 1 if the transition is made and 0 if the
  48516. ** WAL is already in exclusive-locking mode - meaning that this
  48517. ** routine is a no-op. The pager must already hold the exclusive lock
  48518. ** on the main database file before invoking this operation.
  48519. **
  48520. ** If op is negative, then do a dry-run of the op==1 case but do
  48521. ** not actually change anything. The pager uses this to see if it
  48522. ** should acquire the database exclusive lock prior to invoking
  48523. ** the op==1 case.
  48524. */
  48525. SQLITE_PRIVATE int sqlite3WalExclusiveMode(Wal *pWal, int op){
  48526. int rc;
  48527. assert( pWal->writeLock==0 );
  48528. assert( pWal->exclusiveMode!=WAL_HEAPMEMORY_MODE || op==-1 );
  48529. /* pWal->readLock is usually set, but might be -1 if there was a
  48530. ** prior error while attempting to acquire are read-lock. This cannot
  48531. ** happen if the connection is actually in exclusive mode (as no xShmLock
  48532. ** locks are taken in this case). Nor should the pager attempt to
  48533. ** upgrade to exclusive-mode following such an error.
  48534. */
  48535. assert( pWal->readLock>=0 || pWal->lockError );
  48536. assert( pWal->readLock>=0 || (op<=0 && pWal->exclusiveMode==0) );
  48537. if( op==0 ){
  48538. if( pWal->exclusiveMode ){
  48539. pWal->exclusiveMode = 0;
  48540. if( walLockShared(pWal, WAL_READ_LOCK(pWal->readLock))!=SQLITE_OK ){
  48541. pWal->exclusiveMode = 1;
  48542. }
  48543. rc = pWal->exclusiveMode==0;
  48544. }else{
  48545. /* Already in locking_mode=NORMAL */
  48546. rc = 0;
  48547. }
  48548. }else if( op>0 ){
  48549. assert( pWal->exclusiveMode==0 );
  48550. assert( pWal->readLock>=0 );
  48551. walUnlockShared(pWal, WAL_READ_LOCK(pWal->readLock));
  48552. pWal->exclusiveMode = 1;
  48553. rc = 1;
  48554. }else{
  48555. rc = pWal->exclusiveMode==0;
  48556. }
  48557. return rc;
  48558. }
  48559. /*
  48560. ** Return true if the argument is non-NULL and the WAL module is using
  48561. ** heap-memory for the wal-index. Otherwise, if the argument is NULL or the
  48562. ** WAL module is using shared-memory, return false.
  48563. */
  48564. SQLITE_PRIVATE int sqlite3WalHeapMemory(Wal *pWal){
  48565. return (pWal && pWal->exclusiveMode==WAL_HEAPMEMORY_MODE );
  48566. }
  48567. #ifdef SQLITE_ENABLE_ZIPVFS
  48568. /*
  48569. ** If the argument is not NULL, it points to a Wal object that holds a
  48570. ** read-lock. This function returns the database page-size if it is known,
  48571. ** or zero if it is not (or if pWal is NULL).
  48572. */
  48573. SQLITE_PRIVATE int sqlite3WalFramesize(Wal *pWal){
  48574. assert( pWal==0 || pWal->readLock>=0 );
  48575. return (pWal ? pWal->szPage : 0);
  48576. }
  48577. #endif
  48578. #endif /* #ifndef SQLITE_OMIT_WAL */
  48579. /************** End of wal.c *************************************************/
  48580. /************** Begin file btmutex.c *****************************************/
  48581. /*
  48582. ** 2007 August 27
  48583. **
  48584. ** The author disclaims copyright to this source code. In place of
  48585. ** a legal notice, here is a blessing:
  48586. **
  48587. ** May you do good and not evil.
  48588. ** May you find forgiveness for yourself and forgive others.
  48589. ** May you share freely, never taking more than you give.
  48590. **
  48591. *************************************************************************
  48592. **
  48593. ** This file contains code used to implement mutexes on Btree objects.
  48594. ** This code really belongs in btree.c. But btree.c is getting too
  48595. ** big and we want to break it down some. This packaged seemed like
  48596. ** a good breakout.
  48597. */
  48598. /************** Include btreeInt.h in the middle of btmutex.c ****************/
  48599. /************** Begin file btreeInt.h ****************************************/
  48600. /*
  48601. ** 2004 April 6
  48602. **
  48603. ** The author disclaims copyright to this source code. In place of
  48604. ** a legal notice, here is a blessing:
  48605. **
  48606. ** May you do good and not evil.
  48607. ** May you find forgiveness for yourself and forgive others.
  48608. ** May you share freely, never taking more than you give.
  48609. **
  48610. *************************************************************************
  48611. ** This file implements an external (disk-based) database using BTrees.
  48612. ** For a detailed discussion of BTrees, refer to
  48613. **
  48614. ** Donald E. Knuth, THE ART OF COMPUTER PROGRAMMING, Volume 3:
  48615. ** "Sorting And Searching", pages 473-480. Addison-Wesley
  48616. ** Publishing Company, Reading, Massachusetts.
  48617. **
  48618. ** The basic idea is that each page of the file contains N database
  48619. ** entries and N+1 pointers to subpages.
  48620. **
  48621. ** ----------------------------------------------------------------
  48622. ** | Ptr(0) | Key(0) | Ptr(1) | Key(1) | ... | Key(N-1) | Ptr(N) |
  48623. ** ----------------------------------------------------------------
  48624. **
  48625. ** All of the keys on the page that Ptr(0) points to have values less
  48626. ** than Key(0). All of the keys on page Ptr(1) and its subpages have
  48627. ** values greater than Key(0) and less than Key(1). All of the keys
  48628. ** on Ptr(N) and its subpages have values greater than Key(N-1). And
  48629. ** so forth.
  48630. **
  48631. ** Finding a particular key requires reading O(log(M)) pages from the
  48632. ** disk where M is the number of entries in the tree.
  48633. **
  48634. ** In this implementation, a single file can hold one or more separate
  48635. ** BTrees. Each BTree is identified by the index of its root page. The
  48636. ** key and data for any entry are combined to form the "payload". A
  48637. ** fixed amount of payload can be carried directly on the database
  48638. ** page. If the payload is larger than the preset amount then surplus
  48639. ** bytes are stored on overflow pages. The payload for an entry
  48640. ** and the preceding pointer are combined to form a "Cell". Each
  48641. ** page has a small header which contains the Ptr(N) pointer and other
  48642. ** information such as the size of key and data.
  48643. **
  48644. ** FORMAT DETAILS
  48645. **
  48646. ** The file is divided into pages. The first page is called page 1,
  48647. ** the second is page 2, and so forth. A page number of zero indicates
  48648. ** "no such page". The page size can be any power of 2 between 512 and 65536.
  48649. ** Each page can be either a btree page, a freelist page, an overflow
  48650. ** page, or a pointer-map page.
  48651. **
  48652. ** The first page is always a btree page. The first 100 bytes of the first
  48653. ** page contain a special header (the "file header") that describes the file.
  48654. ** The format of the file header is as follows:
  48655. **
  48656. ** OFFSET SIZE DESCRIPTION
  48657. ** 0 16 Header string: "SQLite format 3\000"
  48658. ** 16 2 Page size in bytes. (1 means 65536)
  48659. ** 18 1 File format write version
  48660. ** 19 1 File format read version
  48661. ** 20 1 Bytes of unused space at the end of each page
  48662. ** 21 1 Max embedded payload fraction (must be 64)
  48663. ** 22 1 Min embedded payload fraction (must be 32)
  48664. ** 23 1 Min leaf payload fraction (must be 32)
  48665. ** 24 4 File change counter
  48666. ** 28 4 Reserved for future use
  48667. ** 32 4 First freelist page
  48668. ** 36 4 Number of freelist pages in the file
  48669. ** 40 60 15 4-byte meta values passed to higher layers
  48670. **
  48671. ** 40 4 Schema cookie
  48672. ** 44 4 File format of schema layer
  48673. ** 48 4 Size of page cache
  48674. ** 52 4 Largest root-page (auto/incr_vacuum)
  48675. ** 56 4 1=UTF-8 2=UTF16le 3=UTF16be
  48676. ** 60 4 User version
  48677. ** 64 4 Incremental vacuum mode
  48678. ** 68 4 Application-ID
  48679. ** 72 20 unused
  48680. ** 92 4 The version-valid-for number
  48681. ** 96 4 SQLITE_VERSION_NUMBER
  48682. **
  48683. ** All of the integer values are big-endian (most significant byte first).
  48684. **
  48685. ** The file change counter is incremented when the database is changed
  48686. ** This counter allows other processes to know when the file has changed
  48687. ** and thus when they need to flush their cache.
  48688. **
  48689. ** The max embedded payload fraction is the amount of the total usable
  48690. ** space in a page that can be consumed by a single cell for standard
  48691. ** B-tree (non-LEAFDATA) tables. A value of 255 means 100%. The default
  48692. ** is to limit the maximum cell size so that at least 4 cells will fit
  48693. ** on one page. Thus the default max embedded payload fraction is 64.
  48694. **
  48695. ** If the payload for a cell is larger than the max payload, then extra
  48696. ** payload is spilled to overflow pages. Once an overflow page is allocated,
  48697. ** as many bytes as possible are moved into the overflow pages without letting
  48698. ** the cell size drop below the min embedded payload fraction.
  48699. **
  48700. ** The min leaf payload fraction is like the min embedded payload fraction
  48701. ** except that it applies to leaf nodes in a LEAFDATA tree. The maximum
  48702. ** payload fraction for a LEAFDATA tree is always 100% (or 255) and it
  48703. ** not specified in the header.
  48704. **
  48705. ** Each btree pages is divided into three sections: The header, the
  48706. ** cell pointer array, and the cell content area. Page 1 also has a 100-byte
  48707. ** file header that occurs before the page header.
  48708. **
  48709. ** |----------------|
  48710. ** | file header | 100 bytes. Page 1 only.
  48711. ** |----------------|
  48712. ** | page header | 8 bytes for leaves. 12 bytes for interior nodes
  48713. ** |----------------|
  48714. ** | cell pointer | | 2 bytes per cell. Sorted order.
  48715. ** | array | | Grows downward
  48716. ** | | v
  48717. ** |----------------|
  48718. ** | unallocated |
  48719. ** | space |
  48720. ** |----------------| ^ Grows upwards
  48721. ** | cell content | | Arbitrary order interspersed with freeblocks.
  48722. ** | area | | and free space fragments.
  48723. ** |----------------|
  48724. **
  48725. ** The page headers looks like this:
  48726. **
  48727. ** OFFSET SIZE DESCRIPTION
  48728. ** 0 1 Flags. 1: intkey, 2: zerodata, 4: leafdata, 8: leaf
  48729. ** 1 2 byte offset to the first freeblock
  48730. ** 3 2 number of cells on this page
  48731. ** 5 2 first byte of the cell content area
  48732. ** 7 1 number of fragmented free bytes
  48733. ** 8 4 Right child (the Ptr(N) value). Omitted on leaves.
  48734. **
  48735. ** The flags define the format of this btree page. The leaf flag means that
  48736. ** this page has no children. The zerodata flag means that this page carries
  48737. ** only keys and no data. The intkey flag means that the key is an integer
  48738. ** which is stored in the key size entry of the cell header rather than in
  48739. ** the payload area.
  48740. **
  48741. ** The cell pointer array begins on the first byte after the page header.
  48742. ** The cell pointer array contains zero or more 2-byte numbers which are
  48743. ** offsets from the beginning of the page to the cell content in the cell
  48744. ** content area. The cell pointers occur in sorted order. The system strives
  48745. ** to keep free space after the last cell pointer so that new cells can
  48746. ** be easily added without having to defragment the page.
  48747. **
  48748. ** Cell content is stored at the very end of the page and grows toward the
  48749. ** beginning of the page.
  48750. **
  48751. ** Unused space within the cell content area is collected into a linked list of
  48752. ** freeblocks. Each freeblock is at least 4 bytes in size. The byte offset
  48753. ** to the first freeblock is given in the header. Freeblocks occur in
  48754. ** increasing order. Because a freeblock must be at least 4 bytes in size,
  48755. ** any group of 3 or fewer unused bytes in the cell content area cannot
  48756. ** exist on the freeblock chain. A group of 3 or fewer free bytes is called
  48757. ** a fragment. The total number of bytes in all fragments is recorded.
  48758. ** in the page header at offset 7.
  48759. **
  48760. ** SIZE DESCRIPTION
  48761. ** 2 Byte offset of the next freeblock
  48762. ** 2 Bytes in this freeblock
  48763. **
  48764. ** Cells are of variable length. Cells are stored in the cell content area at
  48765. ** the end of the page. Pointers to the cells are in the cell pointer array
  48766. ** that immediately follows the page header. Cells is not necessarily
  48767. ** contiguous or in order, but cell pointers are contiguous and in order.
  48768. **
  48769. ** Cell content makes use of variable length integers. A variable
  48770. ** length integer is 1 to 9 bytes where the lower 7 bits of each
  48771. ** byte are used. The integer consists of all bytes that have bit 8 set and
  48772. ** the first byte with bit 8 clear. The most significant byte of the integer
  48773. ** appears first. A variable-length integer may not be more than 9 bytes long.
  48774. ** As a special case, all 8 bytes of the 9th byte are used as data. This
  48775. ** allows a 64-bit integer to be encoded in 9 bytes.
  48776. **
  48777. ** 0x00 becomes 0x00000000
  48778. ** 0x7f becomes 0x0000007f
  48779. ** 0x81 0x00 becomes 0x00000080
  48780. ** 0x82 0x00 becomes 0x00000100
  48781. ** 0x80 0x7f becomes 0x0000007f
  48782. ** 0x8a 0x91 0xd1 0xac 0x78 becomes 0x12345678
  48783. ** 0x81 0x81 0x81 0x81 0x01 becomes 0x10204081
  48784. **
  48785. ** Variable length integers are used for rowids and to hold the number of
  48786. ** bytes of key and data in a btree cell.
  48787. **
  48788. ** The content of a cell looks like this:
  48789. **
  48790. ** SIZE DESCRIPTION
  48791. ** 4 Page number of the left child. Omitted if leaf flag is set.
  48792. ** var Number of bytes of data. Omitted if the zerodata flag is set.
  48793. ** var Number of bytes of key. Or the key itself if intkey flag is set.
  48794. ** * Payload
  48795. ** 4 First page of the overflow chain. Omitted if no overflow
  48796. **
  48797. ** Overflow pages form a linked list. Each page except the last is completely
  48798. ** filled with data (pagesize - 4 bytes). The last page can have as little
  48799. ** as 1 byte of data.
  48800. **
  48801. ** SIZE DESCRIPTION
  48802. ** 4 Page number of next overflow page
  48803. ** * Data
  48804. **
  48805. ** Freelist pages come in two subtypes: trunk pages and leaf pages. The
  48806. ** file header points to the first in a linked list of trunk page. Each trunk
  48807. ** page points to multiple leaf pages. The content of a leaf page is
  48808. ** unspecified. A trunk page looks like this:
  48809. **
  48810. ** SIZE DESCRIPTION
  48811. ** 4 Page number of next trunk page
  48812. ** 4 Number of leaf pointers on this page
  48813. ** * zero or more pages numbers of leaves
  48814. */
  48815. /* The following value is the maximum cell size assuming a maximum page
  48816. ** size give above.
  48817. */
  48818. #define MX_CELL_SIZE(pBt) ((int)(pBt->pageSize-8))
  48819. /* The maximum number of cells on a single page of the database. This
  48820. ** assumes a minimum cell size of 6 bytes (4 bytes for the cell itself
  48821. ** plus 2 bytes for the index to the cell in the page header). Such
  48822. ** small cells will be rare, but they are possible.
  48823. */
  48824. #define MX_CELL(pBt) ((pBt->pageSize-8)/6)
  48825. /* Forward declarations */
  48826. typedef struct MemPage MemPage;
  48827. typedef struct BtLock BtLock;
  48828. /*
  48829. ** This is a magic string that appears at the beginning of every
  48830. ** SQLite database in order to identify the file as a real database.
  48831. **
  48832. ** You can change this value at compile-time by specifying a
  48833. ** -DSQLITE_FILE_HEADER="..." on the compiler command-line. The
  48834. ** header must be exactly 16 bytes including the zero-terminator so
  48835. ** the string itself should be 15 characters long. If you change
  48836. ** the header, then your custom library will not be able to read
  48837. ** databases generated by the standard tools and the standard tools
  48838. ** will not be able to read databases created by your custom library.
  48839. */
  48840. #ifndef SQLITE_FILE_HEADER /* 123456789 123456 */
  48841. # define SQLITE_FILE_HEADER "SQLite format 3"
  48842. #endif
  48843. /*
  48844. ** Page type flags. An ORed combination of these flags appear as the
  48845. ** first byte of on-disk image of every BTree page.
  48846. */
  48847. #define PTF_INTKEY 0x01
  48848. #define PTF_ZERODATA 0x02
  48849. #define PTF_LEAFDATA 0x04
  48850. #define PTF_LEAF 0x08
  48851. /*
  48852. ** As each page of the file is loaded into memory, an instance of the following
  48853. ** structure is appended and initialized to zero. This structure stores
  48854. ** information about the page that is decoded from the raw file page.
  48855. **
  48856. ** The pParent field points back to the parent page. This allows us to
  48857. ** walk up the BTree from any leaf to the root. Care must be taken to
  48858. ** unref() the parent page pointer when this page is no longer referenced.
  48859. ** The pageDestructor() routine handles that chore.
  48860. **
  48861. ** Access to all fields of this structure is controlled by the mutex
  48862. ** stored in MemPage.pBt->mutex.
  48863. */
  48864. struct MemPage {
  48865. u8 isInit; /* True if previously initialized. MUST BE FIRST! */
  48866. u8 nOverflow; /* Number of overflow cell bodies in aCell[] */
  48867. u8 intKey; /* True if table b-trees. False for index b-trees */
  48868. u8 intKeyLeaf; /* True if the leaf of an intKey table */
  48869. u8 noPayload; /* True if internal intKey page (thus w/o data) */
  48870. u8 leaf; /* True if a leaf page */
  48871. u8 hdrOffset; /* 100 for page 1. 0 otherwise */
  48872. u8 childPtrSize; /* 0 if leaf==1. 4 if leaf==0 */
  48873. u8 max1bytePayload; /* min(maxLocal,127) */
  48874. u8 bBusy; /* Prevent endless loops on corrupt database files */
  48875. u16 maxLocal; /* Copy of BtShared.maxLocal or BtShared.maxLeaf */
  48876. u16 minLocal; /* Copy of BtShared.minLocal or BtShared.minLeaf */
  48877. u16 cellOffset; /* Index in aData of first cell pointer */
  48878. u16 nFree; /* Number of free bytes on the page */
  48879. u16 nCell; /* Number of cells on this page, local and ovfl */
  48880. u16 maskPage; /* Mask for page offset */
  48881. u16 aiOvfl[5]; /* Insert the i-th overflow cell before the aiOvfl-th
  48882. ** non-overflow cell */
  48883. u8 *apOvfl[5]; /* Pointers to the body of overflow cells */
  48884. BtShared *pBt; /* Pointer to BtShared that this page is part of */
  48885. u8 *aData; /* Pointer to disk image of the page data */
  48886. u8 *aDataEnd; /* One byte past the end of usable data */
  48887. u8 *aCellIdx; /* The cell index area */
  48888. DbPage *pDbPage; /* Pager page handle */
  48889. Pgno pgno; /* Page number for this page */
  48890. };
  48891. /*
  48892. ** The in-memory image of a disk page has the auxiliary information appended
  48893. ** to the end. EXTRA_SIZE is the number of bytes of space needed to hold
  48894. ** that extra information.
  48895. */
  48896. #define EXTRA_SIZE sizeof(MemPage)
  48897. /*
  48898. ** A linked list of the following structures is stored at BtShared.pLock.
  48899. ** Locks are added (or upgraded from READ_LOCK to WRITE_LOCK) when a cursor
  48900. ** is opened on the table with root page BtShared.iTable. Locks are removed
  48901. ** from this list when a transaction is committed or rolled back, or when
  48902. ** a btree handle is closed.
  48903. */
  48904. struct BtLock {
  48905. Btree *pBtree; /* Btree handle holding this lock */
  48906. Pgno iTable; /* Root page of table */
  48907. u8 eLock; /* READ_LOCK or WRITE_LOCK */
  48908. BtLock *pNext; /* Next in BtShared.pLock list */
  48909. };
  48910. /* Candidate values for BtLock.eLock */
  48911. #define READ_LOCK 1
  48912. #define WRITE_LOCK 2
  48913. /* A Btree handle
  48914. **
  48915. ** A database connection contains a pointer to an instance of
  48916. ** this object for every database file that it has open. This structure
  48917. ** is opaque to the database connection. The database connection cannot
  48918. ** see the internals of this structure and only deals with pointers to
  48919. ** this structure.
  48920. **
  48921. ** For some database files, the same underlying database cache might be
  48922. ** shared between multiple connections. In that case, each connection
  48923. ** has it own instance of this object. But each instance of this object
  48924. ** points to the same BtShared object. The database cache and the
  48925. ** schema associated with the database file are all contained within
  48926. ** the BtShared object.
  48927. **
  48928. ** All fields in this structure are accessed under sqlite3.mutex.
  48929. ** The pBt pointer itself may not be changed while there exists cursors
  48930. ** in the referenced BtShared that point back to this Btree since those
  48931. ** cursors have to go through this Btree to find their BtShared and
  48932. ** they often do so without holding sqlite3.mutex.
  48933. */
  48934. struct Btree {
  48935. sqlite3 *db; /* The database connection holding this btree */
  48936. BtShared *pBt; /* Sharable content of this btree */
  48937. u8 inTrans; /* TRANS_NONE, TRANS_READ or TRANS_WRITE */
  48938. u8 sharable; /* True if we can share pBt with another db */
  48939. u8 locked; /* True if db currently has pBt locked */
  48940. int wantToLock; /* Number of nested calls to sqlite3BtreeEnter() */
  48941. int nBackup; /* Number of backup operations reading this btree */
  48942. u32 iDataVersion; /* Combines with pBt->pPager->iDataVersion */
  48943. Btree *pNext; /* List of other sharable Btrees from the same db */
  48944. Btree *pPrev; /* Back pointer of the same list */
  48945. #ifndef SQLITE_OMIT_SHARED_CACHE
  48946. BtLock lock; /* Object used to lock page 1 */
  48947. #endif
  48948. };
  48949. /*
  48950. ** Btree.inTrans may take one of the following values.
  48951. **
  48952. ** If the shared-data extension is enabled, there may be multiple users
  48953. ** of the Btree structure. At most one of these may open a write transaction,
  48954. ** but any number may have active read transactions.
  48955. */
  48956. #define TRANS_NONE 0
  48957. #define TRANS_READ 1
  48958. #define TRANS_WRITE 2
  48959. /*
  48960. ** An instance of this object represents a single database file.
  48961. **
  48962. ** A single database file can be in use at the same time by two
  48963. ** or more database connections. When two or more connections are
  48964. ** sharing the same database file, each connection has it own
  48965. ** private Btree object for the file and each of those Btrees points
  48966. ** to this one BtShared object. BtShared.nRef is the number of
  48967. ** connections currently sharing this database file.
  48968. **
  48969. ** Fields in this structure are accessed under the BtShared.mutex
  48970. ** mutex, except for nRef and pNext which are accessed under the
  48971. ** global SQLITE_MUTEX_STATIC_MASTER mutex. The pPager field
  48972. ** may not be modified once it is initially set as long as nRef>0.
  48973. ** The pSchema field may be set once under BtShared.mutex and
  48974. ** thereafter is unchanged as long as nRef>0.
  48975. **
  48976. ** isPending:
  48977. **
  48978. ** If a BtShared client fails to obtain a write-lock on a database
  48979. ** table (because there exists one or more read-locks on the table),
  48980. ** the shared-cache enters 'pending-lock' state and isPending is
  48981. ** set to true.
  48982. **
  48983. ** The shared-cache leaves the 'pending lock' state when either of
  48984. ** the following occur:
  48985. **
  48986. ** 1) The current writer (BtShared.pWriter) concludes its transaction, OR
  48987. ** 2) The number of locks held by other connections drops to zero.
  48988. **
  48989. ** while in the 'pending-lock' state, no connection may start a new
  48990. ** transaction.
  48991. **
  48992. ** This feature is included to help prevent writer-starvation.
  48993. */
  48994. struct BtShared {
  48995. Pager *pPager; /* The page cache */
  48996. sqlite3 *db; /* Database connection currently using this Btree */
  48997. BtCursor *pCursor; /* A list of all open cursors */
  48998. MemPage *pPage1; /* First page of the database */
  48999. u8 openFlags; /* Flags to sqlite3BtreeOpen() */
  49000. #ifndef SQLITE_OMIT_AUTOVACUUM
  49001. u8 autoVacuum; /* True if auto-vacuum is enabled */
  49002. u8 incrVacuum; /* True if incr-vacuum is enabled */
  49003. u8 bDoTruncate; /* True to truncate db on commit */
  49004. #endif
  49005. u8 inTransaction; /* Transaction state */
  49006. u8 max1bytePayload; /* Maximum first byte of cell for a 1-byte payload */
  49007. #ifdef SQLITE_HAS_CODEC
  49008. u8 optimalReserve; /* Desired amount of reserved space per page */
  49009. #endif
  49010. u16 btsFlags; /* Boolean parameters. See BTS_* macros below */
  49011. u16 maxLocal; /* Maximum local payload in non-LEAFDATA tables */
  49012. u16 minLocal; /* Minimum local payload in non-LEAFDATA tables */
  49013. u16 maxLeaf; /* Maximum local payload in a LEAFDATA table */
  49014. u16 minLeaf; /* Minimum local payload in a LEAFDATA table */
  49015. u32 pageSize; /* Total number of bytes on a page */
  49016. u32 usableSize; /* Number of usable bytes on each page */
  49017. int nTransaction; /* Number of open transactions (read + write) */
  49018. u32 nPage; /* Number of pages in the database */
  49019. void *pSchema; /* Pointer to space allocated by sqlite3BtreeSchema() */
  49020. void (*xFreeSchema)(void*); /* Destructor for BtShared.pSchema */
  49021. sqlite3_mutex *mutex; /* Non-recursive mutex required to access this object */
  49022. Bitvec *pHasContent; /* Set of pages moved to free-list this transaction */
  49023. #ifndef SQLITE_OMIT_SHARED_CACHE
  49024. int nRef; /* Number of references to this structure */
  49025. BtShared *pNext; /* Next on a list of sharable BtShared structs */
  49026. BtLock *pLock; /* List of locks held on this shared-btree struct */
  49027. Btree *pWriter; /* Btree with currently open write transaction */
  49028. #endif
  49029. u8 *pTmpSpace; /* Temp space sufficient to hold a single cell */
  49030. };
  49031. /*
  49032. ** Allowed values for BtShared.btsFlags
  49033. */
  49034. #define BTS_READ_ONLY 0x0001 /* Underlying file is readonly */
  49035. #define BTS_PAGESIZE_FIXED 0x0002 /* Page size can no longer be changed */
  49036. #define BTS_SECURE_DELETE 0x0004 /* PRAGMA secure_delete is enabled */
  49037. #define BTS_INITIALLY_EMPTY 0x0008 /* Database was empty at trans start */
  49038. #define BTS_NO_WAL 0x0010 /* Do not open write-ahead-log files */
  49039. #define BTS_EXCLUSIVE 0x0020 /* pWriter has an exclusive lock */
  49040. #define BTS_PENDING 0x0040 /* Waiting for read-locks to clear */
  49041. /*
  49042. ** An instance of the following structure is used to hold information
  49043. ** about a cell. The parseCellPtr() function fills in this structure
  49044. ** based on information extract from the raw disk page.
  49045. */
  49046. typedef struct CellInfo CellInfo;
  49047. struct CellInfo {
  49048. i64 nKey; /* The key for INTKEY tables, or nPayload otherwise */
  49049. u8 *pPayload; /* Pointer to the start of payload */
  49050. u32 nPayload; /* Bytes of payload */
  49051. u16 nLocal; /* Amount of payload held locally, not on overflow */
  49052. u16 iOverflow; /* Offset to overflow page number. Zero if no overflow */
  49053. u16 nSize; /* Size of the cell content on the main b-tree page */
  49054. };
  49055. /*
  49056. ** Maximum depth of an SQLite B-Tree structure. Any B-Tree deeper than
  49057. ** this will be declared corrupt. This value is calculated based on a
  49058. ** maximum database size of 2^31 pages a minimum fanout of 2 for a
  49059. ** root-node and 3 for all other internal nodes.
  49060. **
  49061. ** If a tree that appears to be taller than this is encountered, it is
  49062. ** assumed that the database is corrupt.
  49063. */
  49064. #define BTCURSOR_MAX_DEPTH 20
  49065. /*
  49066. ** A cursor is a pointer to a particular entry within a particular
  49067. ** b-tree within a database file.
  49068. **
  49069. ** The entry is identified by its MemPage and the index in
  49070. ** MemPage.aCell[] of the entry.
  49071. **
  49072. ** A single database file can be shared by two more database connections,
  49073. ** but cursors cannot be shared. Each cursor is associated with a
  49074. ** particular database connection identified BtCursor.pBtree.db.
  49075. **
  49076. ** Fields in this structure are accessed under the BtShared.mutex
  49077. ** found at self->pBt->mutex.
  49078. **
  49079. ** skipNext meaning:
  49080. ** eState==SKIPNEXT && skipNext>0: Next sqlite3BtreeNext() is no-op.
  49081. ** eState==SKIPNEXT && skipNext<0: Next sqlite3BtreePrevious() is no-op.
  49082. ** eState==FAULT: Cursor fault with skipNext as error code.
  49083. */
  49084. struct BtCursor {
  49085. Btree *pBtree; /* The Btree to which this cursor belongs */
  49086. BtShared *pBt; /* The BtShared this cursor points to */
  49087. BtCursor *pNext, *pPrev; /* Forms a linked list of all cursors */
  49088. struct KeyInfo *pKeyInfo; /* Argument passed to comparison function */
  49089. Pgno *aOverflow; /* Cache of overflow page locations */
  49090. CellInfo info; /* A parse of the cell we are pointing at */
  49091. i64 nKey; /* Size of pKey, or last integer key */
  49092. void *pKey; /* Saved key that was cursor last known position */
  49093. Pgno pgnoRoot; /* The root page of this tree */
  49094. int nOvflAlloc; /* Allocated size of aOverflow[] array */
  49095. int skipNext; /* Prev() is noop if negative. Next() is noop if positive.
  49096. ** Error code if eState==CURSOR_FAULT */
  49097. u8 curFlags; /* zero or more BTCF_* flags defined below */
  49098. u8 eState; /* One of the CURSOR_XXX constants (see below) */
  49099. u8 hints; /* As configured by CursorSetHints() */
  49100. i16 iPage; /* Index of current page in apPage */
  49101. u16 aiIdx[BTCURSOR_MAX_DEPTH]; /* Current index in apPage[i] */
  49102. MemPage *apPage[BTCURSOR_MAX_DEPTH]; /* Pages from root to current page */
  49103. };
  49104. /*
  49105. ** Legal values for BtCursor.curFlags
  49106. */
  49107. #define BTCF_WriteFlag 0x01 /* True if a write cursor */
  49108. #define BTCF_ValidNKey 0x02 /* True if info.nKey is valid */
  49109. #define BTCF_ValidOvfl 0x04 /* True if aOverflow is valid */
  49110. #define BTCF_AtLast 0x08 /* Cursor is pointing ot the last entry */
  49111. #define BTCF_Incrblob 0x10 /* True if an incremental I/O handle */
  49112. /*
  49113. ** Potential values for BtCursor.eState.
  49114. **
  49115. ** CURSOR_INVALID:
  49116. ** Cursor does not point to a valid entry. This can happen (for example)
  49117. ** because the table is empty or because BtreeCursorFirst() has not been
  49118. ** called.
  49119. **
  49120. ** CURSOR_VALID:
  49121. ** Cursor points to a valid entry. getPayload() etc. may be called.
  49122. **
  49123. ** CURSOR_SKIPNEXT:
  49124. ** Cursor is valid except that the Cursor.skipNext field is non-zero
  49125. ** indicating that the next sqlite3BtreeNext() or sqlite3BtreePrevious()
  49126. ** operation should be a no-op.
  49127. **
  49128. ** CURSOR_REQUIRESEEK:
  49129. ** The table that this cursor was opened on still exists, but has been
  49130. ** modified since the cursor was last used. The cursor position is saved
  49131. ** in variables BtCursor.pKey and BtCursor.nKey. When a cursor is in
  49132. ** this state, restoreCursorPosition() can be called to attempt to
  49133. ** seek the cursor to the saved position.
  49134. **
  49135. ** CURSOR_FAULT:
  49136. ** An unrecoverable error (an I/O error or a malloc failure) has occurred
  49137. ** on a different connection that shares the BtShared cache with this
  49138. ** cursor. The error has left the cache in an inconsistent state.
  49139. ** Do nothing else with this cursor. Any attempt to use the cursor
  49140. ** should return the error code stored in BtCursor.skipNext
  49141. */
  49142. #define CURSOR_INVALID 0
  49143. #define CURSOR_VALID 1
  49144. #define CURSOR_SKIPNEXT 2
  49145. #define CURSOR_REQUIRESEEK 3
  49146. #define CURSOR_FAULT 4
  49147. /*
  49148. ** The database page the PENDING_BYTE occupies. This page is never used.
  49149. */
  49150. # define PENDING_BYTE_PAGE(pBt) PAGER_MJ_PGNO(pBt)
  49151. /*
  49152. ** These macros define the location of the pointer-map entry for a
  49153. ** database page. The first argument to each is the number of usable
  49154. ** bytes on each page of the database (often 1024). The second is the
  49155. ** page number to look up in the pointer map.
  49156. **
  49157. ** PTRMAP_PAGENO returns the database page number of the pointer-map
  49158. ** page that stores the required pointer. PTRMAP_PTROFFSET returns
  49159. ** the offset of the requested map entry.
  49160. **
  49161. ** If the pgno argument passed to PTRMAP_PAGENO is a pointer-map page,
  49162. ** then pgno is returned. So (pgno==PTRMAP_PAGENO(pgsz, pgno)) can be
  49163. ** used to test if pgno is a pointer-map page. PTRMAP_ISPAGE implements
  49164. ** this test.
  49165. */
  49166. #define PTRMAP_PAGENO(pBt, pgno) ptrmapPageno(pBt, pgno)
  49167. #define PTRMAP_PTROFFSET(pgptrmap, pgno) (5*(pgno-pgptrmap-1))
  49168. #define PTRMAP_ISPAGE(pBt, pgno) (PTRMAP_PAGENO((pBt),(pgno))==(pgno))
  49169. /*
  49170. ** The pointer map is a lookup table that identifies the parent page for
  49171. ** each child page in the database file. The parent page is the page that
  49172. ** contains a pointer to the child. Every page in the database contains
  49173. ** 0 or 1 parent pages. (In this context 'database page' refers
  49174. ** to any page that is not part of the pointer map itself.) Each pointer map
  49175. ** entry consists of a single byte 'type' and a 4 byte parent page number.
  49176. ** The PTRMAP_XXX identifiers below are the valid types.
  49177. **
  49178. ** The purpose of the pointer map is to facility moving pages from one
  49179. ** position in the file to another as part of autovacuum. When a page
  49180. ** is moved, the pointer in its parent must be updated to point to the
  49181. ** new location. The pointer map is used to locate the parent page quickly.
  49182. **
  49183. ** PTRMAP_ROOTPAGE: The database page is a root-page. The page-number is not
  49184. ** used in this case.
  49185. **
  49186. ** PTRMAP_FREEPAGE: The database page is an unused (free) page. The page-number
  49187. ** is not used in this case.
  49188. **
  49189. ** PTRMAP_OVERFLOW1: The database page is the first page in a list of
  49190. ** overflow pages. The page number identifies the page that
  49191. ** contains the cell with a pointer to this overflow page.
  49192. **
  49193. ** PTRMAP_OVERFLOW2: The database page is the second or later page in a list of
  49194. ** overflow pages. The page-number identifies the previous
  49195. ** page in the overflow page list.
  49196. **
  49197. ** PTRMAP_BTREE: The database page is a non-root btree page. The page number
  49198. ** identifies the parent page in the btree.
  49199. */
  49200. #define PTRMAP_ROOTPAGE 1
  49201. #define PTRMAP_FREEPAGE 2
  49202. #define PTRMAP_OVERFLOW1 3
  49203. #define PTRMAP_OVERFLOW2 4
  49204. #define PTRMAP_BTREE 5
  49205. /* A bunch of assert() statements to check the transaction state variables
  49206. ** of handle p (type Btree*) are internally consistent.
  49207. */
  49208. #define btreeIntegrity(p) \
  49209. assert( p->pBt->inTransaction!=TRANS_NONE || p->pBt->nTransaction==0 ); \
  49210. assert( p->pBt->inTransaction>=p->inTrans );
  49211. /*
  49212. ** The ISAUTOVACUUM macro is used within balance_nonroot() to determine
  49213. ** if the database supports auto-vacuum or not. Because it is used
  49214. ** within an expression that is an argument to another macro
  49215. ** (sqliteMallocRaw), it is not possible to use conditional compilation.
  49216. ** So, this macro is defined instead.
  49217. */
  49218. #ifndef SQLITE_OMIT_AUTOVACUUM
  49219. #define ISAUTOVACUUM (pBt->autoVacuum)
  49220. #else
  49221. #define ISAUTOVACUUM 0
  49222. #endif
  49223. /*
  49224. ** This structure is passed around through all the sanity checking routines
  49225. ** in order to keep track of some global state information.
  49226. **
  49227. ** The aRef[] array is allocated so that there is 1 bit for each page in
  49228. ** the database. As the integrity-check proceeds, for each page used in
  49229. ** the database the corresponding bit is set. This allows integrity-check to
  49230. ** detect pages that are used twice and orphaned pages (both of which
  49231. ** indicate corruption).
  49232. */
  49233. typedef struct IntegrityCk IntegrityCk;
  49234. struct IntegrityCk {
  49235. BtShared *pBt; /* The tree being checked out */
  49236. Pager *pPager; /* The associated pager. Also accessible by pBt->pPager */
  49237. u8 *aPgRef; /* 1 bit per page in the db (see above) */
  49238. Pgno nPage; /* Number of pages in the database */
  49239. int mxErr; /* Stop accumulating errors when this reaches zero */
  49240. int nErr; /* Number of messages written to zErrMsg so far */
  49241. int mallocFailed; /* A memory allocation error has occurred */
  49242. const char *zPfx; /* Error message prefix */
  49243. int v1, v2; /* Values for up to two %d fields in zPfx */
  49244. StrAccum errMsg; /* Accumulate the error message text here */
  49245. };
  49246. /*
  49247. ** Routines to read or write a two- and four-byte big-endian integer values.
  49248. */
  49249. #define get2byte(x) ((x)[0]<<8 | (x)[1])
  49250. #define put2byte(p,v) ((p)[0] = (u8)((v)>>8), (p)[1] = (u8)(v))
  49251. #define get4byte sqlite3Get4byte
  49252. #define put4byte sqlite3Put4byte
  49253. /************** End of btreeInt.h ********************************************/
  49254. /************** Continuing where we left off in btmutex.c ********************/
  49255. #ifndef SQLITE_OMIT_SHARED_CACHE
  49256. #if SQLITE_THREADSAFE
  49257. /*
  49258. ** Obtain the BtShared mutex associated with B-Tree handle p. Also,
  49259. ** set BtShared.db to the database handle associated with p and the
  49260. ** p->locked boolean to true.
  49261. */
  49262. static void lockBtreeMutex(Btree *p){
  49263. assert( p->locked==0 );
  49264. assert( sqlite3_mutex_notheld(p->pBt->mutex) );
  49265. assert( sqlite3_mutex_held(p->db->mutex) );
  49266. sqlite3_mutex_enter(p->pBt->mutex);
  49267. p->pBt->db = p->db;
  49268. p->locked = 1;
  49269. }
  49270. /*
  49271. ** Release the BtShared mutex associated with B-Tree handle p and
  49272. ** clear the p->locked boolean.
  49273. */
  49274. static void SQLITE_NOINLINE unlockBtreeMutex(Btree *p){
  49275. BtShared *pBt = p->pBt;
  49276. assert( p->locked==1 );
  49277. assert( sqlite3_mutex_held(pBt->mutex) );
  49278. assert( sqlite3_mutex_held(p->db->mutex) );
  49279. assert( p->db==pBt->db );
  49280. sqlite3_mutex_leave(pBt->mutex);
  49281. p->locked = 0;
  49282. }
  49283. /* Forward reference */
  49284. static void SQLITE_NOINLINE btreeLockCarefully(Btree *p);
  49285. /*
  49286. ** Enter a mutex on the given BTree object.
  49287. **
  49288. ** If the object is not sharable, then no mutex is ever required
  49289. ** and this routine is a no-op. The underlying mutex is non-recursive.
  49290. ** But we keep a reference count in Btree.wantToLock so the behavior
  49291. ** of this interface is recursive.
  49292. **
  49293. ** To avoid deadlocks, multiple Btrees are locked in the same order
  49294. ** by all database connections. The p->pNext is a list of other
  49295. ** Btrees belonging to the same database connection as the p Btree
  49296. ** which need to be locked after p. If we cannot get a lock on
  49297. ** p, then first unlock all of the others on p->pNext, then wait
  49298. ** for the lock to become available on p, then relock all of the
  49299. ** subsequent Btrees that desire a lock.
  49300. */
  49301. SQLITE_PRIVATE void sqlite3BtreeEnter(Btree *p){
  49302. /* Some basic sanity checking on the Btree. The list of Btrees
  49303. ** connected by pNext and pPrev should be in sorted order by
  49304. ** Btree.pBt value. All elements of the list should belong to
  49305. ** the same connection. Only shared Btrees are on the list. */
  49306. assert( p->pNext==0 || p->pNext->pBt>p->pBt );
  49307. assert( p->pPrev==0 || p->pPrev->pBt<p->pBt );
  49308. assert( p->pNext==0 || p->pNext->db==p->db );
  49309. assert( p->pPrev==0 || p->pPrev->db==p->db );
  49310. assert( p->sharable || (p->pNext==0 && p->pPrev==0) );
  49311. /* Check for locking consistency */
  49312. assert( !p->locked || p->wantToLock>0 );
  49313. assert( p->sharable || p->wantToLock==0 );
  49314. /* We should already hold a lock on the database connection */
  49315. assert( sqlite3_mutex_held(p->db->mutex) );
  49316. /* Unless the database is sharable and unlocked, then BtShared.db
  49317. ** should already be set correctly. */
  49318. assert( (p->locked==0 && p->sharable) || p->pBt->db==p->db );
  49319. if( !p->sharable ) return;
  49320. p->wantToLock++;
  49321. if( p->locked ) return;
  49322. btreeLockCarefully(p);
  49323. }
  49324. /* This is a helper function for sqlite3BtreeLock(). By moving
  49325. ** complex, but seldom used logic, out of sqlite3BtreeLock() and
  49326. ** into this routine, we avoid unnecessary stack pointer changes
  49327. ** and thus help the sqlite3BtreeLock() routine to run much faster
  49328. ** in the common case.
  49329. */
  49330. static void SQLITE_NOINLINE btreeLockCarefully(Btree *p){
  49331. Btree *pLater;
  49332. /* In most cases, we should be able to acquire the lock we
  49333. ** want without having to go through the ascending lock
  49334. ** procedure that follows. Just be sure not to block.
  49335. */
  49336. if( sqlite3_mutex_try(p->pBt->mutex)==SQLITE_OK ){
  49337. p->pBt->db = p->db;
  49338. p->locked = 1;
  49339. return;
  49340. }
  49341. /* To avoid deadlock, first release all locks with a larger
  49342. ** BtShared address. Then acquire our lock. Then reacquire
  49343. ** the other BtShared locks that we used to hold in ascending
  49344. ** order.
  49345. */
  49346. for(pLater=p->pNext; pLater; pLater=pLater->pNext){
  49347. assert( pLater->sharable );
  49348. assert( pLater->pNext==0 || pLater->pNext->pBt>pLater->pBt );
  49349. assert( !pLater->locked || pLater->wantToLock>0 );
  49350. if( pLater->locked ){
  49351. unlockBtreeMutex(pLater);
  49352. }
  49353. }
  49354. lockBtreeMutex(p);
  49355. for(pLater=p->pNext; pLater; pLater=pLater->pNext){
  49356. if( pLater->wantToLock ){
  49357. lockBtreeMutex(pLater);
  49358. }
  49359. }
  49360. }
  49361. /*
  49362. ** Exit the recursive mutex on a Btree.
  49363. */
  49364. SQLITE_PRIVATE void sqlite3BtreeLeave(Btree *p){
  49365. assert( sqlite3_mutex_held(p->db->mutex) );
  49366. if( p->sharable ){
  49367. assert( p->wantToLock>0 );
  49368. p->wantToLock--;
  49369. if( p->wantToLock==0 ){
  49370. unlockBtreeMutex(p);
  49371. }
  49372. }
  49373. }
  49374. #ifndef NDEBUG
  49375. /*
  49376. ** Return true if the BtShared mutex is held on the btree, or if the
  49377. ** B-Tree is not marked as sharable.
  49378. **
  49379. ** This routine is used only from within assert() statements.
  49380. */
  49381. SQLITE_PRIVATE int sqlite3BtreeHoldsMutex(Btree *p){
  49382. assert( p->sharable==0 || p->locked==0 || p->wantToLock>0 );
  49383. assert( p->sharable==0 || p->locked==0 || p->db==p->pBt->db );
  49384. assert( p->sharable==0 || p->locked==0 || sqlite3_mutex_held(p->pBt->mutex) );
  49385. assert( p->sharable==0 || p->locked==0 || sqlite3_mutex_held(p->db->mutex) );
  49386. return (p->sharable==0 || p->locked);
  49387. }
  49388. #endif
  49389. #ifndef SQLITE_OMIT_INCRBLOB
  49390. /*
  49391. ** Enter and leave a mutex on a Btree given a cursor owned by that
  49392. ** Btree. These entry points are used by incremental I/O and can be
  49393. ** omitted if that module is not used.
  49394. */
  49395. SQLITE_PRIVATE void sqlite3BtreeEnterCursor(BtCursor *pCur){
  49396. sqlite3BtreeEnter(pCur->pBtree);
  49397. }
  49398. SQLITE_PRIVATE void sqlite3BtreeLeaveCursor(BtCursor *pCur){
  49399. sqlite3BtreeLeave(pCur->pBtree);
  49400. }
  49401. #endif /* SQLITE_OMIT_INCRBLOB */
  49402. /*
  49403. ** Enter the mutex on every Btree associated with a database
  49404. ** connection. This is needed (for example) prior to parsing
  49405. ** a statement since we will be comparing table and column names
  49406. ** against all schemas and we do not want those schemas being
  49407. ** reset out from under us.
  49408. **
  49409. ** There is a corresponding leave-all procedures.
  49410. **
  49411. ** Enter the mutexes in accending order by BtShared pointer address
  49412. ** to avoid the possibility of deadlock when two threads with
  49413. ** two or more btrees in common both try to lock all their btrees
  49414. ** at the same instant.
  49415. */
  49416. SQLITE_PRIVATE void sqlite3BtreeEnterAll(sqlite3 *db){
  49417. int i;
  49418. Btree *p;
  49419. assert( sqlite3_mutex_held(db->mutex) );
  49420. for(i=0; i<db->nDb; i++){
  49421. p = db->aDb[i].pBt;
  49422. if( p ) sqlite3BtreeEnter(p);
  49423. }
  49424. }
  49425. SQLITE_PRIVATE void sqlite3BtreeLeaveAll(sqlite3 *db){
  49426. int i;
  49427. Btree *p;
  49428. assert( sqlite3_mutex_held(db->mutex) );
  49429. for(i=0; i<db->nDb; i++){
  49430. p = db->aDb[i].pBt;
  49431. if( p ) sqlite3BtreeLeave(p);
  49432. }
  49433. }
  49434. /*
  49435. ** Return true if a particular Btree requires a lock. Return FALSE if
  49436. ** no lock is ever required since it is not sharable.
  49437. */
  49438. SQLITE_PRIVATE int sqlite3BtreeSharable(Btree *p){
  49439. return p->sharable;
  49440. }
  49441. #ifndef NDEBUG
  49442. /*
  49443. ** Return true if the current thread holds the database connection
  49444. ** mutex and all required BtShared mutexes.
  49445. **
  49446. ** This routine is used inside assert() statements only.
  49447. */
  49448. SQLITE_PRIVATE int sqlite3BtreeHoldsAllMutexes(sqlite3 *db){
  49449. int i;
  49450. if( !sqlite3_mutex_held(db->mutex) ){
  49451. return 0;
  49452. }
  49453. for(i=0; i<db->nDb; i++){
  49454. Btree *p;
  49455. p = db->aDb[i].pBt;
  49456. if( p && p->sharable &&
  49457. (p->wantToLock==0 || !sqlite3_mutex_held(p->pBt->mutex)) ){
  49458. return 0;
  49459. }
  49460. }
  49461. return 1;
  49462. }
  49463. #endif /* NDEBUG */
  49464. #ifndef NDEBUG
  49465. /*
  49466. ** Return true if the correct mutexes are held for accessing the
  49467. ** db->aDb[iDb].pSchema structure. The mutexes required for schema
  49468. ** access are:
  49469. **
  49470. ** (1) The mutex on db
  49471. ** (2) if iDb!=1, then the mutex on db->aDb[iDb].pBt.
  49472. **
  49473. ** If pSchema is not NULL, then iDb is computed from pSchema and
  49474. ** db using sqlite3SchemaToIndex().
  49475. */
  49476. SQLITE_PRIVATE int sqlite3SchemaMutexHeld(sqlite3 *db, int iDb, Schema *pSchema){
  49477. Btree *p;
  49478. assert( db!=0 );
  49479. if( pSchema ) iDb = sqlite3SchemaToIndex(db, pSchema);
  49480. assert( iDb>=0 && iDb<db->nDb );
  49481. if( !sqlite3_mutex_held(db->mutex) ) return 0;
  49482. if( iDb==1 ) return 1;
  49483. p = db->aDb[iDb].pBt;
  49484. assert( p!=0 );
  49485. return p->sharable==0 || p->locked==1;
  49486. }
  49487. #endif /* NDEBUG */
  49488. #else /* SQLITE_THREADSAFE>0 above. SQLITE_THREADSAFE==0 below */
  49489. /*
  49490. ** The following are special cases for mutex enter routines for use
  49491. ** in single threaded applications that use shared cache. Except for
  49492. ** these two routines, all mutex operations are no-ops in that case and
  49493. ** are null #defines in btree.h.
  49494. **
  49495. ** If shared cache is disabled, then all btree mutex routines, including
  49496. ** the ones below, are no-ops and are null #defines in btree.h.
  49497. */
  49498. SQLITE_PRIVATE void sqlite3BtreeEnter(Btree *p){
  49499. p->pBt->db = p->db;
  49500. }
  49501. SQLITE_PRIVATE void sqlite3BtreeEnterAll(sqlite3 *db){
  49502. int i;
  49503. for(i=0; i<db->nDb; i++){
  49504. Btree *p = db->aDb[i].pBt;
  49505. if( p ){
  49506. p->pBt->db = p->db;
  49507. }
  49508. }
  49509. }
  49510. #endif /* if SQLITE_THREADSAFE */
  49511. #endif /* ifndef SQLITE_OMIT_SHARED_CACHE */
  49512. /************** End of btmutex.c *********************************************/
  49513. /************** Begin file btree.c *******************************************/
  49514. /*
  49515. ** 2004 April 6
  49516. **
  49517. ** The author disclaims copyright to this source code. In place of
  49518. ** a legal notice, here is a blessing:
  49519. **
  49520. ** May you do good and not evil.
  49521. ** May you find forgiveness for yourself and forgive others.
  49522. ** May you share freely, never taking more than you give.
  49523. **
  49524. *************************************************************************
  49525. ** This file implements an external (disk-based) database using BTrees.
  49526. ** See the header comment on "btreeInt.h" for additional information.
  49527. ** Including a description of file format and an overview of operation.
  49528. */
  49529. /*
  49530. ** The header string that appears at the beginning of every
  49531. ** SQLite database.
  49532. */
  49533. static const char zMagicHeader[] = SQLITE_FILE_HEADER;
  49534. /*
  49535. ** Set this global variable to 1 to enable tracing using the TRACE
  49536. ** macro.
  49537. */
  49538. #if 0
  49539. int sqlite3BtreeTrace=1; /* True to enable tracing */
  49540. # define TRACE(X) if(sqlite3BtreeTrace){printf X;fflush(stdout);}
  49541. #else
  49542. # define TRACE(X)
  49543. #endif
  49544. /*
  49545. ** Extract a 2-byte big-endian integer from an array of unsigned bytes.
  49546. ** But if the value is zero, make it 65536.
  49547. **
  49548. ** This routine is used to extract the "offset to cell content area" value
  49549. ** from the header of a btree page. If the page size is 65536 and the page
  49550. ** is empty, the offset should be 65536, but the 2-byte value stores zero.
  49551. ** This routine makes the necessary adjustment to 65536.
  49552. */
  49553. #define get2byteNotZero(X) (((((int)get2byte(X))-1)&0xffff)+1)
  49554. /*
  49555. ** Values passed as the 5th argument to allocateBtreePage()
  49556. */
  49557. #define BTALLOC_ANY 0 /* Allocate any page */
  49558. #define BTALLOC_EXACT 1 /* Allocate exact page if possible */
  49559. #define BTALLOC_LE 2 /* Allocate any page <= the parameter */
  49560. /*
  49561. ** Macro IfNotOmitAV(x) returns (x) if SQLITE_OMIT_AUTOVACUUM is not
  49562. ** defined, or 0 if it is. For example:
  49563. **
  49564. ** bIncrVacuum = IfNotOmitAV(pBtShared->incrVacuum);
  49565. */
  49566. #ifndef SQLITE_OMIT_AUTOVACUUM
  49567. #define IfNotOmitAV(expr) (expr)
  49568. #else
  49569. #define IfNotOmitAV(expr) 0
  49570. #endif
  49571. #ifndef SQLITE_OMIT_SHARED_CACHE
  49572. /*
  49573. ** A list of BtShared objects that are eligible for participation
  49574. ** in shared cache. This variable has file scope during normal builds,
  49575. ** but the test harness needs to access it so we make it global for
  49576. ** test builds.
  49577. **
  49578. ** Access to this variable is protected by SQLITE_MUTEX_STATIC_MASTER.
  49579. */
  49580. #ifdef SQLITE_TEST
  49581. SQLITE_PRIVATE BtShared *SQLITE_WSD sqlite3SharedCacheList = 0;
  49582. #else
  49583. static BtShared *SQLITE_WSD sqlite3SharedCacheList = 0;
  49584. #endif
  49585. #endif /* SQLITE_OMIT_SHARED_CACHE */
  49586. #ifndef SQLITE_OMIT_SHARED_CACHE
  49587. /*
  49588. ** Enable or disable the shared pager and schema features.
  49589. **
  49590. ** This routine has no effect on existing database connections.
  49591. ** The shared cache setting effects only future calls to
  49592. ** sqlite3_open(), sqlite3_open16(), or sqlite3_open_v2().
  49593. */
  49594. SQLITE_API int SQLITE_STDCALL sqlite3_enable_shared_cache(int enable){
  49595. sqlite3GlobalConfig.sharedCacheEnabled = enable;
  49596. return SQLITE_OK;
  49597. }
  49598. #endif
  49599. #ifdef SQLITE_OMIT_SHARED_CACHE
  49600. /*
  49601. ** The functions querySharedCacheTableLock(), setSharedCacheTableLock(),
  49602. ** and clearAllSharedCacheTableLocks()
  49603. ** manipulate entries in the BtShared.pLock linked list used to store
  49604. ** shared-cache table level locks. If the library is compiled with the
  49605. ** shared-cache feature disabled, then there is only ever one user
  49606. ** of each BtShared structure and so this locking is not necessary.
  49607. ** So define the lock related functions as no-ops.
  49608. */
  49609. #define querySharedCacheTableLock(a,b,c) SQLITE_OK
  49610. #define setSharedCacheTableLock(a,b,c) SQLITE_OK
  49611. #define clearAllSharedCacheTableLocks(a)
  49612. #define downgradeAllSharedCacheTableLocks(a)
  49613. #define hasSharedCacheTableLock(a,b,c,d) 1
  49614. #define hasReadConflicts(a, b) 0
  49615. #endif
  49616. #ifndef SQLITE_OMIT_SHARED_CACHE
  49617. #ifdef SQLITE_DEBUG
  49618. /*
  49619. **** This function is only used as part of an assert() statement. ***
  49620. **
  49621. ** Check to see if pBtree holds the required locks to read or write to the
  49622. ** table with root page iRoot. Return 1 if it does and 0 if not.
  49623. **
  49624. ** For example, when writing to a table with root-page iRoot via
  49625. ** Btree connection pBtree:
  49626. **
  49627. ** assert( hasSharedCacheTableLock(pBtree, iRoot, 0, WRITE_LOCK) );
  49628. **
  49629. ** When writing to an index that resides in a sharable database, the
  49630. ** caller should have first obtained a lock specifying the root page of
  49631. ** the corresponding table. This makes things a bit more complicated,
  49632. ** as this module treats each table as a separate structure. To determine
  49633. ** the table corresponding to the index being written, this
  49634. ** function has to search through the database schema.
  49635. **
  49636. ** Instead of a lock on the table/index rooted at page iRoot, the caller may
  49637. ** hold a write-lock on the schema table (root page 1). This is also
  49638. ** acceptable.
  49639. */
  49640. static int hasSharedCacheTableLock(
  49641. Btree *pBtree, /* Handle that must hold lock */
  49642. Pgno iRoot, /* Root page of b-tree */
  49643. int isIndex, /* True if iRoot is the root of an index b-tree */
  49644. int eLockType /* Required lock type (READ_LOCK or WRITE_LOCK) */
  49645. ){
  49646. Schema *pSchema = (Schema *)pBtree->pBt->pSchema;
  49647. Pgno iTab = 0;
  49648. BtLock *pLock;
  49649. /* If this database is not shareable, or if the client is reading
  49650. ** and has the read-uncommitted flag set, then no lock is required.
  49651. ** Return true immediately.
  49652. */
  49653. if( (pBtree->sharable==0)
  49654. || (eLockType==READ_LOCK && (pBtree->db->flags & SQLITE_ReadUncommitted))
  49655. ){
  49656. return 1;
  49657. }
  49658. /* If the client is reading or writing an index and the schema is
  49659. ** not loaded, then it is too difficult to actually check to see if
  49660. ** the correct locks are held. So do not bother - just return true.
  49661. ** This case does not come up very often anyhow.
  49662. */
  49663. if( isIndex && (!pSchema || (pSchema->schemaFlags&DB_SchemaLoaded)==0) ){
  49664. return 1;
  49665. }
  49666. /* Figure out the root-page that the lock should be held on. For table
  49667. ** b-trees, this is just the root page of the b-tree being read or
  49668. ** written. For index b-trees, it is the root page of the associated
  49669. ** table. */
  49670. if( isIndex ){
  49671. HashElem *p;
  49672. for(p=sqliteHashFirst(&pSchema->idxHash); p; p=sqliteHashNext(p)){
  49673. Index *pIdx = (Index *)sqliteHashData(p);
  49674. if( pIdx->tnum==(int)iRoot ){
  49675. if( iTab ){
  49676. /* Two or more indexes share the same root page. There must
  49677. ** be imposter tables. So just return true. The assert is not
  49678. ** useful in that case. */
  49679. return 1;
  49680. }
  49681. iTab = pIdx->pTable->tnum;
  49682. }
  49683. }
  49684. }else{
  49685. iTab = iRoot;
  49686. }
  49687. /* Search for the required lock. Either a write-lock on root-page iTab, a
  49688. ** write-lock on the schema table, or (if the client is reading) a
  49689. ** read-lock on iTab will suffice. Return 1 if any of these are found. */
  49690. for(pLock=pBtree->pBt->pLock; pLock; pLock=pLock->pNext){
  49691. if( pLock->pBtree==pBtree
  49692. && (pLock->iTable==iTab || (pLock->eLock==WRITE_LOCK && pLock->iTable==1))
  49693. && pLock->eLock>=eLockType
  49694. ){
  49695. return 1;
  49696. }
  49697. }
  49698. /* Failed to find the required lock. */
  49699. return 0;
  49700. }
  49701. #endif /* SQLITE_DEBUG */
  49702. #ifdef SQLITE_DEBUG
  49703. /*
  49704. **** This function may be used as part of assert() statements only. ****
  49705. **
  49706. ** Return true if it would be illegal for pBtree to write into the
  49707. ** table or index rooted at iRoot because other shared connections are
  49708. ** simultaneously reading that same table or index.
  49709. **
  49710. ** It is illegal for pBtree to write if some other Btree object that
  49711. ** shares the same BtShared object is currently reading or writing
  49712. ** the iRoot table. Except, if the other Btree object has the
  49713. ** read-uncommitted flag set, then it is OK for the other object to
  49714. ** have a read cursor.
  49715. **
  49716. ** For example, before writing to any part of the table or index
  49717. ** rooted at page iRoot, one should call:
  49718. **
  49719. ** assert( !hasReadConflicts(pBtree, iRoot) );
  49720. */
  49721. static int hasReadConflicts(Btree *pBtree, Pgno iRoot){
  49722. BtCursor *p;
  49723. for(p=pBtree->pBt->pCursor; p; p=p->pNext){
  49724. if( p->pgnoRoot==iRoot
  49725. && p->pBtree!=pBtree
  49726. && 0==(p->pBtree->db->flags & SQLITE_ReadUncommitted)
  49727. ){
  49728. return 1;
  49729. }
  49730. }
  49731. return 0;
  49732. }
  49733. #endif /* #ifdef SQLITE_DEBUG */
  49734. /*
  49735. ** Query to see if Btree handle p may obtain a lock of type eLock
  49736. ** (READ_LOCK or WRITE_LOCK) on the table with root-page iTab. Return
  49737. ** SQLITE_OK if the lock may be obtained (by calling
  49738. ** setSharedCacheTableLock()), or SQLITE_LOCKED if not.
  49739. */
  49740. static int querySharedCacheTableLock(Btree *p, Pgno iTab, u8 eLock){
  49741. BtShared *pBt = p->pBt;
  49742. BtLock *pIter;
  49743. assert( sqlite3BtreeHoldsMutex(p) );
  49744. assert( eLock==READ_LOCK || eLock==WRITE_LOCK );
  49745. assert( p->db!=0 );
  49746. assert( !(p->db->flags&SQLITE_ReadUncommitted)||eLock==WRITE_LOCK||iTab==1 );
  49747. /* If requesting a write-lock, then the Btree must have an open write
  49748. ** transaction on this file. And, obviously, for this to be so there
  49749. ** must be an open write transaction on the file itself.
  49750. */
  49751. assert( eLock==READ_LOCK || (p==pBt->pWriter && p->inTrans==TRANS_WRITE) );
  49752. assert( eLock==READ_LOCK || pBt->inTransaction==TRANS_WRITE );
  49753. /* This routine is a no-op if the shared-cache is not enabled */
  49754. if( !p->sharable ){
  49755. return SQLITE_OK;
  49756. }
  49757. /* If some other connection is holding an exclusive lock, the
  49758. ** requested lock may not be obtained.
  49759. */
  49760. if( pBt->pWriter!=p && (pBt->btsFlags & BTS_EXCLUSIVE)!=0 ){
  49761. sqlite3ConnectionBlocked(p->db, pBt->pWriter->db);
  49762. return SQLITE_LOCKED_SHAREDCACHE;
  49763. }
  49764. for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
  49765. /* The condition (pIter->eLock!=eLock) in the following if(...)
  49766. ** statement is a simplification of:
  49767. **
  49768. ** (eLock==WRITE_LOCK || pIter->eLock==WRITE_LOCK)
  49769. **
  49770. ** since we know that if eLock==WRITE_LOCK, then no other connection
  49771. ** may hold a WRITE_LOCK on any table in this file (since there can
  49772. ** only be a single writer).
  49773. */
  49774. assert( pIter->eLock==READ_LOCK || pIter->eLock==WRITE_LOCK );
  49775. assert( eLock==READ_LOCK || pIter->pBtree==p || pIter->eLock==READ_LOCK);
  49776. if( pIter->pBtree!=p && pIter->iTable==iTab && pIter->eLock!=eLock ){
  49777. sqlite3ConnectionBlocked(p->db, pIter->pBtree->db);
  49778. if( eLock==WRITE_LOCK ){
  49779. assert( p==pBt->pWriter );
  49780. pBt->btsFlags |= BTS_PENDING;
  49781. }
  49782. return SQLITE_LOCKED_SHAREDCACHE;
  49783. }
  49784. }
  49785. return SQLITE_OK;
  49786. }
  49787. #endif /* !SQLITE_OMIT_SHARED_CACHE */
  49788. #ifndef SQLITE_OMIT_SHARED_CACHE
  49789. /*
  49790. ** Add a lock on the table with root-page iTable to the shared-btree used
  49791. ** by Btree handle p. Parameter eLock must be either READ_LOCK or
  49792. ** WRITE_LOCK.
  49793. **
  49794. ** This function assumes the following:
  49795. **
  49796. ** (a) The specified Btree object p is connected to a sharable
  49797. ** database (one with the BtShared.sharable flag set), and
  49798. **
  49799. ** (b) No other Btree objects hold a lock that conflicts
  49800. ** with the requested lock (i.e. querySharedCacheTableLock() has
  49801. ** already been called and returned SQLITE_OK).
  49802. **
  49803. ** SQLITE_OK is returned if the lock is added successfully. SQLITE_NOMEM
  49804. ** is returned if a malloc attempt fails.
  49805. */
  49806. static int setSharedCacheTableLock(Btree *p, Pgno iTable, u8 eLock){
  49807. BtShared *pBt = p->pBt;
  49808. BtLock *pLock = 0;
  49809. BtLock *pIter;
  49810. assert( sqlite3BtreeHoldsMutex(p) );
  49811. assert( eLock==READ_LOCK || eLock==WRITE_LOCK );
  49812. assert( p->db!=0 );
  49813. /* A connection with the read-uncommitted flag set will never try to
  49814. ** obtain a read-lock using this function. The only read-lock obtained
  49815. ** by a connection in read-uncommitted mode is on the sqlite_master
  49816. ** table, and that lock is obtained in BtreeBeginTrans(). */
  49817. assert( 0==(p->db->flags&SQLITE_ReadUncommitted) || eLock==WRITE_LOCK );
  49818. /* This function should only be called on a sharable b-tree after it
  49819. ** has been determined that no other b-tree holds a conflicting lock. */
  49820. assert( p->sharable );
  49821. assert( SQLITE_OK==querySharedCacheTableLock(p, iTable, eLock) );
  49822. /* First search the list for an existing lock on this table. */
  49823. for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
  49824. if( pIter->iTable==iTable && pIter->pBtree==p ){
  49825. pLock = pIter;
  49826. break;
  49827. }
  49828. }
  49829. /* If the above search did not find a BtLock struct associating Btree p
  49830. ** with table iTable, allocate one and link it into the list.
  49831. */
  49832. if( !pLock ){
  49833. pLock = (BtLock *)sqlite3MallocZero(sizeof(BtLock));
  49834. if( !pLock ){
  49835. return SQLITE_NOMEM;
  49836. }
  49837. pLock->iTable = iTable;
  49838. pLock->pBtree = p;
  49839. pLock->pNext = pBt->pLock;
  49840. pBt->pLock = pLock;
  49841. }
  49842. /* Set the BtLock.eLock variable to the maximum of the current lock
  49843. ** and the requested lock. This means if a write-lock was already held
  49844. ** and a read-lock requested, we don't incorrectly downgrade the lock.
  49845. */
  49846. assert( WRITE_LOCK>READ_LOCK );
  49847. if( eLock>pLock->eLock ){
  49848. pLock->eLock = eLock;
  49849. }
  49850. return SQLITE_OK;
  49851. }
  49852. #endif /* !SQLITE_OMIT_SHARED_CACHE */
  49853. #ifndef SQLITE_OMIT_SHARED_CACHE
  49854. /*
  49855. ** Release all the table locks (locks obtained via calls to
  49856. ** the setSharedCacheTableLock() procedure) held by Btree object p.
  49857. **
  49858. ** This function assumes that Btree p has an open read or write
  49859. ** transaction. If it does not, then the BTS_PENDING flag
  49860. ** may be incorrectly cleared.
  49861. */
  49862. static void clearAllSharedCacheTableLocks(Btree *p){
  49863. BtShared *pBt = p->pBt;
  49864. BtLock **ppIter = &pBt->pLock;
  49865. assert( sqlite3BtreeHoldsMutex(p) );
  49866. assert( p->sharable || 0==*ppIter );
  49867. assert( p->inTrans>0 );
  49868. while( *ppIter ){
  49869. BtLock *pLock = *ppIter;
  49870. assert( (pBt->btsFlags & BTS_EXCLUSIVE)==0 || pBt->pWriter==pLock->pBtree );
  49871. assert( pLock->pBtree->inTrans>=pLock->eLock );
  49872. if( pLock->pBtree==p ){
  49873. *ppIter = pLock->pNext;
  49874. assert( pLock->iTable!=1 || pLock==&p->lock );
  49875. if( pLock->iTable!=1 ){
  49876. sqlite3_free(pLock);
  49877. }
  49878. }else{
  49879. ppIter = &pLock->pNext;
  49880. }
  49881. }
  49882. assert( (pBt->btsFlags & BTS_PENDING)==0 || pBt->pWriter );
  49883. if( pBt->pWriter==p ){
  49884. pBt->pWriter = 0;
  49885. pBt->btsFlags &= ~(BTS_EXCLUSIVE|BTS_PENDING);
  49886. }else if( pBt->nTransaction==2 ){
  49887. /* This function is called when Btree p is concluding its
  49888. ** transaction. If there currently exists a writer, and p is not
  49889. ** that writer, then the number of locks held by connections other
  49890. ** than the writer must be about to drop to zero. In this case
  49891. ** set the BTS_PENDING flag to 0.
  49892. **
  49893. ** If there is not currently a writer, then BTS_PENDING must
  49894. ** be zero already. So this next line is harmless in that case.
  49895. */
  49896. pBt->btsFlags &= ~BTS_PENDING;
  49897. }
  49898. }
  49899. /*
  49900. ** This function changes all write-locks held by Btree p into read-locks.
  49901. */
  49902. static void downgradeAllSharedCacheTableLocks(Btree *p){
  49903. BtShared *pBt = p->pBt;
  49904. if( pBt->pWriter==p ){
  49905. BtLock *pLock;
  49906. pBt->pWriter = 0;
  49907. pBt->btsFlags &= ~(BTS_EXCLUSIVE|BTS_PENDING);
  49908. for(pLock=pBt->pLock; pLock; pLock=pLock->pNext){
  49909. assert( pLock->eLock==READ_LOCK || pLock->pBtree==p );
  49910. pLock->eLock = READ_LOCK;
  49911. }
  49912. }
  49913. }
  49914. #endif /* SQLITE_OMIT_SHARED_CACHE */
  49915. static void releasePage(MemPage *pPage); /* Forward reference */
  49916. /*
  49917. ***** This routine is used inside of assert() only ****
  49918. **
  49919. ** Verify that the cursor holds the mutex on its BtShared
  49920. */
  49921. #ifdef SQLITE_DEBUG
  49922. static int cursorHoldsMutex(BtCursor *p){
  49923. return sqlite3_mutex_held(p->pBt->mutex);
  49924. }
  49925. #endif
  49926. /*
  49927. ** Invalidate the overflow cache of the cursor passed as the first argument.
  49928. ** on the shared btree structure pBt.
  49929. */
  49930. #define invalidateOverflowCache(pCur) (pCur->curFlags &= ~BTCF_ValidOvfl)
  49931. /*
  49932. ** Invalidate the overflow page-list cache for all cursors opened
  49933. ** on the shared btree structure pBt.
  49934. */
  49935. static void invalidateAllOverflowCache(BtShared *pBt){
  49936. BtCursor *p;
  49937. assert( sqlite3_mutex_held(pBt->mutex) );
  49938. for(p=pBt->pCursor; p; p=p->pNext){
  49939. invalidateOverflowCache(p);
  49940. }
  49941. }
  49942. #ifndef SQLITE_OMIT_INCRBLOB
  49943. /*
  49944. ** This function is called before modifying the contents of a table
  49945. ** to invalidate any incrblob cursors that are open on the
  49946. ** row or one of the rows being modified.
  49947. **
  49948. ** If argument isClearTable is true, then the entire contents of the
  49949. ** table is about to be deleted. In this case invalidate all incrblob
  49950. ** cursors open on any row within the table with root-page pgnoRoot.
  49951. **
  49952. ** Otherwise, if argument isClearTable is false, then the row with
  49953. ** rowid iRow is being replaced or deleted. In this case invalidate
  49954. ** only those incrblob cursors open on that specific row.
  49955. */
  49956. static void invalidateIncrblobCursors(
  49957. Btree *pBtree, /* The database file to check */
  49958. i64 iRow, /* The rowid that might be changing */
  49959. int isClearTable /* True if all rows are being deleted */
  49960. ){
  49961. BtCursor *p;
  49962. BtShared *pBt = pBtree->pBt;
  49963. assert( sqlite3BtreeHoldsMutex(pBtree) );
  49964. for(p=pBt->pCursor; p; p=p->pNext){
  49965. if( (p->curFlags & BTCF_Incrblob)!=0
  49966. && (isClearTable || p->info.nKey==iRow)
  49967. ){
  49968. p->eState = CURSOR_INVALID;
  49969. }
  49970. }
  49971. }
  49972. #else
  49973. /* Stub function when INCRBLOB is omitted */
  49974. #define invalidateIncrblobCursors(x,y,z)
  49975. #endif /* SQLITE_OMIT_INCRBLOB */
  49976. /*
  49977. ** Set bit pgno of the BtShared.pHasContent bitvec. This is called
  49978. ** when a page that previously contained data becomes a free-list leaf
  49979. ** page.
  49980. **
  49981. ** The BtShared.pHasContent bitvec exists to work around an obscure
  49982. ** bug caused by the interaction of two useful IO optimizations surrounding
  49983. ** free-list leaf pages:
  49984. **
  49985. ** 1) When all data is deleted from a page and the page becomes
  49986. ** a free-list leaf page, the page is not written to the database
  49987. ** (as free-list leaf pages contain no meaningful data). Sometimes
  49988. ** such a page is not even journalled (as it will not be modified,
  49989. ** why bother journalling it?).
  49990. **
  49991. ** 2) When a free-list leaf page is reused, its content is not read
  49992. ** from the database or written to the journal file (why should it
  49993. ** be, if it is not at all meaningful?).
  49994. **
  49995. ** By themselves, these optimizations work fine and provide a handy
  49996. ** performance boost to bulk delete or insert operations. However, if
  49997. ** a page is moved to the free-list and then reused within the same
  49998. ** transaction, a problem comes up. If the page is not journalled when
  49999. ** it is moved to the free-list and it is also not journalled when it
  50000. ** is extracted from the free-list and reused, then the original data
  50001. ** may be lost. In the event of a rollback, it may not be possible
  50002. ** to restore the database to its original configuration.
  50003. **
  50004. ** The solution is the BtShared.pHasContent bitvec. Whenever a page is
  50005. ** moved to become a free-list leaf page, the corresponding bit is
  50006. ** set in the bitvec. Whenever a leaf page is extracted from the free-list,
  50007. ** optimization 2 above is omitted if the corresponding bit is already
  50008. ** set in BtShared.pHasContent. The contents of the bitvec are cleared
  50009. ** at the end of every transaction.
  50010. */
  50011. static int btreeSetHasContent(BtShared *pBt, Pgno pgno){
  50012. int rc = SQLITE_OK;
  50013. if( !pBt->pHasContent ){
  50014. assert( pgno<=pBt->nPage );
  50015. pBt->pHasContent = sqlite3BitvecCreate(pBt->nPage);
  50016. if( !pBt->pHasContent ){
  50017. rc = SQLITE_NOMEM;
  50018. }
  50019. }
  50020. if( rc==SQLITE_OK && pgno<=sqlite3BitvecSize(pBt->pHasContent) ){
  50021. rc = sqlite3BitvecSet(pBt->pHasContent, pgno);
  50022. }
  50023. return rc;
  50024. }
  50025. /*
  50026. ** Query the BtShared.pHasContent vector.
  50027. **
  50028. ** This function is called when a free-list leaf page is removed from the
  50029. ** free-list for reuse. It returns false if it is safe to retrieve the
  50030. ** page from the pager layer with the 'no-content' flag set. True otherwise.
  50031. */
  50032. static int btreeGetHasContent(BtShared *pBt, Pgno pgno){
  50033. Bitvec *p = pBt->pHasContent;
  50034. return (p && (pgno>sqlite3BitvecSize(p) || sqlite3BitvecTest(p, pgno)));
  50035. }
  50036. /*
  50037. ** Clear (destroy) the BtShared.pHasContent bitvec. This should be
  50038. ** invoked at the conclusion of each write-transaction.
  50039. */
  50040. static void btreeClearHasContent(BtShared *pBt){
  50041. sqlite3BitvecDestroy(pBt->pHasContent);
  50042. pBt->pHasContent = 0;
  50043. }
  50044. /*
  50045. ** Release all of the apPage[] pages for a cursor.
  50046. */
  50047. static void btreeReleaseAllCursorPages(BtCursor *pCur){
  50048. int i;
  50049. for(i=0; i<=pCur->iPage; i++){
  50050. releasePage(pCur->apPage[i]);
  50051. pCur->apPage[i] = 0;
  50052. }
  50053. pCur->iPage = -1;
  50054. }
  50055. /*
  50056. ** Save the current cursor position in the variables BtCursor.nKey
  50057. ** and BtCursor.pKey. The cursor's state is set to CURSOR_REQUIRESEEK.
  50058. **
  50059. ** The caller must ensure that the cursor is valid (has eState==CURSOR_VALID)
  50060. ** prior to calling this routine.
  50061. */
  50062. static int saveCursorPosition(BtCursor *pCur){
  50063. int rc;
  50064. assert( CURSOR_VALID==pCur->eState || CURSOR_SKIPNEXT==pCur->eState );
  50065. assert( 0==pCur->pKey );
  50066. assert( cursorHoldsMutex(pCur) );
  50067. if( pCur->eState==CURSOR_SKIPNEXT ){
  50068. pCur->eState = CURSOR_VALID;
  50069. }else{
  50070. pCur->skipNext = 0;
  50071. }
  50072. rc = sqlite3BtreeKeySize(pCur, &pCur->nKey);
  50073. assert( rc==SQLITE_OK ); /* KeySize() cannot fail */
  50074. /* If this is an intKey table, then the above call to BtreeKeySize()
  50075. ** stores the integer key in pCur->nKey. In this case this value is
  50076. ** all that is required. Otherwise, if pCur is not open on an intKey
  50077. ** table, then malloc space for and store the pCur->nKey bytes of key
  50078. ** data.
  50079. */
  50080. if( 0==pCur->apPage[0]->intKey ){
  50081. void *pKey = sqlite3Malloc( pCur->nKey );
  50082. if( pKey ){
  50083. rc = sqlite3BtreeKey(pCur, 0, (int)pCur->nKey, pKey);
  50084. if( rc==SQLITE_OK ){
  50085. pCur->pKey = pKey;
  50086. }else{
  50087. sqlite3_free(pKey);
  50088. }
  50089. }else{
  50090. rc = SQLITE_NOMEM;
  50091. }
  50092. }
  50093. assert( !pCur->apPage[0]->intKey || !pCur->pKey );
  50094. if( rc==SQLITE_OK ){
  50095. btreeReleaseAllCursorPages(pCur);
  50096. pCur->eState = CURSOR_REQUIRESEEK;
  50097. }
  50098. invalidateOverflowCache(pCur);
  50099. return rc;
  50100. }
  50101. /* Forward reference */
  50102. static int SQLITE_NOINLINE saveCursorsOnList(BtCursor*,Pgno,BtCursor*);
  50103. /*
  50104. ** Save the positions of all cursors (except pExcept) that are open on
  50105. ** the table with root-page iRoot. "Saving the cursor position" means that
  50106. ** the location in the btree is remembered in such a way that it can be
  50107. ** moved back to the same spot after the btree has been modified. This
  50108. ** routine is called just before cursor pExcept is used to modify the
  50109. ** table, for example in BtreeDelete() or BtreeInsert().
  50110. **
  50111. ** Implementation note: This routine merely checks to see if any cursors
  50112. ** need to be saved. It calls out to saveCursorsOnList() in the (unusual)
  50113. ** event that cursors are in need to being saved.
  50114. */
  50115. static int saveAllCursors(BtShared *pBt, Pgno iRoot, BtCursor *pExcept){
  50116. BtCursor *p;
  50117. assert( sqlite3_mutex_held(pBt->mutex) );
  50118. assert( pExcept==0 || pExcept->pBt==pBt );
  50119. for(p=pBt->pCursor; p; p=p->pNext){
  50120. if( p!=pExcept && (0==iRoot || p->pgnoRoot==iRoot) ) break;
  50121. }
  50122. return p ? saveCursorsOnList(p, iRoot, pExcept) : SQLITE_OK;
  50123. }
  50124. /* This helper routine to saveAllCursors does the actual work of saving
  50125. ** the cursors if and when a cursor is found that actually requires saving.
  50126. ** The common case is that no cursors need to be saved, so this routine is
  50127. ** broken out from its caller to avoid unnecessary stack pointer movement.
  50128. */
  50129. static int SQLITE_NOINLINE saveCursorsOnList(
  50130. BtCursor *p, /* The first cursor that needs saving */
  50131. Pgno iRoot, /* Only save cursor with this iRoot. Save all if zero */
  50132. BtCursor *pExcept /* Do not save this cursor */
  50133. ){
  50134. do{
  50135. if( p!=pExcept && (0==iRoot || p->pgnoRoot==iRoot) ){
  50136. if( p->eState==CURSOR_VALID || p->eState==CURSOR_SKIPNEXT ){
  50137. int rc = saveCursorPosition(p);
  50138. if( SQLITE_OK!=rc ){
  50139. return rc;
  50140. }
  50141. }else{
  50142. testcase( p->iPage>0 );
  50143. btreeReleaseAllCursorPages(p);
  50144. }
  50145. }
  50146. p = p->pNext;
  50147. }while( p );
  50148. return SQLITE_OK;
  50149. }
  50150. /*
  50151. ** Clear the current cursor position.
  50152. */
  50153. SQLITE_PRIVATE void sqlite3BtreeClearCursor(BtCursor *pCur){
  50154. assert( cursorHoldsMutex(pCur) );
  50155. sqlite3_free(pCur->pKey);
  50156. pCur->pKey = 0;
  50157. pCur->eState = CURSOR_INVALID;
  50158. }
  50159. /*
  50160. ** In this version of BtreeMoveto, pKey is a packed index record
  50161. ** such as is generated by the OP_MakeRecord opcode. Unpack the
  50162. ** record and then call BtreeMovetoUnpacked() to do the work.
  50163. */
  50164. static int btreeMoveto(
  50165. BtCursor *pCur, /* Cursor open on the btree to be searched */
  50166. const void *pKey, /* Packed key if the btree is an index */
  50167. i64 nKey, /* Integer key for tables. Size of pKey for indices */
  50168. int bias, /* Bias search to the high end */
  50169. int *pRes /* Write search results here */
  50170. ){
  50171. int rc; /* Status code */
  50172. UnpackedRecord *pIdxKey; /* Unpacked index key */
  50173. char aSpace[200]; /* Temp space for pIdxKey - to avoid a malloc */
  50174. char *pFree = 0;
  50175. if( pKey ){
  50176. assert( nKey==(i64)(int)nKey );
  50177. pIdxKey = sqlite3VdbeAllocUnpackedRecord(
  50178. pCur->pKeyInfo, aSpace, sizeof(aSpace), &pFree
  50179. );
  50180. if( pIdxKey==0 ) return SQLITE_NOMEM;
  50181. sqlite3VdbeRecordUnpack(pCur->pKeyInfo, (int)nKey, pKey, pIdxKey);
  50182. if( pIdxKey->nField==0 ){
  50183. sqlite3DbFree(pCur->pKeyInfo->db, pFree);
  50184. return SQLITE_CORRUPT_BKPT;
  50185. }
  50186. }else{
  50187. pIdxKey = 0;
  50188. }
  50189. rc = sqlite3BtreeMovetoUnpacked(pCur, pIdxKey, nKey, bias, pRes);
  50190. if( pFree ){
  50191. sqlite3DbFree(pCur->pKeyInfo->db, pFree);
  50192. }
  50193. return rc;
  50194. }
  50195. /*
  50196. ** Restore the cursor to the position it was in (or as close to as possible)
  50197. ** when saveCursorPosition() was called. Note that this call deletes the
  50198. ** saved position info stored by saveCursorPosition(), so there can be
  50199. ** at most one effective restoreCursorPosition() call after each
  50200. ** saveCursorPosition().
  50201. */
  50202. static int btreeRestoreCursorPosition(BtCursor *pCur){
  50203. int rc;
  50204. int skipNext;
  50205. assert( cursorHoldsMutex(pCur) );
  50206. assert( pCur->eState>=CURSOR_REQUIRESEEK );
  50207. if( pCur->eState==CURSOR_FAULT ){
  50208. return pCur->skipNext;
  50209. }
  50210. pCur->eState = CURSOR_INVALID;
  50211. rc = btreeMoveto(pCur, pCur->pKey, pCur->nKey, 0, &skipNext);
  50212. if( rc==SQLITE_OK ){
  50213. sqlite3_free(pCur->pKey);
  50214. pCur->pKey = 0;
  50215. assert( pCur->eState==CURSOR_VALID || pCur->eState==CURSOR_INVALID );
  50216. pCur->skipNext |= skipNext;
  50217. if( pCur->skipNext && pCur->eState==CURSOR_VALID ){
  50218. pCur->eState = CURSOR_SKIPNEXT;
  50219. }
  50220. }
  50221. return rc;
  50222. }
  50223. #define restoreCursorPosition(p) \
  50224. (p->eState>=CURSOR_REQUIRESEEK ? \
  50225. btreeRestoreCursorPosition(p) : \
  50226. SQLITE_OK)
  50227. /*
  50228. ** Determine whether or not a cursor has moved from the position where
  50229. ** it was last placed, or has been invalidated for any other reason.
  50230. ** Cursors can move when the row they are pointing at is deleted out
  50231. ** from under them, for example. Cursor might also move if a btree
  50232. ** is rebalanced.
  50233. **
  50234. ** Calling this routine with a NULL cursor pointer returns false.
  50235. **
  50236. ** Use the separate sqlite3BtreeCursorRestore() routine to restore a cursor
  50237. ** back to where it ought to be if this routine returns true.
  50238. */
  50239. SQLITE_PRIVATE int sqlite3BtreeCursorHasMoved(BtCursor *pCur){
  50240. return pCur->eState!=CURSOR_VALID;
  50241. }
  50242. /*
  50243. ** This routine restores a cursor back to its original position after it
  50244. ** has been moved by some outside activity (such as a btree rebalance or
  50245. ** a row having been deleted out from under the cursor).
  50246. **
  50247. ** On success, the *pDifferentRow parameter is false if the cursor is left
  50248. ** pointing at exactly the same row. *pDifferntRow is the row the cursor
  50249. ** was pointing to has been deleted, forcing the cursor to point to some
  50250. ** nearby row.
  50251. **
  50252. ** This routine should only be called for a cursor that just returned
  50253. ** TRUE from sqlite3BtreeCursorHasMoved().
  50254. */
  50255. SQLITE_PRIVATE int sqlite3BtreeCursorRestore(BtCursor *pCur, int *pDifferentRow){
  50256. int rc;
  50257. assert( pCur!=0 );
  50258. assert( pCur->eState!=CURSOR_VALID );
  50259. rc = restoreCursorPosition(pCur);
  50260. if( rc ){
  50261. *pDifferentRow = 1;
  50262. return rc;
  50263. }
  50264. if( pCur->eState!=CURSOR_VALID ){
  50265. *pDifferentRow = 1;
  50266. }else{
  50267. assert( pCur->skipNext==0 );
  50268. *pDifferentRow = 0;
  50269. }
  50270. return SQLITE_OK;
  50271. }
  50272. #ifndef SQLITE_OMIT_AUTOVACUUM
  50273. /*
  50274. ** Given a page number of a regular database page, return the page
  50275. ** number for the pointer-map page that contains the entry for the
  50276. ** input page number.
  50277. **
  50278. ** Return 0 (not a valid page) for pgno==1 since there is
  50279. ** no pointer map associated with page 1. The integrity_check logic
  50280. ** requires that ptrmapPageno(*,1)!=1.
  50281. */
  50282. static Pgno ptrmapPageno(BtShared *pBt, Pgno pgno){
  50283. int nPagesPerMapPage;
  50284. Pgno iPtrMap, ret;
  50285. assert( sqlite3_mutex_held(pBt->mutex) );
  50286. if( pgno<2 ) return 0;
  50287. nPagesPerMapPage = (pBt->usableSize/5)+1;
  50288. iPtrMap = (pgno-2)/nPagesPerMapPage;
  50289. ret = (iPtrMap*nPagesPerMapPage) + 2;
  50290. if( ret==PENDING_BYTE_PAGE(pBt) ){
  50291. ret++;
  50292. }
  50293. return ret;
  50294. }
  50295. /*
  50296. ** Write an entry into the pointer map.
  50297. **
  50298. ** This routine updates the pointer map entry for page number 'key'
  50299. ** so that it maps to type 'eType' and parent page number 'pgno'.
  50300. **
  50301. ** If *pRC is initially non-zero (non-SQLITE_OK) then this routine is
  50302. ** a no-op. If an error occurs, the appropriate error code is written
  50303. ** into *pRC.
  50304. */
  50305. static void ptrmapPut(BtShared *pBt, Pgno key, u8 eType, Pgno parent, int *pRC){
  50306. DbPage *pDbPage; /* The pointer map page */
  50307. u8 *pPtrmap; /* The pointer map data */
  50308. Pgno iPtrmap; /* The pointer map page number */
  50309. int offset; /* Offset in pointer map page */
  50310. int rc; /* Return code from subfunctions */
  50311. if( *pRC ) return;
  50312. assert( sqlite3_mutex_held(pBt->mutex) );
  50313. /* The master-journal page number must never be used as a pointer map page */
  50314. assert( 0==PTRMAP_ISPAGE(pBt, PENDING_BYTE_PAGE(pBt)) );
  50315. assert( pBt->autoVacuum );
  50316. if( key==0 ){
  50317. *pRC = SQLITE_CORRUPT_BKPT;
  50318. return;
  50319. }
  50320. iPtrmap = PTRMAP_PAGENO(pBt, key);
  50321. rc = sqlite3PagerGet(pBt->pPager, iPtrmap, &pDbPage);
  50322. if( rc!=SQLITE_OK ){
  50323. *pRC = rc;
  50324. return;
  50325. }
  50326. offset = PTRMAP_PTROFFSET(iPtrmap, key);
  50327. if( offset<0 ){
  50328. *pRC = SQLITE_CORRUPT_BKPT;
  50329. goto ptrmap_exit;
  50330. }
  50331. assert( offset <= (int)pBt->usableSize-5 );
  50332. pPtrmap = (u8 *)sqlite3PagerGetData(pDbPage);
  50333. if( eType!=pPtrmap[offset] || get4byte(&pPtrmap[offset+1])!=parent ){
  50334. TRACE(("PTRMAP_UPDATE: %d->(%d,%d)\n", key, eType, parent));
  50335. *pRC= rc = sqlite3PagerWrite(pDbPage);
  50336. if( rc==SQLITE_OK ){
  50337. pPtrmap[offset] = eType;
  50338. put4byte(&pPtrmap[offset+1], parent);
  50339. }
  50340. }
  50341. ptrmap_exit:
  50342. sqlite3PagerUnref(pDbPage);
  50343. }
  50344. /*
  50345. ** Read an entry from the pointer map.
  50346. **
  50347. ** This routine retrieves the pointer map entry for page 'key', writing
  50348. ** the type and parent page number to *pEType and *pPgno respectively.
  50349. ** An error code is returned if something goes wrong, otherwise SQLITE_OK.
  50350. */
  50351. static int ptrmapGet(BtShared *pBt, Pgno key, u8 *pEType, Pgno *pPgno){
  50352. DbPage *pDbPage; /* The pointer map page */
  50353. int iPtrmap; /* Pointer map page index */
  50354. u8 *pPtrmap; /* Pointer map page data */
  50355. int offset; /* Offset of entry in pointer map */
  50356. int rc;
  50357. assert( sqlite3_mutex_held(pBt->mutex) );
  50358. iPtrmap = PTRMAP_PAGENO(pBt, key);
  50359. rc = sqlite3PagerGet(pBt->pPager, iPtrmap, &pDbPage);
  50360. if( rc!=0 ){
  50361. return rc;
  50362. }
  50363. pPtrmap = (u8 *)sqlite3PagerGetData(pDbPage);
  50364. offset = PTRMAP_PTROFFSET(iPtrmap, key);
  50365. if( offset<0 ){
  50366. sqlite3PagerUnref(pDbPage);
  50367. return SQLITE_CORRUPT_BKPT;
  50368. }
  50369. assert( offset <= (int)pBt->usableSize-5 );
  50370. assert( pEType!=0 );
  50371. *pEType = pPtrmap[offset];
  50372. if( pPgno ) *pPgno = get4byte(&pPtrmap[offset+1]);
  50373. sqlite3PagerUnref(pDbPage);
  50374. if( *pEType<1 || *pEType>5 ) return SQLITE_CORRUPT_BKPT;
  50375. return SQLITE_OK;
  50376. }
  50377. #else /* if defined SQLITE_OMIT_AUTOVACUUM */
  50378. #define ptrmapPut(w,x,y,z,rc)
  50379. #define ptrmapGet(w,x,y,z) SQLITE_OK
  50380. #define ptrmapPutOvflPtr(x, y, rc)
  50381. #endif
  50382. /*
  50383. ** Given a btree page and a cell index (0 means the first cell on
  50384. ** the page, 1 means the second cell, and so forth) return a pointer
  50385. ** to the cell content.
  50386. **
  50387. ** This routine works only for pages that do not contain overflow cells.
  50388. */
  50389. #define findCell(P,I) \
  50390. ((P)->aData + ((P)->maskPage & get2byte(&(P)->aCellIdx[2*(I)])))
  50391. #define findCellv2(D,M,O,I) (D+(M&get2byte(D+(O+2*(I)))))
  50392. /*
  50393. ** This a more complex version of findCell() that works for
  50394. ** pages that do contain overflow cells.
  50395. */
  50396. static u8 *findOverflowCell(MemPage *pPage, int iCell){
  50397. int i;
  50398. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  50399. for(i=pPage->nOverflow-1; i>=0; i--){
  50400. int k;
  50401. k = pPage->aiOvfl[i];
  50402. if( k<=iCell ){
  50403. if( k==iCell ){
  50404. return pPage->apOvfl[i];
  50405. }
  50406. iCell--;
  50407. }
  50408. }
  50409. return findCell(pPage, iCell);
  50410. }
  50411. /*
  50412. ** Parse a cell content block and fill in the CellInfo structure. There
  50413. ** are two versions of this function. btreeParseCell() takes a
  50414. ** cell index as the second argument and btreeParseCellPtr()
  50415. ** takes a pointer to the body of the cell as its second argument.
  50416. */
  50417. static void btreeParseCellPtr(
  50418. MemPage *pPage, /* Page containing the cell */
  50419. u8 *pCell, /* Pointer to the cell text. */
  50420. CellInfo *pInfo /* Fill in this structure */
  50421. ){
  50422. u8 *pIter; /* For scanning through pCell */
  50423. u32 nPayload; /* Number of bytes of cell payload */
  50424. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  50425. assert( pPage->leaf==0 || pPage->leaf==1 );
  50426. if( pPage->intKeyLeaf ){
  50427. assert( pPage->childPtrSize==0 );
  50428. pIter = pCell + getVarint32(pCell, nPayload);
  50429. pIter += getVarint(pIter, (u64*)&pInfo->nKey);
  50430. }else if( pPage->noPayload ){
  50431. assert( pPage->childPtrSize==4 );
  50432. pInfo->nSize = 4 + getVarint(&pCell[4], (u64*)&pInfo->nKey);
  50433. pInfo->nPayload = 0;
  50434. pInfo->nLocal = 0;
  50435. pInfo->iOverflow = 0;
  50436. pInfo->pPayload = 0;
  50437. return;
  50438. }else{
  50439. pIter = pCell + pPage->childPtrSize;
  50440. pIter += getVarint32(pIter, nPayload);
  50441. pInfo->nKey = nPayload;
  50442. }
  50443. pInfo->nPayload = nPayload;
  50444. pInfo->pPayload = pIter;
  50445. testcase( nPayload==pPage->maxLocal );
  50446. testcase( nPayload==pPage->maxLocal+1 );
  50447. if( nPayload<=pPage->maxLocal ){
  50448. /* This is the (easy) common case where the entire payload fits
  50449. ** on the local page. No overflow is required.
  50450. */
  50451. pInfo->nSize = nPayload + (u16)(pIter - pCell);
  50452. if( pInfo->nSize<4 ) pInfo->nSize = 4;
  50453. pInfo->nLocal = (u16)nPayload;
  50454. pInfo->iOverflow = 0;
  50455. }else{
  50456. /* If the payload will not fit completely on the local page, we have
  50457. ** to decide how much to store locally and how much to spill onto
  50458. ** overflow pages. The strategy is to minimize the amount of unused
  50459. ** space on overflow pages while keeping the amount of local storage
  50460. ** in between minLocal and maxLocal.
  50461. **
  50462. ** Warning: changing the way overflow payload is distributed in any
  50463. ** way will result in an incompatible file format.
  50464. */
  50465. int minLocal; /* Minimum amount of payload held locally */
  50466. int maxLocal; /* Maximum amount of payload held locally */
  50467. int surplus; /* Overflow payload available for local storage */
  50468. minLocal = pPage->minLocal;
  50469. maxLocal = pPage->maxLocal;
  50470. surplus = minLocal + (nPayload - minLocal)%(pPage->pBt->usableSize - 4);
  50471. testcase( surplus==maxLocal );
  50472. testcase( surplus==maxLocal+1 );
  50473. if( surplus <= maxLocal ){
  50474. pInfo->nLocal = (u16)surplus;
  50475. }else{
  50476. pInfo->nLocal = (u16)minLocal;
  50477. }
  50478. pInfo->iOverflow = (u16)(&pInfo->pPayload[pInfo->nLocal] - pCell);
  50479. pInfo->nSize = pInfo->iOverflow + 4;
  50480. }
  50481. }
  50482. static void btreeParseCell(
  50483. MemPage *pPage, /* Page containing the cell */
  50484. int iCell, /* The cell index. First cell is 0 */
  50485. CellInfo *pInfo /* Fill in this structure */
  50486. ){
  50487. btreeParseCellPtr(pPage, findCell(pPage, iCell), pInfo);
  50488. }
  50489. /*
  50490. ** Compute the total number of bytes that a Cell needs in the cell
  50491. ** data area of the btree-page. The return number includes the cell
  50492. ** data header and the local payload, but not any overflow page or
  50493. ** the space used by the cell pointer.
  50494. */
  50495. static u16 cellSizePtr(MemPage *pPage, u8 *pCell){
  50496. u8 *pIter = pCell + pPage->childPtrSize; /* For looping over bytes of pCell */
  50497. u8 *pEnd; /* End mark for a varint */
  50498. u32 nSize; /* Size value to return */
  50499. #ifdef SQLITE_DEBUG
  50500. /* The value returned by this function should always be the same as
  50501. ** the (CellInfo.nSize) value found by doing a full parse of the
  50502. ** cell. If SQLITE_DEBUG is defined, an assert() at the bottom of
  50503. ** this function verifies that this invariant is not violated. */
  50504. CellInfo debuginfo;
  50505. btreeParseCellPtr(pPage, pCell, &debuginfo);
  50506. #endif
  50507. if( pPage->noPayload ){
  50508. pEnd = &pIter[9];
  50509. while( (*pIter++)&0x80 && pIter<pEnd );
  50510. assert( pPage->childPtrSize==4 );
  50511. return (u16)(pIter - pCell);
  50512. }
  50513. nSize = *pIter;
  50514. if( nSize>=0x80 ){
  50515. pEnd = &pIter[9];
  50516. nSize &= 0x7f;
  50517. do{
  50518. nSize = (nSize<<7) | (*++pIter & 0x7f);
  50519. }while( *(pIter)>=0x80 && pIter<pEnd );
  50520. }
  50521. pIter++;
  50522. if( pPage->intKey ){
  50523. /* pIter now points at the 64-bit integer key value, a variable length
  50524. ** integer. The following block moves pIter to point at the first byte
  50525. ** past the end of the key value. */
  50526. pEnd = &pIter[9];
  50527. while( (*pIter++)&0x80 && pIter<pEnd );
  50528. }
  50529. testcase( nSize==pPage->maxLocal );
  50530. testcase( nSize==pPage->maxLocal+1 );
  50531. if( nSize<=pPage->maxLocal ){
  50532. nSize += (u32)(pIter - pCell);
  50533. if( nSize<4 ) nSize = 4;
  50534. }else{
  50535. int minLocal = pPage->minLocal;
  50536. nSize = minLocal + (nSize - minLocal) % (pPage->pBt->usableSize - 4);
  50537. testcase( nSize==pPage->maxLocal );
  50538. testcase( nSize==pPage->maxLocal+1 );
  50539. if( nSize>pPage->maxLocal ){
  50540. nSize = minLocal;
  50541. }
  50542. nSize += 4 + (u16)(pIter - pCell);
  50543. }
  50544. assert( nSize==debuginfo.nSize || CORRUPT_DB );
  50545. return (u16)nSize;
  50546. }
  50547. #ifdef SQLITE_DEBUG
  50548. /* This variation on cellSizePtr() is used inside of assert() statements
  50549. ** only. */
  50550. static u16 cellSize(MemPage *pPage, int iCell){
  50551. return cellSizePtr(pPage, findCell(pPage, iCell));
  50552. }
  50553. #endif
  50554. #ifndef SQLITE_OMIT_AUTOVACUUM
  50555. /*
  50556. ** If the cell pCell, part of page pPage contains a pointer
  50557. ** to an overflow page, insert an entry into the pointer-map
  50558. ** for the overflow page.
  50559. */
  50560. static void ptrmapPutOvflPtr(MemPage *pPage, u8 *pCell, int *pRC){
  50561. CellInfo info;
  50562. if( *pRC ) return;
  50563. assert( pCell!=0 );
  50564. btreeParseCellPtr(pPage, pCell, &info);
  50565. if( info.iOverflow ){
  50566. Pgno ovfl = get4byte(&pCell[info.iOverflow]);
  50567. ptrmapPut(pPage->pBt, ovfl, PTRMAP_OVERFLOW1, pPage->pgno, pRC);
  50568. }
  50569. }
  50570. #endif
  50571. /*
  50572. ** Defragment the page given. All Cells are moved to the
  50573. ** end of the page and all free space is collected into one
  50574. ** big FreeBlk that occurs in between the header and cell
  50575. ** pointer array and the cell content area.
  50576. **
  50577. ** EVIDENCE-OF: R-44582-60138 SQLite may from time to time reorganize a
  50578. ** b-tree page so that there are no freeblocks or fragment bytes, all
  50579. ** unused bytes are contained in the unallocated space region, and all
  50580. ** cells are packed tightly at the end of the page.
  50581. */
  50582. static int defragmentPage(MemPage *pPage){
  50583. int i; /* Loop counter */
  50584. int pc; /* Address of the i-th cell */
  50585. int hdr; /* Offset to the page header */
  50586. int size; /* Size of a cell */
  50587. int usableSize; /* Number of usable bytes on a page */
  50588. int cellOffset; /* Offset to the cell pointer array */
  50589. int cbrk; /* Offset to the cell content area */
  50590. int nCell; /* Number of cells on the page */
  50591. unsigned char *data; /* The page data */
  50592. unsigned char *temp; /* Temp area for cell content */
  50593. unsigned char *src; /* Source of content */
  50594. int iCellFirst; /* First allowable cell index */
  50595. int iCellLast; /* Last possible cell index */
  50596. assert( sqlite3PagerIswriteable(pPage->pDbPage) );
  50597. assert( pPage->pBt!=0 );
  50598. assert( pPage->pBt->usableSize <= SQLITE_MAX_PAGE_SIZE );
  50599. assert( pPage->nOverflow==0 );
  50600. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  50601. temp = 0;
  50602. src = data = pPage->aData;
  50603. hdr = pPage->hdrOffset;
  50604. cellOffset = pPage->cellOffset;
  50605. nCell = pPage->nCell;
  50606. assert( nCell==get2byte(&data[hdr+3]) );
  50607. usableSize = pPage->pBt->usableSize;
  50608. cbrk = usableSize;
  50609. iCellFirst = cellOffset + 2*nCell;
  50610. iCellLast = usableSize - 4;
  50611. for(i=0; i<nCell; i++){
  50612. u8 *pAddr; /* The i-th cell pointer */
  50613. pAddr = &data[cellOffset + i*2];
  50614. pc = get2byte(pAddr);
  50615. testcase( pc==iCellFirst );
  50616. testcase( pc==iCellLast );
  50617. #if !defined(SQLITE_ENABLE_OVERSIZE_CELL_CHECK)
  50618. /* These conditions have already been verified in btreeInitPage()
  50619. ** if SQLITE_ENABLE_OVERSIZE_CELL_CHECK is defined
  50620. */
  50621. if( pc<iCellFirst || pc>iCellLast ){
  50622. return SQLITE_CORRUPT_BKPT;
  50623. }
  50624. #endif
  50625. assert( pc>=iCellFirst && pc<=iCellLast );
  50626. size = cellSizePtr(pPage, &src[pc]);
  50627. cbrk -= size;
  50628. #if defined(SQLITE_ENABLE_OVERSIZE_CELL_CHECK)
  50629. if( cbrk<iCellFirst ){
  50630. return SQLITE_CORRUPT_BKPT;
  50631. }
  50632. #else
  50633. if( cbrk<iCellFirst || pc+size>usableSize ){
  50634. return SQLITE_CORRUPT_BKPT;
  50635. }
  50636. #endif
  50637. assert( cbrk+size<=usableSize && cbrk>=iCellFirst );
  50638. testcase( cbrk+size==usableSize );
  50639. testcase( pc+size==usableSize );
  50640. put2byte(pAddr, cbrk);
  50641. if( temp==0 ){
  50642. int x;
  50643. if( cbrk==pc ) continue;
  50644. temp = sqlite3PagerTempSpace(pPage->pBt->pPager);
  50645. x = get2byte(&data[hdr+5]);
  50646. memcpy(&temp[x], &data[x], (cbrk+size) - x);
  50647. src = temp;
  50648. }
  50649. memcpy(&data[cbrk], &src[pc], size);
  50650. }
  50651. assert( cbrk>=iCellFirst );
  50652. put2byte(&data[hdr+5], cbrk);
  50653. data[hdr+1] = 0;
  50654. data[hdr+2] = 0;
  50655. data[hdr+7] = 0;
  50656. memset(&data[iCellFirst], 0, cbrk-iCellFirst);
  50657. assert( sqlite3PagerIswriteable(pPage->pDbPage) );
  50658. if( cbrk-iCellFirst!=pPage->nFree ){
  50659. return SQLITE_CORRUPT_BKPT;
  50660. }
  50661. return SQLITE_OK;
  50662. }
  50663. /*
  50664. ** Search the free-list on page pPg for space to store a cell nByte bytes in
  50665. ** size. If one can be found, return a pointer to the space and remove it
  50666. ** from the free-list.
  50667. **
  50668. ** If no suitable space can be found on the free-list, return NULL.
  50669. **
  50670. ** This function may detect corruption within pPg. If corruption is
  50671. ** detected then *pRc is set to SQLITE_CORRUPT and NULL is returned.
  50672. **
  50673. ** If a slot of at least nByte bytes is found but cannot be used because
  50674. ** there are already at least 60 fragmented bytes on the page, return NULL.
  50675. ** In this case, if pbDefrag parameter is not NULL, set *pbDefrag to true.
  50676. */
  50677. static u8 *pageFindSlot(MemPage *pPg, int nByte, int *pRc, int *pbDefrag){
  50678. const int hdr = pPg->hdrOffset;
  50679. u8 * const aData = pPg->aData;
  50680. int iAddr;
  50681. int pc;
  50682. int usableSize = pPg->pBt->usableSize;
  50683. for(iAddr=hdr+1; (pc = get2byte(&aData[iAddr]))>0; iAddr=pc){
  50684. int size; /* Size of the free slot */
  50685. /* EVIDENCE-OF: R-06866-39125 Freeblocks are always connected in order of
  50686. ** increasing offset. */
  50687. if( pc>usableSize-4 || pc<iAddr+4 ){
  50688. *pRc = SQLITE_CORRUPT_BKPT;
  50689. return 0;
  50690. }
  50691. /* EVIDENCE-OF: R-22710-53328 The third and fourth bytes of each
  50692. ** freeblock form a big-endian integer which is the size of the freeblock
  50693. ** in bytes, including the 4-byte header. */
  50694. size = get2byte(&aData[pc+2]);
  50695. if( size>=nByte ){
  50696. int x = size - nByte;
  50697. testcase( x==4 );
  50698. testcase( x==3 );
  50699. if( x<4 ){
  50700. /* EVIDENCE-OF: R-11498-58022 In a well-formed b-tree page, the total
  50701. ** number of bytes in fragments may not exceed 60. */
  50702. if( aData[hdr+7]>=60 ){
  50703. if( pbDefrag ) *pbDefrag = 1;
  50704. return 0;
  50705. }
  50706. /* Remove the slot from the free-list. Update the number of
  50707. ** fragmented bytes within the page. */
  50708. memcpy(&aData[iAddr], &aData[pc], 2);
  50709. aData[hdr+7] += (u8)x;
  50710. }else if( size+pc > usableSize ){
  50711. *pRc = SQLITE_CORRUPT_BKPT;
  50712. return 0;
  50713. }else{
  50714. /* The slot remains on the free-list. Reduce its size to account
  50715. ** for the portion used by the new allocation. */
  50716. put2byte(&aData[pc+2], x);
  50717. }
  50718. return &aData[pc + x];
  50719. }
  50720. }
  50721. return 0;
  50722. }
  50723. /*
  50724. ** Allocate nByte bytes of space from within the B-Tree page passed
  50725. ** as the first argument. Write into *pIdx the index into pPage->aData[]
  50726. ** of the first byte of allocated space. Return either SQLITE_OK or
  50727. ** an error code (usually SQLITE_CORRUPT).
  50728. **
  50729. ** The caller guarantees that there is sufficient space to make the
  50730. ** allocation. This routine might need to defragment in order to bring
  50731. ** all the space together, however. This routine will avoid using
  50732. ** the first two bytes past the cell pointer area since presumably this
  50733. ** allocation is being made in order to insert a new cell, so we will
  50734. ** also end up needing a new cell pointer.
  50735. */
  50736. static int allocateSpace(MemPage *pPage, int nByte, int *pIdx){
  50737. const int hdr = pPage->hdrOffset; /* Local cache of pPage->hdrOffset */
  50738. u8 * const data = pPage->aData; /* Local cache of pPage->aData */
  50739. int top; /* First byte of cell content area */
  50740. int rc = SQLITE_OK; /* Integer return code */
  50741. int gap; /* First byte of gap between cell pointers and cell content */
  50742. assert( sqlite3PagerIswriteable(pPage->pDbPage) );
  50743. assert( pPage->pBt );
  50744. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  50745. assert( nByte>=0 ); /* Minimum cell size is 4 */
  50746. assert( pPage->nFree>=nByte );
  50747. assert( pPage->nOverflow==0 );
  50748. assert( nByte < (int)(pPage->pBt->usableSize-8) );
  50749. assert( pPage->cellOffset == hdr + 12 - 4*pPage->leaf );
  50750. gap = pPage->cellOffset + 2*pPage->nCell;
  50751. assert( gap<=65536 );
  50752. /* EVIDENCE-OF: R-29356-02391 If the database uses a 65536-byte page size
  50753. ** and the reserved space is zero (the usual value for reserved space)
  50754. ** then the cell content offset of an empty page wants to be 65536.
  50755. ** However, that integer is too large to be stored in a 2-byte unsigned
  50756. ** integer, so a value of 0 is used in its place. */
  50757. top = get2byteNotZero(&data[hdr+5]);
  50758. if( gap>top ) return SQLITE_CORRUPT_BKPT;
  50759. /* If there is enough space between gap and top for one more cell pointer
  50760. ** array entry offset, and if the freelist is not empty, then search the
  50761. ** freelist looking for a free slot big enough to satisfy the request.
  50762. */
  50763. testcase( gap+2==top );
  50764. testcase( gap+1==top );
  50765. testcase( gap==top );
  50766. if( gap+2<=top && (data[hdr+1] || data[hdr+2]) ){
  50767. int bDefrag = 0;
  50768. u8 *pSpace = pageFindSlot(pPage, nByte, &rc, &bDefrag);
  50769. if( rc ) return rc;
  50770. if( bDefrag ) goto defragment_page;
  50771. if( pSpace ){
  50772. assert( pSpace>=data && (pSpace - data)<65536 );
  50773. *pIdx = (int)(pSpace - data);
  50774. return SQLITE_OK;
  50775. }
  50776. }
  50777. /* The request could not be fulfilled using a freelist slot. Check
  50778. ** to see if defragmentation is necessary.
  50779. */
  50780. testcase( gap+2+nByte==top );
  50781. if( gap+2+nByte>top ){
  50782. defragment_page:
  50783. assert( pPage->nCell>0 || CORRUPT_DB );
  50784. rc = defragmentPage(pPage);
  50785. if( rc ) return rc;
  50786. top = get2byteNotZero(&data[hdr+5]);
  50787. assert( gap+nByte<=top );
  50788. }
  50789. /* Allocate memory from the gap in between the cell pointer array
  50790. ** and the cell content area. The btreeInitPage() call has already
  50791. ** validated the freelist. Given that the freelist is valid, there
  50792. ** is no way that the allocation can extend off the end of the page.
  50793. ** The assert() below verifies the previous sentence.
  50794. */
  50795. top -= nByte;
  50796. put2byte(&data[hdr+5], top);
  50797. assert( top+nByte <= (int)pPage->pBt->usableSize );
  50798. *pIdx = top;
  50799. return SQLITE_OK;
  50800. }
  50801. /*
  50802. ** Return a section of the pPage->aData to the freelist.
  50803. ** The first byte of the new free block is pPage->aData[iStart]
  50804. ** and the size of the block is iSize bytes.
  50805. **
  50806. ** Adjacent freeblocks are coalesced.
  50807. **
  50808. ** Note that even though the freeblock list was checked by btreeInitPage(),
  50809. ** that routine will not detect overlap between cells or freeblocks. Nor
  50810. ** does it detect cells or freeblocks that encrouch into the reserved bytes
  50811. ** at the end of the page. So do additional corruption checks inside this
  50812. ** routine and return SQLITE_CORRUPT if any problems are found.
  50813. */
  50814. static int freeSpace(MemPage *pPage, u16 iStart, u16 iSize){
  50815. u16 iPtr; /* Address of ptr to next freeblock */
  50816. u16 iFreeBlk; /* Address of the next freeblock */
  50817. u8 hdr; /* Page header size. 0 or 100 */
  50818. u8 nFrag = 0; /* Reduction in fragmentation */
  50819. u16 iOrigSize = iSize; /* Original value of iSize */
  50820. u32 iLast = pPage->pBt->usableSize-4; /* Largest possible freeblock offset */
  50821. u32 iEnd = iStart + iSize; /* First byte past the iStart buffer */
  50822. unsigned char *data = pPage->aData; /* Page content */
  50823. assert( pPage->pBt!=0 );
  50824. assert( sqlite3PagerIswriteable(pPage->pDbPage) );
  50825. assert( iStart>=pPage->hdrOffset+6+pPage->childPtrSize );
  50826. assert( CORRUPT_DB || iEnd <= pPage->pBt->usableSize );
  50827. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  50828. assert( iSize>=4 ); /* Minimum cell size is 4 */
  50829. assert( iStart<=iLast );
  50830. /* Overwrite deleted information with zeros when the secure_delete
  50831. ** option is enabled */
  50832. if( pPage->pBt->btsFlags & BTS_SECURE_DELETE ){
  50833. memset(&data[iStart], 0, iSize);
  50834. }
  50835. /* The list of freeblocks must be in ascending order. Find the
  50836. ** spot on the list where iStart should be inserted.
  50837. */
  50838. hdr = pPage->hdrOffset;
  50839. iPtr = hdr + 1;
  50840. if( data[iPtr+1]==0 && data[iPtr]==0 ){
  50841. iFreeBlk = 0; /* Shortcut for the case when the freelist is empty */
  50842. }else{
  50843. while( (iFreeBlk = get2byte(&data[iPtr]))>0 && iFreeBlk<iStart ){
  50844. if( iFreeBlk<iPtr+4 ) return SQLITE_CORRUPT_BKPT;
  50845. iPtr = iFreeBlk;
  50846. }
  50847. if( iFreeBlk>iLast ) return SQLITE_CORRUPT_BKPT;
  50848. assert( iFreeBlk>iPtr || iFreeBlk==0 );
  50849. /* At this point:
  50850. ** iFreeBlk: First freeblock after iStart, or zero if none
  50851. ** iPtr: The address of a pointer iFreeBlk
  50852. **
  50853. ** Check to see if iFreeBlk should be coalesced onto the end of iStart.
  50854. */
  50855. if( iFreeBlk && iEnd+3>=iFreeBlk ){
  50856. nFrag = iFreeBlk - iEnd;
  50857. if( iEnd>iFreeBlk ) return SQLITE_CORRUPT_BKPT;
  50858. iEnd = iFreeBlk + get2byte(&data[iFreeBlk+2]);
  50859. iSize = iEnd - iStart;
  50860. iFreeBlk = get2byte(&data[iFreeBlk]);
  50861. }
  50862. /* If iPtr is another freeblock (that is, if iPtr is not the freelist
  50863. ** pointer in the page header) then check to see if iStart should be
  50864. ** coalesced onto the end of iPtr.
  50865. */
  50866. if( iPtr>hdr+1 ){
  50867. int iPtrEnd = iPtr + get2byte(&data[iPtr+2]);
  50868. if( iPtrEnd+3>=iStart ){
  50869. if( iPtrEnd>iStart ) return SQLITE_CORRUPT_BKPT;
  50870. nFrag += iStart - iPtrEnd;
  50871. iSize = iEnd - iPtr;
  50872. iStart = iPtr;
  50873. }
  50874. }
  50875. if( nFrag>data[hdr+7] ) return SQLITE_CORRUPT_BKPT;
  50876. data[hdr+7] -= nFrag;
  50877. }
  50878. if( iStart==get2byte(&data[hdr+5]) ){
  50879. /* The new freeblock is at the beginning of the cell content area,
  50880. ** so just extend the cell content area rather than create another
  50881. ** freelist entry */
  50882. if( iPtr!=hdr+1 ) return SQLITE_CORRUPT_BKPT;
  50883. put2byte(&data[hdr+1], iFreeBlk);
  50884. put2byte(&data[hdr+5], iEnd);
  50885. }else{
  50886. /* Insert the new freeblock into the freelist */
  50887. put2byte(&data[iPtr], iStart);
  50888. put2byte(&data[iStart], iFreeBlk);
  50889. put2byte(&data[iStart+2], iSize);
  50890. }
  50891. pPage->nFree += iOrigSize;
  50892. return SQLITE_OK;
  50893. }
  50894. /*
  50895. ** Decode the flags byte (the first byte of the header) for a page
  50896. ** and initialize fields of the MemPage structure accordingly.
  50897. **
  50898. ** Only the following combinations are supported. Anything different
  50899. ** indicates a corrupt database files:
  50900. **
  50901. ** PTF_ZERODATA
  50902. ** PTF_ZERODATA | PTF_LEAF
  50903. ** PTF_LEAFDATA | PTF_INTKEY
  50904. ** PTF_LEAFDATA | PTF_INTKEY | PTF_LEAF
  50905. */
  50906. static int decodeFlags(MemPage *pPage, int flagByte){
  50907. BtShared *pBt; /* A copy of pPage->pBt */
  50908. assert( pPage->hdrOffset==(pPage->pgno==1 ? 100 : 0) );
  50909. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  50910. pPage->leaf = (u8)(flagByte>>3); assert( PTF_LEAF == 1<<3 );
  50911. flagByte &= ~PTF_LEAF;
  50912. pPage->childPtrSize = 4-4*pPage->leaf;
  50913. pBt = pPage->pBt;
  50914. if( flagByte==(PTF_LEAFDATA | PTF_INTKEY) ){
  50915. /* EVIDENCE-OF: R-03640-13415 A value of 5 means the page is an interior
  50916. ** table b-tree page. */
  50917. assert( (PTF_LEAFDATA|PTF_INTKEY)==5 );
  50918. /* EVIDENCE-OF: R-20501-61796 A value of 13 means the page is a leaf
  50919. ** table b-tree page. */
  50920. assert( (PTF_LEAFDATA|PTF_INTKEY|PTF_LEAF)==13 );
  50921. pPage->intKey = 1;
  50922. pPage->intKeyLeaf = pPage->leaf;
  50923. pPage->noPayload = !pPage->leaf;
  50924. pPage->maxLocal = pBt->maxLeaf;
  50925. pPage->minLocal = pBt->minLeaf;
  50926. }else if( flagByte==PTF_ZERODATA ){
  50927. /* EVIDENCE-OF: R-27225-53936 A value of 2 means the page is an interior
  50928. ** index b-tree page. */
  50929. assert( (PTF_ZERODATA)==2 );
  50930. /* EVIDENCE-OF: R-16571-11615 A value of 10 means the page is a leaf
  50931. ** index b-tree page. */
  50932. assert( (PTF_ZERODATA|PTF_LEAF)==10 );
  50933. pPage->intKey = 0;
  50934. pPage->intKeyLeaf = 0;
  50935. pPage->noPayload = 0;
  50936. pPage->maxLocal = pBt->maxLocal;
  50937. pPage->minLocal = pBt->minLocal;
  50938. }else{
  50939. /* EVIDENCE-OF: R-47608-56469 Any other value for the b-tree page type is
  50940. ** an error. */
  50941. return SQLITE_CORRUPT_BKPT;
  50942. }
  50943. pPage->max1bytePayload = pBt->max1bytePayload;
  50944. return SQLITE_OK;
  50945. }
  50946. /*
  50947. ** Initialize the auxiliary information for a disk block.
  50948. **
  50949. ** Return SQLITE_OK on success. If we see that the page does
  50950. ** not contain a well-formed database page, then return
  50951. ** SQLITE_CORRUPT. Note that a return of SQLITE_OK does not
  50952. ** guarantee that the page is well-formed. It only shows that
  50953. ** we failed to detect any corruption.
  50954. */
  50955. static int btreeInitPage(MemPage *pPage){
  50956. assert( pPage->pBt!=0 );
  50957. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  50958. assert( pPage->pgno==sqlite3PagerPagenumber(pPage->pDbPage) );
  50959. assert( pPage == sqlite3PagerGetExtra(pPage->pDbPage) );
  50960. assert( pPage->aData == sqlite3PagerGetData(pPage->pDbPage) );
  50961. if( !pPage->isInit ){
  50962. u16 pc; /* Address of a freeblock within pPage->aData[] */
  50963. u8 hdr; /* Offset to beginning of page header */
  50964. u8 *data; /* Equal to pPage->aData */
  50965. BtShared *pBt; /* The main btree structure */
  50966. int usableSize; /* Amount of usable space on each page */
  50967. u16 cellOffset; /* Offset from start of page to first cell pointer */
  50968. int nFree; /* Number of unused bytes on the page */
  50969. int top; /* First byte of the cell content area */
  50970. int iCellFirst; /* First allowable cell or freeblock offset */
  50971. int iCellLast; /* Last possible cell or freeblock offset */
  50972. pBt = pPage->pBt;
  50973. hdr = pPage->hdrOffset;
  50974. data = pPage->aData;
  50975. /* EVIDENCE-OF: R-28594-02890 The one-byte flag at offset 0 indicating
  50976. ** the b-tree page type. */
  50977. if( decodeFlags(pPage, data[hdr]) ) return SQLITE_CORRUPT_BKPT;
  50978. assert( pBt->pageSize>=512 && pBt->pageSize<=65536 );
  50979. pPage->maskPage = (u16)(pBt->pageSize - 1);
  50980. pPage->nOverflow = 0;
  50981. usableSize = pBt->usableSize;
  50982. pPage->cellOffset = cellOffset = hdr + 8 + pPage->childPtrSize;
  50983. pPage->aDataEnd = &data[usableSize];
  50984. pPage->aCellIdx = &data[cellOffset];
  50985. /* EVIDENCE-OF: R-58015-48175 The two-byte integer at offset 5 designates
  50986. ** the start of the cell content area. A zero value for this integer is
  50987. ** interpreted as 65536. */
  50988. top = get2byteNotZero(&data[hdr+5]);
  50989. /* EVIDENCE-OF: R-37002-32774 The two-byte integer at offset 3 gives the
  50990. ** number of cells on the page. */
  50991. pPage->nCell = get2byte(&data[hdr+3]);
  50992. if( pPage->nCell>MX_CELL(pBt) ){
  50993. /* To many cells for a single page. The page must be corrupt */
  50994. return SQLITE_CORRUPT_BKPT;
  50995. }
  50996. testcase( pPage->nCell==MX_CELL(pBt) );
  50997. /* EVIDENCE-OF: R-24089-57979 If a page contains no cells (which is only
  50998. ** possible for a root page of a table that contains no rows) then the
  50999. ** offset to the cell content area will equal the page size minus the
  51000. ** bytes of reserved space. */
  51001. assert( pPage->nCell>0 || top==usableSize || CORRUPT_DB );
  51002. /* A malformed database page might cause us to read past the end
  51003. ** of page when parsing a cell.
  51004. **
  51005. ** The following block of code checks early to see if a cell extends
  51006. ** past the end of a page boundary and causes SQLITE_CORRUPT to be
  51007. ** returned if it does.
  51008. */
  51009. iCellFirst = cellOffset + 2*pPage->nCell;
  51010. iCellLast = usableSize - 4;
  51011. #if defined(SQLITE_ENABLE_OVERSIZE_CELL_CHECK)
  51012. {
  51013. int i; /* Index into the cell pointer array */
  51014. int sz; /* Size of a cell */
  51015. if( !pPage->leaf ) iCellLast--;
  51016. for(i=0; i<pPage->nCell; i++){
  51017. pc = get2byte(&data[cellOffset+i*2]);
  51018. testcase( pc==iCellFirst );
  51019. testcase( pc==iCellLast );
  51020. if( pc<iCellFirst || pc>iCellLast ){
  51021. return SQLITE_CORRUPT_BKPT;
  51022. }
  51023. sz = cellSizePtr(pPage, &data[pc]);
  51024. testcase( pc+sz==usableSize );
  51025. if( pc+sz>usableSize ){
  51026. return SQLITE_CORRUPT_BKPT;
  51027. }
  51028. }
  51029. if( !pPage->leaf ) iCellLast++;
  51030. }
  51031. #endif
  51032. /* Compute the total free space on the page
  51033. ** EVIDENCE-OF: R-23588-34450 The two-byte integer at offset 1 gives the
  51034. ** start of the first freeblock on the page, or is zero if there are no
  51035. ** freeblocks. */
  51036. pc = get2byte(&data[hdr+1]);
  51037. nFree = data[hdr+7] + top; /* Init nFree to non-freeblock free space */
  51038. while( pc>0 ){
  51039. u16 next, size;
  51040. if( pc<iCellFirst || pc>iCellLast ){
  51041. /* EVIDENCE-OF: R-55530-52930 In a well-formed b-tree page, there will
  51042. ** always be at least one cell before the first freeblock.
  51043. **
  51044. ** Or, the freeblock is off the end of the page
  51045. */
  51046. return SQLITE_CORRUPT_BKPT;
  51047. }
  51048. next = get2byte(&data[pc]);
  51049. size = get2byte(&data[pc+2]);
  51050. if( (next>0 && next<=pc+size+3) || pc+size>usableSize ){
  51051. /* Free blocks must be in ascending order. And the last byte of
  51052. ** the free-block must lie on the database page. */
  51053. return SQLITE_CORRUPT_BKPT;
  51054. }
  51055. nFree = nFree + size;
  51056. pc = next;
  51057. }
  51058. /* At this point, nFree contains the sum of the offset to the start
  51059. ** of the cell-content area plus the number of free bytes within
  51060. ** the cell-content area. If this is greater than the usable-size
  51061. ** of the page, then the page must be corrupted. This check also
  51062. ** serves to verify that the offset to the start of the cell-content
  51063. ** area, according to the page header, lies within the page.
  51064. */
  51065. if( nFree>usableSize ){
  51066. return SQLITE_CORRUPT_BKPT;
  51067. }
  51068. pPage->nFree = (u16)(nFree - iCellFirst);
  51069. pPage->isInit = 1;
  51070. }
  51071. return SQLITE_OK;
  51072. }
  51073. /*
  51074. ** Set up a raw page so that it looks like a database page holding
  51075. ** no entries.
  51076. */
  51077. static void zeroPage(MemPage *pPage, int flags){
  51078. unsigned char *data = pPage->aData;
  51079. BtShared *pBt = pPage->pBt;
  51080. u8 hdr = pPage->hdrOffset;
  51081. u16 first;
  51082. assert( sqlite3PagerPagenumber(pPage->pDbPage)==pPage->pgno );
  51083. assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage );
  51084. assert( sqlite3PagerGetData(pPage->pDbPage) == data );
  51085. assert( sqlite3PagerIswriteable(pPage->pDbPage) );
  51086. assert( sqlite3_mutex_held(pBt->mutex) );
  51087. if( pBt->btsFlags & BTS_SECURE_DELETE ){
  51088. memset(&data[hdr], 0, pBt->usableSize - hdr);
  51089. }
  51090. data[hdr] = (char)flags;
  51091. first = hdr + ((flags&PTF_LEAF)==0 ? 12 : 8);
  51092. memset(&data[hdr+1], 0, 4);
  51093. data[hdr+7] = 0;
  51094. put2byte(&data[hdr+5], pBt->usableSize);
  51095. pPage->nFree = (u16)(pBt->usableSize - first);
  51096. decodeFlags(pPage, flags);
  51097. pPage->cellOffset = first;
  51098. pPage->aDataEnd = &data[pBt->usableSize];
  51099. pPage->aCellIdx = &data[first];
  51100. pPage->nOverflow = 0;
  51101. assert( pBt->pageSize>=512 && pBt->pageSize<=65536 );
  51102. pPage->maskPage = (u16)(pBt->pageSize - 1);
  51103. pPage->nCell = 0;
  51104. pPage->isInit = 1;
  51105. }
  51106. /*
  51107. ** Convert a DbPage obtained from the pager into a MemPage used by
  51108. ** the btree layer.
  51109. */
  51110. static MemPage *btreePageFromDbPage(DbPage *pDbPage, Pgno pgno, BtShared *pBt){
  51111. MemPage *pPage = (MemPage*)sqlite3PagerGetExtra(pDbPage);
  51112. pPage->aData = sqlite3PagerGetData(pDbPage);
  51113. pPage->pDbPage = pDbPage;
  51114. pPage->pBt = pBt;
  51115. pPage->pgno = pgno;
  51116. pPage->hdrOffset = pPage->pgno==1 ? 100 : 0;
  51117. return pPage;
  51118. }
  51119. /*
  51120. ** Get a page from the pager. Initialize the MemPage.pBt and
  51121. ** MemPage.aData elements if needed.
  51122. **
  51123. ** If the noContent flag is set, it means that we do not care about
  51124. ** the content of the page at this time. So do not go to the disk
  51125. ** to fetch the content. Just fill in the content with zeros for now.
  51126. ** If in the future we call sqlite3PagerWrite() on this page, that
  51127. ** means we have started to be concerned about content and the disk
  51128. ** read should occur at that point.
  51129. */
  51130. static int btreeGetPage(
  51131. BtShared *pBt, /* The btree */
  51132. Pgno pgno, /* Number of the page to fetch */
  51133. MemPage **ppPage, /* Return the page in this parameter */
  51134. int flags /* PAGER_GET_NOCONTENT or PAGER_GET_READONLY */
  51135. ){
  51136. int rc;
  51137. DbPage *pDbPage;
  51138. assert( flags==0 || flags==PAGER_GET_NOCONTENT || flags==PAGER_GET_READONLY );
  51139. assert( sqlite3_mutex_held(pBt->mutex) );
  51140. rc = sqlite3PagerAcquire(pBt->pPager, pgno, (DbPage**)&pDbPage, flags);
  51141. if( rc ) return rc;
  51142. *ppPage = btreePageFromDbPage(pDbPage, pgno, pBt);
  51143. return SQLITE_OK;
  51144. }
  51145. /*
  51146. ** Retrieve a page from the pager cache. If the requested page is not
  51147. ** already in the pager cache return NULL. Initialize the MemPage.pBt and
  51148. ** MemPage.aData elements if needed.
  51149. */
  51150. static MemPage *btreePageLookup(BtShared *pBt, Pgno pgno){
  51151. DbPage *pDbPage;
  51152. assert( sqlite3_mutex_held(pBt->mutex) );
  51153. pDbPage = sqlite3PagerLookup(pBt->pPager, pgno);
  51154. if( pDbPage ){
  51155. return btreePageFromDbPage(pDbPage, pgno, pBt);
  51156. }
  51157. return 0;
  51158. }
  51159. /*
  51160. ** Return the size of the database file in pages. If there is any kind of
  51161. ** error, return ((unsigned int)-1).
  51162. */
  51163. static Pgno btreePagecount(BtShared *pBt){
  51164. return pBt->nPage;
  51165. }
  51166. SQLITE_PRIVATE u32 sqlite3BtreeLastPage(Btree *p){
  51167. assert( sqlite3BtreeHoldsMutex(p) );
  51168. assert( ((p->pBt->nPage)&0x8000000)==0 );
  51169. return btreePagecount(p->pBt);
  51170. }
  51171. /*
  51172. ** Get a page from the pager and initialize it. This routine is just a
  51173. ** convenience wrapper around separate calls to btreeGetPage() and
  51174. ** btreeInitPage().
  51175. **
  51176. ** If an error occurs, then the value *ppPage is set to is undefined. It
  51177. ** may remain unchanged, or it may be set to an invalid value.
  51178. */
  51179. static int getAndInitPage(
  51180. BtShared *pBt, /* The database file */
  51181. Pgno pgno, /* Number of the page to get */
  51182. MemPage **ppPage, /* Write the page pointer here */
  51183. int bReadonly /* PAGER_GET_READONLY or 0 */
  51184. ){
  51185. int rc;
  51186. assert( sqlite3_mutex_held(pBt->mutex) );
  51187. assert( bReadonly==PAGER_GET_READONLY || bReadonly==0 );
  51188. if( pgno>btreePagecount(pBt) ){
  51189. rc = SQLITE_CORRUPT_BKPT;
  51190. }else{
  51191. rc = btreeGetPage(pBt, pgno, ppPage, bReadonly);
  51192. if( rc==SQLITE_OK && (*ppPage)->isInit==0 ){
  51193. rc = btreeInitPage(*ppPage);
  51194. if( rc!=SQLITE_OK ){
  51195. releasePage(*ppPage);
  51196. }
  51197. }
  51198. }
  51199. testcase( pgno==0 );
  51200. assert( pgno!=0 || rc==SQLITE_CORRUPT );
  51201. return rc;
  51202. }
  51203. /*
  51204. ** Release a MemPage. This should be called once for each prior
  51205. ** call to btreeGetPage.
  51206. */
  51207. static void releasePage(MemPage *pPage){
  51208. if( pPage ){
  51209. assert( pPage->aData );
  51210. assert( pPage->pBt );
  51211. assert( pPage->pDbPage!=0 );
  51212. assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage );
  51213. assert( sqlite3PagerGetData(pPage->pDbPage)==pPage->aData );
  51214. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  51215. sqlite3PagerUnrefNotNull(pPage->pDbPage);
  51216. }
  51217. }
  51218. /*
  51219. ** During a rollback, when the pager reloads information into the cache
  51220. ** so that the cache is restored to its original state at the start of
  51221. ** the transaction, for each page restored this routine is called.
  51222. **
  51223. ** This routine needs to reset the extra data section at the end of the
  51224. ** page to agree with the restored data.
  51225. */
  51226. static void pageReinit(DbPage *pData){
  51227. MemPage *pPage;
  51228. pPage = (MemPage *)sqlite3PagerGetExtra(pData);
  51229. assert( sqlite3PagerPageRefcount(pData)>0 );
  51230. if( pPage->isInit ){
  51231. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  51232. pPage->isInit = 0;
  51233. if( sqlite3PagerPageRefcount(pData)>1 ){
  51234. /* pPage might not be a btree page; it might be an overflow page
  51235. ** or ptrmap page or a free page. In those cases, the following
  51236. ** call to btreeInitPage() will likely return SQLITE_CORRUPT.
  51237. ** But no harm is done by this. And it is very important that
  51238. ** btreeInitPage() be called on every btree page so we make
  51239. ** the call for every page that comes in for re-initing. */
  51240. btreeInitPage(pPage);
  51241. }
  51242. }
  51243. }
  51244. /*
  51245. ** Invoke the busy handler for a btree.
  51246. */
  51247. static int btreeInvokeBusyHandler(void *pArg){
  51248. BtShared *pBt = (BtShared*)pArg;
  51249. assert( pBt->db );
  51250. assert( sqlite3_mutex_held(pBt->db->mutex) );
  51251. return sqlite3InvokeBusyHandler(&pBt->db->busyHandler);
  51252. }
  51253. /*
  51254. ** Open a database file.
  51255. **
  51256. ** zFilename is the name of the database file. If zFilename is NULL
  51257. ** then an ephemeral database is created. The ephemeral database might
  51258. ** be exclusively in memory, or it might use a disk-based memory cache.
  51259. ** Either way, the ephemeral database will be automatically deleted
  51260. ** when sqlite3BtreeClose() is called.
  51261. **
  51262. ** If zFilename is ":memory:" then an in-memory database is created
  51263. ** that is automatically destroyed when it is closed.
  51264. **
  51265. ** The "flags" parameter is a bitmask that might contain bits like
  51266. ** BTREE_OMIT_JOURNAL and/or BTREE_MEMORY.
  51267. **
  51268. ** If the database is already opened in the same database connection
  51269. ** and we are in shared cache mode, then the open will fail with an
  51270. ** SQLITE_CONSTRAINT error. We cannot allow two or more BtShared
  51271. ** objects in the same database connection since doing so will lead
  51272. ** to problems with locking.
  51273. */
  51274. SQLITE_PRIVATE int sqlite3BtreeOpen(
  51275. sqlite3_vfs *pVfs, /* VFS to use for this b-tree */
  51276. const char *zFilename, /* Name of the file containing the BTree database */
  51277. sqlite3 *db, /* Associated database handle */
  51278. Btree **ppBtree, /* Pointer to new Btree object written here */
  51279. int flags, /* Options */
  51280. int vfsFlags /* Flags passed through to sqlite3_vfs.xOpen() */
  51281. ){
  51282. BtShared *pBt = 0; /* Shared part of btree structure */
  51283. Btree *p; /* Handle to return */
  51284. sqlite3_mutex *mutexOpen = 0; /* Prevents a race condition. Ticket #3537 */
  51285. int rc = SQLITE_OK; /* Result code from this function */
  51286. u8 nReserve; /* Byte of unused space on each page */
  51287. unsigned char zDbHeader[100]; /* Database header content */
  51288. /* True if opening an ephemeral, temporary database */
  51289. const int isTempDb = zFilename==0 || zFilename[0]==0;
  51290. /* Set the variable isMemdb to true for an in-memory database, or
  51291. ** false for a file-based database.
  51292. */
  51293. #ifdef SQLITE_OMIT_MEMORYDB
  51294. const int isMemdb = 0;
  51295. #else
  51296. const int isMemdb = (zFilename && strcmp(zFilename, ":memory:")==0)
  51297. || (isTempDb && sqlite3TempInMemory(db))
  51298. || (vfsFlags & SQLITE_OPEN_MEMORY)!=0;
  51299. #endif
  51300. assert( db!=0 );
  51301. assert( pVfs!=0 );
  51302. assert( sqlite3_mutex_held(db->mutex) );
  51303. assert( (flags&0xff)==flags ); /* flags fit in 8 bits */
  51304. /* Only a BTREE_SINGLE database can be BTREE_UNORDERED */
  51305. assert( (flags & BTREE_UNORDERED)==0 || (flags & BTREE_SINGLE)!=0 );
  51306. /* A BTREE_SINGLE database is always a temporary and/or ephemeral */
  51307. assert( (flags & BTREE_SINGLE)==0 || isTempDb );
  51308. if( isMemdb ){
  51309. flags |= BTREE_MEMORY;
  51310. }
  51311. if( (vfsFlags & SQLITE_OPEN_MAIN_DB)!=0 && (isMemdb || isTempDb) ){
  51312. vfsFlags = (vfsFlags & ~SQLITE_OPEN_MAIN_DB) | SQLITE_OPEN_TEMP_DB;
  51313. }
  51314. p = sqlite3MallocZero(sizeof(Btree));
  51315. if( !p ){
  51316. return SQLITE_NOMEM;
  51317. }
  51318. p->inTrans = TRANS_NONE;
  51319. p->db = db;
  51320. #ifndef SQLITE_OMIT_SHARED_CACHE
  51321. p->lock.pBtree = p;
  51322. p->lock.iTable = 1;
  51323. #endif
  51324. #if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
  51325. /*
  51326. ** If this Btree is a candidate for shared cache, try to find an
  51327. ** existing BtShared object that we can share with
  51328. */
  51329. if( isTempDb==0 && (isMemdb==0 || (vfsFlags&SQLITE_OPEN_URI)!=0) ){
  51330. if( vfsFlags & SQLITE_OPEN_SHAREDCACHE ){
  51331. int nFilename = sqlite3Strlen30(zFilename)+1;
  51332. int nFullPathname = pVfs->mxPathname+1;
  51333. char *zFullPathname = sqlite3Malloc(MAX(nFullPathname,nFilename));
  51334. MUTEX_LOGIC( sqlite3_mutex *mutexShared; )
  51335. p->sharable = 1;
  51336. if( !zFullPathname ){
  51337. sqlite3_free(p);
  51338. return SQLITE_NOMEM;
  51339. }
  51340. if( isMemdb ){
  51341. memcpy(zFullPathname, zFilename, nFilename);
  51342. }else{
  51343. rc = sqlite3OsFullPathname(pVfs, zFilename,
  51344. nFullPathname, zFullPathname);
  51345. if( rc ){
  51346. sqlite3_free(zFullPathname);
  51347. sqlite3_free(p);
  51348. return rc;
  51349. }
  51350. }
  51351. #if SQLITE_THREADSAFE
  51352. mutexOpen = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_OPEN);
  51353. sqlite3_mutex_enter(mutexOpen);
  51354. mutexShared = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
  51355. sqlite3_mutex_enter(mutexShared);
  51356. #endif
  51357. for(pBt=GLOBAL(BtShared*,sqlite3SharedCacheList); pBt; pBt=pBt->pNext){
  51358. assert( pBt->nRef>0 );
  51359. if( 0==strcmp(zFullPathname, sqlite3PagerFilename(pBt->pPager, 0))
  51360. && sqlite3PagerVfs(pBt->pPager)==pVfs ){
  51361. int iDb;
  51362. for(iDb=db->nDb-1; iDb>=0; iDb--){
  51363. Btree *pExisting = db->aDb[iDb].pBt;
  51364. if( pExisting && pExisting->pBt==pBt ){
  51365. sqlite3_mutex_leave(mutexShared);
  51366. sqlite3_mutex_leave(mutexOpen);
  51367. sqlite3_free(zFullPathname);
  51368. sqlite3_free(p);
  51369. return SQLITE_CONSTRAINT;
  51370. }
  51371. }
  51372. p->pBt = pBt;
  51373. pBt->nRef++;
  51374. break;
  51375. }
  51376. }
  51377. sqlite3_mutex_leave(mutexShared);
  51378. sqlite3_free(zFullPathname);
  51379. }
  51380. #ifdef SQLITE_DEBUG
  51381. else{
  51382. /* In debug mode, we mark all persistent databases as sharable
  51383. ** even when they are not. This exercises the locking code and
  51384. ** gives more opportunity for asserts(sqlite3_mutex_held())
  51385. ** statements to find locking problems.
  51386. */
  51387. p->sharable = 1;
  51388. }
  51389. #endif
  51390. }
  51391. #endif
  51392. if( pBt==0 ){
  51393. /*
  51394. ** The following asserts make sure that structures used by the btree are
  51395. ** the right size. This is to guard against size changes that result
  51396. ** when compiling on a different architecture.
  51397. */
  51398. assert( sizeof(i64)==8 );
  51399. assert( sizeof(u64)==8 );
  51400. assert( sizeof(u32)==4 );
  51401. assert( sizeof(u16)==2 );
  51402. assert( sizeof(Pgno)==4 );
  51403. pBt = sqlite3MallocZero( sizeof(*pBt) );
  51404. if( pBt==0 ){
  51405. rc = SQLITE_NOMEM;
  51406. goto btree_open_out;
  51407. }
  51408. rc = sqlite3PagerOpen(pVfs, &pBt->pPager, zFilename,
  51409. EXTRA_SIZE, flags, vfsFlags, pageReinit);
  51410. if( rc==SQLITE_OK ){
  51411. sqlite3PagerSetMmapLimit(pBt->pPager, db->szMmap);
  51412. rc = sqlite3PagerReadFileheader(pBt->pPager,sizeof(zDbHeader),zDbHeader);
  51413. }
  51414. if( rc!=SQLITE_OK ){
  51415. goto btree_open_out;
  51416. }
  51417. pBt->openFlags = (u8)flags;
  51418. pBt->db = db;
  51419. sqlite3PagerSetBusyhandler(pBt->pPager, btreeInvokeBusyHandler, pBt);
  51420. p->pBt = pBt;
  51421. pBt->pCursor = 0;
  51422. pBt->pPage1 = 0;
  51423. if( sqlite3PagerIsreadonly(pBt->pPager) ) pBt->btsFlags |= BTS_READ_ONLY;
  51424. #ifdef SQLITE_SECURE_DELETE
  51425. pBt->btsFlags |= BTS_SECURE_DELETE;
  51426. #endif
  51427. /* EVIDENCE-OF: R-51873-39618 The page size for a database file is
  51428. ** determined by the 2-byte integer located at an offset of 16 bytes from
  51429. ** the beginning of the database file. */
  51430. pBt->pageSize = (zDbHeader[16]<<8) | (zDbHeader[17]<<16);
  51431. if( pBt->pageSize<512 || pBt->pageSize>SQLITE_MAX_PAGE_SIZE
  51432. || ((pBt->pageSize-1)&pBt->pageSize)!=0 ){
  51433. pBt->pageSize = 0;
  51434. #ifndef SQLITE_OMIT_AUTOVACUUM
  51435. /* If the magic name ":memory:" will create an in-memory database, then
  51436. ** leave the autoVacuum mode at 0 (do not auto-vacuum), even if
  51437. ** SQLITE_DEFAULT_AUTOVACUUM is true. On the other hand, if
  51438. ** SQLITE_OMIT_MEMORYDB has been defined, then ":memory:" is just a
  51439. ** regular file-name. In this case the auto-vacuum applies as per normal.
  51440. */
  51441. if( zFilename && !isMemdb ){
  51442. pBt->autoVacuum = (SQLITE_DEFAULT_AUTOVACUUM ? 1 : 0);
  51443. pBt->incrVacuum = (SQLITE_DEFAULT_AUTOVACUUM==2 ? 1 : 0);
  51444. }
  51445. #endif
  51446. nReserve = 0;
  51447. }else{
  51448. /* EVIDENCE-OF: R-37497-42412 The size of the reserved region is
  51449. ** determined by the one-byte unsigned integer found at an offset of 20
  51450. ** into the database file header. */
  51451. nReserve = zDbHeader[20];
  51452. pBt->btsFlags |= BTS_PAGESIZE_FIXED;
  51453. #ifndef SQLITE_OMIT_AUTOVACUUM
  51454. pBt->autoVacuum = (get4byte(&zDbHeader[36 + 4*4])?1:0);
  51455. pBt->incrVacuum = (get4byte(&zDbHeader[36 + 7*4])?1:0);
  51456. #endif
  51457. }
  51458. rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize, nReserve);
  51459. if( rc ) goto btree_open_out;
  51460. pBt->usableSize = pBt->pageSize - nReserve;
  51461. assert( (pBt->pageSize & 7)==0 ); /* 8-byte alignment of pageSize */
  51462. #if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
  51463. /* Add the new BtShared object to the linked list sharable BtShareds.
  51464. */
  51465. if( p->sharable ){
  51466. MUTEX_LOGIC( sqlite3_mutex *mutexShared; )
  51467. pBt->nRef = 1;
  51468. MUTEX_LOGIC( mutexShared = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);)
  51469. if( SQLITE_THREADSAFE && sqlite3GlobalConfig.bCoreMutex ){
  51470. pBt->mutex = sqlite3MutexAlloc(SQLITE_MUTEX_FAST);
  51471. if( pBt->mutex==0 ){
  51472. rc = SQLITE_NOMEM;
  51473. db->mallocFailed = 0;
  51474. goto btree_open_out;
  51475. }
  51476. }
  51477. sqlite3_mutex_enter(mutexShared);
  51478. pBt->pNext = GLOBAL(BtShared*,sqlite3SharedCacheList);
  51479. GLOBAL(BtShared*,sqlite3SharedCacheList) = pBt;
  51480. sqlite3_mutex_leave(mutexShared);
  51481. }
  51482. #endif
  51483. }
  51484. #if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
  51485. /* If the new Btree uses a sharable pBtShared, then link the new
  51486. ** Btree into the list of all sharable Btrees for the same connection.
  51487. ** The list is kept in ascending order by pBt address.
  51488. */
  51489. if( p->sharable ){
  51490. int i;
  51491. Btree *pSib;
  51492. for(i=0; i<db->nDb; i++){
  51493. if( (pSib = db->aDb[i].pBt)!=0 && pSib->sharable ){
  51494. while( pSib->pPrev ){ pSib = pSib->pPrev; }
  51495. if( p->pBt<pSib->pBt ){
  51496. p->pNext = pSib;
  51497. p->pPrev = 0;
  51498. pSib->pPrev = p;
  51499. }else{
  51500. while( pSib->pNext && pSib->pNext->pBt<p->pBt ){
  51501. pSib = pSib->pNext;
  51502. }
  51503. p->pNext = pSib->pNext;
  51504. p->pPrev = pSib;
  51505. if( p->pNext ){
  51506. p->pNext->pPrev = p;
  51507. }
  51508. pSib->pNext = p;
  51509. }
  51510. break;
  51511. }
  51512. }
  51513. }
  51514. #endif
  51515. *ppBtree = p;
  51516. btree_open_out:
  51517. if( rc!=SQLITE_OK ){
  51518. if( pBt && pBt->pPager ){
  51519. sqlite3PagerClose(pBt->pPager);
  51520. }
  51521. sqlite3_free(pBt);
  51522. sqlite3_free(p);
  51523. *ppBtree = 0;
  51524. }else{
  51525. /* If the B-Tree was successfully opened, set the pager-cache size to the
  51526. ** default value. Except, when opening on an existing shared pager-cache,
  51527. ** do not change the pager-cache size.
  51528. */
  51529. if( sqlite3BtreeSchema(p, 0, 0)==0 ){
  51530. sqlite3PagerSetCachesize(p->pBt->pPager, SQLITE_DEFAULT_CACHE_SIZE);
  51531. }
  51532. }
  51533. if( mutexOpen ){
  51534. assert( sqlite3_mutex_held(mutexOpen) );
  51535. sqlite3_mutex_leave(mutexOpen);
  51536. }
  51537. return rc;
  51538. }
  51539. /*
  51540. ** Decrement the BtShared.nRef counter. When it reaches zero,
  51541. ** remove the BtShared structure from the sharing list. Return
  51542. ** true if the BtShared.nRef counter reaches zero and return
  51543. ** false if it is still positive.
  51544. */
  51545. static int removeFromSharingList(BtShared *pBt){
  51546. #ifndef SQLITE_OMIT_SHARED_CACHE
  51547. MUTEX_LOGIC( sqlite3_mutex *pMaster; )
  51548. BtShared *pList;
  51549. int removed = 0;
  51550. assert( sqlite3_mutex_notheld(pBt->mutex) );
  51551. MUTEX_LOGIC( pMaster = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); )
  51552. sqlite3_mutex_enter(pMaster);
  51553. pBt->nRef--;
  51554. if( pBt->nRef<=0 ){
  51555. if( GLOBAL(BtShared*,sqlite3SharedCacheList)==pBt ){
  51556. GLOBAL(BtShared*,sqlite3SharedCacheList) = pBt->pNext;
  51557. }else{
  51558. pList = GLOBAL(BtShared*,sqlite3SharedCacheList);
  51559. while( ALWAYS(pList) && pList->pNext!=pBt ){
  51560. pList=pList->pNext;
  51561. }
  51562. if( ALWAYS(pList) ){
  51563. pList->pNext = pBt->pNext;
  51564. }
  51565. }
  51566. if( SQLITE_THREADSAFE ){
  51567. sqlite3_mutex_free(pBt->mutex);
  51568. }
  51569. removed = 1;
  51570. }
  51571. sqlite3_mutex_leave(pMaster);
  51572. return removed;
  51573. #else
  51574. return 1;
  51575. #endif
  51576. }
  51577. /*
  51578. ** Make sure pBt->pTmpSpace points to an allocation of
  51579. ** MX_CELL_SIZE(pBt) bytes with a 4-byte prefix for a left-child
  51580. ** pointer.
  51581. */
  51582. static void allocateTempSpace(BtShared *pBt){
  51583. if( !pBt->pTmpSpace ){
  51584. pBt->pTmpSpace = sqlite3PageMalloc( pBt->pageSize );
  51585. /* One of the uses of pBt->pTmpSpace is to format cells before
  51586. ** inserting them into a leaf page (function fillInCell()). If
  51587. ** a cell is less than 4 bytes in size, it is rounded up to 4 bytes
  51588. ** by the various routines that manipulate binary cells. Which
  51589. ** can mean that fillInCell() only initializes the first 2 or 3
  51590. ** bytes of pTmpSpace, but that the first 4 bytes are copied from
  51591. ** it into a database page. This is not actually a problem, but it
  51592. ** does cause a valgrind error when the 1 or 2 bytes of unitialized
  51593. ** data is passed to system call write(). So to avoid this error,
  51594. ** zero the first 4 bytes of temp space here.
  51595. **
  51596. ** Also: Provide four bytes of initialized space before the
  51597. ** beginning of pTmpSpace as an area available to prepend the
  51598. ** left-child pointer to the beginning of a cell.
  51599. */
  51600. if( pBt->pTmpSpace ){
  51601. memset(pBt->pTmpSpace, 0, 8);
  51602. pBt->pTmpSpace += 4;
  51603. }
  51604. }
  51605. }
  51606. /*
  51607. ** Free the pBt->pTmpSpace allocation
  51608. */
  51609. static void freeTempSpace(BtShared *pBt){
  51610. if( pBt->pTmpSpace ){
  51611. pBt->pTmpSpace -= 4;
  51612. sqlite3PageFree(pBt->pTmpSpace);
  51613. pBt->pTmpSpace = 0;
  51614. }
  51615. }
  51616. /*
  51617. ** Close an open database and invalidate all cursors.
  51618. */
  51619. SQLITE_PRIVATE int sqlite3BtreeClose(Btree *p){
  51620. BtShared *pBt = p->pBt;
  51621. BtCursor *pCur;
  51622. /* Close all cursors opened via this handle. */
  51623. assert( sqlite3_mutex_held(p->db->mutex) );
  51624. sqlite3BtreeEnter(p);
  51625. pCur = pBt->pCursor;
  51626. while( pCur ){
  51627. BtCursor *pTmp = pCur;
  51628. pCur = pCur->pNext;
  51629. if( pTmp->pBtree==p ){
  51630. sqlite3BtreeCloseCursor(pTmp);
  51631. }
  51632. }
  51633. /* Rollback any active transaction and free the handle structure.
  51634. ** The call to sqlite3BtreeRollback() drops any table-locks held by
  51635. ** this handle.
  51636. */
  51637. sqlite3BtreeRollback(p, SQLITE_OK, 0);
  51638. sqlite3BtreeLeave(p);
  51639. /* If there are still other outstanding references to the shared-btree
  51640. ** structure, return now. The remainder of this procedure cleans
  51641. ** up the shared-btree.
  51642. */
  51643. assert( p->wantToLock==0 && p->locked==0 );
  51644. if( !p->sharable || removeFromSharingList(pBt) ){
  51645. /* The pBt is no longer on the sharing list, so we can access
  51646. ** it without having to hold the mutex.
  51647. **
  51648. ** Clean out and delete the BtShared object.
  51649. */
  51650. assert( !pBt->pCursor );
  51651. sqlite3PagerClose(pBt->pPager);
  51652. if( pBt->xFreeSchema && pBt->pSchema ){
  51653. pBt->xFreeSchema(pBt->pSchema);
  51654. }
  51655. sqlite3DbFree(0, pBt->pSchema);
  51656. freeTempSpace(pBt);
  51657. sqlite3_free(pBt);
  51658. }
  51659. #ifndef SQLITE_OMIT_SHARED_CACHE
  51660. assert( p->wantToLock==0 );
  51661. assert( p->locked==0 );
  51662. if( p->pPrev ) p->pPrev->pNext = p->pNext;
  51663. if( p->pNext ) p->pNext->pPrev = p->pPrev;
  51664. #endif
  51665. sqlite3_free(p);
  51666. return SQLITE_OK;
  51667. }
  51668. /*
  51669. ** Change the limit on the number of pages allowed in the cache.
  51670. **
  51671. ** The maximum number of cache pages is set to the absolute
  51672. ** value of mxPage. If mxPage is negative, the pager will
  51673. ** operate asynchronously - it will not stop to do fsync()s
  51674. ** to insure data is written to the disk surface before
  51675. ** continuing. Transactions still work if synchronous is off,
  51676. ** and the database cannot be corrupted if this program
  51677. ** crashes. But if the operating system crashes or there is
  51678. ** an abrupt power failure when synchronous is off, the database
  51679. ** could be left in an inconsistent and unrecoverable state.
  51680. ** Synchronous is on by default so database corruption is not
  51681. ** normally a worry.
  51682. */
  51683. SQLITE_PRIVATE int sqlite3BtreeSetCacheSize(Btree *p, int mxPage){
  51684. BtShared *pBt = p->pBt;
  51685. assert( sqlite3_mutex_held(p->db->mutex) );
  51686. sqlite3BtreeEnter(p);
  51687. sqlite3PagerSetCachesize(pBt->pPager, mxPage);
  51688. sqlite3BtreeLeave(p);
  51689. return SQLITE_OK;
  51690. }
  51691. #if SQLITE_MAX_MMAP_SIZE>0
  51692. /*
  51693. ** Change the limit on the amount of the database file that may be
  51694. ** memory mapped.
  51695. */
  51696. SQLITE_PRIVATE int sqlite3BtreeSetMmapLimit(Btree *p, sqlite3_int64 szMmap){
  51697. BtShared *pBt = p->pBt;
  51698. assert( sqlite3_mutex_held(p->db->mutex) );
  51699. sqlite3BtreeEnter(p);
  51700. sqlite3PagerSetMmapLimit(pBt->pPager, szMmap);
  51701. sqlite3BtreeLeave(p);
  51702. return SQLITE_OK;
  51703. }
  51704. #endif /* SQLITE_MAX_MMAP_SIZE>0 */
  51705. /*
  51706. ** Change the way data is synced to disk in order to increase or decrease
  51707. ** how well the database resists damage due to OS crashes and power
  51708. ** failures. Level 1 is the same as asynchronous (no syncs() occur and
  51709. ** there is a high probability of damage) Level 2 is the default. There
  51710. ** is a very low but non-zero probability of damage. Level 3 reduces the
  51711. ** probability of damage to near zero but with a write performance reduction.
  51712. */
  51713. #ifndef SQLITE_OMIT_PAGER_PRAGMAS
  51714. SQLITE_PRIVATE int sqlite3BtreeSetPagerFlags(
  51715. Btree *p, /* The btree to set the safety level on */
  51716. unsigned pgFlags /* Various PAGER_* flags */
  51717. ){
  51718. BtShared *pBt = p->pBt;
  51719. assert( sqlite3_mutex_held(p->db->mutex) );
  51720. sqlite3BtreeEnter(p);
  51721. sqlite3PagerSetFlags(pBt->pPager, pgFlags);
  51722. sqlite3BtreeLeave(p);
  51723. return SQLITE_OK;
  51724. }
  51725. #endif
  51726. /*
  51727. ** Return TRUE if the given btree is set to safety level 1. In other
  51728. ** words, return TRUE if no sync() occurs on the disk files.
  51729. */
  51730. SQLITE_PRIVATE int sqlite3BtreeSyncDisabled(Btree *p){
  51731. BtShared *pBt = p->pBt;
  51732. int rc;
  51733. assert( sqlite3_mutex_held(p->db->mutex) );
  51734. sqlite3BtreeEnter(p);
  51735. assert( pBt && pBt->pPager );
  51736. rc = sqlite3PagerNosync(pBt->pPager);
  51737. sqlite3BtreeLeave(p);
  51738. return rc;
  51739. }
  51740. /*
  51741. ** Change the default pages size and the number of reserved bytes per page.
  51742. ** Or, if the page size has already been fixed, return SQLITE_READONLY
  51743. ** without changing anything.
  51744. **
  51745. ** The page size must be a power of 2 between 512 and 65536. If the page
  51746. ** size supplied does not meet this constraint then the page size is not
  51747. ** changed.
  51748. **
  51749. ** Page sizes are constrained to be a power of two so that the region
  51750. ** of the database file used for locking (beginning at PENDING_BYTE,
  51751. ** the first byte past the 1GB boundary, 0x40000000) needs to occur
  51752. ** at the beginning of a page.
  51753. **
  51754. ** If parameter nReserve is less than zero, then the number of reserved
  51755. ** bytes per page is left unchanged.
  51756. **
  51757. ** If the iFix!=0 then the BTS_PAGESIZE_FIXED flag is set so that the page size
  51758. ** and autovacuum mode can no longer be changed.
  51759. */
  51760. SQLITE_PRIVATE int sqlite3BtreeSetPageSize(Btree *p, int pageSize, int nReserve, int iFix){
  51761. int rc = SQLITE_OK;
  51762. BtShared *pBt = p->pBt;
  51763. assert( nReserve>=-1 && nReserve<=255 );
  51764. sqlite3BtreeEnter(p);
  51765. #if SQLITE_HAS_CODEC
  51766. if( nReserve>pBt->optimalReserve ) pBt->optimalReserve = (u8)nReserve;
  51767. #endif
  51768. if( pBt->btsFlags & BTS_PAGESIZE_FIXED ){
  51769. sqlite3BtreeLeave(p);
  51770. return SQLITE_READONLY;
  51771. }
  51772. if( nReserve<0 ){
  51773. nReserve = pBt->pageSize - pBt->usableSize;
  51774. }
  51775. assert( nReserve>=0 && nReserve<=255 );
  51776. if( pageSize>=512 && pageSize<=SQLITE_MAX_PAGE_SIZE &&
  51777. ((pageSize-1)&pageSize)==0 ){
  51778. assert( (pageSize & 7)==0 );
  51779. assert( !pBt->pCursor );
  51780. pBt->pageSize = (u32)pageSize;
  51781. freeTempSpace(pBt);
  51782. }
  51783. rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize, nReserve);
  51784. pBt->usableSize = pBt->pageSize - (u16)nReserve;
  51785. if( iFix ) pBt->btsFlags |= BTS_PAGESIZE_FIXED;
  51786. sqlite3BtreeLeave(p);
  51787. return rc;
  51788. }
  51789. /*
  51790. ** Return the currently defined page size
  51791. */
  51792. SQLITE_PRIVATE int sqlite3BtreeGetPageSize(Btree *p){
  51793. return p->pBt->pageSize;
  51794. }
  51795. /*
  51796. ** This function is similar to sqlite3BtreeGetReserve(), except that it
  51797. ** may only be called if it is guaranteed that the b-tree mutex is already
  51798. ** held.
  51799. **
  51800. ** This is useful in one special case in the backup API code where it is
  51801. ** known that the shared b-tree mutex is held, but the mutex on the
  51802. ** database handle that owns *p is not. In this case if sqlite3BtreeEnter()
  51803. ** were to be called, it might collide with some other operation on the
  51804. ** database handle that owns *p, causing undefined behavior.
  51805. */
  51806. SQLITE_PRIVATE int sqlite3BtreeGetReserveNoMutex(Btree *p){
  51807. int n;
  51808. assert( sqlite3_mutex_held(p->pBt->mutex) );
  51809. n = p->pBt->pageSize - p->pBt->usableSize;
  51810. return n;
  51811. }
  51812. /*
  51813. ** Return the number of bytes of space at the end of every page that
  51814. ** are intentually left unused. This is the "reserved" space that is
  51815. ** sometimes used by extensions.
  51816. **
  51817. ** If SQLITE_HAS_MUTEX is defined then the number returned is the
  51818. ** greater of the current reserved space and the maximum requested
  51819. ** reserve space.
  51820. */
  51821. SQLITE_PRIVATE int sqlite3BtreeGetOptimalReserve(Btree *p){
  51822. int n;
  51823. sqlite3BtreeEnter(p);
  51824. n = sqlite3BtreeGetReserveNoMutex(p);
  51825. #ifdef SQLITE_HAS_CODEC
  51826. if( n<p->pBt->optimalReserve ) n = p->pBt->optimalReserve;
  51827. #endif
  51828. sqlite3BtreeLeave(p);
  51829. return n;
  51830. }
  51831. /*
  51832. ** Set the maximum page count for a database if mxPage is positive.
  51833. ** No changes are made if mxPage is 0 or negative.
  51834. ** Regardless of the value of mxPage, return the maximum page count.
  51835. */
  51836. SQLITE_PRIVATE int sqlite3BtreeMaxPageCount(Btree *p, int mxPage){
  51837. int n;
  51838. sqlite3BtreeEnter(p);
  51839. n = sqlite3PagerMaxPageCount(p->pBt->pPager, mxPage);
  51840. sqlite3BtreeLeave(p);
  51841. return n;
  51842. }
  51843. /*
  51844. ** Set the BTS_SECURE_DELETE flag if newFlag is 0 or 1. If newFlag is -1,
  51845. ** then make no changes. Always return the value of the BTS_SECURE_DELETE
  51846. ** setting after the change.
  51847. */
  51848. SQLITE_PRIVATE int sqlite3BtreeSecureDelete(Btree *p, int newFlag){
  51849. int b;
  51850. if( p==0 ) return 0;
  51851. sqlite3BtreeEnter(p);
  51852. if( newFlag>=0 ){
  51853. p->pBt->btsFlags &= ~BTS_SECURE_DELETE;
  51854. if( newFlag ) p->pBt->btsFlags |= BTS_SECURE_DELETE;
  51855. }
  51856. b = (p->pBt->btsFlags & BTS_SECURE_DELETE)!=0;
  51857. sqlite3BtreeLeave(p);
  51858. return b;
  51859. }
  51860. /*
  51861. ** Change the 'auto-vacuum' property of the database. If the 'autoVacuum'
  51862. ** parameter is non-zero, then auto-vacuum mode is enabled. If zero, it
  51863. ** is disabled. The default value for the auto-vacuum property is
  51864. ** determined by the SQLITE_DEFAULT_AUTOVACUUM macro.
  51865. */
  51866. SQLITE_PRIVATE int sqlite3BtreeSetAutoVacuum(Btree *p, int autoVacuum){
  51867. #ifdef SQLITE_OMIT_AUTOVACUUM
  51868. return SQLITE_READONLY;
  51869. #else
  51870. BtShared *pBt = p->pBt;
  51871. int rc = SQLITE_OK;
  51872. u8 av = (u8)autoVacuum;
  51873. sqlite3BtreeEnter(p);
  51874. if( (pBt->btsFlags & BTS_PAGESIZE_FIXED)!=0 && (av ?1:0)!=pBt->autoVacuum ){
  51875. rc = SQLITE_READONLY;
  51876. }else{
  51877. pBt->autoVacuum = av ?1:0;
  51878. pBt->incrVacuum = av==2 ?1:0;
  51879. }
  51880. sqlite3BtreeLeave(p);
  51881. return rc;
  51882. #endif
  51883. }
  51884. /*
  51885. ** Return the value of the 'auto-vacuum' property. If auto-vacuum is
  51886. ** enabled 1 is returned. Otherwise 0.
  51887. */
  51888. SQLITE_PRIVATE int sqlite3BtreeGetAutoVacuum(Btree *p){
  51889. #ifdef SQLITE_OMIT_AUTOVACUUM
  51890. return BTREE_AUTOVACUUM_NONE;
  51891. #else
  51892. int rc;
  51893. sqlite3BtreeEnter(p);
  51894. rc = (
  51895. (!p->pBt->autoVacuum)?BTREE_AUTOVACUUM_NONE:
  51896. (!p->pBt->incrVacuum)?BTREE_AUTOVACUUM_FULL:
  51897. BTREE_AUTOVACUUM_INCR
  51898. );
  51899. sqlite3BtreeLeave(p);
  51900. return rc;
  51901. #endif
  51902. }
  51903. /*
  51904. ** Get a reference to pPage1 of the database file. This will
  51905. ** also acquire a readlock on that file.
  51906. **
  51907. ** SQLITE_OK is returned on success. If the file is not a
  51908. ** well-formed database file, then SQLITE_CORRUPT is returned.
  51909. ** SQLITE_BUSY is returned if the database is locked. SQLITE_NOMEM
  51910. ** is returned if we run out of memory.
  51911. */
  51912. static int lockBtree(BtShared *pBt){
  51913. int rc; /* Result code from subfunctions */
  51914. MemPage *pPage1; /* Page 1 of the database file */
  51915. int nPage; /* Number of pages in the database */
  51916. int nPageFile = 0; /* Number of pages in the database file */
  51917. int nPageHeader; /* Number of pages in the database according to hdr */
  51918. assert( sqlite3_mutex_held(pBt->mutex) );
  51919. assert( pBt->pPage1==0 );
  51920. rc = sqlite3PagerSharedLock(pBt->pPager);
  51921. if( rc!=SQLITE_OK ) return rc;
  51922. rc = btreeGetPage(pBt, 1, &pPage1, 0);
  51923. if( rc!=SQLITE_OK ) return rc;
  51924. /* Do some checking to help insure the file we opened really is
  51925. ** a valid database file.
  51926. */
  51927. nPage = nPageHeader = get4byte(28+(u8*)pPage1->aData);
  51928. sqlite3PagerPagecount(pBt->pPager, &nPageFile);
  51929. if( nPage==0 || memcmp(24+(u8*)pPage1->aData, 92+(u8*)pPage1->aData,4)!=0 ){
  51930. nPage = nPageFile;
  51931. }
  51932. if( nPage>0 ){
  51933. u32 pageSize;
  51934. u32 usableSize;
  51935. u8 *page1 = pPage1->aData;
  51936. rc = SQLITE_NOTADB;
  51937. /* EVIDENCE-OF: R-43737-39999 Every valid SQLite database file begins
  51938. ** with the following 16 bytes (in hex): 53 51 4c 69 74 65 20 66 6f 72 6d
  51939. ** 61 74 20 33 00. */
  51940. if( memcmp(page1, zMagicHeader, 16)!=0 ){
  51941. goto page1_init_failed;
  51942. }
  51943. #ifdef SQLITE_OMIT_WAL
  51944. if( page1[18]>1 ){
  51945. pBt->btsFlags |= BTS_READ_ONLY;
  51946. }
  51947. if( page1[19]>1 ){
  51948. goto page1_init_failed;
  51949. }
  51950. #else
  51951. if( page1[18]>2 ){
  51952. pBt->btsFlags |= BTS_READ_ONLY;
  51953. }
  51954. if( page1[19]>2 ){
  51955. goto page1_init_failed;
  51956. }
  51957. /* If the write version is set to 2, this database should be accessed
  51958. ** in WAL mode. If the log is not already open, open it now. Then
  51959. ** return SQLITE_OK and return without populating BtShared.pPage1.
  51960. ** The caller detects this and calls this function again. This is
  51961. ** required as the version of page 1 currently in the page1 buffer
  51962. ** may not be the latest version - there may be a newer one in the log
  51963. ** file.
  51964. */
  51965. if( page1[19]==2 && (pBt->btsFlags & BTS_NO_WAL)==0 ){
  51966. int isOpen = 0;
  51967. rc = sqlite3PagerOpenWal(pBt->pPager, &isOpen);
  51968. if( rc!=SQLITE_OK ){
  51969. goto page1_init_failed;
  51970. }else if( isOpen==0 ){
  51971. releasePage(pPage1);
  51972. return SQLITE_OK;
  51973. }
  51974. rc = SQLITE_NOTADB;
  51975. }
  51976. #endif
  51977. /* EVIDENCE-OF: R-15465-20813 The maximum and minimum embedded payload
  51978. ** fractions and the leaf payload fraction values must be 64, 32, and 32.
  51979. **
  51980. ** The original design allowed these amounts to vary, but as of
  51981. ** version 3.6.0, we require them to be fixed.
  51982. */
  51983. if( memcmp(&page1[21], "\100\040\040",3)!=0 ){
  51984. goto page1_init_failed;
  51985. }
  51986. /* EVIDENCE-OF: R-51873-39618 The page size for a database file is
  51987. ** determined by the 2-byte integer located at an offset of 16 bytes from
  51988. ** the beginning of the database file. */
  51989. pageSize = (page1[16]<<8) | (page1[17]<<16);
  51990. /* EVIDENCE-OF: R-25008-21688 The size of a page is a power of two
  51991. ** between 512 and 65536 inclusive. */
  51992. if( ((pageSize-1)&pageSize)!=0
  51993. || pageSize>SQLITE_MAX_PAGE_SIZE
  51994. || pageSize<=256
  51995. ){
  51996. goto page1_init_failed;
  51997. }
  51998. assert( (pageSize & 7)==0 );
  51999. /* EVIDENCE-OF: R-59310-51205 The "reserved space" size in the 1-byte
  52000. ** integer at offset 20 is the number of bytes of space at the end of
  52001. ** each page to reserve for extensions.
  52002. **
  52003. ** EVIDENCE-OF: R-37497-42412 The size of the reserved region is
  52004. ** determined by the one-byte unsigned integer found at an offset of 20
  52005. ** into the database file header. */
  52006. usableSize = pageSize - page1[20];
  52007. if( (u32)pageSize!=pBt->pageSize ){
  52008. /* After reading the first page of the database assuming a page size
  52009. ** of BtShared.pageSize, we have discovered that the page-size is
  52010. ** actually pageSize. Unlock the database, leave pBt->pPage1 at
  52011. ** zero and return SQLITE_OK. The caller will call this function
  52012. ** again with the correct page-size.
  52013. */
  52014. releasePage(pPage1);
  52015. pBt->usableSize = usableSize;
  52016. pBt->pageSize = pageSize;
  52017. freeTempSpace(pBt);
  52018. rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize,
  52019. pageSize-usableSize);
  52020. return rc;
  52021. }
  52022. if( (pBt->db->flags & SQLITE_RecoveryMode)==0 && nPage>nPageFile ){
  52023. rc = SQLITE_CORRUPT_BKPT;
  52024. goto page1_init_failed;
  52025. }
  52026. /* EVIDENCE-OF: R-28312-64704 However, the usable size is not allowed to
  52027. ** be less than 480. In other words, if the page size is 512, then the
  52028. ** reserved space size cannot exceed 32. */
  52029. if( usableSize<480 ){
  52030. goto page1_init_failed;
  52031. }
  52032. pBt->pageSize = pageSize;
  52033. pBt->usableSize = usableSize;
  52034. #ifndef SQLITE_OMIT_AUTOVACUUM
  52035. pBt->autoVacuum = (get4byte(&page1[36 + 4*4])?1:0);
  52036. pBt->incrVacuum = (get4byte(&page1[36 + 7*4])?1:0);
  52037. #endif
  52038. }
  52039. /* maxLocal is the maximum amount of payload to store locally for
  52040. ** a cell. Make sure it is small enough so that at least minFanout
  52041. ** cells can will fit on one page. We assume a 10-byte page header.
  52042. ** Besides the payload, the cell must store:
  52043. ** 2-byte pointer to the cell
  52044. ** 4-byte child pointer
  52045. ** 9-byte nKey value
  52046. ** 4-byte nData value
  52047. ** 4-byte overflow page pointer
  52048. ** So a cell consists of a 2-byte pointer, a header which is as much as
  52049. ** 17 bytes long, 0 to N bytes of payload, and an optional 4 byte overflow
  52050. ** page pointer.
  52051. */
  52052. pBt->maxLocal = (u16)((pBt->usableSize-12)*64/255 - 23);
  52053. pBt->minLocal = (u16)((pBt->usableSize-12)*32/255 - 23);
  52054. pBt->maxLeaf = (u16)(pBt->usableSize - 35);
  52055. pBt->minLeaf = (u16)((pBt->usableSize-12)*32/255 - 23);
  52056. if( pBt->maxLocal>127 ){
  52057. pBt->max1bytePayload = 127;
  52058. }else{
  52059. pBt->max1bytePayload = (u8)pBt->maxLocal;
  52060. }
  52061. assert( pBt->maxLeaf + 23 <= MX_CELL_SIZE(pBt) );
  52062. pBt->pPage1 = pPage1;
  52063. pBt->nPage = nPage;
  52064. return SQLITE_OK;
  52065. page1_init_failed:
  52066. releasePage(pPage1);
  52067. pBt->pPage1 = 0;
  52068. return rc;
  52069. }
  52070. #ifndef NDEBUG
  52071. /*
  52072. ** Return the number of cursors open on pBt. This is for use
  52073. ** in assert() expressions, so it is only compiled if NDEBUG is not
  52074. ** defined.
  52075. **
  52076. ** Only write cursors are counted if wrOnly is true. If wrOnly is
  52077. ** false then all cursors are counted.
  52078. **
  52079. ** For the purposes of this routine, a cursor is any cursor that
  52080. ** is capable of reading or writing to the database. Cursors that
  52081. ** have been tripped into the CURSOR_FAULT state are not counted.
  52082. */
  52083. static int countValidCursors(BtShared *pBt, int wrOnly){
  52084. BtCursor *pCur;
  52085. int r = 0;
  52086. for(pCur=pBt->pCursor; pCur; pCur=pCur->pNext){
  52087. if( (wrOnly==0 || (pCur->curFlags & BTCF_WriteFlag)!=0)
  52088. && pCur->eState!=CURSOR_FAULT ) r++;
  52089. }
  52090. return r;
  52091. }
  52092. #endif
  52093. /*
  52094. ** If there are no outstanding cursors and we are not in the middle
  52095. ** of a transaction but there is a read lock on the database, then
  52096. ** this routine unrefs the first page of the database file which
  52097. ** has the effect of releasing the read lock.
  52098. **
  52099. ** If there is a transaction in progress, this routine is a no-op.
  52100. */
  52101. static void unlockBtreeIfUnused(BtShared *pBt){
  52102. assert( sqlite3_mutex_held(pBt->mutex) );
  52103. assert( countValidCursors(pBt,0)==0 || pBt->inTransaction>TRANS_NONE );
  52104. if( pBt->inTransaction==TRANS_NONE && pBt->pPage1!=0 ){
  52105. MemPage *pPage1 = pBt->pPage1;
  52106. assert( pPage1->aData );
  52107. assert( sqlite3PagerRefcount(pBt->pPager)==1 );
  52108. pBt->pPage1 = 0;
  52109. releasePage(pPage1);
  52110. }
  52111. }
  52112. /*
  52113. ** If pBt points to an empty file then convert that empty file
  52114. ** into a new empty database by initializing the first page of
  52115. ** the database.
  52116. */
  52117. static int newDatabase(BtShared *pBt){
  52118. MemPage *pP1;
  52119. unsigned char *data;
  52120. int rc;
  52121. assert( sqlite3_mutex_held(pBt->mutex) );
  52122. if( pBt->nPage>0 ){
  52123. return SQLITE_OK;
  52124. }
  52125. pP1 = pBt->pPage1;
  52126. assert( pP1!=0 );
  52127. data = pP1->aData;
  52128. rc = sqlite3PagerWrite(pP1->pDbPage);
  52129. if( rc ) return rc;
  52130. memcpy(data, zMagicHeader, sizeof(zMagicHeader));
  52131. assert( sizeof(zMagicHeader)==16 );
  52132. data[16] = (u8)((pBt->pageSize>>8)&0xff);
  52133. data[17] = (u8)((pBt->pageSize>>16)&0xff);
  52134. data[18] = 1;
  52135. data[19] = 1;
  52136. assert( pBt->usableSize<=pBt->pageSize && pBt->usableSize+255>=pBt->pageSize);
  52137. data[20] = (u8)(pBt->pageSize - pBt->usableSize);
  52138. data[21] = 64;
  52139. data[22] = 32;
  52140. data[23] = 32;
  52141. memset(&data[24], 0, 100-24);
  52142. zeroPage(pP1, PTF_INTKEY|PTF_LEAF|PTF_LEAFDATA );
  52143. pBt->btsFlags |= BTS_PAGESIZE_FIXED;
  52144. #ifndef SQLITE_OMIT_AUTOVACUUM
  52145. assert( pBt->autoVacuum==1 || pBt->autoVacuum==0 );
  52146. assert( pBt->incrVacuum==1 || pBt->incrVacuum==0 );
  52147. put4byte(&data[36 + 4*4], pBt->autoVacuum);
  52148. put4byte(&data[36 + 7*4], pBt->incrVacuum);
  52149. #endif
  52150. pBt->nPage = 1;
  52151. data[31] = 1;
  52152. return SQLITE_OK;
  52153. }
  52154. /*
  52155. ** Initialize the first page of the database file (creating a database
  52156. ** consisting of a single page and no schema objects). Return SQLITE_OK
  52157. ** if successful, or an SQLite error code otherwise.
  52158. */
  52159. SQLITE_PRIVATE int sqlite3BtreeNewDb(Btree *p){
  52160. int rc;
  52161. sqlite3BtreeEnter(p);
  52162. p->pBt->nPage = 0;
  52163. rc = newDatabase(p->pBt);
  52164. sqlite3BtreeLeave(p);
  52165. return rc;
  52166. }
  52167. /*
  52168. ** Attempt to start a new transaction. A write-transaction
  52169. ** is started if the second argument is nonzero, otherwise a read-
  52170. ** transaction. If the second argument is 2 or more and exclusive
  52171. ** transaction is started, meaning that no other process is allowed
  52172. ** to access the database. A preexisting transaction may not be
  52173. ** upgraded to exclusive by calling this routine a second time - the
  52174. ** exclusivity flag only works for a new transaction.
  52175. **
  52176. ** A write-transaction must be started before attempting any
  52177. ** changes to the database. None of the following routines
  52178. ** will work unless a transaction is started first:
  52179. **
  52180. ** sqlite3BtreeCreateTable()
  52181. ** sqlite3BtreeCreateIndex()
  52182. ** sqlite3BtreeClearTable()
  52183. ** sqlite3BtreeDropTable()
  52184. ** sqlite3BtreeInsert()
  52185. ** sqlite3BtreeDelete()
  52186. ** sqlite3BtreeUpdateMeta()
  52187. **
  52188. ** If an initial attempt to acquire the lock fails because of lock contention
  52189. ** and the database was previously unlocked, then invoke the busy handler
  52190. ** if there is one. But if there was previously a read-lock, do not
  52191. ** invoke the busy handler - just return SQLITE_BUSY. SQLITE_BUSY is
  52192. ** returned when there is already a read-lock in order to avoid a deadlock.
  52193. **
  52194. ** Suppose there are two processes A and B. A has a read lock and B has
  52195. ** a reserved lock. B tries to promote to exclusive but is blocked because
  52196. ** of A's read lock. A tries to promote to reserved but is blocked by B.
  52197. ** One or the other of the two processes must give way or there can be
  52198. ** no progress. By returning SQLITE_BUSY and not invoking the busy callback
  52199. ** when A already has a read lock, we encourage A to give up and let B
  52200. ** proceed.
  52201. */
  52202. SQLITE_PRIVATE int sqlite3BtreeBeginTrans(Btree *p, int wrflag){
  52203. sqlite3 *pBlock = 0;
  52204. BtShared *pBt = p->pBt;
  52205. int rc = SQLITE_OK;
  52206. sqlite3BtreeEnter(p);
  52207. btreeIntegrity(p);
  52208. /* If the btree is already in a write-transaction, or it
  52209. ** is already in a read-transaction and a read-transaction
  52210. ** is requested, this is a no-op.
  52211. */
  52212. if( p->inTrans==TRANS_WRITE || (p->inTrans==TRANS_READ && !wrflag) ){
  52213. goto trans_begun;
  52214. }
  52215. assert( pBt->inTransaction==TRANS_WRITE || IfNotOmitAV(pBt->bDoTruncate)==0 );
  52216. /* Write transactions are not possible on a read-only database */
  52217. if( (pBt->btsFlags & BTS_READ_ONLY)!=0 && wrflag ){
  52218. rc = SQLITE_READONLY;
  52219. goto trans_begun;
  52220. }
  52221. #ifndef SQLITE_OMIT_SHARED_CACHE
  52222. /* If another database handle has already opened a write transaction
  52223. ** on this shared-btree structure and a second write transaction is
  52224. ** requested, return SQLITE_LOCKED.
  52225. */
  52226. if( (wrflag && pBt->inTransaction==TRANS_WRITE)
  52227. || (pBt->btsFlags & BTS_PENDING)!=0
  52228. ){
  52229. pBlock = pBt->pWriter->db;
  52230. }else if( wrflag>1 ){
  52231. BtLock *pIter;
  52232. for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
  52233. if( pIter->pBtree!=p ){
  52234. pBlock = pIter->pBtree->db;
  52235. break;
  52236. }
  52237. }
  52238. }
  52239. if( pBlock ){
  52240. sqlite3ConnectionBlocked(p->db, pBlock);
  52241. rc = SQLITE_LOCKED_SHAREDCACHE;
  52242. goto trans_begun;
  52243. }
  52244. #endif
  52245. /* Any read-only or read-write transaction implies a read-lock on
  52246. ** page 1. So if some other shared-cache client already has a write-lock
  52247. ** on page 1, the transaction cannot be opened. */
  52248. rc = querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK);
  52249. if( SQLITE_OK!=rc ) goto trans_begun;
  52250. pBt->btsFlags &= ~BTS_INITIALLY_EMPTY;
  52251. if( pBt->nPage==0 ) pBt->btsFlags |= BTS_INITIALLY_EMPTY;
  52252. do {
  52253. /* Call lockBtree() until either pBt->pPage1 is populated or
  52254. ** lockBtree() returns something other than SQLITE_OK. lockBtree()
  52255. ** may return SQLITE_OK but leave pBt->pPage1 set to 0 if after
  52256. ** reading page 1 it discovers that the page-size of the database
  52257. ** file is not pBt->pageSize. In this case lockBtree() will update
  52258. ** pBt->pageSize to the page-size of the file on disk.
  52259. */
  52260. while( pBt->pPage1==0 && SQLITE_OK==(rc = lockBtree(pBt)) );
  52261. if( rc==SQLITE_OK && wrflag ){
  52262. if( (pBt->btsFlags & BTS_READ_ONLY)!=0 ){
  52263. rc = SQLITE_READONLY;
  52264. }else{
  52265. rc = sqlite3PagerBegin(pBt->pPager,wrflag>1,sqlite3TempInMemory(p->db));
  52266. if( rc==SQLITE_OK ){
  52267. rc = newDatabase(pBt);
  52268. }
  52269. }
  52270. }
  52271. if( rc!=SQLITE_OK ){
  52272. unlockBtreeIfUnused(pBt);
  52273. }
  52274. }while( (rc&0xFF)==SQLITE_BUSY && pBt->inTransaction==TRANS_NONE &&
  52275. btreeInvokeBusyHandler(pBt) );
  52276. if( rc==SQLITE_OK ){
  52277. if( p->inTrans==TRANS_NONE ){
  52278. pBt->nTransaction++;
  52279. #ifndef SQLITE_OMIT_SHARED_CACHE
  52280. if( p->sharable ){
  52281. assert( p->lock.pBtree==p && p->lock.iTable==1 );
  52282. p->lock.eLock = READ_LOCK;
  52283. p->lock.pNext = pBt->pLock;
  52284. pBt->pLock = &p->lock;
  52285. }
  52286. #endif
  52287. }
  52288. p->inTrans = (wrflag?TRANS_WRITE:TRANS_READ);
  52289. if( p->inTrans>pBt->inTransaction ){
  52290. pBt->inTransaction = p->inTrans;
  52291. }
  52292. if( wrflag ){
  52293. MemPage *pPage1 = pBt->pPage1;
  52294. #ifndef SQLITE_OMIT_SHARED_CACHE
  52295. assert( !pBt->pWriter );
  52296. pBt->pWriter = p;
  52297. pBt->btsFlags &= ~BTS_EXCLUSIVE;
  52298. if( wrflag>1 ) pBt->btsFlags |= BTS_EXCLUSIVE;
  52299. #endif
  52300. /* If the db-size header field is incorrect (as it may be if an old
  52301. ** client has been writing the database file), update it now. Doing
  52302. ** this sooner rather than later means the database size can safely
  52303. ** re-read the database size from page 1 if a savepoint or transaction
  52304. ** rollback occurs within the transaction.
  52305. */
  52306. if( pBt->nPage!=get4byte(&pPage1->aData[28]) ){
  52307. rc = sqlite3PagerWrite(pPage1->pDbPage);
  52308. if( rc==SQLITE_OK ){
  52309. put4byte(&pPage1->aData[28], pBt->nPage);
  52310. }
  52311. }
  52312. }
  52313. }
  52314. trans_begun:
  52315. if( rc==SQLITE_OK && wrflag ){
  52316. /* This call makes sure that the pager has the correct number of
  52317. ** open savepoints. If the second parameter is greater than 0 and
  52318. ** the sub-journal is not already open, then it will be opened here.
  52319. */
  52320. rc = sqlite3PagerOpenSavepoint(pBt->pPager, p->db->nSavepoint);
  52321. }
  52322. btreeIntegrity(p);
  52323. sqlite3BtreeLeave(p);
  52324. return rc;
  52325. }
  52326. #ifndef SQLITE_OMIT_AUTOVACUUM
  52327. /*
  52328. ** Set the pointer-map entries for all children of page pPage. Also, if
  52329. ** pPage contains cells that point to overflow pages, set the pointer
  52330. ** map entries for the overflow pages as well.
  52331. */
  52332. static int setChildPtrmaps(MemPage *pPage){
  52333. int i; /* Counter variable */
  52334. int nCell; /* Number of cells in page pPage */
  52335. int rc; /* Return code */
  52336. BtShared *pBt = pPage->pBt;
  52337. u8 isInitOrig = pPage->isInit;
  52338. Pgno pgno = pPage->pgno;
  52339. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  52340. rc = btreeInitPage(pPage);
  52341. if( rc!=SQLITE_OK ){
  52342. goto set_child_ptrmaps_out;
  52343. }
  52344. nCell = pPage->nCell;
  52345. for(i=0; i<nCell; i++){
  52346. u8 *pCell = findCell(pPage, i);
  52347. ptrmapPutOvflPtr(pPage, pCell, &rc);
  52348. if( !pPage->leaf ){
  52349. Pgno childPgno = get4byte(pCell);
  52350. ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno, &rc);
  52351. }
  52352. }
  52353. if( !pPage->leaf ){
  52354. Pgno childPgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
  52355. ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno, &rc);
  52356. }
  52357. set_child_ptrmaps_out:
  52358. pPage->isInit = isInitOrig;
  52359. return rc;
  52360. }
  52361. /*
  52362. ** Somewhere on pPage is a pointer to page iFrom. Modify this pointer so
  52363. ** that it points to iTo. Parameter eType describes the type of pointer to
  52364. ** be modified, as follows:
  52365. **
  52366. ** PTRMAP_BTREE: pPage is a btree-page. The pointer points at a child
  52367. ** page of pPage.
  52368. **
  52369. ** PTRMAP_OVERFLOW1: pPage is a btree-page. The pointer points at an overflow
  52370. ** page pointed to by one of the cells on pPage.
  52371. **
  52372. ** PTRMAP_OVERFLOW2: pPage is an overflow-page. The pointer points at the next
  52373. ** overflow page in the list.
  52374. */
  52375. static int modifyPagePointer(MemPage *pPage, Pgno iFrom, Pgno iTo, u8 eType){
  52376. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  52377. assert( sqlite3PagerIswriteable(pPage->pDbPage) );
  52378. if( eType==PTRMAP_OVERFLOW2 ){
  52379. /* The pointer is always the first 4 bytes of the page in this case. */
  52380. if( get4byte(pPage->aData)!=iFrom ){
  52381. return SQLITE_CORRUPT_BKPT;
  52382. }
  52383. put4byte(pPage->aData, iTo);
  52384. }else{
  52385. u8 isInitOrig = pPage->isInit;
  52386. int i;
  52387. int nCell;
  52388. btreeInitPage(pPage);
  52389. nCell = pPage->nCell;
  52390. for(i=0; i<nCell; i++){
  52391. u8 *pCell = findCell(pPage, i);
  52392. if( eType==PTRMAP_OVERFLOW1 ){
  52393. CellInfo info;
  52394. btreeParseCellPtr(pPage, pCell, &info);
  52395. if( info.iOverflow
  52396. && pCell+info.iOverflow+3<=pPage->aData+pPage->maskPage
  52397. && iFrom==get4byte(&pCell[info.iOverflow])
  52398. ){
  52399. put4byte(&pCell[info.iOverflow], iTo);
  52400. break;
  52401. }
  52402. }else{
  52403. if( get4byte(pCell)==iFrom ){
  52404. put4byte(pCell, iTo);
  52405. break;
  52406. }
  52407. }
  52408. }
  52409. if( i==nCell ){
  52410. if( eType!=PTRMAP_BTREE ||
  52411. get4byte(&pPage->aData[pPage->hdrOffset+8])!=iFrom ){
  52412. return SQLITE_CORRUPT_BKPT;
  52413. }
  52414. put4byte(&pPage->aData[pPage->hdrOffset+8], iTo);
  52415. }
  52416. pPage->isInit = isInitOrig;
  52417. }
  52418. return SQLITE_OK;
  52419. }
  52420. /*
  52421. ** Move the open database page pDbPage to location iFreePage in the
  52422. ** database. The pDbPage reference remains valid.
  52423. **
  52424. ** The isCommit flag indicates that there is no need to remember that
  52425. ** the journal needs to be sync()ed before database page pDbPage->pgno
  52426. ** can be written to. The caller has already promised not to write to that
  52427. ** page.
  52428. */
  52429. static int relocatePage(
  52430. BtShared *pBt, /* Btree */
  52431. MemPage *pDbPage, /* Open page to move */
  52432. u8 eType, /* Pointer map 'type' entry for pDbPage */
  52433. Pgno iPtrPage, /* Pointer map 'page-no' entry for pDbPage */
  52434. Pgno iFreePage, /* The location to move pDbPage to */
  52435. int isCommit /* isCommit flag passed to sqlite3PagerMovepage */
  52436. ){
  52437. MemPage *pPtrPage; /* The page that contains a pointer to pDbPage */
  52438. Pgno iDbPage = pDbPage->pgno;
  52439. Pager *pPager = pBt->pPager;
  52440. int rc;
  52441. assert( eType==PTRMAP_OVERFLOW2 || eType==PTRMAP_OVERFLOW1 ||
  52442. eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE );
  52443. assert( sqlite3_mutex_held(pBt->mutex) );
  52444. assert( pDbPage->pBt==pBt );
  52445. /* Move page iDbPage from its current location to page number iFreePage */
  52446. TRACE(("AUTOVACUUM: Moving %d to free page %d (ptr page %d type %d)\n",
  52447. iDbPage, iFreePage, iPtrPage, eType));
  52448. rc = sqlite3PagerMovepage(pPager, pDbPage->pDbPage, iFreePage, isCommit);
  52449. if( rc!=SQLITE_OK ){
  52450. return rc;
  52451. }
  52452. pDbPage->pgno = iFreePage;
  52453. /* If pDbPage was a btree-page, then it may have child pages and/or cells
  52454. ** that point to overflow pages. The pointer map entries for all these
  52455. ** pages need to be changed.
  52456. **
  52457. ** If pDbPage is an overflow page, then the first 4 bytes may store a
  52458. ** pointer to a subsequent overflow page. If this is the case, then
  52459. ** the pointer map needs to be updated for the subsequent overflow page.
  52460. */
  52461. if( eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE ){
  52462. rc = setChildPtrmaps(pDbPage);
  52463. if( rc!=SQLITE_OK ){
  52464. return rc;
  52465. }
  52466. }else{
  52467. Pgno nextOvfl = get4byte(pDbPage->aData);
  52468. if( nextOvfl!=0 ){
  52469. ptrmapPut(pBt, nextOvfl, PTRMAP_OVERFLOW2, iFreePage, &rc);
  52470. if( rc!=SQLITE_OK ){
  52471. return rc;
  52472. }
  52473. }
  52474. }
  52475. /* Fix the database pointer on page iPtrPage that pointed at iDbPage so
  52476. ** that it points at iFreePage. Also fix the pointer map entry for
  52477. ** iPtrPage.
  52478. */
  52479. if( eType!=PTRMAP_ROOTPAGE ){
  52480. rc = btreeGetPage(pBt, iPtrPage, &pPtrPage, 0);
  52481. if( rc!=SQLITE_OK ){
  52482. return rc;
  52483. }
  52484. rc = sqlite3PagerWrite(pPtrPage->pDbPage);
  52485. if( rc!=SQLITE_OK ){
  52486. releasePage(pPtrPage);
  52487. return rc;
  52488. }
  52489. rc = modifyPagePointer(pPtrPage, iDbPage, iFreePage, eType);
  52490. releasePage(pPtrPage);
  52491. if( rc==SQLITE_OK ){
  52492. ptrmapPut(pBt, iFreePage, eType, iPtrPage, &rc);
  52493. }
  52494. }
  52495. return rc;
  52496. }
  52497. /* Forward declaration required by incrVacuumStep(). */
  52498. static int allocateBtreePage(BtShared *, MemPage **, Pgno *, Pgno, u8);
  52499. /*
  52500. ** Perform a single step of an incremental-vacuum. If successful, return
  52501. ** SQLITE_OK. If there is no work to do (and therefore no point in
  52502. ** calling this function again), return SQLITE_DONE. Or, if an error
  52503. ** occurs, return some other error code.
  52504. **
  52505. ** More specifically, this function attempts to re-organize the database so
  52506. ** that the last page of the file currently in use is no longer in use.
  52507. **
  52508. ** Parameter nFin is the number of pages that this database would contain
  52509. ** were this function called until it returns SQLITE_DONE.
  52510. **
  52511. ** If the bCommit parameter is non-zero, this function assumes that the
  52512. ** caller will keep calling incrVacuumStep() until it returns SQLITE_DONE
  52513. ** or an error. bCommit is passed true for an auto-vacuum-on-commit
  52514. ** operation, or false for an incremental vacuum.
  52515. */
  52516. static int incrVacuumStep(BtShared *pBt, Pgno nFin, Pgno iLastPg, int bCommit){
  52517. Pgno nFreeList; /* Number of pages still on the free-list */
  52518. int rc;
  52519. assert( sqlite3_mutex_held(pBt->mutex) );
  52520. assert( iLastPg>nFin );
  52521. if( !PTRMAP_ISPAGE(pBt, iLastPg) && iLastPg!=PENDING_BYTE_PAGE(pBt) ){
  52522. u8 eType;
  52523. Pgno iPtrPage;
  52524. nFreeList = get4byte(&pBt->pPage1->aData[36]);
  52525. if( nFreeList==0 ){
  52526. return SQLITE_DONE;
  52527. }
  52528. rc = ptrmapGet(pBt, iLastPg, &eType, &iPtrPage);
  52529. if( rc!=SQLITE_OK ){
  52530. return rc;
  52531. }
  52532. if( eType==PTRMAP_ROOTPAGE ){
  52533. return SQLITE_CORRUPT_BKPT;
  52534. }
  52535. if( eType==PTRMAP_FREEPAGE ){
  52536. if( bCommit==0 ){
  52537. /* Remove the page from the files free-list. This is not required
  52538. ** if bCommit is non-zero. In that case, the free-list will be
  52539. ** truncated to zero after this function returns, so it doesn't
  52540. ** matter if it still contains some garbage entries.
  52541. */
  52542. Pgno iFreePg;
  52543. MemPage *pFreePg;
  52544. rc = allocateBtreePage(pBt, &pFreePg, &iFreePg, iLastPg, BTALLOC_EXACT);
  52545. if( rc!=SQLITE_OK ){
  52546. return rc;
  52547. }
  52548. assert( iFreePg==iLastPg );
  52549. releasePage(pFreePg);
  52550. }
  52551. } else {
  52552. Pgno iFreePg; /* Index of free page to move pLastPg to */
  52553. MemPage *pLastPg;
  52554. u8 eMode = BTALLOC_ANY; /* Mode parameter for allocateBtreePage() */
  52555. Pgno iNear = 0; /* nearby parameter for allocateBtreePage() */
  52556. rc = btreeGetPage(pBt, iLastPg, &pLastPg, 0);
  52557. if( rc!=SQLITE_OK ){
  52558. return rc;
  52559. }
  52560. /* If bCommit is zero, this loop runs exactly once and page pLastPg
  52561. ** is swapped with the first free page pulled off the free list.
  52562. **
  52563. ** On the other hand, if bCommit is greater than zero, then keep
  52564. ** looping until a free-page located within the first nFin pages
  52565. ** of the file is found.
  52566. */
  52567. if( bCommit==0 ){
  52568. eMode = BTALLOC_LE;
  52569. iNear = nFin;
  52570. }
  52571. do {
  52572. MemPage *pFreePg;
  52573. rc = allocateBtreePage(pBt, &pFreePg, &iFreePg, iNear, eMode);
  52574. if( rc!=SQLITE_OK ){
  52575. releasePage(pLastPg);
  52576. return rc;
  52577. }
  52578. releasePage(pFreePg);
  52579. }while( bCommit && iFreePg>nFin );
  52580. assert( iFreePg<iLastPg );
  52581. rc = relocatePage(pBt, pLastPg, eType, iPtrPage, iFreePg, bCommit);
  52582. releasePage(pLastPg);
  52583. if( rc!=SQLITE_OK ){
  52584. return rc;
  52585. }
  52586. }
  52587. }
  52588. if( bCommit==0 ){
  52589. do {
  52590. iLastPg--;
  52591. }while( iLastPg==PENDING_BYTE_PAGE(pBt) || PTRMAP_ISPAGE(pBt, iLastPg) );
  52592. pBt->bDoTruncate = 1;
  52593. pBt->nPage = iLastPg;
  52594. }
  52595. return SQLITE_OK;
  52596. }
  52597. /*
  52598. ** The database opened by the first argument is an auto-vacuum database
  52599. ** nOrig pages in size containing nFree free pages. Return the expected
  52600. ** size of the database in pages following an auto-vacuum operation.
  52601. */
  52602. static Pgno finalDbSize(BtShared *pBt, Pgno nOrig, Pgno nFree){
  52603. int nEntry; /* Number of entries on one ptrmap page */
  52604. Pgno nPtrmap; /* Number of PtrMap pages to be freed */
  52605. Pgno nFin; /* Return value */
  52606. nEntry = pBt->usableSize/5;
  52607. nPtrmap = (nFree-nOrig+PTRMAP_PAGENO(pBt, nOrig)+nEntry)/nEntry;
  52608. nFin = nOrig - nFree - nPtrmap;
  52609. if( nOrig>PENDING_BYTE_PAGE(pBt) && nFin<PENDING_BYTE_PAGE(pBt) ){
  52610. nFin--;
  52611. }
  52612. while( PTRMAP_ISPAGE(pBt, nFin) || nFin==PENDING_BYTE_PAGE(pBt) ){
  52613. nFin--;
  52614. }
  52615. return nFin;
  52616. }
  52617. /*
  52618. ** A write-transaction must be opened before calling this function.
  52619. ** It performs a single unit of work towards an incremental vacuum.
  52620. **
  52621. ** If the incremental vacuum is finished after this function has run,
  52622. ** SQLITE_DONE is returned. If it is not finished, but no error occurred,
  52623. ** SQLITE_OK is returned. Otherwise an SQLite error code.
  52624. */
  52625. SQLITE_PRIVATE int sqlite3BtreeIncrVacuum(Btree *p){
  52626. int rc;
  52627. BtShared *pBt = p->pBt;
  52628. sqlite3BtreeEnter(p);
  52629. assert( pBt->inTransaction==TRANS_WRITE && p->inTrans==TRANS_WRITE );
  52630. if( !pBt->autoVacuum ){
  52631. rc = SQLITE_DONE;
  52632. }else{
  52633. Pgno nOrig = btreePagecount(pBt);
  52634. Pgno nFree = get4byte(&pBt->pPage1->aData[36]);
  52635. Pgno nFin = finalDbSize(pBt, nOrig, nFree);
  52636. if( nOrig<nFin ){
  52637. rc = SQLITE_CORRUPT_BKPT;
  52638. }else if( nFree>0 ){
  52639. rc = saveAllCursors(pBt, 0, 0);
  52640. if( rc==SQLITE_OK ){
  52641. invalidateAllOverflowCache(pBt);
  52642. rc = incrVacuumStep(pBt, nFin, nOrig, 0);
  52643. }
  52644. if( rc==SQLITE_OK ){
  52645. rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
  52646. put4byte(&pBt->pPage1->aData[28], pBt->nPage);
  52647. }
  52648. }else{
  52649. rc = SQLITE_DONE;
  52650. }
  52651. }
  52652. sqlite3BtreeLeave(p);
  52653. return rc;
  52654. }
  52655. /*
  52656. ** This routine is called prior to sqlite3PagerCommit when a transaction
  52657. ** is committed for an auto-vacuum database.
  52658. **
  52659. ** If SQLITE_OK is returned, then *pnTrunc is set to the number of pages
  52660. ** the database file should be truncated to during the commit process.
  52661. ** i.e. the database has been reorganized so that only the first *pnTrunc
  52662. ** pages are in use.
  52663. */
  52664. static int autoVacuumCommit(BtShared *pBt){
  52665. int rc = SQLITE_OK;
  52666. Pager *pPager = pBt->pPager;
  52667. VVA_ONLY( int nRef = sqlite3PagerRefcount(pPager) );
  52668. assert( sqlite3_mutex_held(pBt->mutex) );
  52669. invalidateAllOverflowCache(pBt);
  52670. assert(pBt->autoVacuum);
  52671. if( !pBt->incrVacuum ){
  52672. Pgno nFin; /* Number of pages in database after autovacuuming */
  52673. Pgno nFree; /* Number of pages on the freelist initially */
  52674. Pgno iFree; /* The next page to be freed */
  52675. Pgno nOrig; /* Database size before freeing */
  52676. nOrig = btreePagecount(pBt);
  52677. if( PTRMAP_ISPAGE(pBt, nOrig) || nOrig==PENDING_BYTE_PAGE(pBt) ){
  52678. /* It is not possible to create a database for which the final page
  52679. ** is either a pointer-map page or the pending-byte page. If one
  52680. ** is encountered, this indicates corruption.
  52681. */
  52682. return SQLITE_CORRUPT_BKPT;
  52683. }
  52684. nFree = get4byte(&pBt->pPage1->aData[36]);
  52685. nFin = finalDbSize(pBt, nOrig, nFree);
  52686. if( nFin>nOrig ) return SQLITE_CORRUPT_BKPT;
  52687. if( nFin<nOrig ){
  52688. rc = saveAllCursors(pBt, 0, 0);
  52689. }
  52690. for(iFree=nOrig; iFree>nFin && rc==SQLITE_OK; iFree--){
  52691. rc = incrVacuumStep(pBt, nFin, iFree, 1);
  52692. }
  52693. if( (rc==SQLITE_DONE || rc==SQLITE_OK) && nFree>0 ){
  52694. rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
  52695. put4byte(&pBt->pPage1->aData[32], 0);
  52696. put4byte(&pBt->pPage1->aData[36], 0);
  52697. put4byte(&pBt->pPage1->aData[28], nFin);
  52698. pBt->bDoTruncate = 1;
  52699. pBt->nPage = nFin;
  52700. }
  52701. if( rc!=SQLITE_OK ){
  52702. sqlite3PagerRollback(pPager);
  52703. }
  52704. }
  52705. assert( nRef>=sqlite3PagerRefcount(pPager) );
  52706. return rc;
  52707. }
  52708. #else /* ifndef SQLITE_OMIT_AUTOVACUUM */
  52709. # define setChildPtrmaps(x) SQLITE_OK
  52710. #endif
  52711. /*
  52712. ** This routine does the first phase of a two-phase commit. This routine
  52713. ** causes a rollback journal to be created (if it does not already exist)
  52714. ** and populated with enough information so that if a power loss occurs
  52715. ** the database can be restored to its original state by playing back
  52716. ** the journal. Then the contents of the journal are flushed out to
  52717. ** the disk. After the journal is safely on oxide, the changes to the
  52718. ** database are written into the database file and flushed to oxide.
  52719. ** At the end of this call, the rollback journal still exists on the
  52720. ** disk and we are still holding all locks, so the transaction has not
  52721. ** committed. See sqlite3BtreeCommitPhaseTwo() for the second phase of the
  52722. ** commit process.
  52723. **
  52724. ** This call is a no-op if no write-transaction is currently active on pBt.
  52725. **
  52726. ** Otherwise, sync the database file for the btree pBt. zMaster points to
  52727. ** the name of a master journal file that should be written into the
  52728. ** individual journal file, or is NULL, indicating no master journal file
  52729. ** (single database transaction).
  52730. **
  52731. ** When this is called, the master journal should already have been
  52732. ** created, populated with this journal pointer and synced to disk.
  52733. **
  52734. ** Once this is routine has returned, the only thing required to commit
  52735. ** the write-transaction for this database file is to delete the journal.
  52736. */
  52737. SQLITE_PRIVATE int sqlite3BtreeCommitPhaseOne(Btree *p, const char *zMaster){
  52738. int rc = SQLITE_OK;
  52739. if( p->inTrans==TRANS_WRITE ){
  52740. BtShared *pBt = p->pBt;
  52741. sqlite3BtreeEnter(p);
  52742. #ifndef SQLITE_OMIT_AUTOVACUUM
  52743. if( pBt->autoVacuum ){
  52744. rc = autoVacuumCommit(pBt);
  52745. if( rc!=SQLITE_OK ){
  52746. sqlite3BtreeLeave(p);
  52747. return rc;
  52748. }
  52749. }
  52750. if( pBt->bDoTruncate ){
  52751. sqlite3PagerTruncateImage(pBt->pPager, pBt->nPage);
  52752. }
  52753. #endif
  52754. rc = sqlite3PagerCommitPhaseOne(pBt->pPager, zMaster, 0);
  52755. sqlite3BtreeLeave(p);
  52756. }
  52757. return rc;
  52758. }
  52759. /*
  52760. ** This function is called from both BtreeCommitPhaseTwo() and BtreeRollback()
  52761. ** at the conclusion of a transaction.
  52762. */
  52763. static void btreeEndTransaction(Btree *p){
  52764. BtShared *pBt = p->pBt;
  52765. sqlite3 *db = p->db;
  52766. assert( sqlite3BtreeHoldsMutex(p) );
  52767. #ifndef SQLITE_OMIT_AUTOVACUUM
  52768. pBt->bDoTruncate = 0;
  52769. #endif
  52770. if( p->inTrans>TRANS_NONE && db->nVdbeRead>1 ){
  52771. /* If there are other active statements that belong to this database
  52772. ** handle, downgrade to a read-only transaction. The other statements
  52773. ** may still be reading from the database. */
  52774. downgradeAllSharedCacheTableLocks(p);
  52775. p->inTrans = TRANS_READ;
  52776. }else{
  52777. /* If the handle had any kind of transaction open, decrement the
  52778. ** transaction count of the shared btree. If the transaction count
  52779. ** reaches 0, set the shared state to TRANS_NONE. The unlockBtreeIfUnused()
  52780. ** call below will unlock the pager. */
  52781. if( p->inTrans!=TRANS_NONE ){
  52782. clearAllSharedCacheTableLocks(p);
  52783. pBt->nTransaction--;
  52784. if( 0==pBt->nTransaction ){
  52785. pBt->inTransaction = TRANS_NONE;
  52786. }
  52787. }
  52788. /* Set the current transaction state to TRANS_NONE and unlock the
  52789. ** pager if this call closed the only read or write transaction. */
  52790. p->inTrans = TRANS_NONE;
  52791. unlockBtreeIfUnused(pBt);
  52792. }
  52793. btreeIntegrity(p);
  52794. }
  52795. /*
  52796. ** Commit the transaction currently in progress.
  52797. **
  52798. ** This routine implements the second phase of a 2-phase commit. The
  52799. ** sqlite3BtreeCommitPhaseOne() routine does the first phase and should
  52800. ** be invoked prior to calling this routine. The sqlite3BtreeCommitPhaseOne()
  52801. ** routine did all the work of writing information out to disk and flushing the
  52802. ** contents so that they are written onto the disk platter. All this
  52803. ** routine has to do is delete or truncate or zero the header in the
  52804. ** the rollback journal (which causes the transaction to commit) and
  52805. ** drop locks.
  52806. **
  52807. ** Normally, if an error occurs while the pager layer is attempting to
  52808. ** finalize the underlying journal file, this function returns an error and
  52809. ** the upper layer will attempt a rollback. However, if the second argument
  52810. ** is non-zero then this b-tree transaction is part of a multi-file
  52811. ** transaction. In this case, the transaction has already been committed
  52812. ** (by deleting a master journal file) and the caller will ignore this
  52813. ** functions return code. So, even if an error occurs in the pager layer,
  52814. ** reset the b-tree objects internal state to indicate that the write
  52815. ** transaction has been closed. This is quite safe, as the pager will have
  52816. ** transitioned to the error state.
  52817. **
  52818. ** This will release the write lock on the database file. If there
  52819. ** are no active cursors, it also releases the read lock.
  52820. */
  52821. SQLITE_PRIVATE int sqlite3BtreeCommitPhaseTwo(Btree *p, int bCleanup){
  52822. if( p->inTrans==TRANS_NONE ) return SQLITE_OK;
  52823. sqlite3BtreeEnter(p);
  52824. btreeIntegrity(p);
  52825. /* If the handle has a write-transaction open, commit the shared-btrees
  52826. ** transaction and set the shared state to TRANS_READ.
  52827. */
  52828. if( p->inTrans==TRANS_WRITE ){
  52829. int rc;
  52830. BtShared *pBt = p->pBt;
  52831. assert( pBt->inTransaction==TRANS_WRITE );
  52832. assert( pBt->nTransaction>0 );
  52833. rc = sqlite3PagerCommitPhaseTwo(pBt->pPager);
  52834. if( rc!=SQLITE_OK && bCleanup==0 ){
  52835. sqlite3BtreeLeave(p);
  52836. return rc;
  52837. }
  52838. p->iDataVersion--; /* Compensate for pPager->iDataVersion++; */
  52839. pBt->inTransaction = TRANS_READ;
  52840. btreeClearHasContent(pBt);
  52841. }
  52842. btreeEndTransaction(p);
  52843. sqlite3BtreeLeave(p);
  52844. return SQLITE_OK;
  52845. }
  52846. /*
  52847. ** Do both phases of a commit.
  52848. */
  52849. SQLITE_PRIVATE int sqlite3BtreeCommit(Btree *p){
  52850. int rc;
  52851. sqlite3BtreeEnter(p);
  52852. rc = sqlite3BtreeCommitPhaseOne(p, 0);
  52853. if( rc==SQLITE_OK ){
  52854. rc = sqlite3BtreeCommitPhaseTwo(p, 0);
  52855. }
  52856. sqlite3BtreeLeave(p);
  52857. return rc;
  52858. }
  52859. /*
  52860. ** This routine sets the state to CURSOR_FAULT and the error
  52861. ** code to errCode for every cursor on any BtShared that pBtree
  52862. ** references. Or if the writeOnly flag is set to 1, then only
  52863. ** trip write cursors and leave read cursors unchanged.
  52864. **
  52865. ** Every cursor is a candidate to be tripped, including cursors
  52866. ** that belong to other database connections that happen to be
  52867. ** sharing the cache with pBtree.
  52868. **
  52869. ** This routine gets called when a rollback occurs. If the writeOnly
  52870. ** flag is true, then only write-cursors need be tripped - read-only
  52871. ** cursors save their current positions so that they may continue
  52872. ** following the rollback. Or, if writeOnly is false, all cursors are
  52873. ** tripped. In general, writeOnly is false if the transaction being
  52874. ** rolled back modified the database schema. In this case b-tree root
  52875. ** pages may be moved or deleted from the database altogether, making
  52876. ** it unsafe for read cursors to continue.
  52877. **
  52878. ** If the writeOnly flag is true and an error is encountered while
  52879. ** saving the current position of a read-only cursor, all cursors,
  52880. ** including all read-cursors are tripped.
  52881. **
  52882. ** SQLITE_OK is returned if successful, or if an error occurs while
  52883. ** saving a cursor position, an SQLite error code.
  52884. */
  52885. SQLITE_PRIVATE int sqlite3BtreeTripAllCursors(Btree *pBtree, int errCode, int writeOnly){
  52886. BtCursor *p;
  52887. int rc = SQLITE_OK;
  52888. assert( (writeOnly==0 || writeOnly==1) && BTCF_WriteFlag==1 );
  52889. if( pBtree ){
  52890. sqlite3BtreeEnter(pBtree);
  52891. for(p=pBtree->pBt->pCursor; p; p=p->pNext){
  52892. int i;
  52893. if( writeOnly && (p->curFlags & BTCF_WriteFlag)==0 ){
  52894. if( p->eState==CURSOR_VALID || p->eState==CURSOR_SKIPNEXT ){
  52895. rc = saveCursorPosition(p);
  52896. if( rc!=SQLITE_OK ){
  52897. (void)sqlite3BtreeTripAllCursors(pBtree, rc, 0);
  52898. break;
  52899. }
  52900. }
  52901. }else{
  52902. sqlite3BtreeClearCursor(p);
  52903. p->eState = CURSOR_FAULT;
  52904. p->skipNext = errCode;
  52905. }
  52906. for(i=0; i<=p->iPage; i++){
  52907. releasePage(p->apPage[i]);
  52908. p->apPage[i] = 0;
  52909. }
  52910. }
  52911. sqlite3BtreeLeave(pBtree);
  52912. }
  52913. return rc;
  52914. }
  52915. /*
  52916. ** Rollback the transaction in progress.
  52917. **
  52918. ** If tripCode is not SQLITE_OK then cursors will be invalidated (tripped).
  52919. ** Only write cursors are tripped if writeOnly is true but all cursors are
  52920. ** tripped if writeOnly is false. Any attempt to use
  52921. ** a tripped cursor will result in an error.
  52922. **
  52923. ** This will release the write lock on the database file. If there
  52924. ** are no active cursors, it also releases the read lock.
  52925. */
  52926. SQLITE_PRIVATE int sqlite3BtreeRollback(Btree *p, int tripCode, int writeOnly){
  52927. int rc;
  52928. BtShared *pBt = p->pBt;
  52929. MemPage *pPage1;
  52930. assert( writeOnly==1 || writeOnly==0 );
  52931. assert( tripCode==SQLITE_ABORT_ROLLBACK || tripCode==SQLITE_OK );
  52932. sqlite3BtreeEnter(p);
  52933. if( tripCode==SQLITE_OK ){
  52934. rc = tripCode = saveAllCursors(pBt, 0, 0);
  52935. if( rc ) writeOnly = 0;
  52936. }else{
  52937. rc = SQLITE_OK;
  52938. }
  52939. if( tripCode ){
  52940. int rc2 = sqlite3BtreeTripAllCursors(p, tripCode, writeOnly);
  52941. assert( rc==SQLITE_OK || (writeOnly==0 && rc2==SQLITE_OK) );
  52942. if( rc2!=SQLITE_OK ) rc = rc2;
  52943. }
  52944. btreeIntegrity(p);
  52945. if( p->inTrans==TRANS_WRITE ){
  52946. int rc2;
  52947. assert( TRANS_WRITE==pBt->inTransaction );
  52948. rc2 = sqlite3PagerRollback(pBt->pPager);
  52949. if( rc2!=SQLITE_OK ){
  52950. rc = rc2;
  52951. }
  52952. /* The rollback may have destroyed the pPage1->aData value. So
  52953. ** call btreeGetPage() on page 1 again to make
  52954. ** sure pPage1->aData is set correctly. */
  52955. if( btreeGetPage(pBt, 1, &pPage1, 0)==SQLITE_OK ){
  52956. int nPage = get4byte(28+(u8*)pPage1->aData);
  52957. testcase( nPage==0 );
  52958. if( nPage==0 ) sqlite3PagerPagecount(pBt->pPager, &nPage);
  52959. testcase( pBt->nPage!=nPage );
  52960. pBt->nPage = nPage;
  52961. releasePage(pPage1);
  52962. }
  52963. assert( countValidCursors(pBt, 1)==0 );
  52964. pBt->inTransaction = TRANS_READ;
  52965. btreeClearHasContent(pBt);
  52966. }
  52967. btreeEndTransaction(p);
  52968. sqlite3BtreeLeave(p);
  52969. return rc;
  52970. }
  52971. /*
  52972. ** Start a statement subtransaction. The subtransaction can be rolled
  52973. ** back independently of the main transaction. You must start a transaction
  52974. ** before starting a subtransaction. The subtransaction is ended automatically
  52975. ** if the main transaction commits or rolls back.
  52976. **
  52977. ** Statement subtransactions are used around individual SQL statements
  52978. ** that are contained within a BEGIN...COMMIT block. If a constraint
  52979. ** error occurs within the statement, the effect of that one statement
  52980. ** can be rolled back without having to rollback the entire transaction.
  52981. **
  52982. ** A statement sub-transaction is implemented as an anonymous savepoint. The
  52983. ** value passed as the second parameter is the total number of savepoints,
  52984. ** including the new anonymous savepoint, open on the B-Tree. i.e. if there
  52985. ** are no active savepoints and no other statement-transactions open,
  52986. ** iStatement is 1. This anonymous savepoint can be released or rolled back
  52987. ** using the sqlite3BtreeSavepoint() function.
  52988. */
  52989. SQLITE_PRIVATE int sqlite3BtreeBeginStmt(Btree *p, int iStatement){
  52990. int rc;
  52991. BtShared *pBt = p->pBt;
  52992. sqlite3BtreeEnter(p);
  52993. assert( p->inTrans==TRANS_WRITE );
  52994. assert( (pBt->btsFlags & BTS_READ_ONLY)==0 );
  52995. assert( iStatement>0 );
  52996. assert( iStatement>p->db->nSavepoint );
  52997. assert( pBt->inTransaction==TRANS_WRITE );
  52998. /* At the pager level, a statement transaction is a savepoint with
  52999. ** an index greater than all savepoints created explicitly using
  53000. ** SQL statements. It is illegal to open, release or rollback any
  53001. ** such savepoints while the statement transaction savepoint is active.
  53002. */
  53003. rc = sqlite3PagerOpenSavepoint(pBt->pPager, iStatement);
  53004. sqlite3BtreeLeave(p);
  53005. return rc;
  53006. }
  53007. /*
  53008. ** The second argument to this function, op, is always SAVEPOINT_ROLLBACK
  53009. ** or SAVEPOINT_RELEASE. This function either releases or rolls back the
  53010. ** savepoint identified by parameter iSavepoint, depending on the value
  53011. ** of op.
  53012. **
  53013. ** Normally, iSavepoint is greater than or equal to zero. However, if op is
  53014. ** SAVEPOINT_ROLLBACK, then iSavepoint may also be -1. In this case the
  53015. ** contents of the entire transaction are rolled back. This is different
  53016. ** from a normal transaction rollback, as no locks are released and the
  53017. ** transaction remains open.
  53018. */
  53019. SQLITE_PRIVATE int sqlite3BtreeSavepoint(Btree *p, int op, int iSavepoint){
  53020. int rc = SQLITE_OK;
  53021. if( p && p->inTrans==TRANS_WRITE ){
  53022. BtShared *pBt = p->pBt;
  53023. assert( op==SAVEPOINT_RELEASE || op==SAVEPOINT_ROLLBACK );
  53024. assert( iSavepoint>=0 || (iSavepoint==-1 && op==SAVEPOINT_ROLLBACK) );
  53025. sqlite3BtreeEnter(p);
  53026. rc = sqlite3PagerSavepoint(pBt->pPager, op, iSavepoint);
  53027. if( rc==SQLITE_OK ){
  53028. if( iSavepoint<0 && (pBt->btsFlags & BTS_INITIALLY_EMPTY)!=0 ){
  53029. pBt->nPage = 0;
  53030. }
  53031. rc = newDatabase(pBt);
  53032. pBt->nPage = get4byte(28 + pBt->pPage1->aData);
  53033. /* The database size was written into the offset 28 of the header
  53034. ** when the transaction started, so we know that the value at offset
  53035. ** 28 is nonzero. */
  53036. assert( pBt->nPage>0 );
  53037. }
  53038. sqlite3BtreeLeave(p);
  53039. }
  53040. return rc;
  53041. }
  53042. /*
  53043. ** Create a new cursor for the BTree whose root is on the page
  53044. ** iTable. If a read-only cursor is requested, it is assumed that
  53045. ** the caller already has at least a read-only transaction open
  53046. ** on the database already. If a write-cursor is requested, then
  53047. ** the caller is assumed to have an open write transaction.
  53048. **
  53049. ** If wrFlag==0, then the cursor can only be used for reading.
  53050. ** If wrFlag==1, then the cursor can be used for reading or for
  53051. ** writing if other conditions for writing are also met. These
  53052. ** are the conditions that must be met in order for writing to
  53053. ** be allowed:
  53054. **
  53055. ** 1: The cursor must have been opened with wrFlag==1
  53056. **
  53057. ** 2: Other database connections that share the same pager cache
  53058. ** but which are not in the READ_UNCOMMITTED state may not have
  53059. ** cursors open with wrFlag==0 on the same table. Otherwise
  53060. ** the changes made by this write cursor would be visible to
  53061. ** the read cursors in the other database connection.
  53062. **
  53063. ** 3: The database must be writable (not on read-only media)
  53064. **
  53065. ** 4: There must be an active transaction.
  53066. **
  53067. ** No checking is done to make sure that page iTable really is the
  53068. ** root page of a b-tree. If it is not, then the cursor acquired
  53069. ** will not work correctly.
  53070. **
  53071. ** It is assumed that the sqlite3BtreeCursorZero() has been called
  53072. ** on pCur to initialize the memory space prior to invoking this routine.
  53073. */
  53074. static int btreeCursor(
  53075. Btree *p, /* The btree */
  53076. int iTable, /* Root page of table to open */
  53077. int wrFlag, /* 1 to write. 0 read-only */
  53078. struct KeyInfo *pKeyInfo, /* First arg to comparison function */
  53079. BtCursor *pCur /* Space for new cursor */
  53080. ){
  53081. BtShared *pBt = p->pBt; /* Shared b-tree handle */
  53082. assert( sqlite3BtreeHoldsMutex(p) );
  53083. assert( wrFlag==0 || wrFlag==1 );
  53084. /* The following assert statements verify that if this is a sharable
  53085. ** b-tree database, the connection is holding the required table locks,
  53086. ** and that no other connection has any open cursor that conflicts with
  53087. ** this lock. */
  53088. assert( hasSharedCacheTableLock(p, iTable, pKeyInfo!=0, wrFlag+1) );
  53089. assert( wrFlag==0 || !hasReadConflicts(p, iTable) );
  53090. /* Assert that the caller has opened the required transaction. */
  53091. assert( p->inTrans>TRANS_NONE );
  53092. assert( wrFlag==0 || p->inTrans==TRANS_WRITE );
  53093. assert( pBt->pPage1 && pBt->pPage1->aData );
  53094. if( NEVER(wrFlag && (pBt->btsFlags & BTS_READ_ONLY)!=0) ){
  53095. return SQLITE_READONLY;
  53096. }
  53097. if( wrFlag ){
  53098. allocateTempSpace(pBt);
  53099. if( pBt->pTmpSpace==0 ) return SQLITE_NOMEM;
  53100. }
  53101. if( iTable==1 && btreePagecount(pBt)==0 ){
  53102. assert( wrFlag==0 );
  53103. iTable = 0;
  53104. }
  53105. /* Now that no other errors can occur, finish filling in the BtCursor
  53106. ** variables and link the cursor into the BtShared list. */
  53107. pCur->pgnoRoot = (Pgno)iTable;
  53108. pCur->iPage = -1;
  53109. pCur->pKeyInfo = pKeyInfo;
  53110. pCur->pBtree = p;
  53111. pCur->pBt = pBt;
  53112. assert( wrFlag==0 || wrFlag==BTCF_WriteFlag );
  53113. pCur->curFlags = wrFlag;
  53114. pCur->pNext = pBt->pCursor;
  53115. if( pCur->pNext ){
  53116. pCur->pNext->pPrev = pCur;
  53117. }
  53118. pBt->pCursor = pCur;
  53119. pCur->eState = CURSOR_INVALID;
  53120. return SQLITE_OK;
  53121. }
  53122. SQLITE_PRIVATE int sqlite3BtreeCursor(
  53123. Btree *p, /* The btree */
  53124. int iTable, /* Root page of table to open */
  53125. int wrFlag, /* 1 to write. 0 read-only */
  53126. struct KeyInfo *pKeyInfo, /* First arg to xCompare() */
  53127. BtCursor *pCur /* Write new cursor here */
  53128. ){
  53129. int rc;
  53130. sqlite3BtreeEnter(p);
  53131. rc = btreeCursor(p, iTable, wrFlag, pKeyInfo, pCur);
  53132. sqlite3BtreeLeave(p);
  53133. return rc;
  53134. }
  53135. /*
  53136. ** Return the size of a BtCursor object in bytes.
  53137. **
  53138. ** This interfaces is needed so that users of cursors can preallocate
  53139. ** sufficient storage to hold a cursor. The BtCursor object is opaque
  53140. ** to users so they cannot do the sizeof() themselves - they must call
  53141. ** this routine.
  53142. */
  53143. SQLITE_PRIVATE int sqlite3BtreeCursorSize(void){
  53144. return ROUND8(sizeof(BtCursor));
  53145. }
  53146. /*
  53147. ** Initialize memory that will be converted into a BtCursor object.
  53148. **
  53149. ** The simple approach here would be to memset() the entire object
  53150. ** to zero. But it turns out that the apPage[] and aiIdx[] arrays
  53151. ** do not need to be zeroed and they are large, so we can save a lot
  53152. ** of run-time by skipping the initialization of those elements.
  53153. */
  53154. SQLITE_PRIVATE void sqlite3BtreeCursorZero(BtCursor *p){
  53155. memset(p, 0, offsetof(BtCursor, iPage));
  53156. }
  53157. /*
  53158. ** Close a cursor. The read lock on the database file is released
  53159. ** when the last cursor is closed.
  53160. */
  53161. SQLITE_PRIVATE int sqlite3BtreeCloseCursor(BtCursor *pCur){
  53162. Btree *pBtree = pCur->pBtree;
  53163. if( pBtree ){
  53164. int i;
  53165. BtShared *pBt = pCur->pBt;
  53166. sqlite3BtreeEnter(pBtree);
  53167. sqlite3BtreeClearCursor(pCur);
  53168. if( pCur->pPrev ){
  53169. pCur->pPrev->pNext = pCur->pNext;
  53170. }else{
  53171. pBt->pCursor = pCur->pNext;
  53172. }
  53173. if( pCur->pNext ){
  53174. pCur->pNext->pPrev = pCur->pPrev;
  53175. }
  53176. for(i=0; i<=pCur->iPage; i++){
  53177. releasePage(pCur->apPage[i]);
  53178. }
  53179. unlockBtreeIfUnused(pBt);
  53180. sqlite3_free(pCur->aOverflow);
  53181. /* sqlite3_free(pCur); */
  53182. sqlite3BtreeLeave(pBtree);
  53183. }
  53184. return SQLITE_OK;
  53185. }
  53186. /*
  53187. ** Make sure the BtCursor* given in the argument has a valid
  53188. ** BtCursor.info structure. If it is not already valid, call
  53189. ** btreeParseCell() to fill it in.
  53190. **
  53191. ** BtCursor.info is a cache of the information in the current cell.
  53192. ** Using this cache reduces the number of calls to btreeParseCell().
  53193. **
  53194. ** 2007-06-25: There is a bug in some versions of MSVC that cause the
  53195. ** compiler to crash when getCellInfo() is implemented as a macro.
  53196. ** But there is a measureable speed advantage to using the macro on gcc
  53197. ** (when less compiler optimizations like -Os or -O0 are used and the
  53198. ** compiler is not doing aggressive inlining.) So we use a real function
  53199. ** for MSVC and a macro for everything else. Ticket #2457.
  53200. */
  53201. #ifndef NDEBUG
  53202. static void assertCellInfo(BtCursor *pCur){
  53203. CellInfo info;
  53204. int iPage = pCur->iPage;
  53205. memset(&info, 0, sizeof(info));
  53206. btreeParseCell(pCur->apPage[iPage], pCur->aiIdx[iPage], &info);
  53207. assert( CORRUPT_DB || memcmp(&info, &pCur->info, sizeof(info))==0 );
  53208. }
  53209. #else
  53210. #define assertCellInfo(x)
  53211. #endif
  53212. #ifdef _MSC_VER
  53213. /* Use a real function in MSVC to work around bugs in that compiler. */
  53214. static void getCellInfo(BtCursor *pCur){
  53215. if( pCur->info.nSize==0 ){
  53216. int iPage = pCur->iPage;
  53217. btreeParseCell(pCur->apPage[iPage],pCur->aiIdx[iPage],&pCur->info);
  53218. pCur->curFlags |= BTCF_ValidNKey;
  53219. }else{
  53220. assertCellInfo(pCur);
  53221. }
  53222. }
  53223. #else /* if not _MSC_VER */
  53224. /* Use a macro in all other compilers so that the function is inlined */
  53225. #define getCellInfo(pCur) \
  53226. if( pCur->info.nSize==0 ){ \
  53227. int iPage = pCur->iPage; \
  53228. btreeParseCell(pCur->apPage[iPage],pCur->aiIdx[iPage],&pCur->info); \
  53229. pCur->curFlags |= BTCF_ValidNKey; \
  53230. }else{ \
  53231. assertCellInfo(pCur); \
  53232. }
  53233. #endif /* _MSC_VER */
  53234. #ifndef NDEBUG /* The next routine used only within assert() statements */
  53235. /*
  53236. ** Return true if the given BtCursor is valid. A valid cursor is one
  53237. ** that is currently pointing to a row in a (non-empty) table.
  53238. ** This is a verification routine is used only within assert() statements.
  53239. */
  53240. SQLITE_PRIVATE int sqlite3BtreeCursorIsValid(BtCursor *pCur){
  53241. return pCur && pCur->eState==CURSOR_VALID;
  53242. }
  53243. #endif /* NDEBUG */
  53244. /*
  53245. ** Set *pSize to the size of the buffer needed to hold the value of
  53246. ** the key for the current entry. If the cursor is not pointing
  53247. ** to a valid entry, *pSize is set to 0.
  53248. **
  53249. ** For a table with the INTKEY flag set, this routine returns the key
  53250. ** itself, not the number of bytes in the key.
  53251. **
  53252. ** The caller must position the cursor prior to invoking this routine.
  53253. **
  53254. ** This routine cannot fail. It always returns SQLITE_OK.
  53255. */
  53256. SQLITE_PRIVATE int sqlite3BtreeKeySize(BtCursor *pCur, i64 *pSize){
  53257. assert( cursorHoldsMutex(pCur) );
  53258. assert( pCur->eState==CURSOR_VALID );
  53259. getCellInfo(pCur);
  53260. *pSize = pCur->info.nKey;
  53261. return SQLITE_OK;
  53262. }
  53263. /*
  53264. ** Set *pSize to the number of bytes of data in the entry the
  53265. ** cursor currently points to.
  53266. **
  53267. ** The caller must guarantee that the cursor is pointing to a non-NULL
  53268. ** valid entry. In other words, the calling procedure must guarantee
  53269. ** that the cursor has Cursor.eState==CURSOR_VALID.
  53270. **
  53271. ** Failure is not possible. This function always returns SQLITE_OK.
  53272. ** It might just as well be a procedure (returning void) but we continue
  53273. ** to return an integer result code for historical reasons.
  53274. */
  53275. SQLITE_PRIVATE int sqlite3BtreeDataSize(BtCursor *pCur, u32 *pSize){
  53276. assert( cursorHoldsMutex(pCur) );
  53277. assert( pCur->eState==CURSOR_VALID );
  53278. assert( pCur->iPage>=0 );
  53279. assert( pCur->iPage<BTCURSOR_MAX_DEPTH );
  53280. assert( pCur->apPage[pCur->iPage]->intKeyLeaf==1 );
  53281. getCellInfo(pCur);
  53282. *pSize = pCur->info.nPayload;
  53283. return SQLITE_OK;
  53284. }
  53285. /*
  53286. ** Given the page number of an overflow page in the database (parameter
  53287. ** ovfl), this function finds the page number of the next page in the
  53288. ** linked list of overflow pages. If possible, it uses the auto-vacuum
  53289. ** pointer-map data instead of reading the content of page ovfl to do so.
  53290. **
  53291. ** If an error occurs an SQLite error code is returned. Otherwise:
  53292. **
  53293. ** The page number of the next overflow page in the linked list is
  53294. ** written to *pPgnoNext. If page ovfl is the last page in its linked
  53295. ** list, *pPgnoNext is set to zero.
  53296. **
  53297. ** If ppPage is not NULL, and a reference to the MemPage object corresponding
  53298. ** to page number pOvfl was obtained, then *ppPage is set to point to that
  53299. ** reference. It is the responsibility of the caller to call releasePage()
  53300. ** on *ppPage to free the reference. In no reference was obtained (because
  53301. ** the pointer-map was used to obtain the value for *pPgnoNext), then
  53302. ** *ppPage is set to zero.
  53303. */
  53304. static int getOverflowPage(
  53305. BtShared *pBt, /* The database file */
  53306. Pgno ovfl, /* Current overflow page number */
  53307. MemPage **ppPage, /* OUT: MemPage handle (may be NULL) */
  53308. Pgno *pPgnoNext /* OUT: Next overflow page number */
  53309. ){
  53310. Pgno next = 0;
  53311. MemPage *pPage = 0;
  53312. int rc = SQLITE_OK;
  53313. assert( sqlite3_mutex_held(pBt->mutex) );
  53314. assert(pPgnoNext);
  53315. #ifndef SQLITE_OMIT_AUTOVACUUM
  53316. /* Try to find the next page in the overflow list using the
  53317. ** autovacuum pointer-map pages. Guess that the next page in
  53318. ** the overflow list is page number (ovfl+1). If that guess turns
  53319. ** out to be wrong, fall back to loading the data of page
  53320. ** number ovfl to determine the next page number.
  53321. */
  53322. if( pBt->autoVacuum ){
  53323. Pgno pgno;
  53324. Pgno iGuess = ovfl+1;
  53325. u8 eType;
  53326. while( PTRMAP_ISPAGE(pBt, iGuess) || iGuess==PENDING_BYTE_PAGE(pBt) ){
  53327. iGuess++;
  53328. }
  53329. if( iGuess<=btreePagecount(pBt) ){
  53330. rc = ptrmapGet(pBt, iGuess, &eType, &pgno);
  53331. if( rc==SQLITE_OK && eType==PTRMAP_OVERFLOW2 && pgno==ovfl ){
  53332. next = iGuess;
  53333. rc = SQLITE_DONE;
  53334. }
  53335. }
  53336. }
  53337. #endif
  53338. assert( next==0 || rc==SQLITE_DONE );
  53339. if( rc==SQLITE_OK ){
  53340. rc = btreeGetPage(pBt, ovfl, &pPage, (ppPage==0) ? PAGER_GET_READONLY : 0);
  53341. assert( rc==SQLITE_OK || pPage==0 );
  53342. if( rc==SQLITE_OK ){
  53343. next = get4byte(pPage->aData);
  53344. }
  53345. }
  53346. *pPgnoNext = next;
  53347. if( ppPage ){
  53348. *ppPage = pPage;
  53349. }else{
  53350. releasePage(pPage);
  53351. }
  53352. return (rc==SQLITE_DONE ? SQLITE_OK : rc);
  53353. }
  53354. /*
  53355. ** Copy data from a buffer to a page, or from a page to a buffer.
  53356. **
  53357. ** pPayload is a pointer to data stored on database page pDbPage.
  53358. ** If argument eOp is false, then nByte bytes of data are copied
  53359. ** from pPayload to the buffer pointed at by pBuf. If eOp is true,
  53360. ** then sqlite3PagerWrite() is called on pDbPage and nByte bytes
  53361. ** of data are copied from the buffer pBuf to pPayload.
  53362. **
  53363. ** SQLITE_OK is returned on success, otherwise an error code.
  53364. */
  53365. static int copyPayload(
  53366. void *pPayload, /* Pointer to page data */
  53367. void *pBuf, /* Pointer to buffer */
  53368. int nByte, /* Number of bytes to copy */
  53369. int eOp, /* 0 -> copy from page, 1 -> copy to page */
  53370. DbPage *pDbPage /* Page containing pPayload */
  53371. ){
  53372. if( eOp ){
  53373. /* Copy data from buffer to page (a write operation) */
  53374. int rc = sqlite3PagerWrite(pDbPage);
  53375. if( rc!=SQLITE_OK ){
  53376. return rc;
  53377. }
  53378. memcpy(pPayload, pBuf, nByte);
  53379. }else{
  53380. /* Copy data from page to buffer (a read operation) */
  53381. memcpy(pBuf, pPayload, nByte);
  53382. }
  53383. return SQLITE_OK;
  53384. }
  53385. /*
  53386. ** This function is used to read or overwrite payload information
  53387. ** for the entry that the pCur cursor is pointing to. The eOp
  53388. ** argument is interpreted as follows:
  53389. **
  53390. ** 0: The operation is a read. Populate the overflow cache.
  53391. ** 1: The operation is a write. Populate the overflow cache.
  53392. ** 2: The operation is a read. Do not populate the overflow cache.
  53393. **
  53394. ** A total of "amt" bytes are read or written beginning at "offset".
  53395. ** Data is read to or from the buffer pBuf.
  53396. **
  53397. ** The content being read or written might appear on the main page
  53398. ** or be scattered out on multiple overflow pages.
  53399. **
  53400. ** If the current cursor entry uses one or more overflow pages and the
  53401. ** eOp argument is not 2, this function may allocate space for and lazily
  53402. ** populates the overflow page-list cache array (BtCursor.aOverflow).
  53403. ** Subsequent calls use this cache to make seeking to the supplied offset
  53404. ** more efficient.
  53405. **
  53406. ** Once an overflow page-list cache has been allocated, it may be
  53407. ** invalidated if some other cursor writes to the same table, or if
  53408. ** the cursor is moved to a different row. Additionally, in auto-vacuum
  53409. ** mode, the following events may invalidate an overflow page-list cache.
  53410. **
  53411. ** * An incremental vacuum,
  53412. ** * A commit in auto_vacuum="full" mode,
  53413. ** * Creating a table (may require moving an overflow page).
  53414. */
  53415. static int accessPayload(
  53416. BtCursor *pCur, /* Cursor pointing to entry to read from */
  53417. u32 offset, /* Begin reading this far into payload */
  53418. u32 amt, /* Read this many bytes */
  53419. unsigned char *pBuf, /* Write the bytes into this buffer */
  53420. int eOp /* zero to read. non-zero to write. */
  53421. ){
  53422. unsigned char *aPayload;
  53423. int rc = SQLITE_OK;
  53424. int iIdx = 0;
  53425. MemPage *pPage = pCur->apPage[pCur->iPage]; /* Btree page of current entry */
  53426. BtShared *pBt = pCur->pBt; /* Btree this cursor belongs to */
  53427. #ifdef SQLITE_DIRECT_OVERFLOW_READ
  53428. unsigned char * const pBufStart = pBuf;
  53429. int bEnd; /* True if reading to end of data */
  53430. #endif
  53431. assert( pPage );
  53432. assert( pCur->eState==CURSOR_VALID );
  53433. assert( pCur->aiIdx[pCur->iPage]<pPage->nCell );
  53434. assert( cursorHoldsMutex(pCur) );
  53435. assert( eOp!=2 || offset==0 ); /* Always start from beginning for eOp==2 */
  53436. getCellInfo(pCur);
  53437. aPayload = pCur->info.pPayload;
  53438. #ifdef SQLITE_DIRECT_OVERFLOW_READ
  53439. bEnd = offset+amt==pCur->info.nPayload;
  53440. #endif
  53441. assert( offset+amt <= pCur->info.nPayload );
  53442. if( &aPayload[pCur->info.nLocal] > &pPage->aData[pBt->usableSize] ){
  53443. /* Trying to read or write past the end of the data is an error */
  53444. return SQLITE_CORRUPT_BKPT;
  53445. }
  53446. /* Check if data must be read/written to/from the btree page itself. */
  53447. if( offset<pCur->info.nLocal ){
  53448. int a = amt;
  53449. if( a+offset>pCur->info.nLocal ){
  53450. a = pCur->info.nLocal - offset;
  53451. }
  53452. rc = copyPayload(&aPayload[offset], pBuf, a, (eOp & 0x01), pPage->pDbPage);
  53453. offset = 0;
  53454. pBuf += a;
  53455. amt -= a;
  53456. }else{
  53457. offset -= pCur->info.nLocal;
  53458. }
  53459. if( rc==SQLITE_OK && amt>0 ){
  53460. const u32 ovflSize = pBt->usableSize - 4; /* Bytes content per ovfl page */
  53461. Pgno nextPage;
  53462. nextPage = get4byte(&aPayload[pCur->info.nLocal]);
  53463. /* If the BtCursor.aOverflow[] has not been allocated, allocate it now.
  53464. ** Except, do not allocate aOverflow[] for eOp==2.
  53465. **
  53466. ** The aOverflow[] array is sized at one entry for each overflow page
  53467. ** in the overflow chain. The page number of the first overflow page is
  53468. ** stored in aOverflow[0], etc. A value of 0 in the aOverflow[] array
  53469. ** means "not yet known" (the cache is lazily populated).
  53470. */
  53471. if( eOp!=2 && (pCur->curFlags & BTCF_ValidOvfl)==0 ){
  53472. int nOvfl = (pCur->info.nPayload-pCur->info.nLocal+ovflSize-1)/ovflSize;
  53473. if( nOvfl>pCur->nOvflAlloc ){
  53474. Pgno *aNew = (Pgno*)sqlite3Realloc(
  53475. pCur->aOverflow, nOvfl*2*sizeof(Pgno)
  53476. );
  53477. if( aNew==0 ){
  53478. rc = SQLITE_NOMEM;
  53479. }else{
  53480. pCur->nOvflAlloc = nOvfl*2;
  53481. pCur->aOverflow = aNew;
  53482. }
  53483. }
  53484. if( rc==SQLITE_OK ){
  53485. memset(pCur->aOverflow, 0, nOvfl*sizeof(Pgno));
  53486. pCur->curFlags |= BTCF_ValidOvfl;
  53487. }
  53488. }
  53489. /* If the overflow page-list cache has been allocated and the
  53490. ** entry for the first required overflow page is valid, skip
  53491. ** directly to it.
  53492. */
  53493. if( (pCur->curFlags & BTCF_ValidOvfl)!=0
  53494. && pCur->aOverflow[offset/ovflSize]
  53495. ){
  53496. iIdx = (offset/ovflSize);
  53497. nextPage = pCur->aOverflow[iIdx];
  53498. offset = (offset%ovflSize);
  53499. }
  53500. for( ; rc==SQLITE_OK && amt>0 && nextPage; iIdx++){
  53501. /* If required, populate the overflow page-list cache. */
  53502. if( (pCur->curFlags & BTCF_ValidOvfl)!=0 ){
  53503. assert(!pCur->aOverflow[iIdx] || pCur->aOverflow[iIdx]==nextPage);
  53504. pCur->aOverflow[iIdx] = nextPage;
  53505. }
  53506. if( offset>=ovflSize ){
  53507. /* The only reason to read this page is to obtain the page
  53508. ** number for the next page in the overflow chain. The page
  53509. ** data is not required. So first try to lookup the overflow
  53510. ** page-list cache, if any, then fall back to the getOverflowPage()
  53511. ** function.
  53512. **
  53513. ** Note that the aOverflow[] array must be allocated because eOp!=2
  53514. ** here. If eOp==2, then offset==0 and this branch is never taken.
  53515. */
  53516. assert( eOp!=2 );
  53517. assert( pCur->curFlags & BTCF_ValidOvfl );
  53518. assert( pCur->pBtree->db==pBt->db );
  53519. if( pCur->aOverflow[iIdx+1] ){
  53520. nextPage = pCur->aOverflow[iIdx+1];
  53521. }else{
  53522. rc = getOverflowPage(pBt, nextPage, 0, &nextPage);
  53523. }
  53524. offset -= ovflSize;
  53525. }else{
  53526. /* Need to read this page properly. It contains some of the
  53527. ** range of data that is being read (eOp==0) or written (eOp!=0).
  53528. */
  53529. #ifdef SQLITE_DIRECT_OVERFLOW_READ
  53530. sqlite3_file *fd;
  53531. #endif
  53532. int a = amt;
  53533. if( a + offset > ovflSize ){
  53534. a = ovflSize - offset;
  53535. }
  53536. #ifdef SQLITE_DIRECT_OVERFLOW_READ
  53537. /* If all the following are true:
  53538. **
  53539. ** 1) this is a read operation, and
  53540. ** 2) data is required from the start of this overflow page, and
  53541. ** 3) the database is file-backed, and
  53542. ** 4) there is no open write-transaction, and
  53543. ** 5) the database is not a WAL database,
  53544. ** 6) all data from the page is being read.
  53545. ** 7) at least 4 bytes have already been read into the output buffer
  53546. **
  53547. ** then data can be read directly from the database file into the
  53548. ** output buffer, bypassing the page-cache altogether. This speeds
  53549. ** up loading large records that span many overflow pages.
  53550. */
  53551. if( (eOp&0x01)==0 /* (1) */
  53552. && offset==0 /* (2) */
  53553. && (bEnd || a==ovflSize) /* (6) */
  53554. && pBt->inTransaction==TRANS_READ /* (4) */
  53555. && (fd = sqlite3PagerFile(pBt->pPager))->pMethods /* (3) */
  53556. && pBt->pPage1->aData[19]==0x01 /* (5) */
  53557. && &pBuf[-4]>=pBufStart /* (7) */
  53558. ){
  53559. u8 aSave[4];
  53560. u8 *aWrite = &pBuf[-4];
  53561. assert( aWrite>=pBufStart ); /* hence (7) */
  53562. memcpy(aSave, aWrite, 4);
  53563. rc = sqlite3OsRead(fd, aWrite, a+4, (i64)pBt->pageSize*(nextPage-1));
  53564. nextPage = get4byte(aWrite);
  53565. memcpy(aWrite, aSave, 4);
  53566. }else
  53567. #endif
  53568. {
  53569. DbPage *pDbPage;
  53570. rc = sqlite3PagerAcquire(pBt->pPager, nextPage, &pDbPage,
  53571. ((eOp&0x01)==0 ? PAGER_GET_READONLY : 0)
  53572. );
  53573. if( rc==SQLITE_OK ){
  53574. aPayload = sqlite3PagerGetData(pDbPage);
  53575. nextPage = get4byte(aPayload);
  53576. rc = copyPayload(&aPayload[offset+4], pBuf, a, (eOp&0x01), pDbPage);
  53577. sqlite3PagerUnref(pDbPage);
  53578. offset = 0;
  53579. }
  53580. }
  53581. amt -= a;
  53582. pBuf += a;
  53583. }
  53584. }
  53585. }
  53586. if( rc==SQLITE_OK && amt>0 ){
  53587. return SQLITE_CORRUPT_BKPT;
  53588. }
  53589. return rc;
  53590. }
  53591. /*
  53592. ** Read part of the key associated with cursor pCur. Exactly
  53593. ** "amt" bytes will be transferred into pBuf[]. The transfer
  53594. ** begins at "offset".
  53595. **
  53596. ** The caller must ensure that pCur is pointing to a valid row
  53597. ** in the table.
  53598. **
  53599. ** Return SQLITE_OK on success or an error code if anything goes
  53600. ** wrong. An error is returned if "offset+amt" is larger than
  53601. ** the available payload.
  53602. */
  53603. SQLITE_PRIVATE int sqlite3BtreeKey(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){
  53604. assert( cursorHoldsMutex(pCur) );
  53605. assert( pCur->eState==CURSOR_VALID );
  53606. assert( pCur->iPage>=0 && pCur->apPage[pCur->iPage] );
  53607. assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
  53608. return accessPayload(pCur, offset, amt, (unsigned char*)pBuf, 0);
  53609. }
  53610. /*
  53611. ** Read part of the data associated with cursor pCur. Exactly
  53612. ** "amt" bytes will be transfered into pBuf[]. The transfer
  53613. ** begins at "offset".
  53614. **
  53615. ** Return SQLITE_OK on success or an error code if anything goes
  53616. ** wrong. An error is returned if "offset+amt" is larger than
  53617. ** the available payload.
  53618. */
  53619. SQLITE_PRIVATE int sqlite3BtreeData(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){
  53620. int rc;
  53621. #ifndef SQLITE_OMIT_INCRBLOB
  53622. if ( pCur->eState==CURSOR_INVALID ){
  53623. return SQLITE_ABORT;
  53624. }
  53625. #endif
  53626. assert( cursorHoldsMutex(pCur) );
  53627. rc = restoreCursorPosition(pCur);
  53628. if( rc==SQLITE_OK ){
  53629. assert( pCur->eState==CURSOR_VALID );
  53630. assert( pCur->iPage>=0 && pCur->apPage[pCur->iPage] );
  53631. assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
  53632. rc = accessPayload(pCur, offset, amt, pBuf, 0);
  53633. }
  53634. return rc;
  53635. }
  53636. /*
  53637. ** Return a pointer to payload information from the entry that the
  53638. ** pCur cursor is pointing to. The pointer is to the beginning of
  53639. ** the key if index btrees (pPage->intKey==0) and is the data for
  53640. ** table btrees (pPage->intKey==1). The number of bytes of available
  53641. ** key/data is written into *pAmt. If *pAmt==0, then the value
  53642. ** returned will not be a valid pointer.
  53643. **
  53644. ** This routine is an optimization. It is common for the entire key
  53645. ** and data to fit on the local page and for there to be no overflow
  53646. ** pages. When that is so, this routine can be used to access the
  53647. ** key and data without making a copy. If the key and/or data spills
  53648. ** onto overflow pages, then accessPayload() must be used to reassemble
  53649. ** the key/data and copy it into a preallocated buffer.
  53650. **
  53651. ** The pointer returned by this routine looks directly into the cached
  53652. ** page of the database. The data might change or move the next time
  53653. ** any btree routine is called.
  53654. */
  53655. static const void *fetchPayload(
  53656. BtCursor *pCur, /* Cursor pointing to entry to read from */
  53657. u32 *pAmt /* Write the number of available bytes here */
  53658. ){
  53659. u32 amt;
  53660. assert( pCur!=0 && pCur->iPage>=0 && pCur->apPage[pCur->iPage]);
  53661. assert( pCur->eState==CURSOR_VALID );
  53662. assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
  53663. assert( cursorHoldsMutex(pCur) );
  53664. assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
  53665. assert( pCur->info.nSize>0 );
  53666. assert( pCur->info.pPayload>pCur->apPage[pCur->iPage]->aData || CORRUPT_DB );
  53667. assert( pCur->info.pPayload<pCur->apPage[pCur->iPage]->aDataEnd ||CORRUPT_DB);
  53668. amt = (int)(pCur->apPage[pCur->iPage]->aDataEnd - pCur->info.pPayload);
  53669. if( pCur->info.nLocal<amt ) amt = pCur->info.nLocal;
  53670. *pAmt = amt;
  53671. return (void*)pCur->info.pPayload;
  53672. }
  53673. /*
  53674. ** For the entry that cursor pCur is point to, return as
  53675. ** many bytes of the key or data as are available on the local
  53676. ** b-tree page. Write the number of available bytes into *pAmt.
  53677. **
  53678. ** The pointer returned is ephemeral. The key/data may move
  53679. ** or be destroyed on the next call to any Btree routine,
  53680. ** including calls from other threads against the same cache.
  53681. ** Hence, a mutex on the BtShared should be held prior to calling
  53682. ** this routine.
  53683. **
  53684. ** These routines is used to get quick access to key and data
  53685. ** in the common case where no overflow pages are used.
  53686. */
  53687. SQLITE_PRIVATE const void *sqlite3BtreeKeyFetch(BtCursor *pCur, u32 *pAmt){
  53688. return fetchPayload(pCur, pAmt);
  53689. }
  53690. SQLITE_PRIVATE const void *sqlite3BtreeDataFetch(BtCursor *pCur, u32 *pAmt){
  53691. return fetchPayload(pCur, pAmt);
  53692. }
  53693. /*
  53694. ** Move the cursor down to a new child page. The newPgno argument is the
  53695. ** page number of the child page to move to.
  53696. **
  53697. ** This function returns SQLITE_CORRUPT if the page-header flags field of
  53698. ** the new child page does not match the flags field of the parent (i.e.
  53699. ** if an intkey page appears to be the parent of a non-intkey page, or
  53700. ** vice-versa).
  53701. */
  53702. static int moveToChild(BtCursor *pCur, u32 newPgno){
  53703. int rc;
  53704. int i = pCur->iPage;
  53705. MemPage *pNewPage;
  53706. BtShared *pBt = pCur->pBt;
  53707. assert( cursorHoldsMutex(pCur) );
  53708. assert( pCur->eState==CURSOR_VALID );
  53709. assert( pCur->iPage<BTCURSOR_MAX_DEPTH );
  53710. assert( pCur->iPage>=0 );
  53711. if( pCur->iPage>=(BTCURSOR_MAX_DEPTH-1) ){
  53712. return SQLITE_CORRUPT_BKPT;
  53713. }
  53714. rc = getAndInitPage(pBt, newPgno, &pNewPage,
  53715. (pCur->curFlags & BTCF_WriteFlag)==0 ? PAGER_GET_READONLY : 0);
  53716. if( rc ) return rc;
  53717. pCur->apPage[i+1] = pNewPage;
  53718. pCur->aiIdx[i+1] = 0;
  53719. pCur->iPage++;
  53720. pCur->info.nSize = 0;
  53721. pCur->curFlags &= ~(BTCF_ValidNKey|BTCF_ValidOvfl);
  53722. if( pNewPage->nCell<1 || pNewPage->intKey!=pCur->apPage[i]->intKey ){
  53723. return SQLITE_CORRUPT_BKPT;
  53724. }
  53725. return SQLITE_OK;
  53726. }
  53727. #if SQLITE_DEBUG
  53728. /*
  53729. ** Page pParent is an internal (non-leaf) tree page. This function
  53730. ** asserts that page number iChild is the left-child if the iIdx'th
  53731. ** cell in page pParent. Or, if iIdx is equal to the total number of
  53732. ** cells in pParent, that page number iChild is the right-child of
  53733. ** the page.
  53734. */
  53735. static void assertParentIndex(MemPage *pParent, int iIdx, Pgno iChild){
  53736. if( CORRUPT_DB ) return; /* The conditions tested below might not be true
  53737. ** in a corrupt database */
  53738. assert( iIdx<=pParent->nCell );
  53739. if( iIdx==pParent->nCell ){
  53740. assert( get4byte(&pParent->aData[pParent->hdrOffset+8])==iChild );
  53741. }else{
  53742. assert( get4byte(findCell(pParent, iIdx))==iChild );
  53743. }
  53744. }
  53745. #else
  53746. # define assertParentIndex(x,y,z)
  53747. #endif
  53748. /*
  53749. ** Move the cursor up to the parent page.
  53750. **
  53751. ** pCur->idx is set to the cell index that contains the pointer
  53752. ** to the page we are coming from. If we are coming from the
  53753. ** right-most child page then pCur->idx is set to one more than
  53754. ** the largest cell index.
  53755. */
  53756. static void moveToParent(BtCursor *pCur){
  53757. assert( cursorHoldsMutex(pCur) );
  53758. assert( pCur->eState==CURSOR_VALID );
  53759. assert( pCur->iPage>0 );
  53760. assert( pCur->apPage[pCur->iPage] );
  53761. assertParentIndex(
  53762. pCur->apPage[pCur->iPage-1],
  53763. pCur->aiIdx[pCur->iPage-1],
  53764. pCur->apPage[pCur->iPage]->pgno
  53765. );
  53766. testcase( pCur->aiIdx[pCur->iPage-1] > pCur->apPage[pCur->iPage-1]->nCell );
  53767. releasePage(pCur->apPage[pCur->iPage]);
  53768. pCur->iPage--;
  53769. pCur->info.nSize = 0;
  53770. pCur->curFlags &= ~(BTCF_ValidNKey|BTCF_ValidOvfl);
  53771. }
  53772. /*
  53773. ** Move the cursor to point to the root page of its b-tree structure.
  53774. **
  53775. ** If the table has a virtual root page, then the cursor is moved to point
  53776. ** to the virtual root page instead of the actual root page. A table has a
  53777. ** virtual root page when the actual root page contains no cells and a
  53778. ** single child page. This can only happen with the table rooted at page 1.
  53779. **
  53780. ** If the b-tree structure is empty, the cursor state is set to
  53781. ** CURSOR_INVALID. Otherwise, the cursor is set to point to the first
  53782. ** cell located on the root (or virtual root) page and the cursor state
  53783. ** is set to CURSOR_VALID.
  53784. **
  53785. ** If this function returns successfully, it may be assumed that the
  53786. ** page-header flags indicate that the [virtual] root-page is the expected
  53787. ** kind of b-tree page (i.e. if when opening the cursor the caller did not
  53788. ** specify a KeyInfo structure the flags byte is set to 0x05 or 0x0D,
  53789. ** indicating a table b-tree, or if the caller did specify a KeyInfo
  53790. ** structure the flags byte is set to 0x02 or 0x0A, indicating an index
  53791. ** b-tree).
  53792. */
  53793. static int moveToRoot(BtCursor *pCur){
  53794. MemPage *pRoot;
  53795. int rc = SQLITE_OK;
  53796. assert( cursorHoldsMutex(pCur) );
  53797. assert( CURSOR_INVALID < CURSOR_REQUIRESEEK );
  53798. assert( CURSOR_VALID < CURSOR_REQUIRESEEK );
  53799. assert( CURSOR_FAULT > CURSOR_REQUIRESEEK );
  53800. if( pCur->eState>=CURSOR_REQUIRESEEK ){
  53801. if( pCur->eState==CURSOR_FAULT ){
  53802. assert( pCur->skipNext!=SQLITE_OK );
  53803. return pCur->skipNext;
  53804. }
  53805. sqlite3BtreeClearCursor(pCur);
  53806. }
  53807. if( pCur->iPage>=0 ){
  53808. while( pCur->iPage ) releasePage(pCur->apPage[pCur->iPage--]);
  53809. }else if( pCur->pgnoRoot==0 ){
  53810. pCur->eState = CURSOR_INVALID;
  53811. return SQLITE_OK;
  53812. }else{
  53813. rc = getAndInitPage(pCur->pBtree->pBt, pCur->pgnoRoot, &pCur->apPage[0],
  53814. (pCur->curFlags & BTCF_WriteFlag)==0 ? PAGER_GET_READONLY : 0);
  53815. if( rc!=SQLITE_OK ){
  53816. pCur->eState = CURSOR_INVALID;
  53817. return rc;
  53818. }
  53819. pCur->iPage = 0;
  53820. }
  53821. pRoot = pCur->apPage[0];
  53822. assert( pRoot->pgno==pCur->pgnoRoot );
  53823. /* If pCur->pKeyInfo is not NULL, then the caller that opened this cursor
  53824. ** expected to open it on an index b-tree. Otherwise, if pKeyInfo is
  53825. ** NULL, the caller expects a table b-tree. If this is not the case,
  53826. ** return an SQLITE_CORRUPT error.
  53827. **
  53828. ** Earlier versions of SQLite assumed that this test could not fail
  53829. ** if the root page was already loaded when this function was called (i.e.
  53830. ** if pCur->iPage>=0). But this is not so if the database is corrupted
  53831. ** in such a way that page pRoot is linked into a second b-tree table
  53832. ** (or the freelist). */
  53833. assert( pRoot->intKey==1 || pRoot->intKey==0 );
  53834. if( pRoot->isInit==0 || (pCur->pKeyInfo==0)!=pRoot->intKey ){
  53835. return SQLITE_CORRUPT_BKPT;
  53836. }
  53837. pCur->aiIdx[0] = 0;
  53838. pCur->info.nSize = 0;
  53839. pCur->curFlags &= ~(BTCF_AtLast|BTCF_ValidNKey|BTCF_ValidOvfl);
  53840. if( pRoot->nCell>0 ){
  53841. pCur->eState = CURSOR_VALID;
  53842. }else if( !pRoot->leaf ){
  53843. Pgno subpage;
  53844. if( pRoot->pgno!=1 ) return SQLITE_CORRUPT_BKPT;
  53845. subpage = get4byte(&pRoot->aData[pRoot->hdrOffset+8]);
  53846. pCur->eState = CURSOR_VALID;
  53847. rc = moveToChild(pCur, subpage);
  53848. }else{
  53849. pCur->eState = CURSOR_INVALID;
  53850. }
  53851. return rc;
  53852. }
  53853. /*
  53854. ** Move the cursor down to the left-most leaf entry beneath the
  53855. ** entry to which it is currently pointing.
  53856. **
  53857. ** The left-most leaf is the one with the smallest key - the first
  53858. ** in ascending order.
  53859. */
  53860. static int moveToLeftmost(BtCursor *pCur){
  53861. Pgno pgno;
  53862. int rc = SQLITE_OK;
  53863. MemPage *pPage;
  53864. assert( cursorHoldsMutex(pCur) );
  53865. assert( pCur->eState==CURSOR_VALID );
  53866. while( rc==SQLITE_OK && !(pPage = pCur->apPage[pCur->iPage])->leaf ){
  53867. assert( pCur->aiIdx[pCur->iPage]<pPage->nCell );
  53868. pgno = get4byte(findCell(pPage, pCur->aiIdx[pCur->iPage]));
  53869. rc = moveToChild(pCur, pgno);
  53870. }
  53871. return rc;
  53872. }
  53873. /*
  53874. ** Move the cursor down to the right-most leaf entry beneath the
  53875. ** page to which it is currently pointing. Notice the difference
  53876. ** between moveToLeftmost() and moveToRightmost(). moveToLeftmost()
  53877. ** finds the left-most entry beneath the *entry* whereas moveToRightmost()
  53878. ** finds the right-most entry beneath the *page*.
  53879. **
  53880. ** The right-most entry is the one with the largest key - the last
  53881. ** key in ascending order.
  53882. */
  53883. static int moveToRightmost(BtCursor *pCur){
  53884. Pgno pgno;
  53885. int rc = SQLITE_OK;
  53886. MemPage *pPage = 0;
  53887. assert( cursorHoldsMutex(pCur) );
  53888. assert( pCur->eState==CURSOR_VALID );
  53889. while( !(pPage = pCur->apPage[pCur->iPage])->leaf ){
  53890. pgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
  53891. pCur->aiIdx[pCur->iPage] = pPage->nCell;
  53892. rc = moveToChild(pCur, pgno);
  53893. if( rc ) return rc;
  53894. }
  53895. pCur->aiIdx[pCur->iPage] = pPage->nCell-1;
  53896. assert( pCur->info.nSize==0 );
  53897. assert( (pCur->curFlags & BTCF_ValidNKey)==0 );
  53898. return SQLITE_OK;
  53899. }
  53900. /* Move the cursor to the first entry in the table. Return SQLITE_OK
  53901. ** on success. Set *pRes to 0 if the cursor actually points to something
  53902. ** or set *pRes to 1 if the table is empty.
  53903. */
  53904. SQLITE_PRIVATE int sqlite3BtreeFirst(BtCursor *pCur, int *pRes){
  53905. int rc;
  53906. assert( cursorHoldsMutex(pCur) );
  53907. assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
  53908. rc = moveToRoot(pCur);
  53909. if( rc==SQLITE_OK ){
  53910. if( pCur->eState==CURSOR_INVALID ){
  53911. assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage]->nCell==0 );
  53912. *pRes = 1;
  53913. }else{
  53914. assert( pCur->apPage[pCur->iPage]->nCell>0 );
  53915. *pRes = 0;
  53916. rc = moveToLeftmost(pCur);
  53917. }
  53918. }
  53919. return rc;
  53920. }
  53921. /* Move the cursor to the last entry in the table. Return SQLITE_OK
  53922. ** on success. Set *pRes to 0 if the cursor actually points to something
  53923. ** or set *pRes to 1 if the table is empty.
  53924. */
  53925. SQLITE_PRIVATE int sqlite3BtreeLast(BtCursor *pCur, int *pRes){
  53926. int rc;
  53927. assert( cursorHoldsMutex(pCur) );
  53928. assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
  53929. /* If the cursor already points to the last entry, this is a no-op. */
  53930. if( CURSOR_VALID==pCur->eState && (pCur->curFlags & BTCF_AtLast)!=0 ){
  53931. #ifdef SQLITE_DEBUG
  53932. /* This block serves to assert() that the cursor really does point
  53933. ** to the last entry in the b-tree. */
  53934. int ii;
  53935. for(ii=0; ii<pCur->iPage; ii++){
  53936. assert( pCur->aiIdx[ii]==pCur->apPage[ii]->nCell );
  53937. }
  53938. assert( pCur->aiIdx[pCur->iPage]==pCur->apPage[pCur->iPage]->nCell-1 );
  53939. assert( pCur->apPage[pCur->iPage]->leaf );
  53940. #endif
  53941. return SQLITE_OK;
  53942. }
  53943. rc = moveToRoot(pCur);
  53944. if( rc==SQLITE_OK ){
  53945. if( CURSOR_INVALID==pCur->eState ){
  53946. assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage]->nCell==0 );
  53947. *pRes = 1;
  53948. }else{
  53949. assert( pCur->eState==CURSOR_VALID );
  53950. *pRes = 0;
  53951. rc = moveToRightmost(pCur);
  53952. if( rc==SQLITE_OK ){
  53953. pCur->curFlags |= BTCF_AtLast;
  53954. }else{
  53955. pCur->curFlags &= ~BTCF_AtLast;
  53956. }
  53957. }
  53958. }
  53959. return rc;
  53960. }
  53961. /* Move the cursor so that it points to an entry near the key
  53962. ** specified by pIdxKey or intKey. Return a success code.
  53963. **
  53964. ** For INTKEY tables, the intKey parameter is used. pIdxKey
  53965. ** must be NULL. For index tables, pIdxKey is used and intKey
  53966. ** is ignored.
  53967. **
  53968. ** If an exact match is not found, then the cursor is always
  53969. ** left pointing at a leaf page which would hold the entry if it
  53970. ** were present. The cursor might point to an entry that comes
  53971. ** before or after the key.
  53972. **
  53973. ** An integer is written into *pRes which is the result of
  53974. ** comparing the key with the entry to which the cursor is
  53975. ** pointing. The meaning of the integer written into
  53976. ** *pRes is as follows:
  53977. **
  53978. ** *pRes<0 The cursor is left pointing at an entry that
  53979. ** is smaller than intKey/pIdxKey or if the table is empty
  53980. ** and the cursor is therefore left point to nothing.
  53981. **
  53982. ** *pRes==0 The cursor is left pointing at an entry that
  53983. ** exactly matches intKey/pIdxKey.
  53984. **
  53985. ** *pRes>0 The cursor is left pointing at an entry that
  53986. ** is larger than intKey/pIdxKey.
  53987. **
  53988. */
  53989. SQLITE_PRIVATE int sqlite3BtreeMovetoUnpacked(
  53990. BtCursor *pCur, /* The cursor to be moved */
  53991. UnpackedRecord *pIdxKey, /* Unpacked index key */
  53992. i64 intKey, /* The table key */
  53993. int biasRight, /* If true, bias the search to the high end */
  53994. int *pRes /* Write search results here */
  53995. ){
  53996. int rc;
  53997. RecordCompare xRecordCompare;
  53998. assert( cursorHoldsMutex(pCur) );
  53999. assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
  54000. assert( pRes );
  54001. assert( (pIdxKey==0)==(pCur->pKeyInfo==0) );
  54002. /* If the cursor is already positioned at the point we are trying
  54003. ** to move to, then just return without doing any work */
  54004. if( pCur->eState==CURSOR_VALID && (pCur->curFlags & BTCF_ValidNKey)!=0
  54005. && pCur->apPage[0]->intKey
  54006. ){
  54007. if( pCur->info.nKey==intKey ){
  54008. *pRes = 0;
  54009. return SQLITE_OK;
  54010. }
  54011. if( (pCur->curFlags & BTCF_AtLast)!=0 && pCur->info.nKey<intKey ){
  54012. *pRes = -1;
  54013. return SQLITE_OK;
  54014. }
  54015. }
  54016. if( pIdxKey ){
  54017. xRecordCompare = sqlite3VdbeFindCompare(pIdxKey);
  54018. pIdxKey->errCode = 0;
  54019. assert( pIdxKey->default_rc==1
  54020. || pIdxKey->default_rc==0
  54021. || pIdxKey->default_rc==-1
  54022. );
  54023. }else{
  54024. xRecordCompare = 0; /* All keys are integers */
  54025. }
  54026. rc = moveToRoot(pCur);
  54027. if( rc ){
  54028. return rc;
  54029. }
  54030. assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage] );
  54031. assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage]->isInit );
  54032. assert( pCur->eState==CURSOR_INVALID || pCur->apPage[pCur->iPage]->nCell>0 );
  54033. if( pCur->eState==CURSOR_INVALID ){
  54034. *pRes = -1;
  54035. assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage]->nCell==0 );
  54036. return SQLITE_OK;
  54037. }
  54038. assert( pCur->apPage[0]->intKey || pIdxKey );
  54039. for(;;){
  54040. int lwr, upr, idx, c;
  54041. Pgno chldPg;
  54042. MemPage *pPage = pCur->apPage[pCur->iPage];
  54043. u8 *pCell; /* Pointer to current cell in pPage */
  54044. /* pPage->nCell must be greater than zero. If this is the root-page
  54045. ** the cursor would have been INVALID above and this for(;;) loop
  54046. ** not run. If this is not the root-page, then the moveToChild() routine
  54047. ** would have already detected db corruption. Similarly, pPage must
  54048. ** be the right kind (index or table) of b-tree page. Otherwise
  54049. ** a moveToChild() or moveToRoot() call would have detected corruption. */
  54050. assert( pPage->nCell>0 );
  54051. assert( pPage->intKey==(pIdxKey==0) );
  54052. lwr = 0;
  54053. upr = pPage->nCell-1;
  54054. assert( biasRight==0 || biasRight==1 );
  54055. idx = upr>>(1-biasRight); /* idx = biasRight ? upr : (lwr+upr)/2; */
  54056. pCur->aiIdx[pCur->iPage] = (u16)idx;
  54057. if( xRecordCompare==0 ){
  54058. for(;;){
  54059. i64 nCellKey;
  54060. pCell = findCell(pPage, idx) + pPage->childPtrSize;
  54061. if( pPage->intKeyLeaf ){
  54062. while( 0x80 <= *(pCell++) ){
  54063. if( pCell>=pPage->aDataEnd ) return SQLITE_CORRUPT_BKPT;
  54064. }
  54065. }
  54066. getVarint(pCell, (u64*)&nCellKey);
  54067. if( nCellKey<intKey ){
  54068. lwr = idx+1;
  54069. if( lwr>upr ){ c = -1; break; }
  54070. }else if( nCellKey>intKey ){
  54071. upr = idx-1;
  54072. if( lwr>upr ){ c = +1; break; }
  54073. }else{
  54074. assert( nCellKey==intKey );
  54075. pCur->curFlags |= BTCF_ValidNKey;
  54076. pCur->info.nKey = nCellKey;
  54077. pCur->aiIdx[pCur->iPage] = (u16)idx;
  54078. if( !pPage->leaf ){
  54079. lwr = idx;
  54080. goto moveto_next_layer;
  54081. }else{
  54082. *pRes = 0;
  54083. rc = SQLITE_OK;
  54084. goto moveto_finish;
  54085. }
  54086. }
  54087. assert( lwr+upr>=0 );
  54088. idx = (lwr+upr)>>1; /* idx = (lwr+upr)/2; */
  54089. }
  54090. }else{
  54091. for(;;){
  54092. int nCell;
  54093. pCell = findCell(pPage, idx) + pPage->childPtrSize;
  54094. /* The maximum supported page-size is 65536 bytes. This means that
  54095. ** the maximum number of record bytes stored on an index B-Tree
  54096. ** page is less than 16384 bytes and may be stored as a 2-byte
  54097. ** varint. This information is used to attempt to avoid parsing
  54098. ** the entire cell by checking for the cases where the record is
  54099. ** stored entirely within the b-tree page by inspecting the first
  54100. ** 2 bytes of the cell.
  54101. */
  54102. nCell = pCell[0];
  54103. if( nCell<=pPage->max1bytePayload ){
  54104. /* This branch runs if the record-size field of the cell is a
  54105. ** single byte varint and the record fits entirely on the main
  54106. ** b-tree page. */
  54107. testcase( pCell+nCell+1==pPage->aDataEnd );
  54108. c = xRecordCompare(nCell, (void*)&pCell[1], pIdxKey);
  54109. }else if( !(pCell[1] & 0x80)
  54110. && (nCell = ((nCell&0x7f)<<7) + pCell[1])<=pPage->maxLocal
  54111. ){
  54112. /* The record-size field is a 2 byte varint and the record
  54113. ** fits entirely on the main b-tree page. */
  54114. testcase( pCell+nCell+2==pPage->aDataEnd );
  54115. c = xRecordCompare(nCell, (void*)&pCell[2], pIdxKey);
  54116. }else{
  54117. /* The record flows over onto one or more overflow pages. In
  54118. ** this case the whole cell needs to be parsed, a buffer allocated
  54119. ** and accessPayload() used to retrieve the record into the
  54120. ** buffer before VdbeRecordCompare() can be called. */
  54121. void *pCellKey;
  54122. u8 * const pCellBody = pCell - pPage->childPtrSize;
  54123. btreeParseCellPtr(pPage, pCellBody, &pCur->info);
  54124. nCell = (int)pCur->info.nKey;
  54125. pCellKey = sqlite3Malloc( nCell );
  54126. if( pCellKey==0 ){
  54127. rc = SQLITE_NOMEM;
  54128. goto moveto_finish;
  54129. }
  54130. pCur->aiIdx[pCur->iPage] = (u16)idx;
  54131. rc = accessPayload(pCur, 0, nCell, (unsigned char*)pCellKey, 2);
  54132. if( rc ){
  54133. sqlite3_free(pCellKey);
  54134. goto moveto_finish;
  54135. }
  54136. c = xRecordCompare(nCell, pCellKey, pIdxKey);
  54137. sqlite3_free(pCellKey);
  54138. }
  54139. assert(
  54140. (pIdxKey->errCode!=SQLITE_CORRUPT || c==0)
  54141. && (pIdxKey->errCode!=SQLITE_NOMEM || pCur->pBtree->db->mallocFailed)
  54142. );
  54143. if( c<0 ){
  54144. lwr = idx+1;
  54145. }else if( c>0 ){
  54146. upr = idx-1;
  54147. }else{
  54148. assert( c==0 );
  54149. *pRes = 0;
  54150. rc = SQLITE_OK;
  54151. pCur->aiIdx[pCur->iPage] = (u16)idx;
  54152. if( pIdxKey->errCode ) rc = SQLITE_CORRUPT;
  54153. goto moveto_finish;
  54154. }
  54155. if( lwr>upr ) break;
  54156. assert( lwr+upr>=0 );
  54157. idx = (lwr+upr)>>1; /* idx = (lwr+upr)/2 */
  54158. }
  54159. }
  54160. assert( lwr==upr+1 || (pPage->intKey && !pPage->leaf) );
  54161. assert( pPage->isInit );
  54162. if( pPage->leaf ){
  54163. assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
  54164. pCur->aiIdx[pCur->iPage] = (u16)idx;
  54165. *pRes = c;
  54166. rc = SQLITE_OK;
  54167. goto moveto_finish;
  54168. }
  54169. moveto_next_layer:
  54170. if( lwr>=pPage->nCell ){
  54171. chldPg = get4byte(&pPage->aData[pPage->hdrOffset+8]);
  54172. }else{
  54173. chldPg = get4byte(findCell(pPage, lwr));
  54174. }
  54175. pCur->aiIdx[pCur->iPage] = (u16)lwr;
  54176. rc = moveToChild(pCur, chldPg);
  54177. if( rc ) break;
  54178. }
  54179. moveto_finish:
  54180. pCur->info.nSize = 0;
  54181. pCur->curFlags &= ~(BTCF_ValidNKey|BTCF_ValidOvfl);
  54182. return rc;
  54183. }
  54184. /*
  54185. ** Return TRUE if the cursor is not pointing at an entry of the table.
  54186. **
  54187. ** TRUE will be returned after a call to sqlite3BtreeNext() moves
  54188. ** past the last entry in the table or sqlite3BtreePrev() moves past
  54189. ** the first entry. TRUE is also returned if the table is empty.
  54190. */
  54191. SQLITE_PRIVATE int sqlite3BtreeEof(BtCursor *pCur){
  54192. /* TODO: What if the cursor is in CURSOR_REQUIRESEEK but all table entries
  54193. ** have been deleted? This API will need to change to return an error code
  54194. ** as well as the boolean result value.
  54195. */
  54196. return (CURSOR_VALID!=pCur->eState);
  54197. }
  54198. /*
  54199. ** Advance the cursor to the next entry in the database. If
  54200. ** successful then set *pRes=0. If the cursor
  54201. ** was already pointing to the last entry in the database before
  54202. ** this routine was called, then set *pRes=1.
  54203. **
  54204. ** The main entry point is sqlite3BtreeNext(). That routine is optimized
  54205. ** for the common case of merely incrementing the cell counter BtCursor.aiIdx
  54206. ** to the next cell on the current page. The (slower) btreeNext() helper
  54207. ** routine is called when it is necessary to move to a different page or
  54208. ** to restore the cursor.
  54209. **
  54210. ** The calling function will set *pRes to 0 or 1. The initial *pRes value
  54211. ** will be 1 if the cursor being stepped corresponds to an SQL index and
  54212. ** if this routine could have been skipped if that SQL index had been
  54213. ** a unique index. Otherwise the caller will have set *pRes to zero.
  54214. ** Zero is the common case. The btree implementation is free to use the
  54215. ** initial *pRes value as a hint to improve performance, but the current
  54216. ** SQLite btree implementation does not. (Note that the comdb2 btree
  54217. ** implementation does use this hint, however.)
  54218. */
  54219. static SQLITE_NOINLINE int btreeNext(BtCursor *pCur, int *pRes){
  54220. int rc;
  54221. int idx;
  54222. MemPage *pPage;
  54223. assert( cursorHoldsMutex(pCur) );
  54224. assert( pCur->skipNext==0 || pCur->eState!=CURSOR_VALID );
  54225. assert( *pRes==0 );
  54226. if( pCur->eState!=CURSOR_VALID ){
  54227. assert( (pCur->curFlags & BTCF_ValidOvfl)==0 );
  54228. rc = restoreCursorPosition(pCur);
  54229. if( rc!=SQLITE_OK ){
  54230. return rc;
  54231. }
  54232. if( CURSOR_INVALID==pCur->eState ){
  54233. *pRes = 1;
  54234. return SQLITE_OK;
  54235. }
  54236. if( pCur->skipNext ){
  54237. assert( pCur->eState==CURSOR_VALID || pCur->eState==CURSOR_SKIPNEXT );
  54238. pCur->eState = CURSOR_VALID;
  54239. if( pCur->skipNext>0 ){
  54240. pCur->skipNext = 0;
  54241. return SQLITE_OK;
  54242. }
  54243. pCur->skipNext = 0;
  54244. }
  54245. }
  54246. pPage = pCur->apPage[pCur->iPage];
  54247. idx = ++pCur->aiIdx[pCur->iPage];
  54248. assert( pPage->isInit );
  54249. /* If the database file is corrupt, it is possible for the value of idx
  54250. ** to be invalid here. This can only occur if a second cursor modifies
  54251. ** the page while cursor pCur is holding a reference to it. Which can
  54252. ** only happen if the database is corrupt in such a way as to link the
  54253. ** page into more than one b-tree structure. */
  54254. testcase( idx>pPage->nCell );
  54255. if( idx>=pPage->nCell ){
  54256. if( !pPage->leaf ){
  54257. rc = moveToChild(pCur, get4byte(&pPage->aData[pPage->hdrOffset+8]));
  54258. if( rc ) return rc;
  54259. return moveToLeftmost(pCur);
  54260. }
  54261. do{
  54262. if( pCur->iPage==0 ){
  54263. *pRes = 1;
  54264. pCur->eState = CURSOR_INVALID;
  54265. return SQLITE_OK;
  54266. }
  54267. moveToParent(pCur);
  54268. pPage = pCur->apPage[pCur->iPage];
  54269. }while( pCur->aiIdx[pCur->iPage]>=pPage->nCell );
  54270. if( pPage->intKey ){
  54271. return sqlite3BtreeNext(pCur, pRes);
  54272. }else{
  54273. return SQLITE_OK;
  54274. }
  54275. }
  54276. if( pPage->leaf ){
  54277. return SQLITE_OK;
  54278. }else{
  54279. return moveToLeftmost(pCur);
  54280. }
  54281. }
  54282. SQLITE_PRIVATE int sqlite3BtreeNext(BtCursor *pCur, int *pRes){
  54283. MemPage *pPage;
  54284. assert( cursorHoldsMutex(pCur) );
  54285. assert( pRes!=0 );
  54286. assert( *pRes==0 || *pRes==1 );
  54287. assert( pCur->skipNext==0 || pCur->eState!=CURSOR_VALID );
  54288. pCur->info.nSize = 0;
  54289. pCur->curFlags &= ~(BTCF_ValidNKey|BTCF_ValidOvfl);
  54290. *pRes = 0;
  54291. if( pCur->eState!=CURSOR_VALID ) return btreeNext(pCur, pRes);
  54292. pPage = pCur->apPage[pCur->iPage];
  54293. if( (++pCur->aiIdx[pCur->iPage])>=pPage->nCell ){
  54294. pCur->aiIdx[pCur->iPage]--;
  54295. return btreeNext(pCur, pRes);
  54296. }
  54297. if( pPage->leaf ){
  54298. return SQLITE_OK;
  54299. }else{
  54300. return moveToLeftmost(pCur);
  54301. }
  54302. }
  54303. /*
  54304. ** Step the cursor to the back to the previous entry in the database. If
  54305. ** successful then set *pRes=0. If the cursor
  54306. ** was already pointing to the first entry in the database before
  54307. ** this routine was called, then set *pRes=1.
  54308. **
  54309. ** The main entry point is sqlite3BtreePrevious(). That routine is optimized
  54310. ** for the common case of merely decrementing the cell counter BtCursor.aiIdx
  54311. ** to the previous cell on the current page. The (slower) btreePrevious()
  54312. ** helper routine is called when it is necessary to move to a different page
  54313. ** or to restore the cursor.
  54314. **
  54315. ** The calling function will set *pRes to 0 or 1. The initial *pRes value
  54316. ** will be 1 if the cursor being stepped corresponds to an SQL index and
  54317. ** if this routine could have been skipped if that SQL index had been
  54318. ** a unique index. Otherwise the caller will have set *pRes to zero.
  54319. ** Zero is the common case. The btree implementation is free to use the
  54320. ** initial *pRes value as a hint to improve performance, but the current
  54321. ** SQLite btree implementation does not. (Note that the comdb2 btree
  54322. ** implementation does use this hint, however.)
  54323. */
  54324. static SQLITE_NOINLINE int btreePrevious(BtCursor *pCur, int *pRes){
  54325. int rc;
  54326. MemPage *pPage;
  54327. assert( cursorHoldsMutex(pCur) );
  54328. assert( pRes!=0 );
  54329. assert( *pRes==0 );
  54330. assert( pCur->skipNext==0 || pCur->eState!=CURSOR_VALID );
  54331. assert( (pCur->curFlags & (BTCF_AtLast|BTCF_ValidOvfl|BTCF_ValidNKey))==0 );
  54332. assert( pCur->info.nSize==0 );
  54333. if( pCur->eState!=CURSOR_VALID ){
  54334. rc = restoreCursorPosition(pCur);
  54335. if( rc!=SQLITE_OK ){
  54336. return rc;
  54337. }
  54338. if( CURSOR_INVALID==pCur->eState ){
  54339. *pRes = 1;
  54340. return SQLITE_OK;
  54341. }
  54342. if( pCur->skipNext ){
  54343. assert( pCur->eState==CURSOR_VALID || pCur->eState==CURSOR_SKIPNEXT );
  54344. pCur->eState = CURSOR_VALID;
  54345. if( pCur->skipNext<0 ){
  54346. pCur->skipNext = 0;
  54347. return SQLITE_OK;
  54348. }
  54349. pCur->skipNext = 0;
  54350. }
  54351. }
  54352. pPage = pCur->apPage[pCur->iPage];
  54353. assert( pPage->isInit );
  54354. if( !pPage->leaf ){
  54355. int idx = pCur->aiIdx[pCur->iPage];
  54356. rc = moveToChild(pCur, get4byte(findCell(pPage, idx)));
  54357. if( rc ) return rc;
  54358. rc = moveToRightmost(pCur);
  54359. }else{
  54360. while( pCur->aiIdx[pCur->iPage]==0 ){
  54361. if( pCur->iPage==0 ){
  54362. pCur->eState = CURSOR_INVALID;
  54363. *pRes = 1;
  54364. return SQLITE_OK;
  54365. }
  54366. moveToParent(pCur);
  54367. }
  54368. assert( pCur->info.nSize==0 );
  54369. assert( (pCur->curFlags & (BTCF_ValidNKey|BTCF_ValidOvfl))==0 );
  54370. pCur->aiIdx[pCur->iPage]--;
  54371. pPage = pCur->apPage[pCur->iPage];
  54372. if( pPage->intKey && !pPage->leaf ){
  54373. rc = sqlite3BtreePrevious(pCur, pRes);
  54374. }else{
  54375. rc = SQLITE_OK;
  54376. }
  54377. }
  54378. return rc;
  54379. }
  54380. SQLITE_PRIVATE int sqlite3BtreePrevious(BtCursor *pCur, int *pRes){
  54381. assert( cursorHoldsMutex(pCur) );
  54382. assert( pRes!=0 );
  54383. assert( *pRes==0 || *pRes==1 );
  54384. assert( pCur->skipNext==0 || pCur->eState!=CURSOR_VALID );
  54385. *pRes = 0;
  54386. pCur->curFlags &= ~(BTCF_AtLast|BTCF_ValidOvfl|BTCF_ValidNKey);
  54387. pCur->info.nSize = 0;
  54388. if( pCur->eState!=CURSOR_VALID
  54389. || pCur->aiIdx[pCur->iPage]==0
  54390. || pCur->apPage[pCur->iPage]->leaf==0
  54391. ){
  54392. return btreePrevious(pCur, pRes);
  54393. }
  54394. pCur->aiIdx[pCur->iPage]--;
  54395. return SQLITE_OK;
  54396. }
  54397. /*
  54398. ** Allocate a new page from the database file.
  54399. **
  54400. ** The new page is marked as dirty. (In other words, sqlite3PagerWrite()
  54401. ** has already been called on the new page.) The new page has also
  54402. ** been referenced and the calling routine is responsible for calling
  54403. ** sqlite3PagerUnref() on the new page when it is done.
  54404. **
  54405. ** SQLITE_OK is returned on success. Any other return value indicates
  54406. ** an error. *ppPage and *pPgno are undefined in the event of an error.
  54407. ** Do not invoke sqlite3PagerUnref() on *ppPage if an error is returned.
  54408. **
  54409. ** If the "nearby" parameter is not 0, then an effort is made to
  54410. ** locate a page close to the page number "nearby". This can be used in an
  54411. ** attempt to keep related pages close to each other in the database file,
  54412. ** which in turn can make database access faster.
  54413. **
  54414. ** If the eMode parameter is BTALLOC_EXACT and the nearby page exists
  54415. ** anywhere on the free-list, then it is guaranteed to be returned. If
  54416. ** eMode is BTALLOC_LT then the page returned will be less than or equal
  54417. ** to nearby if any such page exists. If eMode is BTALLOC_ANY then there
  54418. ** are no restrictions on which page is returned.
  54419. */
  54420. static int allocateBtreePage(
  54421. BtShared *pBt, /* The btree */
  54422. MemPage **ppPage, /* Store pointer to the allocated page here */
  54423. Pgno *pPgno, /* Store the page number here */
  54424. Pgno nearby, /* Search for a page near this one */
  54425. u8 eMode /* BTALLOC_EXACT, BTALLOC_LT, or BTALLOC_ANY */
  54426. ){
  54427. MemPage *pPage1;
  54428. int rc;
  54429. u32 n; /* Number of pages on the freelist */
  54430. u32 k; /* Number of leaves on the trunk of the freelist */
  54431. MemPage *pTrunk = 0;
  54432. MemPage *pPrevTrunk = 0;
  54433. Pgno mxPage; /* Total size of the database file */
  54434. assert( sqlite3_mutex_held(pBt->mutex) );
  54435. assert( eMode==BTALLOC_ANY || (nearby>0 && IfNotOmitAV(pBt->autoVacuum)) );
  54436. pPage1 = pBt->pPage1;
  54437. mxPage = btreePagecount(pBt);
  54438. /* EVIDENCE-OF: R-05119-02637 The 4-byte big-endian integer at offset 36
  54439. ** stores stores the total number of pages on the freelist. */
  54440. n = get4byte(&pPage1->aData[36]);
  54441. testcase( n==mxPage-1 );
  54442. if( n>=mxPage ){
  54443. return SQLITE_CORRUPT_BKPT;
  54444. }
  54445. if( n>0 ){
  54446. /* There are pages on the freelist. Reuse one of those pages. */
  54447. Pgno iTrunk;
  54448. u8 searchList = 0; /* If the free-list must be searched for 'nearby' */
  54449. /* If eMode==BTALLOC_EXACT and a query of the pointer-map
  54450. ** shows that the page 'nearby' is somewhere on the free-list, then
  54451. ** the entire-list will be searched for that page.
  54452. */
  54453. #ifndef SQLITE_OMIT_AUTOVACUUM
  54454. if( eMode==BTALLOC_EXACT ){
  54455. if( nearby<=mxPage ){
  54456. u8 eType;
  54457. assert( nearby>0 );
  54458. assert( pBt->autoVacuum );
  54459. rc = ptrmapGet(pBt, nearby, &eType, 0);
  54460. if( rc ) return rc;
  54461. if( eType==PTRMAP_FREEPAGE ){
  54462. searchList = 1;
  54463. }
  54464. }
  54465. }else if( eMode==BTALLOC_LE ){
  54466. searchList = 1;
  54467. }
  54468. #endif
  54469. /* Decrement the free-list count by 1. Set iTrunk to the index of the
  54470. ** first free-list trunk page. iPrevTrunk is initially 1.
  54471. */
  54472. rc = sqlite3PagerWrite(pPage1->pDbPage);
  54473. if( rc ) return rc;
  54474. put4byte(&pPage1->aData[36], n-1);
  54475. /* The code within this loop is run only once if the 'searchList' variable
  54476. ** is not true. Otherwise, it runs once for each trunk-page on the
  54477. ** free-list until the page 'nearby' is located (eMode==BTALLOC_EXACT)
  54478. ** or until a page less than 'nearby' is located (eMode==BTALLOC_LT)
  54479. */
  54480. do {
  54481. pPrevTrunk = pTrunk;
  54482. if( pPrevTrunk ){
  54483. /* EVIDENCE-OF: R-01506-11053 The first integer on a freelist trunk page
  54484. ** is the page number of the next freelist trunk page in the list or
  54485. ** zero if this is the last freelist trunk page. */
  54486. iTrunk = get4byte(&pPrevTrunk->aData[0]);
  54487. }else{
  54488. /* EVIDENCE-OF: R-59841-13798 The 4-byte big-endian integer at offset 32
  54489. ** stores the page number of the first page of the freelist, or zero if
  54490. ** the freelist is empty. */
  54491. iTrunk = get4byte(&pPage1->aData[32]);
  54492. }
  54493. testcase( iTrunk==mxPage );
  54494. if( iTrunk>mxPage ){
  54495. rc = SQLITE_CORRUPT_BKPT;
  54496. }else{
  54497. rc = btreeGetPage(pBt, iTrunk, &pTrunk, 0);
  54498. }
  54499. if( rc ){
  54500. pTrunk = 0;
  54501. goto end_allocate_page;
  54502. }
  54503. assert( pTrunk!=0 );
  54504. assert( pTrunk->aData!=0 );
  54505. /* EVIDENCE-OF: R-13523-04394 The second integer on a freelist trunk page
  54506. ** is the number of leaf page pointers to follow. */
  54507. k = get4byte(&pTrunk->aData[4]);
  54508. if( k==0 && !searchList ){
  54509. /* The trunk has no leaves and the list is not being searched.
  54510. ** So extract the trunk page itself and use it as the newly
  54511. ** allocated page */
  54512. assert( pPrevTrunk==0 );
  54513. rc = sqlite3PagerWrite(pTrunk->pDbPage);
  54514. if( rc ){
  54515. goto end_allocate_page;
  54516. }
  54517. *pPgno = iTrunk;
  54518. memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4);
  54519. *ppPage = pTrunk;
  54520. pTrunk = 0;
  54521. TRACE(("ALLOCATE: %d trunk - %d free pages left\n", *pPgno, n-1));
  54522. }else if( k>(u32)(pBt->usableSize/4 - 2) ){
  54523. /* Value of k is out of range. Database corruption */
  54524. rc = SQLITE_CORRUPT_BKPT;
  54525. goto end_allocate_page;
  54526. #ifndef SQLITE_OMIT_AUTOVACUUM
  54527. }else if( searchList
  54528. && (nearby==iTrunk || (iTrunk<nearby && eMode==BTALLOC_LE))
  54529. ){
  54530. /* The list is being searched and this trunk page is the page
  54531. ** to allocate, regardless of whether it has leaves.
  54532. */
  54533. *pPgno = iTrunk;
  54534. *ppPage = pTrunk;
  54535. searchList = 0;
  54536. rc = sqlite3PagerWrite(pTrunk->pDbPage);
  54537. if( rc ){
  54538. goto end_allocate_page;
  54539. }
  54540. if( k==0 ){
  54541. if( !pPrevTrunk ){
  54542. memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4);
  54543. }else{
  54544. rc = sqlite3PagerWrite(pPrevTrunk->pDbPage);
  54545. if( rc!=SQLITE_OK ){
  54546. goto end_allocate_page;
  54547. }
  54548. memcpy(&pPrevTrunk->aData[0], &pTrunk->aData[0], 4);
  54549. }
  54550. }else{
  54551. /* The trunk page is required by the caller but it contains
  54552. ** pointers to free-list leaves. The first leaf becomes a trunk
  54553. ** page in this case.
  54554. */
  54555. MemPage *pNewTrunk;
  54556. Pgno iNewTrunk = get4byte(&pTrunk->aData[8]);
  54557. if( iNewTrunk>mxPage ){
  54558. rc = SQLITE_CORRUPT_BKPT;
  54559. goto end_allocate_page;
  54560. }
  54561. testcase( iNewTrunk==mxPage );
  54562. rc = btreeGetPage(pBt, iNewTrunk, &pNewTrunk, 0);
  54563. if( rc!=SQLITE_OK ){
  54564. goto end_allocate_page;
  54565. }
  54566. rc = sqlite3PagerWrite(pNewTrunk->pDbPage);
  54567. if( rc!=SQLITE_OK ){
  54568. releasePage(pNewTrunk);
  54569. goto end_allocate_page;
  54570. }
  54571. memcpy(&pNewTrunk->aData[0], &pTrunk->aData[0], 4);
  54572. put4byte(&pNewTrunk->aData[4], k-1);
  54573. memcpy(&pNewTrunk->aData[8], &pTrunk->aData[12], (k-1)*4);
  54574. releasePage(pNewTrunk);
  54575. if( !pPrevTrunk ){
  54576. assert( sqlite3PagerIswriteable(pPage1->pDbPage) );
  54577. put4byte(&pPage1->aData[32], iNewTrunk);
  54578. }else{
  54579. rc = sqlite3PagerWrite(pPrevTrunk->pDbPage);
  54580. if( rc ){
  54581. goto end_allocate_page;
  54582. }
  54583. put4byte(&pPrevTrunk->aData[0], iNewTrunk);
  54584. }
  54585. }
  54586. pTrunk = 0;
  54587. TRACE(("ALLOCATE: %d trunk - %d free pages left\n", *pPgno, n-1));
  54588. #endif
  54589. }else if( k>0 ){
  54590. /* Extract a leaf from the trunk */
  54591. u32 closest;
  54592. Pgno iPage;
  54593. unsigned char *aData = pTrunk->aData;
  54594. if( nearby>0 ){
  54595. u32 i;
  54596. closest = 0;
  54597. if( eMode==BTALLOC_LE ){
  54598. for(i=0; i<k; i++){
  54599. iPage = get4byte(&aData[8+i*4]);
  54600. if( iPage<=nearby ){
  54601. closest = i;
  54602. break;
  54603. }
  54604. }
  54605. }else{
  54606. int dist;
  54607. dist = sqlite3AbsInt32(get4byte(&aData[8]) - nearby);
  54608. for(i=1; i<k; i++){
  54609. int d2 = sqlite3AbsInt32(get4byte(&aData[8+i*4]) - nearby);
  54610. if( d2<dist ){
  54611. closest = i;
  54612. dist = d2;
  54613. }
  54614. }
  54615. }
  54616. }else{
  54617. closest = 0;
  54618. }
  54619. iPage = get4byte(&aData[8+closest*4]);
  54620. testcase( iPage==mxPage );
  54621. if( iPage>mxPage ){
  54622. rc = SQLITE_CORRUPT_BKPT;
  54623. goto end_allocate_page;
  54624. }
  54625. testcase( iPage==mxPage );
  54626. if( !searchList
  54627. || (iPage==nearby || (iPage<nearby && eMode==BTALLOC_LE))
  54628. ){
  54629. int noContent;
  54630. *pPgno = iPage;
  54631. TRACE(("ALLOCATE: %d was leaf %d of %d on trunk %d"
  54632. ": %d more free pages\n",
  54633. *pPgno, closest+1, k, pTrunk->pgno, n-1));
  54634. rc = sqlite3PagerWrite(pTrunk->pDbPage);
  54635. if( rc ) goto end_allocate_page;
  54636. if( closest<k-1 ){
  54637. memcpy(&aData[8+closest*4], &aData[4+k*4], 4);
  54638. }
  54639. put4byte(&aData[4], k-1);
  54640. noContent = !btreeGetHasContent(pBt, *pPgno)? PAGER_GET_NOCONTENT : 0;
  54641. rc = btreeGetPage(pBt, *pPgno, ppPage, noContent);
  54642. if( rc==SQLITE_OK ){
  54643. rc = sqlite3PagerWrite((*ppPage)->pDbPage);
  54644. if( rc!=SQLITE_OK ){
  54645. releasePage(*ppPage);
  54646. }
  54647. }
  54648. searchList = 0;
  54649. }
  54650. }
  54651. releasePage(pPrevTrunk);
  54652. pPrevTrunk = 0;
  54653. }while( searchList );
  54654. }else{
  54655. /* There are no pages on the freelist, so append a new page to the
  54656. ** database image.
  54657. **
  54658. ** Normally, new pages allocated by this block can be requested from the
  54659. ** pager layer with the 'no-content' flag set. This prevents the pager
  54660. ** from trying to read the pages content from disk. However, if the
  54661. ** current transaction has already run one or more incremental-vacuum
  54662. ** steps, then the page we are about to allocate may contain content
  54663. ** that is required in the event of a rollback. In this case, do
  54664. ** not set the no-content flag. This causes the pager to load and journal
  54665. ** the current page content before overwriting it.
  54666. **
  54667. ** Note that the pager will not actually attempt to load or journal
  54668. ** content for any page that really does lie past the end of the database
  54669. ** file on disk. So the effects of disabling the no-content optimization
  54670. ** here are confined to those pages that lie between the end of the
  54671. ** database image and the end of the database file.
  54672. */
  54673. int bNoContent = (0==IfNotOmitAV(pBt->bDoTruncate))? PAGER_GET_NOCONTENT:0;
  54674. rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
  54675. if( rc ) return rc;
  54676. pBt->nPage++;
  54677. if( pBt->nPage==PENDING_BYTE_PAGE(pBt) ) pBt->nPage++;
  54678. #ifndef SQLITE_OMIT_AUTOVACUUM
  54679. if( pBt->autoVacuum && PTRMAP_ISPAGE(pBt, pBt->nPage) ){
  54680. /* If *pPgno refers to a pointer-map page, allocate two new pages
  54681. ** at the end of the file instead of one. The first allocated page
  54682. ** becomes a new pointer-map page, the second is used by the caller.
  54683. */
  54684. MemPage *pPg = 0;
  54685. TRACE(("ALLOCATE: %d from end of file (pointer-map page)\n", pBt->nPage));
  54686. assert( pBt->nPage!=PENDING_BYTE_PAGE(pBt) );
  54687. rc = btreeGetPage(pBt, pBt->nPage, &pPg, bNoContent);
  54688. if( rc==SQLITE_OK ){
  54689. rc = sqlite3PagerWrite(pPg->pDbPage);
  54690. releasePage(pPg);
  54691. }
  54692. if( rc ) return rc;
  54693. pBt->nPage++;
  54694. if( pBt->nPage==PENDING_BYTE_PAGE(pBt) ){ pBt->nPage++; }
  54695. }
  54696. #endif
  54697. put4byte(28 + (u8*)pBt->pPage1->aData, pBt->nPage);
  54698. *pPgno = pBt->nPage;
  54699. assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
  54700. rc = btreeGetPage(pBt, *pPgno, ppPage, bNoContent);
  54701. if( rc ) return rc;
  54702. rc = sqlite3PagerWrite((*ppPage)->pDbPage);
  54703. if( rc!=SQLITE_OK ){
  54704. releasePage(*ppPage);
  54705. }
  54706. TRACE(("ALLOCATE: %d from end of file\n", *pPgno));
  54707. }
  54708. assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
  54709. end_allocate_page:
  54710. releasePage(pTrunk);
  54711. releasePage(pPrevTrunk);
  54712. if( rc==SQLITE_OK ){
  54713. if( sqlite3PagerPageRefcount((*ppPage)->pDbPage)>1 ){
  54714. releasePage(*ppPage);
  54715. *ppPage = 0;
  54716. return SQLITE_CORRUPT_BKPT;
  54717. }
  54718. (*ppPage)->isInit = 0;
  54719. }else{
  54720. *ppPage = 0;
  54721. }
  54722. assert( rc!=SQLITE_OK || sqlite3PagerIswriteable((*ppPage)->pDbPage) );
  54723. return rc;
  54724. }
  54725. /*
  54726. ** This function is used to add page iPage to the database file free-list.
  54727. ** It is assumed that the page is not already a part of the free-list.
  54728. **
  54729. ** The value passed as the second argument to this function is optional.
  54730. ** If the caller happens to have a pointer to the MemPage object
  54731. ** corresponding to page iPage handy, it may pass it as the second value.
  54732. ** Otherwise, it may pass NULL.
  54733. **
  54734. ** If a pointer to a MemPage object is passed as the second argument,
  54735. ** its reference count is not altered by this function.
  54736. */
  54737. static int freePage2(BtShared *pBt, MemPage *pMemPage, Pgno iPage){
  54738. MemPage *pTrunk = 0; /* Free-list trunk page */
  54739. Pgno iTrunk = 0; /* Page number of free-list trunk page */
  54740. MemPage *pPage1 = pBt->pPage1; /* Local reference to page 1 */
  54741. MemPage *pPage; /* Page being freed. May be NULL. */
  54742. int rc; /* Return Code */
  54743. int nFree; /* Initial number of pages on free-list */
  54744. assert( sqlite3_mutex_held(pBt->mutex) );
  54745. assert( iPage>1 );
  54746. assert( !pMemPage || pMemPage->pgno==iPage );
  54747. if( pMemPage ){
  54748. pPage = pMemPage;
  54749. sqlite3PagerRef(pPage->pDbPage);
  54750. }else{
  54751. pPage = btreePageLookup(pBt, iPage);
  54752. }
  54753. /* Increment the free page count on pPage1 */
  54754. rc = sqlite3PagerWrite(pPage1->pDbPage);
  54755. if( rc ) goto freepage_out;
  54756. nFree = get4byte(&pPage1->aData[36]);
  54757. put4byte(&pPage1->aData[36], nFree+1);
  54758. if( pBt->btsFlags & BTS_SECURE_DELETE ){
  54759. /* If the secure_delete option is enabled, then
  54760. ** always fully overwrite deleted information with zeros.
  54761. */
  54762. if( (!pPage && ((rc = btreeGetPage(pBt, iPage, &pPage, 0))!=0) )
  54763. || ((rc = sqlite3PagerWrite(pPage->pDbPage))!=0)
  54764. ){
  54765. goto freepage_out;
  54766. }
  54767. memset(pPage->aData, 0, pPage->pBt->pageSize);
  54768. }
  54769. /* If the database supports auto-vacuum, write an entry in the pointer-map
  54770. ** to indicate that the page is free.
  54771. */
  54772. if( ISAUTOVACUUM ){
  54773. ptrmapPut(pBt, iPage, PTRMAP_FREEPAGE, 0, &rc);
  54774. if( rc ) goto freepage_out;
  54775. }
  54776. /* Now manipulate the actual database free-list structure. There are two
  54777. ** possibilities. If the free-list is currently empty, or if the first
  54778. ** trunk page in the free-list is full, then this page will become a
  54779. ** new free-list trunk page. Otherwise, it will become a leaf of the
  54780. ** first trunk page in the current free-list. This block tests if it
  54781. ** is possible to add the page as a new free-list leaf.
  54782. */
  54783. if( nFree!=0 ){
  54784. u32 nLeaf; /* Initial number of leaf cells on trunk page */
  54785. iTrunk = get4byte(&pPage1->aData[32]);
  54786. rc = btreeGetPage(pBt, iTrunk, &pTrunk, 0);
  54787. if( rc!=SQLITE_OK ){
  54788. goto freepage_out;
  54789. }
  54790. nLeaf = get4byte(&pTrunk->aData[4]);
  54791. assert( pBt->usableSize>32 );
  54792. if( nLeaf > (u32)pBt->usableSize/4 - 2 ){
  54793. rc = SQLITE_CORRUPT_BKPT;
  54794. goto freepage_out;
  54795. }
  54796. if( nLeaf < (u32)pBt->usableSize/4 - 8 ){
  54797. /* In this case there is room on the trunk page to insert the page
  54798. ** being freed as a new leaf.
  54799. **
  54800. ** Note that the trunk page is not really full until it contains
  54801. ** usableSize/4 - 2 entries, not usableSize/4 - 8 entries as we have
  54802. ** coded. But due to a coding error in versions of SQLite prior to
  54803. ** 3.6.0, databases with freelist trunk pages holding more than
  54804. ** usableSize/4 - 8 entries will be reported as corrupt. In order
  54805. ** to maintain backwards compatibility with older versions of SQLite,
  54806. ** we will continue to restrict the number of entries to usableSize/4 - 8
  54807. ** for now. At some point in the future (once everyone has upgraded
  54808. ** to 3.6.0 or later) we should consider fixing the conditional above
  54809. ** to read "usableSize/4-2" instead of "usableSize/4-8".
  54810. **
  54811. ** EVIDENCE-OF: R-19920-11576 However, newer versions of SQLite still
  54812. ** avoid using the last six entries in the freelist trunk page array in
  54813. ** order that database files created by newer versions of SQLite can be
  54814. ** read by older versions of SQLite.
  54815. */
  54816. rc = sqlite3PagerWrite(pTrunk->pDbPage);
  54817. if( rc==SQLITE_OK ){
  54818. put4byte(&pTrunk->aData[4], nLeaf+1);
  54819. put4byte(&pTrunk->aData[8+nLeaf*4], iPage);
  54820. if( pPage && (pBt->btsFlags & BTS_SECURE_DELETE)==0 ){
  54821. sqlite3PagerDontWrite(pPage->pDbPage);
  54822. }
  54823. rc = btreeSetHasContent(pBt, iPage);
  54824. }
  54825. TRACE(("FREE-PAGE: %d leaf on trunk page %d\n",pPage->pgno,pTrunk->pgno));
  54826. goto freepage_out;
  54827. }
  54828. }
  54829. /* If control flows to this point, then it was not possible to add the
  54830. ** the page being freed as a leaf page of the first trunk in the free-list.
  54831. ** Possibly because the free-list is empty, or possibly because the
  54832. ** first trunk in the free-list is full. Either way, the page being freed
  54833. ** will become the new first trunk page in the free-list.
  54834. */
  54835. if( pPage==0 && SQLITE_OK!=(rc = btreeGetPage(pBt, iPage, &pPage, 0)) ){
  54836. goto freepage_out;
  54837. }
  54838. rc = sqlite3PagerWrite(pPage->pDbPage);
  54839. if( rc!=SQLITE_OK ){
  54840. goto freepage_out;
  54841. }
  54842. put4byte(pPage->aData, iTrunk);
  54843. put4byte(&pPage->aData[4], 0);
  54844. put4byte(&pPage1->aData[32], iPage);
  54845. TRACE(("FREE-PAGE: %d new trunk page replacing %d\n", pPage->pgno, iTrunk));
  54846. freepage_out:
  54847. if( pPage ){
  54848. pPage->isInit = 0;
  54849. }
  54850. releasePage(pPage);
  54851. releasePage(pTrunk);
  54852. return rc;
  54853. }
  54854. static void freePage(MemPage *pPage, int *pRC){
  54855. if( (*pRC)==SQLITE_OK ){
  54856. *pRC = freePage2(pPage->pBt, pPage, pPage->pgno);
  54857. }
  54858. }
  54859. /*
  54860. ** Free any overflow pages associated with the given Cell. Write the
  54861. ** local Cell size (the number of bytes on the original page, omitting
  54862. ** overflow) into *pnSize.
  54863. */
  54864. static int clearCell(
  54865. MemPage *pPage, /* The page that contains the Cell */
  54866. unsigned char *pCell, /* First byte of the Cell */
  54867. u16 *pnSize /* Write the size of the Cell here */
  54868. ){
  54869. BtShared *pBt = pPage->pBt;
  54870. CellInfo info;
  54871. Pgno ovflPgno;
  54872. int rc;
  54873. int nOvfl;
  54874. u32 ovflPageSize;
  54875. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  54876. btreeParseCellPtr(pPage, pCell, &info);
  54877. *pnSize = info.nSize;
  54878. if( info.iOverflow==0 ){
  54879. return SQLITE_OK; /* No overflow pages. Return without doing anything */
  54880. }
  54881. if( pCell+info.iOverflow+3 > pPage->aData+pPage->maskPage ){
  54882. return SQLITE_CORRUPT_BKPT; /* Cell extends past end of page */
  54883. }
  54884. ovflPgno = get4byte(&pCell[info.iOverflow]);
  54885. assert( pBt->usableSize > 4 );
  54886. ovflPageSize = pBt->usableSize - 4;
  54887. nOvfl = (info.nPayload - info.nLocal + ovflPageSize - 1)/ovflPageSize;
  54888. assert( ovflPgno==0 || nOvfl>0 );
  54889. while( nOvfl-- ){
  54890. Pgno iNext = 0;
  54891. MemPage *pOvfl = 0;
  54892. if( ovflPgno<2 || ovflPgno>btreePagecount(pBt) ){
  54893. /* 0 is not a legal page number and page 1 cannot be an
  54894. ** overflow page. Therefore if ovflPgno<2 or past the end of the
  54895. ** file the database must be corrupt. */
  54896. return SQLITE_CORRUPT_BKPT;
  54897. }
  54898. if( nOvfl ){
  54899. rc = getOverflowPage(pBt, ovflPgno, &pOvfl, &iNext);
  54900. if( rc ) return rc;
  54901. }
  54902. if( ( pOvfl || ((pOvfl = btreePageLookup(pBt, ovflPgno))!=0) )
  54903. && sqlite3PagerPageRefcount(pOvfl->pDbPage)!=1
  54904. ){
  54905. /* There is no reason any cursor should have an outstanding reference
  54906. ** to an overflow page belonging to a cell that is being deleted/updated.
  54907. ** So if there exists more than one reference to this page, then it
  54908. ** must not really be an overflow page and the database must be corrupt.
  54909. ** It is helpful to detect this before calling freePage2(), as
  54910. ** freePage2() may zero the page contents if secure-delete mode is
  54911. ** enabled. If this 'overflow' page happens to be a page that the
  54912. ** caller is iterating through or using in some other way, this
  54913. ** can be problematic.
  54914. */
  54915. rc = SQLITE_CORRUPT_BKPT;
  54916. }else{
  54917. rc = freePage2(pBt, pOvfl, ovflPgno);
  54918. }
  54919. if( pOvfl ){
  54920. sqlite3PagerUnref(pOvfl->pDbPage);
  54921. }
  54922. if( rc ) return rc;
  54923. ovflPgno = iNext;
  54924. }
  54925. return SQLITE_OK;
  54926. }
  54927. /*
  54928. ** Create the byte sequence used to represent a cell on page pPage
  54929. ** and write that byte sequence into pCell[]. Overflow pages are
  54930. ** allocated and filled in as necessary. The calling procedure
  54931. ** is responsible for making sure sufficient space has been allocated
  54932. ** for pCell[].
  54933. **
  54934. ** Note that pCell does not necessary need to point to the pPage->aData
  54935. ** area. pCell might point to some temporary storage. The cell will
  54936. ** be constructed in this temporary area then copied into pPage->aData
  54937. ** later.
  54938. */
  54939. static int fillInCell(
  54940. MemPage *pPage, /* The page that contains the cell */
  54941. unsigned char *pCell, /* Complete text of the cell */
  54942. const void *pKey, i64 nKey, /* The key */
  54943. const void *pData,int nData, /* The data */
  54944. int nZero, /* Extra zero bytes to append to pData */
  54945. int *pnSize /* Write cell size here */
  54946. ){
  54947. int nPayload;
  54948. const u8 *pSrc;
  54949. int nSrc, n, rc;
  54950. int spaceLeft;
  54951. MemPage *pOvfl = 0;
  54952. MemPage *pToRelease = 0;
  54953. unsigned char *pPrior;
  54954. unsigned char *pPayload;
  54955. BtShared *pBt = pPage->pBt;
  54956. Pgno pgnoOvfl = 0;
  54957. int nHeader;
  54958. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  54959. /* pPage is not necessarily writeable since pCell might be auxiliary
  54960. ** buffer space that is separate from the pPage buffer area */
  54961. assert( pCell<pPage->aData || pCell>=&pPage->aData[pBt->pageSize]
  54962. || sqlite3PagerIswriteable(pPage->pDbPage) );
  54963. /* Fill in the header. */
  54964. nHeader = pPage->childPtrSize;
  54965. nPayload = nData + nZero;
  54966. if( pPage->intKeyLeaf ){
  54967. nHeader += putVarint32(&pCell[nHeader], nPayload);
  54968. }else{
  54969. assert( nData==0 );
  54970. assert( nZero==0 );
  54971. }
  54972. nHeader += putVarint(&pCell[nHeader], *(u64*)&nKey);
  54973. /* Fill in the payload size */
  54974. if( pPage->intKey ){
  54975. pSrc = pData;
  54976. nSrc = nData;
  54977. nData = 0;
  54978. }else{
  54979. if( NEVER(nKey>0x7fffffff || pKey==0) ){
  54980. return SQLITE_CORRUPT_BKPT;
  54981. }
  54982. nPayload = (int)nKey;
  54983. pSrc = pKey;
  54984. nSrc = (int)nKey;
  54985. }
  54986. if( nPayload<=pPage->maxLocal ){
  54987. n = nHeader + nPayload;
  54988. testcase( n==3 );
  54989. testcase( n==4 );
  54990. if( n<4 ) n = 4;
  54991. *pnSize = n;
  54992. spaceLeft = nPayload;
  54993. pPrior = pCell;
  54994. }else{
  54995. int mn = pPage->minLocal;
  54996. n = mn + (nPayload - mn) % (pPage->pBt->usableSize - 4);
  54997. testcase( n==pPage->maxLocal );
  54998. testcase( n==pPage->maxLocal+1 );
  54999. if( n > pPage->maxLocal ) n = mn;
  55000. spaceLeft = n;
  55001. *pnSize = n + nHeader + 4;
  55002. pPrior = &pCell[nHeader+n];
  55003. }
  55004. pPayload = &pCell[nHeader];
  55005. /* At this point variables should be set as follows:
  55006. **
  55007. ** nPayload Total payload size in bytes
  55008. ** pPayload Begin writing payload here
  55009. ** spaceLeft Space available at pPayload. If nPayload>spaceLeft,
  55010. ** that means content must spill into overflow pages.
  55011. ** *pnSize Size of the local cell (not counting overflow pages)
  55012. ** pPrior Where to write the pgno of the first overflow page
  55013. **
  55014. ** Use a call to btreeParseCellPtr() to verify that the values above
  55015. ** were computed correctly.
  55016. */
  55017. #if SQLITE_DEBUG
  55018. {
  55019. CellInfo info;
  55020. btreeParseCellPtr(pPage, pCell, &info);
  55021. assert( nHeader=(int)(info.pPayload - pCell) );
  55022. assert( info.nKey==nKey );
  55023. assert( *pnSize == info.nSize );
  55024. assert( spaceLeft == info.nLocal );
  55025. assert( pPrior == &pCell[info.iOverflow] );
  55026. }
  55027. #endif
  55028. /* Write the payload into the local Cell and any extra into overflow pages */
  55029. while( nPayload>0 ){
  55030. if( spaceLeft==0 ){
  55031. #ifndef SQLITE_OMIT_AUTOVACUUM
  55032. Pgno pgnoPtrmap = pgnoOvfl; /* Overflow page pointer-map entry page */
  55033. if( pBt->autoVacuum ){
  55034. do{
  55035. pgnoOvfl++;
  55036. } while(
  55037. PTRMAP_ISPAGE(pBt, pgnoOvfl) || pgnoOvfl==PENDING_BYTE_PAGE(pBt)
  55038. );
  55039. }
  55040. #endif
  55041. rc = allocateBtreePage(pBt, &pOvfl, &pgnoOvfl, pgnoOvfl, 0);
  55042. #ifndef SQLITE_OMIT_AUTOVACUUM
  55043. /* If the database supports auto-vacuum, and the second or subsequent
  55044. ** overflow page is being allocated, add an entry to the pointer-map
  55045. ** for that page now.
  55046. **
  55047. ** If this is the first overflow page, then write a partial entry
  55048. ** to the pointer-map. If we write nothing to this pointer-map slot,
  55049. ** then the optimistic overflow chain processing in clearCell()
  55050. ** may misinterpret the uninitialized values and delete the
  55051. ** wrong pages from the database.
  55052. */
  55053. if( pBt->autoVacuum && rc==SQLITE_OK ){
  55054. u8 eType = (pgnoPtrmap?PTRMAP_OVERFLOW2:PTRMAP_OVERFLOW1);
  55055. ptrmapPut(pBt, pgnoOvfl, eType, pgnoPtrmap, &rc);
  55056. if( rc ){
  55057. releasePage(pOvfl);
  55058. }
  55059. }
  55060. #endif
  55061. if( rc ){
  55062. releasePage(pToRelease);
  55063. return rc;
  55064. }
  55065. /* If pToRelease is not zero than pPrior points into the data area
  55066. ** of pToRelease. Make sure pToRelease is still writeable. */
  55067. assert( pToRelease==0 || sqlite3PagerIswriteable(pToRelease->pDbPage) );
  55068. /* If pPrior is part of the data area of pPage, then make sure pPage
  55069. ** is still writeable */
  55070. assert( pPrior<pPage->aData || pPrior>=&pPage->aData[pBt->pageSize]
  55071. || sqlite3PagerIswriteable(pPage->pDbPage) );
  55072. put4byte(pPrior, pgnoOvfl);
  55073. releasePage(pToRelease);
  55074. pToRelease = pOvfl;
  55075. pPrior = pOvfl->aData;
  55076. put4byte(pPrior, 0);
  55077. pPayload = &pOvfl->aData[4];
  55078. spaceLeft = pBt->usableSize - 4;
  55079. }
  55080. n = nPayload;
  55081. if( n>spaceLeft ) n = spaceLeft;
  55082. /* If pToRelease is not zero than pPayload points into the data area
  55083. ** of pToRelease. Make sure pToRelease is still writeable. */
  55084. assert( pToRelease==0 || sqlite3PagerIswriteable(pToRelease->pDbPage) );
  55085. /* If pPayload is part of the data area of pPage, then make sure pPage
  55086. ** is still writeable */
  55087. assert( pPayload<pPage->aData || pPayload>=&pPage->aData[pBt->pageSize]
  55088. || sqlite3PagerIswriteable(pPage->pDbPage) );
  55089. if( nSrc>0 ){
  55090. if( n>nSrc ) n = nSrc;
  55091. assert( pSrc );
  55092. memcpy(pPayload, pSrc, n);
  55093. }else{
  55094. memset(pPayload, 0, n);
  55095. }
  55096. nPayload -= n;
  55097. pPayload += n;
  55098. pSrc += n;
  55099. nSrc -= n;
  55100. spaceLeft -= n;
  55101. if( nSrc==0 ){
  55102. nSrc = nData;
  55103. pSrc = pData;
  55104. }
  55105. }
  55106. releasePage(pToRelease);
  55107. return SQLITE_OK;
  55108. }
  55109. /*
  55110. ** Remove the i-th cell from pPage. This routine effects pPage only.
  55111. ** The cell content is not freed or deallocated. It is assumed that
  55112. ** the cell content has been copied someplace else. This routine just
  55113. ** removes the reference to the cell from pPage.
  55114. **
  55115. ** "sz" must be the number of bytes in the cell.
  55116. */
  55117. static void dropCell(MemPage *pPage, int idx, int sz, int *pRC){
  55118. u32 pc; /* Offset to cell content of cell being deleted */
  55119. u8 *data; /* pPage->aData */
  55120. u8 *ptr; /* Used to move bytes around within data[] */
  55121. int rc; /* The return code */
  55122. int hdr; /* Beginning of the header. 0 most pages. 100 page 1 */
  55123. if( *pRC ) return;
  55124. assert( idx>=0 && idx<pPage->nCell );
  55125. assert( sz==cellSize(pPage, idx) );
  55126. assert( sqlite3PagerIswriteable(pPage->pDbPage) );
  55127. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  55128. data = pPage->aData;
  55129. ptr = &pPage->aCellIdx[2*idx];
  55130. pc = get2byte(ptr);
  55131. hdr = pPage->hdrOffset;
  55132. testcase( pc==get2byte(&data[hdr+5]) );
  55133. testcase( pc+sz==pPage->pBt->usableSize );
  55134. if( pc < (u32)get2byte(&data[hdr+5]) || pc+sz > pPage->pBt->usableSize ){
  55135. *pRC = SQLITE_CORRUPT_BKPT;
  55136. return;
  55137. }
  55138. rc = freeSpace(pPage, pc, sz);
  55139. if( rc ){
  55140. *pRC = rc;
  55141. return;
  55142. }
  55143. pPage->nCell--;
  55144. if( pPage->nCell==0 ){
  55145. memset(&data[hdr+1], 0, 4);
  55146. data[hdr+7] = 0;
  55147. put2byte(&data[hdr+5], pPage->pBt->usableSize);
  55148. pPage->nFree = pPage->pBt->usableSize - pPage->hdrOffset
  55149. - pPage->childPtrSize - 8;
  55150. }else{
  55151. memmove(ptr, ptr+2, 2*(pPage->nCell - idx));
  55152. put2byte(&data[hdr+3], pPage->nCell);
  55153. pPage->nFree += 2;
  55154. }
  55155. }
  55156. /*
  55157. ** Insert a new cell on pPage at cell index "i". pCell points to the
  55158. ** content of the cell.
  55159. **
  55160. ** If the cell content will fit on the page, then put it there. If it
  55161. ** will not fit, then make a copy of the cell content into pTemp if
  55162. ** pTemp is not null. Regardless of pTemp, allocate a new entry
  55163. ** in pPage->apOvfl[] and make it point to the cell content (either
  55164. ** in pTemp or the original pCell) and also record its index.
  55165. ** Allocating a new entry in pPage->aCell[] implies that
  55166. ** pPage->nOverflow is incremented.
  55167. */
  55168. static void insertCell(
  55169. MemPage *pPage, /* Page into which we are copying */
  55170. int i, /* New cell becomes the i-th cell of the page */
  55171. u8 *pCell, /* Content of the new cell */
  55172. int sz, /* Bytes of content in pCell */
  55173. u8 *pTemp, /* Temp storage space for pCell, if needed */
  55174. Pgno iChild, /* If non-zero, replace first 4 bytes with this value */
  55175. int *pRC /* Read and write return code from here */
  55176. ){
  55177. int idx = 0; /* Where to write new cell content in data[] */
  55178. int j; /* Loop counter */
  55179. int end; /* First byte past the last cell pointer in data[] */
  55180. int ins; /* Index in data[] where new cell pointer is inserted */
  55181. int cellOffset; /* Address of first cell pointer in data[] */
  55182. u8 *data; /* The content of the whole page */
  55183. if( *pRC ) return;
  55184. assert( i>=0 && i<=pPage->nCell+pPage->nOverflow );
  55185. assert( MX_CELL(pPage->pBt)<=10921 );
  55186. assert( pPage->nCell<=MX_CELL(pPage->pBt) || CORRUPT_DB );
  55187. assert( pPage->nOverflow<=ArraySize(pPage->apOvfl) );
  55188. assert( ArraySize(pPage->apOvfl)==ArraySize(pPage->aiOvfl) );
  55189. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  55190. /* The cell should normally be sized correctly. However, when moving a
  55191. ** malformed cell from a leaf page to an interior page, if the cell size
  55192. ** wanted to be less than 4 but got rounded up to 4 on the leaf, then size
  55193. ** might be less than 8 (leaf-size + pointer) on the interior node. Hence
  55194. ** the term after the || in the following assert(). */
  55195. assert( sz==cellSizePtr(pPage, pCell) || (sz==8 && iChild>0) );
  55196. if( pPage->nOverflow || sz+2>pPage->nFree ){
  55197. if( pTemp ){
  55198. memcpy(pTemp, pCell, sz);
  55199. pCell = pTemp;
  55200. }
  55201. if( iChild ){
  55202. put4byte(pCell, iChild);
  55203. }
  55204. j = pPage->nOverflow++;
  55205. assert( j<(int)(sizeof(pPage->apOvfl)/sizeof(pPage->apOvfl[0])) );
  55206. pPage->apOvfl[j] = pCell;
  55207. pPage->aiOvfl[j] = (u16)i;
  55208. }else{
  55209. int rc = sqlite3PagerWrite(pPage->pDbPage);
  55210. if( rc!=SQLITE_OK ){
  55211. *pRC = rc;
  55212. return;
  55213. }
  55214. assert( sqlite3PagerIswriteable(pPage->pDbPage) );
  55215. data = pPage->aData;
  55216. cellOffset = pPage->cellOffset;
  55217. end = cellOffset + 2*pPage->nCell;
  55218. ins = cellOffset + 2*i;
  55219. rc = allocateSpace(pPage, sz, &idx);
  55220. if( rc ){ *pRC = rc; return; }
  55221. /* The allocateSpace() routine guarantees the following two properties
  55222. ** if it returns success */
  55223. assert( idx >= end+2 );
  55224. assert( idx+sz <= (int)pPage->pBt->usableSize );
  55225. pPage->nCell++;
  55226. pPage->nFree -= (u16)(2 + sz);
  55227. memcpy(&data[idx], pCell, sz);
  55228. if( iChild ){
  55229. put4byte(&data[idx], iChild);
  55230. }
  55231. memmove(&data[ins+2], &data[ins], end-ins);
  55232. put2byte(&data[ins], idx);
  55233. put2byte(&data[pPage->hdrOffset+3], pPage->nCell);
  55234. #ifndef SQLITE_OMIT_AUTOVACUUM
  55235. if( pPage->pBt->autoVacuum ){
  55236. /* The cell may contain a pointer to an overflow page. If so, write
  55237. ** the entry for the overflow page into the pointer map.
  55238. */
  55239. ptrmapPutOvflPtr(pPage, pCell, pRC);
  55240. }
  55241. #endif
  55242. }
  55243. }
  55244. /*
  55245. ** Array apCell[] contains pointers to nCell b-tree page cells. The
  55246. ** szCell[] array contains the size in bytes of each cell. This function
  55247. ** replaces the current contents of page pPg with the contents of the cell
  55248. ** array.
  55249. **
  55250. ** Some of the cells in apCell[] may currently be stored in pPg. This
  55251. ** function works around problems caused by this by making a copy of any
  55252. ** such cells before overwriting the page data.
  55253. **
  55254. ** The MemPage.nFree field is invalidated by this function. It is the
  55255. ** responsibility of the caller to set it correctly.
  55256. */
  55257. static void rebuildPage(
  55258. MemPage *pPg, /* Edit this page */
  55259. int nCell, /* Final number of cells on page */
  55260. u8 **apCell, /* Array of cells */
  55261. u16 *szCell /* Array of cell sizes */
  55262. ){
  55263. const int hdr = pPg->hdrOffset; /* Offset of header on pPg */
  55264. u8 * const aData = pPg->aData; /* Pointer to data for pPg */
  55265. const int usableSize = pPg->pBt->usableSize;
  55266. u8 * const pEnd = &aData[usableSize];
  55267. int i;
  55268. u8 *pCellptr = pPg->aCellIdx;
  55269. u8 *pTmp = sqlite3PagerTempSpace(pPg->pBt->pPager);
  55270. u8 *pData;
  55271. i = get2byte(&aData[hdr+5]);
  55272. memcpy(&pTmp[i], &aData[i], usableSize - i);
  55273. pData = pEnd;
  55274. for(i=0; i<nCell; i++){
  55275. u8 *pCell = apCell[i];
  55276. if( pCell>aData && pCell<pEnd ){
  55277. pCell = &pTmp[pCell - aData];
  55278. }
  55279. pData -= szCell[i];
  55280. memcpy(pData, pCell, szCell[i]);
  55281. put2byte(pCellptr, (pData - aData));
  55282. pCellptr += 2;
  55283. assert( szCell[i]==cellSizePtr(pPg, pCell) );
  55284. }
  55285. /* The pPg->nFree field is now set incorrectly. The caller will fix it. */
  55286. pPg->nCell = nCell;
  55287. pPg->nOverflow = 0;
  55288. put2byte(&aData[hdr+1], 0);
  55289. put2byte(&aData[hdr+3], pPg->nCell);
  55290. put2byte(&aData[hdr+5], pData - aData);
  55291. aData[hdr+7] = 0x00;
  55292. }
  55293. /*
  55294. ** Array apCell[] contains nCell pointers to b-tree cells. Array szCell
  55295. ** contains the size in bytes of each such cell. This function attempts to
  55296. ** add the cells stored in the array to page pPg. If it cannot (because
  55297. ** the page needs to be defragmented before the cells will fit), non-zero
  55298. ** is returned. Otherwise, if the cells are added successfully, zero is
  55299. ** returned.
  55300. **
  55301. ** Argument pCellptr points to the first entry in the cell-pointer array
  55302. ** (part of page pPg) to populate. After cell apCell[0] is written to the
  55303. ** page body, a 16-bit offset is written to pCellptr. And so on, for each
  55304. ** cell in the array. It is the responsibility of the caller to ensure
  55305. ** that it is safe to overwrite this part of the cell-pointer array.
  55306. **
  55307. ** When this function is called, *ppData points to the start of the
  55308. ** content area on page pPg. If the size of the content area is extended,
  55309. ** *ppData is updated to point to the new start of the content area
  55310. ** before returning.
  55311. **
  55312. ** Finally, argument pBegin points to the byte immediately following the
  55313. ** end of the space required by this page for the cell-pointer area (for
  55314. ** all cells - not just those inserted by the current call). If the content
  55315. ** area must be extended to before this point in order to accomodate all
  55316. ** cells in apCell[], then the cells do not fit and non-zero is returned.
  55317. */
  55318. static int pageInsertArray(
  55319. MemPage *pPg, /* Page to add cells to */
  55320. u8 *pBegin, /* End of cell-pointer array */
  55321. u8 **ppData, /* IN/OUT: Page content -area pointer */
  55322. u8 *pCellptr, /* Pointer to cell-pointer area */
  55323. int nCell, /* Number of cells to add to pPg */
  55324. u8 **apCell, /* Array of cells */
  55325. u16 *szCell /* Array of cell sizes */
  55326. ){
  55327. int i;
  55328. u8 *aData = pPg->aData;
  55329. u8 *pData = *ppData;
  55330. const int bFreelist = aData[1] || aData[2];
  55331. assert( CORRUPT_DB || pPg->hdrOffset==0 ); /* Never called on page 1 */
  55332. for(i=0; i<nCell; i++){
  55333. int sz = szCell[i];
  55334. int rc;
  55335. u8 *pSlot;
  55336. if( bFreelist==0 || (pSlot = pageFindSlot(pPg, sz, &rc, 0))==0 ){
  55337. pData -= sz;
  55338. if( pData<pBegin ) return 1;
  55339. pSlot = pData;
  55340. }
  55341. memcpy(pSlot, apCell[i], sz);
  55342. put2byte(pCellptr, (pSlot - aData));
  55343. pCellptr += 2;
  55344. }
  55345. *ppData = pData;
  55346. return 0;
  55347. }
  55348. /*
  55349. ** Array apCell[] contains nCell pointers to b-tree cells. Array szCell
  55350. ** contains the size in bytes of each such cell. This function adds the
  55351. ** space associated with each cell in the array that is currently stored
  55352. ** within the body of pPg to the pPg free-list. The cell-pointers and other
  55353. ** fields of the page are not updated.
  55354. **
  55355. ** This function returns the total number of cells added to the free-list.
  55356. */
  55357. static int pageFreeArray(
  55358. MemPage *pPg, /* Page to edit */
  55359. int nCell, /* Cells to delete */
  55360. u8 **apCell, /* Array of cells */
  55361. u16 *szCell /* Array of cell sizes */
  55362. ){
  55363. u8 * const aData = pPg->aData;
  55364. u8 * const pEnd = &aData[pPg->pBt->usableSize];
  55365. u8 * const pStart = &aData[pPg->hdrOffset + 8 + pPg->childPtrSize];
  55366. int nRet = 0;
  55367. int i;
  55368. u8 *pFree = 0;
  55369. int szFree = 0;
  55370. for(i=0; i<nCell; i++){
  55371. u8 *pCell = apCell[i];
  55372. if( pCell>=pStart && pCell<pEnd ){
  55373. int sz = szCell[i];
  55374. if( pFree!=(pCell + sz) ){
  55375. if( pFree ){
  55376. assert( pFree>aData && (pFree - aData)<65536 );
  55377. freeSpace(pPg, (u16)(pFree - aData), szFree);
  55378. }
  55379. pFree = pCell;
  55380. szFree = sz;
  55381. if( pFree+sz>pEnd ) return 0;
  55382. }else{
  55383. pFree = pCell;
  55384. szFree += sz;
  55385. }
  55386. nRet++;
  55387. }
  55388. }
  55389. if( pFree ){
  55390. assert( pFree>aData && (pFree - aData)<65536 );
  55391. freeSpace(pPg, (u16)(pFree - aData), szFree);
  55392. }
  55393. return nRet;
  55394. }
  55395. /*
  55396. ** apCell[] and szCell[] contains pointers to and sizes of all cells in the
  55397. ** pages being balanced. The current page, pPg, has pPg->nCell cells starting
  55398. ** with apCell[iOld]. After balancing, this page should hold nNew cells
  55399. ** starting at apCell[iNew].
  55400. **
  55401. ** This routine makes the necessary adjustments to pPg so that it contains
  55402. ** the correct cells after being balanced.
  55403. **
  55404. ** The pPg->nFree field is invalid when this function returns. It is the
  55405. ** responsibility of the caller to set it correctly.
  55406. */
  55407. static void editPage(
  55408. MemPage *pPg, /* Edit this page */
  55409. int iOld, /* Index of first cell currently on page */
  55410. int iNew, /* Index of new first cell on page */
  55411. int nNew, /* Final number of cells on page */
  55412. u8 **apCell, /* Array of cells */
  55413. u16 *szCell /* Array of cell sizes */
  55414. ){
  55415. u8 * const aData = pPg->aData;
  55416. const int hdr = pPg->hdrOffset;
  55417. u8 *pBegin = &pPg->aCellIdx[nNew * 2];
  55418. int nCell = pPg->nCell; /* Cells stored on pPg */
  55419. u8 *pData;
  55420. u8 *pCellptr;
  55421. int i;
  55422. int iOldEnd = iOld + pPg->nCell + pPg->nOverflow;
  55423. int iNewEnd = iNew + nNew;
  55424. #ifdef SQLITE_DEBUG
  55425. u8 *pTmp = sqlite3PagerTempSpace(pPg->pBt->pPager);
  55426. memcpy(pTmp, aData, pPg->pBt->usableSize);
  55427. #endif
  55428. /* Remove cells from the start and end of the page */
  55429. if( iOld<iNew ){
  55430. int nShift = pageFreeArray(
  55431. pPg, iNew-iOld, &apCell[iOld], &szCell[iOld]
  55432. );
  55433. memmove(pPg->aCellIdx, &pPg->aCellIdx[nShift*2], nCell*2);
  55434. nCell -= nShift;
  55435. }
  55436. if( iNewEnd < iOldEnd ){
  55437. nCell -= pageFreeArray(
  55438. pPg, iOldEnd-iNewEnd, &apCell[iNewEnd], &szCell[iNewEnd]
  55439. );
  55440. }
  55441. pData = &aData[get2byteNotZero(&aData[hdr+5])];
  55442. if( pData<pBegin ) goto editpage_fail;
  55443. /* Add cells to the start of the page */
  55444. if( iNew<iOld ){
  55445. int nAdd = MIN(nNew,iOld-iNew);
  55446. assert( (iOld-iNew)<nNew || nCell==0 || CORRUPT_DB );
  55447. pCellptr = pPg->aCellIdx;
  55448. memmove(&pCellptr[nAdd*2], pCellptr, nCell*2);
  55449. if( pageInsertArray(
  55450. pPg, pBegin, &pData, pCellptr,
  55451. nAdd, &apCell[iNew], &szCell[iNew]
  55452. ) ) goto editpage_fail;
  55453. nCell += nAdd;
  55454. }
  55455. /* Add any overflow cells */
  55456. for(i=0; i<pPg->nOverflow; i++){
  55457. int iCell = (iOld + pPg->aiOvfl[i]) - iNew;
  55458. if( iCell>=0 && iCell<nNew ){
  55459. pCellptr = &pPg->aCellIdx[iCell * 2];
  55460. memmove(&pCellptr[2], pCellptr, (nCell - iCell) * 2);
  55461. nCell++;
  55462. if( pageInsertArray(
  55463. pPg, pBegin, &pData, pCellptr,
  55464. 1, &apCell[iCell + iNew], &szCell[iCell + iNew]
  55465. ) ) goto editpage_fail;
  55466. }
  55467. }
  55468. /* Append cells to the end of the page */
  55469. pCellptr = &pPg->aCellIdx[nCell*2];
  55470. if( pageInsertArray(
  55471. pPg, pBegin, &pData, pCellptr,
  55472. nNew-nCell, &apCell[iNew+nCell], &szCell[iNew+nCell]
  55473. ) ) goto editpage_fail;
  55474. pPg->nCell = nNew;
  55475. pPg->nOverflow = 0;
  55476. put2byte(&aData[hdr+3], pPg->nCell);
  55477. put2byte(&aData[hdr+5], pData - aData);
  55478. #ifdef SQLITE_DEBUG
  55479. for(i=0; i<nNew && !CORRUPT_DB; i++){
  55480. u8 *pCell = apCell[i+iNew];
  55481. int iOff = get2byte(&pPg->aCellIdx[i*2]);
  55482. if( pCell>=aData && pCell<&aData[pPg->pBt->usableSize] ){
  55483. pCell = &pTmp[pCell - aData];
  55484. }
  55485. assert( 0==memcmp(pCell, &aData[iOff], szCell[i+iNew]) );
  55486. }
  55487. #endif
  55488. return;
  55489. editpage_fail:
  55490. /* Unable to edit this page. Rebuild it from scratch instead. */
  55491. rebuildPage(pPg, nNew, &apCell[iNew], &szCell[iNew]);
  55492. }
  55493. /*
  55494. ** The following parameters determine how many adjacent pages get involved
  55495. ** in a balancing operation. NN is the number of neighbors on either side
  55496. ** of the page that participate in the balancing operation. NB is the
  55497. ** total number of pages that participate, including the target page and
  55498. ** NN neighbors on either side.
  55499. **
  55500. ** The minimum value of NN is 1 (of course). Increasing NN above 1
  55501. ** (to 2 or 3) gives a modest improvement in SELECT and DELETE performance
  55502. ** in exchange for a larger degradation in INSERT and UPDATE performance.
  55503. ** The value of NN appears to give the best results overall.
  55504. */
  55505. #define NN 1 /* Number of neighbors on either side of pPage */
  55506. #define NB (NN*2+1) /* Total pages involved in the balance */
  55507. #ifndef SQLITE_OMIT_QUICKBALANCE
  55508. /*
  55509. ** This version of balance() handles the common special case where
  55510. ** a new entry is being inserted on the extreme right-end of the
  55511. ** tree, in other words, when the new entry will become the largest
  55512. ** entry in the tree.
  55513. **
  55514. ** Instead of trying to balance the 3 right-most leaf pages, just add
  55515. ** a new page to the right-hand side and put the one new entry in
  55516. ** that page. This leaves the right side of the tree somewhat
  55517. ** unbalanced. But odds are that we will be inserting new entries
  55518. ** at the end soon afterwards so the nearly empty page will quickly
  55519. ** fill up. On average.
  55520. **
  55521. ** pPage is the leaf page which is the right-most page in the tree.
  55522. ** pParent is its parent. pPage must have a single overflow entry
  55523. ** which is also the right-most entry on the page.
  55524. **
  55525. ** The pSpace buffer is used to store a temporary copy of the divider
  55526. ** cell that will be inserted into pParent. Such a cell consists of a 4
  55527. ** byte page number followed by a variable length integer. In other
  55528. ** words, at most 13 bytes. Hence the pSpace buffer must be at
  55529. ** least 13 bytes in size.
  55530. */
  55531. static int balance_quick(MemPage *pParent, MemPage *pPage, u8 *pSpace){
  55532. BtShared *const pBt = pPage->pBt; /* B-Tree Database */
  55533. MemPage *pNew; /* Newly allocated page */
  55534. int rc; /* Return Code */
  55535. Pgno pgnoNew; /* Page number of pNew */
  55536. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  55537. assert( sqlite3PagerIswriteable(pParent->pDbPage) );
  55538. assert( pPage->nOverflow==1 );
  55539. /* This error condition is now caught prior to reaching this function */
  55540. if( NEVER(pPage->nCell==0) ) return SQLITE_CORRUPT_BKPT;
  55541. /* Allocate a new page. This page will become the right-sibling of
  55542. ** pPage. Make the parent page writable, so that the new divider cell
  55543. ** may be inserted. If both these operations are successful, proceed.
  55544. */
  55545. rc = allocateBtreePage(pBt, &pNew, &pgnoNew, 0, 0);
  55546. if( rc==SQLITE_OK ){
  55547. u8 *pOut = &pSpace[4];
  55548. u8 *pCell = pPage->apOvfl[0];
  55549. u16 szCell = cellSizePtr(pPage, pCell);
  55550. u8 *pStop;
  55551. assert( sqlite3PagerIswriteable(pNew->pDbPage) );
  55552. assert( pPage->aData[0]==(PTF_INTKEY|PTF_LEAFDATA|PTF_LEAF) );
  55553. zeroPage(pNew, PTF_INTKEY|PTF_LEAFDATA|PTF_LEAF);
  55554. rebuildPage(pNew, 1, &pCell, &szCell);
  55555. pNew->nFree = pBt->usableSize - pNew->cellOffset - 2 - szCell;
  55556. /* If this is an auto-vacuum database, update the pointer map
  55557. ** with entries for the new page, and any pointer from the
  55558. ** cell on the page to an overflow page. If either of these
  55559. ** operations fails, the return code is set, but the contents
  55560. ** of the parent page are still manipulated by thh code below.
  55561. ** That is Ok, at this point the parent page is guaranteed to
  55562. ** be marked as dirty. Returning an error code will cause a
  55563. ** rollback, undoing any changes made to the parent page.
  55564. */
  55565. if( ISAUTOVACUUM ){
  55566. ptrmapPut(pBt, pgnoNew, PTRMAP_BTREE, pParent->pgno, &rc);
  55567. if( szCell>pNew->minLocal ){
  55568. ptrmapPutOvflPtr(pNew, pCell, &rc);
  55569. }
  55570. }
  55571. /* Create a divider cell to insert into pParent. The divider cell
  55572. ** consists of a 4-byte page number (the page number of pPage) and
  55573. ** a variable length key value (which must be the same value as the
  55574. ** largest key on pPage).
  55575. **
  55576. ** To find the largest key value on pPage, first find the right-most
  55577. ** cell on pPage. The first two fields of this cell are the
  55578. ** record-length (a variable length integer at most 32-bits in size)
  55579. ** and the key value (a variable length integer, may have any value).
  55580. ** The first of the while(...) loops below skips over the record-length
  55581. ** field. The second while(...) loop copies the key value from the
  55582. ** cell on pPage into the pSpace buffer.
  55583. */
  55584. pCell = findCell(pPage, pPage->nCell-1);
  55585. pStop = &pCell[9];
  55586. while( (*(pCell++)&0x80) && pCell<pStop );
  55587. pStop = &pCell[9];
  55588. while( ((*(pOut++) = *(pCell++))&0x80) && pCell<pStop );
  55589. /* Insert the new divider cell into pParent. */
  55590. insertCell(pParent, pParent->nCell, pSpace, (int)(pOut-pSpace),
  55591. 0, pPage->pgno, &rc);
  55592. /* Set the right-child pointer of pParent to point to the new page. */
  55593. put4byte(&pParent->aData[pParent->hdrOffset+8], pgnoNew);
  55594. /* Release the reference to the new page. */
  55595. releasePage(pNew);
  55596. }
  55597. return rc;
  55598. }
  55599. #endif /* SQLITE_OMIT_QUICKBALANCE */
  55600. #if 0
  55601. /*
  55602. ** This function does not contribute anything to the operation of SQLite.
  55603. ** it is sometimes activated temporarily while debugging code responsible
  55604. ** for setting pointer-map entries.
  55605. */
  55606. static int ptrmapCheckPages(MemPage **apPage, int nPage){
  55607. int i, j;
  55608. for(i=0; i<nPage; i++){
  55609. Pgno n;
  55610. u8 e;
  55611. MemPage *pPage = apPage[i];
  55612. BtShared *pBt = pPage->pBt;
  55613. assert( pPage->isInit );
  55614. for(j=0; j<pPage->nCell; j++){
  55615. CellInfo info;
  55616. u8 *z;
  55617. z = findCell(pPage, j);
  55618. btreeParseCellPtr(pPage, z, &info);
  55619. if( info.iOverflow ){
  55620. Pgno ovfl = get4byte(&z[info.iOverflow]);
  55621. ptrmapGet(pBt, ovfl, &e, &n);
  55622. assert( n==pPage->pgno && e==PTRMAP_OVERFLOW1 );
  55623. }
  55624. if( !pPage->leaf ){
  55625. Pgno child = get4byte(z);
  55626. ptrmapGet(pBt, child, &e, &n);
  55627. assert( n==pPage->pgno && e==PTRMAP_BTREE );
  55628. }
  55629. }
  55630. if( !pPage->leaf ){
  55631. Pgno child = get4byte(&pPage->aData[pPage->hdrOffset+8]);
  55632. ptrmapGet(pBt, child, &e, &n);
  55633. assert( n==pPage->pgno && e==PTRMAP_BTREE );
  55634. }
  55635. }
  55636. return 1;
  55637. }
  55638. #endif
  55639. /*
  55640. ** This function is used to copy the contents of the b-tree node stored
  55641. ** on page pFrom to page pTo. If page pFrom was not a leaf page, then
  55642. ** the pointer-map entries for each child page are updated so that the
  55643. ** parent page stored in the pointer map is page pTo. If pFrom contained
  55644. ** any cells with overflow page pointers, then the corresponding pointer
  55645. ** map entries are also updated so that the parent page is page pTo.
  55646. **
  55647. ** If pFrom is currently carrying any overflow cells (entries in the
  55648. ** MemPage.apOvfl[] array), they are not copied to pTo.
  55649. **
  55650. ** Before returning, page pTo is reinitialized using btreeInitPage().
  55651. **
  55652. ** The performance of this function is not critical. It is only used by
  55653. ** the balance_shallower() and balance_deeper() procedures, neither of
  55654. ** which are called often under normal circumstances.
  55655. */
  55656. static void copyNodeContent(MemPage *pFrom, MemPage *pTo, int *pRC){
  55657. if( (*pRC)==SQLITE_OK ){
  55658. BtShared * const pBt = pFrom->pBt;
  55659. u8 * const aFrom = pFrom->aData;
  55660. u8 * const aTo = pTo->aData;
  55661. int const iFromHdr = pFrom->hdrOffset;
  55662. int const iToHdr = ((pTo->pgno==1) ? 100 : 0);
  55663. int rc;
  55664. int iData;
  55665. assert( pFrom->isInit );
  55666. assert( pFrom->nFree>=iToHdr );
  55667. assert( get2byte(&aFrom[iFromHdr+5]) <= (int)pBt->usableSize );
  55668. /* Copy the b-tree node content from page pFrom to page pTo. */
  55669. iData = get2byte(&aFrom[iFromHdr+5]);
  55670. memcpy(&aTo[iData], &aFrom[iData], pBt->usableSize-iData);
  55671. memcpy(&aTo[iToHdr], &aFrom[iFromHdr], pFrom->cellOffset + 2*pFrom->nCell);
  55672. /* Reinitialize page pTo so that the contents of the MemPage structure
  55673. ** match the new data. The initialization of pTo can actually fail under
  55674. ** fairly obscure circumstances, even though it is a copy of initialized
  55675. ** page pFrom.
  55676. */
  55677. pTo->isInit = 0;
  55678. rc = btreeInitPage(pTo);
  55679. if( rc!=SQLITE_OK ){
  55680. *pRC = rc;
  55681. return;
  55682. }
  55683. /* If this is an auto-vacuum database, update the pointer-map entries
  55684. ** for any b-tree or overflow pages that pTo now contains the pointers to.
  55685. */
  55686. if( ISAUTOVACUUM ){
  55687. *pRC = setChildPtrmaps(pTo);
  55688. }
  55689. }
  55690. }
  55691. /*
  55692. ** This routine redistributes cells on the iParentIdx'th child of pParent
  55693. ** (hereafter "the page") and up to 2 siblings so that all pages have about the
  55694. ** same amount of free space. Usually a single sibling on either side of the
  55695. ** page are used in the balancing, though both siblings might come from one
  55696. ** side if the page is the first or last child of its parent. If the page
  55697. ** has fewer than 2 siblings (something which can only happen if the page
  55698. ** is a root page or a child of a root page) then all available siblings
  55699. ** participate in the balancing.
  55700. **
  55701. ** The number of siblings of the page might be increased or decreased by
  55702. ** one or two in an effort to keep pages nearly full but not over full.
  55703. **
  55704. ** Note that when this routine is called, some of the cells on the page
  55705. ** might not actually be stored in MemPage.aData[]. This can happen
  55706. ** if the page is overfull. This routine ensures that all cells allocated
  55707. ** to the page and its siblings fit into MemPage.aData[] before returning.
  55708. **
  55709. ** In the course of balancing the page and its siblings, cells may be
  55710. ** inserted into or removed from the parent page (pParent). Doing so
  55711. ** may cause the parent page to become overfull or underfull. If this
  55712. ** happens, it is the responsibility of the caller to invoke the correct
  55713. ** balancing routine to fix this problem (see the balance() routine).
  55714. **
  55715. ** If this routine fails for any reason, it might leave the database
  55716. ** in a corrupted state. So if this routine fails, the database should
  55717. ** be rolled back.
  55718. **
  55719. ** The third argument to this function, aOvflSpace, is a pointer to a
  55720. ** buffer big enough to hold one page. If while inserting cells into the parent
  55721. ** page (pParent) the parent page becomes overfull, this buffer is
  55722. ** used to store the parent's overflow cells. Because this function inserts
  55723. ** a maximum of four divider cells into the parent page, and the maximum
  55724. ** size of a cell stored within an internal node is always less than 1/4
  55725. ** of the page-size, the aOvflSpace[] buffer is guaranteed to be large
  55726. ** enough for all overflow cells.
  55727. **
  55728. ** If aOvflSpace is set to a null pointer, this function returns
  55729. ** SQLITE_NOMEM.
  55730. */
  55731. #if defined(_MSC_VER) && _MSC_VER >= 1700 && defined(_M_ARM)
  55732. #pragma optimize("", off)
  55733. #endif
  55734. static int balance_nonroot(
  55735. MemPage *pParent, /* Parent page of siblings being balanced */
  55736. int iParentIdx, /* Index of "the page" in pParent */
  55737. u8 *aOvflSpace, /* page-size bytes of space for parent ovfl */
  55738. int isRoot, /* True if pParent is a root-page */
  55739. int bBulk /* True if this call is part of a bulk load */
  55740. ){
  55741. BtShared *pBt; /* The whole database */
  55742. int nCell = 0; /* Number of cells in apCell[] */
  55743. int nMaxCells = 0; /* Allocated size of apCell, szCell, aFrom. */
  55744. int nNew = 0; /* Number of pages in apNew[] */
  55745. int nOld; /* Number of pages in apOld[] */
  55746. int i, j, k; /* Loop counters */
  55747. int nxDiv; /* Next divider slot in pParent->aCell[] */
  55748. int rc = SQLITE_OK; /* The return code */
  55749. u16 leafCorrection; /* 4 if pPage is a leaf. 0 if not */
  55750. int leafData; /* True if pPage is a leaf of a LEAFDATA tree */
  55751. int usableSpace; /* Bytes in pPage beyond the header */
  55752. int pageFlags; /* Value of pPage->aData[0] */
  55753. int subtotal; /* Subtotal of bytes in cells on one page */
  55754. int iSpace1 = 0; /* First unused byte of aSpace1[] */
  55755. int iOvflSpace = 0; /* First unused byte of aOvflSpace[] */
  55756. int szScratch; /* Size of scratch memory requested */
  55757. MemPage *apOld[NB]; /* pPage and up to two siblings */
  55758. MemPage *apNew[NB+2]; /* pPage and up to NB siblings after balancing */
  55759. u8 *pRight; /* Location in parent of right-sibling pointer */
  55760. u8 *apDiv[NB-1]; /* Divider cells in pParent */
  55761. int cntNew[NB+2]; /* Index in aCell[] of cell after i-th page */
  55762. int cntOld[NB+2]; /* Old index in aCell[] after i-th page */
  55763. int szNew[NB+2]; /* Combined size of cells placed on i-th page */
  55764. u8 **apCell = 0; /* All cells begin balanced */
  55765. u16 *szCell; /* Local size of all cells in apCell[] */
  55766. u8 *aSpace1; /* Space for copies of dividers cells */
  55767. Pgno pgno; /* Temp var to store a page number in */
  55768. u8 abDone[NB+2]; /* True after i'th new page is populated */
  55769. Pgno aPgno[NB+2]; /* Page numbers of new pages before shuffling */
  55770. Pgno aPgOrder[NB+2]; /* Copy of aPgno[] used for sorting pages */
  55771. u16 aPgFlags[NB+2]; /* flags field of new pages before shuffling */
  55772. memset(abDone, 0, sizeof(abDone));
  55773. pBt = pParent->pBt;
  55774. assert( sqlite3_mutex_held(pBt->mutex) );
  55775. assert( sqlite3PagerIswriteable(pParent->pDbPage) );
  55776. #if 0
  55777. TRACE(("BALANCE: begin page %d child of %d\n", pPage->pgno, pParent->pgno));
  55778. #endif
  55779. /* At this point pParent may have at most one overflow cell. And if
  55780. ** this overflow cell is present, it must be the cell with
  55781. ** index iParentIdx. This scenario comes about when this function
  55782. ** is called (indirectly) from sqlite3BtreeDelete().
  55783. */
  55784. assert( pParent->nOverflow==0 || pParent->nOverflow==1 );
  55785. assert( pParent->nOverflow==0 || pParent->aiOvfl[0]==iParentIdx );
  55786. if( !aOvflSpace ){
  55787. return SQLITE_NOMEM;
  55788. }
  55789. /* Find the sibling pages to balance. Also locate the cells in pParent
  55790. ** that divide the siblings. An attempt is made to find NN siblings on
  55791. ** either side of pPage. More siblings are taken from one side, however,
  55792. ** if there are fewer than NN siblings on the other side. If pParent
  55793. ** has NB or fewer children then all children of pParent are taken.
  55794. **
  55795. ** This loop also drops the divider cells from the parent page. This
  55796. ** way, the remainder of the function does not have to deal with any
  55797. ** overflow cells in the parent page, since if any existed they will
  55798. ** have already been removed.
  55799. */
  55800. i = pParent->nOverflow + pParent->nCell;
  55801. if( i<2 ){
  55802. nxDiv = 0;
  55803. }else{
  55804. assert( bBulk==0 || bBulk==1 );
  55805. if( iParentIdx==0 ){
  55806. nxDiv = 0;
  55807. }else if( iParentIdx==i ){
  55808. nxDiv = i-2+bBulk;
  55809. }else{
  55810. nxDiv = iParentIdx-1;
  55811. }
  55812. i = 2-bBulk;
  55813. }
  55814. nOld = i+1;
  55815. if( (i+nxDiv-pParent->nOverflow)==pParent->nCell ){
  55816. pRight = &pParent->aData[pParent->hdrOffset+8];
  55817. }else{
  55818. pRight = findCell(pParent, i+nxDiv-pParent->nOverflow);
  55819. }
  55820. pgno = get4byte(pRight);
  55821. while( 1 ){
  55822. rc = getAndInitPage(pBt, pgno, &apOld[i], 0);
  55823. if( rc ){
  55824. memset(apOld, 0, (i+1)*sizeof(MemPage*));
  55825. goto balance_cleanup;
  55826. }
  55827. nMaxCells += 1+apOld[i]->nCell+apOld[i]->nOverflow;
  55828. if( (i--)==0 ) break;
  55829. if( i+nxDiv==pParent->aiOvfl[0] && pParent->nOverflow ){
  55830. apDiv[i] = pParent->apOvfl[0];
  55831. pgno = get4byte(apDiv[i]);
  55832. szNew[i] = cellSizePtr(pParent, apDiv[i]);
  55833. pParent->nOverflow = 0;
  55834. }else{
  55835. apDiv[i] = findCell(pParent, i+nxDiv-pParent->nOverflow);
  55836. pgno = get4byte(apDiv[i]);
  55837. szNew[i] = cellSizePtr(pParent, apDiv[i]);
  55838. /* Drop the cell from the parent page. apDiv[i] still points to
  55839. ** the cell within the parent, even though it has been dropped.
  55840. ** This is safe because dropping a cell only overwrites the first
  55841. ** four bytes of it, and this function does not need the first
  55842. ** four bytes of the divider cell. So the pointer is safe to use
  55843. ** later on.
  55844. **
  55845. ** But not if we are in secure-delete mode. In secure-delete mode,
  55846. ** the dropCell() routine will overwrite the entire cell with zeroes.
  55847. ** In this case, temporarily copy the cell into the aOvflSpace[]
  55848. ** buffer. It will be copied out again as soon as the aSpace[] buffer
  55849. ** is allocated. */
  55850. if( pBt->btsFlags & BTS_SECURE_DELETE ){
  55851. int iOff;
  55852. iOff = SQLITE_PTR_TO_INT(apDiv[i]) - SQLITE_PTR_TO_INT(pParent->aData);
  55853. if( (iOff+szNew[i])>(int)pBt->usableSize ){
  55854. rc = SQLITE_CORRUPT_BKPT;
  55855. memset(apOld, 0, (i+1)*sizeof(MemPage*));
  55856. goto balance_cleanup;
  55857. }else{
  55858. memcpy(&aOvflSpace[iOff], apDiv[i], szNew[i]);
  55859. apDiv[i] = &aOvflSpace[apDiv[i]-pParent->aData];
  55860. }
  55861. }
  55862. dropCell(pParent, i+nxDiv-pParent->nOverflow, szNew[i], &rc);
  55863. }
  55864. }
  55865. /* Make nMaxCells a multiple of 4 in order to preserve 8-byte
  55866. ** alignment */
  55867. nMaxCells = (nMaxCells + 3)&~3;
  55868. /*
  55869. ** Allocate space for memory structures
  55870. */
  55871. szScratch =
  55872. nMaxCells*sizeof(u8*) /* apCell */
  55873. + nMaxCells*sizeof(u16) /* szCell */
  55874. + pBt->pageSize; /* aSpace1 */
  55875. /* EVIDENCE-OF: R-28375-38319 SQLite will never request a scratch buffer
  55876. ** that is more than 6 times the database page size. */
  55877. assert( szScratch<=6*(int)pBt->pageSize );
  55878. apCell = sqlite3ScratchMalloc( szScratch );
  55879. if( apCell==0 ){
  55880. rc = SQLITE_NOMEM;
  55881. goto balance_cleanup;
  55882. }
  55883. szCell = (u16*)&apCell[nMaxCells];
  55884. aSpace1 = (u8*)&szCell[nMaxCells];
  55885. assert( EIGHT_BYTE_ALIGNMENT(aSpace1) );
  55886. /*
  55887. ** Load pointers to all cells on sibling pages and the divider cells
  55888. ** into the local apCell[] array. Make copies of the divider cells
  55889. ** into space obtained from aSpace1[]. The divider cells have already
  55890. ** been removed from pParent.
  55891. **
  55892. ** If the siblings are on leaf pages, then the child pointers of the
  55893. ** divider cells are stripped from the cells before they are copied
  55894. ** into aSpace1[]. In this way, all cells in apCell[] are without
  55895. ** child pointers. If siblings are not leaves, then all cell in
  55896. ** apCell[] include child pointers. Either way, all cells in apCell[]
  55897. ** are alike.
  55898. **
  55899. ** leafCorrection: 4 if pPage is a leaf. 0 if pPage is not a leaf.
  55900. ** leafData: 1 if pPage holds key+data and pParent holds only keys.
  55901. */
  55902. leafCorrection = apOld[0]->leaf*4;
  55903. leafData = apOld[0]->intKeyLeaf;
  55904. for(i=0; i<nOld; i++){
  55905. int limit;
  55906. MemPage *pOld = apOld[i];
  55907. limit = pOld->nCell+pOld->nOverflow;
  55908. if( pOld->nOverflow>0 ){
  55909. for(j=0; j<limit; j++){
  55910. assert( nCell<nMaxCells );
  55911. apCell[nCell] = findOverflowCell(pOld, j);
  55912. szCell[nCell] = cellSizePtr(pOld, apCell[nCell]);
  55913. nCell++;
  55914. }
  55915. }else{
  55916. u8 *aData = pOld->aData;
  55917. u16 maskPage = pOld->maskPage;
  55918. u16 cellOffset = pOld->cellOffset;
  55919. for(j=0; j<limit; j++){
  55920. assert( nCell<nMaxCells );
  55921. apCell[nCell] = findCellv2(aData, maskPage, cellOffset, j);
  55922. szCell[nCell] = cellSizePtr(pOld, apCell[nCell]);
  55923. nCell++;
  55924. }
  55925. }
  55926. cntOld[i] = nCell;
  55927. if( i<nOld-1 && !leafData){
  55928. u16 sz = (u16)szNew[i];
  55929. u8 *pTemp;
  55930. assert( nCell<nMaxCells );
  55931. szCell[nCell] = sz;
  55932. pTemp = &aSpace1[iSpace1];
  55933. iSpace1 += sz;
  55934. assert( sz<=pBt->maxLocal+23 );
  55935. assert( iSpace1 <= (int)pBt->pageSize );
  55936. memcpy(pTemp, apDiv[i], sz);
  55937. apCell[nCell] = pTemp+leafCorrection;
  55938. assert( leafCorrection==0 || leafCorrection==4 );
  55939. szCell[nCell] = szCell[nCell] - leafCorrection;
  55940. if( !pOld->leaf ){
  55941. assert( leafCorrection==0 );
  55942. assert( pOld->hdrOffset==0 );
  55943. /* The right pointer of the child page pOld becomes the left
  55944. ** pointer of the divider cell */
  55945. memcpy(apCell[nCell], &pOld->aData[8], 4);
  55946. }else{
  55947. assert( leafCorrection==4 );
  55948. if( szCell[nCell]<4 ){
  55949. /* Do not allow any cells smaller than 4 bytes. If a smaller cell
  55950. ** does exist, pad it with 0x00 bytes. */
  55951. assert( szCell[nCell]==3 );
  55952. assert( apCell[nCell]==&aSpace1[iSpace1-3] );
  55953. aSpace1[iSpace1++] = 0x00;
  55954. szCell[nCell] = 4;
  55955. }
  55956. }
  55957. nCell++;
  55958. }
  55959. }
  55960. /*
  55961. ** Figure out the number of pages needed to hold all nCell cells.
  55962. ** Store this number in "k". Also compute szNew[] which is the total
  55963. ** size of all cells on the i-th page and cntNew[] which is the index
  55964. ** in apCell[] of the cell that divides page i from page i+1.
  55965. ** cntNew[k] should equal nCell.
  55966. **
  55967. ** Values computed by this block:
  55968. **
  55969. ** k: The total number of sibling pages
  55970. ** szNew[i]: Spaced used on the i-th sibling page.
  55971. ** cntNew[i]: Index in apCell[] and szCell[] for the first cell to
  55972. ** the right of the i-th sibling page.
  55973. ** usableSpace: Number of bytes of space available on each sibling.
  55974. **
  55975. */
  55976. usableSpace = pBt->usableSize - 12 + leafCorrection;
  55977. for(subtotal=k=i=0; i<nCell; i++){
  55978. assert( i<nMaxCells );
  55979. subtotal += szCell[i] + 2;
  55980. if( subtotal > usableSpace ){
  55981. szNew[k] = subtotal - szCell[i] - 2;
  55982. cntNew[k] = i;
  55983. if( leafData ){ i--; }
  55984. subtotal = 0;
  55985. k++;
  55986. if( k>NB+1 ){ rc = SQLITE_CORRUPT_BKPT; goto balance_cleanup; }
  55987. }
  55988. }
  55989. szNew[k] = subtotal;
  55990. cntNew[k] = nCell;
  55991. k++;
  55992. /*
  55993. ** The packing computed by the previous block is biased toward the siblings
  55994. ** on the left side (siblings with smaller keys). The left siblings are
  55995. ** always nearly full, while the right-most sibling might be nearly empty.
  55996. ** The next block of code attempts to adjust the packing of siblings to
  55997. ** get a better balance.
  55998. **
  55999. ** This adjustment is more than an optimization. The packing above might
  56000. ** be so out of balance as to be illegal. For example, the right-most
  56001. ** sibling might be completely empty. This adjustment is not optional.
  56002. */
  56003. for(i=k-1; i>0; i--){
  56004. int szRight = szNew[i]; /* Size of sibling on the right */
  56005. int szLeft = szNew[i-1]; /* Size of sibling on the left */
  56006. int r; /* Index of right-most cell in left sibling */
  56007. int d; /* Index of first cell to the left of right sibling */
  56008. r = cntNew[i-1] - 1;
  56009. d = r + 1 - leafData;
  56010. assert( d<nMaxCells );
  56011. assert( r<nMaxCells );
  56012. while( szRight==0
  56013. || (!bBulk && szRight+szCell[d]+2<=szLeft-(szCell[r]+2))
  56014. ){
  56015. szRight += szCell[d] + 2;
  56016. szLeft -= szCell[r] + 2;
  56017. cntNew[i-1]--;
  56018. r = cntNew[i-1] - 1;
  56019. d = r + 1 - leafData;
  56020. }
  56021. szNew[i] = szRight;
  56022. szNew[i-1] = szLeft;
  56023. }
  56024. /* Sanity check: For a non-corrupt database file one of the follwing
  56025. ** must be true:
  56026. ** (1) We found one or more cells (cntNew[0])>0), or
  56027. ** (2) pPage is a virtual root page. A virtual root page is when
  56028. ** the real root page is page 1 and we are the only child of
  56029. ** that page.
  56030. */
  56031. assert( cntNew[0]>0 || (pParent->pgno==1 && pParent->nCell==0) || CORRUPT_DB);
  56032. TRACE(("BALANCE: old: %d(nc=%d) %d(nc=%d) %d(nc=%d)\n",
  56033. apOld[0]->pgno, apOld[0]->nCell,
  56034. nOld>=2 ? apOld[1]->pgno : 0, nOld>=2 ? apOld[1]->nCell : 0,
  56035. nOld>=3 ? apOld[2]->pgno : 0, nOld>=3 ? apOld[2]->nCell : 0
  56036. ));
  56037. /*
  56038. ** Allocate k new pages. Reuse old pages where possible.
  56039. */
  56040. if( apOld[0]->pgno<=1 ){
  56041. rc = SQLITE_CORRUPT_BKPT;
  56042. goto balance_cleanup;
  56043. }
  56044. pageFlags = apOld[0]->aData[0];
  56045. for(i=0; i<k; i++){
  56046. MemPage *pNew;
  56047. if( i<nOld ){
  56048. pNew = apNew[i] = apOld[i];
  56049. apOld[i] = 0;
  56050. rc = sqlite3PagerWrite(pNew->pDbPage);
  56051. nNew++;
  56052. if( rc ) goto balance_cleanup;
  56053. }else{
  56054. assert( i>0 );
  56055. rc = allocateBtreePage(pBt, &pNew, &pgno, (bBulk ? 1 : pgno), 0);
  56056. if( rc ) goto balance_cleanup;
  56057. zeroPage(pNew, pageFlags);
  56058. apNew[i] = pNew;
  56059. nNew++;
  56060. cntOld[i] = nCell;
  56061. /* Set the pointer-map entry for the new sibling page. */
  56062. if( ISAUTOVACUUM ){
  56063. ptrmapPut(pBt, pNew->pgno, PTRMAP_BTREE, pParent->pgno, &rc);
  56064. if( rc!=SQLITE_OK ){
  56065. goto balance_cleanup;
  56066. }
  56067. }
  56068. }
  56069. }
  56070. /*
  56071. ** Reassign page numbers so that the new pages are in ascending order.
  56072. ** This helps to keep entries in the disk file in order so that a scan
  56073. ** of the table is closer to a linear scan through the file. That in turn
  56074. ** helps the operating system to deliver pages from the disk more rapidly.
  56075. **
  56076. ** An O(n^2) insertion sort algorithm is used, but since n is never more
  56077. ** than (NB+2) (a small constant), that should not be a problem.
  56078. **
  56079. ** When NB==3, this one optimization makes the database about 25% faster
  56080. ** for large insertions and deletions.
  56081. */
  56082. for(i=0; i<nNew; i++){
  56083. aPgOrder[i] = aPgno[i] = apNew[i]->pgno;
  56084. aPgFlags[i] = apNew[i]->pDbPage->flags;
  56085. for(j=0; j<i; j++){
  56086. if( aPgno[j]==aPgno[i] ){
  56087. /* This branch is taken if the set of sibling pages somehow contains
  56088. ** duplicate entries. This can happen if the database is corrupt.
  56089. ** It would be simpler to detect this as part of the loop below, but
  56090. ** we do the detection here in order to avoid populating the pager
  56091. ** cache with two separate objects associated with the same
  56092. ** page number. */
  56093. assert( CORRUPT_DB );
  56094. rc = SQLITE_CORRUPT_BKPT;
  56095. goto balance_cleanup;
  56096. }
  56097. }
  56098. }
  56099. for(i=0; i<nNew; i++){
  56100. int iBest = 0; /* aPgno[] index of page number to use */
  56101. for(j=1; j<nNew; j++){
  56102. if( aPgOrder[j]<aPgOrder[iBest] ) iBest = j;
  56103. }
  56104. pgno = aPgOrder[iBest];
  56105. aPgOrder[iBest] = 0xffffffff;
  56106. if( iBest!=i ){
  56107. if( iBest>i ){
  56108. sqlite3PagerRekey(apNew[iBest]->pDbPage, pBt->nPage+iBest+1, 0);
  56109. }
  56110. sqlite3PagerRekey(apNew[i]->pDbPage, pgno, aPgFlags[iBest]);
  56111. apNew[i]->pgno = pgno;
  56112. }
  56113. }
  56114. TRACE(("BALANCE: new: %d(%d nc=%d) %d(%d nc=%d) %d(%d nc=%d) "
  56115. "%d(%d nc=%d) %d(%d nc=%d)\n",
  56116. apNew[0]->pgno, szNew[0], cntNew[0],
  56117. nNew>=2 ? apNew[1]->pgno : 0, nNew>=2 ? szNew[1] : 0,
  56118. nNew>=2 ? cntNew[1] - cntNew[0] - !leafData : 0,
  56119. nNew>=3 ? apNew[2]->pgno : 0, nNew>=3 ? szNew[2] : 0,
  56120. nNew>=3 ? cntNew[2] - cntNew[1] - !leafData : 0,
  56121. nNew>=4 ? apNew[3]->pgno : 0, nNew>=4 ? szNew[3] : 0,
  56122. nNew>=4 ? cntNew[3] - cntNew[2] - !leafData : 0,
  56123. nNew>=5 ? apNew[4]->pgno : 0, nNew>=5 ? szNew[4] : 0,
  56124. nNew>=5 ? cntNew[4] - cntNew[3] - !leafData : 0
  56125. ));
  56126. assert( sqlite3PagerIswriteable(pParent->pDbPage) );
  56127. put4byte(pRight, apNew[nNew-1]->pgno);
  56128. /* If the sibling pages are not leaves, ensure that the right-child pointer
  56129. ** of the right-most new sibling page is set to the value that was
  56130. ** originally in the same field of the right-most old sibling page. */
  56131. if( (pageFlags & PTF_LEAF)==0 && nOld!=nNew ){
  56132. MemPage *pOld = (nNew>nOld ? apNew : apOld)[nOld-1];
  56133. memcpy(&apNew[nNew-1]->aData[8], &pOld->aData[8], 4);
  56134. }
  56135. /* Make any required updates to pointer map entries associated with
  56136. ** cells stored on sibling pages following the balance operation. Pointer
  56137. ** map entries associated with divider cells are set by the insertCell()
  56138. ** routine. The associated pointer map entries are:
  56139. **
  56140. ** a) if the cell contains a reference to an overflow chain, the
  56141. ** entry associated with the first page in the overflow chain, and
  56142. **
  56143. ** b) if the sibling pages are not leaves, the child page associated
  56144. ** with the cell.
  56145. **
  56146. ** If the sibling pages are not leaves, then the pointer map entry
  56147. ** associated with the right-child of each sibling may also need to be
  56148. ** updated. This happens below, after the sibling pages have been
  56149. ** populated, not here.
  56150. */
  56151. if( ISAUTOVACUUM ){
  56152. MemPage *pNew = apNew[0];
  56153. u8 *aOld = pNew->aData;
  56154. int cntOldNext = pNew->nCell + pNew->nOverflow;
  56155. int usableSize = pBt->usableSize;
  56156. int iNew = 0;
  56157. int iOld = 0;
  56158. for(i=0; i<nCell; i++){
  56159. u8 *pCell = apCell[i];
  56160. if( i==cntOldNext ){
  56161. MemPage *pOld = (++iOld)<nNew ? apNew[iOld] : apOld[iOld];
  56162. cntOldNext += pOld->nCell + pOld->nOverflow + !leafData;
  56163. aOld = pOld->aData;
  56164. }
  56165. if( i==cntNew[iNew] ){
  56166. pNew = apNew[++iNew];
  56167. if( !leafData ) continue;
  56168. }
  56169. /* Cell pCell is destined for new sibling page pNew. Originally, it
  56170. ** was either part of sibling page iOld (possibly an overflow cell),
  56171. ** or else the divider cell to the left of sibling page iOld. So,
  56172. ** if sibling page iOld had the same page number as pNew, and if
  56173. ** pCell really was a part of sibling page iOld (not a divider or
  56174. ** overflow cell), we can skip updating the pointer map entries. */
  56175. if( iOld>=nNew
  56176. || pNew->pgno!=aPgno[iOld]
  56177. || pCell<aOld
  56178. || pCell>=&aOld[usableSize]
  56179. ){
  56180. if( !leafCorrection ){
  56181. ptrmapPut(pBt, get4byte(pCell), PTRMAP_BTREE, pNew->pgno, &rc);
  56182. }
  56183. if( szCell[i]>pNew->minLocal ){
  56184. ptrmapPutOvflPtr(pNew, pCell, &rc);
  56185. }
  56186. }
  56187. }
  56188. }
  56189. /* Insert new divider cells into pParent. */
  56190. for(i=0; i<nNew-1; i++){
  56191. u8 *pCell;
  56192. u8 *pTemp;
  56193. int sz;
  56194. MemPage *pNew = apNew[i];
  56195. j = cntNew[i];
  56196. assert( j<nMaxCells );
  56197. pCell = apCell[j];
  56198. sz = szCell[j] + leafCorrection;
  56199. pTemp = &aOvflSpace[iOvflSpace];
  56200. if( !pNew->leaf ){
  56201. memcpy(&pNew->aData[8], pCell, 4);
  56202. }else if( leafData ){
  56203. /* If the tree is a leaf-data tree, and the siblings are leaves,
  56204. ** then there is no divider cell in apCell[]. Instead, the divider
  56205. ** cell consists of the integer key for the right-most cell of
  56206. ** the sibling-page assembled above only.
  56207. */
  56208. CellInfo info;
  56209. j--;
  56210. btreeParseCellPtr(pNew, apCell[j], &info);
  56211. pCell = pTemp;
  56212. sz = 4 + putVarint(&pCell[4], info.nKey);
  56213. pTemp = 0;
  56214. }else{
  56215. pCell -= 4;
  56216. /* Obscure case for non-leaf-data trees: If the cell at pCell was
  56217. ** previously stored on a leaf node, and its reported size was 4
  56218. ** bytes, then it may actually be smaller than this
  56219. ** (see btreeParseCellPtr(), 4 bytes is the minimum size of
  56220. ** any cell). But it is important to pass the correct size to
  56221. ** insertCell(), so reparse the cell now.
  56222. **
  56223. ** Note that this can never happen in an SQLite data file, as all
  56224. ** cells are at least 4 bytes. It only happens in b-trees used
  56225. ** to evaluate "IN (SELECT ...)" and similar clauses.
  56226. */
  56227. if( szCell[j]==4 ){
  56228. assert(leafCorrection==4);
  56229. sz = cellSizePtr(pParent, pCell);
  56230. }
  56231. }
  56232. iOvflSpace += sz;
  56233. assert( sz<=pBt->maxLocal+23 );
  56234. assert( iOvflSpace <= (int)pBt->pageSize );
  56235. insertCell(pParent, nxDiv+i, pCell, sz, pTemp, pNew->pgno, &rc);
  56236. if( rc!=SQLITE_OK ) goto balance_cleanup;
  56237. assert( sqlite3PagerIswriteable(pParent->pDbPage) );
  56238. }
  56239. /* Now update the actual sibling pages. The order in which they are updated
  56240. ** is important, as this code needs to avoid disrupting any page from which
  56241. ** cells may still to be read. In practice, this means:
  56242. **
  56243. ** (1) If cells are moving left (from apNew[iPg] to apNew[iPg-1])
  56244. ** then it is not safe to update page apNew[iPg] until after
  56245. ** the left-hand sibling apNew[iPg-1] has been updated.
  56246. **
  56247. ** (2) If cells are moving right (from apNew[iPg] to apNew[iPg+1])
  56248. ** then it is not safe to update page apNew[iPg] until after
  56249. ** the right-hand sibling apNew[iPg+1] has been updated.
  56250. **
  56251. ** If neither of the above apply, the page is safe to update.
  56252. **
  56253. ** The iPg value in the following loop starts at nNew-1 goes down
  56254. ** to 0, then back up to nNew-1 again, thus making two passes over
  56255. ** the pages. On the initial downward pass, only condition (1) above
  56256. ** needs to be tested because (2) will always be true from the previous
  56257. ** step. On the upward pass, both conditions are always true, so the
  56258. ** upwards pass simply processes pages that were missed on the downward
  56259. ** pass.
  56260. */
  56261. for(i=1-nNew; i<nNew; i++){
  56262. int iPg = i<0 ? -i : i;
  56263. assert( iPg>=0 && iPg<nNew );
  56264. if( abDone[iPg] ) continue; /* Skip pages already processed */
  56265. if( i>=0 /* On the upwards pass, or... */
  56266. || cntOld[iPg-1]>=cntNew[iPg-1] /* Condition (1) is true */
  56267. ){
  56268. int iNew;
  56269. int iOld;
  56270. int nNewCell;
  56271. /* Verify condition (1): If cells are moving left, update iPg
  56272. ** only after iPg-1 has already been updated. */
  56273. assert( iPg==0 || cntOld[iPg-1]>=cntNew[iPg-1] || abDone[iPg-1] );
  56274. /* Verify condition (2): If cells are moving right, update iPg
  56275. ** only after iPg+1 has already been updated. */
  56276. assert( cntNew[iPg]>=cntOld[iPg] || abDone[iPg+1] );
  56277. if( iPg==0 ){
  56278. iNew = iOld = 0;
  56279. nNewCell = cntNew[0];
  56280. }else{
  56281. iOld = iPg<nOld ? (cntOld[iPg-1] + !leafData) : nCell;
  56282. iNew = cntNew[iPg-1] + !leafData;
  56283. nNewCell = cntNew[iPg] - iNew;
  56284. }
  56285. editPage(apNew[iPg], iOld, iNew, nNewCell, apCell, szCell);
  56286. abDone[iPg]++;
  56287. apNew[iPg]->nFree = usableSpace-szNew[iPg];
  56288. assert( apNew[iPg]->nOverflow==0 );
  56289. assert( apNew[iPg]->nCell==nNewCell );
  56290. }
  56291. }
  56292. /* All pages have been processed exactly once */
  56293. assert( memcmp(abDone, "\01\01\01\01\01", nNew)==0 );
  56294. assert( nOld>0 );
  56295. assert( nNew>0 );
  56296. if( isRoot && pParent->nCell==0 && pParent->hdrOffset<=apNew[0]->nFree ){
  56297. /* The root page of the b-tree now contains no cells. The only sibling
  56298. ** page is the right-child of the parent. Copy the contents of the
  56299. ** child page into the parent, decreasing the overall height of the
  56300. ** b-tree structure by one. This is described as the "balance-shallower"
  56301. ** sub-algorithm in some documentation.
  56302. **
  56303. ** If this is an auto-vacuum database, the call to copyNodeContent()
  56304. ** sets all pointer-map entries corresponding to database image pages
  56305. ** for which the pointer is stored within the content being copied.
  56306. **
  56307. ** It is critical that the child page be defragmented before being
  56308. ** copied into the parent, because if the parent is page 1 then it will
  56309. ** by smaller than the child due to the database header, and so all the
  56310. ** free space needs to be up front.
  56311. */
  56312. assert( nNew==1 );
  56313. rc = defragmentPage(apNew[0]);
  56314. testcase( rc!=SQLITE_OK );
  56315. assert( apNew[0]->nFree ==
  56316. (get2byte(&apNew[0]->aData[5])-apNew[0]->cellOffset-apNew[0]->nCell*2)
  56317. || rc!=SQLITE_OK
  56318. );
  56319. copyNodeContent(apNew[0], pParent, &rc);
  56320. freePage(apNew[0], &rc);
  56321. }else if( ISAUTOVACUUM && !leafCorrection ){
  56322. /* Fix the pointer map entries associated with the right-child of each
  56323. ** sibling page. All other pointer map entries have already been taken
  56324. ** care of. */
  56325. for(i=0; i<nNew; i++){
  56326. u32 key = get4byte(&apNew[i]->aData[8]);
  56327. ptrmapPut(pBt, key, PTRMAP_BTREE, apNew[i]->pgno, &rc);
  56328. }
  56329. }
  56330. assert( pParent->isInit );
  56331. TRACE(("BALANCE: finished: old=%d new=%d cells=%d\n",
  56332. nOld, nNew, nCell));
  56333. /* Free any old pages that were not reused as new pages.
  56334. */
  56335. for(i=nNew; i<nOld; i++){
  56336. freePage(apOld[i], &rc);
  56337. }
  56338. #if 0
  56339. if( ISAUTOVACUUM && rc==SQLITE_OK && apNew[0]->isInit ){
  56340. /* The ptrmapCheckPages() contains assert() statements that verify that
  56341. ** all pointer map pages are set correctly. This is helpful while
  56342. ** debugging. This is usually disabled because a corrupt database may
  56343. ** cause an assert() statement to fail. */
  56344. ptrmapCheckPages(apNew, nNew);
  56345. ptrmapCheckPages(&pParent, 1);
  56346. }
  56347. #endif
  56348. /*
  56349. ** Cleanup before returning.
  56350. */
  56351. balance_cleanup:
  56352. sqlite3ScratchFree(apCell);
  56353. for(i=0; i<nOld; i++){
  56354. releasePage(apOld[i]);
  56355. }
  56356. for(i=0; i<nNew; i++){
  56357. releasePage(apNew[i]);
  56358. }
  56359. return rc;
  56360. }
  56361. #if defined(_MSC_VER) && _MSC_VER >= 1700 && defined(_M_ARM)
  56362. #pragma optimize("", on)
  56363. #endif
  56364. /*
  56365. ** This function is called when the root page of a b-tree structure is
  56366. ** overfull (has one or more overflow pages).
  56367. **
  56368. ** A new child page is allocated and the contents of the current root
  56369. ** page, including overflow cells, are copied into the child. The root
  56370. ** page is then overwritten to make it an empty page with the right-child
  56371. ** pointer pointing to the new page.
  56372. **
  56373. ** Before returning, all pointer-map entries corresponding to pages
  56374. ** that the new child-page now contains pointers to are updated. The
  56375. ** entry corresponding to the new right-child pointer of the root
  56376. ** page is also updated.
  56377. **
  56378. ** If successful, *ppChild is set to contain a reference to the child
  56379. ** page and SQLITE_OK is returned. In this case the caller is required
  56380. ** to call releasePage() on *ppChild exactly once. If an error occurs,
  56381. ** an error code is returned and *ppChild is set to 0.
  56382. */
  56383. static int balance_deeper(MemPage *pRoot, MemPage **ppChild){
  56384. int rc; /* Return value from subprocedures */
  56385. MemPage *pChild = 0; /* Pointer to a new child page */
  56386. Pgno pgnoChild = 0; /* Page number of the new child page */
  56387. BtShared *pBt = pRoot->pBt; /* The BTree */
  56388. assert( pRoot->nOverflow>0 );
  56389. assert( sqlite3_mutex_held(pBt->mutex) );
  56390. /* Make pRoot, the root page of the b-tree, writable. Allocate a new
  56391. ** page that will become the new right-child of pPage. Copy the contents
  56392. ** of the node stored on pRoot into the new child page.
  56393. */
  56394. rc = sqlite3PagerWrite(pRoot->pDbPage);
  56395. if( rc==SQLITE_OK ){
  56396. rc = allocateBtreePage(pBt,&pChild,&pgnoChild,pRoot->pgno,0);
  56397. copyNodeContent(pRoot, pChild, &rc);
  56398. if( ISAUTOVACUUM ){
  56399. ptrmapPut(pBt, pgnoChild, PTRMAP_BTREE, pRoot->pgno, &rc);
  56400. }
  56401. }
  56402. if( rc ){
  56403. *ppChild = 0;
  56404. releasePage(pChild);
  56405. return rc;
  56406. }
  56407. assert( sqlite3PagerIswriteable(pChild->pDbPage) );
  56408. assert( sqlite3PagerIswriteable(pRoot->pDbPage) );
  56409. assert( pChild->nCell==pRoot->nCell );
  56410. TRACE(("BALANCE: copy root %d into %d\n", pRoot->pgno, pChild->pgno));
  56411. /* Copy the overflow cells from pRoot to pChild */
  56412. memcpy(pChild->aiOvfl, pRoot->aiOvfl,
  56413. pRoot->nOverflow*sizeof(pRoot->aiOvfl[0]));
  56414. memcpy(pChild->apOvfl, pRoot->apOvfl,
  56415. pRoot->nOverflow*sizeof(pRoot->apOvfl[0]));
  56416. pChild->nOverflow = pRoot->nOverflow;
  56417. /* Zero the contents of pRoot. Then install pChild as the right-child. */
  56418. zeroPage(pRoot, pChild->aData[0] & ~PTF_LEAF);
  56419. put4byte(&pRoot->aData[pRoot->hdrOffset+8], pgnoChild);
  56420. *ppChild = pChild;
  56421. return SQLITE_OK;
  56422. }
  56423. /*
  56424. ** The page that pCur currently points to has just been modified in
  56425. ** some way. This function figures out if this modification means the
  56426. ** tree needs to be balanced, and if so calls the appropriate balancing
  56427. ** routine. Balancing routines are:
  56428. **
  56429. ** balance_quick()
  56430. ** balance_deeper()
  56431. ** balance_nonroot()
  56432. */
  56433. static int balance(BtCursor *pCur){
  56434. int rc = SQLITE_OK;
  56435. const int nMin = pCur->pBt->usableSize * 2 / 3;
  56436. u8 aBalanceQuickSpace[13];
  56437. u8 *pFree = 0;
  56438. TESTONLY( int balance_quick_called = 0 );
  56439. TESTONLY( int balance_deeper_called = 0 );
  56440. do {
  56441. int iPage = pCur->iPage;
  56442. MemPage *pPage = pCur->apPage[iPage];
  56443. if( iPage==0 ){
  56444. if( pPage->nOverflow ){
  56445. /* The root page of the b-tree is overfull. In this case call the
  56446. ** balance_deeper() function to create a new child for the root-page
  56447. ** and copy the current contents of the root-page to it. The
  56448. ** next iteration of the do-loop will balance the child page.
  56449. */
  56450. assert( (balance_deeper_called++)==0 );
  56451. rc = balance_deeper(pPage, &pCur->apPage[1]);
  56452. if( rc==SQLITE_OK ){
  56453. pCur->iPage = 1;
  56454. pCur->aiIdx[0] = 0;
  56455. pCur->aiIdx[1] = 0;
  56456. assert( pCur->apPage[1]->nOverflow );
  56457. }
  56458. }else{
  56459. break;
  56460. }
  56461. }else if( pPage->nOverflow==0 && pPage->nFree<=nMin ){
  56462. break;
  56463. }else{
  56464. MemPage * const pParent = pCur->apPage[iPage-1];
  56465. int const iIdx = pCur->aiIdx[iPage-1];
  56466. rc = sqlite3PagerWrite(pParent->pDbPage);
  56467. if( rc==SQLITE_OK ){
  56468. #ifndef SQLITE_OMIT_QUICKBALANCE
  56469. if( pPage->intKeyLeaf
  56470. && pPage->nOverflow==1
  56471. && pPage->aiOvfl[0]==pPage->nCell
  56472. && pParent->pgno!=1
  56473. && pParent->nCell==iIdx
  56474. ){
  56475. /* Call balance_quick() to create a new sibling of pPage on which
  56476. ** to store the overflow cell. balance_quick() inserts a new cell
  56477. ** into pParent, which may cause pParent overflow. If this
  56478. ** happens, the next iteration of the do-loop will balance pParent
  56479. ** use either balance_nonroot() or balance_deeper(). Until this
  56480. ** happens, the overflow cell is stored in the aBalanceQuickSpace[]
  56481. ** buffer.
  56482. **
  56483. ** The purpose of the following assert() is to check that only a
  56484. ** single call to balance_quick() is made for each call to this
  56485. ** function. If this were not verified, a subtle bug involving reuse
  56486. ** of the aBalanceQuickSpace[] might sneak in.
  56487. */
  56488. assert( (balance_quick_called++)==0 );
  56489. rc = balance_quick(pParent, pPage, aBalanceQuickSpace);
  56490. }else
  56491. #endif
  56492. {
  56493. /* In this case, call balance_nonroot() to redistribute cells
  56494. ** between pPage and up to 2 of its sibling pages. This involves
  56495. ** modifying the contents of pParent, which may cause pParent to
  56496. ** become overfull or underfull. The next iteration of the do-loop
  56497. ** will balance the parent page to correct this.
  56498. **
  56499. ** If the parent page becomes overfull, the overflow cell or cells
  56500. ** are stored in the pSpace buffer allocated immediately below.
  56501. ** A subsequent iteration of the do-loop will deal with this by
  56502. ** calling balance_nonroot() (balance_deeper() may be called first,
  56503. ** but it doesn't deal with overflow cells - just moves them to a
  56504. ** different page). Once this subsequent call to balance_nonroot()
  56505. ** has completed, it is safe to release the pSpace buffer used by
  56506. ** the previous call, as the overflow cell data will have been
  56507. ** copied either into the body of a database page or into the new
  56508. ** pSpace buffer passed to the latter call to balance_nonroot().
  56509. */
  56510. u8 *pSpace = sqlite3PageMalloc(pCur->pBt->pageSize);
  56511. rc = balance_nonroot(pParent, iIdx, pSpace, iPage==1,
  56512. pCur->hints&BTREE_BULKLOAD);
  56513. if( pFree ){
  56514. /* If pFree is not NULL, it points to the pSpace buffer used
  56515. ** by a previous call to balance_nonroot(). Its contents are
  56516. ** now stored either on real database pages or within the
  56517. ** new pSpace buffer, so it may be safely freed here. */
  56518. sqlite3PageFree(pFree);
  56519. }
  56520. /* The pSpace buffer will be freed after the next call to
  56521. ** balance_nonroot(), or just before this function returns, whichever
  56522. ** comes first. */
  56523. pFree = pSpace;
  56524. }
  56525. }
  56526. pPage->nOverflow = 0;
  56527. /* The next iteration of the do-loop balances the parent page. */
  56528. releasePage(pPage);
  56529. pCur->iPage--;
  56530. assert( pCur->iPage>=0 );
  56531. }
  56532. }while( rc==SQLITE_OK );
  56533. if( pFree ){
  56534. sqlite3PageFree(pFree);
  56535. }
  56536. return rc;
  56537. }
  56538. /*
  56539. ** Insert a new record into the BTree. The key is given by (pKey,nKey)
  56540. ** and the data is given by (pData,nData). The cursor is used only to
  56541. ** define what table the record should be inserted into. The cursor
  56542. ** is left pointing at a random location.
  56543. **
  56544. ** For an INTKEY table, only the nKey value of the key is used. pKey is
  56545. ** ignored. For a ZERODATA table, the pData and nData are both ignored.
  56546. **
  56547. ** If the seekResult parameter is non-zero, then a successful call to
  56548. ** MovetoUnpacked() to seek cursor pCur to (pKey, nKey) has already
  56549. ** been performed. seekResult is the search result returned (a negative
  56550. ** number if pCur points at an entry that is smaller than (pKey, nKey), or
  56551. ** a positive value if pCur points at an entry that is larger than
  56552. ** (pKey, nKey)).
  56553. **
  56554. ** If the seekResult parameter is non-zero, then the caller guarantees that
  56555. ** cursor pCur is pointing at the existing copy of a row that is to be
  56556. ** overwritten. If the seekResult parameter is 0, then cursor pCur may
  56557. ** point to any entry or to no entry at all and so this function has to seek
  56558. ** the cursor before the new key can be inserted.
  56559. */
  56560. SQLITE_PRIVATE int sqlite3BtreeInsert(
  56561. BtCursor *pCur, /* Insert data into the table of this cursor */
  56562. const void *pKey, i64 nKey, /* The key of the new record */
  56563. const void *pData, int nData, /* The data of the new record */
  56564. int nZero, /* Number of extra 0 bytes to append to data */
  56565. int appendBias, /* True if this is likely an append */
  56566. int seekResult /* Result of prior MovetoUnpacked() call */
  56567. ){
  56568. int rc;
  56569. int loc = seekResult; /* -1: before desired location +1: after */
  56570. int szNew = 0;
  56571. int idx;
  56572. MemPage *pPage;
  56573. Btree *p = pCur->pBtree;
  56574. BtShared *pBt = p->pBt;
  56575. unsigned char *oldCell;
  56576. unsigned char *newCell = 0;
  56577. if( pCur->eState==CURSOR_FAULT ){
  56578. assert( pCur->skipNext!=SQLITE_OK );
  56579. return pCur->skipNext;
  56580. }
  56581. assert( cursorHoldsMutex(pCur) );
  56582. assert( (pCur->curFlags & BTCF_WriteFlag)!=0
  56583. && pBt->inTransaction==TRANS_WRITE
  56584. && (pBt->btsFlags & BTS_READ_ONLY)==0 );
  56585. assert( hasSharedCacheTableLock(p, pCur->pgnoRoot, pCur->pKeyInfo!=0, 2) );
  56586. /* Assert that the caller has been consistent. If this cursor was opened
  56587. ** expecting an index b-tree, then the caller should be inserting blob
  56588. ** keys with no associated data. If the cursor was opened expecting an
  56589. ** intkey table, the caller should be inserting integer keys with a
  56590. ** blob of associated data. */
  56591. assert( (pKey==0)==(pCur->pKeyInfo==0) );
  56592. /* Save the positions of any other cursors open on this table.
  56593. **
  56594. ** In some cases, the call to btreeMoveto() below is a no-op. For
  56595. ** example, when inserting data into a table with auto-generated integer
  56596. ** keys, the VDBE layer invokes sqlite3BtreeLast() to figure out the
  56597. ** integer key to use. It then calls this function to actually insert the
  56598. ** data into the intkey B-Tree. In this case btreeMoveto() recognizes
  56599. ** that the cursor is already where it needs to be and returns without
  56600. ** doing any work. To avoid thwarting these optimizations, it is important
  56601. ** not to clear the cursor here.
  56602. */
  56603. rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur);
  56604. if( rc ) return rc;
  56605. if( pCur->pKeyInfo==0 ){
  56606. /* If this is an insert into a table b-tree, invalidate any incrblob
  56607. ** cursors open on the row being replaced */
  56608. invalidateIncrblobCursors(p, nKey, 0);
  56609. /* If the cursor is currently on the last row and we are appending a
  56610. ** new row onto the end, set the "loc" to avoid an unnecessary btreeMoveto()
  56611. ** call */
  56612. if( (pCur->curFlags&BTCF_ValidNKey)!=0 && nKey>0
  56613. && pCur->info.nKey==nKey-1 ){
  56614. loc = -1;
  56615. }
  56616. }
  56617. if( !loc ){
  56618. rc = btreeMoveto(pCur, pKey, nKey, appendBias, &loc);
  56619. if( rc ) return rc;
  56620. }
  56621. assert( pCur->eState==CURSOR_VALID || (pCur->eState==CURSOR_INVALID && loc) );
  56622. pPage = pCur->apPage[pCur->iPage];
  56623. assert( pPage->intKey || nKey>=0 );
  56624. assert( pPage->leaf || !pPage->intKey );
  56625. TRACE(("INSERT: table=%d nkey=%lld ndata=%d page=%d %s\n",
  56626. pCur->pgnoRoot, nKey, nData, pPage->pgno,
  56627. loc==0 ? "overwrite" : "new entry"));
  56628. assert( pPage->isInit );
  56629. newCell = pBt->pTmpSpace;
  56630. assert( newCell!=0 );
  56631. rc = fillInCell(pPage, newCell, pKey, nKey, pData, nData, nZero, &szNew);
  56632. if( rc ) goto end_insert;
  56633. assert( szNew==cellSizePtr(pPage, newCell) );
  56634. assert( szNew <= MX_CELL_SIZE(pBt) );
  56635. idx = pCur->aiIdx[pCur->iPage];
  56636. if( loc==0 ){
  56637. u16 szOld;
  56638. assert( idx<pPage->nCell );
  56639. rc = sqlite3PagerWrite(pPage->pDbPage);
  56640. if( rc ){
  56641. goto end_insert;
  56642. }
  56643. oldCell = findCell(pPage, idx);
  56644. if( !pPage->leaf ){
  56645. memcpy(newCell, oldCell, 4);
  56646. }
  56647. rc = clearCell(pPage, oldCell, &szOld);
  56648. dropCell(pPage, idx, szOld, &rc);
  56649. if( rc ) goto end_insert;
  56650. }else if( loc<0 && pPage->nCell>0 ){
  56651. assert( pPage->leaf );
  56652. idx = ++pCur->aiIdx[pCur->iPage];
  56653. }else{
  56654. assert( pPage->leaf );
  56655. }
  56656. insertCell(pPage, idx, newCell, szNew, 0, 0, &rc);
  56657. assert( rc!=SQLITE_OK || pPage->nCell>0 || pPage->nOverflow>0 );
  56658. /* If no error has occurred and pPage has an overflow cell, call balance()
  56659. ** to redistribute the cells within the tree. Since balance() may move
  56660. ** the cursor, zero the BtCursor.info.nSize and BTCF_ValidNKey
  56661. ** variables.
  56662. **
  56663. ** Previous versions of SQLite called moveToRoot() to move the cursor
  56664. ** back to the root page as balance() used to invalidate the contents
  56665. ** of BtCursor.apPage[] and BtCursor.aiIdx[]. Instead of doing that,
  56666. ** set the cursor state to "invalid". This makes common insert operations
  56667. ** slightly faster.
  56668. **
  56669. ** There is a subtle but important optimization here too. When inserting
  56670. ** multiple records into an intkey b-tree using a single cursor (as can
  56671. ** happen while processing an "INSERT INTO ... SELECT" statement), it
  56672. ** is advantageous to leave the cursor pointing to the last entry in
  56673. ** the b-tree if possible. If the cursor is left pointing to the last
  56674. ** entry in the table, and the next row inserted has an integer key
  56675. ** larger than the largest existing key, it is possible to insert the
  56676. ** row without seeking the cursor. This can be a big performance boost.
  56677. */
  56678. pCur->info.nSize = 0;
  56679. if( rc==SQLITE_OK && pPage->nOverflow ){
  56680. pCur->curFlags &= ~(BTCF_ValidNKey);
  56681. rc = balance(pCur);
  56682. /* Must make sure nOverflow is reset to zero even if the balance()
  56683. ** fails. Internal data structure corruption will result otherwise.
  56684. ** Also, set the cursor state to invalid. This stops saveCursorPosition()
  56685. ** from trying to save the current position of the cursor. */
  56686. pCur->apPage[pCur->iPage]->nOverflow = 0;
  56687. pCur->eState = CURSOR_INVALID;
  56688. }
  56689. assert( pCur->apPage[pCur->iPage]->nOverflow==0 );
  56690. end_insert:
  56691. return rc;
  56692. }
  56693. /*
  56694. ** Delete the entry that the cursor is pointing to. The cursor
  56695. ** is left pointing at an arbitrary location.
  56696. */
  56697. SQLITE_PRIVATE int sqlite3BtreeDelete(BtCursor *pCur){
  56698. Btree *p = pCur->pBtree;
  56699. BtShared *pBt = p->pBt;
  56700. int rc; /* Return code */
  56701. MemPage *pPage; /* Page to delete cell from */
  56702. unsigned char *pCell; /* Pointer to cell to delete */
  56703. int iCellIdx; /* Index of cell to delete */
  56704. int iCellDepth; /* Depth of node containing pCell */
  56705. u16 szCell; /* Size of the cell being deleted */
  56706. assert( cursorHoldsMutex(pCur) );
  56707. assert( pBt->inTransaction==TRANS_WRITE );
  56708. assert( (pBt->btsFlags & BTS_READ_ONLY)==0 );
  56709. assert( pCur->curFlags & BTCF_WriteFlag );
  56710. assert( hasSharedCacheTableLock(p, pCur->pgnoRoot, pCur->pKeyInfo!=0, 2) );
  56711. assert( !hasReadConflicts(p, pCur->pgnoRoot) );
  56712. if( NEVER(pCur->aiIdx[pCur->iPage]>=pCur->apPage[pCur->iPage]->nCell)
  56713. || NEVER(pCur->eState!=CURSOR_VALID)
  56714. ){
  56715. return SQLITE_ERROR; /* Something has gone awry. */
  56716. }
  56717. iCellDepth = pCur->iPage;
  56718. iCellIdx = pCur->aiIdx[iCellDepth];
  56719. pPage = pCur->apPage[iCellDepth];
  56720. pCell = findCell(pPage, iCellIdx);
  56721. /* If the page containing the entry to delete is not a leaf page, move
  56722. ** the cursor to the largest entry in the tree that is smaller than
  56723. ** the entry being deleted. This cell will replace the cell being deleted
  56724. ** from the internal node. The 'previous' entry is used for this instead
  56725. ** of the 'next' entry, as the previous entry is always a part of the
  56726. ** sub-tree headed by the child page of the cell being deleted. This makes
  56727. ** balancing the tree following the delete operation easier. */
  56728. if( !pPage->leaf ){
  56729. int notUsed = 0;
  56730. rc = sqlite3BtreePrevious(pCur, &notUsed);
  56731. if( rc ) return rc;
  56732. }
  56733. /* Save the positions of any other cursors open on this table before
  56734. ** making any modifications. Make the page containing the entry to be
  56735. ** deleted writable. Then free any overflow pages associated with the
  56736. ** entry and finally remove the cell itself from within the page.
  56737. */
  56738. rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur);
  56739. if( rc ) return rc;
  56740. /* If this is a delete operation to remove a row from a table b-tree,
  56741. ** invalidate any incrblob cursors open on the row being deleted. */
  56742. if( pCur->pKeyInfo==0 ){
  56743. invalidateIncrblobCursors(p, pCur->info.nKey, 0);
  56744. }
  56745. rc = sqlite3PagerWrite(pPage->pDbPage);
  56746. if( rc ) return rc;
  56747. rc = clearCell(pPage, pCell, &szCell);
  56748. dropCell(pPage, iCellIdx, szCell, &rc);
  56749. if( rc ) return rc;
  56750. /* If the cell deleted was not located on a leaf page, then the cursor
  56751. ** is currently pointing to the largest entry in the sub-tree headed
  56752. ** by the child-page of the cell that was just deleted from an internal
  56753. ** node. The cell from the leaf node needs to be moved to the internal
  56754. ** node to replace the deleted cell. */
  56755. if( !pPage->leaf ){
  56756. MemPage *pLeaf = pCur->apPage[pCur->iPage];
  56757. int nCell;
  56758. Pgno n = pCur->apPage[iCellDepth+1]->pgno;
  56759. unsigned char *pTmp;
  56760. pCell = findCell(pLeaf, pLeaf->nCell-1);
  56761. nCell = cellSizePtr(pLeaf, pCell);
  56762. assert( MX_CELL_SIZE(pBt) >= nCell );
  56763. pTmp = pBt->pTmpSpace;
  56764. assert( pTmp!=0 );
  56765. rc = sqlite3PagerWrite(pLeaf->pDbPage);
  56766. insertCell(pPage, iCellIdx, pCell-4, nCell+4, pTmp, n, &rc);
  56767. dropCell(pLeaf, pLeaf->nCell-1, nCell, &rc);
  56768. if( rc ) return rc;
  56769. }
  56770. /* Balance the tree. If the entry deleted was located on a leaf page,
  56771. ** then the cursor still points to that page. In this case the first
  56772. ** call to balance() repairs the tree, and the if(...) condition is
  56773. ** never true.
  56774. **
  56775. ** Otherwise, if the entry deleted was on an internal node page, then
  56776. ** pCur is pointing to the leaf page from which a cell was removed to
  56777. ** replace the cell deleted from the internal node. This is slightly
  56778. ** tricky as the leaf node may be underfull, and the internal node may
  56779. ** be either under or overfull. In this case run the balancing algorithm
  56780. ** on the leaf node first. If the balance proceeds far enough up the
  56781. ** tree that we can be sure that any problem in the internal node has
  56782. ** been corrected, so be it. Otherwise, after balancing the leaf node,
  56783. ** walk the cursor up the tree to the internal node and balance it as
  56784. ** well. */
  56785. rc = balance(pCur);
  56786. if( rc==SQLITE_OK && pCur->iPage>iCellDepth ){
  56787. while( pCur->iPage>iCellDepth ){
  56788. releasePage(pCur->apPage[pCur->iPage--]);
  56789. }
  56790. rc = balance(pCur);
  56791. }
  56792. if( rc==SQLITE_OK ){
  56793. moveToRoot(pCur);
  56794. }
  56795. return rc;
  56796. }
  56797. /*
  56798. ** Create a new BTree table. Write into *piTable the page
  56799. ** number for the root page of the new table.
  56800. **
  56801. ** The type of type is determined by the flags parameter. Only the
  56802. ** following values of flags are currently in use. Other values for
  56803. ** flags might not work:
  56804. **
  56805. ** BTREE_INTKEY|BTREE_LEAFDATA Used for SQL tables with rowid keys
  56806. ** BTREE_ZERODATA Used for SQL indices
  56807. */
  56808. static int btreeCreateTable(Btree *p, int *piTable, int createTabFlags){
  56809. BtShared *pBt = p->pBt;
  56810. MemPage *pRoot;
  56811. Pgno pgnoRoot;
  56812. int rc;
  56813. int ptfFlags; /* Page-type flage for the root page of new table */
  56814. assert( sqlite3BtreeHoldsMutex(p) );
  56815. assert( pBt->inTransaction==TRANS_WRITE );
  56816. assert( (pBt->btsFlags & BTS_READ_ONLY)==0 );
  56817. #ifdef SQLITE_OMIT_AUTOVACUUM
  56818. rc = allocateBtreePage(pBt, &pRoot, &pgnoRoot, 1, 0);
  56819. if( rc ){
  56820. return rc;
  56821. }
  56822. #else
  56823. if( pBt->autoVacuum ){
  56824. Pgno pgnoMove; /* Move a page here to make room for the root-page */
  56825. MemPage *pPageMove; /* The page to move to. */
  56826. /* Creating a new table may probably require moving an existing database
  56827. ** to make room for the new tables root page. In case this page turns
  56828. ** out to be an overflow page, delete all overflow page-map caches
  56829. ** held by open cursors.
  56830. */
  56831. invalidateAllOverflowCache(pBt);
  56832. /* Read the value of meta[3] from the database to determine where the
  56833. ** root page of the new table should go. meta[3] is the largest root-page
  56834. ** created so far, so the new root-page is (meta[3]+1).
  56835. */
  56836. sqlite3BtreeGetMeta(p, BTREE_LARGEST_ROOT_PAGE, &pgnoRoot);
  56837. pgnoRoot++;
  56838. /* The new root-page may not be allocated on a pointer-map page, or the
  56839. ** PENDING_BYTE page.
  56840. */
  56841. while( pgnoRoot==PTRMAP_PAGENO(pBt, pgnoRoot) ||
  56842. pgnoRoot==PENDING_BYTE_PAGE(pBt) ){
  56843. pgnoRoot++;
  56844. }
  56845. assert( pgnoRoot>=3 );
  56846. /* Allocate a page. The page that currently resides at pgnoRoot will
  56847. ** be moved to the allocated page (unless the allocated page happens
  56848. ** to reside at pgnoRoot).
  56849. */
  56850. rc = allocateBtreePage(pBt, &pPageMove, &pgnoMove, pgnoRoot, BTALLOC_EXACT);
  56851. if( rc!=SQLITE_OK ){
  56852. return rc;
  56853. }
  56854. if( pgnoMove!=pgnoRoot ){
  56855. /* pgnoRoot is the page that will be used for the root-page of
  56856. ** the new table (assuming an error did not occur). But we were
  56857. ** allocated pgnoMove. If required (i.e. if it was not allocated
  56858. ** by extending the file), the current page at position pgnoMove
  56859. ** is already journaled.
  56860. */
  56861. u8 eType = 0;
  56862. Pgno iPtrPage = 0;
  56863. /* Save the positions of any open cursors. This is required in
  56864. ** case they are holding a reference to an xFetch reference
  56865. ** corresponding to page pgnoRoot. */
  56866. rc = saveAllCursors(pBt, 0, 0);
  56867. releasePage(pPageMove);
  56868. if( rc!=SQLITE_OK ){
  56869. return rc;
  56870. }
  56871. /* Move the page currently at pgnoRoot to pgnoMove. */
  56872. rc = btreeGetPage(pBt, pgnoRoot, &pRoot, 0);
  56873. if( rc!=SQLITE_OK ){
  56874. return rc;
  56875. }
  56876. rc = ptrmapGet(pBt, pgnoRoot, &eType, &iPtrPage);
  56877. if( eType==PTRMAP_ROOTPAGE || eType==PTRMAP_FREEPAGE ){
  56878. rc = SQLITE_CORRUPT_BKPT;
  56879. }
  56880. if( rc!=SQLITE_OK ){
  56881. releasePage(pRoot);
  56882. return rc;
  56883. }
  56884. assert( eType!=PTRMAP_ROOTPAGE );
  56885. assert( eType!=PTRMAP_FREEPAGE );
  56886. rc = relocatePage(pBt, pRoot, eType, iPtrPage, pgnoMove, 0);
  56887. releasePage(pRoot);
  56888. /* Obtain the page at pgnoRoot */
  56889. if( rc!=SQLITE_OK ){
  56890. return rc;
  56891. }
  56892. rc = btreeGetPage(pBt, pgnoRoot, &pRoot, 0);
  56893. if( rc!=SQLITE_OK ){
  56894. return rc;
  56895. }
  56896. rc = sqlite3PagerWrite(pRoot->pDbPage);
  56897. if( rc!=SQLITE_OK ){
  56898. releasePage(pRoot);
  56899. return rc;
  56900. }
  56901. }else{
  56902. pRoot = pPageMove;
  56903. }
  56904. /* Update the pointer-map and meta-data with the new root-page number. */
  56905. ptrmapPut(pBt, pgnoRoot, PTRMAP_ROOTPAGE, 0, &rc);
  56906. if( rc ){
  56907. releasePage(pRoot);
  56908. return rc;
  56909. }
  56910. /* When the new root page was allocated, page 1 was made writable in
  56911. ** order either to increase the database filesize, or to decrement the
  56912. ** freelist count. Hence, the sqlite3BtreeUpdateMeta() call cannot fail.
  56913. */
  56914. assert( sqlite3PagerIswriteable(pBt->pPage1->pDbPage) );
  56915. rc = sqlite3BtreeUpdateMeta(p, 4, pgnoRoot);
  56916. if( NEVER(rc) ){
  56917. releasePage(pRoot);
  56918. return rc;
  56919. }
  56920. }else{
  56921. rc = allocateBtreePage(pBt, &pRoot, &pgnoRoot, 1, 0);
  56922. if( rc ) return rc;
  56923. }
  56924. #endif
  56925. assert( sqlite3PagerIswriteable(pRoot->pDbPage) );
  56926. if( createTabFlags & BTREE_INTKEY ){
  56927. ptfFlags = PTF_INTKEY | PTF_LEAFDATA | PTF_LEAF;
  56928. }else{
  56929. ptfFlags = PTF_ZERODATA | PTF_LEAF;
  56930. }
  56931. zeroPage(pRoot, ptfFlags);
  56932. sqlite3PagerUnref(pRoot->pDbPage);
  56933. assert( (pBt->openFlags & BTREE_SINGLE)==0 || pgnoRoot==2 );
  56934. *piTable = (int)pgnoRoot;
  56935. return SQLITE_OK;
  56936. }
  56937. SQLITE_PRIVATE int sqlite3BtreeCreateTable(Btree *p, int *piTable, int flags){
  56938. int rc;
  56939. sqlite3BtreeEnter(p);
  56940. rc = btreeCreateTable(p, piTable, flags);
  56941. sqlite3BtreeLeave(p);
  56942. return rc;
  56943. }
  56944. /*
  56945. ** Erase the given database page and all its children. Return
  56946. ** the page to the freelist.
  56947. */
  56948. static int clearDatabasePage(
  56949. BtShared *pBt, /* The BTree that contains the table */
  56950. Pgno pgno, /* Page number to clear */
  56951. int freePageFlag, /* Deallocate page if true */
  56952. int *pnChange /* Add number of Cells freed to this counter */
  56953. ){
  56954. MemPage *pPage;
  56955. int rc;
  56956. unsigned char *pCell;
  56957. int i;
  56958. int hdr;
  56959. u16 szCell;
  56960. assert( sqlite3_mutex_held(pBt->mutex) );
  56961. if( pgno>btreePagecount(pBt) ){
  56962. return SQLITE_CORRUPT_BKPT;
  56963. }
  56964. rc = getAndInitPage(pBt, pgno, &pPage, 0);
  56965. if( rc ) return rc;
  56966. if( pPage->bBusy ){
  56967. rc = SQLITE_CORRUPT_BKPT;
  56968. goto cleardatabasepage_out;
  56969. }
  56970. pPage->bBusy = 1;
  56971. hdr = pPage->hdrOffset;
  56972. for(i=0; i<pPage->nCell; i++){
  56973. pCell = findCell(pPage, i);
  56974. if( !pPage->leaf ){
  56975. rc = clearDatabasePage(pBt, get4byte(pCell), 1, pnChange);
  56976. if( rc ) goto cleardatabasepage_out;
  56977. }
  56978. rc = clearCell(pPage, pCell, &szCell);
  56979. if( rc ) goto cleardatabasepage_out;
  56980. }
  56981. if( !pPage->leaf ){
  56982. rc = clearDatabasePage(pBt, get4byte(&pPage->aData[hdr+8]), 1, pnChange);
  56983. if( rc ) goto cleardatabasepage_out;
  56984. }else if( pnChange ){
  56985. assert( pPage->intKey );
  56986. *pnChange += pPage->nCell;
  56987. }
  56988. if( freePageFlag ){
  56989. freePage(pPage, &rc);
  56990. }else if( (rc = sqlite3PagerWrite(pPage->pDbPage))==0 ){
  56991. zeroPage(pPage, pPage->aData[hdr] | PTF_LEAF);
  56992. }
  56993. cleardatabasepage_out:
  56994. pPage->bBusy = 0;
  56995. releasePage(pPage);
  56996. return rc;
  56997. }
  56998. /*
  56999. ** Delete all information from a single table in the database. iTable is
  57000. ** the page number of the root of the table. After this routine returns,
  57001. ** the root page is empty, but still exists.
  57002. **
  57003. ** This routine will fail with SQLITE_LOCKED if there are any open
  57004. ** read cursors on the table. Open write cursors are moved to the
  57005. ** root of the table.
  57006. **
  57007. ** If pnChange is not NULL, then table iTable must be an intkey table. The
  57008. ** integer value pointed to by pnChange is incremented by the number of
  57009. ** entries in the table.
  57010. */
  57011. SQLITE_PRIVATE int sqlite3BtreeClearTable(Btree *p, int iTable, int *pnChange){
  57012. int rc;
  57013. BtShared *pBt = p->pBt;
  57014. sqlite3BtreeEnter(p);
  57015. assert( p->inTrans==TRANS_WRITE );
  57016. rc = saveAllCursors(pBt, (Pgno)iTable, 0);
  57017. if( SQLITE_OK==rc ){
  57018. /* Invalidate all incrblob cursors open on table iTable (assuming iTable
  57019. ** is the root of a table b-tree - if it is not, the following call is
  57020. ** a no-op). */
  57021. invalidateIncrblobCursors(p, 0, 1);
  57022. rc = clearDatabasePage(pBt, (Pgno)iTable, 0, pnChange);
  57023. }
  57024. sqlite3BtreeLeave(p);
  57025. return rc;
  57026. }
  57027. /*
  57028. ** Delete all information from the single table that pCur is open on.
  57029. **
  57030. ** This routine only work for pCur on an ephemeral table.
  57031. */
  57032. SQLITE_PRIVATE int sqlite3BtreeClearTableOfCursor(BtCursor *pCur){
  57033. return sqlite3BtreeClearTable(pCur->pBtree, pCur->pgnoRoot, 0);
  57034. }
  57035. /*
  57036. ** Erase all information in a table and add the root of the table to
  57037. ** the freelist. Except, the root of the principle table (the one on
  57038. ** page 1) is never added to the freelist.
  57039. **
  57040. ** This routine will fail with SQLITE_LOCKED if there are any open
  57041. ** cursors on the table.
  57042. **
  57043. ** If AUTOVACUUM is enabled and the page at iTable is not the last
  57044. ** root page in the database file, then the last root page
  57045. ** in the database file is moved into the slot formerly occupied by
  57046. ** iTable and that last slot formerly occupied by the last root page
  57047. ** is added to the freelist instead of iTable. In this say, all
  57048. ** root pages are kept at the beginning of the database file, which
  57049. ** is necessary for AUTOVACUUM to work right. *piMoved is set to the
  57050. ** page number that used to be the last root page in the file before
  57051. ** the move. If no page gets moved, *piMoved is set to 0.
  57052. ** The last root page is recorded in meta[3] and the value of
  57053. ** meta[3] is updated by this procedure.
  57054. */
  57055. static int btreeDropTable(Btree *p, Pgno iTable, int *piMoved){
  57056. int rc;
  57057. MemPage *pPage = 0;
  57058. BtShared *pBt = p->pBt;
  57059. assert( sqlite3BtreeHoldsMutex(p) );
  57060. assert( p->inTrans==TRANS_WRITE );
  57061. /* It is illegal to drop a table if any cursors are open on the
  57062. ** database. This is because in auto-vacuum mode the backend may
  57063. ** need to move another root-page to fill a gap left by the deleted
  57064. ** root page. If an open cursor was using this page a problem would
  57065. ** occur.
  57066. **
  57067. ** This error is caught long before control reaches this point.
  57068. */
  57069. if( NEVER(pBt->pCursor) ){
  57070. sqlite3ConnectionBlocked(p->db, pBt->pCursor->pBtree->db);
  57071. return SQLITE_LOCKED_SHAREDCACHE;
  57072. }
  57073. rc = btreeGetPage(pBt, (Pgno)iTable, &pPage, 0);
  57074. if( rc ) return rc;
  57075. rc = sqlite3BtreeClearTable(p, iTable, 0);
  57076. if( rc ){
  57077. releasePage(pPage);
  57078. return rc;
  57079. }
  57080. *piMoved = 0;
  57081. if( iTable>1 ){
  57082. #ifdef SQLITE_OMIT_AUTOVACUUM
  57083. freePage(pPage, &rc);
  57084. releasePage(pPage);
  57085. #else
  57086. if( pBt->autoVacuum ){
  57087. Pgno maxRootPgno;
  57088. sqlite3BtreeGetMeta(p, BTREE_LARGEST_ROOT_PAGE, &maxRootPgno);
  57089. if( iTable==maxRootPgno ){
  57090. /* If the table being dropped is the table with the largest root-page
  57091. ** number in the database, put the root page on the free list.
  57092. */
  57093. freePage(pPage, &rc);
  57094. releasePage(pPage);
  57095. if( rc!=SQLITE_OK ){
  57096. return rc;
  57097. }
  57098. }else{
  57099. /* The table being dropped does not have the largest root-page
  57100. ** number in the database. So move the page that does into the
  57101. ** gap left by the deleted root-page.
  57102. */
  57103. MemPage *pMove;
  57104. releasePage(pPage);
  57105. rc = btreeGetPage(pBt, maxRootPgno, &pMove, 0);
  57106. if( rc!=SQLITE_OK ){
  57107. return rc;
  57108. }
  57109. rc = relocatePage(pBt, pMove, PTRMAP_ROOTPAGE, 0, iTable, 0);
  57110. releasePage(pMove);
  57111. if( rc!=SQLITE_OK ){
  57112. return rc;
  57113. }
  57114. pMove = 0;
  57115. rc = btreeGetPage(pBt, maxRootPgno, &pMove, 0);
  57116. freePage(pMove, &rc);
  57117. releasePage(pMove);
  57118. if( rc!=SQLITE_OK ){
  57119. return rc;
  57120. }
  57121. *piMoved = maxRootPgno;
  57122. }
  57123. /* Set the new 'max-root-page' value in the database header. This
  57124. ** is the old value less one, less one more if that happens to
  57125. ** be a root-page number, less one again if that is the
  57126. ** PENDING_BYTE_PAGE.
  57127. */
  57128. maxRootPgno--;
  57129. while( maxRootPgno==PENDING_BYTE_PAGE(pBt)
  57130. || PTRMAP_ISPAGE(pBt, maxRootPgno) ){
  57131. maxRootPgno--;
  57132. }
  57133. assert( maxRootPgno!=PENDING_BYTE_PAGE(pBt) );
  57134. rc = sqlite3BtreeUpdateMeta(p, 4, maxRootPgno);
  57135. }else{
  57136. freePage(pPage, &rc);
  57137. releasePage(pPage);
  57138. }
  57139. #endif
  57140. }else{
  57141. /* If sqlite3BtreeDropTable was called on page 1.
  57142. ** This really never should happen except in a corrupt
  57143. ** database.
  57144. */
  57145. zeroPage(pPage, PTF_INTKEY|PTF_LEAF );
  57146. releasePage(pPage);
  57147. }
  57148. return rc;
  57149. }
  57150. SQLITE_PRIVATE int sqlite3BtreeDropTable(Btree *p, int iTable, int *piMoved){
  57151. int rc;
  57152. sqlite3BtreeEnter(p);
  57153. rc = btreeDropTable(p, iTable, piMoved);
  57154. sqlite3BtreeLeave(p);
  57155. return rc;
  57156. }
  57157. /*
  57158. ** This function may only be called if the b-tree connection already
  57159. ** has a read or write transaction open on the database.
  57160. **
  57161. ** Read the meta-information out of a database file. Meta[0]
  57162. ** is the number of free pages currently in the database. Meta[1]
  57163. ** through meta[15] are available for use by higher layers. Meta[0]
  57164. ** is read-only, the others are read/write.
  57165. **
  57166. ** The schema layer numbers meta values differently. At the schema
  57167. ** layer (and the SetCookie and ReadCookie opcodes) the number of
  57168. ** free pages is not visible. So Cookie[0] is the same as Meta[1].
  57169. **
  57170. ** This routine treats Meta[BTREE_DATA_VERSION] as a special case. Instead
  57171. ** of reading the value out of the header, it instead loads the "DataVersion"
  57172. ** from the pager. The BTREE_DATA_VERSION value is not actually stored in the
  57173. ** database file. It is a number computed by the pager. But its access
  57174. ** pattern is the same as header meta values, and so it is convenient to
  57175. ** read it from this routine.
  57176. */
  57177. SQLITE_PRIVATE void sqlite3BtreeGetMeta(Btree *p, int idx, u32 *pMeta){
  57178. BtShared *pBt = p->pBt;
  57179. sqlite3BtreeEnter(p);
  57180. assert( p->inTrans>TRANS_NONE );
  57181. assert( SQLITE_OK==querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK) );
  57182. assert( pBt->pPage1 );
  57183. assert( idx>=0 && idx<=15 );
  57184. if( idx==BTREE_DATA_VERSION ){
  57185. *pMeta = sqlite3PagerDataVersion(pBt->pPager) + p->iDataVersion;
  57186. }else{
  57187. *pMeta = get4byte(&pBt->pPage1->aData[36 + idx*4]);
  57188. }
  57189. /* If auto-vacuum is disabled in this build and this is an auto-vacuum
  57190. ** database, mark the database as read-only. */
  57191. #ifdef SQLITE_OMIT_AUTOVACUUM
  57192. if( idx==BTREE_LARGEST_ROOT_PAGE && *pMeta>0 ){
  57193. pBt->btsFlags |= BTS_READ_ONLY;
  57194. }
  57195. #endif
  57196. sqlite3BtreeLeave(p);
  57197. }
  57198. /*
  57199. ** Write meta-information back into the database. Meta[0] is
  57200. ** read-only and may not be written.
  57201. */
  57202. SQLITE_PRIVATE int sqlite3BtreeUpdateMeta(Btree *p, int idx, u32 iMeta){
  57203. BtShared *pBt = p->pBt;
  57204. unsigned char *pP1;
  57205. int rc;
  57206. assert( idx>=1 && idx<=15 );
  57207. sqlite3BtreeEnter(p);
  57208. assert( p->inTrans==TRANS_WRITE );
  57209. assert( pBt->pPage1!=0 );
  57210. pP1 = pBt->pPage1->aData;
  57211. rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
  57212. if( rc==SQLITE_OK ){
  57213. put4byte(&pP1[36 + idx*4], iMeta);
  57214. #ifndef SQLITE_OMIT_AUTOVACUUM
  57215. if( idx==BTREE_INCR_VACUUM ){
  57216. assert( pBt->autoVacuum || iMeta==0 );
  57217. assert( iMeta==0 || iMeta==1 );
  57218. pBt->incrVacuum = (u8)iMeta;
  57219. }
  57220. #endif
  57221. }
  57222. sqlite3BtreeLeave(p);
  57223. return rc;
  57224. }
  57225. #ifndef SQLITE_OMIT_BTREECOUNT
  57226. /*
  57227. ** The first argument, pCur, is a cursor opened on some b-tree. Count the
  57228. ** number of entries in the b-tree and write the result to *pnEntry.
  57229. **
  57230. ** SQLITE_OK is returned if the operation is successfully executed.
  57231. ** Otherwise, if an error is encountered (i.e. an IO error or database
  57232. ** corruption) an SQLite error code is returned.
  57233. */
  57234. SQLITE_PRIVATE int sqlite3BtreeCount(BtCursor *pCur, i64 *pnEntry){
  57235. i64 nEntry = 0; /* Value to return in *pnEntry */
  57236. int rc; /* Return code */
  57237. if( pCur->pgnoRoot==0 ){
  57238. *pnEntry = 0;
  57239. return SQLITE_OK;
  57240. }
  57241. rc = moveToRoot(pCur);
  57242. /* Unless an error occurs, the following loop runs one iteration for each
  57243. ** page in the B-Tree structure (not including overflow pages).
  57244. */
  57245. while( rc==SQLITE_OK ){
  57246. int iIdx; /* Index of child node in parent */
  57247. MemPage *pPage; /* Current page of the b-tree */
  57248. /* If this is a leaf page or the tree is not an int-key tree, then
  57249. ** this page contains countable entries. Increment the entry counter
  57250. ** accordingly.
  57251. */
  57252. pPage = pCur->apPage[pCur->iPage];
  57253. if( pPage->leaf || !pPage->intKey ){
  57254. nEntry += pPage->nCell;
  57255. }
  57256. /* pPage is a leaf node. This loop navigates the cursor so that it
  57257. ** points to the first interior cell that it points to the parent of
  57258. ** the next page in the tree that has not yet been visited. The
  57259. ** pCur->aiIdx[pCur->iPage] value is set to the index of the parent cell
  57260. ** of the page, or to the number of cells in the page if the next page
  57261. ** to visit is the right-child of its parent.
  57262. **
  57263. ** If all pages in the tree have been visited, return SQLITE_OK to the
  57264. ** caller.
  57265. */
  57266. if( pPage->leaf ){
  57267. do {
  57268. if( pCur->iPage==0 ){
  57269. /* All pages of the b-tree have been visited. Return successfully. */
  57270. *pnEntry = nEntry;
  57271. return moveToRoot(pCur);
  57272. }
  57273. moveToParent(pCur);
  57274. }while ( pCur->aiIdx[pCur->iPage]>=pCur->apPage[pCur->iPage]->nCell );
  57275. pCur->aiIdx[pCur->iPage]++;
  57276. pPage = pCur->apPage[pCur->iPage];
  57277. }
  57278. /* Descend to the child node of the cell that the cursor currently
  57279. ** points at. This is the right-child if (iIdx==pPage->nCell).
  57280. */
  57281. iIdx = pCur->aiIdx[pCur->iPage];
  57282. if( iIdx==pPage->nCell ){
  57283. rc = moveToChild(pCur, get4byte(&pPage->aData[pPage->hdrOffset+8]));
  57284. }else{
  57285. rc = moveToChild(pCur, get4byte(findCell(pPage, iIdx)));
  57286. }
  57287. }
  57288. /* An error has occurred. Return an error code. */
  57289. return rc;
  57290. }
  57291. #endif
  57292. /*
  57293. ** Return the pager associated with a BTree. This routine is used for
  57294. ** testing and debugging only.
  57295. */
  57296. SQLITE_PRIVATE Pager *sqlite3BtreePager(Btree *p){
  57297. return p->pBt->pPager;
  57298. }
  57299. #ifndef SQLITE_OMIT_INTEGRITY_CHECK
  57300. /*
  57301. ** Append a message to the error message string.
  57302. */
  57303. static void checkAppendMsg(
  57304. IntegrityCk *pCheck,
  57305. const char *zFormat,
  57306. ...
  57307. ){
  57308. va_list ap;
  57309. char zBuf[200];
  57310. if( !pCheck->mxErr ) return;
  57311. pCheck->mxErr--;
  57312. pCheck->nErr++;
  57313. va_start(ap, zFormat);
  57314. if( pCheck->errMsg.nChar ){
  57315. sqlite3StrAccumAppend(&pCheck->errMsg, "\n", 1);
  57316. }
  57317. if( pCheck->zPfx ){
  57318. sqlite3_snprintf(sizeof(zBuf), zBuf, pCheck->zPfx, pCheck->v1, pCheck->v2);
  57319. sqlite3StrAccumAppendAll(&pCheck->errMsg, zBuf);
  57320. }
  57321. sqlite3VXPrintf(&pCheck->errMsg, 1, zFormat, ap);
  57322. va_end(ap);
  57323. if( pCheck->errMsg.accError==STRACCUM_NOMEM ){
  57324. pCheck->mallocFailed = 1;
  57325. }
  57326. }
  57327. #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
  57328. #ifndef SQLITE_OMIT_INTEGRITY_CHECK
  57329. /*
  57330. ** Return non-zero if the bit in the IntegrityCk.aPgRef[] array that
  57331. ** corresponds to page iPg is already set.
  57332. */
  57333. static int getPageReferenced(IntegrityCk *pCheck, Pgno iPg){
  57334. assert( iPg<=pCheck->nPage && sizeof(pCheck->aPgRef[0])==1 );
  57335. return (pCheck->aPgRef[iPg/8] & (1 << (iPg & 0x07)));
  57336. }
  57337. /*
  57338. ** Set the bit in the IntegrityCk.aPgRef[] array that corresponds to page iPg.
  57339. */
  57340. static void setPageReferenced(IntegrityCk *pCheck, Pgno iPg){
  57341. assert( iPg<=pCheck->nPage && sizeof(pCheck->aPgRef[0])==1 );
  57342. pCheck->aPgRef[iPg/8] |= (1 << (iPg & 0x07));
  57343. }
  57344. /*
  57345. ** Add 1 to the reference count for page iPage. If this is the second
  57346. ** reference to the page, add an error message to pCheck->zErrMsg.
  57347. ** Return 1 if there are 2 or more references to the page and 0 if
  57348. ** if this is the first reference to the page.
  57349. **
  57350. ** Also check that the page number is in bounds.
  57351. */
  57352. static int checkRef(IntegrityCk *pCheck, Pgno iPage){
  57353. if( iPage==0 ) return 1;
  57354. if( iPage>pCheck->nPage ){
  57355. checkAppendMsg(pCheck, "invalid page number %d", iPage);
  57356. return 1;
  57357. }
  57358. if( getPageReferenced(pCheck, iPage) ){
  57359. checkAppendMsg(pCheck, "2nd reference to page %d", iPage);
  57360. return 1;
  57361. }
  57362. setPageReferenced(pCheck, iPage);
  57363. return 0;
  57364. }
  57365. #ifndef SQLITE_OMIT_AUTOVACUUM
  57366. /*
  57367. ** Check that the entry in the pointer-map for page iChild maps to
  57368. ** page iParent, pointer type ptrType. If not, append an error message
  57369. ** to pCheck.
  57370. */
  57371. static void checkPtrmap(
  57372. IntegrityCk *pCheck, /* Integrity check context */
  57373. Pgno iChild, /* Child page number */
  57374. u8 eType, /* Expected pointer map type */
  57375. Pgno iParent /* Expected pointer map parent page number */
  57376. ){
  57377. int rc;
  57378. u8 ePtrmapType;
  57379. Pgno iPtrmapParent;
  57380. rc = ptrmapGet(pCheck->pBt, iChild, &ePtrmapType, &iPtrmapParent);
  57381. if( rc!=SQLITE_OK ){
  57382. if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ) pCheck->mallocFailed = 1;
  57383. checkAppendMsg(pCheck, "Failed to read ptrmap key=%d", iChild);
  57384. return;
  57385. }
  57386. if( ePtrmapType!=eType || iPtrmapParent!=iParent ){
  57387. checkAppendMsg(pCheck,
  57388. "Bad ptr map entry key=%d expected=(%d,%d) got=(%d,%d)",
  57389. iChild, eType, iParent, ePtrmapType, iPtrmapParent);
  57390. }
  57391. }
  57392. #endif
  57393. /*
  57394. ** Check the integrity of the freelist or of an overflow page list.
  57395. ** Verify that the number of pages on the list is N.
  57396. */
  57397. static void checkList(
  57398. IntegrityCk *pCheck, /* Integrity checking context */
  57399. int isFreeList, /* True for a freelist. False for overflow page list */
  57400. int iPage, /* Page number for first page in the list */
  57401. int N /* Expected number of pages in the list */
  57402. ){
  57403. int i;
  57404. int expected = N;
  57405. int iFirst = iPage;
  57406. while( N-- > 0 && pCheck->mxErr ){
  57407. DbPage *pOvflPage;
  57408. unsigned char *pOvflData;
  57409. if( iPage<1 ){
  57410. checkAppendMsg(pCheck,
  57411. "%d of %d pages missing from overflow list starting at %d",
  57412. N+1, expected, iFirst);
  57413. break;
  57414. }
  57415. if( checkRef(pCheck, iPage) ) break;
  57416. if( sqlite3PagerGet(pCheck->pPager, (Pgno)iPage, &pOvflPage) ){
  57417. checkAppendMsg(pCheck, "failed to get page %d", iPage);
  57418. break;
  57419. }
  57420. pOvflData = (unsigned char *)sqlite3PagerGetData(pOvflPage);
  57421. if( isFreeList ){
  57422. int n = get4byte(&pOvflData[4]);
  57423. #ifndef SQLITE_OMIT_AUTOVACUUM
  57424. if( pCheck->pBt->autoVacuum ){
  57425. checkPtrmap(pCheck, iPage, PTRMAP_FREEPAGE, 0);
  57426. }
  57427. #endif
  57428. if( n>(int)pCheck->pBt->usableSize/4-2 ){
  57429. checkAppendMsg(pCheck,
  57430. "freelist leaf count too big on page %d", iPage);
  57431. N--;
  57432. }else{
  57433. for(i=0; i<n; i++){
  57434. Pgno iFreePage = get4byte(&pOvflData[8+i*4]);
  57435. #ifndef SQLITE_OMIT_AUTOVACUUM
  57436. if( pCheck->pBt->autoVacuum ){
  57437. checkPtrmap(pCheck, iFreePage, PTRMAP_FREEPAGE, 0);
  57438. }
  57439. #endif
  57440. checkRef(pCheck, iFreePage);
  57441. }
  57442. N -= n;
  57443. }
  57444. }
  57445. #ifndef SQLITE_OMIT_AUTOVACUUM
  57446. else{
  57447. /* If this database supports auto-vacuum and iPage is not the last
  57448. ** page in this overflow list, check that the pointer-map entry for
  57449. ** the following page matches iPage.
  57450. */
  57451. if( pCheck->pBt->autoVacuum && N>0 ){
  57452. i = get4byte(pOvflData);
  57453. checkPtrmap(pCheck, i, PTRMAP_OVERFLOW2, iPage);
  57454. }
  57455. }
  57456. #endif
  57457. iPage = get4byte(pOvflData);
  57458. sqlite3PagerUnref(pOvflPage);
  57459. }
  57460. }
  57461. #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
  57462. /*
  57463. ** An implementation of a min-heap.
  57464. **
  57465. ** aHeap[0] is the number of elements on the heap. aHeap[1] is the
  57466. ** root element. The daughter nodes of aHeap[N] are aHeap[N*2]
  57467. ** and aHeap[N*2+1].
  57468. **
  57469. ** The heap property is this: Every node is less than or equal to both
  57470. ** of its daughter nodes. A consequence of the heap property is that the
  57471. ** root node aHeap[1] is always the minimum value currently in the heap.
  57472. **
  57473. ** The btreeHeapInsert() routine inserts an unsigned 32-bit number onto
  57474. ** the heap, preserving the heap property. The btreeHeapPull() routine
  57475. ** removes the root element from the heap (the minimum value in the heap)
  57476. ** and then moves other nodes around as necessary to preserve the heap
  57477. ** property.
  57478. **
  57479. ** This heap is used for cell overlap and coverage testing. Each u32
  57480. ** entry represents the span of a cell or freeblock on a btree page.
  57481. ** The upper 16 bits are the index of the first byte of a range and the
  57482. ** lower 16 bits are the index of the last byte of that range.
  57483. */
  57484. static void btreeHeapInsert(u32 *aHeap, u32 x){
  57485. u32 j, i = ++aHeap[0];
  57486. aHeap[i] = x;
  57487. while( (j = i/2)>0 && aHeap[j]>aHeap[i] ){
  57488. x = aHeap[j];
  57489. aHeap[j] = aHeap[i];
  57490. aHeap[i] = x;
  57491. i = j;
  57492. }
  57493. }
  57494. static int btreeHeapPull(u32 *aHeap, u32 *pOut){
  57495. u32 j, i, x;
  57496. if( (x = aHeap[0])==0 ) return 0;
  57497. *pOut = aHeap[1];
  57498. aHeap[1] = aHeap[x];
  57499. aHeap[x] = 0xffffffff;
  57500. aHeap[0]--;
  57501. i = 1;
  57502. while( (j = i*2)<=aHeap[0] ){
  57503. if( aHeap[j]>aHeap[j+1] ) j++;
  57504. if( aHeap[i]<aHeap[j] ) break;
  57505. x = aHeap[i];
  57506. aHeap[i] = aHeap[j];
  57507. aHeap[j] = x;
  57508. i = j;
  57509. }
  57510. return 1;
  57511. }
  57512. #ifndef SQLITE_OMIT_INTEGRITY_CHECK
  57513. /*
  57514. ** Do various sanity checks on a single page of a tree. Return
  57515. ** the tree depth. Root pages return 0. Parents of root pages
  57516. ** return 1, and so forth.
  57517. **
  57518. ** These checks are done:
  57519. **
  57520. ** 1. Make sure that cells and freeblocks do not overlap
  57521. ** but combine to completely cover the page.
  57522. ** NO 2. Make sure cell keys are in order.
  57523. ** NO 3. Make sure no key is less than or equal to zLowerBound.
  57524. ** NO 4. Make sure no key is greater than or equal to zUpperBound.
  57525. ** 5. Check the integrity of overflow pages.
  57526. ** 6. Recursively call checkTreePage on all children.
  57527. ** 7. Verify that the depth of all children is the same.
  57528. ** 8. Make sure this page is at least 33% full or else it is
  57529. ** the root of the tree.
  57530. */
  57531. static int checkTreePage(
  57532. IntegrityCk *pCheck, /* Context for the sanity check */
  57533. int iPage, /* Page number of the page to check */
  57534. i64 *pnParentMinKey,
  57535. i64 *pnParentMaxKey
  57536. ){
  57537. MemPage *pPage;
  57538. int i, rc, depth, d2, pgno, cnt;
  57539. int hdr, cellStart;
  57540. int nCell;
  57541. u8 *data;
  57542. BtShared *pBt;
  57543. int usableSize;
  57544. u32 *heap = 0;
  57545. u32 x, prev = 0;
  57546. i64 nMinKey = 0;
  57547. i64 nMaxKey = 0;
  57548. const char *saved_zPfx = pCheck->zPfx;
  57549. int saved_v1 = pCheck->v1;
  57550. int saved_v2 = pCheck->v2;
  57551. /* Check that the page exists
  57552. */
  57553. pBt = pCheck->pBt;
  57554. usableSize = pBt->usableSize;
  57555. if( iPage==0 ) return 0;
  57556. if( checkRef(pCheck, iPage) ) return 0;
  57557. pCheck->zPfx = "Page %d: ";
  57558. pCheck->v1 = iPage;
  57559. if( (rc = btreeGetPage(pBt, (Pgno)iPage, &pPage, 0))!=0 ){
  57560. checkAppendMsg(pCheck,
  57561. "unable to get the page. error code=%d", rc);
  57562. depth = -1;
  57563. goto end_of_check;
  57564. }
  57565. /* Clear MemPage.isInit to make sure the corruption detection code in
  57566. ** btreeInitPage() is executed. */
  57567. pPage->isInit = 0;
  57568. if( (rc = btreeInitPage(pPage))!=0 ){
  57569. assert( rc==SQLITE_CORRUPT ); /* The only possible error from InitPage */
  57570. checkAppendMsg(pCheck,
  57571. "btreeInitPage() returns error code %d", rc);
  57572. releasePage(pPage);
  57573. depth = -1;
  57574. goto end_of_check;
  57575. }
  57576. /* Check out all the cells.
  57577. */
  57578. depth = 0;
  57579. for(i=0; i<pPage->nCell && pCheck->mxErr; i++){
  57580. u8 *pCell;
  57581. u32 sz;
  57582. CellInfo info;
  57583. /* Check payload overflow pages
  57584. */
  57585. pCheck->zPfx = "On tree page %d cell %d: ";
  57586. pCheck->v1 = iPage;
  57587. pCheck->v2 = i;
  57588. pCell = findCell(pPage,i);
  57589. btreeParseCellPtr(pPage, pCell, &info);
  57590. sz = info.nPayload;
  57591. /* For intKey pages, check that the keys are in order.
  57592. */
  57593. if( pPage->intKey ){
  57594. if( i==0 ){
  57595. nMinKey = nMaxKey = info.nKey;
  57596. }else if( info.nKey <= nMaxKey ){
  57597. checkAppendMsg(pCheck,
  57598. "Rowid %lld out of order (previous was %lld)", info.nKey, nMaxKey);
  57599. }
  57600. nMaxKey = info.nKey;
  57601. }
  57602. if( (sz>info.nLocal)
  57603. && (&pCell[info.iOverflow]<=&pPage->aData[pBt->usableSize])
  57604. ){
  57605. int nPage = (sz - info.nLocal + usableSize - 5)/(usableSize - 4);
  57606. Pgno pgnoOvfl = get4byte(&pCell[info.iOverflow]);
  57607. #ifndef SQLITE_OMIT_AUTOVACUUM
  57608. if( pBt->autoVacuum ){
  57609. checkPtrmap(pCheck, pgnoOvfl, PTRMAP_OVERFLOW1, iPage);
  57610. }
  57611. #endif
  57612. checkList(pCheck, 0, pgnoOvfl, nPage);
  57613. }
  57614. /* Check sanity of left child page.
  57615. */
  57616. if( !pPage->leaf ){
  57617. pgno = get4byte(pCell);
  57618. #ifndef SQLITE_OMIT_AUTOVACUUM
  57619. if( pBt->autoVacuum ){
  57620. checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage);
  57621. }
  57622. #endif
  57623. d2 = checkTreePage(pCheck, pgno, &nMinKey, i==0?NULL:&nMaxKey);
  57624. if( i>0 && d2!=depth ){
  57625. checkAppendMsg(pCheck, "Child page depth differs");
  57626. }
  57627. depth = d2;
  57628. }
  57629. }
  57630. if( !pPage->leaf ){
  57631. pgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
  57632. pCheck->zPfx = "On page %d at right child: ";
  57633. pCheck->v1 = iPage;
  57634. #ifndef SQLITE_OMIT_AUTOVACUUM
  57635. if( pBt->autoVacuum ){
  57636. checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage);
  57637. }
  57638. #endif
  57639. checkTreePage(pCheck, pgno, NULL, !pPage->nCell?NULL:&nMaxKey);
  57640. }
  57641. /* For intKey leaf pages, check that the min/max keys are in order
  57642. ** with any left/parent/right pages.
  57643. */
  57644. pCheck->zPfx = "Page %d: ";
  57645. pCheck->v1 = iPage;
  57646. if( pPage->leaf && pPage->intKey ){
  57647. /* if we are a left child page */
  57648. if( pnParentMinKey ){
  57649. /* if we are the left most child page */
  57650. if( !pnParentMaxKey ){
  57651. if( nMaxKey > *pnParentMinKey ){
  57652. checkAppendMsg(pCheck,
  57653. "Rowid %lld out of order (max larger than parent min of %lld)",
  57654. nMaxKey, *pnParentMinKey);
  57655. }
  57656. }else{
  57657. if( nMinKey <= *pnParentMinKey ){
  57658. checkAppendMsg(pCheck,
  57659. "Rowid %lld out of order (min less than parent min of %lld)",
  57660. nMinKey, *pnParentMinKey);
  57661. }
  57662. if( nMaxKey > *pnParentMaxKey ){
  57663. checkAppendMsg(pCheck,
  57664. "Rowid %lld out of order (max larger than parent max of %lld)",
  57665. nMaxKey, *pnParentMaxKey);
  57666. }
  57667. *pnParentMinKey = nMaxKey;
  57668. }
  57669. /* else if we're a right child page */
  57670. } else if( pnParentMaxKey ){
  57671. if( nMinKey <= *pnParentMaxKey ){
  57672. checkAppendMsg(pCheck,
  57673. "Rowid %lld out of order (min less than parent max of %lld)",
  57674. nMinKey, *pnParentMaxKey);
  57675. }
  57676. }
  57677. }
  57678. /* Check for complete coverage of the page
  57679. */
  57680. data = pPage->aData;
  57681. hdr = pPage->hdrOffset;
  57682. heap = (u32*)sqlite3PageMalloc( pBt->pageSize );
  57683. pCheck->zPfx = 0;
  57684. if( heap==0 ){
  57685. pCheck->mallocFailed = 1;
  57686. }else{
  57687. int contentOffset = get2byteNotZero(&data[hdr+5]);
  57688. assert( contentOffset<=usableSize ); /* Enforced by btreeInitPage() */
  57689. heap[0] = 0;
  57690. btreeHeapInsert(heap, contentOffset-1);
  57691. /* EVIDENCE-OF: R-37002-32774 The two-byte integer at offset 3 gives the
  57692. ** number of cells on the page. */
  57693. nCell = get2byte(&data[hdr+3]);
  57694. /* EVIDENCE-OF: R-23882-45353 The cell pointer array of a b-tree page
  57695. ** immediately follows the b-tree page header. */
  57696. cellStart = hdr + 12 - 4*pPage->leaf;
  57697. /* EVIDENCE-OF: R-02776-14802 The cell pointer array consists of K 2-byte
  57698. ** integer offsets to the cell contents. */
  57699. for(i=0; i<nCell; i++){
  57700. int pc = get2byte(&data[cellStart+i*2]);
  57701. u32 size = 65536;
  57702. if( pc<=usableSize-4 ){
  57703. size = cellSizePtr(pPage, &data[pc]);
  57704. }
  57705. if( (int)(pc+size-1)>=usableSize ){
  57706. pCheck->zPfx = 0;
  57707. checkAppendMsg(pCheck,
  57708. "Corruption detected in cell %d on page %d",i,iPage);
  57709. }else{
  57710. btreeHeapInsert(heap, (pc<<16)|(pc+size-1));
  57711. }
  57712. }
  57713. /* EVIDENCE-OF: R-20690-50594 The second field of the b-tree page header
  57714. ** is the offset of the first freeblock, or zero if there are no
  57715. ** freeblocks on the page. */
  57716. i = get2byte(&data[hdr+1]);
  57717. while( i>0 ){
  57718. int size, j;
  57719. assert( i<=usableSize-4 ); /* Enforced by btreeInitPage() */
  57720. size = get2byte(&data[i+2]);
  57721. assert( i+size<=usableSize ); /* Enforced by btreeInitPage() */
  57722. btreeHeapInsert(heap, (i<<16)|(i+size-1));
  57723. /* EVIDENCE-OF: R-58208-19414 The first 2 bytes of a freeblock are a
  57724. ** big-endian integer which is the offset in the b-tree page of the next
  57725. ** freeblock in the chain, or zero if the freeblock is the last on the
  57726. ** chain. */
  57727. j = get2byte(&data[i]);
  57728. /* EVIDENCE-OF: R-06866-39125 Freeblocks are always connected in order of
  57729. ** increasing offset. */
  57730. assert( j==0 || j>i+size ); /* Enforced by btreeInitPage() */
  57731. assert( j<=usableSize-4 ); /* Enforced by btreeInitPage() */
  57732. i = j;
  57733. }
  57734. cnt = 0;
  57735. assert( heap[0]>0 );
  57736. assert( (heap[1]>>16)==0 );
  57737. btreeHeapPull(heap,&prev);
  57738. while( btreeHeapPull(heap,&x) ){
  57739. if( (prev&0xffff)+1>(x>>16) ){
  57740. checkAppendMsg(pCheck,
  57741. "Multiple uses for byte %u of page %d", x>>16, iPage);
  57742. break;
  57743. }else{
  57744. cnt += (x>>16) - (prev&0xffff) - 1;
  57745. prev = x;
  57746. }
  57747. }
  57748. cnt += usableSize - (prev&0xffff) - 1;
  57749. /* EVIDENCE-OF: R-43263-13491 The total number of bytes in all fragments
  57750. ** is stored in the fifth field of the b-tree page header.
  57751. ** EVIDENCE-OF: R-07161-27322 The one-byte integer at offset 7 gives the
  57752. ** number of fragmented free bytes within the cell content area.
  57753. */
  57754. if( heap[0]==0 && cnt!=data[hdr+7] ){
  57755. checkAppendMsg(pCheck,
  57756. "Fragmentation of %d bytes reported as %d on page %d",
  57757. cnt, data[hdr+7], iPage);
  57758. }
  57759. }
  57760. sqlite3PageFree(heap);
  57761. releasePage(pPage);
  57762. end_of_check:
  57763. pCheck->zPfx = saved_zPfx;
  57764. pCheck->v1 = saved_v1;
  57765. pCheck->v2 = saved_v2;
  57766. return depth+1;
  57767. }
  57768. #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
  57769. #ifndef SQLITE_OMIT_INTEGRITY_CHECK
  57770. /*
  57771. ** This routine does a complete check of the given BTree file. aRoot[] is
  57772. ** an array of pages numbers were each page number is the root page of
  57773. ** a table. nRoot is the number of entries in aRoot.
  57774. **
  57775. ** A read-only or read-write transaction must be opened before calling
  57776. ** this function.
  57777. **
  57778. ** Write the number of error seen in *pnErr. Except for some memory
  57779. ** allocation errors, an error message held in memory obtained from
  57780. ** malloc is returned if *pnErr is non-zero. If *pnErr==0 then NULL is
  57781. ** returned. If a memory allocation error occurs, NULL is returned.
  57782. */
  57783. SQLITE_PRIVATE char *sqlite3BtreeIntegrityCheck(
  57784. Btree *p, /* The btree to be checked */
  57785. int *aRoot, /* An array of root pages numbers for individual trees */
  57786. int nRoot, /* Number of entries in aRoot[] */
  57787. int mxErr, /* Stop reporting errors after this many */
  57788. int *pnErr /* Write number of errors seen to this variable */
  57789. ){
  57790. Pgno i;
  57791. int nRef;
  57792. IntegrityCk sCheck;
  57793. BtShared *pBt = p->pBt;
  57794. char zErr[100];
  57795. sqlite3BtreeEnter(p);
  57796. assert( p->inTrans>TRANS_NONE && pBt->inTransaction>TRANS_NONE );
  57797. nRef = sqlite3PagerRefcount(pBt->pPager);
  57798. sCheck.pBt = pBt;
  57799. sCheck.pPager = pBt->pPager;
  57800. sCheck.nPage = btreePagecount(sCheck.pBt);
  57801. sCheck.mxErr = mxErr;
  57802. sCheck.nErr = 0;
  57803. sCheck.mallocFailed = 0;
  57804. sCheck.zPfx = 0;
  57805. sCheck.v1 = 0;
  57806. sCheck.v2 = 0;
  57807. *pnErr = 0;
  57808. if( sCheck.nPage==0 ){
  57809. sqlite3BtreeLeave(p);
  57810. return 0;
  57811. }
  57812. sCheck.aPgRef = sqlite3MallocZero((sCheck.nPage / 8)+ 1);
  57813. if( !sCheck.aPgRef ){
  57814. *pnErr = 1;
  57815. sqlite3BtreeLeave(p);
  57816. return 0;
  57817. }
  57818. i = PENDING_BYTE_PAGE(pBt);
  57819. if( i<=sCheck.nPage ) setPageReferenced(&sCheck, i);
  57820. sqlite3StrAccumInit(&sCheck.errMsg, 0, zErr, sizeof(zErr), SQLITE_MAX_LENGTH);
  57821. /* Check the integrity of the freelist
  57822. */
  57823. sCheck.zPfx = "Main freelist: ";
  57824. checkList(&sCheck, 1, get4byte(&pBt->pPage1->aData[32]),
  57825. get4byte(&pBt->pPage1->aData[36]));
  57826. sCheck.zPfx = 0;
  57827. /* Check all the tables.
  57828. */
  57829. for(i=0; (int)i<nRoot && sCheck.mxErr; i++){
  57830. if( aRoot[i]==0 ) continue;
  57831. #ifndef SQLITE_OMIT_AUTOVACUUM
  57832. if( pBt->autoVacuum && aRoot[i]>1 ){
  57833. checkPtrmap(&sCheck, aRoot[i], PTRMAP_ROOTPAGE, 0);
  57834. }
  57835. #endif
  57836. sCheck.zPfx = "List of tree roots: ";
  57837. checkTreePage(&sCheck, aRoot[i], NULL, NULL);
  57838. sCheck.zPfx = 0;
  57839. }
  57840. /* Make sure every page in the file is referenced
  57841. */
  57842. for(i=1; i<=sCheck.nPage && sCheck.mxErr; i++){
  57843. #ifdef SQLITE_OMIT_AUTOVACUUM
  57844. if( getPageReferenced(&sCheck, i)==0 ){
  57845. checkAppendMsg(&sCheck, "Page %d is never used", i);
  57846. }
  57847. #else
  57848. /* If the database supports auto-vacuum, make sure no tables contain
  57849. ** references to pointer-map pages.
  57850. */
  57851. if( getPageReferenced(&sCheck, i)==0 &&
  57852. (PTRMAP_PAGENO(pBt, i)!=i || !pBt->autoVacuum) ){
  57853. checkAppendMsg(&sCheck, "Page %d is never used", i);
  57854. }
  57855. if( getPageReferenced(&sCheck, i)!=0 &&
  57856. (PTRMAP_PAGENO(pBt, i)==i && pBt->autoVacuum) ){
  57857. checkAppendMsg(&sCheck, "Pointer map page %d is referenced", i);
  57858. }
  57859. #endif
  57860. }
  57861. /* Make sure this analysis did not leave any unref() pages.
  57862. ** This is an internal consistency check; an integrity check
  57863. ** of the integrity check.
  57864. */
  57865. if( NEVER(nRef != sqlite3PagerRefcount(pBt->pPager)) ){
  57866. checkAppendMsg(&sCheck,
  57867. "Outstanding page count goes from %d to %d during this analysis",
  57868. nRef, sqlite3PagerRefcount(pBt->pPager)
  57869. );
  57870. }
  57871. /* Clean up and report errors.
  57872. */
  57873. sqlite3BtreeLeave(p);
  57874. sqlite3_free(sCheck.aPgRef);
  57875. if( sCheck.mallocFailed ){
  57876. sqlite3StrAccumReset(&sCheck.errMsg);
  57877. *pnErr = sCheck.nErr+1;
  57878. return 0;
  57879. }
  57880. *pnErr = sCheck.nErr;
  57881. if( sCheck.nErr==0 ) sqlite3StrAccumReset(&sCheck.errMsg);
  57882. return sqlite3StrAccumFinish(&sCheck.errMsg);
  57883. }
  57884. #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
  57885. /*
  57886. ** Return the full pathname of the underlying database file. Return
  57887. ** an empty string if the database is in-memory or a TEMP database.
  57888. **
  57889. ** The pager filename is invariant as long as the pager is
  57890. ** open so it is safe to access without the BtShared mutex.
  57891. */
  57892. SQLITE_PRIVATE const char *sqlite3BtreeGetFilename(Btree *p){
  57893. assert( p->pBt->pPager!=0 );
  57894. return sqlite3PagerFilename(p->pBt->pPager, 1);
  57895. }
  57896. /*
  57897. ** Return the pathname of the journal file for this database. The return
  57898. ** value of this routine is the same regardless of whether the journal file
  57899. ** has been created or not.
  57900. **
  57901. ** The pager journal filename is invariant as long as the pager is
  57902. ** open so it is safe to access without the BtShared mutex.
  57903. */
  57904. SQLITE_PRIVATE const char *sqlite3BtreeGetJournalname(Btree *p){
  57905. assert( p->pBt->pPager!=0 );
  57906. return sqlite3PagerJournalname(p->pBt->pPager);
  57907. }
  57908. /*
  57909. ** Return non-zero if a transaction is active.
  57910. */
  57911. SQLITE_PRIVATE int sqlite3BtreeIsInTrans(Btree *p){
  57912. assert( p==0 || sqlite3_mutex_held(p->db->mutex) );
  57913. return (p && (p->inTrans==TRANS_WRITE));
  57914. }
  57915. #ifndef SQLITE_OMIT_WAL
  57916. /*
  57917. ** Run a checkpoint on the Btree passed as the first argument.
  57918. **
  57919. ** Return SQLITE_LOCKED if this or any other connection has an open
  57920. ** transaction on the shared-cache the argument Btree is connected to.
  57921. **
  57922. ** Parameter eMode is one of SQLITE_CHECKPOINT_PASSIVE, FULL or RESTART.
  57923. */
  57924. SQLITE_PRIVATE int sqlite3BtreeCheckpoint(Btree *p, int eMode, int *pnLog, int *pnCkpt){
  57925. int rc = SQLITE_OK;
  57926. if( p ){
  57927. BtShared *pBt = p->pBt;
  57928. sqlite3BtreeEnter(p);
  57929. if( pBt->inTransaction!=TRANS_NONE ){
  57930. rc = SQLITE_LOCKED;
  57931. }else{
  57932. rc = sqlite3PagerCheckpoint(pBt->pPager, eMode, pnLog, pnCkpt);
  57933. }
  57934. sqlite3BtreeLeave(p);
  57935. }
  57936. return rc;
  57937. }
  57938. #endif
  57939. /*
  57940. ** Return non-zero if a read (or write) transaction is active.
  57941. */
  57942. SQLITE_PRIVATE int sqlite3BtreeIsInReadTrans(Btree *p){
  57943. assert( p );
  57944. assert( sqlite3_mutex_held(p->db->mutex) );
  57945. return p->inTrans!=TRANS_NONE;
  57946. }
  57947. SQLITE_PRIVATE int sqlite3BtreeIsInBackup(Btree *p){
  57948. assert( p );
  57949. assert( sqlite3_mutex_held(p->db->mutex) );
  57950. return p->nBackup!=0;
  57951. }
  57952. /*
  57953. ** This function returns a pointer to a blob of memory associated with
  57954. ** a single shared-btree. The memory is used by client code for its own
  57955. ** purposes (for example, to store a high-level schema associated with
  57956. ** the shared-btree). The btree layer manages reference counting issues.
  57957. **
  57958. ** The first time this is called on a shared-btree, nBytes bytes of memory
  57959. ** are allocated, zeroed, and returned to the caller. For each subsequent
  57960. ** call the nBytes parameter is ignored and a pointer to the same blob
  57961. ** of memory returned.
  57962. **
  57963. ** If the nBytes parameter is 0 and the blob of memory has not yet been
  57964. ** allocated, a null pointer is returned. If the blob has already been
  57965. ** allocated, it is returned as normal.
  57966. **
  57967. ** Just before the shared-btree is closed, the function passed as the
  57968. ** xFree argument when the memory allocation was made is invoked on the
  57969. ** blob of allocated memory. The xFree function should not call sqlite3_free()
  57970. ** on the memory, the btree layer does that.
  57971. */
  57972. SQLITE_PRIVATE void *sqlite3BtreeSchema(Btree *p, int nBytes, void(*xFree)(void *)){
  57973. BtShared *pBt = p->pBt;
  57974. sqlite3BtreeEnter(p);
  57975. if( !pBt->pSchema && nBytes ){
  57976. pBt->pSchema = sqlite3DbMallocZero(0, nBytes);
  57977. pBt->xFreeSchema = xFree;
  57978. }
  57979. sqlite3BtreeLeave(p);
  57980. return pBt->pSchema;
  57981. }
  57982. /*
  57983. ** Return SQLITE_LOCKED_SHAREDCACHE if another user of the same shared
  57984. ** btree as the argument handle holds an exclusive lock on the
  57985. ** sqlite_master table. Otherwise SQLITE_OK.
  57986. */
  57987. SQLITE_PRIVATE int sqlite3BtreeSchemaLocked(Btree *p){
  57988. int rc;
  57989. assert( sqlite3_mutex_held(p->db->mutex) );
  57990. sqlite3BtreeEnter(p);
  57991. rc = querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK);
  57992. assert( rc==SQLITE_OK || rc==SQLITE_LOCKED_SHAREDCACHE );
  57993. sqlite3BtreeLeave(p);
  57994. return rc;
  57995. }
  57996. #ifndef SQLITE_OMIT_SHARED_CACHE
  57997. /*
  57998. ** Obtain a lock on the table whose root page is iTab. The
  57999. ** lock is a write lock if isWritelock is true or a read lock
  58000. ** if it is false.
  58001. */
  58002. SQLITE_PRIVATE int sqlite3BtreeLockTable(Btree *p, int iTab, u8 isWriteLock){
  58003. int rc = SQLITE_OK;
  58004. assert( p->inTrans!=TRANS_NONE );
  58005. if( p->sharable ){
  58006. u8 lockType = READ_LOCK + isWriteLock;
  58007. assert( READ_LOCK+1==WRITE_LOCK );
  58008. assert( isWriteLock==0 || isWriteLock==1 );
  58009. sqlite3BtreeEnter(p);
  58010. rc = querySharedCacheTableLock(p, iTab, lockType);
  58011. if( rc==SQLITE_OK ){
  58012. rc = setSharedCacheTableLock(p, iTab, lockType);
  58013. }
  58014. sqlite3BtreeLeave(p);
  58015. }
  58016. return rc;
  58017. }
  58018. #endif
  58019. #ifndef SQLITE_OMIT_INCRBLOB
  58020. /*
  58021. ** Argument pCsr must be a cursor opened for writing on an
  58022. ** INTKEY table currently pointing at a valid table entry.
  58023. ** This function modifies the data stored as part of that entry.
  58024. **
  58025. ** Only the data content may only be modified, it is not possible to
  58026. ** change the length of the data stored. If this function is called with
  58027. ** parameters that attempt to write past the end of the existing data,
  58028. ** no modifications are made and SQLITE_CORRUPT is returned.
  58029. */
  58030. SQLITE_PRIVATE int sqlite3BtreePutData(BtCursor *pCsr, u32 offset, u32 amt, void *z){
  58031. int rc;
  58032. assert( cursorHoldsMutex(pCsr) );
  58033. assert( sqlite3_mutex_held(pCsr->pBtree->db->mutex) );
  58034. assert( pCsr->curFlags & BTCF_Incrblob );
  58035. rc = restoreCursorPosition(pCsr);
  58036. if( rc!=SQLITE_OK ){
  58037. return rc;
  58038. }
  58039. assert( pCsr->eState!=CURSOR_REQUIRESEEK );
  58040. if( pCsr->eState!=CURSOR_VALID ){
  58041. return SQLITE_ABORT;
  58042. }
  58043. /* Save the positions of all other cursors open on this table. This is
  58044. ** required in case any of them are holding references to an xFetch
  58045. ** version of the b-tree page modified by the accessPayload call below.
  58046. **
  58047. ** Note that pCsr must be open on a INTKEY table and saveCursorPosition()
  58048. ** and hence saveAllCursors() cannot fail on a BTREE_INTKEY table, hence
  58049. ** saveAllCursors can only return SQLITE_OK.
  58050. */
  58051. VVA_ONLY(rc =) saveAllCursors(pCsr->pBt, pCsr->pgnoRoot, pCsr);
  58052. assert( rc==SQLITE_OK );
  58053. /* Check some assumptions:
  58054. ** (a) the cursor is open for writing,
  58055. ** (b) there is a read/write transaction open,
  58056. ** (c) the connection holds a write-lock on the table (if required),
  58057. ** (d) there are no conflicting read-locks, and
  58058. ** (e) the cursor points at a valid row of an intKey table.
  58059. */
  58060. if( (pCsr->curFlags & BTCF_WriteFlag)==0 ){
  58061. return SQLITE_READONLY;
  58062. }
  58063. assert( (pCsr->pBt->btsFlags & BTS_READ_ONLY)==0
  58064. && pCsr->pBt->inTransaction==TRANS_WRITE );
  58065. assert( hasSharedCacheTableLock(pCsr->pBtree, pCsr->pgnoRoot, 0, 2) );
  58066. assert( !hasReadConflicts(pCsr->pBtree, pCsr->pgnoRoot) );
  58067. assert( pCsr->apPage[pCsr->iPage]->intKey );
  58068. return accessPayload(pCsr, offset, amt, (unsigned char *)z, 1);
  58069. }
  58070. /*
  58071. ** Mark this cursor as an incremental blob cursor.
  58072. */
  58073. SQLITE_PRIVATE void sqlite3BtreeIncrblobCursor(BtCursor *pCur){
  58074. pCur->curFlags |= BTCF_Incrblob;
  58075. }
  58076. #endif
  58077. /*
  58078. ** Set both the "read version" (single byte at byte offset 18) and
  58079. ** "write version" (single byte at byte offset 19) fields in the database
  58080. ** header to iVersion.
  58081. */
  58082. SQLITE_PRIVATE int sqlite3BtreeSetVersion(Btree *pBtree, int iVersion){
  58083. BtShared *pBt = pBtree->pBt;
  58084. int rc; /* Return code */
  58085. assert( iVersion==1 || iVersion==2 );
  58086. /* If setting the version fields to 1, do not automatically open the
  58087. ** WAL connection, even if the version fields are currently set to 2.
  58088. */
  58089. pBt->btsFlags &= ~BTS_NO_WAL;
  58090. if( iVersion==1 ) pBt->btsFlags |= BTS_NO_WAL;
  58091. rc = sqlite3BtreeBeginTrans(pBtree, 0);
  58092. if( rc==SQLITE_OK ){
  58093. u8 *aData = pBt->pPage1->aData;
  58094. if( aData[18]!=(u8)iVersion || aData[19]!=(u8)iVersion ){
  58095. rc = sqlite3BtreeBeginTrans(pBtree, 2);
  58096. if( rc==SQLITE_OK ){
  58097. rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
  58098. if( rc==SQLITE_OK ){
  58099. aData[18] = (u8)iVersion;
  58100. aData[19] = (u8)iVersion;
  58101. }
  58102. }
  58103. }
  58104. }
  58105. pBt->btsFlags &= ~BTS_NO_WAL;
  58106. return rc;
  58107. }
  58108. /*
  58109. ** set the mask of hint flags for cursor pCsr.
  58110. */
  58111. SQLITE_PRIVATE void sqlite3BtreeCursorHints(BtCursor *pCsr, unsigned int mask){
  58112. assert( mask==BTREE_BULKLOAD || mask==BTREE_SEEK_EQ || mask==0 );
  58113. pCsr->hints = mask;
  58114. }
  58115. #ifdef SQLITE_DEBUG
  58116. /*
  58117. ** Return true if the cursor has a hint specified. This routine is
  58118. ** only used from within assert() statements
  58119. */
  58120. SQLITE_PRIVATE int sqlite3BtreeCursorHasHint(BtCursor *pCsr, unsigned int mask){
  58121. return (pCsr->hints & mask)!=0;
  58122. }
  58123. #endif
  58124. /*
  58125. ** Return true if the given Btree is read-only.
  58126. */
  58127. SQLITE_PRIVATE int sqlite3BtreeIsReadonly(Btree *p){
  58128. return (p->pBt->btsFlags & BTS_READ_ONLY)!=0;
  58129. }
  58130. /*
  58131. ** Return the size of the header added to each page by this module.
  58132. */
  58133. SQLITE_PRIVATE int sqlite3HeaderSizeBtree(void){ return ROUND8(sizeof(MemPage)); }
  58134. /************** End of btree.c ***********************************************/
  58135. /************** Begin file backup.c ******************************************/
  58136. /*
  58137. ** 2009 January 28
  58138. **
  58139. ** The author disclaims copyright to this source code. In place of
  58140. ** a legal notice, here is a blessing:
  58141. **
  58142. ** May you do good and not evil.
  58143. ** May you find forgiveness for yourself and forgive others.
  58144. ** May you share freely, never taking more than you give.
  58145. **
  58146. *************************************************************************
  58147. ** This file contains the implementation of the sqlite3_backup_XXX()
  58148. ** API functions and the related features.
  58149. */
  58150. /*
  58151. ** Structure allocated for each backup operation.
  58152. */
  58153. struct sqlite3_backup {
  58154. sqlite3* pDestDb; /* Destination database handle */
  58155. Btree *pDest; /* Destination b-tree file */
  58156. u32 iDestSchema; /* Original schema cookie in destination */
  58157. int bDestLocked; /* True once a write-transaction is open on pDest */
  58158. Pgno iNext; /* Page number of the next source page to copy */
  58159. sqlite3* pSrcDb; /* Source database handle */
  58160. Btree *pSrc; /* Source b-tree file */
  58161. int rc; /* Backup process error code */
  58162. /* These two variables are set by every call to backup_step(). They are
  58163. ** read by calls to backup_remaining() and backup_pagecount().
  58164. */
  58165. Pgno nRemaining; /* Number of pages left to copy */
  58166. Pgno nPagecount; /* Total number of pages to copy */
  58167. int isAttached; /* True once backup has been registered with pager */
  58168. sqlite3_backup *pNext; /* Next backup associated with source pager */
  58169. };
  58170. /*
  58171. ** THREAD SAFETY NOTES:
  58172. **
  58173. ** Once it has been created using backup_init(), a single sqlite3_backup
  58174. ** structure may be accessed via two groups of thread-safe entry points:
  58175. **
  58176. ** * Via the sqlite3_backup_XXX() API function backup_step() and
  58177. ** backup_finish(). Both these functions obtain the source database
  58178. ** handle mutex and the mutex associated with the source BtShared
  58179. ** structure, in that order.
  58180. **
  58181. ** * Via the BackupUpdate() and BackupRestart() functions, which are
  58182. ** invoked by the pager layer to report various state changes in
  58183. ** the page cache associated with the source database. The mutex
  58184. ** associated with the source database BtShared structure will always
  58185. ** be held when either of these functions are invoked.
  58186. **
  58187. ** The other sqlite3_backup_XXX() API functions, backup_remaining() and
  58188. ** backup_pagecount() are not thread-safe functions. If they are called
  58189. ** while some other thread is calling backup_step() or backup_finish(),
  58190. ** the values returned may be invalid. There is no way for a call to
  58191. ** BackupUpdate() or BackupRestart() to interfere with backup_remaining()
  58192. ** or backup_pagecount().
  58193. **
  58194. ** Depending on the SQLite configuration, the database handles and/or
  58195. ** the Btree objects may have their own mutexes that require locking.
  58196. ** Non-sharable Btrees (in-memory databases for example), do not have
  58197. ** associated mutexes.
  58198. */
  58199. /*
  58200. ** Return a pointer corresponding to database zDb (i.e. "main", "temp")
  58201. ** in connection handle pDb. If such a database cannot be found, return
  58202. ** a NULL pointer and write an error message to pErrorDb.
  58203. **
  58204. ** If the "temp" database is requested, it may need to be opened by this
  58205. ** function. If an error occurs while doing so, return 0 and write an
  58206. ** error message to pErrorDb.
  58207. */
  58208. static Btree *findBtree(sqlite3 *pErrorDb, sqlite3 *pDb, const char *zDb){
  58209. int i = sqlite3FindDbName(pDb, zDb);
  58210. if( i==1 ){
  58211. Parse *pParse;
  58212. int rc = 0;
  58213. pParse = sqlite3StackAllocZero(pErrorDb, sizeof(*pParse));
  58214. if( pParse==0 ){
  58215. sqlite3ErrorWithMsg(pErrorDb, SQLITE_NOMEM, "out of memory");
  58216. rc = SQLITE_NOMEM;
  58217. }else{
  58218. pParse->db = pDb;
  58219. if( sqlite3OpenTempDatabase(pParse) ){
  58220. sqlite3ErrorWithMsg(pErrorDb, pParse->rc, "%s", pParse->zErrMsg);
  58221. rc = SQLITE_ERROR;
  58222. }
  58223. sqlite3DbFree(pErrorDb, pParse->zErrMsg);
  58224. sqlite3ParserReset(pParse);
  58225. sqlite3StackFree(pErrorDb, pParse);
  58226. }
  58227. if( rc ){
  58228. return 0;
  58229. }
  58230. }
  58231. if( i<0 ){
  58232. sqlite3ErrorWithMsg(pErrorDb, SQLITE_ERROR, "unknown database %s", zDb);
  58233. return 0;
  58234. }
  58235. return pDb->aDb[i].pBt;
  58236. }
  58237. /*
  58238. ** Attempt to set the page size of the destination to match the page size
  58239. ** of the source.
  58240. */
  58241. static int setDestPgsz(sqlite3_backup *p){
  58242. int rc;
  58243. rc = sqlite3BtreeSetPageSize(p->pDest,sqlite3BtreeGetPageSize(p->pSrc),-1,0);
  58244. return rc;
  58245. }
  58246. /*
  58247. ** Check that there is no open read-transaction on the b-tree passed as the
  58248. ** second argument. If there is not, return SQLITE_OK. Otherwise, if there
  58249. ** is an open read-transaction, return SQLITE_ERROR and leave an error
  58250. ** message in database handle db.
  58251. */
  58252. static int checkReadTransaction(sqlite3 *db, Btree *p){
  58253. if( sqlite3BtreeIsInReadTrans(p) ){
  58254. sqlite3ErrorWithMsg(db, SQLITE_ERROR, "destination database is in use");
  58255. return SQLITE_ERROR;
  58256. }
  58257. return SQLITE_OK;
  58258. }
  58259. /*
  58260. ** Create an sqlite3_backup process to copy the contents of zSrcDb from
  58261. ** connection handle pSrcDb to zDestDb in pDestDb. If successful, return
  58262. ** a pointer to the new sqlite3_backup object.
  58263. **
  58264. ** If an error occurs, NULL is returned and an error code and error message
  58265. ** stored in database handle pDestDb.
  58266. */
  58267. SQLITE_API sqlite3_backup *SQLITE_STDCALL sqlite3_backup_init(
  58268. sqlite3* pDestDb, /* Database to write to */
  58269. const char *zDestDb, /* Name of database within pDestDb */
  58270. sqlite3* pSrcDb, /* Database connection to read from */
  58271. const char *zSrcDb /* Name of database within pSrcDb */
  58272. ){
  58273. sqlite3_backup *p; /* Value to return */
  58274. #ifdef SQLITE_ENABLE_API_ARMOR
  58275. if( !sqlite3SafetyCheckOk(pSrcDb)||!sqlite3SafetyCheckOk(pDestDb) ){
  58276. (void)SQLITE_MISUSE_BKPT;
  58277. return 0;
  58278. }
  58279. #endif
  58280. /* Lock the source database handle. The destination database
  58281. ** handle is not locked in this routine, but it is locked in
  58282. ** sqlite3_backup_step(). The user is required to ensure that no
  58283. ** other thread accesses the destination handle for the duration
  58284. ** of the backup operation. Any attempt to use the destination
  58285. ** database connection while a backup is in progress may cause
  58286. ** a malfunction or a deadlock.
  58287. */
  58288. sqlite3_mutex_enter(pSrcDb->mutex);
  58289. sqlite3_mutex_enter(pDestDb->mutex);
  58290. if( pSrcDb==pDestDb ){
  58291. sqlite3ErrorWithMsg(
  58292. pDestDb, SQLITE_ERROR, "source and destination must be distinct"
  58293. );
  58294. p = 0;
  58295. }else {
  58296. /* Allocate space for a new sqlite3_backup object...
  58297. ** EVIDENCE-OF: R-64852-21591 The sqlite3_backup object is created by a
  58298. ** call to sqlite3_backup_init() and is destroyed by a call to
  58299. ** sqlite3_backup_finish(). */
  58300. p = (sqlite3_backup *)sqlite3MallocZero(sizeof(sqlite3_backup));
  58301. if( !p ){
  58302. sqlite3Error(pDestDb, SQLITE_NOMEM);
  58303. }
  58304. }
  58305. /* If the allocation succeeded, populate the new object. */
  58306. if( p ){
  58307. p->pSrc = findBtree(pDestDb, pSrcDb, zSrcDb);
  58308. p->pDest = findBtree(pDestDb, pDestDb, zDestDb);
  58309. p->pDestDb = pDestDb;
  58310. p->pSrcDb = pSrcDb;
  58311. p->iNext = 1;
  58312. p->isAttached = 0;
  58313. if( 0==p->pSrc || 0==p->pDest
  58314. || setDestPgsz(p)==SQLITE_NOMEM
  58315. || checkReadTransaction(pDestDb, p->pDest)!=SQLITE_OK
  58316. ){
  58317. /* One (or both) of the named databases did not exist or an OOM
  58318. ** error was hit. Or there is a transaction open on the destination
  58319. ** database. The error has already been written into the pDestDb
  58320. ** handle. All that is left to do here is free the sqlite3_backup
  58321. ** structure. */
  58322. sqlite3_free(p);
  58323. p = 0;
  58324. }
  58325. }
  58326. if( p ){
  58327. p->pSrc->nBackup++;
  58328. }
  58329. sqlite3_mutex_leave(pDestDb->mutex);
  58330. sqlite3_mutex_leave(pSrcDb->mutex);
  58331. return p;
  58332. }
  58333. /*
  58334. ** Argument rc is an SQLite error code. Return true if this error is
  58335. ** considered fatal if encountered during a backup operation. All errors
  58336. ** are considered fatal except for SQLITE_BUSY and SQLITE_LOCKED.
  58337. */
  58338. static int isFatalError(int rc){
  58339. return (rc!=SQLITE_OK && rc!=SQLITE_BUSY && ALWAYS(rc!=SQLITE_LOCKED));
  58340. }
  58341. /*
  58342. ** Parameter zSrcData points to a buffer containing the data for
  58343. ** page iSrcPg from the source database. Copy this data into the
  58344. ** destination database.
  58345. */
  58346. static int backupOnePage(
  58347. sqlite3_backup *p, /* Backup handle */
  58348. Pgno iSrcPg, /* Source database page to backup */
  58349. const u8 *zSrcData, /* Source database page data */
  58350. int bUpdate /* True for an update, false otherwise */
  58351. ){
  58352. Pager * const pDestPager = sqlite3BtreePager(p->pDest);
  58353. const int nSrcPgsz = sqlite3BtreeGetPageSize(p->pSrc);
  58354. int nDestPgsz = sqlite3BtreeGetPageSize(p->pDest);
  58355. const int nCopy = MIN(nSrcPgsz, nDestPgsz);
  58356. const i64 iEnd = (i64)iSrcPg*(i64)nSrcPgsz;
  58357. #ifdef SQLITE_HAS_CODEC
  58358. /* Use BtreeGetReserveNoMutex() for the source b-tree, as although it is
  58359. ** guaranteed that the shared-mutex is held by this thread, handle
  58360. ** p->pSrc may not actually be the owner. */
  58361. int nSrcReserve = sqlite3BtreeGetReserveNoMutex(p->pSrc);
  58362. int nDestReserve = sqlite3BtreeGetOptimalReserve(p->pDest);
  58363. #endif
  58364. int rc = SQLITE_OK;
  58365. i64 iOff;
  58366. assert( sqlite3BtreeGetReserveNoMutex(p->pSrc)>=0 );
  58367. assert( p->bDestLocked );
  58368. assert( !isFatalError(p->rc) );
  58369. assert( iSrcPg!=PENDING_BYTE_PAGE(p->pSrc->pBt) );
  58370. assert( zSrcData );
  58371. /* Catch the case where the destination is an in-memory database and the
  58372. ** page sizes of the source and destination differ.
  58373. */
  58374. if( nSrcPgsz!=nDestPgsz && sqlite3PagerIsMemdb(pDestPager) ){
  58375. rc = SQLITE_READONLY;
  58376. }
  58377. #ifdef SQLITE_HAS_CODEC
  58378. /* Backup is not possible if the page size of the destination is changing
  58379. ** and a codec is in use.
  58380. */
  58381. if( nSrcPgsz!=nDestPgsz && sqlite3PagerGetCodec(pDestPager)!=0 ){
  58382. rc = SQLITE_READONLY;
  58383. }
  58384. /* Backup is not possible if the number of bytes of reserve space differ
  58385. ** between source and destination. If there is a difference, try to
  58386. ** fix the destination to agree with the source. If that is not possible,
  58387. ** then the backup cannot proceed.
  58388. */
  58389. if( nSrcReserve!=nDestReserve ){
  58390. u32 newPgsz = nSrcPgsz;
  58391. rc = sqlite3PagerSetPagesize(pDestPager, &newPgsz, nSrcReserve);
  58392. if( rc==SQLITE_OK && newPgsz!=nSrcPgsz ) rc = SQLITE_READONLY;
  58393. }
  58394. #endif
  58395. /* This loop runs once for each destination page spanned by the source
  58396. ** page. For each iteration, variable iOff is set to the byte offset
  58397. ** of the destination page.
  58398. */
  58399. for(iOff=iEnd-(i64)nSrcPgsz; rc==SQLITE_OK && iOff<iEnd; iOff+=nDestPgsz){
  58400. DbPage *pDestPg = 0;
  58401. Pgno iDest = (Pgno)(iOff/nDestPgsz)+1;
  58402. if( iDest==PENDING_BYTE_PAGE(p->pDest->pBt) ) continue;
  58403. if( SQLITE_OK==(rc = sqlite3PagerGet(pDestPager, iDest, &pDestPg))
  58404. && SQLITE_OK==(rc = sqlite3PagerWrite(pDestPg))
  58405. ){
  58406. const u8 *zIn = &zSrcData[iOff%nSrcPgsz];
  58407. u8 *zDestData = sqlite3PagerGetData(pDestPg);
  58408. u8 *zOut = &zDestData[iOff%nDestPgsz];
  58409. /* Copy the data from the source page into the destination page.
  58410. ** Then clear the Btree layer MemPage.isInit flag. Both this module
  58411. ** and the pager code use this trick (clearing the first byte
  58412. ** of the page 'extra' space to invalidate the Btree layers
  58413. ** cached parse of the page). MemPage.isInit is marked
  58414. ** "MUST BE FIRST" for this purpose.
  58415. */
  58416. memcpy(zOut, zIn, nCopy);
  58417. ((u8 *)sqlite3PagerGetExtra(pDestPg))[0] = 0;
  58418. if( iOff==0 && bUpdate==0 ){
  58419. sqlite3Put4byte(&zOut[28], sqlite3BtreeLastPage(p->pSrc));
  58420. }
  58421. }
  58422. sqlite3PagerUnref(pDestPg);
  58423. }
  58424. return rc;
  58425. }
  58426. /*
  58427. ** If pFile is currently larger than iSize bytes, then truncate it to
  58428. ** exactly iSize bytes. If pFile is not larger than iSize bytes, then
  58429. ** this function is a no-op.
  58430. **
  58431. ** Return SQLITE_OK if everything is successful, or an SQLite error
  58432. ** code if an error occurs.
  58433. */
  58434. static int backupTruncateFile(sqlite3_file *pFile, i64 iSize){
  58435. i64 iCurrent;
  58436. int rc = sqlite3OsFileSize(pFile, &iCurrent);
  58437. if( rc==SQLITE_OK && iCurrent>iSize ){
  58438. rc = sqlite3OsTruncate(pFile, iSize);
  58439. }
  58440. return rc;
  58441. }
  58442. /*
  58443. ** Register this backup object with the associated source pager for
  58444. ** callbacks when pages are changed or the cache invalidated.
  58445. */
  58446. static void attachBackupObject(sqlite3_backup *p){
  58447. sqlite3_backup **pp;
  58448. assert( sqlite3BtreeHoldsMutex(p->pSrc) );
  58449. pp = sqlite3PagerBackupPtr(sqlite3BtreePager(p->pSrc));
  58450. p->pNext = *pp;
  58451. *pp = p;
  58452. p->isAttached = 1;
  58453. }
  58454. /*
  58455. ** Copy nPage pages from the source b-tree to the destination.
  58456. */
  58457. SQLITE_API int SQLITE_STDCALL sqlite3_backup_step(sqlite3_backup *p, int nPage){
  58458. int rc;
  58459. int destMode; /* Destination journal mode */
  58460. int pgszSrc = 0; /* Source page size */
  58461. int pgszDest = 0; /* Destination page size */
  58462. #ifdef SQLITE_ENABLE_API_ARMOR
  58463. if( p==0 ) return SQLITE_MISUSE_BKPT;
  58464. #endif
  58465. sqlite3_mutex_enter(p->pSrcDb->mutex);
  58466. sqlite3BtreeEnter(p->pSrc);
  58467. if( p->pDestDb ){
  58468. sqlite3_mutex_enter(p->pDestDb->mutex);
  58469. }
  58470. rc = p->rc;
  58471. if( !isFatalError(rc) ){
  58472. Pager * const pSrcPager = sqlite3BtreePager(p->pSrc); /* Source pager */
  58473. Pager * const pDestPager = sqlite3BtreePager(p->pDest); /* Dest pager */
  58474. int ii; /* Iterator variable */
  58475. int nSrcPage = -1; /* Size of source db in pages */
  58476. int bCloseTrans = 0; /* True if src db requires unlocking */
  58477. /* If the source pager is currently in a write-transaction, return
  58478. ** SQLITE_BUSY immediately.
  58479. */
  58480. if( p->pDestDb && p->pSrc->pBt->inTransaction==TRANS_WRITE ){
  58481. rc = SQLITE_BUSY;
  58482. }else{
  58483. rc = SQLITE_OK;
  58484. }
  58485. /* Lock the destination database, if it is not locked already. */
  58486. if( SQLITE_OK==rc && p->bDestLocked==0
  58487. && SQLITE_OK==(rc = sqlite3BtreeBeginTrans(p->pDest, 2))
  58488. ){
  58489. p->bDestLocked = 1;
  58490. sqlite3BtreeGetMeta(p->pDest, BTREE_SCHEMA_VERSION, &p->iDestSchema);
  58491. }
  58492. /* If there is no open read-transaction on the source database, open
  58493. ** one now. If a transaction is opened here, then it will be closed
  58494. ** before this function exits.
  58495. */
  58496. if( rc==SQLITE_OK && 0==sqlite3BtreeIsInReadTrans(p->pSrc) ){
  58497. rc = sqlite3BtreeBeginTrans(p->pSrc, 0);
  58498. bCloseTrans = 1;
  58499. }
  58500. /* Do not allow backup if the destination database is in WAL mode
  58501. ** and the page sizes are different between source and destination */
  58502. pgszSrc = sqlite3BtreeGetPageSize(p->pSrc);
  58503. pgszDest = sqlite3BtreeGetPageSize(p->pDest);
  58504. destMode = sqlite3PagerGetJournalMode(sqlite3BtreePager(p->pDest));
  58505. if( SQLITE_OK==rc && destMode==PAGER_JOURNALMODE_WAL && pgszSrc!=pgszDest ){
  58506. rc = SQLITE_READONLY;
  58507. }
  58508. /* Now that there is a read-lock on the source database, query the
  58509. ** source pager for the number of pages in the database.
  58510. */
  58511. nSrcPage = (int)sqlite3BtreeLastPage(p->pSrc);
  58512. assert( nSrcPage>=0 );
  58513. for(ii=0; (nPage<0 || ii<nPage) && p->iNext<=(Pgno)nSrcPage && !rc; ii++){
  58514. const Pgno iSrcPg = p->iNext; /* Source page number */
  58515. if( iSrcPg!=PENDING_BYTE_PAGE(p->pSrc->pBt) ){
  58516. DbPage *pSrcPg; /* Source page object */
  58517. rc = sqlite3PagerAcquire(pSrcPager, iSrcPg, &pSrcPg,
  58518. PAGER_GET_READONLY);
  58519. if( rc==SQLITE_OK ){
  58520. rc = backupOnePage(p, iSrcPg, sqlite3PagerGetData(pSrcPg), 0);
  58521. sqlite3PagerUnref(pSrcPg);
  58522. }
  58523. }
  58524. p->iNext++;
  58525. }
  58526. if( rc==SQLITE_OK ){
  58527. p->nPagecount = nSrcPage;
  58528. p->nRemaining = nSrcPage+1-p->iNext;
  58529. if( p->iNext>(Pgno)nSrcPage ){
  58530. rc = SQLITE_DONE;
  58531. }else if( !p->isAttached ){
  58532. attachBackupObject(p);
  58533. }
  58534. }
  58535. /* Update the schema version field in the destination database. This
  58536. ** is to make sure that the schema-version really does change in
  58537. ** the case where the source and destination databases have the
  58538. ** same schema version.
  58539. */
  58540. if( rc==SQLITE_DONE ){
  58541. if( nSrcPage==0 ){
  58542. rc = sqlite3BtreeNewDb(p->pDest);
  58543. nSrcPage = 1;
  58544. }
  58545. if( rc==SQLITE_OK || rc==SQLITE_DONE ){
  58546. rc = sqlite3BtreeUpdateMeta(p->pDest,1,p->iDestSchema+1);
  58547. }
  58548. if( rc==SQLITE_OK ){
  58549. if( p->pDestDb ){
  58550. sqlite3ResetAllSchemasOfConnection(p->pDestDb);
  58551. }
  58552. if( destMode==PAGER_JOURNALMODE_WAL ){
  58553. rc = sqlite3BtreeSetVersion(p->pDest, 2);
  58554. }
  58555. }
  58556. if( rc==SQLITE_OK ){
  58557. int nDestTruncate;
  58558. /* Set nDestTruncate to the final number of pages in the destination
  58559. ** database. The complication here is that the destination page
  58560. ** size may be different to the source page size.
  58561. **
  58562. ** If the source page size is smaller than the destination page size,
  58563. ** round up. In this case the call to sqlite3OsTruncate() below will
  58564. ** fix the size of the file. However it is important to call
  58565. ** sqlite3PagerTruncateImage() here so that any pages in the
  58566. ** destination file that lie beyond the nDestTruncate page mark are
  58567. ** journalled by PagerCommitPhaseOne() before they are destroyed
  58568. ** by the file truncation.
  58569. */
  58570. assert( pgszSrc==sqlite3BtreeGetPageSize(p->pSrc) );
  58571. assert( pgszDest==sqlite3BtreeGetPageSize(p->pDest) );
  58572. if( pgszSrc<pgszDest ){
  58573. int ratio = pgszDest/pgszSrc;
  58574. nDestTruncate = (nSrcPage+ratio-1)/ratio;
  58575. if( nDestTruncate==(int)PENDING_BYTE_PAGE(p->pDest->pBt) ){
  58576. nDestTruncate--;
  58577. }
  58578. }else{
  58579. nDestTruncate = nSrcPage * (pgszSrc/pgszDest);
  58580. }
  58581. assert( nDestTruncate>0 );
  58582. if( pgszSrc<pgszDest ){
  58583. /* If the source page-size is smaller than the destination page-size,
  58584. ** two extra things may need to happen:
  58585. **
  58586. ** * The destination may need to be truncated, and
  58587. **
  58588. ** * Data stored on the pages immediately following the
  58589. ** pending-byte page in the source database may need to be
  58590. ** copied into the destination database.
  58591. */
  58592. const i64 iSize = (i64)pgszSrc * (i64)nSrcPage;
  58593. sqlite3_file * const pFile = sqlite3PagerFile(pDestPager);
  58594. Pgno iPg;
  58595. int nDstPage;
  58596. i64 iOff;
  58597. i64 iEnd;
  58598. assert( pFile );
  58599. assert( nDestTruncate==0
  58600. || (i64)nDestTruncate*(i64)pgszDest >= iSize || (
  58601. nDestTruncate==(int)(PENDING_BYTE_PAGE(p->pDest->pBt)-1)
  58602. && iSize>=PENDING_BYTE && iSize<=PENDING_BYTE+pgszDest
  58603. ));
  58604. /* This block ensures that all data required to recreate the original
  58605. ** database has been stored in the journal for pDestPager and the
  58606. ** journal synced to disk. So at this point we may safely modify
  58607. ** the database file in any way, knowing that if a power failure
  58608. ** occurs, the original database will be reconstructed from the
  58609. ** journal file. */
  58610. sqlite3PagerPagecount(pDestPager, &nDstPage);
  58611. for(iPg=nDestTruncate; rc==SQLITE_OK && iPg<=(Pgno)nDstPage; iPg++){
  58612. if( iPg!=PENDING_BYTE_PAGE(p->pDest->pBt) ){
  58613. DbPage *pPg;
  58614. rc = sqlite3PagerGet(pDestPager, iPg, &pPg);
  58615. if( rc==SQLITE_OK ){
  58616. rc = sqlite3PagerWrite(pPg);
  58617. sqlite3PagerUnref(pPg);
  58618. }
  58619. }
  58620. }
  58621. if( rc==SQLITE_OK ){
  58622. rc = sqlite3PagerCommitPhaseOne(pDestPager, 0, 1);
  58623. }
  58624. /* Write the extra pages and truncate the database file as required */
  58625. iEnd = MIN(PENDING_BYTE + pgszDest, iSize);
  58626. for(
  58627. iOff=PENDING_BYTE+pgszSrc;
  58628. rc==SQLITE_OK && iOff<iEnd;
  58629. iOff+=pgszSrc
  58630. ){
  58631. PgHdr *pSrcPg = 0;
  58632. const Pgno iSrcPg = (Pgno)((iOff/pgszSrc)+1);
  58633. rc = sqlite3PagerGet(pSrcPager, iSrcPg, &pSrcPg);
  58634. if( rc==SQLITE_OK ){
  58635. u8 *zData = sqlite3PagerGetData(pSrcPg);
  58636. rc = sqlite3OsWrite(pFile, zData, pgszSrc, iOff);
  58637. }
  58638. sqlite3PagerUnref(pSrcPg);
  58639. }
  58640. if( rc==SQLITE_OK ){
  58641. rc = backupTruncateFile(pFile, iSize);
  58642. }
  58643. /* Sync the database file to disk. */
  58644. if( rc==SQLITE_OK ){
  58645. rc = sqlite3PagerSync(pDestPager, 0);
  58646. }
  58647. }else{
  58648. sqlite3PagerTruncateImage(pDestPager, nDestTruncate);
  58649. rc = sqlite3PagerCommitPhaseOne(pDestPager, 0, 0);
  58650. }
  58651. /* Finish committing the transaction to the destination database. */
  58652. if( SQLITE_OK==rc
  58653. && SQLITE_OK==(rc = sqlite3BtreeCommitPhaseTwo(p->pDest, 0))
  58654. ){
  58655. rc = SQLITE_DONE;
  58656. }
  58657. }
  58658. }
  58659. /* If bCloseTrans is true, then this function opened a read transaction
  58660. ** on the source database. Close the read transaction here. There is
  58661. ** no need to check the return values of the btree methods here, as
  58662. ** "committing" a read-only transaction cannot fail.
  58663. */
  58664. if( bCloseTrans ){
  58665. TESTONLY( int rc2 );
  58666. TESTONLY( rc2 = ) sqlite3BtreeCommitPhaseOne(p->pSrc, 0);
  58667. TESTONLY( rc2 |= ) sqlite3BtreeCommitPhaseTwo(p->pSrc, 0);
  58668. assert( rc2==SQLITE_OK );
  58669. }
  58670. if( rc==SQLITE_IOERR_NOMEM ){
  58671. rc = SQLITE_NOMEM;
  58672. }
  58673. p->rc = rc;
  58674. }
  58675. if( p->pDestDb ){
  58676. sqlite3_mutex_leave(p->pDestDb->mutex);
  58677. }
  58678. sqlite3BtreeLeave(p->pSrc);
  58679. sqlite3_mutex_leave(p->pSrcDb->mutex);
  58680. return rc;
  58681. }
  58682. /*
  58683. ** Release all resources associated with an sqlite3_backup* handle.
  58684. */
  58685. SQLITE_API int SQLITE_STDCALL sqlite3_backup_finish(sqlite3_backup *p){
  58686. sqlite3_backup **pp; /* Ptr to head of pagers backup list */
  58687. sqlite3 *pSrcDb; /* Source database connection */
  58688. int rc; /* Value to return */
  58689. /* Enter the mutexes */
  58690. if( p==0 ) return SQLITE_OK;
  58691. pSrcDb = p->pSrcDb;
  58692. sqlite3_mutex_enter(pSrcDb->mutex);
  58693. sqlite3BtreeEnter(p->pSrc);
  58694. if( p->pDestDb ){
  58695. sqlite3_mutex_enter(p->pDestDb->mutex);
  58696. }
  58697. /* Detach this backup from the source pager. */
  58698. if( p->pDestDb ){
  58699. p->pSrc->nBackup--;
  58700. }
  58701. if( p->isAttached ){
  58702. pp = sqlite3PagerBackupPtr(sqlite3BtreePager(p->pSrc));
  58703. while( *pp!=p ){
  58704. pp = &(*pp)->pNext;
  58705. }
  58706. *pp = p->pNext;
  58707. }
  58708. /* If a transaction is still open on the Btree, roll it back. */
  58709. sqlite3BtreeRollback(p->pDest, SQLITE_OK, 0);
  58710. /* Set the error code of the destination database handle. */
  58711. rc = (p->rc==SQLITE_DONE) ? SQLITE_OK : p->rc;
  58712. if( p->pDestDb ){
  58713. sqlite3Error(p->pDestDb, rc);
  58714. /* Exit the mutexes and free the backup context structure. */
  58715. sqlite3LeaveMutexAndCloseZombie(p->pDestDb);
  58716. }
  58717. sqlite3BtreeLeave(p->pSrc);
  58718. if( p->pDestDb ){
  58719. /* EVIDENCE-OF: R-64852-21591 The sqlite3_backup object is created by a
  58720. ** call to sqlite3_backup_init() and is destroyed by a call to
  58721. ** sqlite3_backup_finish(). */
  58722. sqlite3_free(p);
  58723. }
  58724. sqlite3LeaveMutexAndCloseZombie(pSrcDb);
  58725. return rc;
  58726. }
  58727. /*
  58728. ** Return the number of pages still to be backed up as of the most recent
  58729. ** call to sqlite3_backup_step().
  58730. */
  58731. SQLITE_API int SQLITE_STDCALL sqlite3_backup_remaining(sqlite3_backup *p){
  58732. #ifdef SQLITE_ENABLE_API_ARMOR
  58733. if( p==0 ){
  58734. (void)SQLITE_MISUSE_BKPT;
  58735. return 0;
  58736. }
  58737. #endif
  58738. return p->nRemaining;
  58739. }
  58740. /*
  58741. ** Return the total number of pages in the source database as of the most
  58742. ** recent call to sqlite3_backup_step().
  58743. */
  58744. SQLITE_API int SQLITE_STDCALL sqlite3_backup_pagecount(sqlite3_backup *p){
  58745. #ifdef SQLITE_ENABLE_API_ARMOR
  58746. if( p==0 ){
  58747. (void)SQLITE_MISUSE_BKPT;
  58748. return 0;
  58749. }
  58750. #endif
  58751. return p->nPagecount;
  58752. }
  58753. /*
  58754. ** This function is called after the contents of page iPage of the
  58755. ** source database have been modified. If page iPage has already been
  58756. ** copied into the destination database, then the data written to the
  58757. ** destination is now invalidated. The destination copy of iPage needs
  58758. ** to be updated with the new data before the backup operation is
  58759. ** complete.
  58760. **
  58761. ** It is assumed that the mutex associated with the BtShared object
  58762. ** corresponding to the source database is held when this function is
  58763. ** called.
  58764. */
  58765. SQLITE_PRIVATE void sqlite3BackupUpdate(sqlite3_backup *pBackup, Pgno iPage, const u8 *aData){
  58766. sqlite3_backup *p; /* Iterator variable */
  58767. for(p=pBackup; p; p=p->pNext){
  58768. assert( sqlite3_mutex_held(p->pSrc->pBt->mutex) );
  58769. if( !isFatalError(p->rc) && iPage<p->iNext ){
  58770. /* The backup process p has already copied page iPage. But now it
  58771. ** has been modified by a transaction on the source pager. Copy
  58772. ** the new data into the backup.
  58773. */
  58774. int rc;
  58775. assert( p->pDestDb );
  58776. sqlite3_mutex_enter(p->pDestDb->mutex);
  58777. rc = backupOnePage(p, iPage, aData, 1);
  58778. sqlite3_mutex_leave(p->pDestDb->mutex);
  58779. assert( rc!=SQLITE_BUSY && rc!=SQLITE_LOCKED );
  58780. if( rc!=SQLITE_OK ){
  58781. p->rc = rc;
  58782. }
  58783. }
  58784. }
  58785. }
  58786. /*
  58787. ** Restart the backup process. This is called when the pager layer
  58788. ** detects that the database has been modified by an external database
  58789. ** connection. In this case there is no way of knowing which of the
  58790. ** pages that have been copied into the destination database are still
  58791. ** valid and which are not, so the entire process needs to be restarted.
  58792. **
  58793. ** It is assumed that the mutex associated with the BtShared object
  58794. ** corresponding to the source database is held when this function is
  58795. ** called.
  58796. */
  58797. SQLITE_PRIVATE void sqlite3BackupRestart(sqlite3_backup *pBackup){
  58798. sqlite3_backup *p; /* Iterator variable */
  58799. for(p=pBackup; p; p=p->pNext){
  58800. assert( sqlite3_mutex_held(p->pSrc->pBt->mutex) );
  58801. p->iNext = 1;
  58802. }
  58803. }
  58804. #ifndef SQLITE_OMIT_VACUUM
  58805. /*
  58806. ** Copy the complete content of pBtFrom into pBtTo. A transaction
  58807. ** must be active for both files.
  58808. **
  58809. ** The size of file pTo may be reduced by this operation. If anything
  58810. ** goes wrong, the transaction on pTo is rolled back. If successful, the
  58811. ** transaction is committed before returning.
  58812. */
  58813. SQLITE_PRIVATE int sqlite3BtreeCopyFile(Btree *pTo, Btree *pFrom){
  58814. int rc;
  58815. sqlite3_file *pFd; /* File descriptor for database pTo */
  58816. sqlite3_backup b;
  58817. sqlite3BtreeEnter(pTo);
  58818. sqlite3BtreeEnter(pFrom);
  58819. assert( sqlite3BtreeIsInTrans(pTo) );
  58820. pFd = sqlite3PagerFile(sqlite3BtreePager(pTo));
  58821. if( pFd->pMethods ){
  58822. i64 nByte = sqlite3BtreeGetPageSize(pFrom)*(i64)sqlite3BtreeLastPage(pFrom);
  58823. rc = sqlite3OsFileControl(pFd, SQLITE_FCNTL_OVERWRITE, &nByte);
  58824. if( rc==SQLITE_NOTFOUND ) rc = SQLITE_OK;
  58825. if( rc ) goto copy_finished;
  58826. }
  58827. /* Set up an sqlite3_backup object. sqlite3_backup.pDestDb must be set
  58828. ** to 0. This is used by the implementations of sqlite3_backup_step()
  58829. ** and sqlite3_backup_finish() to detect that they are being called
  58830. ** from this function, not directly by the user.
  58831. */
  58832. memset(&b, 0, sizeof(b));
  58833. b.pSrcDb = pFrom->db;
  58834. b.pSrc = pFrom;
  58835. b.pDest = pTo;
  58836. b.iNext = 1;
  58837. /* 0x7FFFFFFF is the hard limit for the number of pages in a database
  58838. ** file. By passing this as the number of pages to copy to
  58839. ** sqlite3_backup_step(), we can guarantee that the copy finishes
  58840. ** within a single call (unless an error occurs). The assert() statement
  58841. ** checks this assumption - (p->rc) should be set to either SQLITE_DONE
  58842. ** or an error code.
  58843. */
  58844. sqlite3_backup_step(&b, 0x7FFFFFFF);
  58845. assert( b.rc!=SQLITE_OK );
  58846. rc = sqlite3_backup_finish(&b);
  58847. if( rc==SQLITE_OK ){
  58848. pTo->pBt->btsFlags &= ~BTS_PAGESIZE_FIXED;
  58849. }else{
  58850. sqlite3PagerClearCache(sqlite3BtreePager(b.pDest));
  58851. }
  58852. assert( sqlite3BtreeIsInTrans(pTo)==0 );
  58853. copy_finished:
  58854. sqlite3BtreeLeave(pFrom);
  58855. sqlite3BtreeLeave(pTo);
  58856. return rc;
  58857. }
  58858. #endif /* SQLITE_OMIT_VACUUM */
  58859. /************** End of backup.c **********************************************/
  58860. /************** Begin file vdbemem.c *****************************************/
  58861. /*
  58862. ** 2004 May 26
  58863. **
  58864. ** The author disclaims copyright to this source code. In place of
  58865. ** a legal notice, here is a blessing:
  58866. **
  58867. ** May you do good and not evil.
  58868. ** May you find forgiveness for yourself and forgive others.
  58869. ** May you share freely, never taking more than you give.
  58870. **
  58871. *************************************************************************
  58872. **
  58873. ** This file contains code use to manipulate "Mem" structure. A "Mem"
  58874. ** stores a single value in the VDBE. Mem is an opaque structure visible
  58875. ** only within the VDBE. Interface routines refer to a Mem using the
  58876. ** name sqlite_value
  58877. */
  58878. #ifdef SQLITE_DEBUG
  58879. /*
  58880. ** Check invariants on a Mem object.
  58881. **
  58882. ** This routine is intended for use inside of assert() statements, like
  58883. ** this: assert( sqlite3VdbeCheckMemInvariants(pMem) );
  58884. */
  58885. SQLITE_PRIVATE int sqlite3VdbeCheckMemInvariants(Mem *p){
  58886. /* If MEM_Dyn is set then Mem.xDel!=0.
  58887. ** Mem.xDel is might not be initialized if MEM_Dyn is clear.
  58888. */
  58889. assert( (p->flags & MEM_Dyn)==0 || p->xDel!=0 );
  58890. /* MEM_Dyn may only be set if Mem.szMalloc==0. In this way we
  58891. ** ensure that if Mem.szMalloc>0 then it is safe to do
  58892. ** Mem.z = Mem.zMalloc without having to check Mem.flags&MEM_Dyn.
  58893. ** That saves a few cycles in inner loops. */
  58894. assert( (p->flags & MEM_Dyn)==0 || p->szMalloc==0 );
  58895. /* Cannot be both MEM_Int and MEM_Real at the same time */
  58896. assert( (p->flags & (MEM_Int|MEM_Real))!=(MEM_Int|MEM_Real) );
  58897. /* The szMalloc field holds the correct memory allocation size */
  58898. assert( p->szMalloc==0
  58899. || p->szMalloc==sqlite3DbMallocSize(p->db,p->zMalloc) );
  58900. /* If p holds a string or blob, the Mem.z must point to exactly
  58901. ** one of the following:
  58902. **
  58903. ** (1) Memory in Mem.zMalloc and managed by the Mem object
  58904. ** (2) Memory to be freed using Mem.xDel
  58905. ** (3) An ephemeral string or blob
  58906. ** (4) A static string or blob
  58907. */
  58908. if( (p->flags & (MEM_Str|MEM_Blob)) && p->n>0 ){
  58909. assert(
  58910. ((p->szMalloc>0 && p->z==p->zMalloc)? 1 : 0) +
  58911. ((p->flags&MEM_Dyn)!=0 ? 1 : 0) +
  58912. ((p->flags&MEM_Ephem)!=0 ? 1 : 0) +
  58913. ((p->flags&MEM_Static)!=0 ? 1 : 0) == 1
  58914. );
  58915. }
  58916. return 1;
  58917. }
  58918. #endif
  58919. /*
  58920. ** If pMem is an object with a valid string representation, this routine
  58921. ** ensures the internal encoding for the string representation is
  58922. ** 'desiredEnc', one of SQLITE_UTF8, SQLITE_UTF16LE or SQLITE_UTF16BE.
  58923. **
  58924. ** If pMem is not a string object, or the encoding of the string
  58925. ** representation is already stored using the requested encoding, then this
  58926. ** routine is a no-op.
  58927. **
  58928. ** SQLITE_OK is returned if the conversion is successful (or not required).
  58929. ** SQLITE_NOMEM may be returned if a malloc() fails during conversion
  58930. ** between formats.
  58931. */
  58932. SQLITE_PRIVATE int sqlite3VdbeChangeEncoding(Mem *pMem, int desiredEnc){
  58933. #ifndef SQLITE_OMIT_UTF16
  58934. int rc;
  58935. #endif
  58936. assert( (pMem->flags&MEM_RowSet)==0 );
  58937. assert( desiredEnc==SQLITE_UTF8 || desiredEnc==SQLITE_UTF16LE
  58938. || desiredEnc==SQLITE_UTF16BE );
  58939. if( !(pMem->flags&MEM_Str) || pMem->enc==desiredEnc ){
  58940. return SQLITE_OK;
  58941. }
  58942. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  58943. #ifdef SQLITE_OMIT_UTF16
  58944. return SQLITE_ERROR;
  58945. #else
  58946. /* MemTranslate() may return SQLITE_OK or SQLITE_NOMEM. If NOMEM is returned,
  58947. ** then the encoding of the value may not have changed.
  58948. */
  58949. rc = sqlite3VdbeMemTranslate(pMem, (u8)desiredEnc);
  58950. assert(rc==SQLITE_OK || rc==SQLITE_NOMEM);
  58951. assert(rc==SQLITE_OK || pMem->enc!=desiredEnc);
  58952. assert(rc==SQLITE_NOMEM || pMem->enc==desiredEnc);
  58953. return rc;
  58954. #endif
  58955. }
  58956. /*
  58957. ** Make sure pMem->z points to a writable allocation of at least
  58958. ** min(n,32) bytes.
  58959. **
  58960. ** If the bPreserve argument is true, then copy of the content of
  58961. ** pMem->z into the new allocation. pMem must be either a string or
  58962. ** blob if bPreserve is true. If bPreserve is false, any prior content
  58963. ** in pMem->z is discarded.
  58964. */
  58965. SQLITE_PRIVATE SQLITE_NOINLINE int sqlite3VdbeMemGrow(Mem *pMem, int n, int bPreserve){
  58966. assert( sqlite3VdbeCheckMemInvariants(pMem) );
  58967. assert( (pMem->flags&MEM_RowSet)==0 );
  58968. /* If the bPreserve flag is set to true, then the memory cell must already
  58969. ** contain a valid string or blob value. */
  58970. assert( bPreserve==0 || pMem->flags&(MEM_Blob|MEM_Str) );
  58971. testcase( bPreserve && pMem->z==0 );
  58972. assert( pMem->szMalloc==0
  58973. || pMem->szMalloc==sqlite3DbMallocSize(pMem->db, pMem->zMalloc) );
  58974. if( pMem->szMalloc<n ){
  58975. if( n<32 ) n = 32;
  58976. if( bPreserve && pMem->szMalloc>0 && pMem->z==pMem->zMalloc ){
  58977. pMem->z = pMem->zMalloc = sqlite3DbReallocOrFree(pMem->db, pMem->z, n);
  58978. bPreserve = 0;
  58979. }else{
  58980. if( pMem->szMalloc>0 ) sqlite3DbFree(pMem->db, pMem->zMalloc);
  58981. pMem->zMalloc = sqlite3DbMallocRaw(pMem->db, n);
  58982. }
  58983. if( pMem->zMalloc==0 ){
  58984. sqlite3VdbeMemSetNull(pMem);
  58985. pMem->z = 0;
  58986. pMem->szMalloc = 0;
  58987. return SQLITE_NOMEM;
  58988. }else{
  58989. pMem->szMalloc = sqlite3DbMallocSize(pMem->db, pMem->zMalloc);
  58990. }
  58991. }
  58992. if( bPreserve && pMem->z && pMem->z!=pMem->zMalloc ){
  58993. memcpy(pMem->zMalloc, pMem->z, pMem->n);
  58994. }
  58995. if( (pMem->flags&MEM_Dyn)!=0 ){
  58996. assert( pMem->xDel!=0 && pMem->xDel!=SQLITE_DYNAMIC );
  58997. pMem->xDel((void *)(pMem->z));
  58998. }
  58999. pMem->z = pMem->zMalloc;
  59000. pMem->flags &= ~(MEM_Dyn|MEM_Ephem|MEM_Static);
  59001. return SQLITE_OK;
  59002. }
  59003. /*
  59004. ** Change the pMem->zMalloc allocation to be at least szNew bytes.
  59005. ** If pMem->zMalloc already meets or exceeds the requested size, this
  59006. ** routine is a no-op.
  59007. **
  59008. ** Any prior string or blob content in the pMem object may be discarded.
  59009. ** The pMem->xDel destructor is called, if it exists. Though MEM_Str
  59010. ** and MEM_Blob values may be discarded, MEM_Int, MEM_Real, and MEM_Null
  59011. ** values are preserved.
  59012. **
  59013. ** Return SQLITE_OK on success or an error code (probably SQLITE_NOMEM)
  59014. ** if unable to complete the resizing.
  59015. */
  59016. SQLITE_PRIVATE int sqlite3VdbeMemClearAndResize(Mem *pMem, int szNew){
  59017. assert( szNew>0 );
  59018. assert( (pMem->flags & MEM_Dyn)==0 || pMem->szMalloc==0 );
  59019. if( pMem->szMalloc<szNew ){
  59020. return sqlite3VdbeMemGrow(pMem, szNew, 0);
  59021. }
  59022. assert( (pMem->flags & MEM_Dyn)==0 );
  59023. pMem->z = pMem->zMalloc;
  59024. pMem->flags &= (MEM_Null|MEM_Int|MEM_Real);
  59025. return SQLITE_OK;
  59026. }
  59027. /*
  59028. ** Change pMem so that its MEM_Str or MEM_Blob value is stored in
  59029. ** MEM.zMalloc, where it can be safely written.
  59030. **
  59031. ** Return SQLITE_OK on success or SQLITE_NOMEM if malloc fails.
  59032. */
  59033. SQLITE_PRIVATE int sqlite3VdbeMemMakeWriteable(Mem *pMem){
  59034. int f;
  59035. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  59036. assert( (pMem->flags&MEM_RowSet)==0 );
  59037. ExpandBlob(pMem);
  59038. f = pMem->flags;
  59039. if( (f&(MEM_Str|MEM_Blob)) && (pMem->szMalloc==0 || pMem->z!=pMem->zMalloc) ){
  59040. if( sqlite3VdbeMemGrow(pMem, pMem->n + 2, 1) ){
  59041. return SQLITE_NOMEM;
  59042. }
  59043. pMem->z[pMem->n] = 0;
  59044. pMem->z[pMem->n+1] = 0;
  59045. pMem->flags |= MEM_Term;
  59046. }
  59047. pMem->flags &= ~MEM_Ephem;
  59048. #ifdef SQLITE_DEBUG
  59049. pMem->pScopyFrom = 0;
  59050. #endif
  59051. return SQLITE_OK;
  59052. }
  59053. /*
  59054. ** If the given Mem* has a zero-filled tail, turn it into an ordinary
  59055. ** blob stored in dynamically allocated space.
  59056. */
  59057. #ifndef SQLITE_OMIT_INCRBLOB
  59058. SQLITE_PRIVATE int sqlite3VdbeMemExpandBlob(Mem *pMem){
  59059. if( pMem->flags & MEM_Zero ){
  59060. int nByte;
  59061. assert( pMem->flags&MEM_Blob );
  59062. assert( (pMem->flags&MEM_RowSet)==0 );
  59063. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  59064. /* Set nByte to the number of bytes required to store the expanded blob. */
  59065. nByte = pMem->n + pMem->u.nZero;
  59066. if( nByte<=0 ){
  59067. nByte = 1;
  59068. }
  59069. if( sqlite3VdbeMemGrow(pMem, nByte, 1) ){
  59070. return SQLITE_NOMEM;
  59071. }
  59072. memset(&pMem->z[pMem->n], 0, pMem->u.nZero);
  59073. pMem->n += pMem->u.nZero;
  59074. pMem->flags &= ~(MEM_Zero|MEM_Term);
  59075. }
  59076. return SQLITE_OK;
  59077. }
  59078. #endif
  59079. /*
  59080. ** It is already known that pMem contains an unterminated string.
  59081. ** Add the zero terminator.
  59082. */
  59083. static SQLITE_NOINLINE int vdbeMemAddTerminator(Mem *pMem){
  59084. if( sqlite3VdbeMemGrow(pMem, pMem->n+2, 1) ){
  59085. return SQLITE_NOMEM;
  59086. }
  59087. pMem->z[pMem->n] = 0;
  59088. pMem->z[pMem->n+1] = 0;
  59089. pMem->flags |= MEM_Term;
  59090. return SQLITE_OK;
  59091. }
  59092. /*
  59093. ** Make sure the given Mem is \u0000 terminated.
  59094. */
  59095. SQLITE_PRIVATE int sqlite3VdbeMemNulTerminate(Mem *pMem){
  59096. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  59097. testcase( (pMem->flags & (MEM_Term|MEM_Str))==(MEM_Term|MEM_Str) );
  59098. testcase( (pMem->flags & (MEM_Term|MEM_Str))==0 );
  59099. if( (pMem->flags & (MEM_Term|MEM_Str))!=MEM_Str ){
  59100. return SQLITE_OK; /* Nothing to do */
  59101. }else{
  59102. return vdbeMemAddTerminator(pMem);
  59103. }
  59104. }
  59105. /*
  59106. ** Add MEM_Str to the set of representations for the given Mem. Numbers
  59107. ** are converted using sqlite3_snprintf(). Converting a BLOB to a string
  59108. ** is a no-op.
  59109. **
  59110. ** Existing representations MEM_Int and MEM_Real are invalidated if
  59111. ** bForce is true but are retained if bForce is false.
  59112. **
  59113. ** A MEM_Null value will never be passed to this function. This function is
  59114. ** used for converting values to text for returning to the user (i.e. via
  59115. ** sqlite3_value_text()), or for ensuring that values to be used as btree
  59116. ** keys are strings. In the former case a NULL pointer is returned the
  59117. ** user and the latter is an internal programming error.
  59118. */
  59119. SQLITE_PRIVATE int sqlite3VdbeMemStringify(Mem *pMem, u8 enc, u8 bForce){
  59120. int fg = pMem->flags;
  59121. const int nByte = 32;
  59122. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  59123. assert( !(fg&MEM_Zero) );
  59124. assert( !(fg&(MEM_Str|MEM_Blob)) );
  59125. assert( fg&(MEM_Int|MEM_Real) );
  59126. assert( (pMem->flags&MEM_RowSet)==0 );
  59127. assert( EIGHT_BYTE_ALIGNMENT(pMem) );
  59128. if( sqlite3VdbeMemClearAndResize(pMem, nByte) ){
  59129. return SQLITE_NOMEM;
  59130. }
  59131. /* For a Real or Integer, use sqlite3_snprintf() to produce the UTF-8
  59132. ** string representation of the value. Then, if the required encoding
  59133. ** is UTF-16le or UTF-16be do a translation.
  59134. **
  59135. ** FIX ME: It would be better if sqlite3_snprintf() could do UTF-16.
  59136. */
  59137. if( fg & MEM_Int ){
  59138. sqlite3_snprintf(nByte, pMem->z, "%lld", pMem->u.i);
  59139. }else{
  59140. assert( fg & MEM_Real );
  59141. sqlite3_snprintf(nByte, pMem->z, "%!.15g", pMem->u.r);
  59142. }
  59143. pMem->n = sqlite3Strlen30(pMem->z);
  59144. pMem->enc = SQLITE_UTF8;
  59145. pMem->flags |= MEM_Str|MEM_Term;
  59146. if( bForce ) pMem->flags &= ~(MEM_Int|MEM_Real);
  59147. sqlite3VdbeChangeEncoding(pMem, enc);
  59148. return SQLITE_OK;
  59149. }
  59150. /*
  59151. ** Memory cell pMem contains the context of an aggregate function.
  59152. ** This routine calls the finalize method for that function. The
  59153. ** result of the aggregate is stored back into pMem.
  59154. **
  59155. ** Return SQLITE_ERROR if the finalizer reports an error. SQLITE_OK
  59156. ** otherwise.
  59157. */
  59158. SQLITE_PRIVATE int sqlite3VdbeMemFinalize(Mem *pMem, FuncDef *pFunc){
  59159. int rc = SQLITE_OK;
  59160. if( ALWAYS(pFunc && pFunc->xFinalize) ){
  59161. sqlite3_context ctx;
  59162. Mem t;
  59163. assert( (pMem->flags & MEM_Null)!=0 || pFunc==pMem->u.pDef );
  59164. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  59165. memset(&ctx, 0, sizeof(ctx));
  59166. memset(&t, 0, sizeof(t));
  59167. t.flags = MEM_Null;
  59168. t.db = pMem->db;
  59169. ctx.pOut = &t;
  59170. ctx.pMem = pMem;
  59171. ctx.pFunc = pFunc;
  59172. pFunc->xFinalize(&ctx); /* IMP: R-24505-23230 */
  59173. assert( (pMem->flags & MEM_Dyn)==0 );
  59174. if( pMem->szMalloc>0 ) sqlite3DbFree(pMem->db, pMem->zMalloc);
  59175. memcpy(pMem, &t, sizeof(t));
  59176. rc = ctx.isError;
  59177. }
  59178. return rc;
  59179. }
  59180. /*
  59181. ** If the memory cell contains a value that must be freed by
  59182. ** invoking the external callback in Mem.xDel, then this routine
  59183. ** will free that value. It also sets Mem.flags to MEM_Null.
  59184. **
  59185. ** This is a helper routine for sqlite3VdbeMemSetNull() and
  59186. ** for sqlite3VdbeMemRelease(). Use those other routines as the
  59187. ** entry point for releasing Mem resources.
  59188. */
  59189. static SQLITE_NOINLINE void vdbeMemClearExternAndSetNull(Mem *p){
  59190. assert( p->db==0 || sqlite3_mutex_held(p->db->mutex) );
  59191. assert( VdbeMemDynamic(p) );
  59192. if( p->flags&MEM_Agg ){
  59193. sqlite3VdbeMemFinalize(p, p->u.pDef);
  59194. assert( (p->flags & MEM_Agg)==0 );
  59195. testcase( p->flags & MEM_Dyn );
  59196. }
  59197. if( p->flags&MEM_Dyn ){
  59198. assert( (p->flags&MEM_RowSet)==0 );
  59199. assert( p->xDel!=SQLITE_DYNAMIC && p->xDel!=0 );
  59200. p->xDel((void *)p->z);
  59201. }else if( p->flags&MEM_RowSet ){
  59202. sqlite3RowSetClear(p->u.pRowSet);
  59203. }else if( p->flags&MEM_Frame ){
  59204. VdbeFrame *pFrame = p->u.pFrame;
  59205. pFrame->pParent = pFrame->v->pDelFrame;
  59206. pFrame->v->pDelFrame = pFrame;
  59207. }
  59208. p->flags = MEM_Null;
  59209. }
  59210. /*
  59211. ** Release memory held by the Mem p, both external memory cleared
  59212. ** by p->xDel and memory in p->zMalloc.
  59213. **
  59214. ** This is a helper routine invoked by sqlite3VdbeMemRelease() in
  59215. ** the unusual case where there really is memory in p that needs
  59216. ** to be freed.
  59217. */
  59218. static SQLITE_NOINLINE void vdbeMemClear(Mem *p){
  59219. if( VdbeMemDynamic(p) ){
  59220. vdbeMemClearExternAndSetNull(p);
  59221. }
  59222. if( p->szMalloc ){
  59223. sqlite3DbFree(p->db, p->zMalloc);
  59224. p->szMalloc = 0;
  59225. }
  59226. p->z = 0;
  59227. }
  59228. /*
  59229. ** Release any memory resources held by the Mem. Both the memory that is
  59230. ** free by Mem.xDel and the Mem.zMalloc allocation are freed.
  59231. **
  59232. ** Use this routine prior to clean up prior to abandoning a Mem, or to
  59233. ** reset a Mem back to its minimum memory utilization.
  59234. **
  59235. ** Use sqlite3VdbeMemSetNull() to release just the Mem.xDel space
  59236. ** prior to inserting new content into the Mem.
  59237. */
  59238. SQLITE_PRIVATE void sqlite3VdbeMemRelease(Mem *p){
  59239. assert( sqlite3VdbeCheckMemInvariants(p) );
  59240. if( VdbeMemDynamic(p) || p->szMalloc ){
  59241. vdbeMemClear(p);
  59242. }
  59243. }
  59244. /*
  59245. ** Convert a 64-bit IEEE double into a 64-bit signed integer.
  59246. ** If the double is out of range of a 64-bit signed integer then
  59247. ** return the closest available 64-bit signed integer.
  59248. */
  59249. static i64 doubleToInt64(double r){
  59250. #ifdef SQLITE_OMIT_FLOATING_POINT
  59251. /* When floating-point is omitted, double and int64 are the same thing */
  59252. return r;
  59253. #else
  59254. /*
  59255. ** Many compilers we encounter do not define constants for the
  59256. ** minimum and maximum 64-bit integers, or they define them
  59257. ** inconsistently. And many do not understand the "LL" notation.
  59258. ** So we define our own static constants here using nothing
  59259. ** larger than a 32-bit integer constant.
  59260. */
  59261. static const i64 maxInt = LARGEST_INT64;
  59262. static const i64 minInt = SMALLEST_INT64;
  59263. if( r<=(double)minInt ){
  59264. return minInt;
  59265. }else if( r>=(double)maxInt ){
  59266. return maxInt;
  59267. }else{
  59268. return (i64)r;
  59269. }
  59270. #endif
  59271. }
  59272. /*
  59273. ** Return some kind of integer value which is the best we can do
  59274. ** at representing the value that *pMem describes as an integer.
  59275. ** If pMem is an integer, then the value is exact. If pMem is
  59276. ** a floating-point then the value returned is the integer part.
  59277. ** If pMem is a string or blob, then we make an attempt to convert
  59278. ** it into an integer and return that. If pMem represents an
  59279. ** an SQL-NULL value, return 0.
  59280. **
  59281. ** If pMem represents a string value, its encoding might be changed.
  59282. */
  59283. SQLITE_PRIVATE i64 sqlite3VdbeIntValue(Mem *pMem){
  59284. int flags;
  59285. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  59286. assert( EIGHT_BYTE_ALIGNMENT(pMem) );
  59287. flags = pMem->flags;
  59288. if( flags & MEM_Int ){
  59289. return pMem->u.i;
  59290. }else if( flags & MEM_Real ){
  59291. return doubleToInt64(pMem->u.r);
  59292. }else if( flags & (MEM_Str|MEM_Blob) ){
  59293. i64 value = 0;
  59294. assert( pMem->z || pMem->n==0 );
  59295. sqlite3Atoi64(pMem->z, &value, pMem->n, pMem->enc);
  59296. return value;
  59297. }else{
  59298. return 0;
  59299. }
  59300. }
  59301. /*
  59302. ** Return the best representation of pMem that we can get into a
  59303. ** double. If pMem is already a double or an integer, return its
  59304. ** value. If it is a string or blob, try to convert it to a double.
  59305. ** If it is a NULL, return 0.0.
  59306. */
  59307. SQLITE_PRIVATE double sqlite3VdbeRealValue(Mem *pMem){
  59308. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  59309. assert( EIGHT_BYTE_ALIGNMENT(pMem) );
  59310. if( pMem->flags & MEM_Real ){
  59311. return pMem->u.r;
  59312. }else if( pMem->flags & MEM_Int ){
  59313. return (double)pMem->u.i;
  59314. }else if( pMem->flags & (MEM_Str|MEM_Blob) ){
  59315. /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
  59316. double val = (double)0;
  59317. sqlite3AtoF(pMem->z, &val, pMem->n, pMem->enc);
  59318. return val;
  59319. }else{
  59320. /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
  59321. return (double)0;
  59322. }
  59323. }
  59324. /*
  59325. ** The MEM structure is already a MEM_Real. Try to also make it a
  59326. ** MEM_Int if we can.
  59327. */
  59328. SQLITE_PRIVATE void sqlite3VdbeIntegerAffinity(Mem *pMem){
  59329. i64 ix;
  59330. assert( pMem->flags & MEM_Real );
  59331. assert( (pMem->flags & MEM_RowSet)==0 );
  59332. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  59333. assert( EIGHT_BYTE_ALIGNMENT(pMem) );
  59334. ix = doubleToInt64(pMem->u.r);
  59335. /* Only mark the value as an integer if
  59336. **
  59337. ** (1) the round-trip conversion real->int->real is a no-op, and
  59338. ** (2) The integer is neither the largest nor the smallest
  59339. ** possible integer (ticket #3922)
  59340. **
  59341. ** The second and third terms in the following conditional enforces
  59342. ** the second condition under the assumption that addition overflow causes
  59343. ** values to wrap around.
  59344. */
  59345. if( pMem->u.r==ix && ix>SMALLEST_INT64 && ix<LARGEST_INT64 ){
  59346. pMem->u.i = ix;
  59347. MemSetTypeFlag(pMem, MEM_Int);
  59348. }
  59349. }
  59350. /*
  59351. ** Convert pMem to type integer. Invalidate any prior representations.
  59352. */
  59353. SQLITE_PRIVATE int sqlite3VdbeMemIntegerify(Mem *pMem){
  59354. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  59355. assert( (pMem->flags & MEM_RowSet)==0 );
  59356. assert( EIGHT_BYTE_ALIGNMENT(pMem) );
  59357. pMem->u.i = sqlite3VdbeIntValue(pMem);
  59358. MemSetTypeFlag(pMem, MEM_Int);
  59359. return SQLITE_OK;
  59360. }
  59361. /*
  59362. ** Convert pMem so that it is of type MEM_Real.
  59363. ** Invalidate any prior representations.
  59364. */
  59365. SQLITE_PRIVATE int sqlite3VdbeMemRealify(Mem *pMem){
  59366. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  59367. assert( EIGHT_BYTE_ALIGNMENT(pMem) );
  59368. pMem->u.r = sqlite3VdbeRealValue(pMem);
  59369. MemSetTypeFlag(pMem, MEM_Real);
  59370. return SQLITE_OK;
  59371. }
  59372. /*
  59373. ** Convert pMem so that it has types MEM_Real or MEM_Int or both.
  59374. ** Invalidate any prior representations.
  59375. **
  59376. ** Every effort is made to force the conversion, even if the input
  59377. ** is a string that does not look completely like a number. Convert
  59378. ** as much of the string as we can and ignore the rest.
  59379. */
  59380. SQLITE_PRIVATE int sqlite3VdbeMemNumerify(Mem *pMem){
  59381. if( (pMem->flags & (MEM_Int|MEM_Real|MEM_Null))==0 ){
  59382. assert( (pMem->flags & (MEM_Blob|MEM_Str))!=0 );
  59383. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  59384. if( 0==sqlite3Atoi64(pMem->z, &pMem->u.i, pMem->n, pMem->enc) ){
  59385. MemSetTypeFlag(pMem, MEM_Int);
  59386. }else{
  59387. pMem->u.r = sqlite3VdbeRealValue(pMem);
  59388. MemSetTypeFlag(pMem, MEM_Real);
  59389. sqlite3VdbeIntegerAffinity(pMem);
  59390. }
  59391. }
  59392. assert( (pMem->flags & (MEM_Int|MEM_Real|MEM_Null))!=0 );
  59393. pMem->flags &= ~(MEM_Str|MEM_Blob);
  59394. return SQLITE_OK;
  59395. }
  59396. /*
  59397. ** Cast the datatype of the value in pMem according to the affinity
  59398. ** "aff". Casting is different from applying affinity in that a cast
  59399. ** is forced. In other words, the value is converted into the desired
  59400. ** affinity even if that results in loss of data. This routine is
  59401. ** used (for example) to implement the SQL "cast()" operator.
  59402. */
  59403. SQLITE_PRIVATE void sqlite3VdbeMemCast(Mem *pMem, u8 aff, u8 encoding){
  59404. if( pMem->flags & MEM_Null ) return;
  59405. switch( aff ){
  59406. case SQLITE_AFF_NONE: { /* Really a cast to BLOB */
  59407. if( (pMem->flags & MEM_Blob)==0 ){
  59408. sqlite3ValueApplyAffinity(pMem, SQLITE_AFF_TEXT, encoding);
  59409. assert( pMem->flags & MEM_Str || pMem->db->mallocFailed );
  59410. MemSetTypeFlag(pMem, MEM_Blob);
  59411. }else{
  59412. pMem->flags &= ~(MEM_TypeMask&~MEM_Blob);
  59413. }
  59414. break;
  59415. }
  59416. case SQLITE_AFF_NUMERIC: {
  59417. sqlite3VdbeMemNumerify(pMem);
  59418. break;
  59419. }
  59420. case SQLITE_AFF_INTEGER: {
  59421. sqlite3VdbeMemIntegerify(pMem);
  59422. break;
  59423. }
  59424. case SQLITE_AFF_REAL: {
  59425. sqlite3VdbeMemRealify(pMem);
  59426. break;
  59427. }
  59428. default: {
  59429. assert( aff==SQLITE_AFF_TEXT );
  59430. assert( MEM_Str==(MEM_Blob>>3) );
  59431. pMem->flags |= (pMem->flags&MEM_Blob)>>3;
  59432. sqlite3ValueApplyAffinity(pMem, SQLITE_AFF_TEXT, encoding);
  59433. assert( pMem->flags & MEM_Str || pMem->db->mallocFailed );
  59434. pMem->flags &= ~(MEM_Int|MEM_Real|MEM_Blob|MEM_Zero);
  59435. break;
  59436. }
  59437. }
  59438. }
  59439. /*
  59440. ** Initialize bulk memory to be a consistent Mem object.
  59441. **
  59442. ** The minimum amount of initialization feasible is performed.
  59443. */
  59444. SQLITE_PRIVATE void sqlite3VdbeMemInit(Mem *pMem, sqlite3 *db, u16 flags){
  59445. assert( (flags & ~MEM_TypeMask)==0 );
  59446. pMem->flags = flags;
  59447. pMem->db = db;
  59448. pMem->szMalloc = 0;
  59449. }
  59450. /*
  59451. ** Delete any previous value and set the value stored in *pMem to NULL.
  59452. **
  59453. ** This routine calls the Mem.xDel destructor to dispose of values that
  59454. ** require the destructor. But it preserves the Mem.zMalloc memory allocation.
  59455. ** To free all resources, use sqlite3VdbeMemRelease(), which both calls this
  59456. ** routine to invoke the destructor and deallocates Mem.zMalloc.
  59457. **
  59458. ** Use this routine to reset the Mem prior to insert a new value.
  59459. **
  59460. ** Use sqlite3VdbeMemRelease() to complete erase the Mem prior to abandoning it.
  59461. */
  59462. SQLITE_PRIVATE void sqlite3VdbeMemSetNull(Mem *pMem){
  59463. if( VdbeMemDynamic(pMem) ){
  59464. vdbeMemClearExternAndSetNull(pMem);
  59465. }else{
  59466. pMem->flags = MEM_Null;
  59467. }
  59468. }
  59469. SQLITE_PRIVATE void sqlite3ValueSetNull(sqlite3_value *p){
  59470. sqlite3VdbeMemSetNull((Mem*)p);
  59471. }
  59472. /*
  59473. ** Delete any previous value and set the value to be a BLOB of length
  59474. ** n containing all zeros.
  59475. */
  59476. SQLITE_PRIVATE void sqlite3VdbeMemSetZeroBlob(Mem *pMem, int n){
  59477. sqlite3VdbeMemRelease(pMem);
  59478. pMem->flags = MEM_Blob|MEM_Zero;
  59479. pMem->n = 0;
  59480. if( n<0 ) n = 0;
  59481. pMem->u.nZero = n;
  59482. pMem->enc = SQLITE_UTF8;
  59483. pMem->z = 0;
  59484. }
  59485. /*
  59486. ** The pMem is known to contain content that needs to be destroyed prior
  59487. ** to a value change. So invoke the destructor, then set the value to
  59488. ** a 64-bit integer.
  59489. */
  59490. static SQLITE_NOINLINE void vdbeReleaseAndSetInt64(Mem *pMem, i64 val){
  59491. sqlite3VdbeMemSetNull(pMem);
  59492. pMem->u.i = val;
  59493. pMem->flags = MEM_Int;
  59494. }
  59495. /*
  59496. ** Delete any previous value and set the value stored in *pMem to val,
  59497. ** manifest type INTEGER.
  59498. */
  59499. SQLITE_PRIVATE void sqlite3VdbeMemSetInt64(Mem *pMem, i64 val){
  59500. if( VdbeMemDynamic(pMem) ){
  59501. vdbeReleaseAndSetInt64(pMem, val);
  59502. }else{
  59503. pMem->u.i = val;
  59504. pMem->flags = MEM_Int;
  59505. }
  59506. }
  59507. #ifndef SQLITE_OMIT_FLOATING_POINT
  59508. /*
  59509. ** Delete any previous value and set the value stored in *pMem to val,
  59510. ** manifest type REAL.
  59511. */
  59512. SQLITE_PRIVATE void sqlite3VdbeMemSetDouble(Mem *pMem, double val){
  59513. sqlite3VdbeMemSetNull(pMem);
  59514. if( !sqlite3IsNaN(val) ){
  59515. pMem->u.r = val;
  59516. pMem->flags = MEM_Real;
  59517. }
  59518. }
  59519. #endif
  59520. /*
  59521. ** Delete any previous value and set the value of pMem to be an
  59522. ** empty boolean index.
  59523. */
  59524. SQLITE_PRIVATE void sqlite3VdbeMemSetRowSet(Mem *pMem){
  59525. sqlite3 *db = pMem->db;
  59526. assert( db!=0 );
  59527. assert( (pMem->flags & MEM_RowSet)==0 );
  59528. sqlite3VdbeMemRelease(pMem);
  59529. pMem->zMalloc = sqlite3DbMallocRaw(db, 64);
  59530. if( db->mallocFailed ){
  59531. pMem->flags = MEM_Null;
  59532. pMem->szMalloc = 0;
  59533. }else{
  59534. assert( pMem->zMalloc );
  59535. pMem->szMalloc = sqlite3DbMallocSize(db, pMem->zMalloc);
  59536. pMem->u.pRowSet = sqlite3RowSetInit(db, pMem->zMalloc, pMem->szMalloc);
  59537. assert( pMem->u.pRowSet!=0 );
  59538. pMem->flags = MEM_RowSet;
  59539. }
  59540. }
  59541. /*
  59542. ** Return true if the Mem object contains a TEXT or BLOB that is
  59543. ** too large - whose size exceeds SQLITE_MAX_LENGTH.
  59544. */
  59545. SQLITE_PRIVATE int sqlite3VdbeMemTooBig(Mem *p){
  59546. assert( p->db!=0 );
  59547. if( p->flags & (MEM_Str|MEM_Blob) ){
  59548. int n = p->n;
  59549. if( p->flags & MEM_Zero ){
  59550. n += p->u.nZero;
  59551. }
  59552. return n>p->db->aLimit[SQLITE_LIMIT_LENGTH];
  59553. }
  59554. return 0;
  59555. }
  59556. #ifdef SQLITE_DEBUG
  59557. /*
  59558. ** This routine prepares a memory cell for modification by breaking
  59559. ** its link to a shallow copy and by marking any current shallow
  59560. ** copies of this cell as invalid.
  59561. **
  59562. ** This is used for testing and debugging only - to make sure shallow
  59563. ** copies are not misused.
  59564. */
  59565. SQLITE_PRIVATE void sqlite3VdbeMemAboutToChange(Vdbe *pVdbe, Mem *pMem){
  59566. int i;
  59567. Mem *pX;
  59568. for(i=1, pX=&pVdbe->aMem[1]; i<=pVdbe->nMem; i++, pX++){
  59569. if( pX->pScopyFrom==pMem ){
  59570. pX->flags |= MEM_Undefined;
  59571. pX->pScopyFrom = 0;
  59572. }
  59573. }
  59574. pMem->pScopyFrom = 0;
  59575. }
  59576. #endif /* SQLITE_DEBUG */
  59577. /*
  59578. ** Size of struct Mem not including the Mem.zMalloc member.
  59579. */
  59580. #define MEMCELLSIZE offsetof(Mem,zMalloc)
  59581. /*
  59582. ** Make an shallow copy of pFrom into pTo. Prior contents of
  59583. ** pTo are freed. The pFrom->z field is not duplicated. If
  59584. ** pFrom->z is used, then pTo->z points to the same thing as pFrom->z
  59585. ** and flags gets srcType (either MEM_Ephem or MEM_Static).
  59586. */
  59587. SQLITE_PRIVATE void sqlite3VdbeMemShallowCopy(Mem *pTo, const Mem *pFrom, int srcType){
  59588. assert( (pFrom->flags & MEM_RowSet)==0 );
  59589. assert( pTo->db==pFrom->db );
  59590. if( VdbeMemDynamic(pTo) ) vdbeMemClearExternAndSetNull(pTo);
  59591. memcpy(pTo, pFrom, MEMCELLSIZE);
  59592. if( (pFrom->flags&MEM_Static)==0 ){
  59593. pTo->flags &= ~(MEM_Dyn|MEM_Static|MEM_Ephem);
  59594. assert( srcType==MEM_Ephem || srcType==MEM_Static );
  59595. pTo->flags |= srcType;
  59596. }
  59597. }
  59598. /*
  59599. ** Make a full copy of pFrom into pTo. Prior contents of pTo are
  59600. ** freed before the copy is made.
  59601. */
  59602. SQLITE_PRIVATE int sqlite3VdbeMemCopy(Mem *pTo, const Mem *pFrom){
  59603. int rc = SQLITE_OK;
  59604. assert( pTo->db==pFrom->db );
  59605. assert( (pFrom->flags & MEM_RowSet)==0 );
  59606. if( VdbeMemDynamic(pTo) ) vdbeMemClearExternAndSetNull(pTo);
  59607. memcpy(pTo, pFrom, MEMCELLSIZE);
  59608. pTo->flags &= ~MEM_Dyn;
  59609. if( pTo->flags&(MEM_Str|MEM_Blob) ){
  59610. if( 0==(pFrom->flags&MEM_Static) ){
  59611. pTo->flags |= MEM_Ephem;
  59612. rc = sqlite3VdbeMemMakeWriteable(pTo);
  59613. }
  59614. }
  59615. return rc;
  59616. }
  59617. /*
  59618. ** Transfer the contents of pFrom to pTo. Any existing value in pTo is
  59619. ** freed. If pFrom contains ephemeral data, a copy is made.
  59620. **
  59621. ** pFrom contains an SQL NULL when this routine returns.
  59622. */
  59623. SQLITE_PRIVATE void sqlite3VdbeMemMove(Mem *pTo, Mem *pFrom){
  59624. assert( pFrom->db==0 || sqlite3_mutex_held(pFrom->db->mutex) );
  59625. assert( pTo->db==0 || sqlite3_mutex_held(pTo->db->mutex) );
  59626. assert( pFrom->db==0 || pTo->db==0 || pFrom->db==pTo->db );
  59627. sqlite3VdbeMemRelease(pTo);
  59628. memcpy(pTo, pFrom, sizeof(Mem));
  59629. pFrom->flags = MEM_Null;
  59630. pFrom->szMalloc = 0;
  59631. }
  59632. /*
  59633. ** Change the value of a Mem to be a string or a BLOB.
  59634. **
  59635. ** The memory management strategy depends on the value of the xDel
  59636. ** parameter. If the value passed is SQLITE_TRANSIENT, then the
  59637. ** string is copied into a (possibly existing) buffer managed by the
  59638. ** Mem structure. Otherwise, any existing buffer is freed and the
  59639. ** pointer copied.
  59640. **
  59641. ** If the string is too large (if it exceeds the SQLITE_LIMIT_LENGTH
  59642. ** size limit) then no memory allocation occurs. If the string can be
  59643. ** stored without allocating memory, then it is. If a memory allocation
  59644. ** is required to store the string, then value of pMem is unchanged. In
  59645. ** either case, SQLITE_TOOBIG is returned.
  59646. */
  59647. SQLITE_PRIVATE int sqlite3VdbeMemSetStr(
  59648. Mem *pMem, /* Memory cell to set to string value */
  59649. const char *z, /* String pointer */
  59650. int n, /* Bytes in string, or negative */
  59651. u8 enc, /* Encoding of z. 0 for BLOBs */
  59652. void (*xDel)(void*) /* Destructor function */
  59653. ){
  59654. int nByte = n; /* New value for pMem->n */
  59655. int iLimit; /* Maximum allowed string or blob size */
  59656. u16 flags = 0; /* New value for pMem->flags */
  59657. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  59658. assert( (pMem->flags & MEM_RowSet)==0 );
  59659. /* If z is a NULL pointer, set pMem to contain an SQL NULL. */
  59660. if( !z ){
  59661. sqlite3VdbeMemSetNull(pMem);
  59662. return SQLITE_OK;
  59663. }
  59664. if( pMem->db ){
  59665. iLimit = pMem->db->aLimit[SQLITE_LIMIT_LENGTH];
  59666. }else{
  59667. iLimit = SQLITE_MAX_LENGTH;
  59668. }
  59669. flags = (enc==0?MEM_Blob:MEM_Str);
  59670. if( nByte<0 ){
  59671. assert( enc!=0 );
  59672. if( enc==SQLITE_UTF8 ){
  59673. nByte = sqlite3Strlen30(z);
  59674. if( nByte>iLimit ) nByte = iLimit+1;
  59675. }else{
  59676. for(nByte=0; nByte<=iLimit && (z[nByte] | z[nByte+1]); nByte+=2){}
  59677. }
  59678. flags |= MEM_Term;
  59679. }
  59680. /* The following block sets the new values of Mem.z and Mem.xDel. It
  59681. ** also sets a flag in local variable "flags" to indicate the memory
  59682. ** management (one of MEM_Dyn or MEM_Static).
  59683. */
  59684. if( xDel==SQLITE_TRANSIENT ){
  59685. int nAlloc = nByte;
  59686. if( flags&MEM_Term ){
  59687. nAlloc += (enc==SQLITE_UTF8?1:2);
  59688. }
  59689. if( nByte>iLimit ){
  59690. return SQLITE_TOOBIG;
  59691. }
  59692. testcase( nAlloc==0 );
  59693. testcase( nAlloc==31 );
  59694. testcase( nAlloc==32 );
  59695. if( sqlite3VdbeMemClearAndResize(pMem, MAX(nAlloc,32)) ){
  59696. return SQLITE_NOMEM;
  59697. }
  59698. memcpy(pMem->z, z, nAlloc);
  59699. }else if( xDel==SQLITE_DYNAMIC ){
  59700. sqlite3VdbeMemRelease(pMem);
  59701. pMem->zMalloc = pMem->z = (char *)z;
  59702. pMem->szMalloc = sqlite3DbMallocSize(pMem->db, pMem->zMalloc);
  59703. }else{
  59704. sqlite3VdbeMemRelease(pMem);
  59705. pMem->z = (char *)z;
  59706. pMem->xDel = xDel;
  59707. flags |= ((xDel==SQLITE_STATIC)?MEM_Static:MEM_Dyn);
  59708. }
  59709. pMem->n = nByte;
  59710. pMem->flags = flags;
  59711. pMem->enc = (enc==0 ? SQLITE_UTF8 : enc);
  59712. #ifndef SQLITE_OMIT_UTF16
  59713. if( pMem->enc!=SQLITE_UTF8 && sqlite3VdbeMemHandleBom(pMem) ){
  59714. return SQLITE_NOMEM;
  59715. }
  59716. #endif
  59717. if( nByte>iLimit ){
  59718. return SQLITE_TOOBIG;
  59719. }
  59720. return SQLITE_OK;
  59721. }
  59722. /*
  59723. ** Move data out of a btree key or data field and into a Mem structure.
  59724. ** The data or key is taken from the entry that pCur is currently pointing
  59725. ** to. offset and amt determine what portion of the data or key to retrieve.
  59726. ** key is true to get the key or false to get data. The result is written
  59727. ** into the pMem element.
  59728. **
  59729. ** The pMem object must have been initialized. This routine will use
  59730. ** pMem->zMalloc to hold the content from the btree, if possible. New
  59731. ** pMem->zMalloc space will be allocated if necessary. The calling routine
  59732. ** is responsible for making sure that the pMem object is eventually
  59733. ** destroyed.
  59734. **
  59735. ** If this routine fails for any reason (malloc returns NULL or unable
  59736. ** to read from the disk) then the pMem is left in an inconsistent state.
  59737. */
  59738. SQLITE_PRIVATE int sqlite3VdbeMemFromBtree(
  59739. BtCursor *pCur, /* Cursor pointing at record to retrieve. */
  59740. u32 offset, /* Offset from the start of data to return bytes from. */
  59741. u32 amt, /* Number of bytes to return. */
  59742. int key, /* If true, retrieve from the btree key, not data. */
  59743. Mem *pMem /* OUT: Return data in this Mem structure. */
  59744. ){
  59745. char *zData; /* Data from the btree layer */
  59746. u32 available = 0; /* Number of bytes available on the local btree page */
  59747. int rc = SQLITE_OK; /* Return code */
  59748. assert( sqlite3BtreeCursorIsValid(pCur) );
  59749. assert( !VdbeMemDynamic(pMem) );
  59750. /* Note: the calls to BtreeKeyFetch() and DataFetch() below assert()
  59751. ** that both the BtShared and database handle mutexes are held. */
  59752. assert( (pMem->flags & MEM_RowSet)==0 );
  59753. if( key ){
  59754. zData = (char *)sqlite3BtreeKeyFetch(pCur, &available);
  59755. }else{
  59756. zData = (char *)sqlite3BtreeDataFetch(pCur, &available);
  59757. }
  59758. assert( zData!=0 );
  59759. if( offset+amt<=available ){
  59760. pMem->z = &zData[offset];
  59761. pMem->flags = MEM_Blob|MEM_Ephem;
  59762. pMem->n = (int)amt;
  59763. }else{
  59764. pMem->flags = MEM_Null;
  59765. if( SQLITE_OK==(rc = sqlite3VdbeMemClearAndResize(pMem, amt+2)) ){
  59766. if( key ){
  59767. rc = sqlite3BtreeKey(pCur, offset, amt, pMem->z);
  59768. }else{
  59769. rc = sqlite3BtreeData(pCur, offset, amt, pMem->z);
  59770. }
  59771. if( rc==SQLITE_OK ){
  59772. pMem->z[amt] = 0;
  59773. pMem->z[amt+1] = 0;
  59774. pMem->flags = MEM_Blob|MEM_Term;
  59775. pMem->n = (int)amt;
  59776. }else{
  59777. sqlite3VdbeMemRelease(pMem);
  59778. }
  59779. }
  59780. }
  59781. return rc;
  59782. }
  59783. /*
  59784. ** The pVal argument is known to be a value other than NULL.
  59785. ** Convert it into a string with encoding enc and return a pointer
  59786. ** to a zero-terminated version of that string.
  59787. */
  59788. static SQLITE_NOINLINE const void *valueToText(sqlite3_value* pVal, u8 enc){
  59789. assert( pVal!=0 );
  59790. assert( pVal->db==0 || sqlite3_mutex_held(pVal->db->mutex) );
  59791. assert( (enc&3)==(enc&~SQLITE_UTF16_ALIGNED) );
  59792. assert( (pVal->flags & MEM_RowSet)==0 );
  59793. assert( (pVal->flags & (MEM_Null))==0 );
  59794. if( pVal->flags & (MEM_Blob|MEM_Str) ){
  59795. pVal->flags |= MEM_Str;
  59796. if( pVal->flags & MEM_Zero ){
  59797. sqlite3VdbeMemExpandBlob(pVal);
  59798. }
  59799. if( pVal->enc != (enc & ~SQLITE_UTF16_ALIGNED) ){
  59800. sqlite3VdbeChangeEncoding(pVal, enc & ~SQLITE_UTF16_ALIGNED);
  59801. }
  59802. if( (enc & SQLITE_UTF16_ALIGNED)!=0 && 1==(1&SQLITE_PTR_TO_INT(pVal->z)) ){
  59803. assert( (pVal->flags & (MEM_Ephem|MEM_Static))!=0 );
  59804. if( sqlite3VdbeMemMakeWriteable(pVal)!=SQLITE_OK ){
  59805. return 0;
  59806. }
  59807. }
  59808. sqlite3VdbeMemNulTerminate(pVal); /* IMP: R-31275-44060 */
  59809. }else{
  59810. sqlite3VdbeMemStringify(pVal, enc, 0);
  59811. assert( 0==(1&SQLITE_PTR_TO_INT(pVal->z)) );
  59812. }
  59813. assert(pVal->enc==(enc & ~SQLITE_UTF16_ALIGNED) || pVal->db==0
  59814. || pVal->db->mallocFailed );
  59815. if( pVal->enc==(enc & ~SQLITE_UTF16_ALIGNED) ){
  59816. return pVal->z;
  59817. }else{
  59818. return 0;
  59819. }
  59820. }
  59821. /* This function is only available internally, it is not part of the
  59822. ** external API. It works in a similar way to sqlite3_value_text(),
  59823. ** except the data returned is in the encoding specified by the second
  59824. ** parameter, which must be one of SQLITE_UTF16BE, SQLITE_UTF16LE or
  59825. ** SQLITE_UTF8.
  59826. **
  59827. ** (2006-02-16:) The enc value can be or-ed with SQLITE_UTF16_ALIGNED.
  59828. ** If that is the case, then the result must be aligned on an even byte
  59829. ** boundary.
  59830. */
  59831. SQLITE_PRIVATE const void *sqlite3ValueText(sqlite3_value* pVal, u8 enc){
  59832. if( !pVal ) return 0;
  59833. assert( pVal->db==0 || sqlite3_mutex_held(pVal->db->mutex) );
  59834. assert( (enc&3)==(enc&~SQLITE_UTF16_ALIGNED) );
  59835. assert( (pVal->flags & MEM_RowSet)==0 );
  59836. if( (pVal->flags&(MEM_Str|MEM_Term))==(MEM_Str|MEM_Term) && pVal->enc==enc ){
  59837. return pVal->z;
  59838. }
  59839. if( pVal->flags&MEM_Null ){
  59840. return 0;
  59841. }
  59842. return valueToText(pVal, enc);
  59843. }
  59844. /*
  59845. ** Create a new sqlite3_value object.
  59846. */
  59847. SQLITE_PRIVATE sqlite3_value *sqlite3ValueNew(sqlite3 *db){
  59848. Mem *p = sqlite3DbMallocZero(db, sizeof(*p));
  59849. if( p ){
  59850. p->flags = MEM_Null;
  59851. p->db = db;
  59852. }
  59853. return p;
  59854. }
  59855. /*
  59856. ** Context object passed by sqlite3Stat4ProbeSetValue() through to
  59857. ** valueNew(). See comments above valueNew() for details.
  59858. */
  59859. struct ValueNewStat4Ctx {
  59860. Parse *pParse;
  59861. Index *pIdx;
  59862. UnpackedRecord **ppRec;
  59863. int iVal;
  59864. };
  59865. /*
  59866. ** Allocate and return a pointer to a new sqlite3_value object. If
  59867. ** the second argument to this function is NULL, the object is allocated
  59868. ** by calling sqlite3ValueNew().
  59869. **
  59870. ** Otherwise, if the second argument is non-zero, then this function is
  59871. ** being called indirectly by sqlite3Stat4ProbeSetValue(). If it has not
  59872. ** already been allocated, allocate the UnpackedRecord structure that
  59873. ** that function will return to its caller here. Then return a pointer to
  59874. ** an sqlite3_value within the UnpackedRecord.a[] array.
  59875. */
  59876. static sqlite3_value *valueNew(sqlite3 *db, struct ValueNewStat4Ctx *p){
  59877. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  59878. if( p ){
  59879. UnpackedRecord *pRec = p->ppRec[0];
  59880. if( pRec==0 ){
  59881. Index *pIdx = p->pIdx; /* Index being probed */
  59882. int nByte; /* Bytes of space to allocate */
  59883. int i; /* Counter variable */
  59884. int nCol = pIdx->nColumn; /* Number of index columns including rowid */
  59885. nByte = sizeof(Mem) * nCol + ROUND8(sizeof(UnpackedRecord));
  59886. pRec = (UnpackedRecord*)sqlite3DbMallocZero(db, nByte);
  59887. if( pRec ){
  59888. pRec->pKeyInfo = sqlite3KeyInfoOfIndex(p->pParse, pIdx);
  59889. if( pRec->pKeyInfo ){
  59890. assert( pRec->pKeyInfo->nField+pRec->pKeyInfo->nXField==nCol );
  59891. assert( pRec->pKeyInfo->enc==ENC(db) );
  59892. pRec->aMem = (Mem *)((u8*)pRec + ROUND8(sizeof(UnpackedRecord)));
  59893. for(i=0; i<nCol; i++){
  59894. pRec->aMem[i].flags = MEM_Null;
  59895. pRec->aMem[i].db = db;
  59896. }
  59897. }else{
  59898. sqlite3DbFree(db, pRec);
  59899. pRec = 0;
  59900. }
  59901. }
  59902. if( pRec==0 ) return 0;
  59903. p->ppRec[0] = pRec;
  59904. }
  59905. pRec->nField = p->iVal+1;
  59906. return &pRec->aMem[p->iVal];
  59907. }
  59908. #else
  59909. UNUSED_PARAMETER(p);
  59910. #endif /* defined(SQLITE_ENABLE_STAT3_OR_STAT4) */
  59911. return sqlite3ValueNew(db);
  59912. }
  59913. /*
  59914. ** The expression object indicated by the second argument is guaranteed
  59915. ** to be a scalar SQL function. If
  59916. **
  59917. ** * all function arguments are SQL literals,
  59918. ** * the SQLITE_FUNC_CONSTANT function flag is set, and
  59919. ** * the SQLITE_FUNC_NEEDCOLL function flag is not set,
  59920. **
  59921. ** then this routine attempts to invoke the SQL function. Assuming no
  59922. ** error occurs, output parameter (*ppVal) is set to point to a value
  59923. ** object containing the result before returning SQLITE_OK.
  59924. **
  59925. ** Affinity aff is applied to the result of the function before returning.
  59926. ** If the result is a text value, the sqlite3_value object uses encoding
  59927. ** enc.
  59928. **
  59929. ** If the conditions above are not met, this function returns SQLITE_OK
  59930. ** and sets (*ppVal) to NULL. Or, if an error occurs, (*ppVal) is set to
  59931. ** NULL and an SQLite error code returned.
  59932. */
  59933. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  59934. static int valueFromFunction(
  59935. sqlite3 *db, /* The database connection */
  59936. Expr *p, /* The expression to evaluate */
  59937. u8 enc, /* Encoding to use */
  59938. u8 aff, /* Affinity to use */
  59939. sqlite3_value **ppVal, /* Write the new value here */
  59940. struct ValueNewStat4Ctx *pCtx /* Second argument for valueNew() */
  59941. ){
  59942. sqlite3_context ctx; /* Context object for function invocation */
  59943. sqlite3_value **apVal = 0; /* Function arguments */
  59944. int nVal = 0; /* Size of apVal[] array */
  59945. FuncDef *pFunc = 0; /* Function definition */
  59946. sqlite3_value *pVal = 0; /* New value */
  59947. int rc = SQLITE_OK; /* Return code */
  59948. int nName; /* Size of function name in bytes */
  59949. ExprList *pList = 0; /* Function arguments */
  59950. int i; /* Iterator variable */
  59951. assert( pCtx!=0 );
  59952. assert( (p->flags & EP_TokenOnly)==0 );
  59953. pList = p->x.pList;
  59954. if( pList ) nVal = pList->nExpr;
  59955. nName = sqlite3Strlen30(p->u.zToken);
  59956. pFunc = sqlite3FindFunction(db, p->u.zToken, nName, nVal, enc, 0);
  59957. assert( pFunc );
  59958. if( (pFunc->funcFlags & SQLITE_FUNC_CONSTANT)==0
  59959. || (pFunc->funcFlags & SQLITE_FUNC_NEEDCOLL)
  59960. ){
  59961. return SQLITE_OK;
  59962. }
  59963. if( pList ){
  59964. apVal = (sqlite3_value**)sqlite3DbMallocZero(db, sizeof(apVal[0]) * nVal);
  59965. if( apVal==0 ){
  59966. rc = SQLITE_NOMEM;
  59967. goto value_from_function_out;
  59968. }
  59969. for(i=0; i<nVal; i++){
  59970. rc = sqlite3ValueFromExpr(db, pList->a[i].pExpr, enc, aff, &apVal[i]);
  59971. if( apVal[i]==0 || rc!=SQLITE_OK ) goto value_from_function_out;
  59972. }
  59973. }
  59974. pVal = valueNew(db, pCtx);
  59975. if( pVal==0 ){
  59976. rc = SQLITE_NOMEM;
  59977. goto value_from_function_out;
  59978. }
  59979. assert( pCtx->pParse->rc==SQLITE_OK );
  59980. memset(&ctx, 0, sizeof(ctx));
  59981. ctx.pOut = pVal;
  59982. ctx.pFunc = pFunc;
  59983. pFunc->xFunc(&ctx, nVal, apVal);
  59984. if( ctx.isError ){
  59985. rc = ctx.isError;
  59986. sqlite3ErrorMsg(pCtx->pParse, "%s", sqlite3_value_text(pVal));
  59987. }else{
  59988. sqlite3ValueApplyAffinity(pVal, aff, SQLITE_UTF8);
  59989. assert( rc==SQLITE_OK );
  59990. rc = sqlite3VdbeChangeEncoding(pVal, enc);
  59991. if( rc==SQLITE_OK && sqlite3VdbeMemTooBig(pVal) ){
  59992. rc = SQLITE_TOOBIG;
  59993. pCtx->pParse->nErr++;
  59994. }
  59995. }
  59996. pCtx->pParse->rc = rc;
  59997. value_from_function_out:
  59998. if( rc!=SQLITE_OK ){
  59999. pVal = 0;
  60000. }
  60001. if( apVal ){
  60002. for(i=0; i<nVal; i++){
  60003. sqlite3ValueFree(apVal[i]);
  60004. }
  60005. sqlite3DbFree(db, apVal);
  60006. }
  60007. *ppVal = pVal;
  60008. return rc;
  60009. }
  60010. #else
  60011. # define valueFromFunction(a,b,c,d,e,f) SQLITE_OK
  60012. #endif /* defined(SQLITE_ENABLE_STAT3_OR_STAT4) */
  60013. /*
  60014. ** Extract a value from the supplied expression in the manner described
  60015. ** above sqlite3ValueFromExpr(). Allocate the sqlite3_value object
  60016. ** using valueNew().
  60017. **
  60018. ** If pCtx is NULL and an error occurs after the sqlite3_value object
  60019. ** has been allocated, it is freed before returning. Or, if pCtx is not
  60020. ** NULL, it is assumed that the caller will free any allocated object
  60021. ** in all cases.
  60022. */
  60023. static int valueFromExpr(
  60024. sqlite3 *db, /* The database connection */
  60025. Expr *pExpr, /* The expression to evaluate */
  60026. u8 enc, /* Encoding to use */
  60027. u8 affinity, /* Affinity to use */
  60028. sqlite3_value **ppVal, /* Write the new value here */
  60029. struct ValueNewStat4Ctx *pCtx /* Second argument for valueNew() */
  60030. ){
  60031. int op;
  60032. char *zVal = 0;
  60033. sqlite3_value *pVal = 0;
  60034. int negInt = 1;
  60035. const char *zNeg = "";
  60036. int rc = SQLITE_OK;
  60037. if( !pExpr ){
  60038. *ppVal = 0;
  60039. return SQLITE_OK;
  60040. }
  60041. while( (op = pExpr->op)==TK_UPLUS ) pExpr = pExpr->pLeft;
  60042. if( NEVER(op==TK_REGISTER) ) op = pExpr->op2;
  60043. /* Compressed expressions only appear when parsing the DEFAULT clause
  60044. ** on a table column definition, and hence only when pCtx==0. This
  60045. ** check ensures that an EP_TokenOnly expression is never passed down
  60046. ** into valueFromFunction(). */
  60047. assert( (pExpr->flags & EP_TokenOnly)==0 || pCtx==0 );
  60048. if( op==TK_CAST ){
  60049. u8 aff = sqlite3AffinityType(pExpr->u.zToken,0);
  60050. rc = valueFromExpr(db, pExpr->pLeft, enc, aff, ppVal, pCtx);
  60051. testcase( rc!=SQLITE_OK );
  60052. if( *ppVal ){
  60053. sqlite3VdbeMemCast(*ppVal, aff, SQLITE_UTF8);
  60054. sqlite3ValueApplyAffinity(*ppVal, affinity, SQLITE_UTF8);
  60055. }
  60056. return rc;
  60057. }
  60058. /* Handle negative integers in a single step. This is needed in the
  60059. ** case when the value is -9223372036854775808.
  60060. */
  60061. if( op==TK_UMINUS
  60062. && (pExpr->pLeft->op==TK_INTEGER || pExpr->pLeft->op==TK_FLOAT) ){
  60063. pExpr = pExpr->pLeft;
  60064. op = pExpr->op;
  60065. negInt = -1;
  60066. zNeg = "-";
  60067. }
  60068. if( op==TK_STRING || op==TK_FLOAT || op==TK_INTEGER ){
  60069. pVal = valueNew(db, pCtx);
  60070. if( pVal==0 ) goto no_mem;
  60071. if( ExprHasProperty(pExpr, EP_IntValue) ){
  60072. sqlite3VdbeMemSetInt64(pVal, (i64)pExpr->u.iValue*negInt);
  60073. }else{
  60074. zVal = sqlite3MPrintf(db, "%s%s", zNeg, pExpr->u.zToken);
  60075. if( zVal==0 ) goto no_mem;
  60076. sqlite3ValueSetStr(pVal, -1, zVal, SQLITE_UTF8, SQLITE_DYNAMIC);
  60077. }
  60078. if( (op==TK_INTEGER || op==TK_FLOAT ) && affinity==SQLITE_AFF_NONE ){
  60079. sqlite3ValueApplyAffinity(pVal, SQLITE_AFF_NUMERIC, SQLITE_UTF8);
  60080. }else{
  60081. sqlite3ValueApplyAffinity(pVal, affinity, SQLITE_UTF8);
  60082. }
  60083. if( pVal->flags & (MEM_Int|MEM_Real) ) pVal->flags &= ~MEM_Str;
  60084. if( enc!=SQLITE_UTF8 ){
  60085. rc = sqlite3VdbeChangeEncoding(pVal, enc);
  60086. }
  60087. }else if( op==TK_UMINUS ) {
  60088. /* This branch happens for multiple negative signs. Ex: -(-5) */
  60089. if( SQLITE_OK==sqlite3ValueFromExpr(db,pExpr->pLeft,enc,affinity,&pVal)
  60090. && pVal!=0
  60091. ){
  60092. sqlite3VdbeMemNumerify(pVal);
  60093. if( pVal->flags & MEM_Real ){
  60094. pVal->u.r = -pVal->u.r;
  60095. }else if( pVal->u.i==SMALLEST_INT64 ){
  60096. pVal->u.r = -(double)SMALLEST_INT64;
  60097. MemSetTypeFlag(pVal, MEM_Real);
  60098. }else{
  60099. pVal->u.i = -pVal->u.i;
  60100. }
  60101. sqlite3ValueApplyAffinity(pVal, affinity, enc);
  60102. }
  60103. }else if( op==TK_NULL ){
  60104. pVal = valueNew(db, pCtx);
  60105. if( pVal==0 ) goto no_mem;
  60106. }
  60107. #ifndef SQLITE_OMIT_BLOB_LITERAL
  60108. else if( op==TK_BLOB ){
  60109. int nVal;
  60110. assert( pExpr->u.zToken[0]=='x' || pExpr->u.zToken[0]=='X' );
  60111. assert( pExpr->u.zToken[1]=='\'' );
  60112. pVal = valueNew(db, pCtx);
  60113. if( !pVal ) goto no_mem;
  60114. zVal = &pExpr->u.zToken[2];
  60115. nVal = sqlite3Strlen30(zVal)-1;
  60116. assert( zVal[nVal]=='\'' );
  60117. sqlite3VdbeMemSetStr(pVal, sqlite3HexToBlob(db, zVal, nVal), nVal/2,
  60118. 0, SQLITE_DYNAMIC);
  60119. }
  60120. #endif
  60121. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  60122. else if( op==TK_FUNCTION && pCtx!=0 ){
  60123. rc = valueFromFunction(db, pExpr, enc, affinity, &pVal, pCtx);
  60124. }
  60125. #endif
  60126. *ppVal = pVal;
  60127. return rc;
  60128. no_mem:
  60129. db->mallocFailed = 1;
  60130. sqlite3DbFree(db, zVal);
  60131. assert( *ppVal==0 );
  60132. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  60133. if( pCtx==0 ) sqlite3ValueFree(pVal);
  60134. #else
  60135. assert( pCtx==0 ); sqlite3ValueFree(pVal);
  60136. #endif
  60137. return SQLITE_NOMEM;
  60138. }
  60139. /*
  60140. ** Create a new sqlite3_value object, containing the value of pExpr.
  60141. **
  60142. ** This only works for very simple expressions that consist of one constant
  60143. ** token (i.e. "5", "5.1", "'a string'"). If the expression can
  60144. ** be converted directly into a value, then the value is allocated and
  60145. ** a pointer written to *ppVal. The caller is responsible for deallocating
  60146. ** the value by passing it to sqlite3ValueFree() later on. If the expression
  60147. ** cannot be converted to a value, then *ppVal is set to NULL.
  60148. */
  60149. SQLITE_PRIVATE int sqlite3ValueFromExpr(
  60150. sqlite3 *db, /* The database connection */
  60151. Expr *pExpr, /* The expression to evaluate */
  60152. u8 enc, /* Encoding to use */
  60153. u8 affinity, /* Affinity to use */
  60154. sqlite3_value **ppVal /* Write the new value here */
  60155. ){
  60156. return valueFromExpr(db, pExpr, enc, affinity, ppVal, 0);
  60157. }
  60158. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  60159. /*
  60160. ** The implementation of the sqlite_record() function. This function accepts
  60161. ** a single argument of any type. The return value is a formatted database
  60162. ** record (a blob) containing the argument value.
  60163. **
  60164. ** This is used to convert the value stored in the 'sample' column of the
  60165. ** sqlite_stat3 table to the record format SQLite uses internally.
  60166. */
  60167. static void recordFunc(
  60168. sqlite3_context *context,
  60169. int argc,
  60170. sqlite3_value **argv
  60171. ){
  60172. const int file_format = 1;
  60173. int iSerial; /* Serial type */
  60174. int nSerial; /* Bytes of space for iSerial as varint */
  60175. int nVal; /* Bytes of space required for argv[0] */
  60176. int nRet;
  60177. sqlite3 *db;
  60178. u8 *aRet;
  60179. UNUSED_PARAMETER( argc );
  60180. iSerial = sqlite3VdbeSerialType(argv[0], file_format);
  60181. nSerial = sqlite3VarintLen(iSerial);
  60182. nVal = sqlite3VdbeSerialTypeLen(iSerial);
  60183. db = sqlite3_context_db_handle(context);
  60184. nRet = 1 + nSerial + nVal;
  60185. aRet = sqlite3DbMallocRaw(db, nRet);
  60186. if( aRet==0 ){
  60187. sqlite3_result_error_nomem(context);
  60188. }else{
  60189. aRet[0] = nSerial+1;
  60190. putVarint32(&aRet[1], iSerial);
  60191. sqlite3VdbeSerialPut(&aRet[1+nSerial], argv[0], iSerial);
  60192. sqlite3_result_blob(context, aRet, nRet, SQLITE_TRANSIENT);
  60193. sqlite3DbFree(db, aRet);
  60194. }
  60195. }
  60196. /*
  60197. ** Register built-in functions used to help read ANALYZE data.
  60198. */
  60199. SQLITE_PRIVATE void sqlite3AnalyzeFunctions(void){
  60200. static SQLITE_WSD FuncDef aAnalyzeTableFuncs[] = {
  60201. FUNCTION(sqlite_record, 1, 0, 0, recordFunc),
  60202. };
  60203. int i;
  60204. FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
  60205. FuncDef *aFunc = (FuncDef*)&GLOBAL(FuncDef, aAnalyzeTableFuncs);
  60206. for(i=0; i<ArraySize(aAnalyzeTableFuncs); i++){
  60207. sqlite3FuncDefInsert(pHash, &aFunc[i]);
  60208. }
  60209. }
  60210. /*
  60211. ** Attempt to extract a value from pExpr and use it to construct *ppVal.
  60212. **
  60213. ** If pAlloc is not NULL, then an UnpackedRecord object is created for
  60214. ** pAlloc if one does not exist and the new value is added to the
  60215. ** UnpackedRecord object.
  60216. **
  60217. ** A value is extracted in the following cases:
  60218. **
  60219. ** * (pExpr==0). In this case the value is assumed to be an SQL NULL,
  60220. **
  60221. ** * The expression is a bound variable, and this is a reprepare, or
  60222. **
  60223. ** * The expression is a literal value.
  60224. **
  60225. ** On success, *ppVal is made to point to the extracted value. The caller
  60226. ** is responsible for ensuring that the value is eventually freed.
  60227. */
  60228. static int stat4ValueFromExpr(
  60229. Parse *pParse, /* Parse context */
  60230. Expr *pExpr, /* The expression to extract a value from */
  60231. u8 affinity, /* Affinity to use */
  60232. struct ValueNewStat4Ctx *pAlloc,/* How to allocate space. Or NULL */
  60233. sqlite3_value **ppVal /* OUT: New value object (or NULL) */
  60234. ){
  60235. int rc = SQLITE_OK;
  60236. sqlite3_value *pVal = 0;
  60237. sqlite3 *db = pParse->db;
  60238. /* Skip over any TK_COLLATE nodes */
  60239. pExpr = sqlite3ExprSkipCollate(pExpr);
  60240. if( !pExpr ){
  60241. pVal = valueNew(db, pAlloc);
  60242. if( pVal ){
  60243. sqlite3VdbeMemSetNull((Mem*)pVal);
  60244. }
  60245. }else if( pExpr->op==TK_VARIABLE
  60246. || NEVER(pExpr->op==TK_REGISTER && pExpr->op2==TK_VARIABLE)
  60247. ){
  60248. Vdbe *v;
  60249. int iBindVar = pExpr->iColumn;
  60250. sqlite3VdbeSetVarmask(pParse->pVdbe, iBindVar);
  60251. if( (v = pParse->pReprepare)!=0 ){
  60252. pVal = valueNew(db, pAlloc);
  60253. if( pVal ){
  60254. rc = sqlite3VdbeMemCopy((Mem*)pVal, &v->aVar[iBindVar-1]);
  60255. if( rc==SQLITE_OK ){
  60256. sqlite3ValueApplyAffinity(pVal, affinity, ENC(db));
  60257. }
  60258. pVal->db = pParse->db;
  60259. }
  60260. }
  60261. }else{
  60262. rc = valueFromExpr(db, pExpr, ENC(db), affinity, &pVal, pAlloc);
  60263. }
  60264. assert( pVal==0 || pVal->db==db );
  60265. *ppVal = pVal;
  60266. return rc;
  60267. }
  60268. /*
  60269. ** This function is used to allocate and populate UnpackedRecord
  60270. ** structures intended to be compared against sample index keys stored
  60271. ** in the sqlite_stat4 table.
  60272. **
  60273. ** A single call to this function attempts to populates field iVal (leftmost
  60274. ** is 0 etc.) of the unpacked record with a value extracted from expression
  60275. ** pExpr. Extraction of values is possible if:
  60276. **
  60277. ** * (pExpr==0). In this case the value is assumed to be an SQL NULL,
  60278. **
  60279. ** * The expression is a bound variable, and this is a reprepare, or
  60280. **
  60281. ** * The sqlite3ValueFromExpr() function is able to extract a value
  60282. ** from the expression (i.e. the expression is a literal value).
  60283. **
  60284. ** If a value can be extracted, the affinity passed as the 5th argument
  60285. ** is applied to it before it is copied into the UnpackedRecord. Output
  60286. ** parameter *pbOk is set to true if a value is extracted, or false
  60287. ** otherwise.
  60288. **
  60289. ** When this function is called, *ppRec must either point to an object
  60290. ** allocated by an earlier call to this function, or must be NULL. If it
  60291. ** is NULL and a value can be successfully extracted, a new UnpackedRecord
  60292. ** is allocated (and *ppRec set to point to it) before returning.
  60293. **
  60294. ** Unless an error is encountered, SQLITE_OK is returned. It is not an
  60295. ** error if a value cannot be extracted from pExpr. If an error does
  60296. ** occur, an SQLite error code is returned.
  60297. */
  60298. SQLITE_PRIVATE int sqlite3Stat4ProbeSetValue(
  60299. Parse *pParse, /* Parse context */
  60300. Index *pIdx, /* Index being probed */
  60301. UnpackedRecord **ppRec, /* IN/OUT: Probe record */
  60302. Expr *pExpr, /* The expression to extract a value from */
  60303. u8 affinity, /* Affinity to use */
  60304. int iVal, /* Array element to populate */
  60305. int *pbOk /* OUT: True if value was extracted */
  60306. ){
  60307. int rc;
  60308. sqlite3_value *pVal = 0;
  60309. struct ValueNewStat4Ctx alloc;
  60310. alloc.pParse = pParse;
  60311. alloc.pIdx = pIdx;
  60312. alloc.ppRec = ppRec;
  60313. alloc.iVal = iVal;
  60314. rc = stat4ValueFromExpr(pParse, pExpr, affinity, &alloc, &pVal);
  60315. assert( pVal==0 || pVal->db==pParse->db );
  60316. *pbOk = (pVal!=0);
  60317. return rc;
  60318. }
  60319. /*
  60320. ** Attempt to extract a value from expression pExpr using the methods
  60321. ** as described for sqlite3Stat4ProbeSetValue() above.
  60322. **
  60323. ** If successful, set *ppVal to point to a new value object and return
  60324. ** SQLITE_OK. If no value can be extracted, but no other error occurs
  60325. ** (e.g. OOM), return SQLITE_OK and set *ppVal to NULL. Or, if an error
  60326. ** does occur, return an SQLite error code. The final value of *ppVal
  60327. ** is undefined in this case.
  60328. */
  60329. SQLITE_PRIVATE int sqlite3Stat4ValueFromExpr(
  60330. Parse *pParse, /* Parse context */
  60331. Expr *pExpr, /* The expression to extract a value from */
  60332. u8 affinity, /* Affinity to use */
  60333. sqlite3_value **ppVal /* OUT: New value object (or NULL) */
  60334. ){
  60335. return stat4ValueFromExpr(pParse, pExpr, affinity, 0, ppVal);
  60336. }
  60337. /*
  60338. ** Extract the iCol-th column from the nRec-byte record in pRec. Write
  60339. ** the column value into *ppVal. If *ppVal is initially NULL then a new
  60340. ** sqlite3_value object is allocated.
  60341. **
  60342. ** If *ppVal is initially NULL then the caller is responsible for
  60343. ** ensuring that the value written into *ppVal is eventually freed.
  60344. */
  60345. SQLITE_PRIVATE int sqlite3Stat4Column(
  60346. sqlite3 *db, /* Database handle */
  60347. const void *pRec, /* Pointer to buffer containing record */
  60348. int nRec, /* Size of buffer pRec in bytes */
  60349. int iCol, /* Column to extract */
  60350. sqlite3_value **ppVal /* OUT: Extracted value */
  60351. ){
  60352. u32 t; /* a column type code */
  60353. int nHdr; /* Size of the header in the record */
  60354. int iHdr; /* Next unread header byte */
  60355. int iField; /* Next unread data byte */
  60356. int szField; /* Size of the current data field */
  60357. int i; /* Column index */
  60358. u8 *a = (u8*)pRec; /* Typecast byte array */
  60359. Mem *pMem = *ppVal; /* Write result into this Mem object */
  60360. assert( iCol>0 );
  60361. iHdr = getVarint32(a, nHdr);
  60362. if( nHdr>nRec || iHdr>=nHdr ) return SQLITE_CORRUPT_BKPT;
  60363. iField = nHdr;
  60364. for(i=0; i<=iCol; i++){
  60365. iHdr += getVarint32(&a[iHdr], t);
  60366. testcase( iHdr==nHdr );
  60367. testcase( iHdr==nHdr+1 );
  60368. if( iHdr>nHdr ) return SQLITE_CORRUPT_BKPT;
  60369. szField = sqlite3VdbeSerialTypeLen(t);
  60370. iField += szField;
  60371. }
  60372. testcase( iField==nRec );
  60373. testcase( iField==nRec+1 );
  60374. if( iField>nRec ) return SQLITE_CORRUPT_BKPT;
  60375. if( pMem==0 ){
  60376. pMem = *ppVal = sqlite3ValueNew(db);
  60377. if( pMem==0 ) return SQLITE_NOMEM;
  60378. }
  60379. sqlite3VdbeSerialGet(&a[iField-szField], t, pMem);
  60380. pMem->enc = ENC(db);
  60381. return SQLITE_OK;
  60382. }
  60383. /*
  60384. ** Unless it is NULL, the argument must be an UnpackedRecord object returned
  60385. ** by an earlier call to sqlite3Stat4ProbeSetValue(). This call deletes
  60386. ** the object.
  60387. */
  60388. SQLITE_PRIVATE void sqlite3Stat4ProbeFree(UnpackedRecord *pRec){
  60389. if( pRec ){
  60390. int i;
  60391. int nCol = pRec->pKeyInfo->nField+pRec->pKeyInfo->nXField;
  60392. Mem *aMem = pRec->aMem;
  60393. sqlite3 *db = aMem[0].db;
  60394. for(i=0; i<nCol; i++){
  60395. sqlite3VdbeMemRelease(&aMem[i]);
  60396. }
  60397. sqlite3KeyInfoUnref(pRec->pKeyInfo);
  60398. sqlite3DbFree(db, pRec);
  60399. }
  60400. }
  60401. #endif /* ifdef SQLITE_ENABLE_STAT4 */
  60402. /*
  60403. ** Change the string value of an sqlite3_value object
  60404. */
  60405. SQLITE_PRIVATE void sqlite3ValueSetStr(
  60406. sqlite3_value *v, /* Value to be set */
  60407. int n, /* Length of string z */
  60408. const void *z, /* Text of the new string */
  60409. u8 enc, /* Encoding to use */
  60410. void (*xDel)(void*) /* Destructor for the string */
  60411. ){
  60412. if( v ) sqlite3VdbeMemSetStr((Mem *)v, z, n, enc, xDel);
  60413. }
  60414. /*
  60415. ** Free an sqlite3_value object
  60416. */
  60417. SQLITE_PRIVATE void sqlite3ValueFree(sqlite3_value *v){
  60418. if( !v ) return;
  60419. sqlite3VdbeMemRelease((Mem *)v);
  60420. sqlite3DbFree(((Mem*)v)->db, v);
  60421. }
  60422. /*
  60423. ** Return the number of bytes in the sqlite3_value object assuming
  60424. ** that it uses the encoding "enc"
  60425. */
  60426. SQLITE_PRIVATE int sqlite3ValueBytes(sqlite3_value *pVal, u8 enc){
  60427. Mem *p = (Mem*)pVal;
  60428. if( (p->flags & MEM_Blob)!=0 || sqlite3ValueText(pVal, enc) ){
  60429. if( p->flags & MEM_Zero ){
  60430. return p->n + p->u.nZero;
  60431. }else{
  60432. return p->n;
  60433. }
  60434. }
  60435. return 0;
  60436. }
  60437. /************** End of vdbemem.c *********************************************/
  60438. /************** Begin file vdbeaux.c *****************************************/
  60439. /*
  60440. ** 2003 September 6
  60441. **
  60442. ** The author disclaims copyright to this source code. In place of
  60443. ** a legal notice, here is a blessing:
  60444. **
  60445. ** May you do good and not evil.
  60446. ** May you find forgiveness for yourself and forgive others.
  60447. ** May you share freely, never taking more than you give.
  60448. **
  60449. *************************************************************************
  60450. ** This file contains code used for creating, destroying, and populating
  60451. ** a VDBE (or an "sqlite3_stmt" as it is known to the outside world.)
  60452. */
  60453. /*
  60454. ** Create a new virtual database engine.
  60455. */
  60456. SQLITE_PRIVATE Vdbe *sqlite3VdbeCreate(Parse *pParse){
  60457. sqlite3 *db = pParse->db;
  60458. Vdbe *p;
  60459. p = sqlite3DbMallocZero(db, sizeof(Vdbe) );
  60460. if( p==0 ) return 0;
  60461. p->db = db;
  60462. if( db->pVdbe ){
  60463. db->pVdbe->pPrev = p;
  60464. }
  60465. p->pNext = db->pVdbe;
  60466. p->pPrev = 0;
  60467. db->pVdbe = p;
  60468. p->magic = VDBE_MAGIC_INIT;
  60469. p->pParse = pParse;
  60470. assert( pParse->aLabel==0 );
  60471. assert( pParse->nLabel==0 );
  60472. assert( pParse->nOpAlloc==0 );
  60473. return p;
  60474. }
  60475. /*
  60476. ** Remember the SQL string for a prepared statement.
  60477. */
  60478. SQLITE_PRIVATE void sqlite3VdbeSetSql(Vdbe *p, const char *z, int n, int isPrepareV2){
  60479. assert( isPrepareV2==1 || isPrepareV2==0 );
  60480. if( p==0 ) return;
  60481. #if defined(SQLITE_OMIT_TRACE) && !defined(SQLITE_ENABLE_SQLLOG)
  60482. if( !isPrepareV2 ) return;
  60483. #endif
  60484. assert( p->zSql==0 );
  60485. p->zSql = sqlite3DbStrNDup(p->db, z, n);
  60486. p->isPrepareV2 = (u8)isPrepareV2;
  60487. }
  60488. /*
  60489. ** Return the SQL associated with a prepared statement
  60490. */
  60491. SQLITE_API const char *SQLITE_STDCALL sqlite3_sql(sqlite3_stmt *pStmt){
  60492. Vdbe *p = (Vdbe *)pStmt;
  60493. return (p && p->isPrepareV2) ? p->zSql : 0;
  60494. }
  60495. /*
  60496. ** Swap all content between two VDBE structures.
  60497. */
  60498. SQLITE_PRIVATE void sqlite3VdbeSwap(Vdbe *pA, Vdbe *pB){
  60499. Vdbe tmp, *pTmp;
  60500. char *zTmp;
  60501. tmp = *pA;
  60502. *pA = *pB;
  60503. *pB = tmp;
  60504. pTmp = pA->pNext;
  60505. pA->pNext = pB->pNext;
  60506. pB->pNext = pTmp;
  60507. pTmp = pA->pPrev;
  60508. pA->pPrev = pB->pPrev;
  60509. pB->pPrev = pTmp;
  60510. zTmp = pA->zSql;
  60511. pA->zSql = pB->zSql;
  60512. pB->zSql = zTmp;
  60513. pB->isPrepareV2 = pA->isPrepareV2;
  60514. }
  60515. /*
  60516. ** Resize the Vdbe.aOp array so that it is at least nOp elements larger
  60517. ** than its current size. nOp is guaranteed to be less than or equal
  60518. ** to 1024/sizeof(Op).
  60519. **
  60520. ** If an out-of-memory error occurs while resizing the array, return
  60521. ** SQLITE_NOMEM. In this case Vdbe.aOp and Parse.nOpAlloc remain
  60522. ** unchanged (this is so that any opcodes already allocated can be
  60523. ** correctly deallocated along with the rest of the Vdbe).
  60524. */
  60525. static int growOpArray(Vdbe *v, int nOp){
  60526. VdbeOp *pNew;
  60527. Parse *p = v->pParse;
  60528. /* The SQLITE_TEST_REALLOC_STRESS compile-time option is designed to force
  60529. ** more frequent reallocs and hence provide more opportunities for
  60530. ** simulated OOM faults. SQLITE_TEST_REALLOC_STRESS is generally used
  60531. ** during testing only. With SQLITE_TEST_REALLOC_STRESS grow the op array
  60532. ** by the minimum* amount required until the size reaches 512. Normal
  60533. ** operation (without SQLITE_TEST_REALLOC_STRESS) is to double the current
  60534. ** size of the op array or add 1KB of space, whichever is smaller. */
  60535. #ifdef SQLITE_TEST_REALLOC_STRESS
  60536. int nNew = (p->nOpAlloc>=512 ? p->nOpAlloc*2 : p->nOpAlloc+nOp);
  60537. #else
  60538. int nNew = (p->nOpAlloc ? p->nOpAlloc*2 : (int)(1024/sizeof(Op)));
  60539. UNUSED_PARAMETER(nOp);
  60540. #endif
  60541. assert( nOp<=(1024/sizeof(Op)) );
  60542. assert( nNew>=(p->nOpAlloc+nOp) );
  60543. pNew = sqlite3DbRealloc(p->db, v->aOp, nNew*sizeof(Op));
  60544. if( pNew ){
  60545. p->nOpAlloc = sqlite3DbMallocSize(p->db, pNew)/sizeof(Op);
  60546. v->aOp = pNew;
  60547. }
  60548. return (pNew ? SQLITE_OK : SQLITE_NOMEM);
  60549. }
  60550. #ifdef SQLITE_DEBUG
  60551. /* This routine is just a convenient place to set a breakpoint that will
  60552. ** fire after each opcode is inserted and displayed using
  60553. ** "PRAGMA vdbe_addoptrace=on".
  60554. */
  60555. static void test_addop_breakpoint(void){
  60556. static int n = 0;
  60557. n++;
  60558. }
  60559. #endif
  60560. /*
  60561. ** Add a new instruction to the list of instructions current in the
  60562. ** VDBE. Return the address of the new instruction.
  60563. **
  60564. ** Parameters:
  60565. **
  60566. ** p Pointer to the VDBE
  60567. **
  60568. ** op The opcode for this instruction
  60569. **
  60570. ** p1, p2, p3 Operands
  60571. **
  60572. ** Use the sqlite3VdbeResolveLabel() function to fix an address and
  60573. ** the sqlite3VdbeChangeP4() function to change the value of the P4
  60574. ** operand.
  60575. */
  60576. SQLITE_PRIVATE int sqlite3VdbeAddOp3(Vdbe *p, int op, int p1, int p2, int p3){
  60577. int i;
  60578. VdbeOp *pOp;
  60579. i = p->nOp;
  60580. assert( p->magic==VDBE_MAGIC_INIT );
  60581. assert( op>0 && op<0xff );
  60582. if( p->pParse->nOpAlloc<=i ){
  60583. if( growOpArray(p, 1) ){
  60584. return 1;
  60585. }
  60586. }
  60587. p->nOp++;
  60588. pOp = &p->aOp[i];
  60589. pOp->opcode = (u8)op;
  60590. pOp->p5 = 0;
  60591. pOp->p1 = p1;
  60592. pOp->p2 = p2;
  60593. pOp->p3 = p3;
  60594. pOp->p4.p = 0;
  60595. pOp->p4type = P4_NOTUSED;
  60596. #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
  60597. pOp->zComment = 0;
  60598. #endif
  60599. #ifdef SQLITE_DEBUG
  60600. if( p->db->flags & SQLITE_VdbeAddopTrace ){
  60601. int jj, kk;
  60602. Parse *pParse = p->pParse;
  60603. for(jj=kk=0; jj<SQLITE_N_COLCACHE; jj++){
  60604. struct yColCache *x = pParse->aColCache + jj;
  60605. if( x->iLevel>pParse->iCacheLevel || x->iReg==0 ) continue;
  60606. printf(" r[%d]={%d:%d}", x->iReg, x->iTable, x->iColumn);
  60607. kk++;
  60608. }
  60609. if( kk ) printf("\n");
  60610. sqlite3VdbePrintOp(0, i, &p->aOp[i]);
  60611. test_addop_breakpoint();
  60612. }
  60613. #endif
  60614. #ifdef VDBE_PROFILE
  60615. pOp->cycles = 0;
  60616. pOp->cnt = 0;
  60617. #endif
  60618. #ifdef SQLITE_VDBE_COVERAGE
  60619. pOp->iSrcLine = 0;
  60620. #endif
  60621. return i;
  60622. }
  60623. SQLITE_PRIVATE int sqlite3VdbeAddOp0(Vdbe *p, int op){
  60624. return sqlite3VdbeAddOp3(p, op, 0, 0, 0);
  60625. }
  60626. SQLITE_PRIVATE int sqlite3VdbeAddOp1(Vdbe *p, int op, int p1){
  60627. return sqlite3VdbeAddOp3(p, op, p1, 0, 0);
  60628. }
  60629. SQLITE_PRIVATE int sqlite3VdbeAddOp2(Vdbe *p, int op, int p1, int p2){
  60630. return sqlite3VdbeAddOp3(p, op, p1, p2, 0);
  60631. }
  60632. /*
  60633. ** Add an opcode that includes the p4 value as a pointer.
  60634. */
  60635. SQLITE_PRIVATE int sqlite3VdbeAddOp4(
  60636. Vdbe *p, /* Add the opcode to this VM */
  60637. int op, /* The new opcode */
  60638. int p1, /* The P1 operand */
  60639. int p2, /* The P2 operand */
  60640. int p3, /* The P3 operand */
  60641. const char *zP4, /* The P4 operand */
  60642. int p4type /* P4 operand type */
  60643. ){
  60644. int addr = sqlite3VdbeAddOp3(p, op, p1, p2, p3);
  60645. sqlite3VdbeChangeP4(p, addr, zP4, p4type);
  60646. return addr;
  60647. }
  60648. /*
  60649. ** Add an OP_ParseSchema opcode. This routine is broken out from
  60650. ** sqlite3VdbeAddOp4() since it needs to also needs to mark all btrees
  60651. ** as having been used.
  60652. **
  60653. ** The zWhere string must have been obtained from sqlite3_malloc().
  60654. ** This routine will take ownership of the allocated memory.
  60655. */
  60656. SQLITE_PRIVATE void sqlite3VdbeAddParseSchemaOp(Vdbe *p, int iDb, char *zWhere){
  60657. int j;
  60658. int addr = sqlite3VdbeAddOp3(p, OP_ParseSchema, iDb, 0, 0);
  60659. sqlite3VdbeChangeP4(p, addr, zWhere, P4_DYNAMIC);
  60660. for(j=0; j<p->db->nDb; j++) sqlite3VdbeUsesBtree(p, j);
  60661. }
  60662. /*
  60663. ** Add an opcode that includes the p4 value as an integer.
  60664. */
  60665. SQLITE_PRIVATE int sqlite3VdbeAddOp4Int(
  60666. Vdbe *p, /* Add the opcode to this VM */
  60667. int op, /* The new opcode */
  60668. int p1, /* The P1 operand */
  60669. int p2, /* The P2 operand */
  60670. int p3, /* The P3 operand */
  60671. int p4 /* The P4 operand as an integer */
  60672. ){
  60673. int addr = sqlite3VdbeAddOp3(p, op, p1, p2, p3);
  60674. sqlite3VdbeChangeP4(p, addr, SQLITE_INT_TO_PTR(p4), P4_INT32);
  60675. return addr;
  60676. }
  60677. /*
  60678. ** Create a new symbolic label for an instruction that has yet to be
  60679. ** coded. The symbolic label is really just a negative number. The
  60680. ** label can be used as the P2 value of an operation. Later, when
  60681. ** the label is resolved to a specific address, the VDBE will scan
  60682. ** through its operation list and change all values of P2 which match
  60683. ** the label into the resolved address.
  60684. **
  60685. ** The VDBE knows that a P2 value is a label because labels are
  60686. ** always negative and P2 values are suppose to be non-negative.
  60687. ** Hence, a negative P2 value is a label that has yet to be resolved.
  60688. **
  60689. ** Zero is returned if a malloc() fails.
  60690. */
  60691. SQLITE_PRIVATE int sqlite3VdbeMakeLabel(Vdbe *v){
  60692. Parse *p = v->pParse;
  60693. int i = p->nLabel++;
  60694. assert( v->magic==VDBE_MAGIC_INIT );
  60695. if( (i & (i-1))==0 ){
  60696. p->aLabel = sqlite3DbReallocOrFree(p->db, p->aLabel,
  60697. (i*2+1)*sizeof(p->aLabel[0]));
  60698. }
  60699. if( p->aLabel ){
  60700. p->aLabel[i] = -1;
  60701. }
  60702. return -1-i;
  60703. }
  60704. /*
  60705. ** Resolve label "x" to be the address of the next instruction to
  60706. ** be inserted. The parameter "x" must have been obtained from
  60707. ** a prior call to sqlite3VdbeMakeLabel().
  60708. */
  60709. SQLITE_PRIVATE void sqlite3VdbeResolveLabel(Vdbe *v, int x){
  60710. Parse *p = v->pParse;
  60711. int j = -1-x;
  60712. assert( v->magic==VDBE_MAGIC_INIT );
  60713. assert( j<p->nLabel );
  60714. if( ALWAYS(j>=0) && p->aLabel ){
  60715. p->aLabel[j] = v->nOp;
  60716. }
  60717. p->iFixedOp = v->nOp - 1;
  60718. }
  60719. /*
  60720. ** Mark the VDBE as one that can only be run one time.
  60721. */
  60722. SQLITE_PRIVATE void sqlite3VdbeRunOnlyOnce(Vdbe *p){
  60723. p->runOnlyOnce = 1;
  60724. }
  60725. #ifdef SQLITE_DEBUG /* sqlite3AssertMayAbort() logic */
  60726. /*
  60727. ** The following type and function are used to iterate through all opcodes
  60728. ** in a Vdbe main program and each of the sub-programs (triggers) it may
  60729. ** invoke directly or indirectly. It should be used as follows:
  60730. **
  60731. ** Op *pOp;
  60732. ** VdbeOpIter sIter;
  60733. **
  60734. ** memset(&sIter, 0, sizeof(sIter));
  60735. ** sIter.v = v; // v is of type Vdbe*
  60736. ** while( (pOp = opIterNext(&sIter)) ){
  60737. ** // Do something with pOp
  60738. ** }
  60739. ** sqlite3DbFree(v->db, sIter.apSub);
  60740. **
  60741. */
  60742. typedef struct VdbeOpIter VdbeOpIter;
  60743. struct VdbeOpIter {
  60744. Vdbe *v; /* Vdbe to iterate through the opcodes of */
  60745. SubProgram **apSub; /* Array of subprograms */
  60746. int nSub; /* Number of entries in apSub */
  60747. int iAddr; /* Address of next instruction to return */
  60748. int iSub; /* 0 = main program, 1 = first sub-program etc. */
  60749. };
  60750. static Op *opIterNext(VdbeOpIter *p){
  60751. Vdbe *v = p->v;
  60752. Op *pRet = 0;
  60753. Op *aOp;
  60754. int nOp;
  60755. if( p->iSub<=p->nSub ){
  60756. if( p->iSub==0 ){
  60757. aOp = v->aOp;
  60758. nOp = v->nOp;
  60759. }else{
  60760. aOp = p->apSub[p->iSub-1]->aOp;
  60761. nOp = p->apSub[p->iSub-1]->nOp;
  60762. }
  60763. assert( p->iAddr<nOp );
  60764. pRet = &aOp[p->iAddr];
  60765. p->iAddr++;
  60766. if( p->iAddr==nOp ){
  60767. p->iSub++;
  60768. p->iAddr = 0;
  60769. }
  60770. if( pRet->p4type==P4_SUBPROGRAM ){
  60771. int nByte = (p->nSub+1)*sizeof(SubProgram*);
  60772. int j;
  60773. for(j=0; j<p->nSub; j++){
  60774. if( p->apSub[j]==pRet->p4.pProgram ) break;
  60775. }
  60776. if( j==p->nSub ){
  60777. p->apSub = sqlite3DbReallocOrFree(v->db, p->apSub, nByte);
  60778. if( !p->apSub ){
  60779. pRet = 0;
  60780. }else{
  60781. p->apSub[p->nSub++] = pRet->p4.pProgram;
  60782. }
  60783. }
  60784. }
  60785. }
  60786. return pRet;
  60787. }
  60788. /*
  60789. ** Check if the program stored in the VM associated with pParse may
  60790. ** throw an ABORT exception (causing the statement, but not entire transaction
  60791. ** to be rolled back). This condition is true if the main program or any
  60792. ** sub-programs contains any of the following:
  60793. **
  60794. ** * OP_Halt with P1=SQLITE_CONSTRAINT and P2=OE_Abort.
  60795. ** * OP_HaltIfNull with P1=SQLITE_CONSTRAINT and P2=OE_Abort.
  60796. ** * OP_Destroy
  60797. ** * OP_VUpdate
  60798. ** * OP_VRename
  60799. ** * OP_FkCounter with P2==0 (immediate foreign key constraint)
  60800. **
  60801. ** Then check that the value of Parse.mayAbort is true if an
  60802. ** ABORT may be thrown, or false otherwise. Return true if it does
  60803. ** match, or false otherwise. This function is intended to be used as
  60804. ** part of an assert statement in the compiler. Similar to:
  60805. **
  60806. ** assert( sqlite3VdbeAssertMayAbort(pParse->pVdbe, pParse->mayAbort) );
  60807. */
  60808. SQLITE_PRIVATE int sqlite3VdbeAssertMayAbort(Vdbe *v, int mayAbort){
  60809. int hasAbort = 0;
  60810. int hasFkCounter = 0;
  60811. Op *pOp;
  60812. VdbeOpIter sIter;
  60813. memset(&sIter, 0, sizeof(sIter));
  60814. sIter.v = v;
  60815. while( (pOp = opIterNext(&sIter))!=0 ){
  60816. int opcode = pOp->opcode;
  60817. if( opcode==OP_Destroy || opcode==OP_VUpdate || opcode==OP_VRename
  60818. || ((opcode==OP_Halt || opcode==OP_HaltIfNull)
  60819. && ((pOp->p1&0xff)==SQLITE_CONSTRAINT && pOp->p2==OE_Abort))
  60820. ){
  60821. hasAbort = 1;
  60822. break;
  60823. }
  60824. #ifndef SQLITE_OMIT_FOREIGN_KEY
  60825. if( opcode==OP_FkCounter && pOp->p1==0 && pOp->p2==1 ){
  60826. hasFkCounter = 1;
  60827. }
  60828. #endif
  60829. }
  60830. sqlite3DbFree(v->db, sIter.apSub);
  60831. /* Return true if hasAbort==mayAbort. Or if a malloc failure occurred.
  60832. ** If malloc failed, then the while() loop above may not have iterated
  60833. ** through all opcodes and hasAbort may be set incorrectly. Return
  60834. ** true for this case to prevent the assert() in the callers frame
  60835. ** from failing. */
  60836. return ( v->db->mallocFailed || hasAbort==mayAbort || hasFkCounter );
  60837. }
  60838. #endif /* SQLITE_DEBUG - the sqlite3AssertMayAbort() function */
  60839. /*
  60840. ** Loop through the program looking for P2 values that are negative
  60841. ** on jump instructions. Each such value is a label. Resolve the
  60842. ** label by setting the P2 value to its correct non-zero value.
  60843. **
  60844. ** This routine is called once after all opcodes have been inserted.
  60845. **
  60846. ** Variable *pMaxFuncArgs is set to the maximum value of any P2 argument
  60847. ** to an OP_Function, OP_AggStep or OP_VFilter opcode. This is used by
  60848. ** sqlite3VdbeMakeReady() to size the Vdbe.apArg[] array.
  60849. **
  60850. ** The Op.opflags field is set on all opcodes.
  60851. */
  60852. static void resolveP2Values(Vdbe *p, int *pMaxFuncArgs){
  60853. int i;
  60854. int nMaxArgs = *pMaxFuncArgs;
  60855. Op *pOp;
  60856. Parse *pParse = p->pParse;
  60857. int *aLabel = pParse->aLabel;
  60858. p->readOnly = 1;
  60859. p->bIsReader = 0;
  60860. for(pOp=p->aOp, i=p->nOp-1; i>=0; i--, pOp++){
  60861. u8 opcode = pOp->opcode;
  60862. /* NOTE: Be sure to update mkopcodeh.awk when adding or removing
  60863. ** cases from this switch! */
  60864. switch( opcode ){
  60865. case OP_Function:
  60866. case OP_AggStep: {
  60867. if( pOp->p5>nMaxArgs ) nMaxArgs = pOp->p5;
  60868. break;
  60869. }
  60870. case OP_Transaction: {
  60871. if( pOp->p2!=0 ) p->readOnly = 0;
  60872. /* fall thru */
  60873. }
  60874. case OP_AutoCommit:
  60875. case OP_Savepoint: {
  60876. p->bIsReader = 1;
  60877. break;
  60878. }
  60879. #ifndef SQLITE_OMIT_WAL
  60880. case OP_Checkpoint:
  60881. #endif
  60882. case OP_Vacuum:
  60883. case OP_JournalMode: {
  60884. p->readOnly = 0;
  60885. p->bIsReader = 1;
  60886. break;
  60887. }
  60888. #ifndef SQLITE_OMIT_VIRTUALTABLE
  60889. case OP_VUpdate: {
  60890. if( pOp->p2>nMaxArgs ) nMaxArgs = pOp->p2;
  60891. break;
  60892. }
  60893. case OP_VFilter: {
  60894. int n;
  60895. assert( p->nOp - i >= 3 );
  60896. assert( pOp[-1].opcode==OP_Integer );
  60897. n = pOp[-1].p1;
  60898. if( n>nMaxArgs ) nMaxArgs = n;
  60899. break;
  60900. }
  60901. #endif
  60902. case OP_Next:
  60903. case OP_NextIfOpen:
  60904. case OP_SorterNext: {
  60905. pOp->p4.xAdvance = sqlite3BtreeNext;
  60906. pOp->p4type = P4_ADVANCE;
  60907. break;
  60908. }
  60909. case OP_Prev:
  60910. case OP_PrevIfOpen: {
  60911. pOp->p4.xAdvance = sqlite3BtreePrevious;
  60912. pOp->p4type = P4_ADVANCE;
  60913. break;
  60914. }
  60915. }
  60916. pOp->opflags = sqlite3OpcodeProperty[opcode];
  60917. if( (pOp->opflags & OPFLG_JUMP)!=0 && pOp->p2<0 ){
  60918. assert( -1-pOp->p2<pParse->nLabel );
  60919. pOp->p2 = aLabel[-1-pOp->p2];
  60920. }
  60921. }
  60922. sqlite3DbFree(p->db, pParse->aLabel);
  60923. pParse->aLabel = 0;
  60924. pParse->nLabel = 0;
  60925. *pMaxFuncArgs = nMaxArgs;
  60926. assert( p->bIsReader!=0 || DbMaskAllZero(p->btreeMask) );
  60927. }
  60928. /*
  60929. ** Return the address of the next instruction to be inserted.
  60930. */
  60931. SQLITE_PRIVATE int sqlite3VdbeCurrentAddr(Vdbe *p){
  60932. assert( p->magic==VDBE_MAGIC_INIT );
  60933. return p->nOp;
  60934. }
  60935. /*
  60936. ** This function returns a pointer to the array of opcodes associated with
  60937. ** the Vdbe passed as the first argument. It is the callers responsibility
  60938. ** to arrange for the returned array to be eventually freed using the
  60939. ** vdbeFreeOpArray() function.
  60940. **
  60941. ** Before returning, *pnOp is set to the number of entries in the returned
  60942. ** array. Also, *pnMaxArg is set to the larger of its current value and
  60943. ** the number of entries in the Vdbe.apArg[] array required to execute the
  60944. ** returned program.
  60945. */
  60946. SQLITE_PRIVATE VdbeOp *sqlite3VdbeTakeOpArray(Vdbe *p, int *pnOp, int *pnMaxArg){
  60947. VdbeOp *aOp = p->aOp;
  60948. assert( aOp && !p->db->mallocFailed );
  60949. /* Check that sqlite3VdbeUsesBtree() was not called on this VM */
  60950. assert( DbMaskAllZero(p->btreeMask) );
  60951. resolveP2Values(p, pnMaxArg);
  60952. *pnOp = p->nOp;
  60953. p->aOp = 0;
  60954. return aOp;
  60955. }
  60956. /*
  60957. ** Add a whole list of operations to the operation stack. Return the
  60958. ** address of the first operation added.
  60959. */
  60960. SQLITE_PRIVATE int sqlite3VdbeAddOpList(Vdbe *p, int nOp, VdbeOpList const *aOp, int iLineno){
  60961. int addr;
  60962. assert( p->magic==VDBE_MAGIC_INIT );
  60963. if( p->nOp + nOp > p->pParse->nOpAlloc && growOpArray(p, nOp) ){
  60964. return 0;
  60965. }
  60966. addr = p->nOp;
  60967. if( ALWAYS(nOp>0) ){
  60968. int i;
  60969. VdbeOpList const *pIn = aOp;
  60970. for(i=0; i<nOp; i++, pIn++){
  60971. int p2 = pIn->p2;
  60972. VdbeOp *pOut = &p->aOp[i+addr];
  60973. pOut->opcode = pIn->opcode;
  60974. pOut->p1 = pIn->p1;
  60975. if( p2<0 ){
  60976. assert( sqlite3OpcodeProperty[pOut->opcode] & OPFLG_JUMP );
  60977. pOut->p2 = addr + ADDR(p2);
  60978. }else{
  60979. pOut->p2 = p2;
  60980. }
  60981. pOut->p3 = pIn->p3;
  60982. pOut->p4type = P4_NOTUSED;
  60983. pOut->p4.p = 0;
  60984. pOut->p5 = 0;
  60985. #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
  60986. pOut->zComment = 0;
  60987. #endif
  60988. #ifdef SQLITE_VDBE_COVERAGE
  60989. pOut->iSrcLine = iLineno+i;
  60990. #else
  60991. (void)iLineno;
  60992. #endif
  60993. #ifdef SQLITE_DEBUG
  60994. if( p->db->flags & SQLITE_VdbeAddopTrace ){
  60995. sqlite3VdbePrintOp(0, i+addr, &p->aOp[i+addr]);
  60996. }
  60997. #endif
  60998. }
  60999. p->nOp += nOp;
  61000. }
  61001. return addr;
  61002. }
  61003. #if defined(SQLITE_ENABLE_STMT_SCANSTATUS)
  61004. /*
  61005. ** Add an entry to the array of counters managed by sqlite3_stmt_scanstatus().
  61006. */
  61007. SQLITE_PRIVATE void sqlite3VdbeScanStatus(
  61008. Vdbe *p, /* VM to add scanstatus() to */
  61009. int addrExplain, /* Address of OP_Explain (or 0) */
  61010. int addrLoop, /* Address of loop counter */
  61011. int addrVisit, /* Address of rows visited counter */
  61012. LogEst nEst, /* Estimated number of output rows */
  61013. const char *zName /* Name of table or index being scanned */
  61014. ){
  61015. int nByte = (p->nScan+1) * sizeof(ScanStatus);
  61016. ScanStatus *aNew;
  61017. aNew = (ScanStatus*)sqlite3DbRealloc(p->db, p->aScan, nByte);
  61018. if( aNew ){
  61019. ScanStatus *pNew = &aNew[p->nScan++];
  61020. pNew->addrExplain = addrExplain;
  61021. pNew->addrLoop = addrLoop;
  61022. pNew->addrVisit = addrVisit;
  61023. pNew->nEst = nEst;
  61024. pNew->zName = sqlite3DbStrDup(p->db, zName);
  61025. p->aScan = aNew;
  61026. }
  61027. }
  61028. #endif
  61029. /*
  61030. ** Change the value of the P1 operand for a specific instruction.
  61031. ** This routine is useful when a large program is loaded from a
  61032. ** static array using sqlite3VdbeAddOpList but we want to make a
  61033. ** few minor changes to the program.
  61034. */
  61035. SQLITE_PRIVATE void sqlite3VdbeChangeP1(Vdbe *p, u32 addr, int val){
  61036. assert( p!=0 );
  61037. if( ((u32)p->nOp)>addr ){
  61038. p->aOp[addr].p1 = val;
  61039. }
  61040. }
  61041. /*
  61042. ** Change the value of the P2 operand for a specific instruction.
  61043. ** This routine is useful for setting a jump destination.
  61044. */
  61045. SQLITE_PRIVATE void sqlite3VdbeChangeP2(Vdbe *p, u32 addr, int val){
  61046. assert( p!=0 );
  61047. if( ((u32)p->nOp)>addr ){
  61048. p->aOp[addr].p2 = val;
  61049. }
  61050. }
  61051. /*
  61052. ** Change the value of the P3 operand for a specific instruction.
  61053. */
  61054. SQLITE_PRIVATE void sqlite3VdbeChangeP3(Vdbe *p, u32 addr, int val){
  61055. assert( p!=0 );
  61056. if( ((u32)p->nOp)>addr ){
  61057. p->aOp[addr].p3 = val;
  61058. }
  61059. }
  61060. /*
  61061. ** Change the value of the P5 operand for the most recently
  61062. ** added operation.
  61063. */
  61064. SQLITE_PRIVATE void sqlite3VdbeChangeP5(Vdbe *p, u8 val){
  61065. assert( p!=0 );
  61066. if( p->aOp ){
  61067. assert( p->nOp>0 );
  61068. p->aOp[p->nOp-1].p5 = val;
  61069. }
  61070. }
  61071. /*
  61072. ** Change the P2 operand of instruction addr so that it points to
  61073. ** the address of the next instruction to be coded.
  61074. */
  61075. SQLITE_PRIVATE void sqlite3VdbeJumpHere(Vdbe *p, int addr){
  61076. sqlite3VdbeChangeP2(p, addr, p->nOp);
  61077. p->pParse->iFixedOp = p->nOp - 1;
  61078. }
  61079. /*
  61080. ** If the input FuncDef structure is ephemeral, then free it. If
  61081. ** the FuncDef is not ephermal, then do nothing.
  61082. */
  61083. static void freeEphemeralFunction(sqlite3 *db, FuncDef *pDef){
  61084. if( ALWAYS(pDef) && (pDef->funcFlags & SQLITE_FUNC_EPHEM)!=0 ){
  61085. sqlite3DbFree(db, pDef);
  61086. }
  61087. }
  61088. static void vdbeFreeOpArray(sqlite3 *, Op *, int);
  61089. /*
  61090. ** Delete a P4 value if necessary.
  61091. */
  61092. static void freeP4(sqlite3 *db, int p4type, void *p4){
  61093. if( p4 ){
  61094. assert( db );
  61095. switch( p4type ){
  61096. case P4_REAL:
  61097. case P4_INT64:
  61098. case P4_DYNAMIC:
  61099. case P4_INTARRAY: {
  61100. sqlite3DbFree(db, p4);
  61101. break;
  61102. }
  61103. case P4_KEYINFO: {
  61104. if( db->pnBytesFreed==0 ) sqlite3KeyInfoUnref((KeyInfo*)p4);
  61105. break;
  61106. }
  61107. case P4_MPRINTF: {
  61108. if( db->pnBytesFreed==0 ) sqlite3_free(p4);
  61109. break;
  61110. }
  61111. case P4_FUNCDEF: {
  61112. freeEphemeralFunction(db, (FuncDef*)p4);
  61113. break;
  61114. }
  61115. case P4_MEM: {
  61116. if( db->pnBytesFreed==0 ){
  61117. sqlite3ValueFree((sqlite3_value*)p4);
  61118. }else{
  61119. Mem *p = (Mem*)p4;
  61120. if( p->szMalloc ) sqlite3DbFree(db, p->zMalloc);
  61121. sqlite3DbFree(db, p);
  61122. }
  61123. break;
  61124. }
  61125. case P4_VTAB : {
  61126. if( db->pnBytesFreed==0 ) sqlite3VtabUnlock((VTable *)p4);
  61127. break;
  61128. }
  61129. }
  61130. }
  61131. }
  61132. /*
  61133. ** Free the space allocated for aOp and any p4 values allocated for the
  61134. ** opcodes contained within. If aOp is not NULL it is assumed to contain
  61135. ** nOp entries.
  61136. */
  61137. static void vdbeFreeOpArray(sqlite3 *db, Op *aOp, int nOp){
  61138. if( aOp ){
  61139. Op *pOp;
  61140. for(pOp=aOp; pOp<&aOp[nOp]; pOp++){
  61141. freeP4(db, pOp->p4type, pOp->p4.p);
  61142. #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
  61143. sqlite3DbFree(db, pOp->zComment);
  61144. #endif
  61145. }
  61146. }
  61147. sqlite3DbFree(db, aOp);
  61148. }
  61149. /*
  61150. ** Link the SubProgram object passed as the second argument into the linked
  61151. ** list at Vdbe.pSubProgram. This list is used to delete all sub-program
  61152. ** objects when the VM is no longer required.
  61153. */
  61154. SQLITE_PRIVATE void sqlite3VdbeLinkSubProgram(Vdbe *pVdbe, SubProgram *p){
  61155. p->pNext = pVdbe->pProgram;
  61156. pVdbe->pProgram = p;
  61157. }
  61158. /*
  61159. ** Change the opcode at addr into OP_Noop
  61160. */
  61161. SQLITE_PRIVATE void sqlite3VdbeChangeToNoop(Vdbe *p, int addr){
  61162. if( addr<p->nOp ){
  61163. VdbeOp *pOp = &p->aOp[addr];
  61164. sqlite3 *db = p->db;
  61165. freeP4(db, pOp->p4type, pOp->p4.p);
  61166. memset(pOp, 0, sizeof(pOp[0]));
  61167. pOp->opcode = OP_Noop;
  61168. if( addr==p->nOp-1 ) p->nOp--;
  61169. }
  61170. }
  61171. /*
  61172. ** If the last opcode is "op" and it is not a jump destination,
  61173. ** then remove it. Return true if and only if an opcode was removed.
  61174. */
  61175. SQLITE_PRIVATE int sqlite3VdbeDeletePriorOpcode(Vdbe *p, u8 op){
  61176. if( (p->nOp-1)>(p->pParse->iFixedOp) && p->aOp[p->nOp-1].opcode==op ){
  61177. sqlite3VdbeChangeToNoop(p, p->nOp-1);
  61178. return 1;
  61179. }else{
  61180. return 0;
  61181. }
  61182. }
  61183. /*
  61184. ** Change the value of the P4 operand for a specific instruction.
  61185. ** This routine is useful when a large program is loaded from a
  61186. ** static array using sqlite3VdbeAddOpList but we want to make a
  61187. ** few minor changes to the program.
  61188. **
  61189. ** If n>=0 then the P4 operand is dynamic, meaning that a copy of
  61190. ** the string is made into memory obtained from sqlite3_malloc().
  61191. ** A value of n==0 means copy bytes of zP4 up to and including the
  61192. ** first null byte. If n>0 then copy n+1 bytes of zP4.
  61193. **
  61194. ** Other values of n (P4_STATIC, P4_COLLSEQ etc.) indicate that zP4 points
  61195. ** to a string or structure that is guaranteed to exist for the lifetime of
  61196. ** the Vdbe. In these cases we can just copy the pointer.
  61197. **
  61198. ** If addr<0 then change P4 on the most recently inserted instruction.
  61199. */
  61200. SQLITE_PRIVATE void sqlite3VdbeChangeP4(Vdbe *p, int addr, const char *zP4, int n){
  61201. Op *pOp;
  61202. sqlite3 *db;
  61203. assert( p!=0 );
  61204. db = p->db;
  61205. assert( p->magic==VDBE_MAGIC_INIT );
  61206. if( p->aOp==0 || db->mallocFailed ){
  61207. if( n!=P4_VTAB ){
  61208. freeP4(db, n, (void*)*(char**)&zP4);
  61209. }
  61210. return;
  61211. }
  61212. assert( p->nOp>0 );
  61213. assert( addr<p->nOp );
  61214. if( addr<0 ){
  61215. addr = p->nOp - 1;
  61216. }
  61217. pOp = &p->aOp[addr];
  61218. assert( pOp->p4type==P4_NOTUSED
  61219. || pOp->p4type==P4_INT32
  61220. || pOp->p4type==P4_KEYINFO );
  61221. freeP4(db, pOp->p4type, pOp->p4.p);
  61222. pOp->p4.p = 0;
  61223. if( n==P4_INT32 ){
  61224. /* Note: this cast is safe, because the origin data point was an int
  61225. ** that was cast to a (const char *). */
  61226. pOp->p4.i = SQLITE_PTR_TO_INT(zP4);
  61227. pOp->p4type = P4_INT32;
  61228. }else if( zP4==0 ){
  61229. pOp->p4.p = 0;
  61230. pOp->p4type = P4_NOTUSED;
  61231. }else if( n==P4_KEYINFO ){
  61232. pOp->p4.p = (void*)zP4;
  61233. pOp->p4type = P4_KEYINFO;
  61234. }else if( n==P4_VTAB ){
  61235. pOp->p4.p = (void*)zP4;
  61236. pOp->p4type = P4_VTAB;
  61237. sqlite3VtabLock((VTable *)zP4);
  61238. assert( ((VTable *)zP4)->db==p->db );
  61239. }else if( n<0 ){
  61240. pOp->p4.p = (void*)zP4;
  61241. pOp->p4type = (signed char)n;
  61242. }else{
  61243. if( n==0 ) n = sqlite3Strlen30(zP4);
  61244. pOp->p4.z = sqlite3DbStrNDup(p->db, zP4, n);
  61245. pOp->p4type = P4_DYNAMIC;
  61246. }
  61247. }
  61248. /*
  61249. ** Set the P4 on the most recently added opcode to the KeyInfo for the
  61250. ** index given.
  61251. */
  61252. SQLITE_PRIVATE void sqlite3VdbeSetP4KeyInfo(Parse *pParse, Index *pIdx){
  61253. Vdbe *v = pParse->pVdbe;
  61254. assert( v!=0 );
  61255. assert( pIdx!=0 );
  61256. sqlite3VdbeChangeP4(v, -1, (char*)sqlite3KeyInfoOfIndex(pParse, pIdx),
  61257. P4_KEYINFO);
  61258. }
  61259. #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
  61260. /*
  61261. ** Change the comment on the most recently coded instruction. Or
  61262. ** insert a No-op and add the comment to that new instruction. This
  61263. ** makes the code easier to read during debugging. None of this happens
  61264. ** in a production build.
  61265. */
  61266. static void vdbeVComment(Vdbe *p, const char *zFormat, va_list ap){
  61267. assert( p->nOp>0 || p->aOp==0 );
  61268. assert( p->aOp==0 || p->aOp[p->nOp-1].zComment==0 || p->db->mallocFailed );
  61269. if( p->nOp ){
  61270. assert( p->aOp );
  61271. sqlite3DbFree(p->db, p->aOp[p->nOp-1].zComment);
  61272. p->aOp[p->nOp-1].zComment = sqlite3VMPrintf(p->db, zFormat, ap);
  61273. }
  61274. }
  61275. SQLITE_PRIVATE void sqlite3VdbeComment(Vdbe *p, const char *zFormat, ...){
  61276. va_list ap;
  61277. if( p ){
  61278. va_start(ap, zFormat);
  61279. vdbeVComment(p, zFormat, ap);
  61280. va_end(ap);
  61281. }
  61282. }
  61283. SQLITE_PRIVATE void sqlite3VdbeNoopComment(Vdbe *p, const char *zFormat, ...){
  61284. va_list ap;
  61285. if( p ){
  61286. sqlite3VdbeAddOp0(p, OP_Noop);
  61287. va_start(ap, zFormat);
  61288. vdbeVComment(p, zFormat, ap);
  61289. va_end(ap);
  61290. }
  61291. }
  61292. #endif /* NDEBUG */
  61293. #ifdef SQLITE_VDBE_COVERAGE
  61294. /*
  61295. ** Set the value if the iSrcLine field for the previously coded instruction.
  61296. */
  61297. SQLITE_PRIVATE void sqlite3VdbeSetLineNumber(Vdbe *v, int iLine){
  61298. sqlite3VdbeGetOp(v,-1)->iSrcLine = iLine;
  61299. }
  61300. #endif /* SQLITE_VDBE_COVERAGE */
  61301. /*
  61302. ** Return the opcode for a given address. If the address is -1, then
  61303. ** return the most recently inserted opcode.
  61304. **
  61305. ** If a memory allocation error has occurred prior to the calling of this
  61306. ** routine, then a pointer to a dummy VdbeOp will be returned. That opcode
  61307. ** is readable but not writable, though it is cast to a writable value.
  61308. ** The return of a dummy opcode allows the call to continue functioning
  61309. ** after an OOM fault without having to check to see if the return from
  61310. ** this routine is a valid pointer. But because the dummy.opcode is 0,
  61311. ** dummy will never be written to. This is verified by code inspection and
  61312. ** by running with Valgrind.
  61313. */
  61314. SQLITE_PRIVATE VdbeOp *sqlite3VdbeGetOp(Vdbe *p, int addr){
  61315. /* C89 specifies that the constant "dummy" will be initialized to all
  61316. ** zeros, which is correct. MSVC generates a warning, nevertheless. */
  61317. static VdbeOp dummy; /* Ignore the MSVC warning about no initializer */
  61318. assert( p->magic==VDBE_MAGIC_INIT );
  61319. if( addr<0 ){
  61320. addr = p->nOp - 1;
  61321. }
  61322. assert( (addr>=0 && addr<p->nOp) || p->db->mallocFailed );
  61323. if( p->db->mallocFailed ){
  61324. return (VdbeOp*)&dummy;
  61325. }else{
  61326. return &p->aOp[addr];
  61327. }
  61328. }
  61329. #if defined(SQLITE_ENABLE_EXPLAIN_COMMENTS)
  61330. /*
  61331. ** Return an integer value for one of the parameters to the opcode pOp
  61332. ** determined by character c.
  61333. */
  61334. static int translateP(char c, const Op *pOp){
  61335. if( c=='1' ) return pOp->p1;
  61336. if( c=='2' ) return pOp->p2;
  61337. if( c=='3' ) return pOp->p3;
  61338. if( c=='4' ) return pOp->p4.i;
  61339. return pOp->p5;
  61340. }
  61341. /*
  61342. ** Compute a string for the "comment" field of a VDBE opcode listing.
  61343. **
  61344. ** The Synopsis: field in comments in the vdbe.c source file gets converted
  61345. ** to an extra string that is appended to the sqlite3OpcodeName(). In the
  61346. ** absence of other comments, this synopsis becomes the comment on the opcode.
  61347. ** Some translation occurs:
  61348. **
  61349. ** "PX" -> "r[X]"
  61350. ** "PX@PY" -> "r[X..X+Y-1]" or "r[x]" if y is 0 or 1
  61351. ** "PX@PY+1" -> "r[X..X+Y]" or "r[x]" if y is 0
  61352. ** "PY..PY" -> "r[X..Y]" or "r[x]" if y<=x
  61353. */
  61354. static int displayComment(
  61355. const Op *pOp, /* The opcode to be commented */
  61356. const char *zP4, /* Previously obtained value for P4 */
  61357. char *zTemp, /* Write result here */
  61358. int nTemp /* Space available in zTemp[] */
  61359. ){
  61360. const char *zOpName;
  61361. const char *zSynopsis;
  61362. int nOpName;
  61363. int ii, jj;
  61364. zOpName = sqlite3OpcodeName(pOp->opcode);
  61365. nOpName = sqlite3Strlen30(zOpName);
  61366. if( zOpName[nOpName+1] ){
  61367. int seenCom = 0;
  61368. char c;
  61369. zSynopsis = zOpName += nOpName + 1;
  61370. for(ii=jj=0; jj<nTemp-1 && (c = zSynopsis[ii])!=0; ii++){
  61371. if( c=='P' ){
  61372. c = zSynopsis[++ii];
  61373. if( c=='4' ){
  61374. sqlite3_snprintf(nTemp-jj, zTemp+jj, "%s", zP4);
  61375. }else if( c=='X' ){
  61376. sqlite3_snprintf(nTemp-jj, zTemp+jj, "%s", pOp->zComment);
  61377. seenCom = 1;
  61378. }else{
  61379. int v1 = translateP(c, pOp);
  61380. int v2;
  61381. sqlite3_snprintf(nTemp-jj, zTemp+jj, "%d", v1);
  61382. if( strncmp(zSynopsis+ii+1, "@P", 2)==0 ){
  61383. ii += 3;
  61384. jj += sqlite3Strlen30(zTemp+jj);
  61385. v2 = translateP(zSynopsis[ii], pOp);
  61386. if( strncmp(zSynopsis+ii+1,"+1",2)==0 ){
  61387. ii += 2;
  61388. v2++;
  61389. }
  61390. if( v2>1 ){
  61391. sqlite3_snprintf(nTemp-jj, zTemp+jj, "..%d", v1+v2-1);
  61392. }
  61393. }else if( strncmp(zSynopsis+ii+1, "..P3", 4)==0 && pOp->p3==0 ){
  61394. ii += 4;
  61395. }
  61396. }
  61397. jj += sqlite3Strlen30(zTemp+jj);
  61398. }else{
  61399. zTemp[jj++] = c;
  61400. }
  61401. }
  61402. if( !seenCom && jj<nTemp-5 && pOp->zComment ){
  61403. sqlite3_snprintf(nTemp-jj, zTemp+jj, "; %s", pOp->zComment);
  61404. jj += sqlite3Strlen30(zTemp+jj);
  61405. }
  61406. if( jj<nTemp ) zTemp[jj] = 0;
  61407. }else if( pOp->zComment ){
  61408. sqlite3_snprintf(nTemp, zTemp, "%s", pOp->zComment);
  61409. jj = sqlite3Strlen30(zTemp);
  61410. }else{
  61411. zTemp[0] = 0;
  61412. jj = 0;
  61413. }
  61414. return jj;
  61415. }
  61416. #endif /* SQLITE_DEBUG */
  61417. #if !defined(SQLITE_OMIT_EXPLAIN) || !defined(NDEBUG) \
  61418. || defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)
  61419. /*
  61420. ** Compute a string that describes the P4 parameter for an opcode.
  61421. ** Use zTemp for any required temporary buffer space.
  61422. */
  61423. static char *displayP4(Op *pOp, char *zTemp, int nTemp){
  61424. char *zP4 = zTemp;
  61425. assert( nTemp>=20 );
  61426. switch( pOp->p4type ){
  61427. case P4_KEYINFO: {
  61428. int i, j;
  61429. KeyInfo *pKeyInfo = pOp->p4.pKeyInfo;
  61430. assert( pKeyInfo->aSortOrder!=0 );
  61431. sqlite3_snprintf(nTemp, zTemp, "k(%d", pKeyInfo->nField);
  61432. i = sqlite3Strlen30(zTemp);
  61433. for(j=0; j<pKeyInfo->nField; j++){
  61434. CollSeq *pColl = pKeyInfo->aColl[j];
  61435. const char *zColl = pColl ? pColl->zName : "nil";
  61436. int n = sqlite3Strlen30(zColl);
  61437. if( n==6 && memcmp(zColl,"BINARY",6)==0 ){
  61438. zColl = "B";
  61439. n = 1;
  61440. }
  61441. if( i+n>nTemp-6 ){
  61442. memcpy(&zTemp[i],",...",4);
  61443. break;
  61444. }
  61445. zTemp[i++] = ',';
  61446. if( pKeyInfo->aSortOrder[j] ){
  61447. zTemp[i++] = '-';
  61448. }
  61449. memcpy(&zTemp[i], zColl, n+1);
  61450. i += n;
  61451. }
  61452. zTemp[i++] = ')';
  61453. zTemp[i] = 0;
  61454. assert( i<nTemp );
  61455. break;
  61456. }
  61457. case P4_COLLSEQ: {
  61458. CollSeq *pColl = pOp->p4.pColl;
  61459. sqlite3_snprintf(nTemp, zTemp, "(%.20s)", pColl->zName);
  61460. break;
  61461. }
  61462. case P4_FUNCDEF: {
  61463. FuncDef *pDef = pOp->p4.pFunc;
  61464. sqlite3_snprintf(nTemp, zTemp, "%s(%d)", pDef->zName, pDef->nArg);
  61465. break;
  61466. }
  61467. case P4_INT64: {
  61468. sqlite3_snprintf(nTemp, zTemp, "%lld", *pOp->p4.pI64);
  61469. break;
  61470. }
  61471. case P4_INT32: {
  61472. sqlite3_snprintf(nTemp, zTemp, "%d", pOp->p4.i);
  61473. break;
  61474. }
  61475. case P4_REAL: {
  61476. sqlite3_snprintf(nTemp, zTemp, "%.16g", *pOp->p4.pReal);
  61477. break;
  61478. }
  61479. case P4_MEM: {
  61480. Mem *pMem = pOp->p4.pMem;
  61481. if( pMem->flags & MEM_Str ){
  61482. zP4 = pMem->z;
  61483. }else if( pMem->flags & MEM_Int ){
  61484. sqlite3_snprintf(nTemp, zTemp, "%lld", pMem->u.i);
  61485. }else if( pMem->flags & MEM_Real ){
  61486. sqlite3_snprintf(nTemp, zTemp, "%.16g", pMem->u.r);
  61487. }else if( pMem->flags & MEM_Null ){
  61488. sqlite3_snprintf(nTemp, zTemp, "NULL");
  61489. }else{
  61490. assert( pMem->flags & MEM_Blob );
  61491. zP4 = "(blob)";
  61492. }
  61493. break;
  61494. }
  61495. #ifndef SQLITE_OMIT_VIRTUALTABLE
  61496. case P4_VTAB: {
  61497. sqlite3_vtab *pVtab = pOp->p4.pVtab->pVtab;
  61498. sqlite3_snprintf(nTemp, zTemp, "vtab:%p", pVtab);
  61499. break;
  61500. }
  61501. #endif
  61502. case P4_INTARRAY: {
  61503. sqlite3_snprintf(nTemp, zTemp, "intarray");
  61504. break;
  61505. }
  61506. case P4_SUBPROGRAM: {
  61507. sqlite3_snprintf(nTemp, zTemp, "program");
  61508. break;
  61509. }
  61510. case P4_ADVANCE: {
  61511. zTemp[0] = 0;
  61512. break;
  61513. }
  61514. default: {
  61515. zP4 = pOp->p4.z;
  61516. if( zP4==0 ){
  61517. zP4 = zTemp;
  61518. zTemp[0] = 0;
  61519. }
  61520. }
  61521. }
  61522. assert( zP4!=0 );
  61523. return zP4;
  61524. }
  61525. #endif
  61526. /*
  61527. ** Declare to the Vdbe that the BTree object at db->aDb[i] is used.
  61528. **
  61529. ** The prepared statements need to know in advance the complete set of
  61530. ** attached databases that will be use. A mask of these databases
  61531. ** is maintained in p->btreeMask. The p->lockMask value is the subset of
  61532. ** p->btreeMask of databases that will require a lock.
  61533. */
  61534. SQLITE_PRIVATE void sqlite3VdbeUsesBtree(Vdbe *p, int i){
  61535. assert( i>=0 && i<p->db->nDb && i<(int)sizeof(yDbMask)*8 );
  61536. assert( i<(int)sizeof(p->btreeMask)*8 );
  61537. DbMaskSet(p->btreeMask, i);
  61538. if( i!=1 && sqlite3BtreeSharable(p->db->aDb[i].pBt) ){
  61539. DbMaskSet(p->lockMask, i);
  61540. }
  61541. }
  61542. #if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE>0
  61543. /*
  61544. ** If SQLite is compiled to support shared-cache mode and to be threadsafe,
  61545. ** this routine obtains the mutex associated with each BtShared structure
  61546. ** that may be accessed by the VM passed as an argument. In doing so it also
  61547. ** sets the BtShared.db member of each of the BtShared structures, ensuring
  61548. ** that the correct busy-handler callback is invoked if required.
  61549. **
  61550. ** If SQLite is not threadsafe but does support shared-cache mode, then
  61551. ** sqlite3BtreeEnter() is invoked to set the BtShared.db variables
  61552. ** of all of BtShared structures accessible via the database handle
  61553. ** associated with the VM.
  61554. **
  61555. ** If SQLite is not threadsafe and does not support shared-cache mode, this
  61556. ** function is a no-op.
  61557. **
  61558. ** The p->btreeMask field is a bitmask of all btrees that the prepared
  61559. ** statement p will ever use. Let N be the number of bits in p->btreeMask
  61560. ** corresponding to btrees that use shared cache. Then the runtime of
  61561. ** this routine is N*N. But as N is rarely more than 1, this should not
  61562. ** be a problem.
  61563. */
  61564. SQLITE_PRIVATE void sqlite3VdbeEnter(Vdbe *p){
  61565. int i;
  61566. sqlite3 *db;
  61567. Db *aDb;
  61568. int nDb;
  61569. if( DbMaskAllZero(p->lockMask) ) return; /* The common case */
  61570. db = p->db;
  61571. aDb = db->aDb;
  61572. nDb = db->nDb;
  61573. for(i=0; i<nDb; i++){
  61574. if( i!=1 && DbMaskTest(p->lockMask,i) && ALWAYS(aDb[i].pBt!=0) ){
  61575. sqlite3BtreeEnter(aDb[i].pBt);
  61576. }
  61577. }
  61578. }
  61579. #endif
  61580. #if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE>0
  61581. /*
  61582. ** Unlock all of the btrees previously locked by a call to sqlite3VdbeEnter().
  61583. */
  61584. SQLITE_PRIVATE void sqlite3VdbeLeave(Vdbe *p){
  61585. int i;
  61586. sqlite3 *db;
  61587. Db *aDb;
  61588. int nDb;
  61589. if( DbMaskAllZero(p->lockMask) ) return; /* The common case */
  61590. db = p->db;
  61591. aDb = db->aDb;
  61592. nDb = db->nDb;
  61593. for(i=0; i<nDb; i++){
  61594. if( i!=1 && DbMaskTest(p->lockMask,i) && ALWAYS(aDb[i].pBt!=0) ){
  61595. sqlite3BtreeLeave(aDb[i].pBt);
  61596. }
  61597. }
  61598. }
  61599. #endif
  61600. #if defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)
  61601. /*
  61602. ** Print a single opcode. This routine is used for debugging only.
  61603. */
  61604. SQLITE_PRIVATE void sqlite3VdbePrintOp(FILE *pOut, int pc, Op *pOp){
  61605. char *zP4;
  61606. char zPtr[50];
  61607. char zCom[100];
  61608. static const char *zFormat1 = "%4d %-13s %4d %4d %4d %-13s %.2X %s\n";
  61609. if( pOut==0 ) pOut = stdout;
  61610. zP4 = displayP4(pOp, zPtr, sizeof(zPtr));
  61611. #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
  61612. displayComment(pOp, zP4, zCom, sizeof(zCom));
  61613. #else
  61614. zCom[0] = 0;
  61615. #endif
  61616. /* NB: The sqlite3OpcodeName() function is implemented by code created
  61617. ** by the mkopcodeh.awk and mkopcodec.awk scripts which extract the
  61618. ** information from the vdbe.c source text */
  61619. fprintf(pOut, zFormat1, pc,
  61620. sqlite3OpcodeName(pOp->opcode), pOp->p1, pOp->p2, pOp->p3, zP4, pOp->p5,
  61621. zCom
  61622. );
  61623. fflush(pOut);
  61624. }
  61625. #endif
  61626. /*
  61627. ** Release an array of N Mem elements
  61628. */
  61629. static void releaseMemArray(Mem *p, int N){
  61630. if( p && N ){
  61631. Mem *pEnd = &p[N];
  61632. sqlite3 *db = p->db;
  61633. u8 malloc_failed = db->mallocFailed;
  61634. if( db->pnBytesFreed ){
  61635. do{
  61636. if( p->szMalloc ) sqlite3DbFree(db, p->zMalloc);
  61637. }while( (++p)<pEnd );
  61638. return;
  61639. }
  61640. do{
  61641. assert( (&p[1])==pEnd || p[0].db==p[1].db );
  61642. assert( sqlite3VdbeCheckMemInvariants(p) );
  61643. /* This block is really an inlined version of sqlite3VdbeMemRelease()
  61644. ** that takes advantage of the fact that the memory cell value is
  61645. ** being set to NULL after releasing any dynamic resources.
  61646. **
  61647. ** The justification for duplicating code is that according to
  61648. ** callgrind, this causes a certain test case to hit the CPU 4.7
  61649. ** percent less (x86 linux, gcc version 4.1.2, -O6) than if
  61650. ** sqlite3MemRelease() were called from here. With -O2, this jumps
  61651. ** to 6.6 percent. The test case is inserting 1000 rows into a table
  61652. ** with no indexes using a single prepared INSERT statement, bind()
  61653. ** and reset(). Inserts are grouped into a transaction.
  61654. */
  61655. testcase( p->flags & MEM_Agg );
  61656. testcase( p->flags & MEM_Dyn );
  61657. testcase( p->flags & MEM_Frame );
  61658. testcase( p->flags & MEM_RowSet );
  61659. if( p->flags&(MEM_Agg|MEM_Dyn|MEM_Frame|MEM_RowSet) ){
  61660. sqlite3VdbeMemRelease(p);
  61661. }else if( p->szMalloc ){
  61662. sqlite3DbFree(db, p->zMalloc);
  61663. p->szMalloc = 0;
  61664. }
  61665. p->flags = MEM_Undefined;
  61666. }while( (++p)<pEnd );
  61667. db->mallocFailed = malloc_failed;
  61668. }
  61669. }
  61670. /*
  61671. ** Delete a VdbeFrame object and its contents. VdbeFrame objects are
  61672. ** allocated by the OP_Program opcode in sqlite3VdbeExec().
  61673. */
  61674. SQLITE_PRIVATE void sqlite3VdbeFrameDelete(VdbeFrame *p){
  61675. int i;
  61676. Mem *aMem = VdbeFrameMem(p);
  61677. VdbeCursor **apCsr = (VdbeCursor **)&aMem[p->nChildMem];
  61678. for(i=0; i<p->nChildCsr; i++){
  61679. sqlite3VdbeFreeCursor(p->v, apCsr[i]);
  61680. }
  61681. releaseMemArray(aMem, p->nChildMem);
  61682. sqlite3DbFree(p->v->db, p);
  61683. }
  61684. #ifndef SQLITE_OMIT_EXPLAIN
  61685. /*
  61686. ** Give a listing of the program in the virtual machine.
  61687. **
  61688. ** The interface is the same as sqlite3VdbeExec(). But instead of
  61689. ** running the code, it invokes the callback once for each instruction.
  61690. ** This feature is used to implement "EXPLAIN".
  61691. **
  61692. ** When p->explain==1, each instruction is listed. When
  61693. ** p->explain==2, only OP_Explain instructions are listed and these
  61694. ** are shown in a different format. p->explain==2 is used to implement
  61695. ** EXPLAIN QUERY PLAN.
  61696. **
  61697. ** When p->explain==1, first the main program is listed, then each of
  61698. ** the trigger subprograms are listed one by one.
  61699. */
  61700. SQLITE_PRIVATE int sqlite3VdbeList(
  61701. Vdbe *p /* The VDBE */
  61702. ){
  61703. int nRow; /* Stop when row count reaches this */
  61704. int nSub = 0; /* Number of sub-vdbes seen so far */
  61705. SubProgram **apSub = 0; /* Array of sub-vdbes */
  61706. Mem *pSub = 0; /* Memory cell hold array of subprogs */
  61707. sqlite3 *db = p->db; /* The database connection */
  61708. int i; /* Loop counter */
  61709. int rc = SQLITE_OK; /* Return code */
  61710. Mem *pMem = &p->aMem[1]; /* First Mem of result set */
  61711. assert( p->explain );
  61712. assert( p->magic==VDBE_MAGIC_RUN );
  61713. assert( p->rc==SQLITE_OK || p->rc==SQLITE_BUSY || p->rc==SQLITE_NOMEM );
  61714. /* Even though this opcode does not use dynamic strings for
  61715. ** the result, result columns may become dynamic if the user calls
  61716. ** sqlite3_column_text16(), causing a translation to UTF-16 encoding.
  61717. */
  61718. releaseMemArray(pMem, 8);
  61719. p->pResultSet = 0;
  61720. if( p->rc==SQLITE_NOMEM ){
  61721. /* This happens if a malloc() inside a call to sqlite3_column_text() or
  61722. ** sqlite3_column_text16() failed. */
  61723. db->mallocFailed = 1;
  61724. return SQLITE_ERROR;
  61725. }
  61726. /* When the number of output rows reaches nRow, that means the
  61727. ** listing has finished and sqlite3_step() should return SQLITE_DONE.
  61728. ** nRow is the sum of the number of rows in the main program, plus
  61729. ** the sum of the number of rows in all trigger subprograms encountered
  61730. ** so far. The nRow value will increase as new trigger subprograms are
  61731. ** encountered, but p->pc will eventually catch up to nRow.
  61732. */
  61733. nRow = p->nOp;
  61734. if( p->explain==1 ){
  61735. /* The first 8 memory cells are used for the result set. So we will
  61736. ** commandeer the 9th cell to use as storage for an array of pointers
  61737. ** to trigger subprograms. The VDBE is guaranteed to have at least 9
  61738. ** cells. */
  61739. assert( p->nMem>9 );
  61740. pSub = &p->aMem[9];
  61741. if( pSub->flags&MEM_Blob ){
  61742. /* On the first call to sqlite3_step(), pSub will hold a NULL. It is
  61743. ** initialized to a BLOB by the P4_SUBPROGRAM processing logic below */
  61744. nSub = pSub->n/sizeof(Vdbe*);
  61745. apSub = (SubProgram **)pSub->z;
  61746. }
  61747. for(i=0; i<nSub; i++){
  61748. nRow += apSub[i]->nOp;
  61749. }
  61750. }
  61751. do{
  61752. i = p->pc++;
  61753. }while( i<nRow && p->explain==2 && p->aOp[i].opcode!=OP_Explain );
  61754. if( i>=nRow ){
  61755. p->rc = SQLITE_OK;
  61756. rc = SQLITE_DONE;
  61757. }else if( db->u1.isInterrupted ){
  61758. p->rc = SQLITE_INTERRUPT;
  61759. rc = SQLITE_ERROR;
  61760. sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3ErrStr(p->rc));
  61761. }else{
  61762. char *zP4;
  61763. Op *pOp;
  61764. if( i<p->nOp ){
  61765. /* The output line number is small enough that we are still in the
  61766. ** main program. */
  61767. pOp = &p->aOp[i];
  61768. }else{
  61769. /* We are currently listing subprograms. Figure out which one and
  61770. ** pick up the appropriate opcode. */
  61771. int j;
  61772. i -= p->nOp;
  61773. for(j=0; i>=apSub[j]->nOp; j++){
  61774. i -= apSub[j]->nOp;
  61775. }
  61776. pOp = &apSub[j]->aOp[i];
  61777. }
  61778. if( p->explain==1 ){
  61779. pMem->flags = MEM_Int;
  61780. pMem->u.i = i; /* Program counter */
  61781. pMem++;
  61782. pMem->flags = MEM_Static|MEM_Str|MEM_Term;
  61783. pMem->z = (char*)sqlite3OpcodeName(pOp->opcode); /* Opcode */
  61784. assert( pMem->z!=0 );
  61785. pMem->n = sqlite3Strlen30(pMem->z);
  61786. pMem->enc = SQLITE_UTF8;
  61787. pMem++;
  61788. /* When an OP_Program opcode is encounter (the only opcode that has
  61789. ** a P4_SUBPROGRAM argument), expand the size of the array of subprograms
  61790. ** kept in p->aMem[9].z to hold the new program - assuming this subprogram
  61791. ** has not already been seen.
  61792. */
  61793. if( pOp->p4type==P4_SUBPROGRAM ){
  61794. int nByte = (nSub+1)*sizeof(SubProgram*);
  61795. int j;
  61796. for(j=0; j<nSub; j++){
  61797. if( apSub[j]==pOp->p4.pProgram ) break;
  61798. }
  61799. if( j==nSub && SQLITE_OK==sqlite3VdbeMemGrow(pSub, nByte, nSub!=0) ){
  61800. apSub = (SubProgram **)pSub->z;
  61801. apSub[nSub++] = pOp->p4.pProgram;
  61802. pSub->flags |= MEM_Blob;
  61803. pSub->n = nSub*sizeof(SubProgram*);
  61804. }
  61805. }
  61806. }
  61807. pMem->flags = MEM_Int;
  61808. pMem->u.i = pOp->p1; /* P1 */
  61809. pMem++;
  61810. pMem->flags = MEM_Int;
  61811. pMem->u.i = pOp->p2; /* P2 */
  61812. pMem++;
  61813. pMem->flags = MEM_Int;
  61814. pMem->u.i = pOp->p3; /* P3 */
  61815. pMem++;
  61816. if( sqlite3VdbeMemClearAndResize(pMem, 32) ){ /* P4 */
  61817. assert( p->db->mallocFailed );
  61818. return SQLITE_ERROR;
  61819. }
  61820. pMem->flags = MEM_Str|MEM_Term;
  61821. zP4 = displayP4(pOp, pMem->z, 32);
  61822. if( zP4!=pMem->z ){
  61823. sqlite3VdbeMemSetStr(pMem, zP4, -1, SQLITE_UTF8, 0);
  61824. }else{
  61825. assert( pMem->z!=0 );
  61826. pMem->n = sqlite3Strlen30(pMem->z);
  61827. pMem->enc = SQLITE_UTF8;
  61828. }
  61829. pMem++;
  61830. if( p->explain==1 ){
  61831. if( sqlite3VdbeMemClearAndResize(pMem, 4) ){
  61832. assert( p->db->mallocFailed );
  61833. return SQLITE_ERROR;
  61834. }
  61835. pMem->flags = MEM_Str|MEM_Term;
  61836. pMem->n = 2;
  61837. sqlite3_snprintf(3, pMem->z, "%.2x", pOp->p5); /* P5 */
  61838. pMem->enc = SQLITE_UTF8;
  61839. pMem++;
  61840. #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
  61841. if( sqlite3VdbeMemClearAndResize(pMem, 500) ){
  61842. assert( p->db->mallocFailed );
  61843. return SQLITE_ERROR;
  61844. }
  61845. pMem->flags = MEM_Str|MEM_Term;
  61846. pMem->n = displayComment(pOp, zP4, pMem->z, 500);
  61847. pMem->enc = SQLITE_UTF8;
  61848. #else
  61849. pMem->flags = MEM_Null; /* Comment */
  61850. #endif
  61851. }
  61852. p->nResColumn = 8 - 4*(p->explain-1);
  61853. p->pResultSet = &p->aMem[1];
  61854. p->rc = SQLITE_OK;
  61855. rc = SQLITE_ROW;
  61856. }
  61857. return rc;
  61858. }
  61859. #endif /* SQLITE_OMIT_EXPLAIN */
  61860. #ifdef SQLITE_DEBUG
  61861. /*
  61862. ** Print the SQL that was used to generate a VDBE program.
  61863. */
  61864. SQLITE_PRIVATE void sqlite3VdbePrintSql(Vdbe *p){
  61865. const char *z = 0;
  61866. if( p->zSql ){
  61867. z = p->zSql;
  61868. }else if( p->nOp>=1 ){
  61869. const VdbeOp *pOp = &p->aOp[0];
  61870. if( pOp->opcode==OP_Init && pOp->p4.z!=0 ){
  61871. z = pOp->p4.z;
  61872. while( sqlite3Isspace(*z) ) z++;
  61873. }
  61874. }
  61875. if( z ) printf("SQL: [%s]\n", z);
  61876. }
  61877. #endif
  61878. #if !defined(SQLITE_OMIT_TRACE) && defined(SQLITE_ENABLE_IOTRACE)
  61879. /*
  61880. ** Print an IOTRACE message showing SQL content.
  61881. */
  61882. SQLITE_PRIVATE void sqlite3VdbeIOTraceSql(Vdbe *p){
  61883. int nOp = p->nOp;
  61884. VdbeOp *pOp;
  61885. if( sqlite3IoTrace==0 ) return;
  61886. if( nOp<1 ) return;
  61887. pOp = &p->aOp[0];
  61888. if( pOp->opcode==OP_Init && pOp->p4.z!=0 ){
  61889. int i, j;
  61890. char z[1000];
  61891. sqlite3_snprintf(sizeof(z), z, "%s", pOp->p4.z);
  61892. for(i=0; sqlite3Isspace(z[i]); i++){}
  61893. for(j=0; z[i]; i++){
  61894. if( sqlite3Isspace(z[i]) ){
  61895. if( z[i-1]!=' ' ){
  61896. z[j++] = ' ';
  61897. }
  61898. }else{
  61899. z[j++] = z[i];
  61900. }
  61901. }
  61902. z[j] = 0;
  61903. sqlite3IoTrace("SQL %s\n", z);
  61904. }
  61905. }
  61906. #endif /* !SQLITE_OMIT_TRACE && SQLITE_ENABLE_IOTRACE */
  61907. /*
  61908. ** Allocate space from a fixed size buffer and return a pointer to
  61909. ** that space. If insufficient space is available, return NULL.
  61910. **
  61911. ** The pBuf parameter is the initial value of a pointer which will
  61912. ** receive the new memory. pBuf is normally NULL. If pBuf is not
  61913. ** NULL, it means that memory space has already been allocated and that
  61914. ** this routine should not allocate any new memory. When pBuf is not
  61915. ** NULL simply return pBuf. Only allocate new memory space when pBuf
  61916. ** is NULL.
  61917. **
  61918. ** nByte is the number of bytes of space needed.
  61919. **
  61920. ** *ppFrom points to available space and pEnd points to the end of the
  61921. ** available space. When space is allocated, *ppFrom is advanced past
  61922. ** the end of the allocated space.
  61923. **
  61924. ** *pnByte is a counter of the number of bytes of space that have failed
  61925. ** to allocate. If there is insufficient space in *ppFrom to satisfy the
  61926. ** request, then increment *pnByte by the amount of the request.
  61927. */
  61928. static void *allocSpace(
  61929. void *pBuf, /* Where return pointer will be stored */
  61930. int nByte, /* Number of bytes to allocate */
  61931. u8 **ppFrom, /* IN/OUT: Allocate from *ppFrom */
  61932. u8 *pEnd, /* Pointer to 1 byte past the end of *ppFrom buffer */
  61933. int *pnByte /* If allocation cannot be made, increment *pnByte */
  61934. ){
  61935. assert( EIGHT_BYTE_ALIGNMENT(*ppFrom) );
  61936. if( pBuf ) return pBuf;
  61937. nByte = ROUND8(nByte);
  61938. if( &(*ppFrom)[nByte] <= pEnd ){
  61939. pBuf = (void*)*ppFrom;
  61940. *ppFrom += nByte;
  61941. }else{
  61942. *pnByte += nByte;
  61943. }
  61944. return pBuf;
  61945. }
  61946. /*
  61947. ** Rewind the VDBE back to the beginning in preparation for
  61948. ** running it.
  61949. */
  61950. SQLITE_PRIVATE void sqlite3VdbeRewind(Vdbe *p){
  61951. #if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE)
  61952. int i;
  61953. #endif
  61954. assert( p!=0 );
  61955. assert( p->magic==VDBE_MAGIC_INIT );
  61956. /* There should be at least one opcode.
  61957. */
  61958. assert( p->nOp>0 );
  61959. /* Set the magic to VDBE_MAGIC_RUN sooner rather than later. */
  61960. p->magic = VDBE_MAGIC_RUN;
  61961. #ifdef SQLITE_DEBUG
  61962. for(i=1; i<p->nMem; i++){
  61963. assert( p->aMem[i].db==p->db );
  61964. }
  61965. #endif
  61966. p->pc = -1;
  61967. p->rc = SQLITE_OK;
  61968. p->errorAction = OE_Abort;
  61969. p->magic = VDBE_MAGIC_RUN;
  61970. p->nChange = 0;
  61971. p->cacheCtr = 1;
  61972. p->minWriteFileFormat = 255;
  61973. p->iStatement = 0;
  61974. p->nFkConstraint = 0;
  61975. #ifdef VDBE_PROFILE
  61976. for(i=0; i<p->nOp; i++){
  61977. p->aOp[i].cnt = 0;
  61978. p->aOp[i].cycles = 0;
  61979. }
  61980. #endif
  61981. }
  61982. /*
  61983. ** Prepare a virtual machine for execution for the first time after
  61984. ** creating the virtual machine. This involves things such
  61985. ** as allocating registers and initializing the program counter.
  61986. ** After the VDBE has be prepped, it can be executed by one or more
  61987. ** calls to sqlite3VdbeExec().
  61988. **
  61989. ** This function may be called exactly once on each virtual machine.
  61990. ** After this routine is called the VM has been "packaged" and is ready
  61991. ** to run. After this routine is called, further calls to
  61992. ** sqlite3VdbeAddOp() functions are prohibited. This routine disconnects
  61993. ** the Vdbe from the Parse object that helped generate it so that the
  61994. ** the Vdbe becomes an independent entity and the Parse object can be
  61995. ** destroyed.
  61996. **
  61997. ** Use the sqlite3VdbeRewind() procedure to restore a virtual machine back
  61998. ** to its initial state after it has been run.
  61999. */
  62000. SQLITE_PRIVATE void sqlite3VdbeMakeReady(
  62001. Vdbe *p, /* The VDBE */
  62002. Parse *pParse /* Parsing context */
  62003. ){
  62004. sqlite3 *db; /* The database connection */
  62005. int nVar; /* Number of parameters */
  62006. int nMem; /* Number of VM memory registers */
  62007. int nCursor; /* Number of cursors required */
  62008. int nArg; /* Number of arguments in subprograms */
  62009. int nOnce; /* Number of OP_Once instructions */
  62010. int n; /* Loop counter */
  62011. u8 *zCsr; /* Memory available for allocation */
  62012. u8 *zEnd; /* First byte past allocated memory */
  62013. int nByte; /* How much extra memory is needed */
  62014. assert( p!=0 );
  62015. assert( p->nOp>0 );
  62016. assert( pParse!=0 );
  62017. assert( p->magic==VDBE_MAGIC_INIT );
  62018. assert( pParse==p->pParse );
  62019. db = p->db;
  62020. assert( db->mallocFailed==0 );
  62021. nVar = pParse->nVar;
  62022. nMem = pParse->nMem;
  62023. nCursor = pParse->nTab;
  62024. nArg = pParse->nMaxArg;
  62025. nOnce = pParse->nOnce;
  62026. if( nOnce==0 ) nOnce = 1; /* Ensure at least one byte in p->aOnceFlag[] */
  62027. /* For each cursor required, also allocate a memory cell. Memory
  62028. ** cells (nMem+1-nCursor)..nMem, inclusive, will never be used by
  62029. ** the vdbe program. Instead they are used to allocate space for
  62030. ** VdbeCursor/BtCursor structures. The blob of memory associated with
  62031. ** cursor 0 is stored in memory cell nMem. Memory cell (nMem-1)
  62032. ** stores the blob of memory associated with cursor 1, etc.
  62033. **
  62034. ** See also: allocateCursor().
  62035. */
  62036. nMem += nCursor;
  62037. /* Allocate space for memory registers, SQL variables, VDBE cursors and
  62038. ** an array to marshal SQL function arguments in.
  62039. */
  62040. zCsr = (u8*)&p->aOp[p->nOp]; /* Memory avaliable for allocation */
  62041. zEnd = (u8*)&p->aOp[pParse->nOpAlloc]; /* First byte past end of zCsr[] */
  62042. resolveP2Values(p, &nArg);
  62043. p->usesStmtJournal = (u8)(pParse->isMultiWrite && pParse->mayAbort);
  62044. if( pParse->explain && nMem<10 ){
  62045. nMem = 10;
  62046. }
  62047. memset(zCsr, 0, zEnd-zCsr);
  62048. zCsr += (zCsr - (u8*)0)&7;
  62049. assert( EIGHT_BYTE_ALIGNMENT(zCsr) );
  62050. p->expired = 0;
  62051. /* Memory for registers, parameters, cursor, etc, is allocated in two
  62052. ** passes. On the first pass, we try to reuse unused space at the
  62053. ** end of the opcode array. If we are unable to satisfy all memory
  62054. ** requirements by reusing the opcode array tail, then the second
  62055. ** pass will fill in the rest using a fresh allocation.
  62056. **
  62057. ** This two-pass approach that reuses as much memory as possible from
  62058. ** the leftover space at the end of the opcode array can significantly
  62059. ** reduce the amount of memory held by a prepared statement.
  62060. */
  62061. do {
  62062. nByte = 0;
  62063. p->aMem = allocSpace(p->aMem, nMem*sizeof(Mem), &zCsr, zEnd, &nByte);
  62064. p->aVar = allocSpace(p->aVar, nVar*sizeof(Mem), &zCsr, zEnd, &nByte);
  62065. p->apArg = allocSpace(p->apArg, nArg*sizeof(Mem*), &zCsr, zEnd, &nByte);
  62066. p->azVar = allocSpace(p->azVar, nVar*sizeof(char*), &zCsr, zEnd, &nByte);
  62067. p->apCsr = allocSpace(p->apCsr, nCursor*sizeof(VdbeCursor*),
  62068. &zCsr, zEnd, &nByte);
  62069. p->aOnceFlag = allocSpace(p->aOnceFlag, nOnce, &zCsr, zEnd, &nByte);
  62070. #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
  62071. p->anExec = allocSpace(p->anExec, p->nOp*sizeof(i64), &zCsr, zEnd, &nByte);
  62072. #endif
  62073. if( nByte ){
  62074. p->pFree = sqlite3DbMallocZero(db, nByte);
  62075. }
  62076. zCsr = p->pFree;
  62077. zEnd = &zCsr[nByte];
  62078. }while( nByte && !db->mallocFailed );
  62079. p->nCursor = nCursor;
  62080. p->nOnceFlag = nOnce;
  62081. if( p->aVar ){
  62082. p->nVar = (ynVar)nVar;
  62083. for(n=0; n<nVar; n++){
  62084. p->aVar[n].flags = MEM_Null;
  62085. p->aVar[n].db = db;
  62086. }
  62087. }
  62088. if( p->azVar && pParse->nzVar>0 ){
  62089. p->nzVar = pParse->nzVar;
  62090. memcpy(p->azVar, pParse->azVar, p->nzVar*sizeof(p->azVar[0]));
  62091. memset(pParse->azVar, 0, pParse->nzVar*sizeof(pParse->azVar[0]));
  62092. }
  62093. if( p->aMem ){
  62094. p->aMem--; /* aMem[] goes from 1..nMem */
  62095. p->nMem = nMem; /* not from 0..nMem-1 */
  62096. for(n=1; n<=nMem; n++){
  62097. p->aMem[n].flags = MEM_Undefined;
  62098. p->aMem[n].db = db;
  62099. }
  62100. }
  62101. p->explain = pParse->explain;
  62102. sqlite3VdbeRewind(p);
  62103. }
  62104. /*
  62105. ** Close a VDBE cursor and release all the resources that cursor
  62106. ** happens to hold.
  62107. */
  62108. SQLITE_PRIVATE void sqlite3VdbeFreeCursor(Vdbe *p, VdbeCursor *pCx){
  62109. if( pCx==0 ){
  62110. return;
  62111. }
  62112. sqlite3VdbeSorterClose(p->db, pCx);
  62113. if( pCx->pBt ){
  62114. sqlite3BtreeClose(pCx->pBt);
  62115. /* The pCx->pCursor will be close automatically, if it exists, by
  62116. ** the call above. */
  62117. }else if( pCx->pCursor ){
  62118. sqlite3BtreeCloseCursor(pCx->pCursor);
  62119. }
  62120. #ifndef SQLITE_OMIT_VIRTUALTABLE
  62121. else if( pCx->pVtabCursor ){
  62122. sqlite3_vtab_cursor *pVtabCursor = pCx->pVtabCursor;
  62123. const sqlite3_module *pModule = pVtabCursor->pVtab->pModule;
  62124. assert( pVtabCursor->pVtab->nRef>0 );
  62125. pVtabCursor->pVtab->nRef--;
  62126. pModule->xClose(pVtabCursor);
  62127. }
  62128. #endif
  62129. }
  62130. /*
  62131. ** Close all cursors in the current frame.
  62132. */
  62133. static void closeCursorsInFrame(Vdbe *p){
  62134. if( p->apCsr ){
  62135. int i;
  62136. for(i=0; i<p->nCursor; i++){
  62137. VdbeCursor *pC = p->apCsr[i];
  62138. if( pC ){
  62139. sqlite3VdbeFreeCursor(p, pC);
  62140. p->apCsr[i] = 0;
  62141. }
  62142. }
  62143. }
  62144. }
  62145. /*
  62146. ** Copy the values stored in the VdbeFrame structure to its Vdbe. This
  62147. ** is used, for example, when a trigger sub-program is halted to restore
  62148. ** control to the main program.
  62149. */
  62150. SQLITE_PRIVATE int sqlite3VdbeFrameRestore(VdbeFrame *pFrame){
  62151. Vdbe *v = pFrame->v;
  62152. closeCursorsInFrame(v);
  62153. #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
  62154. v->anExec = pFrame->anExec;
  62155. #endif
  62156. v->aOnceFlag = pFrame->aOnceFlag;
  62157. v->nOnceFlag = pFrame->nOnceFlag;
  62158. v->aOp = pFrame->aOp;
  62159. v->nOp = pFrame->nOp;
  62160. v->aMem = pFrame->aMem;
  62161. v->nMem = pFrame->nMem;
  62162. v->apCsr = pFrame->apCsr;
  62163. v->nCursor = pFrame->nCursor;
  62164. v->db->lastRowid = pFrame->lastRowid;
  62165. v->nChange = pFrame->nChange;
  62166. v->db->nChange = pFrame->nDbChange;
  62167. return pFrame->pc;
  62168. }
  62169. /*
  62170. ** Close all cursors.
  62171. **
  62172. ** Also release any dynamic memory held by the VM in the Vdbe.aMem memory
  62173. ** cell array. This is necessary as the memory cell array may contain
  62174. ** pointers to VdbeFrame objects, which may in turn contain pointers to
  62175. ** open cursors.
  62176. */
  62177. static void closeAllCursors(Vdbe *p){
  62178. if( p->pFrame ){
  62179. VdbeFrame *pFrame;
  62180. for(pFrame=p->pFrame; pFrame->pParent; pFrame=pFrame->pParent);
  62181. sqlite3VdbeFrameRestore(pFrame);
  62182. p->pFrame = 0;
  62183. p->nFrame = 0;
  62184. }
  62185. assert( p->nFrame==0 );
  62186. closeCursorsInFrame(p);
  62187. if( p->aMem ){
  62188. releaseMemArray(&p->aMem[1], p->nMem);
  62189. }
  62190. while( p->pDelFrame ){
  62191. VdbeFrame *pDel = p->pDelFrame;
  62192. p->pDelFrame = pDel->pParent;
  62193. sqlite3VdbeFrameDelete(pDel);
  62194. }
  62195. /* Delete any auxdata allocations made by the VM */
  62196. if( p->pAuxData ) sqlite3VdbeDeleteAuxData(p, -1, 0);
  62197. assert( p->pAuxData==0 );
  62198. }
  62199. /*
  62200. ** Clean up the VM after a single run.
  62201. */
  62202. static void Cleanup(Vdbe *p){
  62203. sqlite3 *db = p->db;
  62204. #ifdef SQLITE_DEBUG
  62205. /* Execute assert() statements to ensure that the Vdbe.apCsr[] and
  62206. ** Vdbe.aMem[] arrays have already been cleaned up. */
  62207. int i;
  62208. if( p->apCsr ) for(i=0; i<p->nCursor; i++) assert( p->apCsr[i]==0 );
  62209. if( p->aMem ){
  62210. for(i=1; i<=p->nMem; i++) assert( p->aMem[i].flags==MEM_Undefined );
  62211. }
  62212. #endif
  62213. sqlite3DbFree(db, p->zErrMsg);
  62214. p->zErrMsg = 0;
  62215. p->pResultSet = 0;
  62216. }
  62217. /*
  62218. ** Set the number of result columns that will be returned by this SQL
  62219. ** statement. This is now set at compile time, rather than during
  62220. ** execution of the vdbe program so that sqlite3_column_count() can
  62221. ** be called on an SQL statement before sqlite3_step().
  62222. */
  62223. SQLITE_PRIVATE void sqlite3VdbeSetNumCols(Vdbe *p, int nResColumn){
  62224. Mem *pColName;
  62225. int n;
  62226. sqlite3 *db = p->db;
  62227. releaseMemArray(p->aColName, p->nResColumn*COLNAME_N);
  62228. sqlite3DbFree(db, p->aColName);
  62229. n = nResColumn*COLNAME_N;
  62230. p->nResColumn = (u16)nResColumn;
  62231. p->aColName = pColName = (Mem*)sqlite3DbMallocZero(db, sizeof(Mem)*n );
  62232. if( p->aColName==0 ) return;
  62233. while( n-- > 0 ){
  62234. pColName->flags = MEM_Null;
  62235. pColName->db = p->db;
  62236. pColName++;
  62237. }
  62238. }
  62239. /*
  62240. ** Set the name of the idx'th column to be returned by the SQL statement.
  62241. ** zName must be a pointer to a nul terminated string.
  62242. **
  62243. ** This call must be made after a call to sqlite3VdbeSetNumCols().
  62244. **
  62245. ** The final parameter, xDel, must be one of SQLITE_DYNAMIC, SQLITE_STATIC
  62246. ** or SQLITE_TRANSIENT. If it is SQLITE_DYNAMIC, then the buffer pointed
  62247. ** to by zName will be freed by sqlite3DbFree() when the vdbe is destroyed.
  62248. */
  62249. SQLITE_PRIVATE int sqlite3VdbeSetColName(
  62250. Vdbe *p, /* Vdbe being configured */
  62251. int idx, /* Index of column zName applies to */
  62252. int var, /* One of the COLNAME_* constants */
  62253. const char *zName, /* Pointer to buffer containing name */
  62254. void (*xDel)(void*) /* Memory management strategy for zName */
  62255. ){
  62256. int rc;
  62257. Mem *pColName;
  62258. assert( idx<p->nResColumn );
  62259. assert( var<COLNAME_N );
  62260. if( p->db->mallocFailed ){
  62261. assert( !zName || xDel!=SQLITE_DYNAMIC );
  62262. return SQLITE_NOMEM;
  62263. }
  62264. assert( p->aColName!=0 );
  62265. pColName = &(p->aColName[idx+var*p->nResColumn]);
  62266. rc = sqlite3VdbeMemSetStr(pColName, zName, -1, SQLITE_UTF8, xDel);
  62267. assert( rc!=0 || !zName || (pColName->flags&MEM_Term)!=0 );
  62268. return rc;
  62269. }
  62270. /*
  62271. ** A read or write transaction may or may not be active on database handle
  62272. ** db. If a transaction is active, commit it. If there is a
  62273. ** write-transaction spanning more than one database file, this routine
  62274. ** takes care of the master journal trickery.
  62275. */
  62276. static int vdbeCommit(sqlite3 *db, Vdbe *p){
  62277. int i;
  62278. int nTrans = 0; /* Number of databases with an active write-transaction */
  62279. int rc = SQLITE_OK;
  62280. int needXcommit = 0;
  62281. #ifdef SQLITE_OMIT_VIRTUALTABLE
  62282. /* With this option, sqlite3VtabSync() is defined to be simply
  62283. ** SQLITE_OK so p is not used.
  62284. */
  62285. UNUSED_PARAMETER(p);
  62286. #endif
  62287. /* Before doing anything else, call the xSync() callback for any
  62288. ** virtual module tables written in this transaction. This has to
  62289. ** be done before determining whether a master journal file is
  62290. ** required, as an xSync() callback may add an attached database
  62291. ** to the transaction.
  62292. */
  62293. rc = sqlite3VtabSync(db, p);
  62294. /* This loop determines (a) if the commit hook should be invoked and
  62295. ** (b) how many database files have open write transactions, not
  62296. ** including the temp database. (b) is important because if more than
  62297. ** one database file has an open write transaction, a master journal
  62298. ** file is required for an atomic commit.
  62299. */
  62300. for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
  62301. Btree *pBt = db->aDb[i].pBt;
  62302. if( sqlite3BtreeIsInTrans(pBt) ){
  62303. needXcommit = 1;
  62304. if( i!=1 ) nTrans++;
  62305. sqlite3BtreeEnter(pBt);
  62306. rc = sqlite3PagerExclusiveLock(sqlite3BtreePager(pBt));
  62307. sqlite3BtreeLeave(pBt);
  62308. }
  62309. }
  62310. if( rc!=SQLITE_OK ){
  62311. return rc;
  62312. }
  62313. /* If there are any write-transactions at all, invoke the commit hook */
  62314. if( needXcommit && db->xCommitCallback ){
  62315. rc = db->xCommitCallback(db->pCommitArg);
  62316. if( rc ){
  62317. return SQLITE_CONSTRAINT_COMMITHOOK;
  62318. }
  62319. }
  62320. /* The simple case - no more than one database file (not counting the
  62321. ** TEMP database) has a transaction active. There is no need for the
  62322. ** master-journal.
  62323. **
  62324. ** If the return value of sqlite3BtreeGetFilename() is a zero length
  62325. ** string, it means the main database is :memory: or a temp file. In
  62326. ** that case we do not support atomic multi-file commits, so use the
  62327. ** simple case then too.
  62328. */
  62329. if( 0==sqlite3Strlen30(sqlite3BtreeGetFilename(db->aDb[0].pBt))
  62330. || nTrans<=1
  62331. ){
  62332. for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
  62333. Btree *pBt = db->aDb[i].pBt;
  62334. if( pBt ){
  62335. rc = sqlite3BtreeCommitPhaseOne(pBt, 0);
  62336. }
  62337. }
  62338. /* Do the commit only if all databases successfully complete phase 1.
  62339. ** If one of the BtreeCommitPhaseOne() calls fails, this indicates an
  62340. ** IO error while deleting or truncating a journal file. It is unlikely,
  62341. ** but could happen. In this case abandon processing and return the error.
  62342. */
  62343. for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
  62344. Btree *pBt = db->aDb[i].pBt;
  62345. if( pBt ){
  62346. rc = sqlite3BtreeCommitPhaseTwo(pBt, 0);
  62347. }
  62348. }
  62349. if( rc==SQLITE_OK ){
  62350. sqlite3VtabCommit(db);
  62351. }
  62352. }
  62353. /* The complex case - There is a multi-file write-transaction active.
  62354. ** This requires a master journal file to ensure the transaction is
  62355. ** committed atomically.
  62356. */
  62357. #ifndef SQLITE_OMIT_DISKIO
  62358. else{
  62359. sqlite3_vfs *pVfs = db->pVfs;
  62360. int needSync = 0;
  62361. char *zMaster = 0; /* File-name for the master journal */
  62362. char const *zMainFile = sqlite3BtreeGetFilename(db->aDb[0].pBt);
  62363. sqlite3_file *pMaster = 0;
  62364. i64 offset = 0;
  62365. int res;
  62366. int retryCount = 0;
  62367. int nMainFile;
  62368. /* Select a master journal file name */
  62369. nMainFile = sqlite3Strlen30(zMainFile);
  62370. zMaster = sqlite3MPrintf(db, "%s-mjXXXXXX9XXz", zMainFile);
  62371. if( zMaster==0 ) return SQLITE_NOMEM;
  62372. do {
  62373. u32 iRandom;
  62374. if( retryCount ){
  62375. if( retryCount>100 ){
  62376. sqlite3_log(SQLITE_FULL, "MJ delete: %s", zMaster);
  62377. sqlite3OsDelete(pVfs, zMaster, 0);
  62378. break;
  62379. }else if( retryCount==1 ){
  62380. sqlite3_log(SQLITE_FULL, "MJ collide: %s", zMaster);
  62381. }
  62382. }
  62383. retryCount++;
  62384. sqlite3_randomness(sizeof(iRandom), &iRandom);
  62385. sqlite3_snprintf(13, &zMaster[nMainFile], "-mj%06X9%02X",
  62386. (iRandom>>8)&0xffffff, iRandom&0xff);
  62387. /* The antipenultimate character of the master journal name must
  62388. ** be "9" to avoid name collisions when using 8+3 filenames. */
  62389. assert( zMaster[sqlite3Strlen30(zMaster)-3]=='9' );
  62390. sqlite3FileSuffix3(zMainFile, zMaster);
  62391. rc = sqlite3OsAccess(pVfs, zMaster, SQLITE_ACCESS_EXISTS, &res);
  62392. }while( rc==SQLITE_OK && res );
  62393. if( rc==SQLITE_OK ){
  62394. /* Open the master journal. */
  62395. rc = sqlite3OsOpenMalloc(pVfs, zMaster, &pMaster,
  62396. SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|
  62397. SQLITE_OPEN_EXCLUSIVE|SQLITE_OPEN_MASTER_JOURNAL, 0
  62398. );
  62399. }
  62400. if( rc!=SQLITE_OK ){
  62401. sqlite3DbFree(db, zMaster);
  62402. return rc;
  62403. }
  62404. /* Write the name of each database file in the transaction into the new
  62405. ** master journal file. If an error occurs at this point close
  62406. ** and delete the master journal file. All the individual journal files
  62407. ** still have 'null' as the master journal pointer, so they will roll
  62408. ** back independently if a failure occurs.
  62409. */
  62410. for(i=0; i<db->nDb; i++){
  62411. Btree *pBt = db->aDb[i].pBt;
  62412. if( sqlite3BtreeIsInTrans(pBt) ){
  62413. char const *zFile = sqlite3BtreeGetJournalname(pBt);
  62414. if( zFile==0 ){
  62415. continue; /* Ignore TEMP and :memory: databases */
  62416. }
  62417. assert( zFile[0]!=0 );
  62418. if( !needSync && !sqlite3BtreeSyncDisabled(pBt) ){
  62419. needSync = 1;
  62420. }
  62421. rc = sqlite3OsWrite(pMaster, zFile, sqlite3Strlen30(zFile)+1, offset);
  62422. offset += sqlite3Strlen30(zFile)+1;
  62423. if( rc!=SQLITE_OK ){
  62424. sqlite3OsCloseFree(pMaster);
  62425. sqlite3OsDelete(pVfs, zMaster, 0);
  62426. sqlite3DbFree(db, zMaster);
  62427. return rc;
  62428. }
  62429. }
  62430. }
  62431. /* Sync the master journal file. If the IOCAP_SEQUENTIAL device
  62432. ** flag is set this is not required.
  62433. */
  62434. if( needSync
  62435. && 0==(sqlite3OsDeviceCharacteristics(pMaster)&SQLITE_IOCAP_SEQUENTIAL)
  62436. && SQLITE_OK!=(rc = sqlite3OsSync(pMaster, SQLITE_SYNC_NORMAL))
  62437. ){
  62438. sqlite3OsCloseFree(pMaster);
  62439. sqlite3OsDelete(pVfs, zMaster, 0);
  62440. sqlite3DbFree(db, zMaster);
  62441. return rc;
  62442. }
  62443. /* Sync all the db files involved in the transaction. The same call
  62444. ** sets the master journal pointer in each individual journal. If
  62445. ** an error occurs here, do not delete the master journal file.
  62446. **
  62447. ** If the error occurs during the first call to
  62448. ** sqlite3BtreeCommitPhaseOne(), then there is a chance that the
  62449. ** master journal file will be orphaned. But we cannot delete it,
  62450. ** in case the master journal file name was written into the journal
  62451. ** file before the failure occurred.
  62452. */
  62453. for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
  62454. Btree *pBt = db->aDb[i].pBt;
  62455. if( pBt ){
  62456. rc = sqlite3BtreeCommitPhaseOne(pBt, zMaster);
  62457. }
  62458. }
  62459. sqlite3OsCloseFree(pMaster);
  62460. assert( rc!=SQLITE_BUSY );
  62461. if( rc!=SQLITE_OK ){
  62462. sqlite3DbFree(db, zMaster);
  62463. return rc;
  62464. }
  62465. /* Delete the master journal file. This commits the transaction. After
  62466. ** doing this the directory is synced again before any individual
  62467. ** transaction files are deleted.
  62468. */
  62469. rc = sqlite3OsDelete(pVfs, zMaster, needSync);
  62470. sqlite3DbFree(db, zMaster);
  62471. zMaster = 0;
  62472. if( rc ){
  62473. return rc;
  62474. }
  62475. /* All files and directories have already been synced, so the following
  62476. ** calls to sqlite3BtreeCommitPhaseTwo() are only closing files and
  62477. ** deleting or truncating journals. If something goes wrong while
  62478. ** this is happening we don't really care. The integrity of the
  62479. ** transaction is already guaranteed, but some stray 'cold' journals
  62480. ** may be lying around. Returning an error code won't help matters.
  62481. */
  62482. disable_simulated_io_errors();
  62483. sqlite3BeginBenignMalloc();
  62484. for(i=0; i<db->nDb; i++){
  62485. Btree *pBt = db->aDb[i].pBt;
  62486. if( pBt ){
  62487. sqlite3BtreeCommitPhaseTwo(pBt, 1);
  62488. }
  62489. }
  62490. sqlite3EndBenignMalloc();
  62491. enable_simulated_io_errors();
  62492. sqlite3VtabCommit(db);
  62493. }
  62494. #endif
  62495. return rc;
  62496. }
  62497. /*
  62498. ** This routine checks that the sqlite3.nVdbeActive count variable
  62499. ** matches the number of vdbe's in the list sqlite3.pVdbe that are
  62500. ** currently active. An assertion fails if the two counts do not match.
  62501. ** This is an internal self-check only - it is not an essential processing
  62502. ** step.
  62503. **
  62504. ** This is a no-op if NDEBUG is defined.
  62505. */
  62506. #ifndef NDEBUG
  62507. static void checkActiveVdbeCnt(sqlite3 *db){
  62508. Vdbe *p;
  62509. int cnt = 0;
  62510. int nWrite = 0;
  62511. int nRead = 0;
  62512. p = db->pVdbe;
  62513. while( p ){
  62514. if( sqlite3_stmt_busy((sqlite3_stmt*)p) ){
  62515. cnt++;
  62516. if( p->readOnly==0 ) nWrite++;
  62517. if( p->bIsReader ) nRead++;
  62518. }
  62519. p = p->pNext;
  62520. }
  62521. assert( cnt==db->nVdbeActive );
  62522. assert( nWrite==db->nVdbeWrite );
  62523. assert( nRead==db->nVdbeRead );
  62524. }
  62525. #else
  62526. #define checkActiveVdbeCnt(x)
  62527. #endif
  62528. /*
  62529. ** If the Vdbe passed as the first argument opened a statement-transaction,
  62530. ** close it now. Argument eOp must be either SAVEPOINT_ROLLBACK or
  62531. ** SAVEPOINT_RELEASE. If it is SAVEPOINT_ROLLBACK, then the statement
  62532. ** transaction is rolled back. If eOp is SAVEPOINT_RELEASE, then the
  62533. ** statement transaction is committed.
  62534. **
  62535. ** If an IO error occurs, an SQLITE_IOERR_XXX error code is returned.
  62536. ** Otherwise SQLITE_OK.
  62537. */
  62538. SQLITE_PRIVATE int sqlite3VdbeCloseStatement(Vdbe *p, int eOp){
  62539. sqlite3 *const db = p->db;
  62540. int rc = SQLITE_OK;
  62541. /* If p->iStatement is greater than zero, then this Vdbe opened a
  62542. ** statement transaction that should be closed here. The only exception
  62543. ** is that an IO error may have occurred, causing an emergency rollback.
  62544. ** In this case (db->nStatement==0), and there is nothing to do.
  62545. */
  62546. if( db->nStatement && p->iStatement ){
  62547. int i;
  62548. const int iSavepoint = p->iStatement-1;
  62549. assert( eOp==SAVEPOINT_ROLLBACK || eOp==SAVEPOINT_RELEASE);
  62550. assert( db->nStatement>0 );
  62551. assert( p->iStatement==(db->nStatement+db->nSavepoint) );
  62552. for(i=0; i<db->nDb; i++){
  62553. int rc2 = SQLITE_OK;
  62554. Btree *pBt = db->aDb[i].pBt;
  62555. if( pBt ){
  62556. if( eOp==SAVEPOINT_ROLLBACK ){
  62557. rc2 = sqlite3BtreeSavepoint(pBt, SAVEPOINT_ROLLBACK, iSavepoint);
  62558. }
  62559. if( rc2==SQLITE_OK ){
  62560. rc2 = sqlite3BtreeSavepoint(pBt, SAVEPOINT_RELEASE, iSavepoint);
  62561. }
  62562. if( rc==SQLITE_OK ){
  62563. rc = rc2;
  62564. }
  62565. }
  62566. }
  62567. db->nStatement--;
  62568. p->iStatement = 0;
  62569. if( rc==SQLITE_OK ){
  62570. if( eOp==SAVEPOINT_ROLLBACK ){
  62571. rc = sqlite3VtabSavepoint(db, SAVEPOINT_ROLLBACK, iSavepoint);
  62572. }
  62573. if( rc==SQLITE_OK ){
  62574. rc = sqlite3VtabSavepoint(db, SAVEPOINT_RELEASE, iSavepoint);
  62575. }
  62576. }
  62577. /* If the statement transaction is being rolled back, also restore the
  62578. ** database handles deferred constraint counter to the value it had when
  62579. ** the statement transaction was opened. */
  62580. if( eOp==SAVEPOINT_ROLLBACK ){
  62581. db->nDeferredCons = p->nStmtDefCons;
  62582. db->nDeferredImmCons = p->nStmtDefImmCons;
  62583. }
  62584. }
  62585. return rc;
  62586. }
  62587. /*
  62588. ** This function is called when a transaction opened by the database
  62589. ** handle associated with the VM passed as an argument is about to be
  62590. ** committed. If there are outstanding deferred foreign key constraint
  62591. ** violations, return SQLITE_ERROR. Otherwise, SQLITE_OK.
  62592. **
  62593. ** If there are outstanding FK violations and this function returns
  62594. ** SQLITE_ERROR, set the result of the VM to SQLITE_CONSTRAINT_FOREIGNKEY
  62595. ** and write an error message to it. Then return SQLITE_ERROR.
  62596. */
  62597. #ifndef SQLITE_OMIT_FOREIGN_KEY
  62598. SQLITE_PRIVATE int sqlite3VdbeCheckFk(Vdbe *p, int deferred){
  62599. sqlite3 *db = p->db;
  62600. if( (deferred && (db->nDeferredCons+db->nDeferredImmCons)>0)
  62601. || (!deferred && p->nFkConstraint>0)
  62602. ){
  62603. p->rc = SQLITE_CONSTRAINT_FOREIGNKEY;
  62604. p->errorAction = OE_Abort;
  62605. sqlite3SetString(&p->zErrMsg, db, "FOREIGN KEY constraint failed");
  62606. return SQLITE_ERROR;
  62607. }
  62608. return SQLITE_OK;
  62609. }
  62610. #endif
  62611. /*
  62612. ** This routine is called the when a VDBE tries to halt. If the VDBE
  62613. ** has made changes and is in autocommit mode, then commit those
  62614. ** changes. If a rollback is needed, then do the rollback.
  62615. **
  62616. ** This routine is the only way to move the state of a VM from
  62617. ** SQLITE_MAGIC_RUN to SQLITE_MAGIC_HALT. It is harmless to
  62618. ** call this on a VM that is in the SQLITE_MAGIC_HALT state.
  62619. **
  62620. ** Return an error code. If the commit could not complete because of
  62621. ** lock contention, return SQLITE_BUSY. If SQLITE_BUSY is returned, it
  62622. ** means the close did not happen and needs to be repeated.
  62623. */
  62624. SQLITE_PRIVATE int sqlite3VdbeHalt(Vdbe *p){
  62625. int rc; /* Used to store transient return codes */
  62626. sqlite3 *db = p->db;
  62627. /* This function contains the logic that determines if a statement or
  62628. ** transaction will be committed or rolled back as a result of the
  62629. ** execution of this virtual machine.
  62630. **
  62631. ** If any of the following errors occur:
  62632. **
  62633. ** SQLITE_NOMEM
  62634. ** SQLITE_IOERR
  62635. ** SQLITE_FULL
  62636. ** SQLITE_INTERRUPT
  62637. **
  62638. ** Then the internal cache might have been left in an inconsistent
  62639. ** state. We need to rollback the statement transaction, if there is
  62640. ** one, or the complete transaction if there is no statement transaction.
  62641. */
  62642. if( p->db->mallocFailed ){
  62643. p->rc = SQLITE_NOMEM;
  62644. }
  62645. if( p->aOnceFlag ) memset(p->aOnceFlag, 0, p->nOnceFlag);
  62646. closeAllCursors(p);
  62647. if( p->magic!=VDBE_MAGIC_RUN ){
  62648. return SQLITE_OK;
  62649. }
  62650. checkActiveVdbeCnt(db);
  62651. /* No commit or rollback needed if the program never started or if the
  62652. ** SQL statement does not read or write a database file. */
  62653. if( p->pc>=0 && p->bIsReader ){
  62654. int mrc; /* Primary error code from p->rc */
  62655. int eStatementOp = 0;
  62656. int isSpecialError; /* Set to true if a 'special' error */
  62657. /* Lock all btrees used by the statement */
  62658. sqlite3VdbeEnter(p);
  62659. /* Check for one of the special errors */
  62660. mrc = p->rc & 0xff;
  62661. isSpecialError = mrc==SQLITE_NOMEM || mrc==SQLITE_IOERR
  62662. || mrc==SQLITE_INTERRUPT || mrc==SQLITE_FULL;
  62663. if( isSpecialError ){
  62664. /* If the query was read-only and the error code is SQLITE_INTERRUPT,
  62665. ** no rollback is necessary. Otherwise, at least a savepoint
  62666. ** transaction must be rolled back to restore the database to a
  62667. ** consistent state.
  62668. **
  62669. ** Even if the statement is read-only, it is important to perform
  62670. ** a statement or transaction rollback operation. If the error
  62671. ** occurred while writing to the journal, sub-journal or database
  62672. ** file as part of an effort to free up cache space (see function
  62673. ** pagerStress() in pager.c), the rollback is required to restore
  62674. ** the pager to a consistent state.
  62675. */
  62676. if( !p->readOnly || mrc!=SQLITE_INTERRUPT ){
  62677. if( (mrc==SQLITE_NOMEM || mrc==SQLITE_FULL) && p->usesStmtJournal ){
  62678. eStatementOp = SAVEPOINT_ROLLBACK;
  62679. }else{
  62680. /* We are forced to roll back the active transaction. Before doing
  62681. ** so, abort any other statements this handle currently has active.
  62682. */
  62683. sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK);
  62684. sqlite3CloseSavepoints(db);
  62685. db->autoCommit = 1;
  62686. p->nChange = 0;
  62687. }
  62688. }
  62689. }
  62690. /* Check for immediate foreign key violations. */
  62691. if( p->rc==SQLITE_OK ){
  62692. sqlite3VdbeCheckFk(p, 0);
  62693. }
  62694. /* If the auto-commit flag is set and this is the only active writer
  62695. ** VM, then we do either a commit or rollback of the current transaction.
  62696. **
  62697. ** Note: This block also runs if one of the special errors handled
  62698. ** above has occurred.
  62699. */
  62700. if( !sqlite3VtabInSync(db)
  62701. && db->autoCommit
  62702. && db->nVdbeWrite==(p->readOnly==0)
  62703. ){
  62704. if( p->rc==SQLITE_OK || (p->errorAction==OE_Fail && !isSpecialError) ){
  62705. rc = sqlite3VdbeCheckFk(p, 1);
  62706. if( rc!=SQLITE_OK ){
  62707. if( NEVER(p->readOnly) ){
  62708. sqlite3VdbeLeave(p);
  62709. return SQLITE_ERROR;
  62710. }
  62711. rc = SQLITE_CONSTRAINT_FOREIGNKEY;
  62712. }else{
  62713. /* The auto-commit flag is true, the vdbe program was successful
  62714. ** or hit an 'OR FAIL' constraint and there are no deferred foreign
  62715. ** key constraints to hold up the transaction. This means a commit
  62716. ** is required. */
  62717. rc = vdbeCommit(db, p);
  62718. }
  62719. if( rc==SQLITE_BUSY && p->readOnly ){
  62720. sqlite3VdbeLeave(p);
  62721. return SQLITE_BUSY;
  62722. }else if( rc!=SQLITE_OK ){
  62723. p->rc = rc;
  62724. sqlite3RollbackAll(db, SQLITE_OK);
  62725. p->nChange = 0;
  62726. }else{
  62727. db->nDeferredCons = 0;
  62728. db->nDeferredImmCons = 0;
  62729. db->flags &= ~SQLITE_DeferFKs;
  62730. sqlite3CommitInternalChanges(db);
  62731. }
  62732. }else{
  62733. sqlite3RollbackAll(db, SQLITE_OK);
  62734. p->nChange = 0;
  62735. }
  62736. db->nStatement = 0;
  62737. }else if( eStatementOp==0 ){
  62738. if( p->rc==SQLITE_OK || p->errorAction==OE_Fail ){
  62739. eStatementOp = SAVEPOINT_RELEASE;
  62740. }else if( p->errorAction==OE_Abort ){
  62741. eStatementOp = SAVEPOINT_ROLLBACK;
  62742. }else{
  62743. sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK);
  62744. sqlite3CloseSavepoints(db);
  62745. db->autoCommit = 1;
  62746. p->nChange = 0;
  62747. }
  62748. }
  62749. /* If eStatementOp is non-zero, then a statement transaction needs to
  62750. ** be committed or rolled back. Call sqlite3VdbeCloseStatement() to
  62751. ** do so. If this operation returns an error, and the current statement
  62752. ** error code is SQLITE_OK or SQLITE_CONSTRAINT, then promote the
  62753. ** current statement error code.
  62754. */
  62755. if( eStatementOp ){
  62756. rc = sqlite3VdbeCloseStatement(p, eStatementOp);
  62757. if( rc ){
  62758. if( p->rc==SQLITE_OK || (p->rc&0xff)==SQLITE_CONSTRAINT ){
  62759. p->rc = rc;
  62760. sqlite3DbFree(db, p->zErrMsg);
  62761. p->zErrMsg = 0;
  62762. }
  62763. sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK);
  62764. sqlite3CloseSavepoints(db);
  62765. db->autoCommit = 1;
  62766. p->nChange = 0;
  62767. }
  62768. }
  62769. /* If this was an INSERT, UPDATE or DELETE and no statement transaction
  62770. ** has been rolled back, update the database connection change-counter.
  62771. */
  62772. if( p->changeCntOn ){
  62773. if( eStatementOp!=SAVEPOINT_ROLLBACK ){
  62774. sqlite3VdbeSetChanges(db, p->nChange);
  62775. }else{
  62776. sqlite3VdbeSetChanges(db, 0);
  62777. }
  62778. p->nChange = 0;
  62779. }
  62780. /* Release the locks */
  62781. sqlite3VdbeLeave(p);
  62782. }
  62783. /* We have successfully halted and closed the VM. Record this fact. */
  62784. if( p->pc>=0 ){
  62785. db->nVdbeActive--;
  62786. if( !p->readOnly ) db->nVdbeWrite--;
  62787. if( p->bIsReader ) db->nVdbeRead--;
  62788. assert( db->nVdbeActive>=db->nVdbeRead );
  62789. assert( db->nVdbeRead>=db->nVdbeWrite );
  62790. assert( db->nVdbeWrite>=0 );
  62791. }
  62792. p->magic = VDBE_MAGIC_HALT;
  62793. checkActiveVdbeCnt(db);
  62794. if( p->db->mallocFailed ){
  62795. p->rc = SQLITE_NOMEM;
  62796. }
  62797. /* If the auto-commit flag is set to true, then any locks that were held
  62798. ** by connection db have now been released. Call sqlite3ConnectionUnlocked()
  62799. ** to invoke any required unlock-notify callbacks.
  62800. */
  62801. if( db->autoCommit ){
  62802. sqlite3ConnectionUnlocked(db);
  62803. }
  62804. assert( db->nVdbeActive>0 || db->autoCommit==0 || db->nStatement==0 );
  62805. return (p->rc==SQLITE_BUSY ? SQLITE_BUSY : SQLITE_OK);
  62806. }
  62807. /*
  62808. ** Each VDBE holds the result of the most recent sqlite3_step() call
  62809. ** in p->rc. This routine sets that result back to SQLITE_OK.
  62810. */
  62811. SQLITE_PRIVATE void sqlite3VdbeResetStepResult(Vdbe *p){
  62812. p->rc = SQLITE_OK;
  62813. }
  62814. /*
  62815. ** Copy the error code and error message belonging to the VDBE passed
  62816. ** as the first argument to its database handle (so that they will be
  62817. ** returned by calls to sqlite3_errcode() and sqlite3_errmsg()).
  62818. **
  62819. ** This function does not clear the VDBE error code or message, just
  62820. ** copies them to the database handle.
  62821. */
  62822. SQLITE_PRIVATE int sqlite3VdbeTransferError(Vdbe *p){
  62823. sqlite3 *db = p->db;
  62824. int rc = p->rc;
  62825. if( p->zErrMsg ){
  62826. u8 mallocFailed = db->mallocFailed;
  62827. sqlite3BeginBenignMalloc();
  62828. if( db->pErr==0 ) db->pErr = sqlite3ValueNew(db);
  62829. sqlite3ValueSetStr(db->pErr, -1, p->zErrMsg, SQLITE_UTF8, SQLITE_TRANSIENT);
  62830. sqlite3EndBenignMalloc();
  62831. db->mallocFailed = mallocFailed;
  62832. db->errCode = rc;
  62833. }else{
  62834. sqlite3Error(db, rc);
  62835. }
  62836. return rc;
  62837. }
  62838. #ifdef SQLITE_ENABLE_SQLLOG
  62839. /*
  62840. ** If an SQLITE_CONFIG_SQLLOG hook is registered and the VM has been run,
  62841. ** invoke it.
  62842. */
  62843. static void vdbeInvokeSqllog(Vdbe *v){
  62844. if( sqlite3GlobalConfig.xSqllog && v->rc==SQLITE_OK && v->zSql && v->pc>=0 ){
  62845. char *zExpanded = sqlite3VdbeExpandSql(v, v->zSql);
  62846. assert( v->db->init.busy==0 );
  62847. if( zExpanded ){
  62848. sqlite3GlobalConfig.xSqllog(
  62849. sqlite3GlobalConfig.pSqllogArg, v->db, zExpanded, 1
  62850. );
  62851. sqlite3DbFree(v->db, zExpanded);
  62852. }
  62853. }
  62854. }
  62855. #else
  62856. # define vdbeInvokeSqllog(x)
  62857. #endif
  62858. /*
  62859. ** Clean up a VDBE after execution but do not delete the VDBE just yet.
  62860. ** Write any error messages into *pzErrMsg. Return the result code.
  62861. **
  62862. ** After this routine is run, the VDBE should be ready to be executed
  62863. ** again.
  62864. **
  62865. ** To look at it another way, this routine resets the state of the
  62866. ** virtual machine from VDBE_MAGIC_RUN or VDBE_MAGIC_HALT back to
  62867. ** VDBE_MAGIC_INIT.
  62868. */
  62869. SQLITE_PRIVATE int sqlite3VdbeReset(Vdbe *p){
  62870. sqlite3 *db;
  62871. db = p->db;
  62872. /* If the VM did not run to completion or if it encountered an
  62873. ** error, then it might not have been halted properly. So halt
  62874. ** it now.
  62875. */
  62876. sqlite3VdbeHalt(p);
  62877. /* If the VDBE has be run even partially, then transfer the error code
  62878. ** and error message from the VDBE into the main database structure. But
  62879. ** if the VDBE has just been set to run but has not actually executed any
  62880. ** instructions yet, leave the main database error information unchanged.
  62881. */
  62882. if( p->pc>=0 ){
  62883. vdbeInvokeSqllog(p);
  62884. sqlite3VdbeTransferError(p);
  62885. sqlite3DbFree(db, p->zErrMsg);
  62886. p->zErrMsg = 0;
  62887. if( p->runOnlyOnce ) p->expired = 1;
  62888. }else if( p->rc && p->expired ){
  62889. /* The expired flag was set on the VDBE before the first call
  62890. ** to sqlite3_step(). For consistency (since sqlite3_step() was
  62891. ** called), set the database error in this case as well.
  62892. */
  62893. sqlite3ErrorWithMsg(db, p->rc, p->zErrMsg ? "%s" : 0, p->zErrMsg);
  62894. sqlite3DbFree(db, p->zErrMsg);
  62895. p->zErrMsg = 0;
  62896. }
  62897. /* Reclaim all memory used by the VDBE
  62898. */
  62899. Cleanup(p);
  62900. /* Save profiling information from this VDBE run.
  62901. */
  62902. #ifdef VDBE_PROFILE
  62903. {
  62904. FILE *out = fopen("vdbe_profile.out", "a");
  62905. if( out ){
  62906. int i;
  62907. fprintf(out, "---- ");
  62908. for(i=0; i<p->nOp; i++){
  62909. fprintf(out, "%02x", p->aOp[i].opcode);
  62910. }
  62911. fprintf(out, "\n");
  62912. if( p->zSql ){
  62913. char c, pc = 0;
  62914. fprintf(out, "-- ");
  62915. for(i=0; (c = p->zSql[i])!=0; i++){
  62916. if( pc=='\n' ) fprintf(out, "-- ");
  62917. putc(c, out);
  62918. pc = c;
  62919. }
  62920. if( pc!='\n' ) fprintf(out, "\n");
  62921. }
  62922. for(i=0; i<p->nOp; i++){
  62923. char zHdr[100];
  62924. sqlite3_snprintf(sizeof(zHdr), zHdr, "%6u %12llu %8llu ",
  62925. p->aOp[i].cnt,
  62926. p->aOp[i].cycles,
  62927. p->aOp[i].cnt>0 ? p->aOp[i].cycles/p->aOp[i].cnt : 0
  62928. );
  62929. fprintf(out, "%s", zHdr);
  62930. sqlite3VdbePrintOp(out, i, &p->aOp[i]);
  62931. }
  62932. fclose(out);
  62933. }
  62934. }
  62935. #endif
  62936. p->iCurrentTime = 0;
  62937. p->magic = VDBE_MAGIC_INIT;
  62938. return p->rc & db->errMask;
  62939. }
  62940. /*
  62941. ** Clean up and delete a VDBE after execution. Return an integer which is
  62942. ** the result code. Write any error message text into *pzErrMsg.
  62943. */
  62944. SQLITE_PRIVATE int sqlite3VdbeFinalize(Vdbe *p){
  62945. int rc = SQLITE_OK;
  62946. if( p->magic==VDBE_MAGIC_RUN || p->magic==VDBE_MAGIC_HALT ){
  62947. rc = sqlite3VdbeReset(p);
  62948. assert( (rc & p->db->errMask)==rc );
  62949. }
  62950. sqlite3VdbeDelete(p);
  62951. return rc;
  62952. }
  62953. /*
  62954. ** If parameter iOp is less than zero, then invoke the destructor for
  62955. ** all auxiliary data pointers currently cached by the VM passed as
  62956. ** the first argument.
  62957. **
  62958. ** Or, if iOp is greater than or equal to zero, then the destructor is
  62959. ** only invoked for those auxiliary data pointers created by the user
  62960. ** function invoked by the OP_Function opcode at instruction iOp of
  62961. ** VM pVdbe, and only then if:
  62962. **
  62963. ** * the associated function parameter is the 32nd or later (counting
  62964. ** from left to right), or
  62965. **
  62966. ** * the corresponding bit in argument mask is clear (where the first
  62967. ** function parameter corresponds to bit 0 etc.).
  62968. */
  62969. SQLITE_PRIVATE void sqlite3VdbeDeleteAuxData(Vdbe *pVdbe, int iOp, int mask){
  62970. AuxData **pp = &pVdbe->pAuxData;
  62971. while( *pp ){
  62972. AuxData *pAux = *pp;
  62973. if( (iOp<0)
  62974. || (pAux->iOp==iOp && (pAux->iArg>31 || !(mask & MASKBIT32(pAux->iArg))))
  62975. ){
  62976. testcase( pAux->iArg==31 );
  62977. if( pAux->xDelete ){
  62978. pAux->xDelete(pAux->pAux);
  62979. }
  62980. *pp = pAux->pNext;
  62981. sqlite3DbFree(pVdbe->db, pAux);
  62982. }else{
  62983. pp= &pAux->pNext;
  62984. }
  62985. }
  62986. }
  62987. /*
  62988. ** Free all memory associated with the Vdbe passed as the second argument,
  62989. ** except for object itself, which is preserved.
  62990. **
  62991. ** The difference between this function and sqlite3VdbeDelete() is that
  62992. ** VdbeDelete() also unlinks the Vdbe from the list of VMs associated with
  62993. ** the database connection and frees the object itself.
  62994. */
  62995. SQLITE_PRIVATE void sqlite3VdbeClearObject(sqlite3 *db, Vdbe *p){
  62996. SubProgram *pSub, *pNext;
  62997. int i;
  62998. assert( p->db==0 || p->db==db );
  62999. releaseMemArray(p->aVar, p->nVar);
  63000. releaseMemArray(p->aColName, p->nResColumn*COLNAME_N);
  63001. for(pSub=p->pProgram; pSub; pSub=pNext){
  63002. pNext = pSub->pNext;
  63003. vdbeFreeOpArray(db, pSub->aOp, pSub->nOp);
  63004. sqlite3DbFree(db, pSub);
  63005. }
  63006. for(i=p->nzVar-1; i>=0; i--) sqlite3DbFree(db, p->azVar[i]);
  63007. vdbeFreeOpArray(db, p->aOp, p->nOp);
  63008. sqlite3DbFree(db, p->aColName);
  63009. sqlite3DbFree(db, p->zSql);
  63010. sqlite3DbFree(db, p->pFree);
  63011. #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
  63012. for(i=0; i<p->nScan; i++){
  63013. sqlite3DbFree(db, p->aScan[i].zName);
  63014. }
  63015. sqlite3DbFree(db, p->aScan);
  63016. #endif
  63017. }
  63018. /*
  63019. ** Delete an entire VDBE.
  63020. */
  63021. SQLITE_PRIVATE void sqlite3VdbeDelete(Vdbe *p){
  63022. sqlite3 *db;
  63023. if( NEVER(p==0) ) return;
  63024. db = p->db;
  63025. assert( sqlite3_mutex_held(db->mutex) );
  63026. sqlite3VdbeClearObject(db, p);
  63027. if( p->pPrev ){
  63028. p->pPrev->pNext = p->pNext;
  63029. }else{
  63030. assert( db->pVdbe==p );
  63031. db->pVdbe = p->pNext;
  63032. }
  63033. if( p->pNext ){
  63034. p->pNext->pPrev = p->pPrev;
  63035. }
  63036. p->magic = VDBE_MAGIC_DEAD;
  63037. p->db = 0;
  63038. sqlite3DbFree(db, p);
  63039. }
  63040. /*
  63041. ** The cursor "p" has a pending seek operation that has not yet been
  63042. ** carried out. Seek the cursor now. If an error occurs, return
  63043. ** the appropriate error code.
  63044. */
  63045. static int SQLITE_NOINLINE handleDeferredMoveto(VdbeCursor *p){
  63046. int res, rc;
  63047. #ifdef SQLITE_TEST
  63048. extern int sqlite3_search_count;
  63049. #endif
  63050. assert( p->deferredMoveto );
  63051. assert( p->isTable );
  63052. rc = sqlite3BtreeMovetoUnpacked(p->pCursor, 0, p->movetoTarget, 0, &res);
  63053. if( rc ) return rc;
  63054. if( res!=0 ) return SQLITE_CORRUPT_BKPT;
  63055. #ifdef SQLITE_TEST
  63056. sqlite3_search_count++;
  63057. #endif
  63058. p->deferredMoveto = 0;
  63059. p->cacheStatus = CACHE_STALE;
  63060. return SQLITE_OK;
  63061. }
  63062. /*
  63063. ** Something has moved cursor "p" out of place. Maybe the row it was
  63064. ** pointed to was deleted out from under it. Or maybe the btree was
  63065. ** rebalanced. Whatever the cause, try to restore "p" to the place it
  63066. ** is supposed to be pointing. If the row was deleted out from under the
  63067. ** cursor, set the cursor to point to a NULL row.
  63068. */
  63069. static int SQLITE_NOINLINE handleMovedCursor(VdbeCursor *p){
  63070. int isDifferentRow, rc;
  63071. assert( p->pCursor!=0 );
  63072. assert( sqlite3BtreeCursorHasMoved(p->pCursor) );
  63073. rc = sqlite3BtreeCursorRestore(p->pCursor, &isDifferentRow);
  63074. p->cacheStatus = CACHE_STALE;
  63075. if( isDifferentRow ) p->nullRow = 1;
  63076. return rc;
  63077. }
  63078. /*
  63079. ** Check to ensure that the cursor is valid. Restore the cursor
  63080. ** if need be. Return any I/O error from the restore operation.
  63081. */
  63082. SQLITE_PRIVATE int sqlite3VdbeCursorRestore(VdbeCursor *p){
  63083. if( sqlite3BtreeCursorHasMoved(p->pCursor) ){
  63084. return handleMovedCursor(p);
  63085. }
  63086. return SQLITE_OK;
  63087. }
  63088. /*
  63089. ** Make sure the cursor p is ready to read or write the row to which it
  63090. ** was last positioned. Return an error code if an OOM fault or I/O error
  63091. ** prevents us from positioning the cursor to its correct position.
  63092. **
  63093. ** If a MoveTo operation is pending on the given cursor, then do that
  63094. ** MoveTo now. If no move is pending, check to see if the row has been
  63095. ** deleted out from under the cursor and if it has, mark the row as
  63096. ** a NULL row.
  63097. **
  63098. ** If the cursor is already pointing to the correct row and that row has
  63099. ** not been deleted out from under the cursor, then this routine is a no-op.
  63100. */
  63101. SQLITE_PRIVATE int sqlite3VdbeCursorMoveto(VdbeCursor *p){
  63102. if( p->deferredMoveto ){
  63103. return handleDeferredMoveto(p);
  63104. }
  63105. if( p->pCursor && sqlite3BtreeCursorHasMoved(p->pCursor) ){
  63106. return handleMovedCursor(p);
  63107. }
  63108. return SQLITE_OK;
  63109. }
  63110. /*
  63111. ** The following functions:
  63112. **
  63113. ** sqlite3VdbeSerialType()
  63114. ** sqlite3VdbeSerialTypeLen()
  63115. ** sqlite3VdbeSerialLen()
  63116. ** sqlite3VdbeSerialPut()
  63117. ** sqlite3VdbeSerialGet()
  63118. **
  63119. ** encapsulate the code that serializes values for storage in SQLite
  63120. ** data and index records. Each serialized value consists of a
  63121. ** 'serial-type' and a blob of data. The serial type is an 8-byte unsigned
  63122. ** integer, stored as a varint.
  63123. **
  63124. ** In an SQLite index record, the serial type is stored directly before
  63125. ** the blob of data that it corresponds to. In a table record, all serial
  63126. ** types are stored at the start of the record, and the blobs of data at
  63127. ** the end. Hence these functions allow the caller to handle the
  63128. ** serial-type and data blob separately.
  63129. **
  63130. ** The following table describes the various storage classes for data:
  63131. **
  63132. ** serial type bytes of data type
  63133. ** -------------- --------------- ---------------
  63134. ** 0 0 NULL
  63135. ** 1 1 signed integer
  63136. ** 2 2 signed integer
  63137. ** 3 3 signed integer
  63138. ** 4 4 signed integer
  63139. ** 5 6 signed integer
  63140. ** 6 8 signed integer
  63141. ** 7 8 IEEE float
  63142. ** 8 0 Integer constant 0
  63143. ** 9 0 Integer constant 1
  63144. ** 10,11 reserved for expansion
  63145. ** N>=12 and even (N-12)/2 BLOB
  63146. ** N>=13 and odd (N-13)/2 text
  63147. **
  63148. ** The 8 and 9 types were added in 3.3.0, file format 4. Prior versions
  63149. ** of SQLite will not understand those serial types.
  63150. */
  63151. /*
  63152. ** Return the serial-type for the value stored in pMem.
  63153. */
  63154. SQLITE_PRIVATE u32 sqlite3VdbeSerialType(Mem *pMem, int file_format){
  63155. int flags = pMem->flags;
  63156. u32 n;
  63157. if( flags&MEM_Null ){
  63158. return 0;
  63159. }
  63160. if( flags&MEM_Int ){
  63161. /* Figure out whether to use 1, 2, 4, 6 or 8 bytes. */
  63162. # define MAX_6BYTE ((((i64)0x00008000)<<32)-1)
  63163. i64 i = pMem->u.i;
  63164. u64 u;
  63165. if( i<0 ){
  63166. u = ~i;
  63167. }else{
  63168. u = i;
  63169. }
  63170. if( u<=127 ){
  63171. return ((i&1)==i && file_format>=4) ? 8+(u32)u : 1;
  63172. }
  63173. if( u<=32767 ) return 2;
  63174. if( u<=8388607 ) return 3;
  63175. if( u<=2147483647 ) return 4;
  63176. if( u<=MAX_6BYTE ) return 5;
  63177. return 6;
  63178. }
  63179. if( flags&MEM_Real ){
  63180. return 7;
  63181. }
  63182. assert( pMem->db->mallocFailed || flags&(MEM_Str|MEM_Blob) );
  63183. assert( pMem->n>=0 );
  63184. n = (u32)pMem->n;
  63185. if( flags & MEM_Zero ){
  63186. n += pMem->u.nZero;
  63187. }
  63188. return ((n*2) + 12 + ((flags&MEM_Str)!=0));
  63189. }
  63190. /*
  63191. ** Return the length of the data corresponding to the supplied serial-type.
  63192. */
  63193. SQLITE_PRIVATE u32 sqlite3VdbeSerialTypeLen(u32 serial_type){
  63194. if( serial_type>=12 ){
  63195. return (serial_type-12)/2;
  63196. }else{
  63197. static const u8 aSize[] = { 0, 1, 2, 3, 4, 6, 8, 8, 0, 0, 0, 0 };
  63198. return aSize[serial_type];
  63199. }
  63200. }
  63201. /*
  63202. ** If we are on an architecture with mixed-endian floating
  63203. ** points (ex: ARM7) then swap the lower 4 bytes with the
  63204. ** upper 4 bytes. Return the result.
  63205. **
  63206. ** For most architectures, this is a no-op.
  63207. **
  63208. ** (later): It is reported to me that the mixed-endian problem
  63209. ** on ARM7 is an issue with GCC, not with the ARM7 chip. It seems
  63210. ** that early versions of GCC stored the two words of a 64-bit
  63211. ** float in the wrong order. And that error has been propagated
  63212. ** ever since. The blame is not necessarily with GCC, though.
  63213. ** GCC might have just copying the problem from a prior compiler.
  63214. ** I am also told that newer versions of GCC that follow a different
  63215. ** ABI get the byte order right.
  63216. **
  63217. ** Developers using SQLite on an ARM7 should compile and run their
  63218. ** application using -DSQLITE_DEBUG=1 at least once. With DEBUG
  63219. ** enabled, some asserts below will ensure that the byte order of
  63220. ** floating point values is correct.
  63221. **
  63222. ** (2007-08-30) Frank van Vugt has studied this problem closely
  63223. ** and has send his findings to the SQLite developers. Frank
  63224. ** writes that some Linux kernels offer floating point hardware
  63225. ** emulation that uses only 32-bit mantissas instead of a full
  63226. ** 48-bits as required by the IEEE standard. (This is the
  63227. ** CONFIG_FPE_FASTFPE option.) On such systems, floating point
  63228. ** byte swapping becomes very complicated. To avoid problems,
  63229. ** the necessary byte swapping is carried out using a 64-bit integer
  63230. ** rather than a 64-bit float. Frank assures us that the code here
  63231. ** works for him. We, the developers, have no way to independently
  63232. ** verify this, but Frank seems to know what he is talking about
  63233. ** so we trust him.
  63234. */
  63235. #ifdef SQLITE_MIXED_ENDIAN_64BIT_FLOAT
  63236. static u64 floatSwap(u64 in){
  63237. union {
  63238. u64 r;
  63239. u32 i[2];
  63240. } u;
  63241. u32 t;
  63242. u.r = in;
  63243. t = u.i[0];
  63244. u.i[0] = u.i[1];
  63245. u.i[1] = t;
  63246. return u.r;
  63247. }
  63248. # define swapMixedEndianFloat(X) X = floatSwap(X)
  63249. #else
  63250. # define swapMixedEndianFloat(X)
  63251. #endif
  63252. /*
  63253. ** Write the serialized data blob for the value stored in pMem into
  63254. ** buf. It is assumed that the caller has allocated sufficient space.
  63255. ** Return the number of bytes written.
  63256. **
  63257. ** nBuf is the amount of space left in buf[]. The caller is responsible
  63258. ** for allocating enough space to buf[] to hold the entire field, exclusive
  63259. ** of the pMem->u.nZero bytes for a MEM_Zero value.
  63260. **
  63261. ** Return the number of bytes actually written into buf[]. The number
  63262. ** of bytes in the zero-filled tail is included in the return value only
  63263. ** if those bytes were zeroed in buf[].
  63264. */
  63265. SQLITE_PRIVATE u32 sqlite3VdbeSerialPut(u8 *buf, Mem *pMem, u32 serial_type){
  63266. u32 len;
  63267. /* Integer and Real */
  63268. if( serial_type<=7 && serial_type>0 ){
  63269. u64 v;
  63270. u32 i;
  63271. if( serial_type==7 ){
  63272. assert( sizeof(v)==sizeof(pMem->u.r) );
  63273. memcpy(&v, &pMem->u.r, sizeof(v));
  63274. swapMixedEndianFloat(v);
  63275. }else{
  63276. v = pMem->u.i;
  63277. }
  63278. len = i = sqlite3VdbeSerialTypeLen(serial_type);
  63279. assert( i>0 );
  63280. do{
  63281. buf[--i] = (u8)(v&0xFF);
  63282. v >>= 8;
  63283. }while( i );
  63284. return len;
  63285. }
  63286. /* String or blob */
  63287. if( serial_type>=12 ){
  63288. assert( pMem->n + ((pMem->flags & MEM_Zero)?pMem->u.nZero:0)
  63289. == (int)sqlite3VdbeSerialTypeLen(serial_type) );
  63290. len = pMem->n;
  63291. memcpy(buf, pMem->z, len);
  63292. return len;
  63293. }
  63294. /* NULL or constants 0 or 1 */
  63295. return 0;
  63296. }
  63297. /* Input "x" is a sequence of unsigned characters that represent a
  63298. ** big-endian integer. Return the equivalent native integer
  63299. */
  63300. #define ONE_BYTE_INT(x) ((i8)(x)[0])
  63301. #define TWO_BYTE_INT(x) (256*(i8)((x)[0])|(x)[1])
  63302. #define THREE_BYTE_INT(x) (65536*(i8)((x)[0])|((x)[1]<<8)|(x)[2])
  63303. #define FOUR_BYTE_UINT(x) (((u32)(x)[0]<<24)|((x)[1]<<16)|((x)[2]<<8)|(x)[3])
  63304. #define FOUR_BYTE_INT(x) (16777216*(i8)((x)[0])|((x)[1]<<16)|((x)[2]<<8)|(x)[3])
  63305. /*
  63306. ** Deserialize the data blob pointed to by buf as serial type serial_type
  63307. ** and store the result in pMem. Return the number of bytes read.
  63308. **
  63309. ** This function is implemented as two separate routines for performance.
  63310. ** The few cases that require local variables are broken out into a separate
  63311. ** routine so that in most cases the overhead of moving the stack pointer
  63312. ** is avoided.
  63313. */
  63314. static u32 SQLITE_NOINLINE serialGet(
  63315. const unsigned char *buf, /* Buffer to deserialize from */
  63316. u32 serial_type, /* Serial type to deserialize */
  63317. Mem *pMem /* Memory cell to write value into */
  63318. ){
  63319. u64 x = FOUR_BYTE_UINT(buf);
  63320. u32 y = FOUR_BYTE_UINT(buf+4);
  63321. x = (x<<32) + y;
  63322. if( serial_type==6 ){
  63323. /* EVIDENCE-OF: R-29851-52272 Value is a big-endian 64-bit
  63324. ** twos-complement integer. */
  63325. pMem->u.i = *(i64*)&x;
  63326. pMem->flags = MEM_Int;
  63327. testcase( pMem->u.i<0 );
  63328. }else{
  63329. /* EVIDENCE-OF: R-57343-49114 Value is a big-endian IEEE 754-2008 64-bit
  63330. ** floating point number. */
  63331. #if !defined(NDEBUG) && !defined(SQLITE_OMIT_FLOATING_POINT)
  63332. /* Verify that integers and floating point values use the same
  63333. ** byte order. Or, that if SQLITE_MIXED_ENDIAN_64BIT_FLOAT is
  63334. ** defined that 64-bit floating point values really are mixed
  63335. ** endian.
  63336. */
  63337. static const u64 t1 = ((u64)0x3ff00000)<<32;
  63338. static const double r1 = 1.0;
  63339. u64 t2 = t1;
  63340. swapMixedEndianFloat(t2);
  63341. assert( sizeof(r1)==sizeof(t2) && memcmp(&r1, &t2, sizeof(r1))==0 );
  63342. #endif
  63343. assert( sizeof(x)==8 && sizeof(pMem->u.r)==8 );
  63344. swapMixedEndianFloat(x);
  63345. memcpy(&pMem->u.r, &x, sizeof(x));
  63346. pMem->flags = sqlite3IsNaN(pMem->u.r) ? MEM_Null : MEM_Real;
  63347. }
  63348. return 8;
  63349. }
  63350. SQLITE_PRIVATE u32 sqlite3VdbeSerialGet(
  63351. const unsigned char *buf, /* Buffer to deserialize from */
  63352. u32 serial_type, /* Serial type to deserialize */
  63353. Mem *pMem /* Memory cell to write value into */
  63354. ){
  63355. switch( serial_type ){
  63356. case 10: /* Reserved for future use */
  63357. case 11: /* Reserved for future use */
  63358. case 0: { /* Null */
  63359. /* EVIDENCE-OF: R-24078-09375 Value is a NULL. */
  63360. pMem->flags = MEM_Null;
  63361. break;
  63362. }
  63363. case 1: {
  63364. /* EVIDENCE-OF: R-44885-25196 Value is an 8-bit twos-complement
  63365. ** integer. */
  63366. pMem->u.i = ONE_BYTE_INT(buf);
  63367. pMem->flags = MEM_Int;
  63368. testcase( pMem->u.i<0 );
  63369. return 1;
  63370. }
  63371. case 2: { /* 2-byte signed integer */
  63372. /* EVIDENCE-OF: R-49794-35026 Value is a big-endian 16-bit
  63373. ** twos-complement integer. */
  63374. pMem->u.i = TWO_BYTE_INT(buf);
  63375. pMem->flags = MEM_Int;
  63376. testcase( pMem->u.i<0 );
  63377. return 2;
  63378. }
  63379. case 3: { /* 3-byte signed integer */
  63380. /* EVIDENCE-OF: R-37839-54301 Value is a big-endian 24-bit
  63381. ** twos-complement integer. */
  63382. pMem->u.i = THREE_BYTE_INT(buf);
  63383. pMem->flags = MEM_Int;
  63384. testcase( pMem->u.i<0 );
  63385. return 3;
  63386. }
  63387. case 4: { /* 4-byte signed integer */
  63388. /* EVIDENCE-OF: R-01849-26079 Value is a big-endian 32-bit
  63389. ** twos-complement integer. */
  63390. pMem->u.i = FOUR_BYTE_INT(buf);
  63391. pMem->flags = MEM_Int;
  63392. testcase( pMem->u.i<0 );
  63393. return 4;
  63394. }
  63395. case 5: { /* 6-byte signed integer */
  63396. /* EVIDENCE-OF: R-50385-09674 Value is a big-endian 48-bit
  63397. ** twos-complement integer. */
  63398. pMem->u.i = FOUR_BYTE_UINT(buf+2) + (((i64)1)<<32)*TWO_BYTE_INT(buf);
  63399. pMem->flags = MEM_Int;
  63400. testcase( pMem->u.i<0 );
  63401. return 6;
  63402. }
  63403. case 6: /* 8-byte signed integer */
  63404. case 7: { /* IEEE floating point */
  63405. /* These use local variables, so do them in a separate routine
  63406. ** to avoid having to move the frame pointer in the common case */
  63407. return serialGet(buf,serial_type,pMem);
  63408. }
  63409. case 8: /* Integer 0 */
  63410. case 9: { /* Integer 1 */
  63411. /* EVIDENCE-OF: R-12976-22893 Value is the integer 0. */
  63412. /* EVIDENCE-OF: R-18143-12121 Value is the integer 1. */
  63413. pMem->u.i = serial_type-8;
  63414. pMem->flags = MEM_Int;
  63415. return 0;
  63416. }
  63417. default: {
  63418. /* EVIDENCE-OF: R-14606-31564 Value is a BLOB that is (N-12)/2 bytes in
  63419. ** length.
  63420. ** EVIDENCE-OF: R-28401-00140 Value is a string in the text encoding and
  63421. ** (N-13)/2 bytes in length. */
  63422. static const u16 aFlag[] = { MEM_Blob|MEM_Ephem, MEM_Str|MEM_Ephem };
  63423. pMem->z = (char *)buf;
  63424. pMem->n = (serial_type-12)/2;
  63425. pMem->flags = aFlag[serial_type&1];
  63426. return pMem->n;
  63427. }
  63428. }
  63429. return 0;
  63430. }
  63431. /*
  63432. ** This routine is used to allocate sufficient space for an UnpackedRecord
  63433. ** structure large enough to be used with sqlite3VdbeRecordUnpack() if
  63434. ** the first argument is a pointer to KeyInfo structure pKeyInfo.
  63435. **
  63436. ** The space is either allocated using sqlite3DbMallocRaw() or from within
  63437. ** the unaligned buffer passed via the second and third arguments (presumably
  63438. ** stack space). If the former, then *ppFree is set to a pointer that should
  63439. ** be eventually freed by the caller using sqlite3DbFree(). Or, if the
  63440. ** allocation comes from the pSpace/szSpace buffer, *ppFree is set to NULL
  63441. ** before returning.
  63442. **
  63443. ** If an OOM error occurs, NULL is returned.
  63444. */
  63445. SQLITE_PRIVATE UnpackedRecord *sqlite3VdbeAllocUnpackedRecord(
  63446. KeyInfo *pKeyInfo, /* Description of the record */
  63447. char *pSpace, /* Unaligned space available */
  63448. int szSpace, /* Size of pSpace[] in bytes */
  63449. char **ppFree /* OUT: Caller should free this pointer */
  63450. ){
  63451. UnpackedRecord *p; /* Unpacked record to return */
  63452. int nOff; /* Increment pSpace by nOff to align it */
  63453. int nByte; /* Number of bytes required for *p */
  63454. /* We want to shift the pointer pSpace up such that it is 8-byte aligned.
  63455. ** Thus, we need to calculate a value, nOff, between 0 and 7, to shift
  63456. ** it by. If pSpace is already 8-byte aligned, nOff should be zero.
  63457. */
  63458. nOff = (8 - (SQLITE_PTR_TO_INT(pSpace) & 7)) & 7;
  63459. nByte = ROUND8(sizeof(UnpackedRecord)) + sizeof(Mem)*(pKeyInfo->nField+1);
  63460. if( nByte>szSpace+nOff ){
  63461. p = (UnpackedRecord *)sqlite3DbMallocRaw(pKeyInfo->db, nByte);
  63462. *ppFree = (char *)p;
  63463. if( !p ) return 0;
  63464. }else{
  63465. p = (UnpackedRecord*)&pSpace[nOff];
  63466. *ppFree = 0;
  63467. }
  63468. p->aMem = (Mem*)&((char*)p)[ROUND8(sizeof(UnpackedRecord))];
  63469. assert( pKeyInfo->aSortOrder!=0 );
  63470. p->pKeyInfo = pKeyInfo;
  63471. p->nField = pKeyInfo->nField + 1;
  63472. return p;
  63473. }
  63474. /*
  63475. ** Given the nKey-byte encoding of a record in pKey[], populate the
  63476. ** UnpackedRecord structure indicated by the fourth argument with the
  63477. ** contents of the decoded record.
  63478. */
  63479. SQLITE_PRIVATE void sqlite3VdbeRecordUnpack(
  63480. KeyInfo *pKeyInfo, /* Information about the record format */
  63481. int nKey, /* Size of the binary record */
  63482. const void *pKey, /* The binary record */
  63483. UnpackedRecord *p /* Populate this structure before returning. */
  63484. ){
  63485. const unsigned char *aKey = (const unsigned char *)pKey;
  63486. int d;
  63487. u32 idx; /* Offset in aKey[] to read from */
  63488. u16 u; /* Unsigned loop counter */
  63489. u32 szHdr;
  63490. Mem *pMem = p->aMem;
  63491. p->default_rc = 0;
  63492. assert( EIGHT_BYTE_ALIGNMENT(pMem) );
  63493. idx = getVarint32(aKey, szHdr);
  63494. d = szHdr;
  63495. u = 0;
  63496. while( idx<szHdr && d<=nKey ){
  63497. u32 serial_type;
  63498. idx += getVarint32(&aKey[idx], serial_type);
  63499. pMem->enc = pKeyInfo->enc;
  63500. pMem->db = pKeyInfo->db;
  63501. /* pMem->flags = 0; // sqlite3VdbeSerialGet() will set this for us */
  63502. pMem->szMalloc = 0;
  63503. d += sqlite3VdbeSerialGet(&aKey[d], serial_type, pMem);
  63504. pMem++;
  63505. if( (++u)>=p->nField ) break;
  63506. }
  63507. assert( u<=pKeyInfo->nField + 1 );
  63508. p->nField = u;
  63509. }
  63510. #if SQLITE_DEBUG
  63511. /*
  63512. ** This function compares two index or table record keys in the same way
  63513. ** as the sqlite3VdbeRecordCompare() routine. Unlike VdbeRecordCompare(),
  63514. ** this function deserializes and compares values using the
  63515. ** sqlite3VdbeSerialGet() and sqlite3MemCompare() functions. It is used
  63516. ** in assert() statements to ensure that the optimized code in
  63517. ** sqlite3VdbeRecordCompare() returns results with these two primitives.
  63518. **
  63519. ** Return true if the result of comparison is equivalent to desiredResult.
  63520. ** Return false if there is a disagreement.
  63521. */
  63522. static int vdbeRecordCompareDebug(
  63523. int nKey1, const void *pKey1, /* Left key */
  63524. const UnpackedRecord *pPKey2, /* Right key */
  63525. int desiredResult /* Correct answer */
  63526. ){
  63527. u32 d1; /* Offset into aKey[] of next data element */
  63528. u32 idx1; /* Offset into aKey[] of next header element */
  63529. u32 szHdr1; /* Number of bytes in header */
  63530. int i = 0;
  63531. int rc = 0;
  63532. const unsigned char *aKey1 = (const unsigned char *)pKey1;
  63533. KeyInfo *pKeyInfo;
  63534. Mem mem1;
  63535. pKeyInfo = pPKey2->pKeyInfo;
  63536. if( pKeyInfo->db==0 ) return 1;
  63537. mem1.enc = pKeyInfo->enc;
  63538. mem1.db = pKeyInfo->db;
  63539. /* mem1.flags = 0; // Will be initialized by sqlite3VdbeSerialGet() */
  63540. VVA_ONLY( mem1.szMalloc = 0; ) /* Only needed by assert() statements */
  63541. /* Compilers may complain that mem1.u.i is potentially uninitialized.
  63542. ** We could initialize it, as shown here, to silence those complaints.
  63543. ** But in fact, mem1.u.i will never actually be used uninitialized, and doing
  63544. ** the unnecessary initialization has a measurable negative performance
  63545. ** impact, since this routine is a very high runner. And so, we choose
  63546. ** to ignore the compiler warnings and leave this variable uninitialized.
  63547. */
  63548. /* mem1.u.i = 0; // not needed, here to silence compiler warning */
  63549. idx1 = getVarint32(aKey1, szHdr1);
  63550. d1 = szHdr1;
  63551. assert( pKeyInfo->nField+pKeyInfo->nXField>=pPKey2->nField || CORRUPT_DB );
  63552. assert( pKeyInfo->aSortOrder!=0 );
  63553. assert( pKeyInfo->nField>0 );
  63554. assert( idx1<=szHdr1 || CORRUPT_DB );
  63555. do{
  63556. u32 serial_type1;
  63557. /* Read the serial types for the next element in each key. */
  63558. idx1 += getVarint32( aKey1+idx1, serial_type1 );
  63559. /* Verify that there is enough key space remaining to avoid
  63560. ** a buffer overread. The "d1+serial_type1+2" subexpression will
  63561. ** always be greater than or equal to the amount of required key space.
  63562. ** Use that approximation to avoid the more expensive call to
  63563. ** sqlite3VdbeSerialTypeLen() in the common case.
  63564. */
  63565. if( d1+serial_type1+2>(u32)nKey1
  63566. && d1+sqlite3VdbeSerialTypeLen(serial_type1)>(u32)nKey1
  63567. ){
  63568. break;
  63569. }
  63570. /* Extract the values to be compared.
  63571. */
  63572. d1 += sqlite3VdbeSerialGet(&aKey1[d1], serial_type1, &mem1);
  63573. /* Do the comparison
  63574. */
  63575. rc = sqlite3MemCompare(&mem1, &pPKey2->aMem[i], pKeyInfo->aColl[i]);
  63576. if( rc!=0 ){
  63577. assert( mem1.szMalloc==0 ); /* See comment below */
  63578. if( pKeyInfo->aSortOrder[i] ){
  63579. rc = -rc; /* Invert the result for DESC sort order. */
  63580. }
  63581. goto debugCompareEnd;
  63582. }
  63583. i++;
  63584. }while( idx1<szHdr1 && i<pPKey2->nField );
  63585. /* No memory allocation is ever used on mem1. Prove this using
  63586. ** the following assert(). If the assert() fails, it indicates a
  63587. ** memory leak and a need to call sqlite3VdbeMemRelease(&mem1).
  63588. */
  63589. assert( mem1.szMalloc==0 );
  63590. /* rc==0 here means that one of the keys ran out of fields and
  63591. ** all the fields up to that point were equal. Return the default_rc
  63592. ** value. */
  63593. rc = pPKey2->default_rc;
  63594. debugCompareEnd:
  63595. if( desiredResult==0 && rc==0 ) return 1;
  63596. if( desiredResult<0 && rc<0 ) return 1;
  63597. if( desiredResult>0 && rc>0 ) return 1;
  63598. if( CORRUPT_DB ) return 1;
  63599. if( pKeyInfo->db->mallocFailed ) return 1;
  63600. return 0;
  63601. }
  63602. #endif
  63603. #if SQLITE_DEBUG
  63604. /*
  63605. ** Count the number of fields (a.k.a. columns) in the record given by
  63606. ** pKey,nKey. The verify that this count is less than or equal to the
  63607. ** limit given by pKeyInfo->nField + pKeyInfo->nXField.
  63608. **
  63609. ** If this constraint is not satisfied, it means that the high-speed
  63610. ** vdbeRecordCompareInt() and vdbeRecordCompareString() routines will
  63611. ** not work correctly. If this assert() ever fires, it probably means
  63612. ** that the KeyInfo.nField or KeyInfo.nXField values were computed
  63613. ** incorrectly.
  63614. */
  63615. static void vdbeAssertFieldCountWithinLimits(
  63616. int nKey, const void *pKey, /* The record to verify */
  63617. const KeyInfo *pKeyInfo /* Compare size with this KeyInfo */
  63618. ){
  63619. int nField = 0;
  63620. u32 szHdr;
  63621. u32 idx;
  63622. u32 notUsed;
  63623. const unsigned char *aKey = (const unsigned char*)pKey;
  63624. if( CORRUPT_DB ) return;
  63625. idx = getVarint32(aKey, szHdr);
  63626. assert( nKey>=0 );
  63627. assert( szHdr<=(u32)nKey );
  63628. while( idx<szHdr ){
  63629. idx += getVarint32(aKey+idx, notUsed);
  63630. nField++;
  63631. }
  63632. assert( nField <= pKeyInfo->nField+pKeyInfo->nXField );
  63633. }
  63634. #else
  63635. # define vdbeAssertFieldCountWithinLimits(A,B,C)
  63636. #endif
  63637. /*
  63638. ** Both *pMem1 and *pMem2 contain string values. Compare the two values
  63639. ** using the collation sequence pColl. As usual, return a negative , zero
  63640. ** or positive value if *pMem1 is less than, equal to or greater than
  63641. ** *pMem2, respectively. Similar in spirit to "rc = (*pMem1) - (*pMem2);".
  63642. */
  63643. static int vdbeCompareMemString(
  63644. const Mem *pMem1,
  63645. const Mem *pMem2,
  63646. const CollSeq *pColl,
  63647. u8 *prcErr /* If an OOM occurs, set to SQLITE_NOMEM */
  63648. ){
  63649. if( pMem1->enc==pColl->enc ){
  63650. /* The strings are already in the correct encoding. Call the
  63651. ** comparison function directly */
  63652. return pColl->xCmp(pColl->pUser,pMem1->n,pMem1->z,pMem2->n,pMem2->z);
  63653. }else{
  63654. int rc;
  63655. const void *v1, *v2;
  63656. int n1, n2;
  63657. Mem c1;
  63658. Mem c2;
  63659. sqlite3VdbeMemInit(&c1, pMem1->db, MEM_Null);
  63660. sqlite3VdbeMemInit(&c2, pMem1->db, MEM_Null);
  63661. sqlite3VdbeMemShallowCopy(&c1, pMem1, MEM_Ephem);
  63662. sqlite3VdbeMemShallowCopy(&c2, pMem2, MEM_Ephem);
  63663. v1 = sqlite3ValueText((sqlite3_value*)&c1, pColl->enc);
  63664. n1 = v1==0 ? 0 : c1.n;
  63665. v2 = sqlite3ValueText((sqlite3_value*)&c2, pColl->enc);
  63666. n2 = v2==0 ? 0 : c2.n;
  63667. rc = pColl->xCmp(pColl->pUser, n1, v1, n2, v2);
  63668. sqlite3VdbeMemRelease(&c1);
  63669. sqlite3VdbeMemRelease(&c2);
  63670. if( (v1==0 || v2==0) && prcErr ) *prcErr = SQLITE_NOMEM;
  63671. return rc;
  63672. }
  63673. }
  63674. /*
  63675. ** Compare two blobs. Return negative, zero, or positive if the first
  63676. ** is less than, equal to, or greater than the second, respectively.
  63677. ** If one blob is a prefix of the other, then the shorter is the lessor.
  63678. */
  63679. static SQLITE_NOINLINE int sqlite3BlobCompare(const Mem *pB1, const Mem *pB2){
  63680. int c = memcmp(pB1->z, pB2->z, pB1->n>pB2->n ? pB2->n : pB1->n);
  63681. if( c ) return c;
  63682. return pB1->n - pB2->n;
  63683. }
  63684. /*
  63685. ** Compare the values contained by the two memory cells, returning
  63686. ** negative, zero or positive if pMem1 is less than, equal to, or greater
  63687. ** than pMem2. Sorting order is NULL's first, followed by numbers (integers
  63688. ** and reals) sorted numerically, followed by text ordered by the collating
  63689. ** sequence pColl and finally blob's ordered by memcmp().
  63690. **
  63691. ** Two NULL values are considered equal by this function.
  63692. */
  63693. SQLITE_PRIVATE int sqlite3MemCompare(const Mem *pMem1, const Mem *pMem2, const CollSeq *pColl){
  63694. int f1, f2;
  63695. int combined_flags;
  63696. f1 = pMem1->flags;
  63697. f2 = pMem2->flags;
  63698. combined_flags = f1|f2;
  63699. assert( (combined_flags & MEM_RowSet)==0 );
  63700. /* If one value is NULL, it is less than the other. If both values
  63701. ** are NULL, return 0.
  63702. */
  63703. if( combined_flags&MEM_Null ){
  63704. return (f2&MEM_Null) - (f1&MEM_Null);
  63705. }
  63706. /* If one value is a number and the other is not, the number is less.
  63707. ** If both are numbers, compare as reals if one is a real, or as integers
  63708. ** if both values are integers.
  63709. */
  63710. if( combined_flags&(MEM_Int|MEM_Real) ){
  63711. double r1, r2;
  63712. if( (f1 & f2 & MEM_Int)!=0 ){
  63713. if( pMem1->u.i < pMem2->u.i ) return -1;
  63714. if( pMem1->u.i > pMem2->u.i ) return 1;
  63715. return 0;
  63716. }
  63717. if( (f1&MEM_Real)!=0 ){
  63718. r1 = pMem1->u.r;
  63719. }else if( (f1&MEM_Int)!=0 ){
  63720. r1 = (double)pMem1->u.i;
  63721. }else{
  63722. return 1;
  63723. }
  63724. if( (f2&MEM_Real)!=0 ){
  63725. r2 = pMem2->u.r;
  63726. }else if( (f2&MEM_Int)!=0 ){
  63727. r2 = (double)pMem2->u.i;
  63728. }else{
  63729. return -1;
  63730. }
  63731. if( r1<r2 ) return -1;
  63732. if( r1>r2 ) return 1;
  63733. return 0;
  63734. }
  63735. /* If one value is a string and the other is a blob, the string is less.
  63736. ** If both are strings, compare using the collating functions.
  63737. */
  63738. if( combined_flags&MEM_Str ){
  63739. if( (f1 & MEM_Str)==0 ){
  63740. return 1;
  63741. }
  63742. if( (f2 & MEM_Str)==0 ){
  63743. return -1;
  63744. }
  63745. assert( pMem1->enc==pMem2->enc );
  63746. assert( pMem1->enc==SQLITE_UTF8 ||
  63747. pMem1->enc==SQLITE_UTF16LE || pMem1->enc==SQLITE_UTF16BE );
  63748. /* The collation sequence must be defined at this point, even if
  63749. ** the user deletes the collation sequence after the vdbe program is
  63750. ** compiled (this was not always the case).
  63751. */
  63752. assert( !pColl || pColl->xCmp );
  63753. if( pColl ){
  63754. return vdbeCompareMemString(pMem1, pMem2, pColl, 0);
  63755. }
  63756. /* If a NULL pointer was passed as the collate function, fall through
  63757. ** to the blob case and use memcmp(). */
  63758. }
  63759. /* Both values must be blobs. Compare using memcmp(). */
  63760. return sqlite3BlobCompare(pMem1, pMem2);
  63761. }
  63762. /*
  63763. ** The first argument passed to this function is a serial-type that
  63764. ** corresponds to an integer - all values between 1 and 9 inclusive
  63765. ** except 7. The second points to a buffer containing an integer value
  63766. ** serialized according to serial_type. This function deserializes
  63767. ** and returns the value.
  63768. */
  63769. static i64 vdbeRecordDecodeInt(u32 serial_type, const u8 *aKey){
  63770. u32 y;
  63771. assert( CORRUPT_DB || (serial_type>=1 && serial_type<=9 && serial_type!=7) );
  63772. switch( serial_type ){
  63773. case 0:
  63774. case 1:
  63775. testcase( aKey[0]&0x80 );
  63776. return ONE_BYTE_INT(aKey);
  63777. case 2:
  63778. testcase( aKey[0]&0x80 );
  63779. return TWO_BYTE_INT(aKey);
  63780. case 3:
  63781. testcase( aKey[0]&0x80 );
  63782. return THREE_BYTE_INT(aKey);
  63783. case 4: {
  63784. testcase( aKey[0]&0x80 );
  63785. y = FOUR_BYTE_UINT(aKey);
  63786. return (i64)*(int*)&y;
  63787. }
  63788. case 5: {
  63789. testcase( aKey[0]&0x80 );
  63790. return FOUR_BYTE_UINT(aKey+2) + (((i64)1)<<32)*TWO_BYTE_INT(aKey);
  63791. }
  63792. case 6: {
  63793. u64 x = FOUR_BYTE_UINT(aKey);
  63794. testcase( aKey[0]&0x80 );
  63795. x = (x<<32) | FOUR_BYTE_UINT(aKey+4);
  63796. return (i64)*(i64*)&x;
  63797. }
  63798. }
  63799. return (serial_type - 8);
  63800. }
  63801. /*
  63802. ** This function compares the two table rows or index records
  63803. ** specified by {nKey1, pKey1} and pPKey2. It returns a negative, zero
  63804. ** or positive integer if key1 is less than, equal to or
  63805. ** greater than key2. The {nKey1, pKey1} key must be a blob
  63806. ** created by the OP_MakeRecord opcode of the VDBE. The pPKey2
  63807. ** key must be a parsed key such as obtained from
  63808. ** sqlite3VdbeParseRecord.
  63809. **
  63810. ** If argument bSkip is non-zero, it is assumed that the caller has already
  63811. ** determined that the first fields of the keys are equal.
  63812. **
  63813. ** Key1 and Key2 do not have to contain the same number of fields. If all
  63814. ** fields that appear in both keys are equal, then pPKey2->default_rc is
  63815. ** returned.
  63816. **
  63817. ** If database corruption is discovered, set pPKey2->errCode to
  63818. ** SQLITE_CORRUPT and return 0. If an OOM error is encountered,
  63819. ** pPKey2->errCode is set to SQLITE_NOMEM and, if it is not NULL, the
  63820. ** malloc-failed flag set on database handle (pPKey2->pKeyInfo->db).
  63821. */
  63822. SQLITE_PRIVATE int sqlite3VdbeRecordCompareWithSkip(
  63823. int nKey1, const void *pKey1, /* Left key */
  63824. UnpackedRecord *pPKey2, /* Right key */
  63825. int bSkip /* If true, skip the first field */
  63826. ){
  63827. u32 d1; /* Offset into aKey[] of next data element */
  63828. int i; /* Index of next field to compare */
  63829. u32 szHdr1; /* Size of record header in bytes */
  63830. u32 idx1; /* Offset of first type in header */
  63831. int rc = 0; /* Return value */
  63832. Mem *pRhs = pPKey2->aMem; /* Next field of pPKey2 to compare */
  63833. KeyInfo *pKeyInfo = pPKey2->pKeyInfo;
  63834. const unsigned char *aKey1 = (const unsigned char *)pKey1;
  63835. Mem mem1;
  63836. /* If bSkip is true, then the caller has already determined that the first
  63837. ** two elements in the keys are equal. Fix the various stack variables so
  63838. ** that this routine begins comparing at the second field. */
  63839. if( bSkip ){
  63840. u32 s1;
  63841. idx1 = 1 + getVarint32(&aKey1[1], s1);
  63842. szHdr1 = aKey1[0];
  63843. d1 = szHdr1 + sqlite3VdbeSerialTypeLen(s1);
  63844. i = 1;
  63845. pRhs++;
  63846. }else{
  63847. idx1 = getVarint32(aKey1, szHdr1);
  63848. d1 = szHdr1;
  63849. if( d1>(unsigned)nKey1 ){
  63850. pPKey2->errCode = (u8)SQLITE_CORRUPT_BKPT;
  63851. return 0; /* Corruption */
  63852. }
  63853. i = 0;
  63854. }
  63855. VVA_ONLY( mem1.szMalloc = 0; ) /* Only needed by assert() statements */
  63856. assert( pPKey2->pKeyInfo->nField+pPKey2->pKeyInfo->nXField>=pPKey2->nField
  63857. || CORRUPT_DB );
  63858. assert( pPKey2->pKeyInfo->aSortOrder!=0 );
  63859. assert( pPKey2->pKeyInfo->nField>0 );
  63860. assert( idx1<=szHdr1 || CORRUPT_DB );
  63861. do{
  63862. u32 serial_type;
  63863. /* RHS is an integer */
  63864. if( pRhs->flags & MEM_Int ){
  63865. serial_type = aKey1[idx1];
  63866. testcase( serial_type==12 );
  63867. if( serial_type>=12 ){
  63868. rc = +1;
  63869. }else if( serial_type==0 ){
  63870. rc = -1;
  63871. }else if( serial_type==7 ){
  63872. double rhs = (double)pRhs->u.i;
  63873. sqlite3VdbeSerialGet(&aKey1[d1], serial_type, &mem1);
  63874. if( mem1.u.r<rhs ){
  63875. rc = -1;
  63876. }else if( mem1.u.r>rhs ){
  63877. rc = +1;
  63878. }
  63879. }else{
  63880. i64 lhs = vdbeRecordDecodeInt(serial_type, &aKey1[d1]);
  63881. i64 rhs = pRhs->u.i;
  63882. if( lhs<rhs ){
  63883. rc = -1;
  63884. }else if( lhs>rhs ){
  63885. rc = +1;
  63886. }
  63887. }
  63888. }
  63889. /* RHS is real */
  63890. else if( pRhs->flags & MEM_Real ){
  63891. serial_type = aKey1[idx1];
  63892. if( serial_type>=12 ){
  63893. rc = +1;
  63894. }else if( serial_type==0 ){
  63895. rc = -1;
  63896. }else{
  63897. double rhs = pRhs->u.r;
  63898. double lhs;
  63899. sqlite3VdbeSerialGet(&aKey1[d1], serial_type, &mem1);
  63900. if( serial_type==7 ){
  63901. lhs = mem1.u.r;
  63902. }else{
  63903. lhs = (double)mem1.u.i;
  63904. }
  63905. if( lhs<rhs ){
  63906. rc = -1;
  63907. }else if( lhs>rhs ){
  63908. rc = +1;
  63909. }
  63910. }
  63911. }
  63912. /* RHS is a string */
  63913. else if( pRhs->flags & MEM_Str ){
  63914. getVarint32(&aKey1[idx1], serial_type);
  63915. testcase( serial_type==12 );
  63916. if( serial_type<12 ){
  63917. rc = -1;
  63918. }else if( !(serial_type & 0x01) ){
  63919. rc = +1;
  63920. }else{
  63921. mem1.n = (serial_type - 12) / 2;
  63922. testcase( (d1+mem1.n)==(unsigned)nKey1 );
  63923. testcase( (d1+mem1.n+1)==(unsigned)nKey1 );
  63924. if( (d1+mem1.n) > (unsigned)nKey1 ){
  63925. pPKey2->errCode = (u8)SQLITE_CORRUPT_BKPT;
  63926. return 0; /* Corruption */
  63927. }else if( pKeyInfo->aColl[i] ){
  63928. mem1.enc = pKeyInfo->enc;
  63929. mem1.db = pKeyInfo->db;
  63930. mem1.flags = MEM_Str;
  63931. mem1.z = (char*)&aKey1[d1];
  63932. rc = vdbeCompareMemString(
  63933. &mem1, pRhs, pKeyInfo->aColl[i], &pPKey2->errCode
  63934. );
  63935. }else{
  63936. int nCmp = MIN(mem1.n, pRhs->n);
  63937. rc = memcmp(&aKey1[d1], pRhs->z, nCmp);
  63938. if( rc==0 ) rc = mem1.n - pRhs->n;
  63939. }
  63940. }
  63941. }
  63942. /* RHS is a blob */
  63943. else if( pRhs->flags & MEM_Blob ){
  63944. getVarint32(&aKey1[idx1], serial_type);
  63945. testcase( serial_type==12 );
  63946. if( serial_type<12 || (serial_type & 0x01) ){
  63947. rc = -1;
  63948. }else{
  63949. int nStr = (serial_type - 12) / 2;
  63950. testcase( (d1+nStr)==(unsigned)nKey1 );
  63951. testcase( (d1+nStr+1)==(unsigned)nKey1 );
  63952. if( (d1+nStr) > (unsigned)nKey1 ){
  63953. pPKey2->errCode = (u8)SQLITE_CORRUPT_BKPT;
  63954. return 0; /* Corruption */
  63955. }else{
  63956. int nCmp = MIN(nStr, pRhs->n);
  63957. rc = memcmp(&aKey1[d1], pRhs->z, nCmp);
  63958. if( rc==0 ) rc = nStr - pRhs->n;
  63959. }
  63960. }
  63961. }
  63962. /* RHS is null */
  63963. else{
  63964. serial_type = aKey1[idx1];
  63965. rc = (serial_type!=0);
  63966. }
  63967. if( rc!=0 ){
  63968. if( pKeyInfo->aSortOrder[i] ){
  63969. rc = -rc;
  63970. }
  63971. assert( vdbeRecordCompareDebug(nKey1, pKey1, pPKey2, rc) );
  63972. assert( mem1.szMalloc==0 ); /* See comment below */
  63973. return rc;
  63974. }
  63975. i++;
  63976. pRhs++;
  63977. d1 += sqlite3VdbeSerialTypeLen(serial_type);
  63978. idx1 += sqlite3VarintLen(serial_type);
  63979. }while( idx1<(unsigned)szHdr1 && i<pPKey2->nField && d1<=(unsigned)nKey1 );
  63980. /* No memory allocation is ever used on mem1. Prove this using
  63981. ** the following assert(). If the assert() fails, it indicates a
  63982. ** memory leak and a need to call sqlite3VdbeMemRelease(&mem1). */
  63983. assert( mem1.szMalloc==0 );
  63984. /* rc==0 here means that one or both of the keys ran out of fields and
  63985. ** all the fields up to that point were equal. Return the default_rc
  63986. ** value. */
  63987. assert( CORRUPT_DB
  63988. || vdbeRecordCompareDebug(nKey1, pKey1, pPKey2, pPKey2->default_rc)
  63989. || pKeyInfo->db->mallocFailed
  63990. );
  63991. return pPKey2->default_rc;
  63992. }
  63993. SQLITE_PRIVATE int sqlite3VdbeRecordCompare(
  63994. int nKey1, const void *pKey1, /* Left key */
  63995. UnpackedRecord *pPKey2 /* Right key */
  63996. ){
  63997. return sqlite3VdbeRecordCompareWithSkip(nKey1, pKey1, pPKey2, 0);
  63998. }
  63999. /*
  64000. ** This function is an optimized version of sqlite3VdbeRecordCompare()
  64001. ** that (a) the first field of pPKey2 is an integer, and (b) the
  64002. ** size-of-header varint at the start of (pKey1/nKey1) fits in a single
  64003. ** byte (i.e. is less than 128).
  64004. **
  64005. ** To avoid concerns about buffer overreads, this routine is only used
  64006. ** on schemas where the maximum valid header size is 63 bytes or less.
  64007. */
  64008. static int vdbeRecordCompareInt(
  64009. int nKey1, const void *pKey1, /* Left key */
  64010. UnpackedRecord *pPKey2 /* Right key */
  64011. ){
  64012. const u8 *aKey = &((const u8*)pKey1)[*(const u8*)pKey1 & 0x3F];
  64013. int serial_type = ((const u8*)pKey1)[1];
  64014. int res;
  64015. u32 y;
  64016. u64 x;
  64017. i64 v = pPKey2->aMem[0].u.i;
  64018. i64 lhs;
  64019. vdbeAssertFieldCountWithinLimits(nKey1, pKey1, pPKey2->pKeyInfo);
  64020. assert( (*(u8*)pKey1)<=0x3F || CORRUPT_DB );
  64021. switch( serial_type ){
  64022. case 1: { /* 1-byte signed integer */
  64023. lhs = ONE_BYTE_INT(aKey);
  64024. testcase( lhs<0 );
  64025. break;
  64026. }
  64027. case 2: { /* 2-byte signed integer */
  64028. lhs = TWO_BYTE_INT(aKey);
  64029. testcase( lhs<0 );
  64030. break;
  64031. }
  64032. case 3: { /* 3-byte signed integer */
  64033. lhs = THREE_BYTE_INT(aKey);
  64034. testcase( lhs<0 );
  64035. break;
  64036. }
  64037. case 4: { /* 4-byte signed integer */
  64038. y = FOUR_BYTE_UINT(aKey);
  64039. lhs = (i64)*(int*)&y;
  64040. testcase( lhs<0 );
  64041. break;
  64042. }
  64043. case 5: { /* 6-byte signed integer */
  64044. lhs = FOUR_BYTE_UINT(aKey+2) + (((i64)1)<<32)*TWO_BYTE_INT(aKey);
  64045. testcase( lhs<0 );
  64046. break;
  64047. }
  64048. case 6: { /* 8-byte signed integer */
  64049. x = FOUR_BYTE_UINT(aKey);
  64050. x = (x<<32) | FOUR_BYTE_UINT(aKey+4);
  64051. lhs = *(i64*)&x;
  64052. testcase( lhs<0 );
  64053. break;
  64054. }
  64055. case 8:
  64056. lhs = 0;
  64057. break;
  64058. case 9:
  64059. lhs = 1;
  64060. break;
  64061. /* This case could be removed without changing the results of running
  64062. ** this code. Including it causes gcc to generate a faster switch
  64063. ** statement (since the range of switch targets now starts at zero and
  64064. ** is contiguous) but does not cause any duplicate code to be generated
  64065. ** (as gcc is clever enough to combine the two like cases). Other
  64066. ** compilers might be similar. */
  64067. case 0: case 7:
  64068. return sqlite3VdbeRecordCompare(nKey1, pKey1, pPKey2);
  64069. default:
  64070. return sqlite3VdbeRecordCompare(nKey1, pKey1, pPKey2);
  64071. }
  64072. if( v>lhs ){
  64073. res = pPKey2->r1;
  64074. }else if( v<lhs ){
  64075. res = pPKey2->r2;
  64076. }else if( pPKey2->nField>1 ){
  64077. /* The first fields of the two keys are equal. Compare the trailing
  64078. ** fields. */
  64079. res = sqlite3VdbeRecordCompareWithSkip(nKey1, pKey1, pPKey2, 1);
  64080. }else{
  64081. /* The first fields of the two keys are equal and there are no trailing
  64082. ** fields. Return pPKey2->default_rc in this case. */
  64083. res = pPKey2->default_rc;
  64084. }
  64085. assert( vdbeRecordCompareDebug(nKey1, pKey1, pPKey2, res) );
  64086. return res;
  64087. }
  64088. /*
  64089. ** This function is an optimized version of sqlite3VdbeRecordCompare()
  64090. ** that (a) the first field of pPKey2 is a string, that (b) the first field
  64091. ** uses the collation sequence BINARY and (c) that the size-of-header varint
  64092. ** at the start of (pKey1/nKey1) fits in a single byte.
  64093. */
  64094. static int vdbeRecordCompareString(
  64095. int nKey1, const void *pKey1, /* Left key */
  64096. UnpackedRecord *pPKey2 /* Right key */
  64097. ){
  64098. const u8 *aKey1 = (const u8*)pKey1;
  64099. int serial_type;
  64100. int res;
  64101. vdbeAssertFieldCountWithinLimits(nKey1, pKey1, pPKey2->pKeyInfo);
  64102. getVarint32(&aKey1[1], serial_type);
  64103. if( serial_type<12 ){
  64104. res = pPKey2->r1; /* (pKey1/nKey1) is a number or a null */
  64105. }else if( !(serial_type & 0x01) ){
  64106. res = pPKey2->r2; /* (pKey1/nKey1) is a blob */
  64107. }else{
  64108. int nCmp;
  64109. int nStr;
  64110. int szHdr = aKey1[0];
  64111. nStr = (serial_type-12) / 2;
  64112. if( (szHdr + nStr) > nKey1 ){
  64113. pPKey2->errCode = (u8)SQLITE_CORRUPT_BKPT;
  64114. return 0; /* Corruption */
  64115. }
  64116. nCmp = MIN( pPKey2->aMem[0].n, nStr );
  64117. res = memcmp(&aKey1[szHdr], pPKey2->aMem[0].z, nCmp);
  64118. if( res==0 ){
  64119. res = nStr - pPKey2->aMem[0].n;
  64120. if( res==0 ){
  64121. if( pPKey2->nField>1 ){
  64122. res = sqlite3VdbeRecordCompareWithSkip(nKey1, pKey1, pPKey2, 1);
  64123. }else{
  64124. res = pPKey2->default_rc;
  64125. }
  64126. }else if( res>0 ){
  64127. res = pPKey2->r2;
  64128. }else{
  64129. res = pPKey2->r1;
  64130. }
  64131. }else if( res>0 ){
  64132. res = pPKey2->r2;
  64133. }else{
  64134. res = pPKey2->r1;
  64135. }
  64136. }
  64137. assert( vdbeRecordCompareDebug(nKey1, pKey1, pPKey2, res)
  64138. || CORRUPT_DB
  64139. || pPKey2->pKeyInfo->db->mallocFailed
  64140. );
  64141. return res;
  64142. }
  64143. /*
  64144. ** Return a pointer to an sqlite3VdbeRecordCompare() compatible function
  64145. ** suitable for comparing serialized records to the unpacked record passed
  64146. ** as the only argument.
  64147. */
  64148. SQLITE_PRIVATE RecordCompare sqlite3VdbeFindCompare(UnpackedRecord *p){
  64149. /* varintRecordCompareInt() and varintRecordCompareString() both assume
  64150. ** that the size-of-header varint that occurs at the start of each record
  64151. ** fits in a single byte (i.e. is 127 or less). varintRecordCompareInt()
  64152. ** also assumes that it is safe to overread a buffer by at least the
  64153. ** maximum possible legal header size plus 8 bytes. Because there is
  64154. ** guaranteed to be at least 74 (but not 136) bytes of padding following each
  64155. ** buffer passed to varintRecordCompareInt() this makes it convenient to
  64156. ** limit the size of the header to 64 bytes in cases where the first field
  64157. ** is an integer.
  64158. **
  64159. ** The easiest way to enforce this limit is to consider only records with
  64160. ** 13 fields or less. If the first field is an integer, the maximum legal
  64161. ** header size is (12*5 + 1 + 1) bytes. */
  64162. if( (p->pKeyInfo->nField + p->pKeyInfo->nXField)<=13 ){
  64163. int flags = p->aMem[0].flags;
  64164. if( p->pKeyInfo->aSortOrder[0] ){
  64165. p->r1 = 1;
  64166. p->r2 = -1;
  64167. }else{
  64168. p->r1 = -1;
  64169. p->r2 = 1;
  64170. }
  64171. if( (flags & MEM_Int) ){
  64172. return vdbeRecordCompareInt;
  64173. }
  64174. testcase( flags & MEM_Real );
  64175. testcase( flags & MEM_Null );
  64176. testcase( flags & MEM_Blob );
  64177. if( (flags & (MEM_Real|MEM_Null|MEM_Blob))==0 && p->pKeyInfo->aColl[0]==0 ){
  64178. assert( flags & MEM_Str );
  64179. return vdbeRecordCompareString;
  64180. }
  64181. }
  64182. return sqlite3VdbeRecordCompare;
  64183. }
  64184. /*
  64185. ** pCur points at an index entry created using the OP_MakeRecord opcode.
  64186. ** Read the rowid (the last field in the record) and store it in *rowid.
  64187. ** Return SQLITE_OK if everything works, or an error code otherwise.
  64188. **
  64189. ** pCur might be pointing to text obtained from a corrupt database file.
  64190. ** So the content cannot be trusted. Do appropriate checks on the content.
  64191. */
  64192. SQLITE_PRIVATE int sqlite3VdbeIdxRowid(sqlite3 *db, BtCursor *pCur, i64 *rowid){
  64193. i64 nCellKey = 0;
  64194. int rc;
  64195. u32 szHdr; /* Size of the header */
  64196. u32 typeRowid; /* Serial type of the rowid */
  64197. u32 lenRowid; /* Size of the rowid */
  64198. Mem m, v;
  64199. /* Get the size of the index entry. Only indices entries of less
  64200. ** than 2GiB are support - anything large must be database corruption.
  64201. ** Any corruption is detected in sqlite3BtreeParseCellPtr(), though, so
  64202. ** this code can safely assume that nCellKey is 32-bits
  64203. */
  64204. assert( sqlite3BtreeCursorIsValid(pCur) );
  64205. VVA_ONLY(rc =) sqlite3BtreeKeySize(pCur, &nCellKey);
  64206. assert( rc==SQLITE_OK ); /* pCur is always valid so KeySize cannot fail */
  64207. assert( (nCellKey & SQLITE_MAX_U32)==(u64)nCellKey );
  64208. /* Read in the complete content of the index entry */
  64209. sqlite3VdbeMemInit(&m, db, 0);
  64210. rc = sqlite3VdbeMemFromBtree(pCur, 0, (u32)nCellKey, 1, &m);
  64211. if( rc ){
  64212. return rc;
  64213. }
  64214. /* The index entry must begin with a header size */
  64215. (void)getVarint32((u8*)m.z, szHdr);
  64216. testcase( szHdr==3 );
  64217. testcase( szHdr==m.n );
  64218. if( unlikely(szHdr<3 || (int)szHdr>m.n) ){
  64219. goto idx_rowid_corruption;
  64220. }
  64221. /* The last field of the index should be an integer - the ROWID.
  64222. ** Verify that the last entry really is an integer. */
  64223. (void)getVarint32((u8*)&m.z[szHdr-1], typeRowid);
  64224. testcase( typeRowid==1 );
  64225. testcase( typeRowid==2 );
  64226. testcase( typeRowid==3 );
  64227. testcase( typeRowid==4 );
  64228. testcase( typeRowid==5 );
  64229. testcase( typeRowid==6 );
  64230. testcase( typeRowid==8 );
  64231. testcase( typeRowid==9 );
  64232. if( unlikely(typeRowid<1 || typeRowid>9 || typeRowid==7) ){
  64233. goto idx_rowid_corruption;
  64234. }
  64235. lenRowid = sqlite3VdbeSerialTypeLen(typeRowid);
  64236. testcase( (u32)m.n==szHdr+lenRowid );
  64237. if( unlikely((u32)m.n<szHdr+lenRowid) ){
  64238. goto idx_rowid_corruption;
  64239. }
  64240. /* Fetch the integer off the end of the index record */
  64241. sqlite3VdbeSerialGet((u8*)&m.z[m.n-lenRowid], typeRowid, &v);
  64242. *rowid = v.u.i;
  64243. sqlite3VdbeMemRelease(&m);
  64244. return SQLITE_OK;
  64245. /* Jump here if database corruption is detected after m has been
  64246. ** allocated. Free the m object and return SQLITE_CORRUPT. */
  64247. idx_rowid_corruption:
  64248. testcase( m.szMalloc!=0 );
  64249. sqlite3VdbeMemRelease(&m);
  64250. return SQLITE_CORRUPT_BKPT;
  64251. }
  64252. /*
  64253. ** Compare the key of the index entry that cursor pC is pointing to against
  64254. ** the key string in pUnpacked. Write into *pRes a number
  64255. ** that is negative, zero, or positive if pC is less than, equal to,
  64256. ** or greater than pUnpacked. Return SQLITE_OK on success.
  64257. **
  64258. ** pUnpacked is either created without a rowid or is truncated so that it
  64259. ** omits the rowid at the end. The rowid at the end of the index entry
  64260. ** is ignored as well. Hence, this routine only compares the prefixes
  64261. ** of the keys prior to the final rowid, not the entire key.
  64262. */
  64263. SQLITE_PRIVATE int sqlite3VdbeIdxKeyCompare(
  64264. sqlite3 *db, /* Database connection */
  64265. VdbeCursor *pC, /* The cursor to compare against */
  64266. UnpackedRecord *pUnpacked, /* Unpacked version of key */
  64267. int *res /* Write the comparison result here */
  64268. ){
  64269. i64 nCellKey = 0;
  64270. int rc;
  64271. BtCursor *pCur = pC->pCursor;
  64272. Mem m;
  64273. assert( sqlite3BtreeCursorIsValid(pCur) );
  64274. VVA_ONLY(rc =) sqlite3BtreeKeySize(pCur, &nCellKey);
  64275. assert( rc==SQLITE_OK ); /* pCur is always valid so KeySize cannot fail */
  64276. /* nCellKey will always be between 0 and 0xffffffff because of the way
  64277. ** that btreeParseCellPtr() and sqlite3GetVarint32() are implemented */
  64278. if( nCellKey<=0 || nCellKey>0x7fffffff ){
  64279. *res = 0;
  64280. return SQLITE_CORRUPT_BKPT;
  64281. }
  64282. sqlite3VdbeMemInit(&m, db, 0);
  64283. rc = sqlite3VdbeMemFromBtree(pC->pCursor, 0, (u32)nCellKey, 1, &m);
  64284. if( rc ){
  64285. return rc;
  64286. }
  64287. *res = sqlite3VdbeRecordCompare(m.n, m.z, pUnpacked);
  64288. sqlite3VdbeMemRelease(&m);
  64289. return SQLITE_OK;
  64290. }
  64291. /*
  64292. ** This routine sets the value to be returned by subsequent calls to
  64293. ** sqlite3_changes() on the database handle 'db'.
  64294. */
  64295. SQLITE_PRIVATE void sqlite3VdbeSetChanges(sqlite3 *db, int nChange){
  64296. assert( sqlite3_mutex_held(db->mutex) );
  64297. db->nChange = nChange;
  64298. db->nTotalChange += nChange;
  64299. }
  64300. /*
  64301. ** Set a flag in the vdbe to update the change counter when it is finalised
  64302. ** or reset.
  64303. */
  64304. SQLITE_PRIVATE void sqlite3VdbeCountChanges(Vdbe *v){
  64305. v->changeCntOn = 1;
  64306. }
  64307. /*
  64308. ** Mark every prepared statement associated with a database connection
  64309. ** as expired.
  64310. **
  64311. ** An expired statement means that recompilation of the statement is
  64312. ** recommend. Statements expire when things happen that make their
  64313. ** programs obsolete. Removing user-defined functions or collating
  64314. ** sequences, or changing an authorization function are the types of
  64315. ** things that make prepared statements obsolete.
  64316. */
  64317. SQLITE_PRIVATE void sqlite3ExpirePreparedStatements(sqlite3 *db){
  64318. Vdbe *p;
  64319. for(p = db->pVdbe; p; p=p->pNext){
  64320. p->expired = 1;
  64321. }
  64322. }
  64323. /*
  64324. ** Return the database associated with the Vdbe.
  64325. */
  64326. SQLITE_PRIVATE sqlite3 *sqlite3VdbeDb(Vdbe *v){
  64327. return v->db;
  64328. }
  64329. /*
  64330. ** Return a pointer to an sqlite3_value structure containing the value bound
  64331. ** parameter iVar of VM v. Except, if the value is an SQL NULL, return
  64332. ** 0 instead. Unless it is NULL, apply affinity aff (one of the SQLITE_AFF_*
  64333. ** constants) to the value before returning it.
  64334. **
  64335. ** The returned value must be freed by the caller using sqlite3ValueFree().
  64336. */
  64337. SQLITE_PRIVATE sqlite3_value *sqlite3VdbeGetBoundValue(Vdbe *v, int iVar, u8 aff){
  64338. assert( iVar>0 );
  64339. if( v ){
  64340. Mem *pMem = &v->aVar[iVar-1];
  64341. if( 0==(pMem->flags & MEM_Null) ){
  64342. sqlite3_value *pRet = sqlite3ValueNew(v->db);
  64343. if( pRet ){
  64344. sqlite3VdbeMemCopy((Mem *)pRet, pMem);
  64345. sqlite3ValueApplyAffinity(pRet, aff, SQLITE_UTF8);
  64346. }
  64347. return pRet;
  64348. }
  64349. }
  64350. return 0;
  64351. }
  64352. /*
  64353. ** Configure SQL variable iVar so that binding a new value to it signals
  64354. ** to sqlite3_reoptimize() that re-preparing the statement may result
  64355. ** in a better query plan.
  64356. */
  64357. SQLITE_PRIVATE void sqlite3VdbeSetVarmask(Vdbe *v, int iVar){
  64358. assert( iVar>0 );
  64359. if( iVar>32 ){
  64360. v->expmask = 0xffffffff;
  64361. }else{
  64362. v->expmask |= ((u32)1 << (iVar-1));
  64363. }
  64364. }
  64365. #ifndef SQLITE_OMIT_VIRTUALTABLE
  64366. /*
  64367. ** Transfer error message text from an sqlite3_vtab.zErrMsg (text stored
  64368. ** in memory obtained from sqlite3_malloc) into a Vdbe.zErrMsg (text stored
  64369. ** in memory obtained from sqlite3DbMalloc).
  64370. */
  64371. SQLITE_PRIVATE void sqlite3VtabImportErrmsg(Vdbe *p, sqlite3_vtab *pVtab){
  64372. sqlite3 *db = p->db;
  64373. sqlite3DbFree(db, p->zErrMsg);
  64374. p->zErrMsg = sqlite3DbStrDup(db, pVtab->zErrMsg);
  64375. sqlite3_free(pVtab->zErrMsg);
  64376. pVtab->zErrMsg = 0;
  64377. }
  64378. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  64379. /************** End of vdbeaux.c *********************************************/
  64380. /************** Begin file vdbeapi.c *****************************************/
  64381. /*
  64382. ** 2004 May 26
  64383. **
  64384. ** The author disclaims copyright to this source code. In place of
  64385. ** a legal notice, here is a blessing:
  64386. **
  64387. ** May you do good and not evil.
  64388. ** May you find forgiveness for yourself and forgive others.
  64389. ** May you share freely, never taking more than you give.
  64390. **
  64391. *************************************************************************
  64392. **
  64393. ** This file contains code use to implement APIs that are part of the
  64394. ** VDBE.
  64395. */
  64396. #ifndef SQLITE_OMIT_DEPRECATED
  64397. /*
  64398. ** Return TRUE (non-zero) of the statement supplied as an argument needs
  64399. ** to be recompiled. A statement needs to be recompiled whenever the
  64400. ** execution environment changes in a way that would alter the program
  64401. ** that sqlite3_prepare() generates. For example, if new functions or
  64402. ** collating sequences are registered or if an authorizer function is
  64403. ** added or changed.
  64404. */
  64405. SQLITE_API int SQLITE_STDCALL sqlite3_expired(sqlite3_stmt *pStmt){
  64406. Vdbe *p = (Vdbe*)pStmt;
  64407. return p==0 || p->expired;
  64408. }
  64409. #endif
  64410. /*
  64411. ** Check on a Vdbe to make sure it has not been finalized. Log
  64412. ** an error and return true if it has been finalized (or is otherwise
  64413. ** invalid). Return false if it is ok.
  64414. */
  64415. static int vdbeSafety(Vdbe *p){
  64416. if( p->db==0 ){
  64417. sqlite3_log(SQLITE_MISUSE, "API called with finalized prepared statement");
  64418. return 1;
  64419. }else{
  64420. return 0;
  64421. }
  64422. }
  64423. static int vdbeSafetyNotNull(Vdbe *p){
  64424. if( p==0 ){
  64425. sqlite3_log(SQLITE_MISUSE, "API called with NULL prepared statement");
  64426. return 1;
  64427. }else{
  64428. return vdbeSafety(p);
  64429. }
  64430. }
  64431. /*
  64432. ** The following routine destroys a virtual machine that is created by
  64433. ** the sqlite3_compile() routine. The integer returned is an SQLITE_
  64434. ** success/failure code that describes the result of executing the virtual
  64435. ** machine.
  64436. **
  64437. ** This routine sets the error code and string returned by
  64438. ** sqlite3_errcode(), sqlite3_errmsg() and sqlite3_errmsg16().
  64439. */
  64440. SQLITE_API int SQLITE_STDCALL sqlite3_finalize(sqlite3_stmt *pStmt){
  64441. int rc;
  64442. if( pStmt==0 ){
  64443. /* IMPLEMENTATION-OF: R-57228-12904 Invoking sqlite3_finalize() on a NULL
  64444. ** pointer is a harmless no-op. */
  64445. rc = SQLITE_OK;
  64446. }else{
  64447. Vdbe *v = (Vdbe*)pStmt;
  64448. sqlite3 *db = v->db;
  64449. if( vdbeSafety(v) ) return SQLITE_MISUSE_BKPT;
  64450. sqlite3_mutex_enter(db->mutex);
  64451. rc = sqlite3VdbeFinalize(v);
  64452. rc = sqlite3ApiExit(db, rc);
  64453. sqlite3LeaveMutexAndCloseZombie(db);
  64454. }
  64455. return rc;
  64456. }
  64457. /*
  64458. ** Terminate the current execution of an SQL statement and reset it
  64459. ** back to its starting state so that it can be reused. A success code from
  64460. ** the prior execution is returned.
  64461. **
  64462. ** This routine sets the error code and string returned by
  64463. ** sqlite3_errcode(), sqlite3_errmsg() and sqlite3_errmsg16().
  64464. */
  64465. SQLITE_API int SQLITE_STDCALL sqlite3_reset(sqlite3_stmt *pStmt){
  64466. int rc;
  64467. if( pStmt==0 ){
  64468. rc = SQLITE_OK;
  64469. }else{
  64470. Vdbe *v = (Vdbe*)pStmt;
  64471. sqlite3_mutex_enter(v->db->mutex);
  64472. rc = sqlite3VdbeReset(v);
  64473. sqlite3VdbeRewind(v);
  64474. assert( (rc & (v->db->errMask))==rc );
  64475. rc = sqlite3ApiExit(v->db, rc);
  64476. sqlite3_mutex_leave(v->db->mutex);
  64477. }
  64478. return rc;
  64479. }
  64480. /*
  64481. ** Set all the parameters in the compiled SQL statement to NULL.
  64482. */
  64483. SQLITE_API int SQLITE_STDCALL sqlite3_clear_bindings(sqlite3_stmt *pStmt){
  64484. int i;
  64485. int rc = SQLITE_OK;
  64486. Vdbe *p = (Vdbe*)pStmt;
  64487. #if SQLITE_THREADSAFE
  64488. sqlite3_mutex *mutex = ((Vdbe*)pStmt)->db->mutex;
  64489. #endif
  64490. sqlite3_mutex_enter(mutex);
  64491. for(i=0; i<p->nVar; i++){
  64492. sqlite3VdbeMemRelease(&p->aVar[i]);
  64493. p->aVar[i].flags = MEM_Null;
  64494. }
  64495. if( p->isPrepareV2 && p->expmask ){
  64496. p->expired = 1;
  64497. }
  64498. sqlite3_mutex_leave(mutex);
  64499. return rc;
  64500. }
  64501. /**************************** sqlite3_value_ *******************************
  64502. ** The following routines extract information from a Mem or sqlite3_value
  64503. ** structure.
  64504. */
  64505. SQLITE_API const void *SQLITE_STDCALL sqlite3_value_blob(sqlite3_value *pVal){
  64506. Mem *p = (Mem*)pVal;
  64507. if( p->flags & (MEM_Blob|MEM_Str) ){
  64508. sqlite3VdbeMemExpandBlob(p);
  64509. p->flags |= MEM_Blob;
  64510. return p->n ? p->z : 0;
  64511. }else{
  64512. return sqlite3_value_text(pVal);
  64513. }
  64514. }
  64515. SQLITE_API int SQLITE_STDCALL sqlite3_value_bytes(sqlite3_value *pVal){
  64516. return sqlite3ValueBytes(pVal, SQLITE_UTF8);
  64517. }
  64518. SQLITE_API int SQLITE_STDCALL sqlite3_value_bytes16(sqlite3_value *pVal){
  64519. return sqlite3ValueBytes(pVal, SQLITE_UTF16NATIVE);
  64520. }
  64521. SQLITE_API double SQLITE_STDCALL sqlite3_value_double(sqlite3_value *pVal){
  64522. return sqlite3VdbeRealValue((Mem*)pVal);
  64523. }
  64524. SQLITE_API int SQLITE_STDCALL sqlite3_value_int(sqlite3_value *pVal){
  64525. return (int)sqlite3VdbeIntValue((Mem*)pVal);
  64526. }
  64527. SQLITE_API sqlite_int64 SQLITE_STDCALL sqlite3_value_int64(sqlite3_value *pVal){
  64528. return sqlite3VdbeIntValue((Mem*)pVal);
  64529. }
  64530. SQLITE_API const unsigned char *SQLITE_STDCALL sqlite3_value_text(sqlite3_value *pVal){
  64531. return (const unsigned char *)sqlite3ValueText(pVal, SQLITE_UTF8);
  64532. }
  64533. #ifndef SQLITE_OMIT_UTF16
  64534. SQLITE_API const void *SQLITE_STDCALL sqlite3_value_text16(sqlite3_value* pVal){
  64535. return sqlite3ValueText(pVal, SQLITE_UTF16NATIVE);
  64536. }
  64537. SQLITE_API const void *SQLITE_STDCALL sqlite3_value_text16be(sqlite3_value *pVal){
  64538. return sqlite3ValueText(pVal, SQLITE_UTF16BE);
  64539. }
  64540. SQLITE_API const void *SQLITE_STDCALL sqlite3_value_text16le(sqlite3_value *pVal){
  64541. return sqlite3ValueText(pVal, SQLITE_UTF16LE);
  64542. }
  64543. #endif /* SQLITE_OMIT_UTF16 */
  64544. /* EVIDENCE-OF: R-12793-43283 Every value in SQLite has one of five
  64545. ** fundamental datatypes: 64-bit signed integer 64-bit IEEE floating
  64546. ** point number string BLOB NULL
  64547. */
  64548. SQLITE_API int SQLITE_STDCALL sqlite3_value_type(sqlite3_value* pVal){
  64549. static const u8 aType[] = {
  64550. SQLITE_BLOB, /* 0x00 */
  64551. SQLITE_NULL, /* 0x01 */
  64552. SQLITE_TEXT, /* 0x02 */
  64553. SQLITE_NULL, /* 0x03 */
  64554. SQLITE_INTEGER, /* 0x04 */
  64555. SQLITE_NULL, /* 0x05 */
  64556. SQLITE_INTEGER, /* 0x06 */
  64557. SQLITE_NULL, /* 0x07 */
  64558. SQLITE_FLOAT, /* 0x08 */
  64559. SQLITE_NULL, /* 0x09 */
  64560. SQLITE_FLOAT, /* 0x0a */
  64561. SQLITE_NULL, /* 0x0b */
  64562. SQLITE_INTEGER, /* 0x0c */
  64563. SQLITE_NULL, /* 0x0d */
  64564. SQLITE_INTEGER, /* 0x0e */
  64565. SQLITE_NULL, /* 0x0f */
  64566. SQLITE_BLOB, /* 0x10 */
  64567. SQLITE_NULL, /* 0x11 */
  64568. SQLITE_TEXT, /* 0x12 */
  64569. SQLITE_NULL, /* 0x13 */
  64570. SQLITE_INTEGER, /* 0x14 */
  64571. SQLITE_NULL, /* 0x15 */
  64572. SQLITE_INTEGER, /* 0x16 */
  64573. SQLITE_NULL, /* 0x17 */
  64574. SQLITE_FLOAT, /* 0x18 */
  64575. SQLITE_NULL, /* 0x19 */
  64576. SQLITE_FLOAT, /* 0x1a */
  64577. SQLITE_NULL, /* 0x1b */
  64578. SQLITE_INTEGER, /* 0x1c */
  64579. SQLITE_NULL, /* 0x1d */
  64580. SQLITE_INTEGER, /* 0x1e */
  64581. SQLITE_NULL, /* 0x1f */
  64582. };
  64583. return aType[pVal->flags&MEM_AffMask];
  64584. }
  64585. /**************************** sqlite3_result_ *******************************
  64586. ** The following routines are used by user-defined functions to specify
  64587. ** the function result.
  64588. **
  64589. ** The setStrOrError() function calls sqlite3VdbeMemSetStr() to store the
  64590. ** result as a string or blob but if the string or blob is too large, it
  64591. ** then sets the error code to SQLITE_TOOBIG
  64592. **
  64593. ** The invokeValueDestructor(P,X) routine invokes destructor function X()
  64594. ** on value P is not going to be used and need to be destroyed.
  64595. */
  64596. static void setResultStrOrError(
  64597. sqlite3_context *pCtx, /* Function context */
  64598. const char *z, /* String pointer */
  64599. int n, /* Bytes in string, or negative */
  64600. u8 enc, /* Encoding of z. 0 for BLOBs */
  64601. void (*xDel)(void*) /* Destructor function */
  64602. ){
  64603. if( sqlite3VdbeMemSetStr(pCtx->pOut, z, n, enc, xDel)==SQLITE_TOOBIG ){
  64604. sqlite3_result_error_toobig(pCtx);
  64605. }
  64606. }
  64607. static int invokeValueDestructor(
  64608. const void *p, /* Value to destroy */
  64609. void (*xDel)(void*), /* The destructor */
  64610. sqlite3_context *pCtx /* Set a SQLITE_TOOBIG error if no NULL */
  64611. ){
  64612. assert( xDel!=SQLITE_DYNAMIC );
  64613. if( xDel==0 ){
  64614. /* noop */
  64615. }else if( xDel==SQLITE_TRANSIENT ){
  64616. /* noop */
  64617. }else{
  64618. xDel((void*)p);
  64619. }
  64620. if( pCtx ) sqlite3_result_error_toobig(pCtx);
  64621. return SQLITE_TOOBIG;
  64622. }
  64623. SQLITE_API void SQLITE_STDCALL sqlite3_result_blob(
  64624. sqlite3_context *pCtx,
  64625. const void *z,
  64626. int n,
  64627. void (*xDel)(void *)
  64628. ){
  64629. assert( n>=0 );
  64630. assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  64631. setResultStrOrError(pCtx, z, n, 0, xDel);
  64632. }
  64633. SQLITE_API void SQLITE_STDCALL sqlite3_result_blob64(
  64634. sqlite3_context *pCtx,
  64635. const void *z,
  64636. sqlite3_uint64 n,
  64637. void (*xDel)(void *)
  64638. ){
  64639. assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  64640. assert( xDel!=SQLITE_DYNAMIC );
  64641. if( n>0x7fffffff ){
  64642. (void)invokeValueDestructor(z, xDel, pCtx);
  64643. }else{
  64644. setResultStrOrError(pCtx, z, (int)n, 0, xDel);
  64645. }
  64646. }
  64647. SQLITE_API void SQLITE_STDCALL sqlite3_result_double(sqlite3_context *pCtx, double rVal){
  64648. assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  64649. sqlite3VdbeMemSetDouble(pCtx->pOut, rVal);
  64650. }
  64651. SQLITE_API void SQLITE_STDCALL sqlite3_result_error(sqlite3_context *pCtx, const char *z, int n){
  64652. assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  64653. pCtx->isError = SQLITE_ERROR;
  64654. pCtx->fErrorOrAux = 1;
  64655. sqlite3VdbeMemSetStr(pCtx->pOut, z, n, SQLITE_UTF8, SQLITE_TRANSIENT);
  64656. }
  64657. #ifndef SQLITE_OMIT_UTF16
  64658. SQLITE_API void SQLITE_STDCALL sqlite3_result_error16(sqlite3_context *pCtx, const void *z, int n){
  64659. assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  64660. pCtx->isError = SQLITE_ERROR;
  64661. pCtx->fErrorOrAux = 1;
  64662. sqlite3VdbeMemSetStr(pCtx->pOut, z, n, SQLITE_UTF16NATIVE, SQLITE_TRANSIENT);
  64663. }
  64664. #endif
  64665. SQLITE_API void SQLITE_STDCALL sqlite3_result_int(sqlite3_context *pCtx, int iVal){
  64666. assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  64667. sqlite3VdbeMemSetInt64(pCtx->pOut, (i64)iVal);
  64668. }
  64669. SQLITE_API void SQLITE_STDCALL sqlite3_result_int64(sqlite3_context *pCtx, i64 iVal){
  64670. assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  64671. sqlite3VdbeMemSetInt64(pCtx->pOut, iVal);
  64672. }
  64673. SQLITE_API void SQLITE_STDCALL sqlite3_result_null(sqlite3_context *pCtx){
  64674. assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  64675. sqlite3VdbeMemSetNull(pCtx->pOut);
  64676. }
  64677. SQLITE_API void SQLITE_STDCALL sqlite3_result_text(
  64678. sqlite3_context *pCtx,
  64679. const char *z,
  64680. int n,
  64681. void (*xDel)(void *)
  64682. ){
  64683. assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  64684. setResultStrOrError(pCtx, z, n, SQLITE_UTF8, xDel);
  64685. }
  64686. SQLITE_API void SQLITE_STDCALL sqlite3_result_text64(
  64687. sqlite3_context *pCtx,
  64688. const char *z,
  64689. sqlite3_uint64 n,
  64690. void (*xDel)(void *),
  64691. unsigned char enc
  64692. ){
  64693. assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  64694. assert( xDel!=SQLITE_DYNAMIC );
  64695. if( enc==SQLITE_UTF16 ) enc = SQLITE_UTF16NATIVE;
  64696. if( n>0x7fffffff ){
  64697. (void)invokeValueDestructor(z, xDel, pCtx);
  64698. }else{
  64699. setResultStrOrError(pCtx, z, (int)n, enc, xDel);
  64700. }
  64701. }
  64702. #ifndef SQLITE_OMIT_UTF16
  64703. SQLITE_API void SQLITE_STDCALL sqlite3_result_text16(
  64704. sqlite3_context *pCtx,
  64705. const void *z,
  64706. int n,
  64707. void (*xDel)(void *)
  64708. ){
  64709. assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  64710. setResultStrOrError(pCtx, z, n, SQLITE_UTF16NATIVE, xDel);
  64711. }
  64712. SQLITE_API void SQLITE_STDCALL sqlite3_result_text16be(
  64713. sqlite3_context *pCtx,
  64714. const void *z,
  64715. int n,
  64716. void (*xDel)(void *)
  64717. ){
  64718. assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  64719. setResultStrOrError(pCtx, z, n, SQLITE_UTF16BE, xDel);
  64720. }
  64721. SQLITE_API void SQLITE_STDCALL sqlite3_result_text16le(
  64722. sqlite3_context *pCtx,
  64723. const void *z,
  64724. int n,
  64725. void (*xDel)(void *)
  64726. ){
  64727. assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  64728. setResultStrOrError(pCtx, z, n, SQLITE_UTF16LE, xDel);
  64729. }
  64730. #endif /* SQLITE_OMIT_UTF16 */
  64731. SQLITE_API void SQLITE_STDCALL sqlite3_result_value(sqlite3_context *pCtx, sqlite3_value *pValue){
  64732. assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  64733. sqlite3VdbeMemCopy(pCtx->pOut, pValue);
  64734. }
  64735. SQLITE_API void SQLITE_STDCALL sqlite3_result_zeroblob(sqlite3_context *pCtx, int n){
  64736. assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  64737. sqlite3VdbeMemSetZeroBlob(pCtx->pOut, n);
  64738. }
  64739. SQLITE_API void SQLITE_STDCALL sqlite3_result_error_code(sqlite3_context *pCtx, int errCode){
  64740. pCtx->isError = errCode;
  64741. pCtx->fErrorOrAux = 1;
  64742. #ifdef SQLITE_DEBUG
  64743. if( pCtx->pVdbe ) pCtx->pVdbe->rcApp = errCode;
  64744. #endif
  64745. if( pCtx->pOut->flags & MEM_Null ){
  64746. sqlite3VdbeMemSetStr(pCtx->pOut, sqlite3ErrStr(errCode), -1,
  64747. SQLITE_UTF8, SQLITE_STATIC);
  64748. }
  64749. }
  64750. /* Force an SQLITE_TOOBIG error. */
  64751. SQLITE_API void SQLITE_STDCALL sqlite3_result_error_toobig(sqlite3_context *pCtx){
  64752. assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  64753. pCtx->isError = SQLITE_TOOBIG;
  64754. pCtx->fErrorOrAux = 1;
  64755. sqlite3VdbeMemSetStr(pCtx->pOut, "string or blob too big", -1,
  64756. SQLITE_UTF8, SQLITE_STATIC);
  64757. }
  64758. /* An SQLITE_NOMEM error. */
  64759. SQLITE_API void SQLITE_STDCALL sqlite3_result_error_nomem(sqlite3_context *pCtx){
  64760. assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  64761. sqlite3VdbeMemSetNull(pCtx->pOut);
  64762. pCtx->isError = SQLITE_NOMEM;
  64763. pCtx->fErrorOrAux = 1;
  64764. pCtx->pOut->db->mallocFailed = 1;
  64765. }
  64766. /*
  64767. ** This function is called after a transaction has been committed. It
  64768. ** invokes callbacks registered with sqlite3_wal_hook() as required.
  64769. */
  64770. static int doWalCallbacks(sqlite3 *db){
  64771. int rc = SQLITE_OK;
  64772. #ifndef SQLITE_OMIT_WAL
  64773. int i;
  64774. for(i=0; i<db->nDb; i++){
  64775. Btree *pBt = db->aDb[i].pBt;
  64776. if( pBt ){
  64777. int nEntry;
  64778. sqlite3BtreeEnter(pBt);
  64779. nEntry = sqlite3PagerWalCallback(sqlite3BtreePager(pBt));
  64780. sqlite3BtreeLeave(pBt);
  64781. if( db->xWalCallback && nEntry>0 && rc==SQLITE_OK ){
  64782. rc = db->xWalCallback(db->pWalArg, db, db->aDb[i].zName, nEntry);
  64783. }
  64784. }
  64785. }
  64786. #endif
  64787. return rc;
  64788. }
  64789. /*
  64790. ** Execute the statement pStmt, either until a row of data is ready, the
  64791. ** statement is completely executed or an error occurs.
  64792. **
  64793. ** This routine implements the bulk of the logic behind the sqlite_step()
  64794. ** API. The only thing omitted is the automatic recompile if a
  64795. ** schema change has occurred. That detail is handled by the
  64796. ** outer sqlite3_step() wrapper procedure.
  64797. */
  64798. static int sqlite3Step(Vdbe *p){
  64799. sqlite3 *db;
  64800. int rc;
  64801. assert(p);
  64802. if( p->magic!=VDBE_MAGIC_RUN ){
  64803. /* We used to require that sqlite3_reset() be called before retrying
  64804. ** sqlite3_step() after any error or after SQLITE_DONE. But beginning
  64805. ** with version 3.7.0, we changed this so that sqlite3_reset() would
  64806. ** be called automatically instead of throwing the SQLITE_MISUSE error.
  64807. ** This "automatic-reset" change is not technically an incompatibility,
  64808. ** since any application that receives an SQLITE_MISUSE is broken by
  64809. ** definition.
  64810. **
  64811. ** Nevertheless, some published applications that were originally written
  64812. ** for version 3.6.23 or earlier do in fact depend on SQLITE_MISUSE
  64813. ** returns, and those were broken by the automatic-reset change. As a
  64814. ** a work-around, the SQLITE_OMIT_AUTORESET compile-time restores the
  64815. ** legacy behavior of returning SQLITE_MISUSE for cases where the
  64816. ** previous sqlite3_step() returned something other than a SQLITE_LOCKED
  64817. ** or SQLITE_BUSY error.
  64818. */
  64819. #ifdef SQLITE_OMIT_AUTORESET
  64820. if( (rc = p->rc&0xff)==SQLITE_BUSY || rc==SQLITE_LOCKED ){
  64821. sqlite3_reset((sqlite3_stmt*)p);
  64822. }else{
  64823. return SQLITE_MISUSE_BKPT;
  64824. }
  64825. #else
  64826. sqlite3_reset((sqlite3_stmt*)p);
  64827. #endif
  64828. }
  64829. /* Check that malloc() has not failed. If it has, return early. */
  64830. db = p->db;
  64831. if( db->mallocFailed ){
  64832. p->rc = SQLITE_NOMEM;
  64833. return SQLITE_NOMEM;
  64834. }
  64835. if( p->pc<=0 && p->expired ){
  64836. p->rc = SQLITE_SCHEMA;
  64837. rc = SQLITE_ERROR;
  64838. goto end_of_step;
  64839. }
  64840. if( p->pc<0 ){
  64841. /* If there are no other statements currently running, then
  64842. ** reset the interrupt flag. This prevents a call to sqlite3_interrupt
  64843. ** from interrupting a statement that has not yet started.
  64844. */
  64845. if( db->nVdbeActive==0 ){
  64846. db->u1.isInterrupted = 0;
  64847. }
  64848. assert( db->nVdbeWrite>0 || db->autoCommit==0
  64849. || (db->nDeferredCons==0 && db->nDeferredImmCons==0)
  64850. );
  64851. #ifndef SQLITE_OMIT_TRACE
  64852. if( db->xProfile && !db->init.busy ){
  64853. sqlite3OsCurrentTimeInt64(db->pVfs, &p->startTime);
  64854. }
  64855. #endif
  64856. db->nVdbeActive++;
  64857. if( p->readOnly==0 ) db->nVdbeWrite++;
  64858. if( p->bIsReader ) db->nVdbeRead++;
  64859. p->pc = 0;
  64860. }
  64861. #ifdef SQLITE_DEBUG
  64862. p->rcApp = SQLITE_OK;
  64863. #endif
  64864. #ifndef SQLITE_OMIT_EXPLAIN
  64865. if( p->explain ){
  64866. rc = sqlite3VdbeList(p);
  64867. }else
  64868. #endif /* SQLITE_OMIT_EXPLAIN */
  64869. {
  64870. db->nVdbeExec++;
  64871. rc = sqlite3VdbeExec(p);
  64872. db->nVdbeExec--;
  64873. }
  64874. #ifndef SQLITE_OMIT_TRACE
  64875. /* Invoke the profile callback if there is one
  64876. */
  64877. if( rc!=SQLITE_ROW && db->xProfile && !db->init.busy && p->zSql ){
  64878. sqlite3_int64 iNow;
  64879. sqlite3OsCurrentTimeInt64(db->pVfs, &iNow);
  64880. db->xProfile(db->pProfileArg, p->zSql, (iNow - p->startTime)*1000000);
  64881. }
  64882. #endif
  64883. if( rc==SQLITE_DONE ){
  64884. assert( p->rc==SQLITE_OK );
  64885. p->rc = doWalCallbacks(db);
  64886. if( p->rc!=SQLITE_OK ){
  64887. rc = SQLITE_ERROR;
  64888. }
  64889. }
  64890. db->errCode = rc;
  64891. if( SQLITE_NOMEM==sqlite3ApiExit(p->db, p->rc) ){
  64892. p->rc = SQLITE_NOMEM;
  64893. }
  64894. end_of_step:
  64895. /* At this point local variable rc holds the value that should be
  64896. ** returned if this statement was compiled using the legacy
  64897. ** sqlite3_prepare() interface. According to the docs, this can only
  64898. ** be one of the values in the first assert() below. Variable p->rc
  64899. ** contains the value that would be returned if sqlite3_finalize()
  64900. ** were called on statement p.
  64901. */
  64902. assert( rc==SQLITE_ROW || rc==SQLITE_DONE || rc==SQLITE_ERROR
  64903. || rc==SQLITE_BUSY || rc==SQLITE_MISUSE
  64904. );
  64905. assert( (p->rc!=SQLITE_ROW && p->rc!=SQLITE_DONE) || p->rc==p->rcApp );
  64906. if( p->isPrepareV2 && rc!=SQLITE_ROW && rc!=SQLITE_DONE ){
  64907. /* If this statement was prepared using sqlite3_prepare_v2(), and an
  64908. ** error has occurred, then return the error code in p->rc to the
  64909. ** caller. Set the error code in the database handle to the same value.
  64910. */
  64911. rc = sqlite3VdbeTransferError(p);
  64912. }
  64913. return (rc&db->errMask);
  64914. }
  64915. /*
  64916. ** This is the top-level implementation of sqlite3_step(). Call
  64917. ** sqlite3Step() to do most of the work. If a schema error occurs,
  64918. ** call sqlite3Reprepare() and try again.
  64919. */
  64920. SQLITE_API int SQLITE_STDCALL sqlite3_step(sqlite3_stmt *pStmt){
  64921. int rc = SQLITE_OK; /* Result from sqlite3Step() */
  64922. int rc2 = SQLITE_OK; /* Result from sqlite3Reprepare() */
  64923. Vdbe *v = (Vdbe*)pStmt; /* the prepared statement */
  64924. int cnt = 0; /* Counter to prevent infinite loop of reprepares */
  64925. sqlite3 *db; /* The database connection */
  64926. if( vdbeSafetyNotNull(v) ){
  64927. return SQLITE_MISUSE_BKPT;
  64928. }
  64929. db = v->db;
  64930. sqlite3_mutex_enter(db->mutex);
  64931. v->doingRerun = 0;
  64932. while( (rc = sqlite3Step(v))==SQLITE_SCHEMA
  64933. && cnt++ < SQLITE_MAX_SCHEMA_RETRY ){
  64934. int savedPc = v->pc;
  64935. rc2 = rc = sqlite3Reprepare(v);
  64936. if( rc!=SQLITE_OK) break;
  64937. sqlite3_reset(pStmt);
  64938. if( savedPc>=0 ) v->doingRerun = 1;
  64939. assert( v->expired==0 );
  64940. }
  64941. if( rc2!=SQLITE_OK ){
  64942. /* This case occurs after failing to recompile an sql statement.
  64943. ** The error message from the SQL compiler has already been loaded
  64944. ** into the database handle. This block copies the error message
  64945. ** from the database handle into the statement and sets the statement
  64946. ** program counter to 0 to ensure that when the statement is
  64947. ** finalized or reset the parser error message is available via
  64948. ** sqlite3_errmsg() and sqlite3_errcode().
  64949. */
  64950. const char *zErr = (const char *)sqlite3_value_text(db->pErr);
  64951. sqlite3DbFree(db, v->zErrMsg);
  64952. if( !db->mallocFailed ){
  64953. v->zErrMsg = sqlite3DbStrDup(db, zErr);
  64954. v->rc = rc2;
  64955. } else {
  64956. v->zErrMsg = 0;
  64957. v->rc = rc = SQLITE_NOMEM;
  64958. }
  64959. }
  64960. rc = sqlite3ApiExit(db, rc);
  64961. sqlite3_mutex_leave(db->mutex);
  64962. return rc;
  64963. }
  64964. /*
  64965. ** Extract the user data from a sqlite3_context structure and return a
  64966. ** pointer to it.
  64967. */
  64968. SQLITE_API void *SQLITE_STDCALL sqlite3_user_data(sqlite3_context *p){
  64969. assert( p && p->pFunc );
  64970. return p->pFunc->pUserData;
  64971. }
  64972. /*
  64973. ** Extract the user data from a sqlite3_context structure and return a
  64974. ** pointer to it.
  64975. **
  64976. ** IMPLEMENTATION-OF: R-46798-50301 The sqlite3_context_db_handle() interface
  64977. ** returns a copy of the pointer to the database connection (the 1st
  64978. ** parameter) of the sqlite3_create_function() and
  64979. ** sqlite3_create_function16() routines that originally registered the
  64980. ** application defined function.
  64981. */
  64982. SQLITE_API sqlite3 *SQLITE_STDCALL sqlite3_context_db_handle(sqlite3_context *p){
  64983. assert( p && p->pFunc );
  64984. return p->pOut->db;
  64985. }
  64986. /*
  64987. ** Return the current time for a statement. If the current time
  64988. ** is requested more than once within the same run of a single prepared
  64989. ** statement, the exact same time is returned for each invocation regardless
  64990. ** of the amount of time that elapses between invocations. In other words,
  64991. ** the time returned is always the time of the first call.
  64992. */
  64993. SQLITE_PRIVATE sqlite3_int64 sqlite3StmtCurrentTime(sqlite3_context *p){
  64994. int rc;
  64995. #ifndef SQLITE_ENABLE_STAT3_OR_STAT4
  64996. sqlite3_int64 *piTime = &p->pVdbe->iCurrentTime;
  64997. assert( p->pVdbe!=0 );
  64998. #else
  64999. sqlite3_int64 iTime = 0;
  65000. sqlite3_int64 *piTime = p->pVdbe!=0 ? &p->pVdbe->iCurrentTime : &iTime;
  65001. #endif
  65002. if( *piTime==0 ){
  65003. rc = sqlite3OsCurrentTimeInt64(p->pOut->db->pVfs, piTime);
  65004. if( rc ) *piTime = 0;
  65005. }
  65006. return *piTime;
  65007. }
  65008. /*
  65009. ** The following is the implementation of an SQL function that always
  65010. ** fails with an error message stating that the function is used in the
  65011. ** wrong context. The sqlite3_overload_function() API might construct
  65012. ** SQL function that use this routine so that the functions will exist
  65013. ** for name resolution but are actually overloaded by the xFindFunction
  65014. ** method of virtual tables.
  65015. */
  65016. SQLITE_PRIVATE void sqlite3InvalidFunction(
  65017. sqlite3_context *context, /* The function calling context */
  65018. int NotUsed, /* Number of arguments to the function */
  65019. sqlite3_value **NotUsed2 /* Value of each argument */
  65020. ){
  65021. const char *zName = context->pFunc->zName;
  65022. char *zErr;
  65023. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  65024. zErr = sqlite3_mprintf(
  65025. "unable to use function %s in the requested context", zName);
  65026. sqlite3_result_error(context, zErr, -1);
  65027. sqlite3_free(zErr);
  65028. }
  65029. /*
  65030. ** Create a new aggregate context for p and return a pointer to
  65031. ** its pMem->z element.
  65032. */
  65033. static SQLITE_NOINLINE void *createAggContext(sqlite3_context *p, int nByte){
  65034. Mem *pMem = p->pMem;
  65035. assert( (pMem->flags & MEM_Agg)==0 );
  65036. if( nByte<=0 ){
  65037. sqlite3VdbeMemSetNull(pMem);
  65038. pMem->z = 0;
  65039. }else{
  65040. sqlite3VdbeMemClearAndResize(pMem, nByte);
  65041. pMem->flags = MEM_Agg;
  65042. pMem->u.pDef = p->pFunc;
  65043. if( pMem->z ){
  65044. memset(pMem->z, 0, nByte);
  65045. }
  65046. }
  65047. return (void*)pMem->z;
  65048. }
  65049. /*
  65050. ** Allocate or return the aggregate context for a user function. A new
  65051. ** context is allocated on the first call. Subsequent calls return the
  65052. ** same context that was returned on prior calls.
  65053. */
  65054. SQLITE_API void *SQLITE_STDCALL sqlite3_aggregate_context(sqlite3_context *p, int nByte){
  65055. assert( p && p->pFunc && p->pFunc->xStep );
  65056. assert( sqlite3_mutex_held(p->pOut->db->mutex) );
  65057. testcase( nByte<0 );
  65058. if( (p->pMem->flags & MEM_Agg)==0 ){
  65059. return createAggContext(p, nByte);
  65060. }else{
  65061. return (void*)p->pMem->z;
  65062. }
  65063. }
  65064. /*
  65065. ** Return the auxiliary data pointer, if any, for the iArg'th argument to
  65066. ** the user-function defined by pCtx.
  65067. */
  65068. SQLITE_API void *SQLITE_STDCALL sqlite3_get_auxdata(sqlite3_context *pCtx, int iArg){
  65069. AuxData *pAuxData;
  65070. assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  65071. #if SQLITE_ENABLE_STAT3_OR_STAT4
  65072. if( pCtx->pVdbe==0 ) return 0;
  65073. #else
  65074. assert( pCtx->pVdbe!=0 );
  65075. #endif
  65076. for(pAuxData=pCtx->pVdbe->pAuxData; pAuxData; pAuxData=pAuxData->pNext){
  65077. if( pAuxData->iOp==pCtx->iOp && pAuxData->iArg==iArg ) break;
  65078. }
  65079. return (pAuxData ? pAuxData->pAux : 0);
  65080. }
  65081. /*
  65082. ** Set the auxiliary data pointer and delete function, for the iArg'th
  65083. ** argument to the user-function defined by pCtx. Any previous value is
  65084. ** deleted by calling the delete function specified when it was set.
  65085. */
  65086. SQLITE_API void SQLITE_STDCALL sqlite3_set_auxdata(
  65087. sqlite3_context *pCtx,
  65088. int iArg,
  65089. void *pAux,
  65090. void (*xDelete)(void*)
  65091. ){
  65092. AuxData *pAuxData;
  65093. Vdbe *pVdbe = pCtx->pVdbe;
  65094. assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  65095. if( iArg<0 ) goto failed;
  65096. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  65097. if( pVdbe==0 ) goto failed;
  65098. #else
  65099. assert( pVdbe!=0 );
  65100. #endif
  65101. for(pAuxData=pVdbe->pAuxData; pAuxData; pAuxData=pAuxData->pNext){
  65102. if( pAuxData->iOp==pCtx->iOp && pAuxData->iArg==iArg ) break;
  65103. }
  65104. if( pAuxData==0 ){
  65105. pAuxData = sqlite3DbMallocZero(pVdbe->db, sizeof(AuxData));
  65106. if( !pAuxData ) goto failed;
  65107. pAuxData->iOp = pCtx->iOp;
  65108. pAuxData->iArg = iArg;
  65109. pAuxData->pNext = pVdbe->pAuxData;
  65110. pVdbe->pAuxData = pAuxData;
  65111. if( pCtx->fErrorOrAux==0 ){
  65112. pCtx->isError = 0;
  65113. pCtx->fErrorOrAux = 1;
  65114. }
  65115. }else if( pAuxData->xDelete ){
  65116. pAuxData->xDelete(pAuxData->pAux);
  65117. }
  65118. pAuxData->pAux = pAux;
  65119. pAuxData->xDelete = xDelete;
  65120. return;
  65121. failed:
  65122. if( xDelete ){
  65123. xDelete(pAux);
  65124. }
  65125. }
  65126. #ifndef SQLITE_OMIT_DEPRECATED
  65127. /*
  65128. ** Return the number of times the Step function of an aggregate has been
  65129. ** called.
  65130. **
  65131. ** This function is deprecated. Do not use it for new code. It is
  65132. ** provide only to avoid breaking legacy code. New aggregate function
  65133. ** implementations should keep their own counts within their aggregate
  65134. ** context.
  65135. */
  65136. SQLITE_API int SQLITE_STDCALL sqlite3_aggregate_count(sqlite3_context *p){
  65137. assert( p && p->pMem && p->pFunc && p->pFunc->xStep );
  65138. return p->pMem->n;
  65139. }
  65140. #endif
  65141. /*
  65142. ** Return the number of columns in the result set for the statement pStmt.
  65143. */
  65144. SQLITE_API int SQLITE_STDCALL sqlite3_column_count(sqlite3_stmt *pStmt){
  65145. Vdbe *pVm = (Vdbe *)pStmt;
  65146. return pVm ? pVm->nResColumn : 0;
  65147. }
  65148. /*
  65149. ** Return the number of values available from the current row of the
  65150. ** currently executing statement pStmt.
  65151. */
  65152. SQLITE_API int SQLITE_STDCALL sqlite3_data_count(sqlite3_stmt *pStmt){
  65153. Vdbe *pVm = (Vdbe *)pStmt;
  65154. if( pVm==0 || pVm->pResultSet==0 ) return 0;
  65155. return pVm->nResColumn;
  65156. }
  65157. /*
  65158. ** Return a pointer to static memory containing an SQL NULL value.
  65159. */
  65160. static const Mem *columnNullValue(void){
  65161. /* Even though the Mem structure contains an element
  65162. ** of type i64, on certain architectures (x86) with certain compiler
  65163. ** switches (-Os), gcc may align this Mem object on a 4-byte boundary
  65164. ** instead of an 8-byte one. This all works fine, except that when
  65165. ** running with SQLITE_DEBUG defined the SQLite code sometimes assert()s
  65166. ** that a Mem structure is located on an 8-byte boundary. To prevent
  65167. ** these assert()s from failing, when building with SQLITE_DEBUG defined
  65168. ** using gcc, we force nullMem to be 8-byte aligned using the magical
  65169. ** __attribute__((aligned(8))) macro. */
  65170. static const Mem nullMem
  65171. #if defined(SQLITE_DEBUG) && defined(__GNUC__)
  65172. __attribute__((aligned(8)))
  65173. #endif
  65174. = {
  65175. /* .u = */ {0},
  65176. /* .flags = */ MEM_Null,
  65177. /* .enc = */ 0,
  65178. /* .n = */ 0,
  65179. /* .z = */ 0,
  65180. /* .zMalloc = */ 0,
  65181. /* .szMalloc = */ 0,
  65182. /* .iPadding1 = */ 0,
  65183. /* .db = */ 0,
  65184. /* .xDel = */ 0,
  65185. #ifdef SQLITE_DEBUG
  65186. /* .pScopyFrom = */ 0,
  65187. /* .pFiller = */ 0,
  65188. #endif
  65189. };
  65190. return &nullMem;
  65191. }
  65192. /*
  65193. ** Check to see if column iCol of the given statement is valid. If
  65194. ** it is, return a pointer to the Mem for the value of that column.
  65195. ** If iCol is not valid, return a pointer to a Mem which has a value
  65196. ** of NULL.
  65197. */
  65198. static Mem *columnMem(sqlite3_stmt *pStmt, int i){
  65199. Vdbe *pVm;
  65200. Mem *pOut;
  65201. pVm = (Vdbe *)pStmt;
  65202. if( pVm && pVm->pResultSet!=0 && i<pVm->nResColumn && i>=0 ){
  65203. sqlite3_mutex_enter(pVm->db->mutex);
  65204. pOut = &pVm->pResultSet[i];
  65205. }else{
  65206. if( pVm && ALWAYS(pVm->db) ){
  65207. sqlite3_mutex_enter(pVm->db->mutex);
  65208. sqlite3Error(pVm->db, SQLITE_RANGE);
  65209. }
  65210. pOut = (Mem*)columnNullValue();
  65211. }
  65212. return pOut;
  65213. }
  65214. /*
  65215. ** This function is called after invoking an sqlite3_value_XXX function on a
  65216. ** column value (i.e. a value returned by evaluating an SQL expression in the
  65217. ** select list of a SELECT statement) that may cause a malloc() failure. If
  65218. ** malloc() has failed, the threads mallocFailed flag is cleared and the result
  65219. ** code of statement pStmt set to SQLITE_NOMEM.
  65220. **
  65221. ** Specifically, this is called from within:
  65222. **
  65223. ** sqlite3_column_int()
  65224. ** sqlite3_column_int64()
  65225. ** sqlite3_column_text()
  65226. ** sqlite3_column_text16()
  65227. ** sqlite3_column_real()
  65228. ** sqlite3_column_bytes()
  65229. ** sqlite3_column_bytes16()
  65230. ** sqiite3_column_blob()
  65231. */
  65232. static void columnMallocFailure(sqlite3_stmt *pStmt)
  65233. {
  65234. /* If malloc() failed during an encoding conversion within an
  65235. ** sqlite3_column_XXX API, then set the return code of the statement to
  65236. ** SQLITE_NOMEM. The next call to _step() (if any) will return SQLITE_ERROR
  65237. ** and _finalize() will return NOMEM.
  65238. */
  65239. Vdbe *p = (Vdbe *)pStmt;
  65240. if( p ){
  65241. p->rc = sqlite3ApiExit(p->db, p->rc);
  65242. sqlite3_mutex_leave(p->db->mutex);
  65243. }
  65244. }
  65245. /**************************** sqlite3_column_ *******************************
  65246. ** The following routines are used to access elements of the current row
  65247. ** in the result set.
  65248. */
  65249. SQLITE_API const void *SQLITE_STDCALL sqlite3_column_blob(sqlite3_stmt *pStmt, int i){
  65250. const void *val;
  65251. val = sqlite3_value_blob( columnMem(pStmt,i) );
  65252. /* Even though there is no encoding conversion, value_blob() might
  65253. ** need to call malloc() to expand the result of a zeroblob()
  65254. ** expression.
  65255. */
  65256. columnMallocFailure(pStmt);
  65257. return val;
  65258. }
  65259. SQLITE_API int SQLITE_STDCALL sqlite3_column_bytes(sqlite3_stmt *pStmt, int i){
  65260. int val = sqlite3_value_bytes( columnMem(pStmt,i) );
  65261. columnMallocFailure(pStmt);
  65262. return val;
  65263. }
  65264. SQLITE_API int SQLITE_STDCALL sqlite3_column_bytes16(sqlite3_stmt *pStmt, int i){
  65265. int val = sqlite3_value_bytes16( columnMem(pStmt,i) );
  65266. columnMallocFailure(pStmt);
  65267. return val;
  65268. }
  65269. SQLITE_API double SQLITE_STDCALL sqlite3_column_double(sqlite3_stmt *pStmt, int i){
  65270. double val = sqlite3_value_double( columnMem(pStmt,i) );
  65271. columnMallocFailure(pStmt);
  65272. return val;
  65273. }
  65274. SQLITE_API int SQLITE_STDCALL sqlite3_column_int(sqlite3_stmt *pStmt, int i){
  65275. int val = sqlite3_value_int( columnMem(pStmt,i) );
  65276. columnMallocFailure(pStmt);
  65277. return val;
  65278. }
  65279. SQLITE_API sqlite_int64 SQLITE_STDCALL sqlite3_column_int64(sqlite3_stmt *pStmt, int i){
  65280. sqlite_int64 val = sqlite3_value_int64( columnMem(pStmt,i) );
  65281. columnMallocFailure(pStmt);
  65282. return val;
  65283. }
  65284. SQLITE_API const unsigned char *SQLITE_STDCALL sqlite3_column_text(sqlite3_stmt *pStmt, int i){
  65285. const unsigned char *val = sqlite3_value_text( columnMem(pStmt,i) );
  65286. columnMallocFailure(pStmt);
  65287. return val;
  65288. }
  65289. SQLITE_API sqlite3_value *SQLITE_STDCALL sqlite3_column_value(sqlite3_stmt *pStmt, int i){
  65290. Mem *pOut = columnMem(pStmt, i);
  65291. if( pOut->flags&MEM_Static ){
  65292. pOut->flags &= ~MEM_Static;
  65293. pOut->flags |= MEM_Ephem;
  65294. }
  65295. columnMallocFailure(pStmt);
  65296. return (sqlite3_value *)pOut;
  65297. }
  65298. #ifndef SQLITE_OMIT_UTF16
  65299. SQLITE_API const void *SQLITE_STDCALL sqlite3_column_text16(sqlite3_stmt *pStmt, int i){
  65300. const void *val = sqlite3_value_text16( columnMem(pStmt,i) );
  65301. columnMallocFailure(pStmt);
  65302. return val;
  65303. }
  65304. #endif /* SQLITE_OMIT_UTF16 */
  65305. SQLITE_API int SQLITE_STDCALL sqlite3_column_type(sqlite3_stmt *pStmt, int i){
  65306. int iType = sqlite3_value_type( columnMem(pStmt,i) );
  65307. columnMallocFailure(pStmt);
  65308. return iType;
  65309. }
  65310. /*
  65311. ** Convert the N-th element of pStmt->pColName[] into a string using
  65312. ** xFunc() then return that string. If N is out of range, return 0.
  65313. **
  65314. ** There are up to 5 names for each column. useType determines which
  65315. ** name is returned. Here are the names:
  65316. **
  65317. ** 0 The column name as it should be displayed for output
  65318. ** 1 The datatype name for the column
  65319. ** 2 The name of the database that the column derives from
  65320. ** 3 The name of the table that the column derives from
  65321. ** 4 The name of the table column that the result column derives from
  65322. **
  65323. ** If the result is not a simple column reference (if it is an expression
  65324. ** or a constant) then useTypes 2, 3, and 4 return NULL.
  65325. */
  65326. static const void *columnName(
  65327. sqlite3_stmt *pStmt,
  65328. int N,
  65329. const void *(*xFunc)(Mem*),
  65330. int useType
  65331. ){
  65332. const void *ret;
  65333. Vdbe *p;
  65334. int n;
  65335. sqlite3 *db;
  65336. #ifdef SQLITE_ENABLE_API_ARMOR
  65337. if( pStmt==0 ){
  65338. (void)SQLITE_MISUSE_BKPT;
  65339. return 0;
  65340. }
  65341. #endif
  65342. ret = 0;
  65343. p = (Vdbe *)pStmt;
  65344. db = p->db;
  65345. assert( db!=0 );
  65346. n = sqlite3_column_count(pStmt);
  65347. if( N<n && N>=0 ){
  65348. N += useType*n;
  65349. sqlite3_mutex_enter(db->mutex);
  65350. assert( db->mallocFailed==0 );
  65351. ret = xFunc(&p->aColName[N]);
  65352. /* A malloc may have failed inside of the xFunc() call. If this
  65353. ** is the case, clear the mallocFailed flag and return NULL.
  65354. */
  65355. if( db->mallocFailed ){
  65356. db->mallocFailed = 0;
  65357. ret = 0;
  65358. }
  65359. sqlite3_mutex_leave(db->mutex);
  65360. }
  65361. return ret;
  65362. }
  65363. /*
  65364. ** Return the name of the Nth column of the result set returned by SQL
  65365. ** statement pStmt.
  65366. */
  65367. SQLITE_API const char *SQLITE_STDCALL sqlite3_column_name(sqlite3_stmt *pStmt, int N){
  65368. return columnName(
  65369. pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_NAME);
  65370. }
  65371. #ifndef SQLITE_OMIT_UTF16
  65372. SQLITE_API const void *SQLITE_STDCALL sqlite3_column_name16(sqlite3_stmt *pStmt, int N){
  65373. return columnName(
  65374. pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_NAME);
  65375. }
  65376. #endif
  65377. /*
  65378. ** Constraint: If you have ENABLE_COLUMN_METADATA then you must
  65379. ** not define OMIT_DECLTYPE.
  65380. */
  65381. #if defined(SQLITE_OMIT_DECLTYPE) && defined(SQLITE_ENABLE_COLUMN_METADATA)
  65382. # error "Must not define both SQLITE_OMIT_DECLTYPE \
  65383. and SQLITE_ENABLE_COLUMN_METADATA"
  65384. #endif
  65385. #ifndef SQLITE_OMIT_DECLTYPE
  65386. /*
  65387. ** Return the column declaration type (if applicable) of the 'i'th column
  65388. ** of the result set of SQL statement pStmt.
  65389. */
  65390. SQLITE_API const char *SQLITE_STDCALL sqlite3_column_decltype(sqlite3_stmt *pStmt, int N){
  65391. return columnName(
  65392. pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_DECLTYPE);
  65393. }
  65394. #ifndef SQLITE_OMIT_UTF16
  65395. SQLITE_API const void *SQLITE_STDCALL sqlite3_column_decltype16(sqlite3_stmt *pStmt, int N){
  65396. return columnName(
  65397. pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_DECLTYPE);
  65398. }
  65399. #endif /* SQLITE_OMIT_UTF16 */
  65400. #endif /* SQLITE_OMIT_DECLTYPE */
  65401. #ifdef SQLITE_ENABLE_COLUMN_METADATA
  65402. /*
  65403. ** Return the name of the database from which a result column derives.
  65404. ** NULL is returned if the result column is an expression or constant or
  65405. ** anything else which is not an unambiguous reference to a database column.
  65406. */
  65407. SQLITE_API const char *SQLITE_STDCALL sqlite3_column_database_name(sqlite3_stmt *pStmt, int N){
  65408. return columnName(
  65409. pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_DATABASE);
  65410. }
  65411. #ifndef SQLITE_OMIT_UTF16
  65412. SQLITE_API const void *SQLITE_STDCALL sqlite3_column_database_name16(sqlite3_stmt *pStmt, int N){
  65413. return columnName(
  65414. pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_DATABASE);
  65415. }
  65416. #endif /* SQLITE_OMIT_UTF16 */
  65417. /*
  65418. ** Return the name of the table from which a result column derives.
  65419. ** NULL is returned if the result column is an expression or constant or
  65420. ** anything else which is not an unambiguous reference to a database column.
  65421. */
  65422. SQLITE_API const char *SQLITE_STDCALL sqlite3_column_table_name(sqlite3_stmt *pStmt, int N){
  65423. return columnName(
  65424. pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_TABLE);
  65425. }
  65426. #ifndef SQLITE_OMIT_UTF16
  65427. SQLITE_API const void *SQLITE_STDCALL sqlite3_column_table_name16(sqlite3_stmt *pStmt, int N){
  65428. return columnName(
  65429. pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_TABLE);
  65430. }
  65431. #endif /* SQLITE_OMIT_UTF16 */
  65432. /*
  65433. ** Return the name of the table column from which a result column derives.
  65434. ** NULL is returned if the result column is an expression or constant or
  65435. ** anything else which is not an unambiguous reference to a database column.
  65436. */
  65437. SQLITE_API const char *SQLITE_STDCALL sqlite3_column_origin_name(sqlite3_stmt *pStmt, int N){
  65438. return columnName(
  65439. pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_COLUMN);
  65440. }
  65441. #ifndef SQLITE_OMIT_UTF16
  65442. SQLITE_API const void *SQLITE_STDCALL sqlite3_column_origin_name16(sqlite3_stmt *pStmt, int N){
  65443. return columnName(
  65444. pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_COLUMN);
  65445. }
  65446. #endif /* SQLITE_OMIT_UTF16 */
  65447. #endif /* SQLITE_ENABLE_COLUMN_METADATA */
  65448. /******************************* sqlite3_bind_ ***************************
  65449. **
  65450. ** Routines used to attach values to wildcards in a compiled SQL statement.
  65451. */
  65452. /*
  65453. ** Unbind the value bound to variable i in virtual machine p. This is the
  65454. ** the same as binding a NULL value to the column. If the "i" parameter is
  65455. ** out of range, then SQLITE_RANGE is returned. Othewise SQLITE_OK.
  65456. **
  65457. ** A successful evaluation of this routine acquires the mutex on p.
  65458. ** the mutex is released if any kind of error occurs.
  65459. **
  65460. ** The error code stored in database p->db is overwritten with the return
  65461. ** value in any case.
  65462. */
  65463. static int vdbeUnbind(Vdbe *p, int i){
  65464. Mem *pVar;
  65465. if( vdbeSafetyNotNull(p) ){
  65466. return SQLITE_MISUSE_BKPT;
  65467. }
  65468. sqlite3_mutex_enter(p->db->mutex);
  65469. if( p->magic!=VDBE_MAGIC_RUN || p->pc>=0 ){
  65470. sqlite3Error(p->db, SQLITE_MISUSE);
  65471. sqlite3_mutex_leave(p->db->mutex);
  65472. sqlite3_log(SQLITE_MISUSE,
  65473. "bind on a busy prepared statement: [%s]", p->zSql);
  65474. return SQLITE_MISUSE_BKPT;
  65475. }
  65476. if( i<1 || i>p->nVar ){
  65477. sqlite3Error(p->db, SQLITE_RANGE);
  65478. sqlite3_mutex_leave(p->db->mutex);
  65479. return SQLITE_RANGE;
  65480. }
  65481. i--;
  65482. pVar = &p->aVar[i];
  65483. sqlite3VdbeMemRelease(pVar);
  65484. pVar->flags = MEM_Null;
  65485. sqlite3Error(p->db, SQLITE_OK);
  65486. /* If the bit corresponding to this variable in Vdbe.expmask is set, then
  65487. ** binding a new value to this variable invalidates the current query plan.
  65488. **
  65489. ** IMPLEMENTATION-OF: R-48440-37595 If the specific value bound to host
  65490. ** parameter in the WHERE clause might influence the choice of query plan
  65491. ** for a statement, then the statement will be automatically recompiled,
  65492. ** as if there had been a schema change, on the first sqlite3_step() call
  65493. ** following any change to the bindings of that parameter.
  65494. */
  65495. if( p->isPrepareV2 &&
  65496. ((i<32 && p->expmask & ((u32)1 << i)) || p->expmask==0xffffffff)
  65497. ){
  65498. p->expired = 1;
  65499. }
  65500. return SQLITE_OK;
  65501. }
  65502. /*
  65503. ** Bind a text or BLOB value.
  65504. */
  65505. static int bindText(
  65506. sqlite3_stmt *pStmt, /* The statement to bind against */
  65507. int i, /* Index of the parameter to bind */
  65508. const void *zData, /* Pointer to the data to be bound */
  65509. int nData, /* Number of bytes of data to be bound */
  65510. void (*xDel)(void*), /* Destructor for the data */
  65511. u8 encoding /* Encoding for the data */
  65512. ){
  65513. Vdbe *p = (Vdbe *)pStmt;
  65514. Mem *pVar;
  65515. int rc;
  65516. rc = vdbeUnbind(p, i);
  65517. if( rc==SQLITE_OK ){
  65518. if( zData!=0 ){
  65519. pVar = &p->aVar[i-1];
  65520. rc = sqlite3VdbeMemSetStr(pVar, zData, nData, encoding, xDel);
  65521. if( rc==SQLITE_OK && encoding!=0 ){
  65522. rc = sqlite3VdbeChangeEncoding(pVar, ENC(p->db));
  65523. }
  65524. sqlite3Error(p->db, rc);
  65525. rc = sqlite3ApiExit(p->db, rc);
  65526. }
  65527. sqlite3_mutex_leave(p->db->mutex);
  65528. }else if( xDel!=SQLITE_STATIC && xDel!=SQLITE_TRANSIENT ){
  65529. xDel((void*)zData);
  65530. }
  65531. return rc;
  65532. }
  65533. /*
  65534. ** Bind a blob value to an SQL statement variable.
  65535. */
  65536. SQLITE_API int SQLITE_STDCALL sqlite3_bind_blob(
  65537. sqlite3_stmt *pStmt,
  65538. int i,
  65539. const void *zData,
  65540. int nData,
  65541. void (*xDel)(void*)
  65542. ){
  65543. return bindText(pStmt, i, zData, nData, xDel, 0);
  65544. }
  65545. SQLITE_API int SQLITE_STDCALL sqlite3_bind_blob64(
  65546. sqlite3_stmt *pStmt,
  65547. int i,
  65548. const void *zData,
  65549. sqlite3_uint64 nData,
  65550. void (*xDel)(void*)
  65551. ){
  65552. assert( xDel!=SQLITE_DYNAMIC );
  65553. if( nData>0x7fffffff ){
  65554. return invokeValueDestructor(zData, xDel, 0);
  65555. }else{
  65556. return bindText(pStmt, i, zData, (int)nData, xDel, 0);
  65557. }
  65558. }
  65559. SQLITE_API int SQLITE_STDCALL sqlite3_bind_double(sqlite3_stmt *pStmt, int i, double rValue){
  65560. int rc;
  65561. Vdbe *p = (Vdbe *)pStmt;
  65562. rc = vdbeUnbind(p, i);
  65563. if( rc==SQLITE_OK ){
  65564. sqlite3VdbeMemSetDouble(&p->aVar[i-1], rValue);
  65565. sqlite3_mutex_leave(p->db->mutex);
  65566. }
  65567. return rc;
  65568. }
  65569. SQLITE_API int SQLITE_STDCALL sqlite3_bind_int(sqlite3_stmt *p, int i, int iValue){
  65570. return sqlite3_bind_int64(p, i, (i64)iValue);
  65571. }
  65572. SQLITE_API int SQLITE_STDCALL sqlite3_bind_int64(sqlite3_stmt *pStmt, int i, sqlite_int64 iValue){
  65573. int rc;
  65574. Vdbe *p = (Vdbe *)pStmt;
  65575. rc = vdbeUnbind(p, i);
  65576. if( rc==SQLITE_OK ){
  65577. sqlite3VdbeMemSetInt64(&p->aVar[i-1], iValue);
  65578. sqlite3_mutex_leave(p->db->mutex);
  65579. }
  65580. return rc;
  65581. }
  65582. SQLITE_API int SQLITE_STDCALL sqlite3_bind_null(sqlite3_stmt *pStmt, int i){
  65583. int rc;
  65584. Vdbe *p = (Vdbe*)pStmt;
  65585. rc = vdbeUnbind(p, i);
  65586. if( rc==SQLITE_OK ){
  65587. sqlite3_mutex_leave(p->db->mutex);
  65588. }
  65589. return rc;
  65590. }
  65591. SQLITE_API int SQLITE_STDCALL sqlite3_bind_text(
  65592. sqlite3_stmt *pStmt,
  65593. int i,
  65594. const char *zData,
  65595. int nData,
  65596. void (*xDel)(void*)
  65597. ){
  65598. return bindText(pStmt, i, zData, nData, xDel, SQLITE_UTF8);
  65599. }
  65600. SQLITE_API int SQLITE_STDCALL sqlite3_bind_text64(
  65601. sqlite3_stmt *pStmt,
  65602. int i,
  65603. const char *zData,
  65604. sqlite3_uint64 nData,
  65605. void (*xDel)(void*),
  65606. unsigned char enc
  65607. ){
  65608. assert( xDel!=SQLITE_DYNAMIC );
  65609. if( nData>0x7fffffff ){
  65610. return invokeValueDestructor(zData, xDel, 0);
  65611. }else{
  65612. if( enc==SQLITE_UTF16 ) enc = SQLITE_UTF16NATIVE;
  65613. return bindText(pStmt, i, zData, (int)nData, xDel, enc);
  65614. }
  65615. }
  65616. #ifndef SQLITE_OMIT_UTF16
  65617. SQLITE_API int SQLITE_STDCALL sqlite3_bind_text16(
  65618. sqlite3_stmt *pStmt,
  65619. int i,
  65620. const void *zData,
  65621. int nData,
  65622. void (*xDel)(void*)
  65623. ){
  65624. return bindText(pStmt, i, zData, nData, xDel, SQLITE_UTF16NATIVE);
  65625. }
  65626. #endif /* SQLITE_OMIT_UTF16 */
  65627. SQLITE_API int SQLITE_STDCALL sqlite3_bind_value(sqlite3_stmt *pStmt, int i, const sqlite3_value *pValue){
  65628. int rc;
  65629. switch( sqlite3_value_type((sqlite3_value*)pValue) ){
  65630. case SQLITE_INTEGER: {
  65631. rc = sqlite3_bind_int64(pStmt, i, pValue->u.i);
  65632. break;
  65633. }
  65634. case SQLITE_FLOAT: {
  65635. rc = sqlite3_bind_double(pStmt, i, pValue->u.r);
  65636. break;
  65637. }
  65638. case SQLITE_BLOB: {
  65639. if( pValue->flags & MEM_Zero ){
  65640. rc = sqlite3_bind_zeroblob(pStmt, i, pValue->u.nZero);
  65641. }else{
  65642. rc = sqlite3_bind_blob(pStmt, i, pValue->z, pValue->n,SQLITE_TRANSIENT);
  65643. }
  65644. break;
  65645. }
  65646. case SQLITE_TEXT: {
  65647. rc = bindText(pStmt,i, pValue->z, pValue->n, SQLITE_TRANSIENT,
  65648. pValue->enc);
  65649. break;
  65650. }
  65651. default: {
  65652. rc = sqlite3_bind_null(pStmt, i);
  65653. break;
  65654. }
  65655. }
  65656. return rc;
  65657. }
  65658. SQLITE_API int SQLITE_STDCALL sqlite3_bind_zeroblob(sqlite3_stmt *pStmt, int i, int n){
  65659. int rc;
  65660. Vdbe *p = (Vdbe *)pStmt;
  65661. rc = vdbeUnbind(p, i);
  65662. if( rc==SQLITE_OK ){
  65663. sqlite3VdbeMemSetZeroBlob(&p->aVar[i-1], n);
  65664. sqlite3_mutex_leave(p->db->mutex);
  65665. }
  65666. return rc;
  65667. }
  65668. /*
  65669. ** Return the number of wildcards that can be potentially bound to.
  65670. ** This routine is added to support DBD::SQLite.
  65671. */
  65672. SQLITE_API int SQLITE_STDCALL sqlite3_bind_parameter_count(sqlite3_stmt *pStmt){
  65673. Vdbe *p = (Vdbe*)pStmt;
  65674. return p ? p->nVar : 0;
  65675. }
  65676. /*
  65677. ** Return the name of a wildcard parameter. Return NULL if the index
  65678. ** is out of range or if the wildcard is unnamed.
  65679. **
  65680. ** The result is always UTF-8.
  65681. */
  65682. SQLITE_API const char *SQLITE_STDCALL sqlite3_bind_parameter_name(sqlite3_stmt *pStmt, int i){
  65683. Vdbe *p = (Vdbe*)pStmt;
  65684. if( p==0 || i<1 || i>p->nzVar ){
  65685. return 0;
  65686. }
  65687. return p->azVar[i-1];
  65688. }
  65689. /*
  65690. ** Given a wildcard parameter name, return the index of the variable
  65691. ** with that name. If there is no variable with the given name,
  65692. ** return 0.
  65693. */
  65694. SQLITE_PRIVATE int sqlite3VdbeParameterIndex(Vdbe *p, const char *zName, int nName){
  65695. int i;
  65696. if( p==0 ){
  65697. return 0;
  65698. }
  65699. if( zName ){
  65700. for(i=0; i<p->nzVar; i++){
  65701. const char *z = p->azVar[i];
  65702. if( z && strncmp(z,zName,nName)==0 && z[nName]==0 ){
  65703. return i+1;
  65704. }
  65705. }
  65706. }
  65707. return 0;
  65708. }
  65709. SQLITE_API int SQLITE_STDCALL sqlite3_bind_parameter_index(sqlite3_stmt *pStmt, const char *zName){
  65710. return sqlite3VdbeParameterIndex((Vdbe*)pStmt, zName, sqlite3Strlen30(zName));
  65711. }
  65712. /*
  65713. ** Transfer all bindings from the first statement over to the second.
  65714. */
  65715. SQLITE_PRIVATE int sqlite3TransferBindings(sqlite3_stmt *pFromStmt, sqlite3_stmt *pToStmt){
  65716. Vdbe *pFrom = (Vdbe*)pFromStmt;
  65717. Vdbe *pTo = (Vdbe*)pToStmt;
  65718. int i;
  65719. assert( pTo->db==pFrom->db );
  65720. assert( pTo->nVar==pFrom->nVar );
  65721. sqlite3_mutex_enter(pTo->db->mutex);
  65722. for(i=0; i<pFrom->nVar; i++){
  65723. sqlite3VdbeMemMove(&pTo->aVar[i], &pFrom->aVar[i]);
  65724. }
  65725. sqlite3_mutex_leave(pTo->db->mutex);
  65726. return SQLITE_OK;
  65727. }
  65728. #ifndef SQLITE_OMIT_DEPRECATED
  65729. /*
  65730. ** Deprecated external interface. Internal/core SQLite code
  65731. ** should call sqlite3TransferBindings.
  65732. **
  65733. ** It is misuse to call this routine with statements from different
  65734. ** database connections. But as this is a deprecated interface, we
  65735. ** will not bother to check for that condition.
  65736. **
  65737. ** If the two statements contain a different number of bindings, then
  65738. ** an SQLITE_ERROR is returned. Nothing else can go wrong, so otherwise
  65739. ** SQLITE_OK is returned.
  65740. */
  65741. SQLITE_API int SQLITE_STDCALL sqlite3_transfer_bindings(sqlite3_stmt *pFromStmt, sqlite3_stmt *pToStmt){
  65742. Vdbe *pFrom = (Vdbe*)pFromStmt;
  65743. Vdbe *pTo = (Vdbe*)pToStmt;
  65744. if( pFrom->nVar!=pTo->nVar ){
  65745. return SQLITE_ERROR;
  65746. }
  65747. if( pTo->isPrepareV2 && pTo->expmask ){
  65748. pTo->expired = 1;
  65749. }
  65750. if( pFrom->isPrepareV2 && pFrom->expmask ){
  65751. pFrom->expired = 1;
  65752. }
  65753. return sqlite3TransferBindings(pFromStmt, pToStmt);
  65754. }
  65755. #endif
  65756. /*
  65757. ** Return the sqlite3* database handle to which the prepared statement given
  65758. ** in the argument belongs. This is the same database handle that was
  65759. ** the first argument to the sqlite3_prepare() that was used to create
  65760. ** the statement in the first place.
  65761. */
  65762. SQLITE_API sqlite3 *SQLITE_STDCALL sqlite3_db_handle(sqlite3_stmt *pStmt){
  65763. return pStmt ? ((Vdbe*)pStmt)->db : 0;
  65764. }
  65765. /*
  65766. ** Return true if the prepared statement is guaranteed to not modify the
  65767. ** database.
  65768. */
  65769. SQLITE_API int SQLITE_STDCALL sqlite3_stmt_readonly(sqlite3_stmt *pStmt){
  65770. return pStmt ? ((Vdbe*)pStmt)->readOnly : 1;
  65771. }
  65772. /*
  65773. ** Return true if the prepared statement is in need of being reset.
  65774. */
  65775. SQLITE_API int SQLITE_STDCALL sqlite3_stmt_busy(sqlite3_stmt *pStmt){
  65776. Vdbe *v = (Vdbe*)pStmt;
  65777. return v!=0 && v->pc>=0 && v->magic==VDBE_MAGIC_RUN;
  65778. }
  65779. /*
  65780. ** Return a pointer to the next prepared statement after pStmt associated
  65781. ** with database connection pDb. If pStmt is NULL, return the first
  65782. ** prepared statement for the database connection. Return NULL if there
  65783. ** are no more.
  65784. */
  65785. SQLITE_API sqlite3_stmt *SQLITE_STDCALL sqlite3_next_stmt(sqlite3 *pDb, sqlite3_stmt *pStmt){
  65786. sqlite3_stmt *pNext;
  65787. #ifdef SQLITE_ENABLE_API_ARMOR
  65788. if( !sqlite3SafetyCheckOk(pDb) ){
  65789. (void)SQLITE_MISUSE_BKPT;
  65790. return 0;
  65791. }
  65792. #endif
  65793. sqlite3_mutex_enter(pDb->mutex);
  65794. if( pStmt==0 ){
  65795. pNext = (sqlite3_stmt*)pDb->pVdbe;
  65796. }else{
  65797. pNext = (sqlite3_stmt*)((Vdbe*)pStmt)->pNext;
  65798. }
  65799. sqlite3_mutex_leave(pDb->mutex);
  65800. return pNext;
  65801. }
  65802. /*
  65803. ** Return the value of a status counter for a prepared statement
  65804. */
  65805. SQLITE_API int SQLITE_STDCALL sqlite3_stmt_status(sqlite3_stmt *pStmt, int op, int resetFlag){
  65806. Vdbe *pVdbe = (Vdbe*)pStmt;
  65807. u32 v;
  65808. #ifdef SQLITE_ENABLE_API_ARMOR
  65809. if( !pStmt ){
  65810. (void)SQLITE_MISUSE_BKPT;
  65811. return 0;
  65812. }
  65813. #endif
  65814. v = pVdbe->aCounter[op];
  65815. if( resetFlag ) pVdbe->aCounter[op] = 0;
  65816. return (int)v;
  65817. }
  65818. #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
  65819. /*
  65820. ** Return status data for a single loop within query pStmt.
  65821. */
  65822. SQLITE_API int SQLITE_STDCALL sqlite3_stmt_scanstatus(
  65823. sqlite3_stmt *pStmt, /* Prepared statement being queried */
  65824. int idx, /* Index of loop to report on */
  65825. int iScanStatusOp, /* Which metric to return */
  65826. void *pOut /* OUT: Write the answer here */
  65827. ){
  65828. Vdbe *p = (Vdbe*)pStmt;
  65829. ScanStatus *pScan;
  65830. if( idx<0 || idx>=p->nScan ) return 1;
  65831. pScan = &p->aScan[idx];
  65832. switch( iScanStatusOp ){
  65833. case SQLITE_SCANSTAT_NLOOP: {
  65834. *(sqlite3_int64*)pOut = p->anExec[pScan->addrLoop];
  65835. break;
  65836. }
  65837. case SQLITE_SCANSTAT_NVISIT: {
  65838. *(sqlite3_int64*)pOut = p->anExec[pScan->addrVisit];
  65839. break;
  65840. }
  65841. case SQLITE_SCANSTAT_EST: {
  65842. double r = 1.0;
  65843. LogEst x = pScan->nEst;
  65844. while( x<100 ){
  65845. x += 10;
  65846. r *= 0.5;
  65847. }
  65848. *(double*)pOut = r*sqlite3LogEstToInt(x);
  65849. break;
  65850. }
  65851. case SQLITE_SCANSTAT_NAME: {
  65852. *(const char**)pOut = pScan->zName;
  65853. break;
  65854. }
  65855. case SQLITE_SCANSTAT_EXPLAIN: {
  65856. if( pScan->addrExplain ){
  65857. *(const char**)pOut = p->aOp[ pScan->addrExplain ].p4.z;
  65858. }else{
  65859. *(const char**)pOut = 0;
  65860. }
  65861. break;
  65862. }
  65863. case SQLITE_SCANSTAT_SELECTID: {
  65864. if( pScan->addrExplain ){
  65865. *(int*)pOut = p->aOp[ pScan->addrExplain ].p1;
  65866. }else{
  65867. *(int*)pOut = -1;
  65868. }
  65869. break;
  65870. }
  65871. default: {
  65872. return 1;
  65873. }
  65874. }
  65875. return 0;
  65876. }
  65877. /*
  65878. ** Zero all counters associated with the sqlite3_stmt_scanstatus() data.
  65879. */
  65880. SQLITE_API void SQLITE_STDCALL sqlite3_stmt_scanstatus_reset(sqlite3_stmt *pStmt){
  65881. Vdbe *p = (Vdbe*)pStmt;
  65882. memset(p->anExec, 0, p->nOp * sizeof(i64));
  65883. }
  65884. #endif /* SQLITE_ENABLE_STMT_SCANSTATUS */
  65885. /************** End of vdbeapi.c *********************************************/
  65886. /************** Begin file vdbetrace.c ***************************************/
  65887. /*
  65888. ** 2009 November 25
  65889. **
  65890. ** The author disclaims copyright to this source code. In place of
  65891. ** a legal notice, here is a blessing:
  65892. **
  65893. ** May you do good and not evil.
  65894. ** May you find forgiveness for yourself and forgive others.
  65895. ** May you share freely, never taking more than you give.
  65896. **
  65897. *************************************************************************
  65898. **
  65899. ** This file contains code used to insert the values of host parameters
  65900. ** (aka "wildcards") into the SQL text output by sqlite3_trace().
  65901. **
  65902. ** The Vdbe parse-tree explainer is also found here.
  65903. */
  65904. #ifndef SQLITE_OMIT_TRACE
  65905. /*
  65906. ** zSql is a zero-terminated string of UTF-8 SQL text. Return the number of
  65907. ** bytes in this text up to but excluding the first character in
  65908. ** a host parameter. If the text contains no host parameters, return
  65909. ** the total number of bytes in the text.
  65910. */
  65911. static int findNextHostParameter(const char *zSql, int *pnToken){
  65912. int tokenType;
  65913. int nTotal = 0;
  65914. int n;
  65915. *pnToken = 0;
  65916. while( zSql[0] ){
  65917. n = sqlite3GetToken((u8*)zSql, &tokenType);
  65918. assert( n>0 && tokenType!=TK_ILLEGAL );
  65919. if( tokenType==TK_VARIABLE ){
  65920. *pnToken = n;
  65921. break;
  65922. }
  65923. nTotal += n;
  65924. zSql += n;
  65925. }
  65926. return nTotal;
  65927. }
  65928. /*
  65929. ** This function returns a pointer to a nul-terminated string in memory
  65930. ** obtained from sqlite3DbMalloc(). If sqlite3.nVdbeExec is 1, then the
  65931. ** string contains a copy of zRawSql but with host parameters expanded to
  65932. ** their current bindings. Or, if sqlite3.nVdbeExec is greater than 1,
  65933. ** then the returned string holds a copy of zRawSql with "-- " prepended
  65934. ** to each line of text.
  65935. **
  65936. ** If the SQLITE_TRACE_SIZE_LIMIT macro is defined to an integer, then
  65937. ** then long strings and blobs are truncated to that many bytes. This
  65938. ** can be used to prevent unreasonably large trace strings when dealing
  65939. ** with large (multi-megabyte) strings and blobs.
  65940. **
  65941. ** The calling function is responsible for making sure the memory returned
  65942. ** is eventually freed.
  65943. **
  65944. ** ALGORITHM: Scan the input string looking for host parameters in any of
  65945. ** these forms: ?, ?N, $A, @A, :A. Take care to avoid text within
  65946. ** string literals, quoted identifier names, and comments. For text forms,
  65947. ** the host parameter index is found by scanning the prepared
  65948. ** statement for the corresponding OP_Variable opcode. Once the host
  65949. ** parameter index is known, locate the value in p->aVar[]. Then render
  65950. ** the value as a literal in place of the host parameter name.
  65951. */
  65952. SQLITE_PRIVATE char *sqlite3VdbeExpandSql(
  65953. Vdbe *p, /* The prepared statement being evaluated */
  65954. const char *zRawSql /* Raw text of the SQL statement */
  65955. ){
  65956. sqlite3 *db; /* The database connection */
  65957. int idx = 0; /* Index of a host parameter */
  65958. int nextIndex = 1; /* Index of next ? host parameter */
  65959. int n; /* Length of a token prefix */
  65960. int nToken; /* Length of the parameter token */
  65961. int i; /* Loop counter */
  65962. Mem *pVar; /* Value of a host parameter */
  65963. StrAccum out; /* Accumulate the output here */
  65964. char zBase[100]; /* Initial working space */
  65965. db = p->db;
  65966. sqlite3StrAccumInit(&out, db, zBase, sizeof(zBase),
  65967. db->aLimit[SQLITE_LIMIT_LENGTH]);
  65968. if( db->nVdbeExec>1 ){
  65969. while( *zRawSql ){
  65970. const char *zStart = zRawSql;
  65971. while( *(zRawSql++)!='\n' && *zRawSql );
  65972. sqlite3StrAccumAppend(&out, "-- ", 3);
  65973. assert( (zRawSql - zStart) > 0 );
  65974. sqlite3StrAccumAppend(&out, zStart, (int)(zRawSql-zStart));
  65975. }
  65976. }else if( p->nVar==0 ){
  65977. sqlite3StrAccumAppend(&out, zRawSql, sqlite3Strlen30(zRawSql));
  65978. }else{
  65979. while( zRawSql[0] ){
  65980. n = findNextHostParameter(zRawSql, &nToken);
  65981. assert( n>0 );
  65982. sqlite3StrAccumAppend(&out, zRawSql, n);
  65983. zRawSql += n;
  65984. assert( zRawSql[0] || nToken==0 );
  65985. if( nToken==0 ) break;
  65986. if( zRawSql[0]=='?' ){
  65987. if( nToken>1 ){
  65988. assert( sqlite3Isdigit(zRawSql[1]) );
  65989. sqlite3GetInt32(&zRawSql[1], &idx);
  65990. }else{
  65991. idx = nextIndex;
  65992. }
  65993. }else{
  65994. assert( zRawSql[0]==':' || zRawSql[0]=='$' ||
  65995. zRawSql[0]=='@' || zRawSql[0]=='#' );
  65996. testcase( zRawSql[0]==':' );
  65997. testcase( zRawSql[0]=='$' );
  65998. testcase( zRawSql[0]=='@' );
  65999. testcase( zRawSql[0]=='#' );
  66000. idx = sqlite3VdbeParameterIndex(p, zRawSql, nToken);
  66001. assert( idx>0 );
  66002. }
  66003. zRawSql += nToken;
  66004. nextIndex = idx + 1;
  66005. assert( idx>0 && idx<=p->nVar );
  66006. pVar = &p->aVar[idx-1];
  66007. if( pVar->flags & MEM_Null ){
  66008. sqlite3StrAccumAppend(&out, "NULL", 4);
  66009. }else if( pVar->flags & MEM_Int ){
  66010. sqlite3XPrintf(&out, 0, "%lld", pVar->u.i);
  66011. }else if( pVar->flags & MEM_Real ){
  66012. sqlite3XPrintf(&out, 0, "%!.15g", pVar->u.r);
  66013. }else if( pVar->flags & MEM_Str ){
  66014. int nOut; /* Number of bytes of the string text to include in output */
  66015. #ifndef SQLITE_OMIT_UTF16
  66016. u8 enc = ENC(db);
  66017. Mem utf8;
  66018. if( enc!=SQLITE_UTF8 ){
  66019. memset(&utf8, 0, sizeof(utf8));
  66020. utf8.db = db;
  66021. sqlite3VdbeMemSetStr(&utf8, pVar->z, pVar->n, enc, SQLITE_STATIC);
  66022. sqlite3VdbeChangeEncoding(&utf8, SQLITE_UTF8);
  66023. pVar = &utf8;
  66024. }
  66025. #endif
  66026. nOut = pVar->n;
  66027. #ifdef SQLITE_TRACE_SIZE_LIMIT
  66028. if( nOut>SQLITE_TRACE_SIZE_LIMIT ){
  66029. nOut = SQLITE_TRACE_SIZE_LIMIT;
  66030. while( nOut<pVar->n && (pVar->z[nOut]&0xc0)==0x80 ){ nOut++; }
  66031. }
  66032. #endif
  66033. sqlite3XPrintf(&out, 0, "'%.*q'", nOut, pVar->z);
  66034. #ifdef SQLITE_TRACE_SIZE_LIMIT
  66035. if( nOut<pVar->n ){
  66036. sqlite3XPrintf(&out, 0, "/*+%d bytes*/", pVar->n-nOut);
  66037. }
  66038. #endif
  66039. #ifndef SQLITE_OMIT_UTF16
  66040. if( enc!=SQLITE_UTF8 ) sqlite3VdbeMemRelease(&utf8);
  66041. #endif
  66042. }else if( pVar->flags & MEM_Zero ){
  66043. sqlite3XPrintf(&out, 0, "zeroblob(%d)", pVar->u.nZero);
  66044. }else{
  66045. int nOut; /* Number of bytes of the blob to include in output */
  66046. assert( pVar->flags & MEM_Blob );
  66047. sqlite3StrAccumAppend(&out, "x'", 2);
  66048. nOut = pVar->n;
  66049. #ifdef SQLITE_TRACE_SIZE_LIMIT
  66050. if( nOut>SQLITE_TRACE_SIZE_LIMIT ) nOut = SQLITE_TRACE_SIZE_LIMIT;
  66051. #endif
  66052. for(i=0; i<nOut; i++){
  66053. sqlite3XPrintf(&out, 0, "%02x", pVar->z[i]&0xff);
  66054. }
  66055. sqlite3StrAccumAppend(&out, "'", 1);
  66056. #ifdef SQLITE_TRACE_SIZE_LIMIT
  66057. if( nOut<pVar->n ){
  66058. sqlite3XPrintf(&out, 0, "/*+%d bytes*/", pVar->n-nOut);
  66059. }
  66060. #endif
  66061. }
  66062. }
  66063. }
  66064. return sqlite3StrAccumFinish(&out);
  66065. }
  66066. #endif /* #ifndef SQLITE_OMIT_TRACE */
  66067. /************** End of vdbetrace.c *******************************************/
  66068. /************** Begin file vdbe.c ********************************************/
  66069. /*
  66070. ** 2001 September 15
  66071. **
  66072. ** The author disclaims copyright to this source code. In place of
  66073. ** a legal notice, here is a blessing:
  66074. **
  66075. ** May you do good and not evil.
  66076. ** May you find forgiveness for yourself and forgive others.
  66077. ** May you share freely, never taking more than you give.
  66078. **
  66079. *************************************************************************
  66080. ** The code in this file implements the function that runs the
  66081. ** bytecode of a prepared statement.
  66082. **
  66083. ** Various scripts scan this source file in order to generate HTML
  66084. ** documentation, headers files, or other derived files. The formatting
  66085. ** of the code in this file is, therefore, important. See other comments
  66086. ** in this file for details. If in doubt, do not deviate from existing
  66087. ** commenting and indentation practices when changing or adding code.
  66088. */
  66089. /*
  66090. ** Invoke this macro on memory cells just prior to changing the
  66091. ** value of the cell. This macro verifies that shallow copies are
  66092. ** not misused. A shallow copy of a string or blob just copies a
  66093. ** pointer to the string or blob, not the content. If the original
  66094. ** is changed while the copy is still in use, the string or blob might
  66095. ** be changed out from under the copy. This macro verifies that nothing
  66096. ** like that ever happens.
  66097. */
  66098. #ifdef SQLITE_DEBUG
  66099. # define memAboutToChange(P,M) sqlite3VdbeMemAboutToChange(P,M)
  66100. #else
  66101. # define memAboutToChange(P,M)
  66102. #endif
  66103. /*
  66104. ** The following global variable is incremented every time a cursor
  66105. ** moves, either by the OP_SeekXX, OP_Next, or OP_Prev opcodes. The test
  66106. ** procedures use this information to make sure that indices are
  66107. ** working correctly. This variable has no function other than to
  66108. ** help verify the correct operation of the library.
  66109. */
  66110. #ifdef SQLITE_TEST
  66111. SQLITE_API int sqlite3_search_count = 0;
  66112. #endif
  66113. /*
  66114. ** When this global variable is positive, it gets decremented once before
  66115. ** each instruction in the VDBE. When it reaches zero, the u1.isInterrupted
  66116. ** field of the sqlite3 structure is set in order to simulate an interrupt.
  66117. **
  66118. ** This facility is used for testing purposes only. It does not function
  66119. ** in an ordinary build.
  66120. */
  66121. #ifdef SQLITE_TEST
  66122. SQLITE_API int sqlite3_interrupt_count = 0;
  66123. #endif
  66124. /*
  66125. ** The next global variable is incremented each type the OP_Sort opcode
  66126. ** is executed. The test procedures use this information to make sure that
  66127. ** sorting is occurring or not occurring at appropriate times. This variable
  66128. ** has no function other than to help verify the correct operation of the
  66129. ** library.
  66130. */
  66131. #ifdef SQLITE_TEST
  66132. SQLITE_API int sqlite3_sort_count = 0;
  66133. #endif
  66134. /*
  66135. ** The next global variable records the size of the largest MEM_Blob
  66136. ** or MEM_Str that has been used by a VDBE opcode. The test procedures
  66137. ** use this information to make sure that the zero-blob functionality
  66138. ** is working correctly. This variable has no function other than to
  66139. ** help verify the correct operation of the library.
  66140. */
  66141. #ifdef SQLITE_TEST
  66142. SQLITE_API int sqlite3_max_blobsize = 0;
  66143. static void updateMaxBlobsize(Mem *p){
  66144. if( (p->flags & (MEM_Str|MEM_Blob))!=0 && p->n>sqlite3_max_blobsize ){
  66145. sqlite3_max_blobsize = p->n;
  66146. }
  66147. }
  66148. #endif
  66149. /*
  66150. ** The next global variable is incremented each time the OP_Found opcode
  66151. ** is executed. This is used to test whether or not the foreign key
  66152. ** operation implemented using OP_FkIsZero is working. This variable
  66153. ** has no function other than to help verify the correct operation of the
  66154. ** library.
  66155. */
  66156. #ifdef SQLITE_TEST
  66157. SQLITE_API int sqlite3_found_count = 0;
  66158. #endif
  66159. /*
  66160. ** Test a register to see if it exceeds the current maximum blob size.
  66161. ** If it does, record the new maximum blob size.
  66162. */
  66163. #if defined(SQLITE_TEST) && !defined(SQLITE_OMIT_BUILTIN_TEST)
  66164. # define UPDATE_MAX_BLOBSIZE(P) updateMaxBlobsize(P)
  66165. #else
  66166. # define UPDATE_MAX_BLOBSIZE(P)
  66167. #endif
  66168. /*
  66169. ** Invoke the VDBE coverage callback, if that callback is defined. This
  66170. ** feature is used for test suite validation only and does not appear an
  66171. ** production builds.
  66172. **
  66173. ** M is an integer, 2 or 3, that indices how many different ways the
  66174. ** branch can go. It is usually 2. "I" is the direction the branch
  66175. ** goes. 0 means falls through. 1 means branch is taken. 2 means the
  66176. ** second alternative branch is taken.
  66177. **
  66178. ** iSrcLine is the source code line (from the __LINE__ macro) that
  66179. ** generated the VDBE instruction. This instrumentation assumes that all
  66180. ** source code is in a single file (the amalgamation). Special values 1
  66181. ** and 2 for the iSrcLine parameter mean that this particular branch is
  66182. ** always taken or never taken, respectively.
  66183. */
  66184. #if !defined(SQLITE_VDBE_COVERAGE)
  66185. # define VdbeBranchTaken(I,M)
  66186. #else
  66187. # define VdbeBranchTaken(I,M) vdbeTakeBranch(pOp->iSrcLine,I,M)
  66188. static void vdbeTakeBranch(int iSrcLine, u8 I, u8 M){
  66189. if( iSrcLine<=2 && ALWAYS(iSrcLine>0) ){
  66190. M = iSrcLine;
  66191. /* Assert the truth of VdbeCoverageAlwaysTaken() and
  66192. ** VdbeCoverageNeverTaken() */
  66193. assert( (M & I)==I );
  66194. }else{
  66195. if( sqlite3GlobalConfig.xVdbeBranch==0 ) return; /*NO_TEST*/
  66196. sqlite3GlobalConfig.xVdbeBranch(sqlite3GlobalConfig.pVdbeBranchArg,
  66197. iSrcLine,I,M);
  66198. }
  66199. }
  66200. #endif
  66201. /*
  66202. ** Convert the given register into a string if it isn't one
  66203. ** already. Return non-zero if a malloc() fails.
  66204. */
  66205. #define Stringify(P, enc) \
  66206. if(((P)->flags&(MEM_Str|MEM_Blob))==0 && sqlite3VdbeMemStringify(P,enc,0)) \
  66207. { goto no_mem; }
  66208. /*
  66209. ** An ephemeral string value (signified by the MEM_Ephem flag) contains
  66210. ** a pointer to a dynamically allocated string where some other entity
  66211. ** is responsible for deallocating that string. Because the register
  66212. ** does not control the string, it might be deleted without the register
  66213. ** knowing it.
  66214. **
  66215. ** This routine converts an ephemeral string into a dynamically allocated
  66216. ** string that the register itself controls. In other words, it
  66217. ** converts an MEM_Ephem string into a string with P.z==P.zMalloc.
  66218. */
  66219. #define Deephemeralize(P) \
  66220. if( ((P)->flags&MEM_Ephem)!=0 \
  66221. && sqlite3VdbeMemMakeWriteable(P) ){ goto no_mem;}
  66222. /* Return true if the cursor was opened using the OP_OpenSorter opcode. */
  66223. #define isSorter(x) ((x)->pSorter!=0)
  66224. /*
  66225. ** Allocate VdbeCursor number iCur. Return a pointer to it. Return NULL
  66226. ** if we run out of memory.
  66227. */
  66228. static VdbeCursor *allocateCursor(
  66229. Vdbe *p, /* The virtual machine */
  66230. int iCur, /* Index of the new VdbeCursor */
  66231. int nField, /* Number of fields in the table or index */
  66232. int iDb, /* Database the cursor belongs to, or -1 */
  66233. int isBtreeCursor /* True for B-Tree. False for pseudo-table or vtab */
  66234. ){
  66235. /* Find the memory cell that will be used to store the blob of memory
  66236. ** required for this VdbeCursor structure. It is convenient to use a
  66237. ** vdbe memory cell to manage the memory allocation required for a
  66238. ** VdbeCursor structure for the following reasons:
  66239. **
  66240. ** * Sometimes cursor numbers are used for a couple of different
  66241. ** purposes in a vdbe program. The different uses might require
  66242. ** different sized allocations. Memory cells provide growable
  66243. ** allocations.
  66244. **
  66245. ** * When using ENABLE_MEMORY_MANAGEMENT, memory cell buffers can
  66246. ** be freed lazily via the sqlite3_release_memory() API. This
  66247. ** minimizes the number of malloc calls made by the system.
  66248. **
  66249. ** Memory cells for cursors are allocated at the top of the address
  66250. ** space. Memory cell (p->nMem) corresponds to cursor 0. Space for
  66251. ** cursor 1 is managed by memory cell (p->nMem-1), etc.
  66252. */
  66253. Mem *pMem = &p->aMem[p->nMem-iCur];
  66254. int nByte;
  66255. VdbeCursor *pCx = 0;
  66256. nByte =
  66257. ROUND8(sizeof(VdbeCursor)) + 2*sizeof(u32)*nField +
  66258. (isBtreeCursor?sqlite3BtreeCursorSize():0);
  66259. assert( iCur<p->nCursor );
  66260. if( p->apCsr[iCur] ){
  66261. sqlite3VdbeFreeCursor(p, p->apCsr[iCur]);
  66262. p->apCsr[iCur] = 0;
  66263. }
  66264. if( SQLITE_OK==sqlite3VdbeMemClearAndResize(pMem, nByte) ){
  66265. p->apCsr[iCur] = pCx = (VdbeCursor*)pMem->z;
  66266. memset(pCx, 0, sizeof(VdbeCursor));
  66267. pCx->iDb = iDb;
  66268. pCx->nField = nField;
  66269. pCx->aOffset = &pCx->aType[nField];
  66270. if( isBtreeCursor ){
  66271. pCx->pCursor = (BtCursor*)
  66272. &pMem->z[ROUND8(sizeof(VdbeCursor))+2*sizeof(u32)*nField];
  66273. sqlite3BtreeCursorZero(pCx->pCursor);
  66274. }
  66275. }
  66276. return pCx;
  66277. }
  66278. /*
  66279. ** Try to convert a value into a numeric representation if we can
  66280. ** do so without loss of information. In other words, if the string
  66281. ** looks like a number, convert it into a number. If it does not
  66282. ** look like a number, leave it alone.
  66283. **
  66284. ** If the bTryForInt flag is true, then extra effort is made to give
  66285. ** an integer representation. Strings that look like floating point
  66286. ** values but which have no fractional component (example: '48.00')
  66287. ** will have a MEM_Int representation when bTryForInt is true.
  66288. **
  66289. ** If bTryForInt is false, then if the input string contains a decimal
  66290. ** point or exponential notation, the result is only MEM_Real, even
  66291. ** if there is an exact integer representation of the quantity.
  66292. */
  66293. static void applyNumericAffinity(Mem *pRec, int bTryForInt){
  66294. double rValue;
  66295. i64 iValue;
  66296. u8 enc = pRec->enc;
  66297. assert( (pRec->flags & (MEM_Str|MEM_Int|MEM_Real))==MEM_Str );
  66298. if( sqlite3AtoF(pRec->z, &rValue, pRec->n, enc)==0 ) return;
  66299. if( 0==sqlite3Atoi64(pRec->z, &iValue, pRec->n, enc) ){
  66300. pRec->u.i = iValue;
  66301. pRec->flags |= MEM_Int;
  66302. }else{
  66303. pRec->u.r = rValue;
  66304. pRec->flags |= MEM_Real;
  66305. if( bTryForInt ) sqlite3VdbeIntegerAffinity(pRec);
  66306. }
  66307. }
  66308. /*
  66309. ** Processing is determine by the affinity parameter:
  66310. **
  66311. ** SQLITE_AFF_INTEGER:
  66312. ** SQLITE_AFF_REAL:
  66313. ** SQLITE_AFF_NUMERIC:
  66314. ** Try to convert pRec to an integer representation or a
  66315. ** floating-point representation if an integer representation
  66316. ** is not possible. Note that the integer representation is
  66317. ** always preferred, even if the affinity is REAL, because
  66318. ** an integer representation is more space efficient on disk.
  66319. **
  66320. ** SQLITE_AFF_TEXT:
  66321. ** Convert pRec to a text representation.
  66322. **
  66323. ** SQLITE_AFF_NONE:
  66324. ** No-op. pRec is unchanged.
  66325. */
  66326. static void applyAffinity(
  66327. Mem *pRec, /* The value to apply affinity to */
  66328. char affinity, /* The affinity to be applied */
  66329. u8 enc /* Use this text encoding */
  66330. ){
  66331. if( affinity>=SQLITE_AFF_NUMERIC ){
  66332. assert( affinity==SQLITE_AFF_INTEGER || affinity==SQLITE_AFF_REAL
  66333. || affinity==SQLITE_AFF_NUMERIC );
  66334. if( (pRec->flags & MEM_Int)==0 ){
  66335. if( (pRec->flags & MEM_Real)==0 ){
  66336. if( pRec->flags & MEM_Str ) applyNumericAffinity(pRec,1);
  66337. }else{
  66338. sqlite3VdbeIntegerAffinity(pRec);
  66339. }
  66340. }
  66341. }else if( affinity==SQLITE_AFF_TEXT ){
  66342. /* Only attempt the conversion to TEXT if there is an integer or real
  66343. ** representation (blob and NULL do not get converted) but no string
  66344. ** representation.
  66345. */
  66346. if( 0==(pRec->flags&MEM_Str) && (pRec->flags&(MEM_Real|MEM_Int)) ){
  66347. sqlite3VdbeMemStringify(pRec, enc, 1);
  66348. }
  66349. pRec->flags &= ~(MEM_Real|MEM_Int);
  66350. }
  66351. }
  66352. /*
  66353. ** Try to convert the type of a function argument or a result column
  66354. ** into a numeric representation. Use either INTEGER or REAL whichever
  66355. ** is appropriate. But only do the conversion if it is possible without
  66356. ** loss of information and return the revised type of the argument.
  66357. */
  66358. SQLITE_API int SQLITE_STDCALL sqlite3_value_numeric_type(sqlite3_value *pVal){
  66359. int eType = sqlite3_value_type(pVal);
  66360. if( eType==SQLITE_TEXT ){
  66361. Mem *pMem = (Mem*)pVal;
  66362. applyNumericAffinity(pMem, 0);
  66363. eType = sqlite3_value_type(pVal);
  66364. }
  66365. return eType;
  66366. }
  66367. /*
  66368. ** Exported version of applyAffinity(). This one works on sqlite3_value*,
  66369. ** not the internal Mem* type.
  66370. */
  66371. SQLITE_PRIVATE void sqlite3ValueApplyAffinity(
  66372. sqlite3_value *pVal,
  66373. u8 affinity,
  66374. u8 enc
  66375. ){
  66376. applyAffinity((Mem *)pVal, affinity, enc);
  66377. }
  66378. /*
  66379. ** pMem currently only holds a string type (or maybe a BLOB that we can
  66380. ** interpret as a string if we want to). Compute its corresponding
  66381. ** numeric type, if has one. Set the pMem->u.r and pMem->u.i fields
  66382. ** accordingly.
  66383. */
  66384. static u16 SQLITE_NOINLINE computeNumericType(Mem *pMem){
  66385. assert( (pMem->flags & (MEM_Int|MEM_Real))==0 );
  66386. assert( (pMem->flags & (MEM_Str|MEM_Blob))!=0 );
  66387. if( sqlite3AtoF(pMem->z, &pMem->u.r, pMem->n, pMem->enc)==0 ){
  66388. return 0;
  66389. }
  66390. if( sqlite3Atoi64(pMem->z, &pMem->u.i, pMem->n, pMem->enc)==SQLITE_OK ){
  66391. return MEM_Int;
  66392. }
  66393. return MEM_Real;
  66394. }
  66395. /*
  66396. ** Return the numeric type for pMem, either MEM_Int or MEM_Real or both or
  66397. ** none.
  66398. **
  66399. ** Unlike applyNumericAffinity(), this routine does not modify pMem->flags.
  66400. ** But it does set pMem->u.r and pMem->u.i appropriately.
  66401. */
  66402. static u16 numericType(Mem *pMem){
  66403. if( pMem->flags & (MEM_Int|MEM_Real) ){
  66404. return pMem->flags & (MEM_Int|MEM_Real);
  66405. }
  66406. if( pMem->flags & (MEM_Str|MEM_Blob) ){
  66407. return computeNumericType(pMem);
  66408. }
  66409. return 0;
  66410. }
  66411. #ifdef SQLITE_DEBUG
  66412. /*
  66413. ** Write a nice string representation of the contents of cell pMem
  66414. ** into buffer zBuf, length nBuf.
  66415. */
  66416. SQLITE_PRIVATE void sqlite3VdbeMemPrettyPrint(Mem *pMem, char *zBuf){
  66417. char *zCsr = zBuf;
  66418. int f = pMem->flags;
  66419. static const char *const encnames[] = {"(X)", "(8)", "(16LE)", "(16BE)"};
  66420. if( f&MEM_Blob ){
  66421. int i;
  66422. char c;
  66423. if( f & MEM_Dyn ){
  66424. c = 'z';
  66425. assert( (f & (MEM_Static|MEM_Ephem))==0 );
  66426. }else if( f & MEM_Static ){
  66427. c = 't';
  66428. assert( (f & (MEM_Dyn|MEM_Ephem))==0 );
  66429. }else if( f & MEM_Ephem ){
  66430. c = 'e';
  66431. assert( (f & (MEM_Static|MEM_Dyn))==0 );
  66432. }else{
  66433. c = 's';
  66434. }
  66435. sqlite3_snprintf(100, zCsr, "%c", c);
  66436. zCsr += sqlite3Strlen30(zCsr);
  66437. sqlite3_snprintf(100, zCsr, "%d[", pMem->n);
  66438. zCsr += sqlite3Strlen30(zCsr);
  66439. for(i=0; i<16 && i<pMem->n; i++){
  66440. sqlite3_snprintf(100, zCsr, "%02X", ((int)pMem->z[i] & 0xFF));
  66441. zCsr += sqlite3Strlen30(zCsr);
  66442. }
  66443. for(i=0; i<16 && i<pMem->n; i++){
  66444. char z = pMem->z[i];
  66445. if( z<32 || z>126 ) *zCsr++ = '.';
  66446. else *zCsr++ = z;
  66447. }
  66448. sqlite3_snprintf(100, zCsr, "]%s", encnames[pMem->enc]);
  66449. zCsr += sqlite3Strlen30(zCsr);
  66450. if( f & MEM_Zero ){
  66451. sqlite3_snprintf(100, zCsr,"+%dz",pMem->u.nZero);
  66452. zCsr += sqlite3Strlen30(zCsr);
  66453. }
  66454. *zCsr = '\0';
  66455. }else if( f & MEM_Str ){
  66456. int j, k;
  66457. zBuf[0] = ' ';
  66458. if( f & MEM_Dyn ){
  66459. zBuf[1] = 'z';
  66460. assert( (f & (MEM_Static|MEM_Ephem))==0 );
  66461. }else if( f & MEM_Static ){
  66462. zBuf[1] = 't';
  66463. assert( (f & (MEM_Dyn|MEM_Ephem))==0 );
  66464. }else if( f & MEM_Ephem ){
  66465. zBuf[1] = 'e';
  66466. assert( (f & (MEM_Static|MEM_Dyn))==0 );
  66467. }else{
  66468. zBuf[1] = 's';
  66469. }
  66470. k = 2;
  66471. sqlite3_snprintf(100, &zBuf[k], "%d", pMem->n);
  66472. k += sqlite3Strlen30(&zBuf[k]);
  66473. zBuf[k++] = '[';
  66474. for(j=0; j<15 && j<pMem->n; j++){
  66475. u8 c = pMem->z[j];
  66476. if( c>=0x20 && c<0x7f ){
  66477. zBuf[k++] = c;
  66478. }else{
  66479. zBuf[k++] = '.';
  66480. }
  66481. }
  66482. zBuf[k++] = ']';
  66483. sqlite3_snprintf(100,&zBuf[k], encnames[pMem->enc]);
  66484. k += sqlite3Strlen30(&zBuf[k]);
  66485. zBuf[k++] = 0;
  66486. }
  66487. }
  66488. #endif
  66489. #ifdef SQLITE_DEBUG
  66490. /*
  66491. ** Print the value of a register for tracing purposes:
  66492. */
  66493. static void memTracePrint(Mem *p){
  66494. if( p->flags & MEM_Undefined ){
  66495. printf(" undefined");
  66496. }else if( p->flags & MEM_Null ){
  66497. printf(" NULL");
  66498. }else if( (p->flags & (MEM_Int|MEM_Str))==(MEM_Int|MEM_Str) ){
  66499. printf(" si:%lld", p->u.i);
  66500. }else if( p->flags & MEM_Int ){
  66501. printf(" i:%lld", p->u.i);
  66502. #ifndef SQLITE_OMIT_FLOATING_POINT
  66503. }else if( p->flags & MEM_Real ){
  66504. printf(" r:%g", p->u.r);
  66505. #endif
  66506. }else if( p->flags & MEM_RowSet ){
  66507. printf(" (rowset)");
  66508. }else{
  66509. char zBuf[200];
  66510. sqlite3VdbeMemPrettyPrint(p, zBuf);
  66511. printf(" %s", zBuf);
  66512. }
  66513. }
  66514. static void registerTrace(int iReg, Mem *p){
  66515. printf("REG[%d] = ", iReg);
  66516. memTracePrint(p);
  66517. printf("\n");
  66518. }
  66519. #endif
  66520. #ifdef SQLITE_DEBUG
  66521. # define REGISTER_TRACE(R,M) if(db->flags&SQLITE_VdbeTrace)registerTrace(R,M)
  66522. #else
  66523. # define REGISTER_TRACE(R,M)
  66524. #endif
  66525. #ifdef VDBE_PROFILE
  66526. /*
  66527. ** hwtime.h contains inline assembler code for implementing
  66528. ** high-performance timing routines.
  66529. */
  66530. /************** Include hwtime.h in the middle of vdbe.c *********************/
  66531. /************** Begin file hwtime.h ******************************************/
  66532. /*
  66533. ** 2008 May 27
  66534. **
  66535. ** The author disclaims copyright to this source code. In place of
  66536. ** a legal notice, here is a blessing:
  66537. **
  66538. ** May you do good and not evil.
  66539. ** May you find forgiveness for yourself and forgive others.
  66540. ** May you share freely, never taking more than you give.
  66541. **
  66542. ******************************************************************************
  66543. **
  66544. ** This file contains inline asm code for retrieving "high-performance"
  66545. ** counters for x86 class CPUs.
  66546. */
  66547. #ifndef _HWTIME_H_
  66548. #define _HWTIME_H_
  66549. /*
  66550. ** The following routine only works on pentium-class (or newer) processors.
  66551. ** It uses the RDTSC opcode to read the cycle count value out of the
  66552. ** processor and returns that value. This can be used for high-res
  66553. ** profiling.
  66554. */
  66555. #if (defined(__GNUC__) || defined(_MSC_VER)) && \
  66556. (defined(i386) || defined(__i386__) || defined(_M_IX86))
  66557. #if defined(__GNUC__)
  66558. __inline__ sqlite_uint64 sqlite3Hwtime(void){
  66559. unsigned int lo, hi;
  66560. __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
  66561. return (sqlite_uint64)hi << 32 | lo;
  66562. }
  66563. #elif defined(_MSC_VER)
  66564. __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
  66565. __asm {
  66566. rdtsc
  66567. ret ; return value at EDX:EAX
  66568. }
  66569. }
  66570. #endif
  66571. #elif (defined(__GNUC__) && defined(__x86_64__))
  66572. __inline__ sqlite_uint64 sqlite3Hwtime(void){
  66573. unsigned long val;
  66574. __asm__ __volatile__ ("rdtsc" : "=A" (val));
  66575. return val;
  66576. }
  66577. #elif (defined(__GNUC__) && defined(__ppc__))
  66578. __inline__ sqlite_uint64 sqlite3Hwtime(void){
  66579. unsigned long long retval;
  66580. unsigned long junk;
  66581. __asm__ __volatile__ ("\n\
  66582. 1: mftbu %1\n\
  66583. mftb %L0\n\
  66584. mftbu %0\n\
  66585. cmpw %0,%1\n\
  66586. bne 1b"
  66587. : "=r" (retval), "=r" (junk));
  66588. return retval;
  66589. }
  66590. #else
  66591. #error Need implementation of sqlite3Hwtime() for your platform.
  66592. /*
  66593. ** To compile without implementing sqlite3Hwtime() for your platform,
  66594. ** you can remove the above #error and use the following
  66595. ** stub function. You will lose timing support for many
  66596. ** of the debugging and testing utilities, but it should at
  66597. ** least compile and run.
  66598. */
  66599. SQLITE_PRIVATE sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
  66600. #endif
  66601. #endif /* !defined(_HWTIME_H_) */
  66602. /************** End of hwtime.h **********************************************/
  66603. /************** Continuing where we left off in vdbe.c ***********************/
  66604. #endif
  66605. #ifndef NDEBUG
  66606. /*
  66607. ** This function is only called from within an assert() expression. It
  66608. ** checks that the sqlite3.nTransaction variable is correctly set to
  66609. ** the number of non-transaction savepoints currently in the
  66610. ** linked list starting at sqlite3.pSavepoint.
  66611. **
  66612. ** Usage:
  66613. **
  66614. ** assert( checkSavepointCount(db) );
  66615. */
  66616. static int checkSavepointCount(sqlite3 *db){
  66617. int n = 0;
  66618. Savepoint *p;
  66619. for(p=db->pSavepoint; p; p=p->pNext) n++;
  66620. assert( n==(db->nSavepoint + db->isTransactionSavepoint) );
  66621. return 1;
  66622. }
  66623. #endif
  66624. /*
  66625. ** Return the register of pOp->p2 after first preparing it to be
  66626. ** overwritten with an integer value.
  66627. */
  66628. static Mem *out2Prerelease(Vdbe *p, VdbeOp *pOp){
  66629. Mem *pOut;
  66630. assert( pOp->p2>0 );
  66631. assert( pOp->p2<=(p->nMem-p->nCursor) );
  66632. pOut = &p->aMem[pOp->p2];
  66633. memAboutToChange(p, pOut);
  66634. if( VdbeMemDynamic(pOut) ) sqlite3VdbeMemSetNull(pOut);
  66635. pOut->flags = MEM_Int;
  66636. return pOut;
  66637. }
  66638. /*
  66639. ** Execute as much of a VDBE program as we can.
  66640. ** This is the core of sqlite3_step().
  66641. */
  66642. SQLITE_PRIVATE int sqlite3VdbeExec(
  66643. Vdbe *p /* The VDBE */
  66644. ){
  66645. Op *aOp = p->aOp; /* Copy of p->aOp */
  66646. Op *pOp = aOp; /* Current operation */
  66647. #if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE)
  66648. Op *pOrigOp; /* Value of pOp at the top of the loop */
  66649. #endif
  66650. int rc = SQLITE_OK; /* Value to return */
  66651. sqlite3 *db = p->db; /* The database */
  66652. u8 resetSchemaOnFault = 0; /* Reset schema after an error if positive */
  66653. u8 encoding = ENC(db); /* The database encoding */
  66654. int iCompare = 0; /* Result of last OP_Compare operation */
  66655. unsigned nVmStep = 0; /* Number of virtual machine steps */
  66656. #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
  66657. unsigned nProgressLimit = 0;/* Invoke xProgress() when nVmStep reaches this */
  66658. #endif
  66659. Mem *aMem = p->aMem; /* Copy of p->aMem */
  66660. Mem *pIn1 = 0; /* 1st input operand */
  66661. Mem *pIn2 = 0; /* 2nd input operand */
  66662. Mem *pIn3 = 0; /* 3rd input operand */
  66663. Mem *pOut = 0; /* Output operand */
  66664. int *aPermute = 0; /* Permutation of columns for OP_Compare */
  66665. i64 lastRowid = db->lastRowid; /* Saved value of the last insert ROWID */
  66666. #ifdef VDBE_PROFILE
  66667. u64 start; /* CPU clock count at start of opcode */
  66668. #endif
  66669. /*** INSERT STACK UNION HERE ***/
  66670. assert( p->magic==VDBE_MAGIC_RUN ); /* sqlite3_step() verifies this */
  66671. sqlite3VdbeEnter(p);
  66672. if( p->rc==SQLITE_NOMEM ){
  66673. /* This happens if a malloc() inside a call to sqlite3_column_text() or
  66674. ** sqlite3_column_text16() failed. */
  66675. goto no_mem;
  66676. }
  66677. assert( p->rc==SQLITE_OK || p->rc==SQLITE_BUSY );
  66678. assert( p->bIsReader || p->readOnly!=0 );
  66679. p->rc = SQLITE_OK;
  66680. p->iCurrentTime = 0;
  66681. assert( p->explain==0 );
  66682. p->pResultSet = 0;
  66683. db->busyHandler.nBusy = 0;
  66684. if( db->u1.isInterrupted ) goto abort_due_to_interrupt;
  66685. sqlite3VdbeIOTraceSql(p);
  66686. #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
  66687. if( db->xProgress ){
  66688. assert( 0 < db->nProgressOps );
  66689. nProgressLimit = (unsigned)p->aCounter[SQLITE_STMTSTATUS_VM_STEP];
  66690. if( nProgressLimit==0 ){
  66691. nProgressLimit = db->nProgressOps;
  66692. }else{
  66693. nProgressLimit %= (unsigned)db->nProgressOps;
  66694. }
  66695. }
  66696. #endif
  66697. #ifdef SQLITE_DEBUG
  66698. sqlite3BeginBenignMalloc();
  66699. if( p->pc==0
  66700. && (p->db->flags & (SQLITE_VdbeListing|SQLITE_VdbeEQP|SQLITE_VdbeTrace))!=0
  66701. ){
  66702. int i;
  66703. int once = 1;
  66704. sqlite3VdbePrintSql(p);
  66705. if( p->db->flags & SQLITE_VdbeListing ){
  66706. printf("VDBE Program Listing:\n");
  66707. for(i=0; i<p->nOp; i++){
  66708. sqlite3VdbePrintOp(stdout, i, &aOp[i]);
  66709. }
  66710. }
  66711. if( p->db->flags & SQLITE_VdbeEQP ){
  66712. for(i=0; i<p->nOp; i++){
  66713. if( aOp[i].opcode==OP_Explain ){
  66714. if( once ) printf("VDBE Query Plan:\n");
  66715. printf("%s\n", aOp[i].p4.z);
  66716. once = 0;
  66717. }
  66718. }
  66719. }
  66720. if( p->db->flags & SQLITE_VdbeTrace ) printf("VDBE Trace:\n");
  66721. }
  66722. sqlite3EndBenignMalloc();
  66723. #endif
  66724. for(pOp=&aOp[p->pc]; rc==SQLITE_OK; pOp++){
  66725. assert( pOp>=aOp && pOp<&aOp[p->nOp]);
  66726. if( db->mallocFailed ) goto no_mem;
  66727. #ifdef VDBE_PROFILE
  66728. start = sqlite3Hwtime();
  66729. #endif
  66730. nVmStep++;
  66731. #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
  66732. if( p->anExec ) p->anExec[(int)(pOp-aOp)]++;
  66733. #endif
  66734. /* Only allow tracing if SQLITE_DEBUG is defined.
  66735. */
  66736. #ifdef SQLITE_DEBUG
  66737. if( db->flags & SQLITE_VdbeTrace ){
  66738. sqlite3VdbePrintOp(stdout, (int)(pOp - aOp), pOp);
  66739. }
  66740. #endif
  66741. /* Check to see if we need to simulate an interrupt. This only happens
  66742. ** if we have a special test build.
  66743. */
  66744. #ifdef SQLITE_TEST
  66745. if( sqlite3_interrupt_count>0 ){
  66746. sqlite3_interrupt_count--;
  66747. if( sqlite3_interrupt_count==0 ){
  66748. sqlite3_interrupt(db);
  66749. }
  66750. }
  66751. #endif
  66752. /* Sanity checking on other operands */
  66753. #ifdef SQLITE_DEBUG
  66754. assert( pOp->opflags==sqlite3OpcodeProperty[pOp->opcode] );
  66755. if( (pOp->opflags & OPFLG_IN1)!=0 ){
  66756. assert( pOp->p1>0 );
  66757. assert( pOp->p1<=(p->nMem-p->nCursor) );
  66758. assert( memIsValid(&aMem[pOp->p1]) );
  66759. assert( sqlite3VdbeCheckMemInvariants(&aMem[pOp->p1]) );
  66760. REGISTER_TRACE(pOp->p1, &aMem[pOp->p1]);
  66761. }
  66762. if( (pOp->opflags & OPFLG_IN2)!=0 ){
  66763. assert( pOp->p2>0 );
  66764. assert( pOp->p2<=(p->nMem-p->nCursor) );
  66765. assert( memIsValid(&aMem[pOp->p2]) );
  66766. assert( sqlite3VdbeCheckMemInvariants(&aMem[pOp->p2]) );
  66767. REGISTER_TRACE(pOp->p2, &aMem[pOp->p2]);
  66768. }
  66769. if( (pOp->opflags & OPFLG_IN3)!=0 ){
  66770. assert( pOp->p3>0 );
  66771. assert( pOp->p3<=(p->nMem-p->nCursor) );
  66772. assert( memIsValid(&aMem[pOp->p3]) );
  66773. assert( sqlite3VdbeCheckMemInvariants(&aMem[pOp->p3]) );
  66774. REGISTER_TRACE(pOp->p3, &aMem[pOp->p3]);
  66775. }
  66776. if( (pOp->opflags & OPFLG_OUT2)!=0 ){
  66777. assert( pOp->p2>0 );
  66778. assert( pOp->p2<=(p->nMem-p->nCursor) );
  66779. memAboutToChange(p, &aMem[pOp->p2]);
  66780. }
  66781. if( (pOp->opflags & OPFLG_OUT3)!=0 ){
  66782. assert( pOp->p3>0 );
  66783. assert( pOp->p3<=(p->nMem-p->nCursor) );
  66784. memAboutToChange(p, &aMem[pOp->p3]);
  66785. }
  66786. #endif
  66787. #if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE)
  66788. pOrigOp = pOp;
  66789. #endif
  66790. switch( pOp->opcode ){
  66791. /*****************************************************************************
  66792. ** What follows is a massive switch statement where each case implements a
  66793. ** separate instruction in the virtual machine. If we follow the usual
  66794. ** indentation conventions, each case should be indented by 6 spaces. But
  66795. ** that is a lot of wasted space on the left margin. So the code within
  66796. ** the switch statement will break with convention and be flush-left. Another
  66797. ** big comment (similar to this one) will mark the point in the code where
  66798. ** we transition back to normal indentation.
  66799. **
  66800. ** The formatting of each case is important. The makefile for SQLite
  66801. ** generates two C files "opcodes.h" and "opcodes.c" by scanning this
  66802. ** file looking for lines that begin with "case OP_". The opcodes.h files
  66803. ** will be filled with #defines that give unique integer values to each
  66804. ** opcode and the opcodes.c file is filled with an array of strings where
  66805. ** each string is the symbolic name for the corresponding opcode. If the
  66806. ** case statement is followed by a comment of the form "/# same as ... #/"
  66807. ** that comment is used to determine the particular value of the opcode.
  66808. **
  66809. ** Other keywords in the comment that follows each case are used to
  66810. ** construct the OPFLG_INITIALIZER value that initializes opcodeProperty[].
  66811. ** Keywords include: in1, in2, in3, out2, out3. See
  66812. ** the mkopcodeh.awk script for additional information.
  66813. **
  66814. ** Documentation about VDBE opcodes is generated by scanning this file
  66815. ** for lines of that contain "Opcode:". That line and all subsequent
  66816. ** comment lines are used in the generation of the opcode.html documentation
  66817. ** file.
  66818. **
  66819. ** SUMMARY:
  66820. **
  66821. ** Formatting is important to scripts that scan this file.
  66822. ** Do not deviate from the formatting style currently in use.
  66823. **
  66824. *****************************************************************************/
  66825. /* Opcode: Goto * P2 * * *
  66826. **
  66827. ** An unconditional jump to address P2.
  66828. ** The next instruction executed will be
  66829. ** the one at index P2 from the beginning of
  66830. ** the program.
  66831. **
  66832. ** The P1 parameter is not actually used by this opcode. However, it
  66833. ** is sometimes set to 1 instead of 0 as a hint to the command-line shell
  66834. ** that this Goto is the bottom of a loop and that the lines from P2 down
  66835. ** to the current line should be indented for EXPLAIN output.
  66836. */
  66837. case OP_Goto: { /* jump */
  66838. jump_to_p2_and_check_for_interrupt:
  66839. pOp = &aOp[pOp->p2 - 1];
  66840. /* Opcodes that are used as the bottom of a loop (OP_Next, OP_Prev,
  66841. ** OP_VNext, OP_RowSetNext, or OP_SorterNext) all jump here upon
  66842. ** completion. Check to see if sqlite3_interrupt() has been called
  66843. ** or if the progress callback needs to be invoked.
  66844. **
  66845. ** This code uses unstructured "goto" statements and does not look clean.
  66846. ** But that is not due to sloppy coding habits. The code is written this
  66847. ** way for performance, to avoid having to run the interrupt and progress
  66848. ** checks on every opcode. This helps sqlite3_step() to run about 1.5%
  66849. ** faster according to "valgrind --tool=cachegrind" */
  66850. check_for_interrupt:
  66851. if( db->u1.isInterrupted ) goto abort_due_to_interrupt;
  66852. #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
  66853. /* Call the progress callback if it is configured and the required number
  66854. ** of VDBE ops have been executed (either since this invocation of
  66855. ** sqlite3VdbeExec() or since last time the progress callback was called).
  66856. ** If the progress callback returns non-zero, exit the virtual machine with
  66857. ** a return code SQLITE_ABORT.
  66858. */
  66859. if( db->xProgress!=0 && nVmStep>=nProgressLimit ){
  66860. assert( db->nProgressOps!=0 );
  66861. nProgressLimit = nVmStep + db->nProgressOps - (nVmStep%db->nProgressOps);
  66862. if( db->xProgress(db->pProgressArg) ){
  66863. rc = SQLITE_INTERRUPT;
  66864. goto vdbe_error_halt;
  66865. }
  66866. }
  66867. #endif
  66868. break;
  66869. }
  66870. /* Opcode: Gosub P1 P2 * * *
  66871. **
  66872. ** Write the current address onto register P1
  66873. ** and then jump to address P2.
  66874. */
  66875. case OP_Gosub: { /* jump */
  66876. assert( pOp->p1>0 && pOp->p1<=(p->nMem-p->nCursor) );
  66877. pIn1 = &aMem[pOp->p1];
  66878. assert( VdbeMemDynamic(pIn1)==0 );
  66879. memAboutToChange(p, pIn1);
  66880. pIn1->flags = MEM_Int;
  66881. pIn1->u.i = (int)(pOp-aOp);
  66882. REGISTER_TRACE(pOp->p1, pIn1);
  66883. /* Most jump operations do a goto to this spot in order to update
  66884. ** the pOp pointer. */
  66885. jump_to_p2:
  66886. pOp = &aOp[pOp->p2 - 1];
  66887. break;
  66888. }
  66889. /* Opcode: Return P1 * * * *
  66890. **
  66891. ** Jump to the next instruction after the address in register P1. After
  66892. ** the jump, register P1 becomes undefined.
  66893. */
  66894. case OP_Return: { /* in1 */
  66895. pIn1 = &aMem[pOp->p1];
  66896. assert( pIn1->flags==MEM_Int );
  66897. pOp = &aOp[pIn1->u.i];
  66898. pIn1->flags = MEM_Undefined;
  66899. break;
  66900. }
  66901. /* Opcode: InitCoroutine P1 P2 P3 * *
  66902. **
  66903. ** Set up register P1 so that it will Yield to the coroutine
  66904. ** located at address P3.
  66905. **
  66906. ** If P2!=0 then the coroutine implementation immediately follows
  66907. ** this opcode. So jump over the coroutine implementation to
  66908. ** address P2.
  66909. **
  66910. ** See also: EndCoroutine
  66911. */
  66912. case OP_InitCoroutine: { /* jump */
  66913. assert( pOp->p1>0 && pOp->p1<=(p->nMem-p->nCursor) );
  66914. assert( pOp->p2>=0 && pOp->p2<p->nOp );
  66915. assert( pOp->p3>=0 && pOp->p3<p->nOp );
  66916. pOut = &aMem[pOp->p1];
  66917. assert( !VdbeMemDynamic(pOut) );
  66918. pOut->u.i = pOp->p3 - 1;
  66919. pOut->flags = MEM_Int;
  66920. if( pOp->p2 ) goto jump_to_p2;
  66921. break;
  66922. }
  66923. /* Opcode: EndCoroutine P1 * * * *
  66924. **
  66925. ** The instruction at the address in register P1 is a Yield.
  66926. ** Jump to the P2 parameter of that Yield.
  66927. ** After the jump, register P1 becomes undefined.
  66928. **
  66929. ** See also: InitCoroutine
  66930. */
  66931. case OP_EndCoroutine: { /* in1 */
  66932. VdbeOp *pCaller;
  66933. pIn1 = &aMem[pOp->p1];
  66934. assert( pIn1->flags==MEM_Int );
  66935. assert( pIn1->u.i>=0 && pIn1->u.i<p->nOp );
  66936. pCaller = &aOp[pIn1->u.i];
  66937. assert( pCaller->opcode==OP_Yield );
  66938. assert( pCaller->p2>=0 && pCaller->p2<p->nOp );
  66939. pOp = &aOp[pCaller->p2 - 1];
  66940. pIn1->flags = MEM_Undefined;
  66941. break;
  66942. }
  66943. /* Opcode: Yield P1 P2 * * *
  66944. **
  66945. ** Swap the program counter with the value in register P1. This
  66946. ** has the effect of yielding to a coroutine.
  66947. **
  66948. ** If the coroutine that is launched by this instruction ends with
  66949. ** Yield or Return then continue to the next instruction. But if
  66950. ** the coroutine launched by this instruction ends with
  66951. ** EndCoroutine, then jump to P2 rather than continuing with the
  66952. ** next instruction.
  66953. **
  66954. ** See also: InitCoroutine
  66955. */
  66956. case OP_Yield: { /* in1, jump */
  66957. int pcDest;
  66958. pIn1 = &aMem[pOp->p1];
  66959. assert( VdbeMemDynamic(pIn1)==0 );
  66960. pIn1->flags = MEM_Int;
  66961. pcDest = (int)pIn1->u.i;
  66962. pIn1->u.i = (int)(pOp - aOp);
  66963. REGISTER_TRACE(pOp->p1, pIn1);
  66964. pOp = &aOp[pcDest];
  66965. break;
  66966. }
  66967. /* Opcode: HaltIfNull P1 P2 P3 P4 P5
  66968. ** Synopsis: if r[P3]=null halt
  66969. **
  66970. ** Check the value in register P3. If it is NULL then Halt using
  66971. ** parameter P1, P2, and P4 as if this were a Halt instruction. If the
  66972. ** value in register P3 is not NULL, then this routine is a no-op.
  66973. ** The P5 parameter should be 1.
  66974. */
  66975. case OP_HaltIfNull: { /* in3 */
  66976. pIn3 = &aMem[pOp->p3];
  66977. if( (pIn3->flags & MEM_Null)==0 ) break;
  66978. /* Fall through into OP_Halt */
  66979. }
  66980. /* Opcode: Halt P1 P2 * P4 P5
  66981. **
  66982. ** Exit immediately. All open cursors, etc are closed
  66983. ** automatically.
  66984. **
  66985. ** P1 is the result code returned by sqlite3_exec(), sqlite3_reset(),
  66986. ** or sqlite3_finalize(). For a normal halt, this should be SQLITE_OK (0).
  66987. ** For errors, it can be some other value. If P1!=0 then P2 will determine
  66988. ** whether or not to rollback the current transaction. Do not rollback
  66989. ** if P2==OE_Fail. Do the rollback if P2==OE_Rollback. If P2==OE_Abort,
  66990. ** then back out all changes that have occurred during this execution of the
  66991. ** VDBE, but do not rollback the transaction.
  66992. **
  66993. ** If P4 is not null then it is an error message string.
  66994. **
  66995. ** P5 is a value between 0 and 4, inclusive, that modifies the P4 string.
  66996. **
  66997. ** 0: (no change)
  66998. ** 1: NOT NULL contraint failed: P4
  66999. ** 2: UNIQUE constraint failed: P4
  67000. ** 3: CHECK constraint failed: P4
  67001. ** 4: FOREIGN KEY constraint failed: P4
  67002. **
  67003. ** If P5 is not zero and P4 is NULL, then everything after the ":" is
  67004. ** omitted.
  67005. **
  67006. ** There is an implied "Halt 0 0 0" instruction inserted at the very end of
  67007. ** every program. So a jump past the last instruction of the program
  67008. ** is the same as executing Halt.
  67009. */
  67010. case OP_Halt: {
  67011. const char *zType;
  67012. const char *zLogFmt;
  67013. VdbeFrame *pFrame;
  67014. int pcx;
  67015. pcx = (int)(pOp - aOp);
  67016. if( pOp->p1==SQLITE_OK && p->pFrame ){
  67017. /* Halt the sub-program. Return control to the parent frame. */
  67018. pFrame = p->pFrame;
  67019. p->pFrame = pFrame->pParent;
  67020. p->nFrame--;
  67021. sqlite3VdbeSetChanges(db, p->nChange);
  67022. pcx = sqlite3VdbeFrameRestore(pFrame);
  67023. lastRowid = db->lastRowid;
  67024. if( pOp->p2==OE_Ignore ){
  67025. /* Instruction pcx is the OP_Program that invoked the sub-program
  67026. ** currently being halted. If the p2 instruction of this OP_Halt
  67027. ** instruction is set to OE_Ignore, then the sub-program is throwing
  67028. ** an IGNORE exception. In this case jump to the address specified
  67029. ** as the p2 of the calling OP_Program. */
  67030. pcx = p->aOp[pcx].p2-1;
  67031. }
  67032. aOp = p->aOp;
  67033. aMem = p->aMem;
  67034. pOp = &aOp[pcx];
  67035. break;
  67036. }
  67037. p->rc = pOp->p1;
  67038. p->errorAction = (u8)pOp->p2;
  67039. p->pc = pcx;
  67040. if( p->rc ){
  67041. if( pOp->p5 ){
  67042. static const char * const azType[] = { "NOT NULL", "UNIQUE", "CHECK",
  67043. "FOREIGN KEY" };
  67044. assert( pOp->p5>=1 && pOp->p5<=4 );
  67045. testcase( pOp->p5==1 );
  67046. testcase( pOp->p5==2 );
  67047. testcase( pOp->p5==3 );
  67048. testcase( pOp->p5==4 );
  67049. zType = azType[pOp->p5-1];
  67050. }else{
  67051. zType = 0;
  67052. }
  67053. assert( zType!=0 || pOp->p4.z!=0 );
  67054. zLogFmt = "abort at %d in [%s]: %s";
  67055. if( zType && pOp->p4.z ){
  67056. sqlite3SetString(&p->zErrMsg, db, "%s constraint failed: %s",
  67057. zType, pOp->p4.z);
  67058. }else if( pOp->p4.z ){
  67059. sqlite3SetString(&p->zErrMsg, db, "%s", pOp->p4.z);
  67060. }else{
  67061. sqlite3SetString(&p->zErrMsg, db, "%s constraint failed", zType);
  67062. }
  67063. sqlite3_log(pOp->p1, zLogFmt, pcx, p->zSql, p->zErrMsg);
  67064. }
  67065. rc = sqlite3VdbeHalt(p);
  67066. assert( rc==SQLITE_BUSY || rc==SQLITE_OK || rc==SQLITE_ERROR );
  67067. if( rc==SQLITE_BUSY ){
  67068. p->rc = rc = SQLITE_BUSY;
  67069. }else{
  67070. assert( rc==SQLITE_OK || (p->rc&0xff)==SQLITE_CONSTRAINT );
  67071. assert( rc==SQLITE_OK || db->nDeferredCons>0 || db->nDeferredImmCons>0 );
  67072. rc = p->rc ? SQLITE_ERROR : SQLITE_DONE;
  67073. }
  67074. goto vdbe_return;
  67075. }
  67076. /* Opcode: Integer P1 P2 * * *
  67077. ** Synopsis: r[P2]=P1
  67078. **
  67079. ** The 32-bit integer value P1 is written into register P2.
  67080. */
  67081. case OP_Integer: { /* out2 */
  67082. pOut = out2Prerelease(p, pOp);
  67083. pOut->u.i = pOp->p1;
  67084. break;
  67085. }
  67086. /* Opcode: Int64 * P2 * P4 *
  67087. ** Synopsis: r[P2]=P4
  67088. **
  67089. ** P4 is a pointer to a 64-bit integer value.
  67090. ** Write that value into register P2.
  67091. */
  67092. case OP_Int64: { /* out2 */
  67093. pOut = out2Prerelease(p, pOp);
  67094. assert( pOp->p4.pI64!=0 );
  67095. pOut->u.i = *pOp->p4.pI64;
  67096. break;
  67097. }
  67098. #ifndef SQLITE_OMIT_FLOATING_POINT
  67099. /* Opcode: Real * P2 * P4 *
  67100. ** Synopsis: r[P2]=P4
  67101. **
  67102. ** P4 is a pointer to a 64-bit floating point value.
  67103. ** Write that value into register P2.
  67104. */
  67105. case OP_Real: { /* same as TK_FLOAT, out2 */
  67106. pOut = out2Prerelease(p, pOp);
  67107. pOut->flags = MEM_Real;
  67108. assert( !sqlite3IsNaN(*pOp->p4.pReal) );
  67109. pOut->u.r = *pOp->p4.pReal;
  67110. break;
  67111. }
  67112. #endif
  67113. /* Opcode: String8 * P2 * P4 *
  67114. ** Synopsis: r[P2]='P4'
  67115. **
  67116. ** P4 points to a nul terminated UTF-8 string. This opcode is transformed
  67117. ** into a String opcode before it is executed for the first time. During
  67118. ** this transformation, the length of string P4 is computed and stored
  67119. ** as the P1 parameter.
  67120. */
  67121. case OP_String8: { /* same as TK_STRING, out2 */
  67122. assert( pOp->p4.z!=0 );
  67123. pOut = out2Prerelease(p, pOp);
  67124. pOp->opcode = OP_String;
  67125. pOp->p1 = sqlite3Strlen30(pOp->p4.z);
  67126. #ifndef SQLITE_OMIT_UTF16
  67127. if( encoding!=SQLITE_UTF8 ){
  67128. rc = sqlite3VdbeMemSetStr(pOut, pOp->p4.z, -1, SQLITE_UTF8, SQLITE_STATIC);
  67129. if( rc==SQLITE_TOOBIG ) goto too_big;
  67130. if( SQLITE_OK!=sqlite3VdbeChangeEncoding(pOut, encoding) ) goto no_mem;
  67131. assert( pOut->szMalloc>0 && pOut->zMalloc==pOut->z );
  67132. assert( VdbeMemDynamic(pOut)==0 );
  67133. pOut->szMalloc = 0;
  67134. pOut->flags |= MEM_Static;
  67135. if( pOp->p4type==P4_DYNAMIC ){
  67136. sqlite3DbFree(db, pOp->p4.z);
  67137. }
  67138. pOp->p4type = P4_DYNAMIC;
  67139. pOp->p4.z = pOut->z;
  67140. pOp->p1 = pOut->n;
  67141. }
  67142. #endif
  67143. if( pOp->p1>db->aLimit[SQLITE_LIMIT_LENGTH] ){
  67144. goto too_big;
  67145. }
  67146. /* Fall through to the next case, OP_String */
  67147. }
  67148. /* Opcode: String P1 P2 P3 P4 P5
  67149. ** Synopsis: r[P2]='P4' (len=P1)
  67150. **
  67151. ** The string value P4 of length P1 (bytes) is stored in register P2.
  67152. **
  67153. ** If P5!=0 and the content of register P3 is greater than zero, then
  67154. ** the datatype of the register P2 is converted to BLOB. The content is
  67155. ** the same sequence of bytes, it is merely interpreted as a BLOB instead
  67156. ** of a string, as if it had been CAST.
  67157. */
  67158. case OP_String: { /* out2 */
  67159. assert( pOp->p4.z!=0 );
  67160. pOut = out2Prerelease(p, pOp);
  67161. pOut->flags = MEM_Str|MEM_Static|MEM_Term;
  67162. pOut->z = pOp->p4.z;
  67163. pOut->n = pOp->p1;
  67164. pOut->enc = encoding;
  67165. UPDATE_MAX_BLOBSIZE(pOut);
  67166. if( pOp->p5 ){
  67167. assert( pOp->p3>0 );
  67168. assert( pOp->p3<=(p->nMem-p->nCursor) );
  67169. pIn3 = &aMem[pOp->p3];
  67170. assert( pIn3->flags & MEM_Int );
  67171. if( pIn3->u.i ) pOut->flags = MEM_Blob|MEM_Static|MEM_Term;
  67172. }
  67173. break;
  67174. }
  67175. /* Opcode: Null P1 P2 P3 * *
  67176. ** Synopsis: r[P2..P3]=NULL
  67177. **
  67178. ** Write a NULL into registers P2. If P3 greater than P2, then also write
  67179. ** NULL into register P3 and every register in between P2 and P3. If P3
  67180. ** is less than P2 (typically P3 is zero) then only register P2 is
  67181. ** set to NULL.
  67182. **
  67183. ** If the P1 value is non-zero, then also set the MEM_Cleared flag so that
  67184. ** NULL values will not compare equal even if SQLITE_NULLEQ is set on
  67185. ** OP_Ne or OP_Eq.
  67186. */
  67187. case OP_Null: { /* out2 */
  67188. int cnt;
  67189. u16 nullFlag;
  67190. pOut = out2Prerelease(p, pOp);
  67191. cnt = pOp->p3-pOp->p2;
  67192. assert( pOp->p3<=(p->nMem-p->nCursor) );
  67193. pOut->flags = nullFlag = pOp->p1 ? (MEM_Null|MEM_Cleared) : MEM_Null;
  67194. while( cnt>0 ){
  67195. pOut++;
  67196. memAboutToChange(p, pOut);
  67197. sqlite3VdbeMemSetNull(pOut);
  67198. pOut->flags = nullFlag;
  67199. cnt--;
  67200. }
  67201. break;
  67202. }
  67203. /* Opcode: SoftNull P1 * * * *
  67204. ** Synopsis: r[P1]=NULL
  67205. **
  67206. ** Set register P1 to have the value NULL as seen by the OP_MakeRecord
  67207. ** instruction, but do not free any string or blob memory associated with
  67208. ** the register, so that if the value was a string or blob that was
  67209. ** previously copied using OP_SCopy, the copies will continue to be valid.
  67210. */
  67211. case OP_SoftNull: {
  67212. assert( pOp->p1>0 && pOp->p1<=(p->nMem-p->nCursor) );
  67213. pOut = &aMem[pOp->p1];
  67214. pOut->flags = (pOut->flags|MEM_Null)&~MEM_Undefined;
  67215. break;
  67216. }
  67217. /* Opcode: Blob P1 P2 * P4 *
  67218. ** Synopsis: r[P2]=P4 (len=P1)
  67219. **
  67220. ** P4 points to a blob of data P1 bytes long. Store this
  67221. ** blob in register P2.
  67222. */
  67223. case OP_Blob: { /* out2 */
  67224. assert( pOp->p1 <= SQLITE_MAX_LENGTH );
  67225. pOut = out2Prerelease(p, pOp);
  67226. sqlite3VdbeMemSetStr(pOut, pOp->p4.z, pOp->p1, 0, 0);
  67227. pOut->enc = encoding;
  67228. UPDATE_MAX_BLOBSIZE(pOut);
  67229. break;
  67230. }
  67231. /* Opcode: Variable P1 P2 * P4 *
  67232. ** Synopsis: r[P2]=parameter(P1,P4)
  67233. **
  67234. ** Transfer the values of bound parameter P1 into register P2
  67235. **
  67236. ** If the parameter is named, then its name appears in P4.
  67237. ** The P4 value is used by sqlite3_bind_parameter_name().
  67238. */
  67239. case OP_Variable: { /* out2 */
  67240. Mem *pVar; /* Value being transferred */
  67241. assert( pOp->p1>0 && pOp->p1<=p->nVar );
  67242. assert( pOp->p4.z==0 || pOp->p4.z==p->azVar[pOp->p1-1] );
  67243. pVar = &p->aVar[pOp->p1 - 1];
  67244. if( sqlite3VdbeMemTooBig(pVar) ){
  67245. goto too_big;
  67246. }
  67247. pOut = out2Prerelease(p, pOp);
  67248. sqlite3VdbeMemShallowCopy(pOut, pVar, MEM_Static);
  67249. UPDATE_MAX_BLOBSIZE(pOut);
  67250. break;
  67251. }
  67252. /* Opcode: Move P1 P2 P3 * *
  67253. ** Synopsis: r[P2@P3]=r[P1@P3]
  67254. **
  67255. ** Move the P3 values in register P1..P1+P3-1 over into
  67256. ** registers P2..P2+P3-1. Registers P1..P1+P3-1 are
  67257. ** left holding a NULL. It is an error for register ranges
  67258. ** P1..P1+P3-1 and P2..P2+P3-1 to overlap. It is an error
  67259. ** for P3 to be less than 1.
  67260. */
  67261. case OP_Move: {
  67262. int n; /* Number of registers left to copy */
  67263. int p1; /* Register to copy from */
  67264. int p2; /* Register to copy to */
  67265. n = pOp->p3;
  67266. p1 = pOp->p1;
  67267. p2 = pOp->p2;
  67268. assert( n>0 && p1>0 && p2>0 );
  67269. assert( p1+n<=p2 || p2+n<=p1 );
  67270. pIn1 = &aMem[p1];
  67271. pOut = &aMem[p2];
  67272. do{
  67273. assert( pOut<=&aMem[(p->nMem-p->nCursor)] );
  67274. assert( pIn1<=&aMem[(p->nMem-p->nCursor)] );
  67275. assert( memIsValid(pIn1) );
  67276. memAboutToChange(p, pOut);
  67277. sqlite3VdbeMemMove(pOut, pIn1);
  67278. #ifdef SQLITE_DEBUG
  67279. if( pOut->pScopyFrom>=&aMem[p1] && pOut->pScopyFrom<pOut ){
  67280. pOut->pScopyFrom += pOp->p2 - p1;
  67281. }
  67282. #endif
  67283. Deephemeralize(pOut);
  67284. REGISTER_TRACE(p2++, pOut);
  67285. pIn1++;
  67286. pOut++;
  67287. }while( --n );
  67288. break;
  67289. }
  67290. /* Opcode: Copy P1 P2 P3 * *
  67291. ** Synopsis: r[P2@P3+1]=r[P1@P3+1]
  67292. **
  67293. ** Make a copy of registers P1..P1+P3 into registers P2..P2+P3.
  67294. **
  67295. ** This instruction makes a deep copy of the value. A duplicate
  67296. ** is made of any string or blob constant. See also OP_SCopy.
  67297. */
  67298. case OP_Copy: {
  67299. int n;
  67300. n = pOp->p3;
  67301. pIn1 = &aMem[pOp->p1];
  67302. pOut = &aMem[pOp->p2];
  67303. assert( pOut!=pIn1 );
  67304. while( 1 ){
  67305. sqlite3VdbeMemShallowCopy(pOut, pIn1, MEM_Ephem);
  67306. Deephemeralize(pOut);
  67307. #ifdef SQLITE_DEBUG
  67308. pOut->pScopyFrom = 0;
  67309. #endif
  67310. REGISTER_TRACE(pOp->p2+pOp->p3-n, pOut);
  67311. if( (n--)==0 ) break;
  67312. pOut++;
  67313. pIn1++;
  67314. }
  67315. break;
  67316. }
  67317. /* Opcode: SCopy P1 P2 * * *
  67318. ** Synopsis: r[P2]=r[P1]
  67319. **
  67320. ** Make a shallow copy of register P1 into register P2.
  67321. **
  67322. ** This instruction makes a shallow copy of the value. If the value
  67323. ** is a string or blob, then the copy is only a pointer to the
  67324. ** original and hence if the original changes so will the copy.
  67325. ** Worse, if the original is deallocated, the copy becomes invalid.
  67326. ** Thus the program must guarantee that the original will not change
  67327. ** during the lifetime of the copy. Use OP_Copy to make a complete
  67328. ** copy.
  67329. */
  67330. case OP_SCopy: { /* out2 */
  67331. pIn1 = &aMem[pOp->p1];
  67332. pOut = &aMem[pOp->p2];
  67333. assert( pOut!=pIn1 );
  67334. sqlite3VdbeMemShallowCopy(pOut, pIn1, MEM_Ephem);
  67335. #ifdef SQLITE_DEBUG
  67336. if( pOut->pScopyFrom==0 ) pOut->pScopyFrom = pIn1;
  67337. #endif
  67338. break;
  67339. }
  67340. /* Opcode: ResultRow P1 P2 * * *
  67341. ** Synopsis: output=r[P1@P2]
  67342. **
  67343. ** The registers P1 through P1+P2-1 contain a single row of
  67344. ** results. This opcode causes the sqlite3_step() call to terminate
  67345. ** with an SQLITE_ROW return code and it sets up the sqlite3_stmt
  67346. ** structure to provide access to the r(P1)..r(P1+P2-1) values as
  67347. ** the result row.
  67348. */
  67349. case OP_ResultRow: {
  67350. Mem *pMem;
  67351. int i;
  67352. assert( p->nResColumn==pOp->p2 );
  67353. assert( pOp->p1>0 );
  67354. assert( pOp->p1+pOp->p2<=(p->nMem-p->nCursor)+1 );
  67355. #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
  67356. /* Run the progress counter just before returning.
  67357. */
  67358. if( db->xProgress!=0
  67359. && nVmStep>=nProgressLimit
  67360. && db->xProgress(db->pProgressArg)!=0
  67361. ){
  67362. rc = SQLITE_INTERRUPT;
  67363. goto vdbe_error_halt;
  67364. }
  67365. #endif
  67366. /* If this statement has violated immediate foreign key constraints, do
  67367. ** not return the number of rows modified. And do not RELEASE the statement
  67368. ** transaction. It needs to be rolled back. */
  67369. if( SQLITE_OK!=(rc = sqlite3VdbeCheckFk(p, 0)) ){
  67370. assert( db->flags&SQLITE_CountRows );
  67371. assert( p->usesStmtJournal );
  67372. break;
  67373. }
  67374. /* If the SQLITE_CountRows flag is set in sqlite3.flags mask, then
  67375. ** DML statements invoke this opcode to return the number of rows
  67376. ** modified to the user. This is the only way that a VM that
  67377. ** opens a statement transaction may invoke this opcode.
  67378. **
  67379. ** In case this is such a statement, close any statement transaction
  67380. ** opened by this VM before returning control to the user. This is to
  67381. ** ensure that statement-transactions are always nested, not overlapping.
  67382. ** If the open statement-transaction is not closed here, then the user
  67383. ** may step another VM that opens its own statement transaction. This
  67384. ** may lead to overlapping statement transactions.
  67385. **
  67386. ** The statement transaction is never a top-level transaction. Hence
  67387. ** the RELEASE call below can never fail.
  67388. */
  67389. assert( p->iStatement==0 || db->flags&SQLITE_CountRows );
  67390. rc = sqlite3VdbeCloseStatement(p, SAVEPOINT_RELEASE);
  67391. if( NEVER(rc!=SQLITE_OK) ){
  67392. break;
  67393. }
  67394. /* Invalidate all ephemeral cursor row caches */
  67395. p->cacheCtr = (p->cacheCtr + 2)|1;
  67396. /* Make sure the results of the current row are \000 terminated
  67397. ** and have an assigned type. The results are de-ephemeralized as
  67398. ** a side effect.
  67399. */
  67400. pMem = p->pResultSet = &aMem[pOp->p1];
  67401. for(i=0; i<pOp->p2; i++){
  67402. assert( memIsValid(&pMem[i]) );
  67403. Deephemeralize(&pMem[i]);
  67404. assert( (pMem[i].flags & MEM_Ephem)==0
  67405. || (pMem[i].flags & (MEM_Str|MEM_Blob))==0 );
  67406. sqlite3VdbeMemNulTerminate(&pMem[i]);
  67407. REGISTER_TRACE(pOp->p1+i, &pMem[i]);
  67408. }
  67409. if( db->mallocFailed ) goto no_mem;
  67410. /* Return SQLITE_ROW
  67411. */
  67412. p->pc = (int)(pOp - aOp) + 1;
  67413. rc = SQLITE_ROW;
  67414. goto vdbe_return;
  67415. }
  67416. /* Opcode: Concat P1 P2 P3 * *
  67417. ** Synopsis: r[P3]=r[P2]+r[P1]
  67418. **
  67419. ** Add the text in register P1 onto the end of the text in
  67420. ** register P2 and store the result in register P3.
  67421. ** If either the P1 or P2 text are NULL then store NULL in P3.
  67422. **
  67423. ** P3 = P2 || P1
  67424. **
  67425. ** It is illegal for P1 and P3 to be the same register. Sometimes,
  67426. ** if P3 is the same register as P2, the implementation is able
  67427. ** to avoid a memcpy().
  67428. */
  67429. case OP_Concat: { /* same as TK_CONCAT, in1, in2, out3 */
  67430. i64 nByte;
  67431. pIn1 = &aMem[pOp->p1];
  67432. pIn2 = &aMem[pOp->p2];
  67433. pOut = &aMem[pOp->p3];
  67434. assert( pIn1!=pOut );
  67435. if( (pIn1->flags | pIn2->flags) & MEM_Null ){
  67436. sqlite3VdbeMemSetNull(pOut);
  67437. break;
  67438. }
  67439. if( ExpandBlob(pIn1) || ExpandBlob(pIn2) ) goto no_mem;
  67440. Stringify(pIn1, encoding);
  67441. Stringify(pIn2, encoding);
  67442. nByte = pIn1->n + pIn2->n;
  67443. if( nByte>db->aLimit[SQLITE_LIMIT_LENGTH] ){
  67444. goto too_big;
  67445. }
  67446. if( sqlite3VdbeMemGrow(pOut, (int)nByte+2, pOut==pIn2) ){
  67447. goto no_mem;
  67448. }
  67449. MemSetTypeFlag(pOut, MEM_Str);
  67450. if( pOut!=pIn2 ){
  67451. memcpy(pOut->z, pIn2->z, pIn2->n);
  67452. }
  67453. memcpy(&pOut->z[pIn2->n], pIn1->z, pIn1->n);
  67454. pOut->z[nByte]=0;
  67455. pOut->z[nByte+1] = 0;
  67456. pOut->flags |= MEM_Term;
  67457. pOut->n = (int)nByte;
  67458. pOut->enc = encoding;
  67459. UPDATE_MAX_BLOBSIZE(pOut);
  67460. break;
  67461. }
  67462. /* Opcode: Add P1 P2 P3 * *
  67463. ** Synopsis: r[P3]=r[P1]+r[P2]
  67464. **
  67465. ** Add the value in register P1 to the value in register P2
  67466. ** and store the result in register P3.
  67467. ** If either input is NULL, the result is NULL.
  67468. */
  67469. /* Opcode: Multiply P1 P2 P3 * *
  67470. ** Synopsis: r[P3]=r[P1]*r[P2]
  67471. **
  67472. **
  67473. ** Multiply the value in register P1 by the value in register P2
  67474. ** and store the result in register P3.
  67475. ** If either input is NULL, the result is NULL.
  67476. */
  67477. /* Opcode: Subtract P1 P2 P3 * *
  67478. ** Synopsis: r[P3]=r[P2]-r[P1]
  67479. **
  67480. ** Subtract the value in register P1 from the value in register P2
  67481. ** and store the result in register P3.
  67482. ** If either input is NULL, the result is NULL.
  67483. */
  67484. /* Opcode: Divide P1 P2 P3 * *
  67485. ** Synopsis: r[P3]=r[P2]/r[P1]
  67486. **
  67487. ** Divide the value in register P1 by the value in register P2
  67488. ** and store the result in register P3 (P3=P2/P1). If the value in
  67489. ** register P1 is zero, then the result is NULL. If either input is
  67490. ** NULL, the result is NULL.
  67491. */
  67492. /* Opcode: Remainder P1 P2 P3 * *
  67493. ** Synopsis: r[P3]=r[P2]%r[P1]
  67494. **
  67495. ** Compute the remainder after integer register P2 is divided by
  67496. ** register P1 and store the result in register P3.
  67497. ** If the value in register P1 is zero the result is NULL.
  67498. ** If either operand is NULL, the result is NULL.
  67499. */
  67500. case OP_Add: /* same as TK_PLUS, in1, in2, out3 */
  67501. case OP_Subtract: /* same as TK_MINUS, in1, in2, out3 */
  67502. case OP_Multiply: /* same as TK_STAR, in1, in2, out3 */
  67503. case OP_Divide: /* same as TK_SLASH, in1, in2, out3 */
  67504. case OP_Remainder: { /* same as TK_REM, in1, in2, out3 */
  67505. char bIntint; /* Started out as two integer operands */
  67506. u16 flags; /* Combined MEM_* flags from both inputs */
  67507. u16 type1; /* Numeric type of left operand */
  67508. u16 type2; /* Numeric type of right operand */
  67509. i64 iA; /* Integer value of left operand */
  67510. i64 iB; /* Integer value of right operand */
  67511. double rA; /* Real value of left operand */
  67512. double rB; /* Real value of right operand */
  67513. pIn1 = &aMem[pOp->p1];
  67514. type1 = numericType(pIn1);
  67515. pIn2 = &aMem[pOp->p2];
  67516. type2 = numericType(pIn2);
  67517. pOut = &aMem[pOp->p3];
  67518. flags = pIn1->flags | pIn2->flags;
  67519. if( (flags & MEM_Null)!=0 ) goto arithmetic_result_is_null;
  67520. if( (type1 & type2 & MEM_Int)!=0 ){
  67521. iA = pIn1->u.i;
  67522. iB = pIn2->u.i;
  67523. bIntint = 1;
  67524. switch( pOp->opcode ){
  67525. case OP_Add: if( sqlite3AddInt64(&iB,iA) ) goto fp_math; break;
  67526. case OP_Subtract: if( sqlite3SubInt64(&iB,iA) ) goto fp_math; break;
  67527. case OP_Multiply: if( sqlite3MulInt64(&iB,iA) ) goto fp_math; break;
  67528. case OP_Divide: {
  67529. if( iA==0 ) goto arithmetic_result_is_null;
  67530. if( iA==-1 && iB==SMALLEST_INT64 ) goto fp_math;
  67531. iB /= iA;
  67532. break;
  67533. }
  67534. default: {
  67535. if( iA==0 ) goto arithmetic_result_is_null;
  67536. if( iA==-1 ) iA = 1;
  67537. iB %= iA;
  67538. break;
  67539. }
  67540. }
  67541. pOut->u.i = iB;
  67542. MemSetTypeFlag(pOut, MEM_Int);
  67543. }else{
  67544. bIntint = 0;
  67545. fp_math:
  67546. rA = sqlite3VdbeRealValue(pIn1);
  67547. rB = sqlite3VdbeRealValue(pIn2);
  67548. switch( pOp->opcode ){
  67549. case OP_Add: rB += rA; break;
  67550. case OP_Subtract: rB -= rA; break;
  67551. case OP_Multiply: rB *= rA; break;
  67552. case OP_Divide: {
  67553. /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
  67554. if( rA==(double)0 ) goto arithmetic_result_is_null;
  67555. rB /= rA;
  67556. break;
  67557. }
  67558. default: {
  67559. iA = (i64)rA;
  67560. iB = (i64)rB;
  67561. if( iA==0 ) goto arithmetic_result_is_null;
  67562. if( iA==-1 ) iA = 1;
  67563. rB = (double)(iB % iA);
  67564. break;
  67565. }
  67566. }
  67567. #ifdef SQLITE_OMIT_FLOATING_POINT
  67568. pOut->u.i = rB;
  67569. MemSetTypeFlag(pOut, MEM_Int);
  67570. #else
  67571. if( sqlite3IsNaN(rB) ){
  67572. goto arithmetic_result_is_null;
  67573. }
  67574. pOut->u.r = rB;
  67575. MemSetTypeFlag(pOut, MEM_Real);
  67576. if( ((type1|type2)&MEM_Real)==0 && !bIntint ){
  67577. sqlite3VdbeIntegerAffinity(pOut);
  67578. }
  67579. #endif
  67580. }
  67581. break;
  67582. arithmetic_result_is_null:
  67583. sqlite3VdbeMemSetNull(pOut);
  67584. break;
  67585. }
  67586. /* Opcode: CollSeq P1 * * P4
  67587. **
  67588. ** P4 is a pointer to a CollSeq struct. If the next call to a user function
  67589. ** or aggregate calls sqlite3GetFuncCollSeq(), this collation sequence will
  67590. ** be returned. This is used by the built-in min(), max() and nullif()
  67591. ** functions.
  67592. **
  67593. ** If P1 is not zero, then it is a register that a subsequent min() or
  67594. ** max() aggregate will set to 1 if the current row is not the minimum or
  67595. ** maximum. The P1 register is initialized to 0 by this instruction.
  67596. **
  67597. ** The interface used by the implementation of the aforementioned functions
  67598. ** to retrieve the collation sequence set by this opcode is not available
  67599. ** publicly. Only built-in functions have access to this feature.
  67600. */
  67601. case OP_CollSeq: {
  67602. assert( pOp->p4type==P4_COLLSEQ );
  67603. if( pOp->p1 ){
  67604. sqlite3VdbeMemSetInt64(&aMem[pOp->p1], 0);
  67605. }
  67606. break;
  67607. }
  67608. /* Opcode: Function P1 P2 P3 P4 P5
  67609. ** Synopsis: r[P3]=func(r[P2@P5])
  67610. **
  67611. ** Invoke a user function (P4 is a pointer to a Function structure that
  67612. ** defines the function) with P5 arguments taken from register P2 and
  67613. ** successors. The result of the function is stored in register P3.
  67614. ** Register P3 must not be one of the function inputs.
  67615. **
  67616. ** P1 is a 32-bit bitmask indicating whether or not each argument to the
  67617. ** function was determined to be constant at compile time. If the first
  67618. ** argument was constant then bit 0 of P1 is set. This is used to determine
  67619. ** whether meta data associated with a user function argument using the
  67620. ** sqlite3_set_auxdata() API may be safely retained until the next
  67621. ** invocation of this opcode.
  67622. **
  67623. ** See also: AggStep and AggFinal
  67624. */
  67625. case OP_Function: {
  67626. int i;
  67627. Mem *pArg;
  67628. sqlite3_context ctx;
  67629. sqlite3_value **apVal;
  67630. int n;
  67631. n = pOp->p5;
  67632. apVal = p->apArg;
  67633. assert( apVal || n==0 );
  67634. assert( pOp->p3>0 && pOp->p3<=(p->nMem-p->nCursor) );
  67635. ctx.pOut = &aMem[pOp->p3];
  67636. memAboutToChange(p, ctx.pOut);
  67637. assert( n==0 || (pOp->p2>0 && pOp->p2+n<=(p->nMem-p->nCursor)+1) );
  67638. assert( pOp->p3<pOp->p2 || pOp->p3>=pOp->p2+n );
  67639. pArg = &aMem[pOp->p2];
  67640. for(i=0; i<n; i++, pArg++){
  67641. assert( memIsValid(pArg) );
  67642. apVal[i] = pArg;
  67643. Deephemeralize(pArg);
  67644. REGISTER_TRACE(pOp->p2+i, pArg);
  67645. }
  67646. assert( pOp->p4type==P4_FUNCDEF );
  67647. ctx.pFunc = pOp->p4.pFunc;
  67648. ctx.iOp = (int)(pOp - aOp);
  67649. ctx.pVdbe = p;
  67650. MemSetTypeFlag(ctx.pOut, MEM_Null);
  67651. ctx.fErrorOrAux = 0;
  67652. db->lastRowid = lastRowid;
  67653. (*ctx.pFunc->xFunc)(&ctx, n, apVal); /* IMP: R-24505-23230 */
  67654. lastRowid = db->lastRowid; /* Remember rowid changes made by xFunc */
  67655. /* If the function returned an error, throw an exception */
  67656. if( ctx.fErrorOrAux ){
  67657. if( ctx.isError ){
  67658. sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3_value_text(ctx.pOut));
  67659. rc = ctx.isError;
  67660. }
  67661. sqlite3VdbeDeleteAuxData(p, (int)(pOp - aOp), pOp->p1);
  67662. }
  67663. /* Copy the result of the function into register P3 */
  67664. sqlite3VdbeChangeEncoding(ctx.pOut, encoding);
  67665. if( sqlite3VdbeMemTooBig(ctx.pOut) ){
  67666. goto too_big;
  67667. }
  67668. REGISTER_TRACE(pOp->p3, ctx.pOut);
  67669. UPDATE_MAX_BLOBSIZE(ctx.pOut);
  67670. break;
  67671. }
  67672. /* Opcode: BitAnd P1 P2 P3 * *
  67673. ** Synopsis: r[P3]=r[P1]&r[P2]
  67674. **
  67675. ** Take the bit-wise AND of the values in register P1 and P2 and
  67676. ** store the result in register P3.
  67677. ** If either input is NULL, the result is NULL.
  67678. */
  67679. /* Opcode: BitOr P1 P2 P3 * *
  67680. ** Synopsis: r[P3]=r[P1]|r[P2]
  67681. **
  67682. ** Take the bit-wise OR of the values in register P1 and P2 and
  67683. ** store the result in register P3.
  67684. ** If either input is NULL, the result is NULL.
  67685. */
  67686. /* Opcode: ShiftLeft P1 P2 P3 * *
  67687. ** Synopsis: r[P3]=r[P2]<<r[P1]
  67688. **
  67689. ** Shift the integer value in register P2 to the left by the
  67690. ** number of bits specified by the integer in register P1.
  67691. ** Store the result in register P3.
  67692. ** If either input is NULL, the result is NULL.
  67693. */
  67694. /* Opcode: ShiftRight P1 P2 P3 * *
  67695. ** Synopsis: r[P3]=r[P2]>>r[P1]
  67696. **
  67697. ** Shift the integer value in register P2 to the right by the
  67698. ** number of bits specified by the integer in register P1.
  67699. ** Store the result in register P3.
  67700. ** If either input is NULL, the result is NULL.
  67701. */
  67702. case OP_BitAnd: /* same as TK_BITAND, in1, in2, out3 */
  67703. case OP_BitOr: /* same as TK_BITOR, in1, in2, out3 */
  67704. case OP_ShiftLeft: /* same as TK_LSHIFT, in1, in2, out3 */
  67705. case OP_ShiftRight: { /* same as TK_RSHIFT, in1, in2, out3 */
  67706. i64 iA;
  67707. u64 uA;
  67708. i64 iB;
  67709. u8 op;
  67710. pIn1 = &aMem[pOp->p1];
  67711. pIn2 = &aMem[pOp->p2];
  67712. pOut = &aMem[pOp->p3];
  67713. if( (pIn1->flags | pIn2->flags) & MEM_Null ){
  67714. sqlite3VdbeMemSetNull(pOut);
  67715. break;
  67716. }
  67717. iA = sqlite3VdbeIntValue(pIn2);
  67718. iB = sqlite3VdbeIntValue(pIn1);
  67719. op = pOp->opcode;
  67720. if( op==OP_BitAnd ){
  67721. iA &= iB;
  67722. }else if( op==OP_BitOr ){
  67723. iA |= iB;
  67724. }else if( iB!=0 ){
  67725. assert( op==OP_ShiftRight || op==OP_ShiftLeft );
  67726. /* If shifting by a negative amount, shift in the other direction */
  67727. if( iB<0 ){
  67728. assert( OP_ShiftRight==OP_ShiftLeft+1 );
  67729. op = 2*OP_ShiftLeft + 1 - op;
  67730. iB = iB>(-64) ? -iB : 64;
  67731. }
  67732. if( iB>=64 ){
  67733. iA = (iA>=0 || op==OP_ShiftLeft) ? 0 : -1;
  67734. }else{
  67735. memcpy(&uA, &iA, sizeof(uA));
  67736. if( op==OP_ShiftLeft ){
  67737. uA <<= iB;
  67738. }else{
  67739. uA >>= iB;
  67740. /* Sign-extend on a right shift of a negative number */
  67741. if( iA<0 ) uA |= ((((u64)0xffffffff)<<32)|0xffffffff) << (64-iB);
  67742. }
  67743. memcpy(&iA, &uA, sizeof(iA));
  67744. }
  67745. }
  67746. pOut->u.i = iA;
  67747. MemSetTypeFlag(pOut, MEM_Int);
  67748. break;
  67749. }
  67750. /* Opcode: AddImm P1 P2 * * *
  67751. ** Synopsis: r[P1]=r[P1]+P2
  67752. **
  67753. ** Add the constant P2 to the value in register P1.
  67754. ** The result is always an integer.
  67755. **
  67756. ** To force any register to be an integer, just add 0.
  67757. */
  67758. case OP_AddImm: { /* in1 */
  67759. pIn1 = &aMem[pOp->p1];
  67760. memAboutToChange(p, pIn1);
  67761. sqlite3VdbeMemIntegerify(pIn1);
  67762. pIn1->u.i += pOp->p2;
  67763. break;
  67764. }
  67765. /* Opcode: MustBeInt P1 P2 * * *
  67766. **
  67767. ** Force the value in register P1 to be an integer. If the value
  67768. ** in P1 is not an integer and cannot be converted into an integer
  67769. ** without data loss, then jump immediately to P2, or if P2==0
  67770. ** raise an SQLITE_MISMATCH exception.
  67771. */
  67772. case OP_MustBeInt: { /* jump, in1 */
  67773. pIn1 = &aMem[pOp->p1];
  67774. if( (pIn1->flags & MEM_Int)==0 ){
  67775. applyAffinity(pIn1, SQLITE_AFF_NUMERIC, encoding);
  67776. VdbeBranchTaken((pIn1->flags&MEM_Int)==0, 2);
  67777. if( (pIn1->flags & MEM_Int)==0 ){
  67778. if( pOp->p2==0 ){
  67779. rc = SQLITE_MISMATCH;
  67780. goto abort_due_to_error;
  67781. }else{
  67782. goto jump_to_p2;
  67783. }
  67784. }
  67785. }
  67786. MemSetTypeFlag(pIn1, MEM_Int);
  67787. break;
  67788. }
  67789. #ifndef SQLITE_OMIT_FLOATING_POINT
  67790. /* Opcode: RealAffinity P1 * * * *
  67791. **
  67792. ** If register P1 holds an integer convert it to a real value.
  67793. **
  67794. ** This opcode is used when extracting information from a column that
  67795. ** has REAL affinity. Such column values may still be stored as
  67796. ** integers, for space efficiency, but after extraction we want them
  67797. ** to have only a real value.
  67798. */
  67799. case OP_RealAffinity: { /* in1 */
  67800. pIn1 = &aMem[pOp->p1];
  67801. if( pIn1->flags & MEM_Int ){
  67802. sqlite3VdbeMemRealify(pIn1);
  67803. }
  67804. break;
  67805. }
  67806. #endif
  67807. #ifndef SQLITE_OMIT_CAST
  67808. /* Opcode: Cast P1 P2 * * *
  67809. ** Synopsis: affinity(r[P1])
  67810. **
  67811. ** Force the value in register P1 to be the type defined by P2.
  67812. **
  67813. ** <ul>
  67814. ** <li value="97"> TEXT
  67815. ** <li value="98"> BLOB
  67816. ** <li value="99"> NUMERIC
  67817. ** <li value="100"> INTEGER
  67818. ** <li value="101"> REAL
  67819. ** </ul>
  67820. **
  67821. ** A NULL value is not changed by this routine. It remains NULL.
  67822. */
  67823. case OP_Cast: { /* in1 */
  67824. assert( pOp->p2>=SQLITE_AFF_NONE && pOp->p2<=SQLITE_AFF_REAL );
  67825. testcase( pOp->p2==SQLITE_AFF_TEXT );
  67826. testcase( pOp->p2==SQLITE_AFF_NONE );
  67827. testcase( pOp->p2==SQLITE_AFF_NUMERIC );
  67828. testcase( pOp->p2==SQLITE_AFF_INTEGER );
  67829. testcase( pOp->p2==SQLITE_AFF_REAL );
  67830. pIn1 = &aMem[pOp->p1];
  67831. memAboutToChange(p, pIn1);
  67832. rc = ExpandBlob(pIn1);
  67833. sqlite3VdbeMemCast(pIn1, pOp->p2, encoding);
  67834. UPDATE_MAX_BLOBSIZE(pIn1);
  67835. break;
  67836. }
  67837. #endif /* SQLITE_OMIT_CAST */
  67838. /* Opcode: Lt P1 P2 P3 P4 P5
  67839. ** Synopsis: if r[P1]<r[P3] goto P2
  67840. **
  67841. ** Compare the values in register P1 and P3. If reg(P3)<reg(P1) then
  67842. ** jump to address P2.
  67843. **
  67844. ** If the SQLITE_JUMPIFNULL bit of P5 is set and either reg(P1) or
  67845. ** reg(P3) is NULL then take the jump. If the SQLITE_JUMPIFNULL
  67846. ** bit is clear then fall through if either operand is NULL.
  67847. **
  67848. ** The SQLITE_AFF_MASK portion of P5 must be an affinity character -
  67849. ** SQLITE_AFF_TEXT, SQLITE_AFF_INTEGER, and so forth. An attempt is made
  67850. ** to coerce both inputs according to this affinity before the
  67851. ** comparison is made. If the SQLITE_AFF_MASK is 0x00, then numeric
  67852. ** affinity is used. Note that the affinity conversions are stored
  67853. ** back into the input registers P1 and P3. So this opcode can cause
  67854. ** persistent changes to registers P1 and P3.
  67855. **
  67856. ** Once any conversions have taken place, and neither value is NULL,
  67857. ** the values are compared. If both values are blobs then memcmp() is
  67858. ** used to determine the results of the comparison. If both values
  67859. ** are text, then the appropriate collating function specified in
  67860. ** P4 is used to do the comparison. If P4 is not specified then
  67861. ** memcmp() is used to compare text string. If both values are
  67862. ** numeric, then a numeric comparison is used. If the two values
  67863. ** are of different types, then numbers are considered less than
  67864. ** strings and strings are considered less than blobs.
  67865. **
  67866. ** If the SQLITE_STOREP2 bit of P5 is set, then do not jump. Instead,
  67867. ** store a boolean result (either 0, or 1, or NULL) in register P2.
  67868. **
  67869. ** If the SQLITE_NULLEQ bit is set in P5, then NULL values are considered
  67870. ** equal to one another, provided that they do not have their MEM_Cleared
  67871. ** bit set.
  67872. */
  67873. /* Opcode: Ne P1 P2 P3 P4 P5
  67874. ** Synopsis: if r[P1]!=r[P3] goto P2
  67875. **
  67876. ** This works just like the Lt opcode except that the jump is taken if
  67877. ** the operands in registers P1 and P3 are not equal. See the Lt opcode for
  67878. ** additional information.
  67879. **
  67880. ** If SQLITE_NULLEQ is set in P5 then the result of comparison is always either
  67881. ** true or false and is never NULL. If both operands are NULL then the result
  67882. ** of comparison is false. If either operand is NULL then the result is true.
  67883. ** If neither operand is NULL the result is the same as it would be if
  67884. ** the SQLITE_NULLEQ flag were omitted from P5.
  67885. */
  67886. /* Opcode: Eq P1 P2 P3 P4 P5
  67887. ** Synopsis: if r[P1]==r[P3] goto P2
  67888. **
  67889. ** This works just like the Lt opcode except that the jump is taken if
  67890. ** the operands in registers P1 and P3 are equal.
  67891. ** See the Lt opcode for additional information.
  67892. **
  67893. ** If SQLITE_NULLEQ is set in P5 then the result of comparison is always either
  67894. ** true or false and is never NULL. If both operands are NULL then the result
  67895. ** of comparison is true. If either operand is NULL then the result is false.
  67896. ** If neither operand is NULL the result is the same as it would be if
  67897. ** the SQLITE_NULLEQ flag were omitted from P5.
  67898. */
  67899. /* Opcode: Le P1 P2 P3 P4 P5
  67900. ** Synopsis: if r[P1]<=r[P3] goto P2
  67901. **
  67902. ** This works just like the Lt opcode except that the jump is taken if
  67903. ** the content of register P3 is less than or equal to the content of
  67904. ** register P1. See the Lt opcode for additional information.
  67905. */
  67906. /* Opcode: Gt P1 P2 P3 P4 P5
  67907. ** Synopsis: if r[P1]>r[P3] goto P2
  67908. **
  67909. ** This works just like the Lt opcode except that the jump is taken if
  67910. ** the content of register P3 is greater than the content of
  67911. ** register P1. See the Lt opcode for additional information.
  67912. */
  67913. /* Opcode: Ge P1 P2 P3 P4 P5
  67914. ** Synopsis: if r[P1]>=r[P3] goto P2
  67915. **
  67916. ** This works just like the Lt opcode except that the jump is taken if
  67917. ** the content of register P3 is greater than or equal to the content of
  67918. ** register P1. See the Lt opcode for additional information.
  67919. */
  67920. case OP_Eq: /* same as TK_EQ, jump, in1, in3 */
  67921. case OP_Ne: /* same as TK_NE, jump, in1, in3 */
  67922. case OP_Lt: /* same as TK_LT, jump, in1, in3 */
  67923. case OP_Le: /* same as TK_LE, jump, in1, in3 */
  67924. case OP_Gt: /* same as TK_GT, jump, in1, in3 */
  67925. case OP_Ge: { /* same as TK_GE, jump, in1, in3 */
  67926. int res; /* Result of the comparison of pIn1 against pIn3 */
  67927. char affinity; /* Affinity to use for comparison */
  67928. u16 flags1; /* Copy of initial value of pIn1->flags */
  67929. u16 flags3; /* Copy of initial value of pIn3->flags */
  67930. pIn1 = &aMem[pOp->p1];
  67931. pIn3 = &aMem[pOp->p3];
  67932. flags1 = pIn1->flags;
  67933. flags3 = pIn3->flags;
  67934. if( (flags1 | flags3)&MEM_Null ){
  67935. /* One or both operands are NULL */
  67936. if( pOp->p5 & SQLITE_NULLEQ ){
  67937. /* If SQLITE_NULLEQ is set (which will only happen if the operator is
  67938. ** OP_Eq or OP_Ne) then take the jump or not depending on whether
  67939. ** or not both operands are null.
  67940. */
  67941. assert( pOp->opcode==OP_Eq || pOp->opcode==OP_Ne );
  67942. assert( (flags1 & MEM_Cleared)==0 );
  67943. assert( (pOp->p5 & SQLITE_JUMPIFNULL)==0 );
  67944. if( (flags1&MEM_Null)!=0
  67945. && (flags3&MEM_Null)!=0
  67946. && (flags3&MEM_Cleared)==0
  67947. ){
  67948. res = 0; /* Results are equal */
  67949. }else{
  67950. res = 1; /* Results are not equal */
  67951. }
  67952. }else{
  67953. /* SQLITE_NULLEQ is clear and at least one operand is NULL,
  67954. ** then the result is always NULL.
  67955. ** The jump is taken if the SQLITE_JUMPIFNULL bit is set.
  67956. */
  67957. if( pOp->p5 & SQLITE_STOREP2 ){
  67958. pOut = &aMem[pOp->p2];
  67959. MemSetTypeFlag(pOut, MEM_Null);
  67960. REGISTER_TRACE(pOp->p2, pOut);
  67961. }else{
  67962. VdbeBranchTaken(2,3);
  67963. if( pOp->p5 & SQLITE_JUMPIFNULL ){
  67964. goto jump_to_p2;
  67965. }
  67966. }
  67967. break;
  67968. }
  67969. }else{
  67970. /* Neither operand is NULL. Do a comparison. */
  67971. affinity = pOp->p5 & SQLITE_AFF_MASK;
  67972. if( affinity>=SQLITE_AFF_NUMERIC ){
  67973. if( (pIn1->flags & (MEM_Int|MEM_Real|MEM_Str))==MEM_Str ){
  67974. applyNumericAffinity(pIn1,0);
  67975. }
  67976. if( (pIn3->flags & (MEM_Int|MEM_Real|MEM_Str))==MEM_Str ){
  67977. applyNumericAffinity(pIn3,0);
  67978. }
  67979. }else if( affinity==SQLITE_AFF_TEXT ){
  67980. if( (pIn1->flags & MEM_Str)==0 && (pIn1->flags & (MEM_Int|MEM_Real))!=0 ){
  67981. testcase( pIn1->flags & MEM_Int );
  67982. testcase( pIn1->flags & MEM_Real );
  67983. sqlite3VdbeMemStringify(pIn1, encoding, 1);
  67984. testcase( (flags1&MEM_Dyn) != (pIn1->flags&MEM_Dyn) );
  67985. flags1 = (pIn1->flags & ~MEM_TypeMask) | (flags1 & MEM_TypeMask);
  67986. }
  67987. if( (pIn3->flags & MEM_Str)==0 && (pIn3->flags & (MEM_Int|MEM_Real))!=0 ){
  67988. testcase( pIn3->flags & MEM_Int );
  67989. testcase( pIn3->flags & MEM_Real );
  67990. sqlite3VdbeMemStringify(pIn3, encoding, 1);
  67991. testcase( (flags3&MEM_Dyn) != (pIn3->flags&MEM_Dyn) );
  67992. flags3 = (pIn3->flags & ~MEM_TypeMask) | (flags3 & MEM_TypeMask);
  67993. }
  67994. }
  67995. assert( pOp->p4type==P4_COLLSEQ || pOp->p4.pColl==0 );
  67996. if( pIn1->flags & MEM_Zero ){
  67997. sqlite3VdbeMemExpandBlob(pIn1);
  67998. flags1 &= ~MEM_Zero;
  67999. }
  68000. if( pIn3->flags & MEM_Zero ){
  68001. sqlite3VdbeMemExpandBlob(pIn3);
  68002. flags3 &= ~MEM_Zero;
  68003. }
  68004. if( db->mallocFailed ) goto no_mem;
  68005. res = sqlite3MemCompare(pIn3, pIn1, pOp->p4.pColl);
  68006. }
  68007. switch( pOp->opcode ){
  68008. case OP_Eq: res = res==0; break;
  68009. case OP_Ne: res = res!=0; break;
  68010. case OP_Lt: res = res<0; break;
  68011. case OP_Le: res = res<=0; break;
  68012. case OP_Gt: res = res>0; break;
  68013. default: res = res>=0; break;
  68014. }
  68015. /* Undo any changes made by applyAffinity() to the input registers. */
  68016. assert( (pIn1->flags & MEM_Dyn) == (flags1 & MEM_Dyn) );
  68017. pIn1->flags = flags1;
  68018. assert( (pIn3->flags & MEM_Dyn) == (flags3 & MEM_Dyn) );
  68019. pIn3->flags = flags3;
  68020. if( pOp->p5 & SQLITE_STOREP2 ){
  68021. pOut = &aMem[pOp->p2];
  68022. memAboutToChange(p, pOut);
  68023. MemSetTypeFlag(pOut, MEM_Int);
  68024. pOut->u.i = res;
  68025. REGISTER_TRACE(pOp->p2, pOut);
  68026. }else{
  68027. VdbeBranchTaken(res!=0, (pOp->p5 & SQLITE_NULLEQ)?2:3);
  68028. if( res ){
  68029. goto jump_to_p2;
  68030. }
  68031. }
  68032. break;
  68033. }
  68034. /* Opcode: Permutation * * * P4 *
  68035. **
  68036. ** Set the permutation used by the OP_Compare operator to be the array
  68037. ** of integers in P4.
  68038. **
  68039. ** The permutation is only valid until the next OP_Compare that has
  68040. ** the OPFLAG_PERMUTE bit set in P5. Typically the OP_Permutation should
  68041. ** occur immediately prior to the OP_Compare.
  68042. */
  68043. case OP_Permutation: {
  68044. assert( pOp->p4type==P4_INTARRAY );
  68045. assert( pOp->p4.ai );
  68046. aPermute = pOp->p4.ai;
  68047. break;
  68048. }
  68049. /* Opcode: Compare P1 P2 P3 P4 P5
  68050. ** Synopsis: r[P1@P3] <-> r[P2@P3]
  68051. **
  68052. ** Compare two vectors of registers in reg(P1)..reg(P1+P3-1) (call this
  68053. ** vector "A") and in reg(P2)..reg(P2+P3-1) ("B"). Save the result of
  68054. ** the comparison for use by the next OP_Jump instruct.
  68055. **
  68056. ** If P5 has the OPFLAG_PERMUTE bit set, then the order of comparison is
  68057. ** determined by the most recent OP_Permutation operator. If the
  68058. ** OPFLAG_PERMUTE bit is clear, then register are compared in sequential
  68059. ** order.
  68060. **
  68061. ** P4 is a KeyInfo structure that defines collating sequences and sort
  68062. ** orders for the comparison. The permutation applies to registers
  68063. ** only. The KeyInfo elements are used sequentially.
  68064. **
  68065. ** The comparison is a sort comparison, so NULLs compare equal,
  68066. ** NULLs are less than numbers, numbers are less than strings,
  68067. ** and strings are less than blobs.
  68068. */
  68069. case OP_Compare: {
  68070. int n;
  68071. int i;
  68072. int p1;
  68073. int p2;
  68074. const KeyInfo *pKeyInfo;
  68075. int idx;
  68076. CollSeq *pColl; /* Collating sequence to use on this term */
  68077. int bRev; /* True for DESCENDING sort order */
  68078. if( (pOp->p5 & OPFLAG_PERMUTE)==0 ) aPermute = 0;
  68079. n = pOp->p3;
  68080. pKeyInfo = pOp->p4.pKeyInfo;
  68081. assert( n>0 );
  68082. assert( pKeyInfo!=0 );
  68083. p1 = pOp->p1;
  68084. p2 = pOp->p2;
  68085. #if SQLITE_DEBUG
  68086. if( aPermute ){
  68087. int k, mx = 0;
  68088. for(k=0; k<n; k++) if( aPermute[k]>mx ) mx = aPermute[k];
  68089. assert( p1>0 && p1+mx<=(p->nMem-p->nCursor)+1 );
  68090. assert( p2>0 && p2+mx<=(p->nMem-p->nCursor)+1 );
  68091. }else{
  68092. assert( p1>0 && p1+n<=(p->nMem-p->nCursor)+1 );
  68093. assert( p2>0 && p2+n<=(p->nMem-p->nCursor)+1 );
  68094. }
  68095. #endif /* SQLITE_DEBUG */
  68096. for(i=0; i<n; i++){
  68097. idx = aPermute ? aPermute[i] : i;
  68098. assert( memIsValid(&aMem[p1+idx]) );
  68099. assert( memIsValid(&aMem[p2+idx]) );
  68100. REGISTER_TRACE(p1+idx, &aMem[p1+idx]);
  68101. REGISTER_TRACE(p2+idx, &aMem[p2+idx]);
  68102. assert( i<pKeyInfo->nField );
  68103. pColl = pKeyInfo->aColl[i];
  68104. bRev = pKeyInfo->aSortOrder[i];
  68105. iCompare = sqlite3MemCompare(&aMem[p1+idx], &aMem[p2+idx], pColl);
  68106. if( iCompare ){
  68107. if( bRev ) iCompare = -iCompare;
  68108. break;
  68109. }
  68110. }
  68111. aPermute = 0;
  68112. break;
  68113. }
  68114. /* Opcode: Jump P1 P2 P3 * *
  68115. **
  68116. ** Jump to the instruction at address P1, P2, or P3 depending on whether
  68117. ** in the most recent OP_Compare instruction the P1 vector was less than
  68118. ** equal to, or greater than the P2 vector, respectively.
  68119. */
  68120. case OP_Jump: { /* jump */
  68121. if( iCompare<0 ){
  68122. VdbeBranchTaken(0,3); pOp = &aOp[pOp->p1 - 1];
  68123. }else if( iCompare==0 ){
  68124. VdbeBranchTaken(1,3); pOp = &aOp[pOp->p2 - 1];
  68125. }else{
  68126. VdbeBranchTaken(2,3); pOp = &aOp[pOp->p3 - 1];
  68127. }
  68128. break;
  68129. }
  68130. /* Opcode: And P1 P2 P3 * *
  68131. ** Synopsis: r[P3]=(r[P1] && r[P2])
  68132. **
  68133. ** Take the logical AND of the values in registers P1 and P2 and
  68134. ** write the result into register P3.
  68135. **
  68136. ** If either P1 or P2 is 0 (false) then the result is 0 even if
  68137. ** the other input is NULL. A NULL and true or two NULLs give
  68138. ** a NULL output.
  68139. */
  68140. /* Opcode: Or P1 P2 P3 * *
  68141. ** Synopsis: r[P3]=(r[P1] || r[P2])
  68142. **
  68143. ** Take the logical OR of the values in register P1 and P2 and
  68144. ** store the answer in register P3.
  68145. **
  68146. ** If either P1 or P2 is nonzero (true) then the result is 1 (true)
  68147. ** even if the other input is NULL. A NULL and false or two NULLs
  68148. ** give a NULL output.
  68149. */
  68150. case OP_And: /* same as TK_AND, in1, in2, out3 */
  68151. case OP_Or: { /* same as TK_OR, in1, in2, out3 */
  68152. int v1; /* Left operand: 0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */
  68153. int v2; /* Right operand: 0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */
  68154. pIn1 = &aMem[pOp->p1];
  68155. if( pIn1->flags & MEM_Null ){
  68156. v1 = 2;
  68157. }else{
  68158. v1 = sqlite3VdbeIntValue(pIn1)!=0;
  68159. }
  68160. pIn2 = &aMem[pOp->p2];
  68161. if( pIn2->flags & MEM_Null ){
  68162. v2 = 2;
  68163. }else{
  68164. v2 = sqlite3VdbeIntValue(pIn2)!=0;
  68165. }
  68166. if( pOp->opcode==OP_And ){
  68167. static const unsigned char and_logic[] = { 0, 0, 0, 0, 1, 2, 0, 2, 2 };
  68168. v1 = and_logic[v1*3+v2];
  68169. }else{
  68170. static const unsigned char or_logic[] = { 0, 1, 2, 1, 1, 1, 2, 1, 2 };
  68171. v1 = or_logic[v1*3+v2];
  68172. }
  68173. pOut = &aMem[pOp->p3];
  68174. if( v1==2 ){
  68175. MemSetTypeFlag(pOut, MEM_Null);
  68176. }else{
  68177. pOut->u.i = v1;
  68178. MemSetTypeFlag(pOut, MEM_Int);
  68179. }
  68180. break;
  68181. }
  68182. /* Opcode: Not P1 P2 * * *
  68183. ** Synopsis: r[P2]= !r[P1]
  68184. **
  68185. ** Interpret the value in register P1 as a boolean value. Store the
  68186. ** boolean complement in register P2. If the value in register P1 is
  68187. ** NULL, then a NULL is stored in P2.
  68188. */
  68189. case OP_Not: { /* same as TK_NOT, in1, out2 */
  68190. pIn1 = &aMem[pOp->p1];
  68191. pOut = &aMem[pOp->p2];
  68192. sqlite3VdbeMemSetNull(pOut);
  68193. if( (pIn1->flags & MEM_Null)==0 ){
  68194. pOut->flags = MEM_Int;
  68195. pOut->u.i = !sqlite3VdbeIntValue(pIn1);
  68196. }
  68197. break;
  68198. }
  68199. /* Opcode: BitNot P1 P2 * * *
  68200. ** Synopsis: r[P1]= ~r[P1]
  68201. **
  68202. ** Interpret the content of register P1 as an integer. Store the
  68203. ** ones-complement of the P1 value into register P2. If P1 holds
  68204. ** a NULL then store a NULL in P2.
  68205. */
  68206. case OP_BitNot: { /* same as TK_BITNOT, in1, out2 */
  68207. pIn1 = &aMem[pOp->p1];
  68208. pOut = &aMem[pOp->p2];
  68209. sqlite3VdbeMemSetNull(pOut);
  68210. if( (pIn1->flags & MEM_Null)==0 ){
  68211. pOut->flags = MEM_Int;
  68212. pOut->u.i = ~sqlite3VdbeIntValue(pIn1);
  68213. }
  68214. break;
  68215. }
  68216. /* Opcode: Once P1 P2 * * *
  68217. **
  68218. ** Check the "once" flag number P1. If it is set, jump to instruction P2.
  68219. ** Otherwise, set the flag and fall through to the next instruction.
  68220. ** In other words, this opcode causes all following opcodes up through P2
  68221. ** (but not including P2) to run just once and to be skipped on subsequent
  68222. ** times through the loop.
  68223. **
  68224. ** All "once" flags are initially cleared whenever a prepared statement
  68225. ** first begins to run.
  68226. */
  68227. case OP_Once: { /* jump */
  68228. assert( pOp->p1<p->nOnceFlag );
  68229. VdbeBranchTaken(p->aOnceFlag[pOp->p1]!=0, 2);
  68230. if( p->aOnceFlag[pOp->p1] ){
  68231. goto jump_to_p2;
  68232. }else{
  68233. p->aOnceFlag[pOp->p1] = 1;
  68234. }
  68235. break;
  68236. }
  68237. /* Opcode: If P1 P2 P3 * *
  68238. **
  68239. ** Jump to P2 if the value in register P1 is true. The value
  68240. ** is considered true if it is numeric and non-zero. If the value
  68241. ** in P1 is NULL then take the jump if and only if P3 is non-zero.
  68242. */
  68243. /* Opcode: IfNot P1 P2 P3 * *
  68244. **
  68245. ** Jump to P2 if the value in register P1 is False. The value
  68246. ** is considered false if it has a numeric value of zero. If the value
  68247. ** in P1 is NULL then take the jump if and only if P3 is non-zero.
  68248. */
  68249. case OP_If: /* jump, in1 */
  68250. case OP_IfNot: { /* jump, in1 */
  68251. int c;
  68252. pIn1 = &aMem[pOp->p1];
  68253. if( pIn1->flags & MEM_Null ){
  68254. c = pOp->p3;
  68255. }else{
  68256. #ifdef SQLITE_OMIT_FLOATING_POINT
  68257. c = sqlite3VdbeIntValue(pIn1)!=0;
  68258. #else
  68259. c = sqlite3VdbeRealValue(pIn1)!=0.0;
  68260. #endif
  68261. if( pOp->opcode==OP_IfNot ) c = !c;
  68262. }
  68263. VdbeBranchTaken(c!=0, 2);
  68264. if( c ){
  68265. goto jump_to_p2;
  68266. }
  68267. break;
  68268. }
  68269. /* Opcode: IsNull P1 P2 * * *
  68270. ** Synopsis: if r[P1]==NULL goto P2
  68271. **
  68272. ** Jump to P2 if the value in register P1 is NULL.
  68273. */
  68274. case OP_IsNull: { /* same as TK_ISNULL, jump, in1 */
  68275. pIn1 = &aMem[pOp->p1];
  68276. VdbeBranchTaken( (pIn1->flags & MEM_Null)!=0, 2);
  68277. if( (pIn1->flags & MEM_Null)!=0 ){
  68278. goto jump_to_p2;
  68279. }
  68280. break;
  68281. }
  68282. /* Opcode: NotNull P1 P2 * * *
  68283. ** Synopsis: if r[P1]!=NULL goto P2
  68284. **
  68285. ** Jump to P2 if the value in register P1 is not NULL.
  68286. */
  68287. case OP_NotNull: { /* same as TK_NOTNULL, jump, in1 */
  68288. pIn1 = &aMem[pOp->p1];
  68289. VdbeBranchTaken( (pIn1->flags & MEM_Null)==0, 2);
  68290. if( (pIn1->flags & MEM_Null)==0 ){
  68291. goto jump_to_p2;
  68292. }
  68293. break;
  68294. }
  68295. /* Opcode: Column P1 P2 P3 P4 P5
  68296. ** Synopsis: r[P3]=PX
  68297. **
  68298. ** Interpret the data that cursor P1 points to as a structure built using
  68299. ** the MakeRecord instruction. (See the MakeRecord opcode for additional
  68300. ** information about the format of the data.) Extract the P2-th column
  68301. ** from this record. If there are less that (P2+1)
  68302. ** values in the record, extract a NULL.
  68303. **
  68304. ** The value extracted is stored in register P3.
  68305. **
  68306. ** If the column contains fewer than P2 fields, then extract a NULL. Or,
  68307. ** if the P4 argument is a P4_MEM use the value of the P4 argument as
  68308. ** the result.
  68309. **
  68310. ** If the OPFLAG_CLEARCACHE bit is set on P5 and P1 is a pseudo-table cursor,
  68311. ** then the cache of the cursor is reset prior to extracting the column.
  68312. ** The first OP_Column against a pseudo-table after the value of the content
  68313. ** register has changed should have this bit set.
  68314. **
  68315. ** If the OPFLAG_LENGTHARG and OPFLAG_TYPEOFARG bits are set on P5 when
  68316. ** the result is guaranteed to only be used as the argument of a length()
  68317. ** or typeof() function, respectively. The loading of large blobs can be
  68318. ** skipped for length() and all content loading can be skipped for typeof().
  68319. */
  68320. case OP_Column: {
  68321. i64 payloadSize64; /* Number of bytes in the record */
  68322. int p2; /* column number to retrieve */
  68323. VdbeCursor *pC; /* The VDBE cursor */
  68324. BtCursor *pCrsr; /* The BTree cursor */
  68325. u32 *aOffset; /* aOffset[i] is offset to start of data for i-th column */
  68326. int len; /* The length of the serialized data for the column */
  68327. int i; /* Loop counter */
  68328. Mem *pDest; /* Where to write the extracted value */
  68329. Mem sMem; /* For storing the record being decoded */
  68330. const u8 *zData; /* Part of the record being decoded */
  68331. const u8 *zHdr; /* Next unparsed byte of the header */
  68332. const u8 *zEndHdr; /* Pointer to first byte after the header */
  68333. u32 offset; /* Offset into the data */
  68334. u32 szField; /* Number of bytes in the content of a field */
  68335. u32 avail; /* Number of bytes of available data */
  68336. u32 t; /* A type code from the record header */
  68337. u16 fx; /* pDest->flags value */
  68338. Mem *pReg; /* PseudoTable input register */
  68339. p2 = pOp->p2;
  68340. assert( pOp->p3>0 && pOp->p3<=(p->nMem-p->nCursor) );
  68341. pDest = &aMem[pOp->p3];
  68342. memAboutToChange(p, pDest);
  68343. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  68344. pC = p->apCsr[pOp->p1];
  68345. assert( pC!=0 );
  68346. assert( p2<pC->nField );
  68347. aOffset = pC->aOffset;
  68348. #ifndef SQLITE_OMIT_VIRTUALTABLE
  68349. assert( pC->pVtabCursor==0 ); /* OP_Column never called on virtual table */
  68350. #endif
  68351. pCrsr = pC->pCursor;
  68352. assert( pCrsr!=0 || pC->pseudoTableReg>0 ); /* pCrsr NULL on PseudoTables */
  68353. assert( pCrsr!=0 || pC->nullRow ); /* pC->nullRow on PseudoTables */
  68354. /* If the cursor cache is stale, bring it up-to-date */
  68355. rc = sqlite3VdbeCursorMoveto(pC);
  68356. if( rc ) goto abort_due_to_error;
  68357. if( pC->cacheStatus!=p->cacheCtr ){
  68358. if( pC->nullRow ){
  68359. if( pCrsr==0 ){
  68360. assert( pC->pseudoTableReg>0 );
  68361. pReg = &aMem[pC->pseudoTableReg];
  68362. assert( pReg->flags & MEM_Blob );
  68363. assert( memIsValid(pReg) );
  68364. pC->payloadSize = pC->szRow = avail = pReg->n;
  68365. pC->aRow = (u8*)pReg->z;
  68366. }else{
  68367. sqlite3VdbeMemSetNull(pDest);
  68368. goto op_column_out;
  68369. }
  68370. }else{
  68371. assert( pCrsr );
  68372. if( pC->isTable==0 ){
  68373. assert( sqlite3BtreeCursorIsValid(pCrsr) );
  68374. VVA_ONLY(rc =) sqlite3BtreeKeySize(pCrsr, &payloadSize64);
  68375. assert( rc==SQLITE_OK ); /* True because of CursorMoveto() call above */
  68376. /* sqlite3BtreeParseCellPtr() uses getVarint32() to extract the
  68377. ** payload size, so it is impossible for payloadSize64 to be
  68378. ** larger than 32 bits. */
  68379. assert( (payloadSize64 & SQLITE_MAX_U32)==(u64)payloadSize64 );
  68380. pC->aRow = sqlite3BtreeKeyFetch(pCrsr, &avail);
  68381. pC->payloadSize = (u32)payloadSize64;
  68382. }else{
  68383. assert( sqlite3BtreeCursorIsValid(pCrsr) );
  68384. VVA_ONLY(rc =) sqlite3BtreeDataSize(pCrsr, &pC->payloadSize);
  68385. assert( rc==SQLITE_OK ); /* DataSize() cannot fail */
  68386. pC->aRow = sqlite3BtreeDataFetch(pCrsr, &avail);
  68387. }
  68388. assert( avail<=65536 ); /* Maximum page size is 64KiB */
  68389. if( pC->payloadSize <= (u32)avail ){
  68390. pC->szRow = pC->payloadSize;
  68391. }else{
  68392. pC->szRow = avail;
  68393. }
  68394. if( pC->payloadSize > (u32)db->aLimit[SQLITE_LIMIT_LENGTH] ){
  68395. goto too_big;
  68396. }
  68397. }
  68398. pC->cacheStatus = p->cacheCtr;
  68399. pC->iHdrOffset = getVarint32(pC->aRow, offset);
  68400. pC->nHdrParsed = 0;
  68401. aOffset[0] = offset;
  68402. /* Make sure a corrupt database has not given us an oversize header.
  68403. ** Do this now to avoid an oversize memory allocation.
  68404. **
  68405. ** Type entries can be between 1 and 5 bytes each. But 4 and 5 byte
  68406. ** types use so much data space that there can only be 4096 and 32 of
  68407. ** them, respectively. So the maximum header length results from a
  68408. ** 3-byte type for each of the maximum of 32768 columns plus three
  68409. ** extra bytes for the header length itself. 32768*3 + 3 = 98307.
  68410. */
  68411. if( offset > 98307 || offset > pC->payloadSize ){
  68412. rc = SQLITE_CORRUPT_BKPT;
  68413. goto op_column_error;
  68414. }
  68415. if( avail<offset ){
  68416. /* pC->aRow does not have to hold the entire row, but it does at least
  68417. ** need to cover the header of the record. If pC->aRow does not contain
  68418. ** the complete header, then set it to zero, forcing the header to be
  68419. ** dynamically allocated. */
  68420. pC->aRow = 0;
  68421. pC->szRow = 0;
  68422. }
  68423. /* The following goto is an optimization. It can be omitted and
  68424. ** everything will still work. But OP_Column is measurably faster
  68425. ** by skipping the subsequent conditional, which is always true.
  68426. */
  68427. assert( pC->nHdrParsed<=p2 ); /* Conditional skipped */
  68428. goto op_column_read_header;
  68429. }
  68430. /* Make sure at least the first p2+1 entries of the header have been
  68431. ** parsed and valid information is in aOffset[] and pC->aType[].
  68432. */
  68433. if( pC->nHdrParsed<=p2 ){
  68434. /* If there is more header available for parsing in the record, try
  68435. ** to extract additional fields up through the p2+1-th field
  68436. */
  68437. op_column_read_header:
  68438. if( pC->iHdrOffset<aOffset[0] ){
  68439. /* Make sure zData points to enough of the record to cover the header. */
  68440. if( pC->aRow==0 ){
  68441. memset(&sMem, 0, sizeof(sMem));
  68442. rc = sqlite3VdbeMemFromBtree(pCrsr, 0, aOffset[0],
  68443. !pC->isTable, &sMem);
  68444. if( rc!=SQLITE_OK ){
  68445. goto op_column_error;
  68446. }
  68447. zData = (u8*)sMem.z;
  68448. }else{
  68449. zData = pC->aRow;
  68450. }
  68451. /* Fill in pC->aType[i] and aOffset[i] values through the p2-th field. */
  68452. i = pC->nHdrParsed;
  68453. offset = aOffset[i];
  68454. zHdr = zData + pC->iHdrOffset;
  68455. zEndHdr = zData + aOffset[0];
  68456. assert( i<=p2 && zHdr<zEndHdr );
  68457. do{
  68458. if( zHdr[0]<0x80 ){
  68459. t = zHdr[0];
  68460. zHdr++;
  68461. }else{
  68462. zHdr += sqlite3GetVarint32(zHdr, &t);
  68463. }
  68464. pC->aType[i] = t;
  68465. szField = sqlite3VdbeSerialTypeLen(t);
  68466. offset += szField;
  68467. if( offset<szField ){ /* True if offset overflows */
  68468. zHdr = &zEndHdr[1]; /* Forces SQLITE_CORRUPT return below */
  68469. break;
  68470. }
  68471. i++;
  68472. aOffset[i] = offset;
  68473. }while( i<=p2 && zHdr<zEndHdr );
  68474. pC->nHdrParsed = i;
  68475. pC->iHdrOffset = (u32)(zHdr - zData);
  68476. if( pC->aRow==0 ){
  68477. sqlite3VdbeMemRelease(&sMem);
  68478. sMem.flags = MEM_Null;
  68479. }
  68480. /* The record is corrupt if any of the following are true:
  68481. ** (1) the bytes of the header extend past the declared header size
  68482. ** (zHdr>zEndHdr)
  68483. ** (2) the entire header was used but not all data was used
  68484. ** (zHdr==zEndHdr && offset!=pC->payloadSize)
  68485. ** (3) the end of the data extends beyond the end of the record.
  68486. ** (offset > pC->payloadSize)
  68487. */
  68488. if( (zHdr>=zEndHdr && (zHdr>zEndHdr || offset!=pC->payloadSize))
  68489. || (offset > pC->payloadSize)
  68490. ){
  68491. rc = SQLITE_CORRUPT_BKPT;
  68492. goto op_column_error;
  68493. }
  68494. }
  68495. /* If after trying to extract new entries from the header, nHdrParsed is
  68496. ** still not up to p2, that means that the record has fewer than p2
  68497. ** columns. So the result will be either the default value or a NULL.
  68498. */
  68499. if( pC->nHdrParsed<=p2 ){
  68500. if( pOp->p4type==P4_MEM ){
  68501. sqlite3VdbeMemShallowCopy(pDest, pOp->p4.pMem, MEM_Static);
  68502. }else{
  68503. sqlite3VdbeMemSetNull(pDest);
  68504. }
  68505. goto op_column_out;
  68506. }
  68507. }
  68508. /* Extract the content for the p2+1-th column. Control can only
  68509. ** reach this point if aOffset[p2], aOffset[p2+1], and pC->aType[p2] are
  68510. ** all valid.
  68511. */
  68512. assert( p2<pC->nHdrParsed );
  68513. assert( rc==SQLITE_OK );
  68514. assert( sqlite3VdbeCheckMemInvariants(pDest) );
  68515. if( VdbeMemDynamic(pDest) ) sqlite3VdbeMemSetNull(pDest);
  68516. t = pC->aType[p2];
  68517. if( pC->szRow>=aOffset[p2+1] ){
  68518. /* This is the common case where the desired content fits on the original
  68519. ** page - where the content is not on an overflow page */
  68520. sqlite3VdbeSerialGet(pC->aRow+aOffset[p2], t, pDest);
  68521. }else{
  68522. /* This branch happens only when content is on overflow pages */
  68523. if( ((pOp->p5 & (OPFLAG_LENGTHARG|OPFLAG_TYPEOFARG))!=0
  68524. && ((t>=12 && (t&1)==0) || (pOp->p5 & OPFLAG_TYPEOFARG)!=0))
  68525. || (len = sqlite3VdbeSerialTypeLen(t))==0
  68526. ){
  68527. /* Content is irrelevant for
  68528. ** 1. the typeof() function,
  68529. ** 2. the length(X) function if X is a blob, and
  68530. ** 3. if the content length is zero.
  68531. ** So we might as well use bogus content rather than reading
  68532. ** content from disk. NULL will work for the value for strings
  68533. ** and blobs and whatever is in the payloadSize64 variable
  68534. ** will work for everything else. */
  68535. sqlite3VdbeSerialGet(t<=13 ? (u8*)&payloadSize64 : 0, t, pDest);
  68536. }else{
  68537. rc = sqlite3VdbeMemFromBtree(pCrsr, aOffset[p2], len, !pC->isTable,
  68538. pDest);
  68539. if( rc!=SQLITE_OK ){
  68540. goto op_column_error;
  68541. }
  68542. sqlite3VdbeSerialGet((const u8*)pDest->z, t, pDest);
  68543. pDest->flags &= ~MEM_Ephem;
  68544. }
  68545. }
  68546. pDest->enc = encoding;
  68547. op_column_out:
  68548. /* If the column value is an ephemeral string, go ahead and persist
  68549. ** that string in case the cursor moves before the column value is
  68550. ** used. The following code does the equivalent of Deephemeralize()
  68551. ** but does it faster. */
  68552. if( (pDest->flags & MEM_Ephem)!=0 && pDest->z ){
  68553. fx = pDest->flags & (MEM_Str|MEM_Blob);
  68554. assert( fx!=0 );
  68555. zData = (const u8*)pDest->z;
  68556. len = pDest->n;
  68557. if( sqlite3VdbeMemClearAndResize(pDest, len+2) ) goto no_mem;
  68558. memcpy(pDest->z, zData, len);
  68559. pDest->z[len] = 0;
  68560. pDest->z[len+1] = 0;
  68561. pDest->flags = fx|MEM_Term;
  68562. }
  68563. op_column_error:
  68564. UPDATE_MAX_BLOBSIZE(pDest);
  68565. REGISTER_TRACE(pOp->p3, pDest);
  68566. break;
  68567. }
  68568. /* Opcode: Affinity P1 P2 * P4 *
  68569. ** Synopsis: affinity(r[P1@P2])
  68570. **
  68571. ** Apply affinities to a range of P2 registers starting with P1.
  68572. **
  68573. ** P4 is a string that is P2 characters long. The nth character of the
  68574. ** string indicates the column affinity that should be used for the nth
  68575. ** memory cell in the range.
  68576. */
  68577. case OP_Affinity: {
  68578. const char *zAffinity; /* The affinity to be applied */
  68579. char cAff; /* A single character of affinity */
  68580. zAffinity = pOp->p4.z;
  68581. assert( zAffinity!=0 );
  68582. assert( zAffinity[pOp->p2]==0 );
  68583. pIn1 = &aMem[pOp->p1];
  68584. while( (cAff = *(zAffinity++))!=0 ){
  68585. assert( pIn1 <= &p->aMem[(p->nMem-p->nCursor)] );
  68586. assert( memIsValid(pIn1) );
  68587. applyAffinity(pIn1, cAff, encoding);
  68588. pIn1++;
  68589. }
  68590. break;
  68591. }
  68592. /* Opcode: MakeRecord P1 P2 P3 P4 *
  68593. ** Synopsis: r[P3]=mkrec(r[P1@P2])
  68594. **
  68595. ** Convert P2 registers beginning with P1 into the [record format]
  68596. ** use as a data record in a database table or as a key
  68597. ** in an index. The OP_Column opcode can decode the record later.
  68598. **
  68599. ** P4 may be a string that is P2 characters long. The nth character of the
  68600. ** string indicates the column affinity that should be used for the nth
  68601. ** field of the index key.
  68602. **
  68603. ** The mapping from character to affinity is given by the SQLITE_AFF_
  68604. ** macros defined in sqliteInt.h.
  68605. **
  68606. ** If P4 is NULL then all index fields have the affinity NONE.
  68607. */
  68608. case OP_MakeRecord: {
  68609. u8 *zNewRecord; /* A buffer to hold the data for the new record */
  68610. Mem *pRec; /* The new record */
  68611. u64 nData; /* Number of bytes of data space */
  68612. int nHdr; /* Number of bytes of header space */
  68613. i64 nByte; /* Data space required for this record */
  68614. i64 nZero; /* Number of zero bytes at the end of the record */
  68615. int nVarint; /* Number of bytes in a varint */
  68616. u32 serial_type; /* Type field */
  68617. Mem *pData0; /* First field to be combined into the record */
  68618. Mem *pLast; /* Last field of the record */
  68619. int nField; /* Number of fields in the record */
  68620. char *zAffinity; /* The affinity string for the record */
  68621. int file_format; /* File format to use for encoding */
  68622. int i; /* Space used in zNewRecord[] header */
  68623. int j; /* Space used in zNewRecord[] content */
  68624. int len; /* Length of a field */
  68625. /* Assuming the record contains N fields, the record format looks
  68626. ** like this:
  68627. **
  68628. ** ------------------------------------------------------------------------
  68629. ** | hdr-size | type 0 | type 1 | ... | type N-1 | data0 | ... | data N-1 |
  68630. ** ------------------------------------------------------------------------
  68631. **
  68632. ** Data(0) is taken from register P1. Data(1) comes from register P1+1
  68633. ** and so forth.
  68634. **
  68635. ** Each type field is a varint representing the serial type of the
  68636. ** corresponding data element (see sqlite3VdbeSerialType()). The
  68637. ** hdr-size field is also a varint which is the offset from the beginning
  68638. ** of the record to data0.
  68639. */
  68640. nData = 0; /* Number of bytes of data space */
  68641. nHdr = 0; /* Number of bytes of header space */
  68642. nZero = 0; /* Number of zero bytes at the end of the record */
  68643. nField = pOp->p1;
  68644. zAffinity = pOp->p4.z;
  68645. assert( nField>0 && pOp->p2>0 && pOp->p2+nField<=(p->nMem-p->nCursor)+1 );
  68646. pData0 = &aMem[nField];
  68647. nField = pOp->p2;
  68648. pLast = &pData0[nField-1];
  68649. file_format = p->minWriteFileFormat;
  68650. /* Identify the output register */
  68651. assert( pOp->p3<pOp->p1 || pOp->p3>=pOp->p1+pOp->p2 );
  68652. pOut = &aMem[pOp->p3];
  68653. memAboutToChange(p, pOut);
  68654. /* Apply the requested affinity to all inputs
  68655. */
  68656. assert( pData0<=pLast );
  68657. if( zAffinity ){
  68658. pRec = pData0;
  68659. do{
  68660. applyAffinity(pRec++, *(zAffinity++), encoding);
  68661. assert( zAffinity[0]==0 || pRec<=pLast );
  68662. }while( zAffinity[0] );
  68663. }
  68664. /* Loop through the elements that will make up the record to figure
  68665. ** out how much space is required for the new record.
  68666. */
  68667. pRec = pLast;
  68668. do{
  68669. assert( memIsValid(pRec) );
  68670. pRec->uTemp = serial_type = sqlite3VdbeSerialType(pRec, file_format);
  68671. len = sqlite3VdbeSerialTypeLen(serial_type);
  68672. if( pRec->flags & MEM_Zero ){
  68673. if( nData ){
  68674. sqlite3VdbeMemExpandBlob(pRec);
  68675. }else{
  68676. nZero += pRec->u.nZero;
  68677. len -= pRec->u.nZero;
  68678. }
  68679. }
  68680. nData += len;
  68681. testcase( serial_type==127 );
  68682. testcase( serial_type==128 );
  68683. nHdr += serial_type<=127 ? 1 : sqlite3VarintLen(serial_type);
  68684. }while( (--pRec)>=pData0 );
  68685. /* EVIDENCE-OF: R-22564-11647 The header begins with a single varint
  68686. ** which determines the total number of bytes in the header. The varint
  68687. ** value is the size of the header in bytes including the size varint
  68688. ** itself. */
  68689. testcase( nHdr==126 );
  68690. testcase( nHdr==127 );
  68691. if( nHdr<=126 ){
  68692. /* The common case */
  68693. nHdr += 1;
  68694. }else{
  68695. /* Rare case of a really large header */
  68696. nVarint = sqlite3VarintLen(nHdr);
  68697. nHdr += nVarint;
  68698. if( nVarint<sqlite3VarintLen(nHdr) ) nHdr++;
  68699. }
  68700. nByte = nHdr+nData;
  68701. if( nByte+nZero>db->aLimit[SQLITE_LIMIT_LENGTH] ){
  68702. goto too_big;
  68703. }
  68704. /* Make sure the output register has a buffer large enough to store
  68705. ** the new record. The output register (pOp->p3) is not allowed to
  68706. ** be one of the input registers (because the following call to
  68707. ** sqlite3VdbeMemClearAndResize() could clobber the value before it is used).
  68708. */
  68709. if( sqlite3VdbeMemClearAndResize(pOut, (int)nByte) ){
  68710. goto no_mem;
  68711. }
  68712. zNewRecord = (u8 *)pOut->z;
  68713. /* Write the record */
  68714. i = putVarint32(zNewRecord, nHdr);
  68715. j = nHdr;
  68716. assert( pData0<=pLast );
  68717. pRec = pData0;
  68718. do{
  68719. serial_type = pRec->uTemp;
  68720. /* EVIDENCE-OF: R-06529-47362 Following the size varint are one or more
  68721. ** additional varints, one per column. */
  68722. i += putVarint32(&zNewRecord[i], serial_type); /* serial type */
  68723. /* EVIDENCE-OF: R-64536-51728 The values for each column in the record
  68724. ** immediately follow the header. */
  68725. j += sqlite3VdbeSerialPut(&zNewRecord[j], pRec, serial_type); /* content */
  68726. }while( (++pRec)<=pLast );
  68727. assert( i==nHdr );
  68728. assert( j==nByte );
  68729. assert( pOp->p3>0 && pOp->p3<=(p->nMem-p->nCursor) );
  68730. pOut->n = (int)nByte;
  68731. pOut->flags = MEM_Blob;
  68732. if( nZero ){
  68733. pOut->u.nZero = nZero;
  68734. pOut->flags |= MEM_Zero;
  68735. }
  68736. pOut->enc = SQLITE_UTF8; /* In case the blob is ever converted to text */
  68737. REGISTER_TRACE(pOp->p3, pOut);
  68738. UPDATE_MAX_BLOBSIZE(pOut);
  68739. break;
  68740. }
  68741. /* Opcode: Count P1 P2 * * *
  68742. ** Synopsis: r[P2]=count()
  68743. **
  68744. ** Store the number of entries (an integer value) in the table or index
  68745. ** opened by cursor P1 in register P2
  68746. */
  68747. #ifndef SQLITE_OMIT_BTREECOUNT
  68748. case OP_Count: { /* out2 */
  68749. i64 nEntry;
  68750. BtCursor *pCrsr;
  68751. pCrsr = p->apCsr[pOp->p1]->pCursor;
  68752. assert( pCrsr );
  68753. nEntry = 0; /* Not needed. Only used to silence a warning. */
  68754. rc = sqlite3BtreeCount(pCrsr, &nEntry);
  68755. pOut = out2Prerelease(p, pOp);
  68756. pOut->u.i = nEntry;
  68757. break;
  68758. }
  68759. #endif
  68760. /* Opcode: Savepoint P1 * * P4 *
  68761. **
  68762. ** Open, release or rollback the savepoint named by parameter P4, depending
  68763. ** on the value of P1. To open a new savepoint, P1==0. To release (commit) an
  68764. ** existing savepoint, P1==1, or to rollback an existing savepoint P1==2.
  68765. */
  68766. case OP_Savepoint: {
  68767. int p1; /* Value of P1 operand */
  68768. char *zName; /* Name of savepoint */
  68769. int nName;
  68770. Savepoint *pNew;
  68771. Savepoint *pSavepoint;
  68772. Savepoint *pTmp;
  68773. int iSavepoint;
  68774. int ii;
  68775. p1 = pOp->p1;
  68776. zName = pOp->p4.z;
  68777. /* Assert that the p1 parameter is valid. Also that if there is no open
  68778. ** transaction, then there cannot be any savepoints.
  68779. */
  68780. assert( db->pSavepoint==0 || db->autoCommit==0 );
  68781. assert( p1==SAVEPOINT_BEGIN||p1==SAVEPOINT_RELEASE||p1==SAVEPOINT_ROLLBACK );
  68782. assert( db->pSavepoint || db->isTransactionSavepoint==0 );
  68783. assert( checkSavepointCount(db) );
  68784. assert( p->bIsReader );
  68785. if( p1==SAVEPOINT_BEGIN ){
  68786. if( db->nVdbeWrite>0 ){
  68787. /* A new savepoint cannot be created if there are active write
  68788. ** statements (i.e. open read/write incremental blob handles).
  68789. */
  68790. sqlite3SetString(&p->zErrMsg, db, "cannot open savepoint - "
  68791. "SQL statements in progress");
  68792. rc = SQLITE_BUSY;
  68793. }else{
  68794. nName = sqlite3Strlen30(zName);
  68795. #ifndef SQLITE_OMIT_VIRTUALTABLE
  68796. /* This call is Ok even if this savepoint is actually a transaction
  68797. ** savepoint (and therefore should not prompt xSavepoint()) callbacks.
  68798. ** If this is a transaction savepoint being opened, it is guaranteed
  68799. ** that the db->aVTrans[] array is empty. */
  68800. assert( db->autoCommit==0 || db->nVTrans==0 );
  68801. rc = sqlite3VtabSavepoint(db, SAVEPOINT_BEGIN,
  68802. db->nStatement+db->nSavepoint);
  68803. if( rc!=SQLITE_OK ) goto abort_due_to_error;
  68804. #endif
  68805. /* Create a new savepoint structure. */
  68806. pNew = sqlite3DbMallocRaw(db, sizeof(Savepoint)+nName+1);
  68807. if( pNew ){
  68808. pNew->zName = (char *)&pNew[1];
  68809. memcpy(pNew->zName, zName, nName+1);
  68810. /* If there is no open transaction, then mark this as a special
  68811. ** "transaction savepoint". */
  68812. if( db->autoCommit ){
  68813. db->autoCommit = 0;
  68814. db->isTransactionSavepoint = 1;
  68815. }else{
  68816. db->nSavepoint++;
  68817. }
  68818. /* Link the new savepoint into the database handle's list. */
  68819. pNew->pNext = db->pSavepoint;
  68820. db->pSavepoint = pNew;
  68821. pNew->nDeferredCons = db->nDeferredCons;
  68822. pNew->nDeferredImmCons = db->nDeferredImmCons;
  68823. }
  68824. }
  68825. }else{
  68826. iSavepoint = 0;
  68827. /* Find the named savepoint. If there is no such savepoint, then an
  68828. ** an error is returned to the user. */
  68829. for(
  68830. pSavepoint = db->pSavepoint;
  68831. pSavepoint && sqlite3StrICmp(pSavepoint->zName, zName);
  68832. pSavepoint = pSavepoint->pNext
  68833. ){
  68834. iSavepoint++;
  68835. }
  68836. if( !pSavepoint ){
  68837. sqlite3SetString(&p->zErrMsg, db, "no such savepoint: %s", zName);
  68838. rc = SQLITE_ERROR;
  68839. }else if( db->nVdbeWrite>0 && p1==SAVEPOINT_RELEASE ){
  68840. /* It is not possible to release (commit) a savepoint if there are
  68841. ** active write statements.
  68842. */
  68843. sqlite3SetString(&p->zErrMsg, db,
  68844. "cannot release savepoint - SQL statements in progress"
  68845. );
  68846. rc = SQLITE_BUSY;
  68847. }else{
  68848. /* Determine whether or not this is a transaction savepoint. If so,
  68849. ** and this is a RELEASE command, then the current transaction
  68850. ** is committed.
  68851. */
  68852. int isTransaction = pSavepoint->pNext==0 && db->isTransactionSavepoint;
  68853. if( isTransaction && p1==SAVEPOINT_RELEASE ){
  68854. if( (rc = sqlite3VdbeCheckFk(p, 1))!=SQLITE_OK ){
  68855. goto vdbe_return;
  68856. }
  68857. db->autoCommit = 1;
  68858. if( sqlite3VdbeHalt(p)==SQLITE_BUSY ){
  68859. p->pc = (int)(pOp - aOp);
  68860. db->autoCommit = 0;
  68861. p->rc = rc = SQLITE_BUSY;
  68862. goto vdbe_return;
  68863. }
  68864. db->isTransactionSavepoint = 0;
  68865. rc = p->rc;
  68866. }else{
  68867. int isSchemaChange;
  68868. iSavepoint = db->nSavepoint - iSavepoint - 1;
  68869. if( p1==SAVEPOINT_ROLLBACK ){
  68870. isSchemaChange = (db->flags & SQLITE_InternChanges)!=0;
  68871. for(ii=0; ii<db->nDb; ii++){
  68872. rc = sqlite3BtreeTripAllCursors(db->aDb[ii].pBt,
  68873. SQLITE_ABORT_ROLLBACK,
  68874. isSchemaChange==0);
  68875. if( rc!=SQLITE_OK ) goto abort_due_to_error;
  68876. }
  68877. }else{
  68878. isSchemaChange = 0;
  68879. }
  68880. for(ii=0; ii<db->nDb; ii++){
  68881. rc = sqlite3BtreeSavepoint(db->aDb[ii].pBt, p1, iSavepoint);
  68882. if( rc!=SQLITE_OK ){
  68883. goto abort_due_to_error;
  68884. }
  68885. }
  68886. if( isSchemaChange ){
  68887. sqlite3ExpirePreparedStatements(db);
  68888. sqlite3ResetAllSchemasOfConnection(db);
  68889. db->flags = (db->flags | SQLITE_InternChanges);
  68890. }
  68891. }
  68892. /* Regardless of whether this is a RELEASE or ROLLBACK, destroy all
  68893. ** savepoints nested inside of the savepoint being operated on. */
  68894. while( db->pSavepoint!=pSavepoint ){
  68895. pTmp = db->pSavepoint;
  68896. db->pSavepoint = pTmp->pNext;
  68897. sqlite3DbFree(db, pTmp);
  68898. db->nSavepoint--;
  68899. }
  68900. /* If it is a RELEASE, then destroy the savepoint being operated on
  68901. ** too. If it is a ROLLBACK TO, then set the number of deferred
  68902. ** constraint violations present in the database to the value stored
  68903. ** when the savepoint was created. */
  68904. if( p1==SAVEPOINT_RELEASE ){
  68905. assert( pSavepoint==db->pSavepoint );
  68906. db->pSavepoint = pSavepoint->pNext;
  68907. sqlite3DbFree(db, pSavepoint);
  68908. if( !isTransaction ){
  68909. db->nSavepoint--;
  68910. }
  68911. }else{
  68912. db->nDeferredCons = pSavepoint->nDeferredCons;
  68913. db->nDeferredImmCons = pSavepoint->nDeferredImmCons;
  68914. }
  68915. if( !isTransaction || p1==SAVEPOINT_ROLLBACK ){
  68916. rc = sqlite3VtabSavepoint(db, p1, iSavepoint);
  68917. if( rc!=SQLITE_OK ) goto abort_due_to_error;
  68918. }
  68919. }
  68920. }
  68921. break;
  68922. }
  68923. /* Opcode: AutoCommit P1 P2 * * *
  68924. **
  68925. ** Set the database auto-commit flag to P1 (1 or 0). If P2 is true, roll
  68926. ** back any currently active btree transactions. If there are any active
  68927. ** VMs (apart from this one), then a ROLLBACK fails. A COMMIT fails if
  68928. ** there are active writing VMs or active VMs that use shared cache.
  68929. **
  68930. ** This instruction causes the VM to halt.
  68931. */
  68932. case OP_AutoCommit: {
  68933. int desiredAutoCommit;
  68934. int iRollback;
  68935. int turnOnAC;
  68936. desiredAutoCommit = pOp->p1;
  68937. iRollback = pOp->p2;
  68938. turnOnAC = desiredAutoCommit && !db->autoCommit;
  68939. assert( desiredAutoCommit==1 || desiredAutoCommit==0 );
  68940. assert( desiredAutoCommit==1 || iRollback==0 );
  68941. assert( db->nVdbeActive>0 ); /* At least this one VM is active */
  68942. assert( p->bIsReader );
  68943. #if 0
  68944. if( turnOnAC && iRollback && db->nVdbeActive>1 ){
  68945. /* If this instruction implements a ROLLBACK and other VMs are
  68946. ** still running, and a transaction is active, return an error indicating
  68947. ** that the other VMs must complete first.
  68948. */
  68949. sqlite3SetString(&p->zErrMsg, db, "cannot rollback transaction - "
  68950. "SQL statements in progress");
  68951. rc = SQLITE_BUSY;
  68952. }else
  68953. #endif
  68954. if( turnOnAC && !iRollback && db->nVdbeWrite>0 ){
  68955. /* If this instruction implements a COMMIT and other VMs are writing
  68956. ** return an error indicating that the other VMs must complete first.
  68957. */
  68958. sqlite3SetString(&p->zErrMsg, db, "cannot commit transaction - "
  68959. "SQL statements in progress");
  68960. rc = SQLITE_BUSY;
  68961. }else if( desiredAutoCommit!=db->autoCommit ){
  68962. if( iRollback ){
  68963. assert( desiredAutoCommit==1 );
  68964. sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK);
  68965. db->autoCommit = 1;
  68966. }else if( (rc = sqlite3VdbeCheckFk(p, 1))!=SQLITE_OK ){
  68967. goto vdbe_return;
  68968. }else{
  68969. db->autoCommit = (u8)desiredAutoCommit;
  68970. if( sqlite3VdbeHalt(p)==SQLITE_BUSY ){
  68971. p->pc = (int)(pOp - aOp);
  68972. db->autoCommit = (u8)(1-desiredAutoCommit);
  68973. p->rc = rc = SQLITE_BUSY;
  68974. goto vdbe_return;
  68975. }
  68976. }
  68977. assert( db->nStatement==0 );
  68978. sqlite3CloseSavepoints(db);
  68979. if( p->rc==SQLITE_OK ){
  68980. rc = SQLITE_DONE;
  68981. }else{
  68982. rc = SQLITE_ERROR;
  68983. }
  68984. goto vdbe_return;
  68985. }else{
  68986. sqlite3SetString(&p->zErrMsg, db,
  68987. (!desiredAutoCommit)?"cannot start a transaction within a transaction":(
  68988. (iRollback)?"cannot rollback - no transaction is active":
  68989. "cannot commit - no transaction is active"));
  68990. rc = SQLITE_ERROR;
  68991. }
  68992. break;
  68993. }
  68994. /* Opcode: Transaction P1 P2 P3 P4 P5
  68995. **
  68996. ** Begin a transaction on database P1 if a transaction is not already
  68997. ** active.
  68998. ** If P2 is non-zero, then a write-transaction is started, or if a
  68999. ** read-transaction is already active, it is upgraded to a write-transaction.
  69000. ** If P2 is zero, then a read-transaction is started.
  69001. **
  69002. ** P1 is the index of the database file on which the transaction is
  69003. ** started. Index 0 is the main database file and index 1 is the
  69004. ** file used for temporary tables. Indices of 2 or more are used for
  69005. ** attached databases.
  69006. **
  69007. ** If a write-transaction is started and the Vdbe.usesStmtJournal flag is
  69008. ** true (this flag is set if the Vdbe may modify more than one row and may
  69009. ** throw an ABORT exception), a statement transaction may also be opened.
  69010. ** More specifically, a statement transaction is opened iff the database
  69011. ** connection is currently not in autocommit mode, or if there are other
  69012. ** active statements. A statement transaction allows the changes made by this
  69013. ** VDBE to be rolled back after an error without having to roll back the
  69014. ** entire transaction. If no error is encountered, the statement transaction
  69015. ** will automatically commit when the VDBE halts.
  69016. **
  69017. ** If P5!=0 then this opcode also checks the schema cookie against P3
  69018. ** and the schema generation counter against P4.
  69019. ** The cookie changes its value whenever the database schema changes.
  69020. ** This operation is used to detect when that the cookie has changed
  69021. ** and that the current process needs to reread the schema. If the schema
  69022. ** cookie in P3 differs from the schema cookie in the database header or
  69023. ** if the schema generation counter in P4 differs from the current
  69024. ** generation counter, then an SQLITE_SCHEMA error is raised and execution
  69025. ** halts. The sqlite3_step() wrapper function might then reprepare the
  69026. ** statement and rerun it from the beginning.
  69027. */
  69028. case OP_Transaction: {
  69029. Btree *pBt;
  69030. int iMeta;
  69031. int iGen;
  69032. assert( p->bIsReader );
  69033. assert( p->readOnly==0 || pOp->p2==0 );
  69034. assert( pOp->p1>=0 && pOp->p1<db->nDb );
  69035. assert( DbMaskTest(p->btreeMask, pOp->p1) );
  69036. if( pOp->p2 && (db->flags & SQLITE_QueryOnly)!=0 ){
  69037. rc = SQLITE_READONLY;
  69038. goto abort_due_to_error;
  69039. }
  69040. pBt = db->aDb[pOp->p1].pBt;
  69041. if( pBt ){
  69042. rc = sqlite3BtreeBeginTrans(pBt, pOp->p2);
  69043. if( rc==SQLITE_BUSY ){
  69044. p->pc = (int)(pOp - aOp);
  69045. p->rc = rc = SQLITE_BUSY;
  69046. goto vdbe_return;
  69047. }
  69048. if( rc!=SQLITE_OK ){
  69049. goto abort_due_to_error;
  69050. }
  69051. if( pOp->p2 && p->usesStmtJournal
  69052. && (db->autoCommit==0 || db->nVdbeRead>1)
  69053. ){
  69054. assert( sqlite3BtreeIsInTrans(pBt) );
  69055. if( p->iStatement==0 ){
  69056. assert( db->nStatement>=0 && db->nSavepoint>=0 );
  69057. db->nStatement++;
  69058. p->iStatement = db->nSavepoint + db->nStatement;
  69059. }
  69060. rc = sqlite3VtabSavepoint(db, SAVEPOINT_BEGIN, p->iStatement-1);
  69061. if( rc==SQLITE_OK ){
  69062. rc = sqlite3BtreeBeginStmt(pBt, p->iStatement);
  69063. }
  69064. /* Store the current value of the database handles deferred constraint
  69065. ** counter. If the statement transaction needs to be rolled back,
  69066. ** the value of this counter needs to be restored too. */
  69067. p->nStmtDefCons = db->nDeferredCons;
  69068. p->nStmtDefImmCons = db->nDeferredImmCons;
  69069. }
  69070. /* Gather the schema version number for checking:
  69071. ** IMPLEMENTATION-OF: R-32195-19465 The schema version is used by SQLite
  69072. ** each time a query is executed to ensure that the internal cache of the
  69073. ** schema used when compiling the SQL query matches the schema of the
  69074. ** database against which the compiled query is actually executed.
  69075. */
  69076. sqlite3BtreeGetMeta(pBt, BTREE_SCHEMA_VERSION, (u32 *)&iMeta);
  69077. iGen = db->aDb[pOp->p1].pSchema->iGeneration;
  69078. }else{
  69079. iGen = iMeta = 0;
  69080. }
  69081. assert( pOp->p5==0 || pOp->p4type==P4_INT32 );
  69082. if( pOp->p5 && (iMeta!=pOp->p3 || iGen!=pOp->p4.i) ){
  69083. sqlite3DbFree(db, p->zErrMsg);
  69084. p->zErrMsg = sqlite3DbStrDup(db, "database schema has changed");
  69085. /* If the schema-cookie from the database file matches the cookie
  69086. ** stored with the in-memory representation of the schema, do
  69087. ** not reload the schema from the database file.
  69088. **
  69089. ** If virtual-tables are in use, this is not just an optimization.
  69090. ** Often, v-tables store their data in other SQLite tables, which
  69091. ** are queried from within xNext() and other v-table methods using
  69092. ** prepared queries. If such a query is out-of-date, we do not want to
  69093. ** discard the database schema, as the user code implementing the
  69094. ** v-table would have to be ready for the sqlite3_vtab structure itself
  69095. ** to be invalidated whenever sqlite3_step() is called from within
  69096. ** a v-table method.
  69097. */
  69098. if( db->aDb[pOp->p1].pSchema->schema_cookie!=iMeta ){
  69099. sqlite3ResetOneSchema(db, pOp->p1);
  69100. }
  69101. p->expired = 1;
  69102. rc = SQLITE_SCHEMA;
  69103. }
  69104. break;
  69105. }
  69106. /* Opcode: ReadCookie P1 P2 P3 * *
  69107. **
  69108. ** Read cookie number P3 from database P1 and write it into register P2.
  69109. ** P3==1 is the schema version. P3==2 is the database format.
  69110. ** P3==3 is the recommended pager cache size, and so forth. P1==0 is
  69111. ** the main database file and P1==1 is the database file used to store
  69112. ** temporary tables.
  69113. **
  69114. ** There must be a read-lock on the database (either a transaction
  69115. ** must be started or there must be an open cursor) before
  69116. ** executing this instruction.
  69117. */
  69118. case OP_ReadCookie: { /* out2 */
  69119. int iMeta;
  69120. int iDb;
  69121. int iCookie;
  69122. assert( p->bIsReader );
  69123. iDb = pOp->p1;
  69124. iCookie = pOp->p3;
  69125. assert( pOp->p3<SQLITE_N_BTREE_META );
  69126. assert( iDb>=0 && iDb<db->nDb );
  69127. assert( db->aDb[iDb].pBt!=0 );
  69128. assert( DbMaskTest(p->btreeMask, iDb) );
  69129. sqlite3BtreeGetMeta(db->aDb[iDb].pBt, iCookie, (u32 *)&iMeta);
  69130. pOut = out2Prerelease(p, pOp);
  69131. pOut->u.i = iMeta;
  69132. break;
  69133. }
  69134. /* Opcode: SetCookie P1 P2 P3 * *
  69135. **
  69136. ** Write the content of register P3 (interpreted as an integer)
  69137. ** into cookie number P2 of database P1. P2==1 is the schema version.
  69138. ** P2==2 is the database format. P2==3 is the recommended pager cache
  69139. ** size, and so forth. P1==0 is the main database file and P1==1 is the
  69140. ** database file used to store temporary tables.
  69141. **
  69142. ** A transaction must be started before executing this opcode.
  69143. */
  69144. case OP_SetCookie: { /* in3 */
  69145. Db *pDb;
  69146. assert( pOp->p2<SQLITE_N_BTREE_META );
  69147. assert( pOp->p1>=0 && pOp->p1<db->nDb );
  69148. assert( DbMaskTest(p->btreeMask, pOp->p1) );
  69149. assert( p->readOnly==0 );
  69150. pDb = &db->aDb[pOp->p1];
  69151. assert( pDb->pBt!=0 );
  69152. assert( sqlite3SchemaMutexHeld(db, pOp->p1, 0) );
  69153. pIn3 = &aMem[pOp->p3];
  69154. sqlite3VdbeMemIntegerify(pIn3);
  69155. /* See note about index shifting on OP_ReadCookie */
  69156. rc = sqlite3BtreeUpdateMeta(pDb->pBt, pOp->p2, (int)pIn3->u.i);
  69157. if( pOp->p2==BTREE_SCHEMA_VERSION ){
  69158. /* When the schema cookie changes, record the new cookie internally */
  69159. pDb->pSchema->schema_cookie = (int)pIn3->u.i;
  69160. db->flags |= SQLITE_InternChanges;
  69161. }else if( pOp->p2==BTREE_FILE_FORMAT ){
  69162. /* Record changes in the file format */
  69163. pDb->pSchema->file_format = (u8)pIn3->u.i;
  69164. }
  69165. if( pOp->p1==1 ){
  69166. /* Invalidate all prepared statements whenever the TEMP database
  69167. ** schema is changed. Ticket #1644 */
  69168. sqlite3ExpirePreparedStatements(db);
  69169. p->expired = 0;
  69170. }
  69171. break;
  69172. }
  69173. /* Opcode: OpenRead P1 P2 P3 P4 P5
  69174. ** Synopsis: root=P2 iDb=P3
  69175. **
  69176. ** Open a read-only cursor for the database table whose root page is
  69177. ** P2 in a database file. The database file is determined by P3.
  69178. ** P3==0 means the main database, P3==1 means the database used for
  69179. ** temporary tables, and P3>1 means used the corresponding attached
  69180. ** database. Give the new cursor an identifier of P1. The P1
  69181. ** values need not be contiguous but all P1 values should be small integers.
  69182. ** It is an error for P1 to be negative.
  69183. **
  69184. ** If P5!=0 then use the content of register P2 as the root page, not
  69185. ** the value of P2 itself.
  69186. **
  69187. ** There will be a read lock on the database whenever there is an
  69188. ** open cursor. If the database was unlocked prior to this instruction
  69189. ** then a read lock is acquired as part of this instruction. A read
  69190. ** lock allows other processes to read the database but prohibits
  69191. ** any other process from modifying the database. The read lock is
  69192. ** released when all cursors are closed. If this instruction attempts
  69193. ** to get a read lock but fails, the script terminates with an
  69194. ** SQLITE_BUSY error code.
  69195. **
  69196. ** The P4 value may be either an integer (P4_INT32) or a pointer to
  69197. ** a KeyInfo structure (P4_KEYINFO). If it is a pointer to a KeyInfo
  69198. ** structure, then said structure defines the content and collating
  69199. ** sequence of the index being opened. Otherwise, if P4 is an integer
  69200. ** value, it is set to the number of columns in the table.
  69201. **
  69202. ** See also: OpenWrite, ReopenIdx
  69203. */
  69204. /* Opcode: ReopenIdx P1 P2 P3 P4 P5
  69205. ** Synopsis: root=P2 iDb=P3
  69206. **
  69207. ** The ReopenIdx opcode works exactly like ReadOpen except that it first
  69208. ** checks to see if the cursor on P1 is already open with a root page
  69209. ** number of P2 and if it is this opcode becomes a no-op. In other words,
  69210. ** if the cursor is already open, do not reopen it.
  69211. **
  69212. ** The ReopenIdx opcode may only be used with P5==0 and with P4 being
  69213. ** a P4_KEYINFO object. Furthermore, the P3 value must be the same as
  69214. ** every other ReopenIdx or OpenRead for the same cursor number.
  69215. **
  69216. ** See the OpenRead opcode documentation for additional information.
  69217. */
  69218. /* Opcode: OpenWrite P1 P2 P3 P4 P5
  69219. ** Synopsis: root=P2 iDb=P3
  69220. **
  69221. ** Open a read/write cursor named P1 on the table or index whose root
  69222. ** page is P2. Or if P5!=0 use the content of register P2 to find the
  69223. ** root page.
  69224. **
  69225. ** The P4 value may be either an integer (P4_INT32) or a pointer to
  69226. ** a KeyInfo structure (P4_KEYINFO). If it is a pointer to a KeyInfo
  69227. ** structure, then said structure defines the content and collating
  69228. ** sequence of the index being opened. Otherwise, if P4 is an integer
  69229. ** value, it is set to the number of columns in the table, or to the
  69230. ** largest index of any column of the table that is actually used.
  69231. **
  69232. ** This instruction works just like OpenRead except that it opens the cursor
  69233. ** in read/write mode. For a given table, there can be one or more read-only
  69234. ** cursors or a single read/write cursor but not both.
  69235. **
  69236. ** See also OpenRead.
  69237. */
  69238. case OP_ReopenIdx: {
  69239. int nField;
  69240. KeyInfo *pKeyInfo;
  69241. int p2;
  69242. int iDb;
  69243. int wrFlag;
  69244. Btree *pX;
  69245. VdbeCursor *pCur;
  69246. Db *pDb;
  69247. assert( pOp->p5==0 || pOp->p5==OPFLAG_SEEKEQ );
  69248. assert( pOp->p4type==P4_KEYINFO );
  69249. pCur = p->apCsr[pOp->p1];
  69250. if( pCur && pCur->pgnoRoot==(u32)pOp->p2 ){
  69251. assert( pCur->iDb==pOp->p3 ); /* Guaranteed by the code generator */
  69252. goto open_cursor_set_hints;
  69253. }
  69254. /* If the cursor is not currently open or is open on a different
  69255. ** index, then fall through into OP_OpenRead to force a reopen */
  69256. case OP_OpenRead:
  69257. case OP_OpenWrite:
  69258. assert( (pOp->p5&(OPFLAG_P2ISREG|OPFLAG_BULKCSR|OPFLAG_SEEKEQ))==pOp->p5 );
  69259. assert( pOp->opcode==OP_OpenWrite || pOp->p5==0 || pOp->p5==OPFLAG_SEEKEQ );
  69260. assert( p->bIsReader );
  69261. assert( pOp->opcode==OP_OpenRead || pOp->opcode==OP_ReopenIdx
  69262. || p->readOnly==0 );
  69263. if( p->expired ){
  69264. rc = SQLITE_ABORT_ROLLBACK;
  69265. break;
  69266. }
  69267. nField = 0;
  69268. pKeyInfo = 0;
  69269. p2 = pOp->p2;
  69270. iDb = pOp->p3;
  69271. assert( iDb>=0 && iDb<db->nDb );
  69272. assert( DbMaskTest(p->btreeMask, iDb) );
  69273. pDb = &db->aDb[iDb];
  69274. pX = pDb->pBt;
  69275. assert( pX!=0 );
  69276. if( pOp->opcode==OP_OpenWrite ){
  69277. wrFlag = 1;
  69278. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  69279. if( pDb->pSchema->file_format < p->minWriteFileFormat ){
  69280. p->minWriteFileFormat = pDb->pSchema->file_format;
  69281. }
  69282. }else{
  69283. wrFlag = 0;
  69284. }
  69285. if( pOp->p5 & OPFLAG_P2ISREG ){
  69286. assert( p2>0 );
  69287. assert( p2<=(p->nMem-p->nCursor) );
  69288. pIn2 = &aMem[p2];
  69289. assert( memIsValid(pIn2) );
  69290. assert( (pIn2->flags & MEM_Int)!=0 );
  69291. sqlite3VdbeMemIntegerify(pIn2);
  69292. p2 = (int)pIn2->u.i;
  69293. /* The p2 value always comes from a prior OP_CreateTable opcode and
  69294. ** that opcode will always set the p2 value to 2 or more or else fail.
  69295. ** If there were a failure, the prepared statement would have halted
  69296. ** before reaching this instruction. */
  69297. if( NEVER(p2<2) ) {
  69298. rc = SQLITE_CORRUPT_BKPT;
  69299. goto abort_due_to_error;
  69300. }
  69301. }
  69302. if( pOp->p4type==P4_KEYINFO ){
  69303. pKeyInfo = pOp->p4.pKeyInfo;
  69304. assert( pKeyInfo->enc==ENC(db) );
  69305. assert( pKeyInfo->db==db );
  69306. nField = pKeyInfo->nField+pKeyInfo->nXField;
  69307. }else if( pOp->p4type==P4_INT32 ){
  69308. nField = pOp->p4.i;
  69309. }
  69310. assert( pOp->p1>=0 );
  69311. assert( nField>=0 );
  69312. testcase( nField==0 ); /* Table with INTEGER PRIMARY KEY and nothing else */
  69313. pCur = allocateCursor(p, pOp->p1, nField, iDb, 1);
  69314. if( pCur==0 ) goto no_mem;
  69315. pCur->nullRow = 1;
  69316. pCur->isOrdered = 1;
  69317. pCur->pgnoRoot = p2;
  69318. rc = sqlite3BtreeCursor(pX, p2, wrFlag, pKeyInfo, pCur->pCursor);
  69319. pCur->pKeyInfo = pKeyInfo;
  69320. /* Set the VdbeCursor.isTable variable. Previous versions of
  69321. ** SQLite used to check if the root-page flags were sane at this point
  69322. ** and report database corruption if they were not, but this check has
  69323. ** since moved into the btree layer. */
  69324. pCur->isTable = pOp->p4type!=P4_KEYINFO;
  69325. open_cursor_set_hints:
  69326. assert( OPFLAG_BULKCSR==BTREE_BULKLOAD );
  69327. assert( OPFLAG_SEEKEQ==BTREE_SEEK_EQ );
  69328. sqlite3BtreeCursorHints(pCur->pCursor,
  69329. (pOp->p5 & (OPFLAG_BULKCSR|OPFLAG_SEEKEQ)));
  69330. break;
  69331. }
  69332. /* Opcode: OpenEphemeral P1 P2 * P4 P5
  69333. ** Synopsis: nColumn=P2
  69334. **
  69335. ** Open a new cursor P1 to a transient table.
  69336. ** The cursor is always opened read/write even if
  69337. ** the main database is read-only. The ephemeral
  69338. ** table is deleted automatically when the cursor is closed.
  69339. **
  69340. ** P2 is the number of columns in the ephemeral table.
  69341. ** The cursor points to a BTree table if P4==0 and to a BTree index
  69342. ** if P4 is not 0. If P4 is not NULL, it points to a KeyInfo structure
  69343. ** that defines the format of keys in the index.
  69344. **
  69345. ** The P5 parameter can be a mask of the BTREE_* flags defined
  69346. ** in btree.h. These flags control aspects of the operation of
  69347. ** the btree. The BTREE_OMIT_JOURNAL and BTREE_SINGLE flags are
  69348. ** added automatically.
  69349. */
  69350. /* Opcode: OpenAutoindex P1 P2 * P4 *
  69351. ** Synopsis: nColumn=P2
  69352. **
  69353. ** This opcode works the same as OP_OpenEphemeral. It has a
  69354. ** different name to distinguish its use. Tables created using
  69355. ** by this opcode will be used for automatically created transient
  69356. ** indices in joins.
  69357. */
  69358. case OP_OpenAutoindex:
  69359. case OP_OpenEphemeral: {
  69360. VdbeCursor *pCx;
  69361. KeyInfo *pKeyInfo;
  69362. static const int vfsFlags =
  69363. SQLITE_OPEN_READWRITE |
  69364. SQLITE_OPEN_CREATE |
  69365. SQLITE_OPEN_EXCLUSIVE |
  69366. SQLITE_OPEN_DELETEONCLOSE |
  69367. SQLITE_OPEN_TRANSIENT_DB;
  69368. assert( pOp->p1>=0 );
  69369. assert( pOp->p2>=0 );
  69370. pCx = allocateCursor(p, pOp->p1, pOp->p2, -1, 1);
  69371. if( pCx==0 ) goto no_mem;
  69372. pCx->nullRow = 1;
  69373. pCx->isEphemeral = 1;
  69374. rc = sqlite3BtreeOpen(db->pVfs, 0, db, &pCx->pBt,
  69375. BTREE_OMIT_JOURNAL | BTREE_SINGLE | pOp->p5, vfsFlags);
  69376. if( rc==SQLITE_OK ){
  69377. rc = sqlite3BtreeBeginTrans(pCx->pBt, 1);
  69378. }
  69379. if( rc==SQLITE_OK ){
  69380. /* If a transient index is required, create it by calling
  69381. ** sqlite3BtreeCreateTable() with the BTREE_BLOBKEY flag before
  69382. ** opening it. If a transient table is required, just use the
  69383. ** automatically created table with root-page 1 (an BLOB_INTKEY table).
  69384. */
  69385. if( (pKeyInfo = pOp->p4.pKeyInfo)!=0 ){
  69386. int pgno;
  69387. assert( pOp->p4type==P4_KEYINFO );
  69388. rc = sqlite3BtreeCreateTable(pCx->pBt, &pgno, BTREE_BLOBKEY | pOp->p5);
  69389. if( rc==SQLITE_OK ){
  69390. assert( pgno==MASTER_ROOT+1 );
  69391. assert( pKeyInfo->db==db );
  69392. assert( pKeyInfo->enc==ENC(db) );
  69393. pCx->pKeyInfo = pKeyInfo;
  69394. rc = sqlite3BtreeCursor(pCx->pBt, pgno, 1, pKeyInfo, pCx->pCursor);
  69395. }
  69396. pCx->isTable = 0;
  69397. }else{
  69398. rc = sqlite3BtreeCursor(pCx->pBt, MASTER_ROOT, 1, 0, pCx->pCursor);
  69399. pCx->isTable = 1;
  69400. }
  69401. }
  69402. pCx->isOrdered = (pOp->p5!=BTREE_UNORDERED);
  69403. break;
  69404. }
  69405. /* Opcode: SorterOpen P1 P2 P3 P4 *
  69406. **
  69407. ** This opcode works like OP_OpenEphemeral except that it opens
  69408. ** a transient index that is specifically designed to sort large
  69409. ** tables using an external merge-sort algorithm.
  69410. **
  69411. ** If argument P3 is non-zero, then it indicates that the sorter may
  69412. ** assume that a stable sort considering the first P3 fields of each
  69413. ** key is sufficient to produce the required results.
  69414. */
  69415. case OP_SorterOpen: {
  69416. VdbeCursor *pCx;
  69417. assert( pOp->p1>=0 );
  69418. assert( pOp->p2>=0 );
  69419. pCx = allocateCursor(p, pOp->p1, pOp->p2, -1, 1);
  69420. if( pCx==0 ) goto no_mem;
  69421. pCx->pKeyInfo = pOp->p4.pKeyInfo;
  69422. assert( pCx->pKeyInfo->db==db );
  69423. assert( pCx->pKeyInfo->enc==ENC(db) );
  69424. rc = sqlite3VdbeSorterInit(db, pOp->p3, pCx);
  69425. break;
  69426. }
  69427. /* Opcode: SequenceTest P1 P2 * * *
  69428. ** Synopsis: if( cursor[P1].ctr++ ) pc = P2
  69429. **
  69430. ** P1 is a sorter cursor. If the sequence counter is currently zero, jump
  69431. ** to P2. Regardless of whether or not the jump is taken, increment the
  69432. ** the sequence value.
  69433. */
  69434. case OP_SequenceTest: {
  69435. VdbeCursor *pC;
  69436. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  69437. pC = p->apCsr[pOp->p1];
  69438. assert( pC->pSorter );
  69439. if( (pC->seqCount++)==0 ){
  69440. goto jump_to_p2;
  69441. }
  69442. break;
  69443. }
  69444. /* Opcode: OpenPseudo P1 P2 P3 * *
  69445. ** Synopsis: P3 columns in r[P2]
  69446. **
  69447. ** Open a new cursor that points to a fake table that contains a single
  69448. ** row of data. The content of that one row is the content of memory
  69449. ** register P2. In other words, cursor P1 becomes an alias for the
  69450. ** MEM_Blob content contained in register P2.
  69451. **
  69452. ** A pseudo-table created by this opcode is used to hold a single
  69453. ** row output from the sorter so that the row can be decomposed into
  69454. ** individual columns using the OP_Column opcode. The OP_Column opcode
  69455. ** is the only cursor opcode that works with a pseudo-table.
  69456. **
  69457. ** P3 is the number of fields in the records that will be stored by
  69458. ** the pseudo-table.
  69459. */
  69460. case OP_OpenPseudo: {
  69461. VdbeCursor *pCx;
  69462. assert( pOp->p1>=0 );
  69463. assert( pOp->p3>=0 );
  69464. pCx = allocateCursor(p, pOp->p1, pOp->p3, -1, 0);
  69465. if( pCx==0 ) goto no_mem;
  69466. pCx->nullRow = 1;
  69467. pCx->pseudoTableReg = pOp->p2;
  69468. pCx->isTable = 1;
  69469. assert( pOp->p5==0 );
  69470. break;
  69471. }
  69472. /* Opcode: Close P1 * * * *
  69473. **
  69474. ** Close a cursor previously opened as P1. If P1 is not
  69475. ** currently open, this instruction is a no-op.
  69476. */
  69477. case OP_Close: {
  69478. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  69479. sqlite3VdbeFreeCursor(p, p->apCsr[pOp->p1]);
  69480. p->apCsr[pOp->p1] = 0;
  69481. break;
  69482. }
  69483. /* Opcode: SeekGE P1 P2 P3 P4 *
  69484. ** Synopsis: key=r[P3@P4]
  69485. **
  69486. ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
  69487. ** use the value in register P3 as the key. If cursor P1 refers
  69488. ** to an SQL index, then P3 is the first in an array of P4 registers
  69489. ** that are used as an unpacked index key.
  69490. **
  69491. ** Reposition cursor P1 so that it points to the smallest entry that
  69492. ** is greater than or equal to the key value. If there are no records
  69493. ** greater than or equal to the key and P2 is not zero, then jump to P2.
  69494. **
  69495. ** This opcode leaves the cursor configured to move in forward order,
  69496. ** from the beginning toward the end. In other words, the cursor is
  69497. ** configured to use Next, not Prev.
  69498. **
  69499. ** See also: Found, NotFound, SeekLt, SeekGt, SeekLe
  69500. */
  69501. /* Opcode: SeekGT P1 P2 P3 P4 *
  69502. ** Synopsis: key=r[P3@P4]
  69503. **
  69504. ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
  69505. ** use the value in register P3 as a key. If cursor P1 refers
  69506. ** to an SQL index, then P3 is the first in an array of P4 registers
  69507. ** that are used as an unpacked index key.
  69508. **
  69509. ** Reposition cursor P1 so that it points to the smallest entry that
  69510. ** is greater than the key value. If there are no records greater than
  69511. ** the key and P2 is not zero, then jump to P2.
  69512. **
  69513. ** This opcode leaves the cursor configured to move in forward order,
  69514. ** from the beginning toward the end. In other words, the cursor is
  69515. ** configured to use Next, not Prev.
  69516. **
  69517. ** See also: Found, NotFound, SeekLt, SeekGe, SeekLe
  69518. */
  69519. /* Opcode: SeekLT P1 P2 P3 P4 *
  69520. ** Synopsis: key=r[P3@P4]
  69521. **
  69522. ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
  69523. ** use the value in register P3 as a key. If cursor P1 refers
  69524. ** to an SQL index, then P3 is the first in an array of P4 registers
  69525. ** that are used as an unpacked index key.
  69526. **
  69527. ** Reposition cursor P1 so that it points to the largest entry that
  69528. ** is less than the key value. If there are no records less than
  69529. ** the key and P2 is not zero, then jump to P2.
  69530. **
  69531. ** This opcode leaves the cursor configured to move in reverse order,
  69532. ** from the end toward the beginning. In other words, the cursor is
  69533. ** configured to use Prev, not Next.
  69534. **
  69535. ** See also: Found, NotFound, SeekGt, SeekGe, SeekLe
  69536. */
  69537. /* Opcode: SeekLE P1 P2 P3 P4 *
  69538. ** Synopsis: key=r[P3@P4]
  69539. **
  69540. ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
  69541. ** use the value in register P3 as a key. If cursor P1 refers
  69542. ** to an SQL index, then P3 is the first in an array of P4 registers
  69543. ** that are used as an unpacked index key.
  69544. **
  69545. ** Reposition cursor P1 so that it points to the largest entry that
  69546. ** is less than or equal to the key value. If there are no records
  69547. ** less than or equal to the key and P2 is not zero, then jump to P2.
  69548. **
  69549. ** This opcode leaves the cursor configured to move in reverse order,
  69550. ** from the end toward the beginning. In other words, the cursor is
  69551. ** configured to use Prev, not Next.
  69552. **
  69553. ** See also: Found, NotFound, SeekGt, SeekGe, SeekLt
  69554. */
  69555. case OP_SeekLT: /* jump, in3 */
  69556. case OP_SeekLE: /* jump, in3 */
  69557. case OP_SeekGE: /* jump, in3 */
  69558. case OP_SeekGT: { /* jump, in3 */
  69559. int res;
  69560. int oc;
  69561. VdbeCursor *pC;
  69562. UnpackedRecord r;
  69563. int nField;
  69564. i64 iKey; /* The rowid we are to seek to */
  69565. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  69566. assert( pOp->p2!=0 );
  69567. pC = p->apCsr[pOp->p1];
  69568. assert( pC!=0 );
  69569. assert( pC->pseudoTableReg==0 );
  69570. assert( OP_SeekLE == OP_SeekLT+1 );
  69571. assert( OP_SeekGE == OP_SeekLT+2 );
  69572. assert( OP_SeekGT == OP_SeekLT+3 );
  69573. assert( pC->isOrdered );
  69574. assert( pC->pCursor!=0 );
  69575. oc = pOp->opcode;
  69576. pC->nullRow = 0;
  69577. #ifdef SQLITE_DEBUG
  69578. pC->seekOp = pOp->opcode;
  69579. #endif
  69580. /* For a cursor with the BTREE_SEEK_EQ hint, only the OP_SeekGE and
  69581. ** OP_SeekLE opcodes are allowed, and these must be immediately followed
  69582. ** by an OP_IdxGT or OP_IdxLT opcode, respectively, with the same key.
  69583. */
  69584. #ifdef SQLITE_DEBUG
  69585. if( sqlite3BtreeCursorHasHint(pC->pCursor, BTREE_SEEK_EQ) ){
  69586. assert( pOp->opcode==OP_SeekGE || pOp->opcode==OP_SeekLE );
  69587. assert( pOp[1].opcode==OP_IdxLT || pOp[1].opcode==OP_IdxGT );
  69588. assert( pOp[1].p1==pOp[0].p1 );
  69589. assert( pOp[1].p2==pOp[0].p2 );
  69590. assert( pOp[1].p3==pOp[0].p3 );
  69591. assert( pOp[1].p4.i==pOp[0].p4.i );
  69592. }
  69593. #endif
  69594. if( pC->isTable ){
  69595. /* The input value in P3 might be of any type: integer, real, string,
  69596. ** blob, or NULL. But it needs to be an integer before we can do
  69597. ** the seek, so convert it. */
  69598. pIn3 = &aMem[pOp->p3];
  69599. if( (pIn3->flags & (MEM_Int|MEM_Real|MEM_Str))==MEM_Str ){
  69600. applyNumericAffinity(pIn3, 0);
  69601. }
  69602. iKey = sqlite3VdbeIntValue(pIn3);
  69603. /* If the P3 value could not be converted into an integer without
  69604. ** loss of information, then special processing is required... */
  69605. if( (pIn3->flags & MEM_Int)==0 ){
  69606. if( (pIn3->flags & MEM_Real)==0 ){
  69607. /* If the P3 value cannot be converted into any kind of a number,
  69608. ** then the seek is not possible, so jump to P2 */
  69609. VdbeBranchTaken(1,2); goto jump_to_p2;
  69610. break;
  69611. }
  69612. /* If the approximation iKey is larger than the actual real search
  69613. ** term, substitute >= for > and < for <=. e.g. if the search term
  69614. ** is 4.9 and the integer approximation 5:
  69615. **
  69616. ** (x > 4.9) -> (x >= 5)
  69617. ** (x <= 4.9) -> (x < 5)
  69618. */
  69619. if( pIn3->u.r<(double)iKey ){
  69620. assert( OP_SeekGE==(OP_SeekGT-1) );
  69621. assert( OP_SeekLT==(OP_SeekLE-1) );
  69622. assert( (OP_SeekLE & 0x0001)==(OP_SeekGT & 0x0001) );
  69623. if( (oc & 0x0001)==(OP_SeekGT & 0x0001) ) oc--;
  69624. }
  69625. /* If the approximation iKey is smaller than the actual real search
  69626. ** term, substitute <= for < and > for >=. */
  69627. else if( pIn3->u.r>(double)iKey ){
  69628. assert( OP_SeekLE==(OP_SeekLT+1) );
  69629. assert( OP_SeekGT==(OP_SeekGE+1) );
  69630. assert( (OP_SeekLT & 0x0001)==(OP_SeekGE & 0x0001) );
  69631. if( (oc & 0x0001)==(OP_SeekLT & 0x0001) ) oc++;
  69632. }
  69633. }
  69634. rc = sqlite3BtreeMovetoUnpacked(pC->pCursor, 0, (u64)iKey, 0, &res);
  69635. pC->movetoTarget = iKey; /* Used by OP_Delete */
  69636. if( rc!=SQLITE_OK ){
  69637. goto abort_due_to_error;
  69638. }
  69639. }else{
  69640. nField = pOp->p4.i;
  69641. assert( pOp->p4type==P4_INT32 );
  69642. assert( nField>0 );
  69643. r.pKeyInfo = pC->pKeyInfo;
  69644. r.nField = (u16)nField;
  69645. /* The next line of code computes as follows, only faster:
  69646. ** if( oc==OP_SeekGT || oc==OP_SeekLE ){
  69647. ** r.default_rc = -1;
  69648. ** }else{
  69649. ** r.default_rc = +1;
  69650. ** }
  69651. */
  69652. r.default_rc = ((1 & (oc - OP_SeekLT)) ? -1 : +1);
  69653. assert( oc!=OP_SeekGT || r.default_rc==-1 );
  69654. assert( oc!=OP_SeekLE || r.default_rc==-1 );
  69655. assert( oc!=OP_SeekGE || r.default_rc==+1 );
  69656. assert( oc!=OP_SeekLT || r.default_rc==+1 );
  69657. r.aMem = &aMem[pOp->p3];
  69658. #ifdef SQLITE_DEBUG
  69659. { int i; for(i=0; i<r.nField; i++) assert( memIsValid(&r.aMem[i]) ); }
  69660. #endif
  69661. ExpandBlob(r.aMem);
  69662. rc = sqlite3BtreeMovetoUnpacked(pC->pCursor, &r, 0, 0, &res);
  69663. if( rc!=SQLITE_OK ){
  69664. goto abort_due_to_error;
  69665. }
  69666. }
  69667. pC->deferredMoveto = 0;
  69668. pC->cacheStatus = CACHE_STALE;
  69669. #ifdef SQLITE_TEST
  69670. sqlite3_search_count++;
  69671. #endif
  69672. if( oc>=OP_SeekGE ){ assert( oc==OP_SeekGE || oc==OP_SeekGT );
  69673. if( res<0 || (res==0 && oc==OP_SeekGT) ){
  69674. res = 0;
  69675. rc = sqlite3BtreeNext(pC->pCursor, &res);
  69676. if( rc!=SQLITE_OK ) goto abort_due_to_error;
  69677. }else{
  69678. res = 0;
  69679. }
  69680. }else{
  69681. assert( oc==OP_SeekLT || oc==OP_SeekLE );
  69682. if( res>0 || (res==0 && oc==OP_SeekLT) ){
  69683. res = 0;
  69684. rc = sqlite3BtreePrevious(pC->pCursor, &res);
  69685. if( rc!=SQLITE_OK ) goto abort_due_to_error;
  69686. }else{
  69687. /* res might be negative because the table is empty. Check to
  69688. ** see if this is the case.
  69689. */
  69690. res = sqlite3BtreeEof(pC->pCursor);
  69691. }
  69692. }
  69693. assert( pOp->p2>0 );
  69694. VdbeBranchTaken(res!=0,2);
  69695. if( res ){
  69696. goto jump_to_p2;
  69697. }
  69698. break;
  69699. }
  69700. /* Opcode: Seek P1 P2 * * *
  69701. ** Synopsis: intkey=r[P2]
  69702. **
  69703. ** P1 is an open table cursor and P2 is a rowid integer. Arrange
  69704. ** for P1 to move so that it points to the rowid given by P2.
  69705. **
  69706. ** This is actually a deferred seek. Nothing actually happens until
  69707. ** the cursor is used to read a record. That way, if no reads
  69708. ** occur, no unnecessary I/O happens.
  69709. */
  69710. case OP_Seek: { /* in2 */
  69711. VdbeCursor *pC;
  69712. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  69713. pC = p->apCsr[pOp->p1];
  69714. assert( pC!=0 );
  69715. assert( pC->pCursor!=0 );
  69716. assert( pC->isTable );
  69717. pC->nullRow = 0;
  69718. pIn2 = &aMem[pOp->p2];
  69719. pC->movetoTarget = sqlite3VdbeIntValue(pIn2);
  69720. pC->deferredMoveto = 1;
  69721. break;
  69722. }
  69723. /* Opcode: Found P1 P2 P3 P4 *
  69724. ** Synopsis: key=r[P3@P4]
  69725. **
  69726. ** If P4==0 then register P3 holds a blob constructed by MakeRecord. If
  69727. ** P4>0 then register P3 is the first of P4 registers that form an unpacked
  69728. ** record.
  69729. **
  69730. ** Cursor P1 is on an index btree. If the record identified by P3 and P4
  69731. ** is a prefix of any entry in P1 then a jump is made to P2 and
  69732. ** P1 is left pointing at the matching entry.
  69733. **
  69734. ** This operation leaves the cursor in a state where it can be
  69735. ** advanced in the forward direction. The Next instruction will work,
  69736. ** but not the Prev instruction.
  69737. **
  69738. ** See also: NotFound, NoConflict, NotExists. SeekGe
  69739. */
  69740. /* Opcode: NotFound P1 P2 P3 P4 *
  69741. ** Synopsis: key=r[P3@P4]
  69742. **
  69743. ** If P4==0 then register P3 holds a blob constructed by MakeRecord. If
  69744. ** P4>0 then register P3 is the first of P4 registers that form an unpacked
  69745. ** record.
  69746. **
  69747. ** Cursor P1 is on an index btree. If the record identified by P3 and P4
  69748. ** is not the prefix of any entry in P1 then a jump is made to P2. If P1
  69749. ** does contain an entry whose prefix matches the P3/P4 record then control
  69750. ** falls through to the next instruction and P1 is left pointing at the
  69751. ** matching entry.
  69752. **
  69753. ** This operation leaves the cursor in a state where it cannot be
  69754. ** advanced in either direction. In other words, the Next and Prev
  69755. ** opcodes do not work after this operation.
  69756. **
  69757. ** See also: Found, NotExists, NoConflict
  69758. */
  69759. /* Opcode: NoConflict P1 P2 P3 P4 *
  69760. ** Synopsis: key=r[P3@P4]
  69761. **
  69762. ** If P4==0 then register P3 holds a blob constructed by MakeRecord. If
  69763. ** P4>0 then register P3 is the first of P4 registers that form an unpacked
  69764. ** record.
  69765. **
  69766. ** Cursor P1 is on an index btree. If the record identified by P3 and P4
  69767. ** contains any NULL value, jump immediately to P2. If all terms of the
  69768. ** record are not-NULL then a check is done to determine if any row in the
  69769. ** P1 index btree has a matching key prefix. If there are no matches, jump
  69770. ** immediately to P2. If there is a match, fall through and leave the P1
  69771. ** cursor pointing to the matching row.
  69772. **
  69773. ** This opcode is similar to OP_NotFound with the exceptions that the
  69774. ** branch is always taken if any part of the search key input is NULL.
  69775. **
  69776. ** This operation leaves the cursor in a state where it cannot be
  69777. ** advanced in either direction. In other words, the Next and Prev
  69778. ** opcodes do not work after this operation.
  69779. **
  69780. ** See also: NotFound, Found, NotExists
  69781. */
  69782. case OP_NoConflict: /* jump, in3 */
  69783. case OP_NotFound: /* jump, in3 */
  69784. case OP_Found: { /* jump, in3 */
  69785. int alreadyExists;
  69786. int takeJump;
  69787. int ii;
  69788. VdbeCursor *pC;
  69789. int res;
  69790. char *pFree;
  69791. UnpackedRecord *pIdxKey;
  69792. UnpackedRecord r;
  69793. char aTempRec[ROUND8(sizeof(UnpackedRecord)) + sizeof(Mem)*4 + 7];
  69794. #ifdef SQLITE_TEST
  69795. if( pOp->opcode!=OP_NoConflict ) sqlite3_found_count++;
  69796. #endif
  69797. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  69798. assert( pOp->p4type==P4_INT32 );
  69799. pC = p->apCsr[pOp->p1];
  69800. assert( pC!=0 );
  69801. #ifdef SQLITE_DEBUG
  69802. pC->seekOp = pOp->opcode;
  69803. #endif
  69804. pIn3 = &aMem[pOp->p3];
  69805. assert( pC->pCursor!=0 );
  69806. assert( pC->isTable==0 );
  69807. pFree = 0;
  69808. if( pOp->p4.i>0 ){
  69809. r.pKeyInfo = pC->pKeyInfo;
  69810. r.nField = (u16)pOp->p4.i;
  69811. r.aMem = pIn3;
  69812. for(ii=0; ii<r.nField; ii++){
  69813. assert( memIsValid(&r.aMem[ii]) );
  69814. ExpandBlob(&r.aMem[ii]);
  69815. #ifdef SQLITE_DEBUG
  69816. if( ii ) REGISTER_TRACE(pOp->p3+ii, &r.aMem[ii]);
  69817. #endif
  69818. }
  69819. pIdxKey = &r;
  69820. }else{
  69821. pIdxKey = sqlite3VdbeAllocUnpackedRecord(
  69822. pC->pKeyInfo, aTempRec, sizeof(aTempRec), &pFree
  69823. );
  69824. if( pIdxKey==0 ) goto no_mem;
  69825. assert( pIn3->flags & MEM_Blob );
  69826. ExpandBlob(pIn3);
  69827. sqlite3VdbeRecordUnpack(pC->pKeyInfo, pIn3->n, pIn3->z, pIdxKey);
  69828. }
  69829. pIdxKey->default_rc = 0;
  69830. takeJump = 0;
  69831. if( pOp->opcode==OP_NoConflict ){
  69832. /* For the OP_NoConflict opcode, take the jump if any of the
  69833. ** input fields are NULL, since any key with a NULL will not
  69834. ** conflict */
  69835. for(ii=0; ii<pIdxKey->nField; ii++){
  69836. if( pIdxKey->aMem[ii].flags & MEM_Null ){
  69837. takeJump = 1;
  69838. break;
  69839. }
  69840. }
  69841. }
  69842. rc = sqlite3BtreeMovetoUnpacked(pC->pCursor, pIdxKey, 0, 0, &res);
  69843. sqlite3DbFree(db, pFree);
  69844. if( rc!=SQLITE_OK ){
  69845. break;
  69846. }
  69847. pC->seekResult = res;
  69848. alreadyExists = (res==0);
  69849. pC->nullRow = 1-alreadyExists;
  69850. pC->deferredMoveto = 0;
  69851. pC->cacheStatus = CACHE_STALE;
  69852. if( pOp->opcode==OP_Found ){
  69853. VdbeBranchTaken(alreadyExists!=0,2);
  69854. if( alreadyExists ) goto jump_to_p2;
  69855. }else{
  69856. VdbeBranchTaken(takeJump||alreadyExists==0,2);
  69857. if( takeJump || !alreadyExists ) goto jump_to_p2;
  69858. }
  69859. break;
  69860. }
  69861. /* Opcode: NotExists P1 P2 P3 * *
  69862. ** Synopsis: intkey=r[P3]
  69863. **
  69864. ** P1 is the index of a cursor open on an SQL table btree (with integer
  69865. ** keys). P3 is an integer rowid. If P1 does not contain a record with
  69866. ** rowid P3 then jump immediately to P2. If P1 does contain a record
  69867. ** with rowid P3 then leave the cursor pointing at that record and fall
  69868. ** through to the next instruction.
  69869. **
  69870. ** The OP_NotFound opcode performs the same operation on index btrees
  69871. ** (with arbitrary multi-value keys).
  69872. **
  69873. ** This opcode leaves the cursor in a state where it cannot be advanced
  69874. ** in either direction. In other words, the Next and Prev opcodes will
  69875. ** not work following this opcode.
  69876. **
  69877. ** See also: Found, NotFound, NoConflict
  69878. */
  69879. case OP_NotExists: { /* jump, in3 */
  69880. VdbeCursor *pC;
  69881. BtCursor *pCrsr;
  69882. int res;
  69883. u64 iKey;
  69884. pIn3 = &aMem[pOp->p3];
  69885. assert( pIn3->flags & MEM_Int );
  69886. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  69887. pC = p->apCsr[pOp->p1];
  69888. assert( pC!=0 );
  69889. #ifdef SQLITE_DEBUG
  69890. pC->seekOp = 0;
  69891. #endif
  69892. assert( pC->isTable );
  69893. assert( pC->pseudoTableReg==0 );
  69894. pCrsr = pC->pCursor;
  69895. assert( pCrsr!=0 );
  69896. res = 0;
  69897. iKey = pIn3->u.i;
  69898. rc = sqlite3BtreeMovetoUnpacked(pCrsr, 0, iKey, 0, &res);
  69899. pC->movetoTarget = iKey; /* Used by OP_Delete */
  69900. pC->nullRow = 0;
  69901. pC->cacheStatus = CACHE_STALE;
  69902. pC->deferredMoveto = 0;
  69903. VdbeBranchTaken(res!=0,2);
  69904. pC->seekResult = res;
  69905. if( res!=0 ) goto jump_to_p2;
  69906. break;
  69907. }
  69908. /* Opcode: Sequence P1 P2 * * *
  69909. ** Synopsis: r[P2]=cursor[P1].ctr++
  69910. **
  69911. ** Find the next available sequence number for cursor P1.
  69912. ** Write the sequence number into register P2.
  69913. ** The sequence number on the cursor is incremented after this
  69914. ** instruction.
  69915. */
  69916. case OP_Sequence: { /* out2 */
  69917. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  69918. assert( p->apCsr[pOp->p1]!=0 );
  69919. pOut = out2Prerelease(p, pOp);
  69920. pOut->u.i = p->apCsr[pOp->p1]->seqCount++;
  69921. break;
  69922. }
  69923. /* Opcode: NewRowid P1 P2 P3 * *
  69924. ** Synopsis: r[P2]=rowid
  69925. **
  69926. ** Get a new integer record number (a.k.a "rowid") used as the key to a table.
  69927. ** The record number is not previously used as a key in the database
  69928. ** table that cursor P1 points to. The new record number is written
  69929. ** written to register P2.
  69930. **
  69931. ** If P3>0 then P3 is a register in the root frame of this VDBE that holds
  69932. ** the largest previously generated record number. No new record numbers are
  69933. ** allowed to be less than this value. When this value reaches its maximum,
  69934. ** an SQLITE_FULL error is generated. The P3 register is updated with the '
  69935. ** generated record number. This P3 mechanism is used to help implement the
  69936. ** AUTOINCREMENT feature.
  69937. */
  69938. case OP_NewRowid: { /* out2 */
  69939. i64 v; /* The new rowid */
  69940. VdbeCursor *pC; /* Cursor of table to get the new rowid */
  69941. int res; /* Result of an sqlite3BtreeLast() */
  69942. int cnt; /* Counter to limit the number of searches */
  69943. Mem *pMem; /* Register holding largest rowid for AUTOINCREMENT */
  69944. VdbeFrame *pFrame; /* Root frame of VDBE */
  69945. v = 0;
  69946. res = 0;
  69947. pOut = out2Prerelease(p, pOp);
  69948. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  69949. pC = p->apCsr[pOp->p1];
  69950. assert( pC!=0 );
  69951. if( NEVER(pC->pCursor==0) ){
  69952. /* The zero initialization above is all that is needed */
  69953. }else{
  69954. /* The next rowid or record number (different terms for the same
  69955. ** thing) is obtained in a two-step algorithm.
  69956. **
  69957. ** First we attempt to find the largest existing rowid and add one
  69958. ** to that. But if the largest existing rowid is already the maximum
  69959. ** positive integer, we have to fall through to the second
  69960. ** probabilistic algorithm
  69961. **
  69962. ** The second algorithm is to select a rowid at random and see if
  69963. ** it already exists in the table. If it does not exist, we have
  69964. ** succeeded. If the random rowid does exist, we select a new one
  69965. ** and try again, up to 100 times.
  69966. */
  69967. assert( pC->isTable );
  69968. #ifdef SQLITE_32BIT_ROWID
  69969. # define MAX_ROWID 0x7fffffff
  69970. #else
  69971. /* Some compilers complain about constants of the form 0x7fffffffffffffff.
  69972. ** Others complain about 0x7ffffffffffffffffLL. The following macro seems
  69973. ** to provide the constant while making all compilers happy.
  69974. */
  69975. # define MAX_ROWID (i64)( (((u64)0x7fffffff)<<32) | (u64)0xffffffff )
  69976. #endif
  69977. if( !pC->useRandomRowid ){
  69978. rc = sqlite3BtreeLast(pC->pCursor, &res);
  69979. if( rc!=SQLITE_OK ){
  69980. goto abort_due_to_error;
  69981. }
  69982. if( res ){
  69983. v = 1; /* IMP: R-61914-48074 */
  69984. }else{
  69985. assert( sqlite3BtreeCursorIsValid(pC->pCursor) );
  69986. rc = sqlite3BtreeKeySize(pC->pCursor, &v);
  69987. assert( rc==SQLITE_OK ); /* Cannot fail following BtreeLast() */
  69988. if( v>=MAX_ROWID ){
  69989. pC->useRandomRowid = 1;
  69990. }else{
  69991. v++; /* IMP: R-29538-34987 */
  69992. }
  69993. }
  69994. }
  69995. #ifndef SQLITE_OMIT_AUTOINCREMENT
  69996. if( pOp->p3 ){
  69997. /* Assert that P3 is a valid memory cell. */
  69998. assert( pOp->p3>0 );
  69999. if( p->pFrame ){
  70000. for(pFrame=p->pFrame; pFrame->pParent; pFrame=pFrame->pParent);
  70001. /* Assert that P3 is a valid memory cell. */
  70002. assert( pOp->p3<=pFrame->nMem );
  70003. pMem = &pFrame->aMem[pOp->p3];
  70004. }else{
  70005. /* Assert that P3 is a valid memory cell. */
  70006. assert( pOp->p3<=(p->nMem-p->nCursor) );
  70007. pMem = &aMem[pOp->p3];
  70008. memAboutToChange(p, pMem);
  70009. }
  70010. assert( memIsValid(pMem) );
  70011. REGISTER_TRACE(pOp->p3, pMem);
  70012. sqlite3VdbeMemIntegerify(pMem);
  70013. assert( (pMem->flags & MEM_Int)!=0 ); /* mem(P3) holds an integer */
  70014. if( pMem->u.i==MAX_ROWID || pC->useRandomRowid ){
  70015. rc = SQLITE_FULL; /* IMP: R-12275-61338 */
  70016. goto abort_due_to_error;
  70017. }
  70018. if( v<pMem->u.i+1 ){
  70019. v = pMem->u.i + 1;
  70020. }
  70021. pMem->u.i = v;
  70022. }
  70023. #endif
  70024. if( pC->useRandomRowid ){
  70025. /* IMPLEMENTATION-OF: R-07677-41881 If the largest ROWID is equal to the
  70026. ** largest possible integer (9223372036854775807) then the database
  70027. ** engine starts picking positive candidate ROWIDs at random until
  70028. ** it finds one that is not previously used. */
  70029. assert( pOp->p3==0 ); /* We cannot be in random rowid mode if this is
  70030. ** an AUTOINCREMENT table. */
  70031. cnt = 0;
  70032. do{
  70033. sqlite3_randomness(sizeof(v), &v);
  70034. v &= (MAX_ROWID>>1); v++; /* Ensure that v is greater than zero */
  70035. }while( ((rc = sqlite3BtreeMovetoUnpacked(pC->pCursor, 0, (u64)v,
  70036. 0, &res))==SQLITE_OK)
  70037. && (res==0)
  70038. && (++cnt<100));
  70039. if( rc==SQLITE_OK && res==0 ){
  70040. rc = SQLITE_FULL; /* IMP: R-38219-53002 */
  70041. goto abort_due_to_error;
  70042. }
  70043. assert( v>0 ); /* EV: R-40812-03570 */
  70044. }
  70045. pC->deferredMoveto = 0;
  70046. pC->cacheStatus = CACHE_STALE;
  70047. }
  70048. pOut->u.i = v;
  70049. break;
  70050. }
  70051. /* Opcode: Insert P1 P2 P3 P4 P5
  70052. ** Synopsis: intkey=r[P3] data=r[P2]
  70053. **
  70054. ** Write an entry into the table of cursor P1. A new entry is
  70055. ** created if it doesn't already exist or the data for an existing
  70056. ** entry is overwritten. The data is the value MEM_Blob stored in register
  70057. ** number P2. The key is stored in register P3. The key must
  70058. ** be a MEM_Int.
  70059. **
  70060. ** If the OPFLAG_NCHANGE flag of P5 is set, then the row change count is
  70061. ** incremented (otherwise not). If the OPFLAG_LASTROWID flag of P5 is set,
  70062. ** then rowid is stored for subsequent return by the
  70063. ** sqlite3_last_insert_rowid() function (otherwise it is unmodified).
  70064. **
  70065. ** If the OPFLAG_USESEEKRESULT flag of P5 is set and if the result of
  70066. ** the last seek operation (OP_NotExists) was a success, then this
  70067. ** operation will not attempt to find the appropriate row before doing
  70068. ** the insert but will instead overwrite the row that the cursor is
  70069. ** currently pointing to. Presumably, the prior OP_NotExists opcode
  70070. ** has already positioned the cursor correctly. This is an optimization
  70071. ** that boosts performance by avoiding redundant seeks.
  70072. **
  70073. ** If the OPFLAG_ISUPDATE flag is set, then this opcode is part of an
  70074. ** UPDATE operation. Otherwise (if the flag is clear) then this opcode
  70075. ** is part of an INSERT operation. The difference is only important to
  70076. ** the update hook.
  70077. **
  70078. ** Parameter P4 may point to a string containing the table-name, or
  70079. ** may be NULL. If it is not NULL, then the update-hook
  70080. ** (sqlite3.xUpdateCallback) is invoked following a successful insert.
  70081. **
  70082. ** (WARNING/TODO: If P1 is a pseudo-cursor and P2 is dynamically
  70083. ** allocated, then ownership of P2 is transferred to the pseudo-cursor
  70084. ** and register P2 becomes ephemeral. If the cursor is changed, the
  70085. ** value of register P2 will then change. Make sure this does not
  70086. ** cause any problems.)
  70087. **
  70088. ** This instruction only works on tables. The equivalent instruction
  70089. ** for indices is OP_IdxInsert.
  70090. */
  70091. /* Opcode: InsertInt P1 P2 P3 P4 P5
  70092. ** Synopsis: intkey=P3 data=r[P2]
  70093. **
  70094. ** This works exactly like OP_Insert except that the key is the
  70095. ** integer value P3, not the value of the integer stored in register P3.
  70096. */
  70097. case OP_Insert:
  70098. case OP_InsertInt: {
  70099. Mem *pData; /* MEM cell holding data for the record to be inserted */
  70100. Mem *pKey; /* MEM cell holding key for the record */
  70101. i64 iKey; /* The integer ROWID or key for the record to be inserted */
  70102. VdbeCursor *pC; /* Cursor to table into which insert is written */
  70103. int nZero; /* Number of zero-bytes to append */
  70104. int seekResult; /* Result of prior seek or 0 if no USESEEKRESULT flag */
  70105. const char *zDb; /* database name - used by the update hook */
  70106. const char *zTbl; /* Table name - used by the opdate hook */
  70107. int op; /* Opcode for update hook: SQLITE_UPDATE or SQLITE_INSERT */
  70108. pData = &aMem[pOp->p2];
  70109. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  70110. assert( memIsValid(pData) );
  70111. pC = p->apCsr[pOp->p1];
  70112. assert( pC!=0 );
  70113. assert( pC->pCursor!=0 );
  70114. assert( pC->pseudoTableReg==0 );
  70115. assert( pC->isTable );
  70116. REGISTER_TRACE(pOp->p2, pData);
  70117. if( pOp->opcode==OP_Insert ){
  70118. pKey = &aMem[pOp->p3];
  70119. assert( pKey->flags & MEM_Int );
  70120. assert( memIsValid(pKey) );
  70121. REGISTER_TRACE(pOp->p3, pKey);
  70122. iKey = pKey->u.i;
  70123. }else{
  70124. assert( pOp->opcode==OP_InsertInt );
  70125. iKey = pOp->p3;
  70126. }
  70127. if( pOp->p5 & OPFLAG_NCHANGE ) p->nChange++;
  70128. if( pOp->p5 & OPFLAG_LASTROWID ) db->lastRowid = lastRowid = iKey;
  70129. if( pData->flags & MEM_Null ){
  70130. pData->z = 0;
  70131. pData->n = 0;
  70132. }else{
  70133. assert( pData->flags & (MEM_Blob|MEM_Str) );
  70134. }
  70135. seekResult = ((pOp->p5 & OPFLAG_USESEEKRESULT) ? pC->seekResult : 0);
  70136. if( pData->flags & MEM_Zero ){
  70137. nZero = pData->u.nZero;
  70138. }else{
  70139. nZero = 0;
  70140. }
  70141. rc = sqlite3BtreeInsert(pC->pCursor, 0, iKey,
  70142. pData->z, pData->n, nZero,
  70143. (pOp->p5 & OPFLAG_APPEND)!=0, seekResult
  70144. );
  70145. pC->deferredMoveto = 0;
  70146. pC->cacheStatus = CACHE_STALE;
  70147. /* Invoke the update-hook if required. */
  70148. if( rc==SQLITE_OK && db->xUpdateCallback && pOp->p4.z ){
  70149. zDb = db->aDb[pC->iDb].zName;
  70150. zTbl = pOp->p4.z;
  70151. op = ((pOp->p5 & OPFLAG_ISUPDATE) ? SQLITE_UPDATE : SQLITE_INSERT);
  70152. assert( pC->isTable );
  70153. db->xUpdateCallback(db->pUpdateArg, op, zDb, zTbl, iKey);
  70154. assert( pC->iDb>=0 );
  70155. }
  70156. break;
  70157. }
  70158. /* Opcode: Delete P1 P2 * P4 *
  70159. **
  70160. ** Delete the record at which the P1 cursor is currently pointing.
  70161. **
  70162. ** The cursor will be left pointing at either the next or the previous
  70163. ** record in the table. If it is left pointing at the next record, then
  70164. ** the next Next instruction will be a no-op. Hence it is OK to delete
  70165. ** a record from within a Next loop.
  70166. **
  70167. ** If the OPFLAG_NCHANGE flag of P2 is set, then the row change count is
  70168. ** incremented (otherwise not).
  70169. **
  70170. ** P1 must not be pseudo-table. It has to be a real table with
  70171. ** multiple rows.
  70172. **
  70173. ** If P4 is not NULL, then it is the name of the table that P1 is
  70174. ** pointing to. The update hook will be invoked, if it exists.
  70175. ** If P4 is not NULL then the P1 cursor must have been positioned
  70176. ** using OP_NotFound prior to invoking this opcode.
  70177. */
  70178. case OP_Delete: {
  70179. VdbeCursor *pC;
  70180. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  70181. pC = p->apCsr[pOp->p1];
  70182. assert( pC!=0 );
  70183. assert( pC->pCursor!=0 ); /* Only valid for real tables, no pseudotables */
  70184. assert( pC->deferredMoveto==0 );
  70185. #ifdef SQLITE_DEBUG
  70186. /* The seek operation that positioned the cursor prior to OP_Delete will
  70187. ** have also set the pC->movetoTarget field to the rowid of the row that
  70188. ** is being deleted */
  70189. if( pOp->p4.z && pC->isTable ){
  70190. i64 iKey = 0;
  70191. sqlite3BtreeKeySize(pC->pCursor, &iKey);
  70192. assert( pC->movetoTarget==iKey );
  70193. }
  70194. #endif
  70195. rc = sqlite3BtreeDelete(pC->pCursor);
  70196. pC->cacheStatus = CACHE_STALE;
  70197. /* Invoke the update-hook if required. */
  70198. if( rc==SQLITE_OK && db->xUpdateCallback && pOp->p4.z && pC->isTable ){
  70199. db->xUpdateCallback(db->pUpdateArg, SQLITE_DELETE,
  70200. db->aDb[pC->iDb].zName, pOp->p4.z, pC->movetoTarget);
  70201. assert( pC->iDb>=0 );
  70202. }
  70203. if( pOp->p2 & OPFLAG_NCHANGE ) p->nChange++;
  70204. break;
  70205. }
  70206. /* Opcode: ResetCount * * * * *
  70207. **
  70208. ** The value of the change counter is copied to the database handle
  70209. ** change counter (returned by subsequent calls to sqlite3_changes()).
  70210. ** Then the VMs internal change counter resets to 0.
  70211. ** This is used by trigger programs.
  70212. */
  70213. case OP_ResetCount: {
  70214. sqlite3VdbeSetChanges(db, p->nChange);
  70215. p->nChange = 0;
  70216. break;
  70217. }
  70218. /* Opcode: SorterCompare P1 P2 P3 P4
  70219. ** Synopsis: if key(P1)!=trim(r[P3],P4) goto P2
  70220. **
  70221. ** P1 is a sorter cursor. This instruction compares a prefix of the
  70222. ** record blob in register P3 against a prefix of the entry that
  70223. ** the sorter cursor currently points to. Only the first P4 fields
  70224. ** of r[P3] and the sorter record are compared.
  70225. **
  70226. ** If either P3 or the sorter contains a NULL in one of their significant
  70227. ** fields (not counting the P4 fields at the end which are ignored) then
  70228. ** the comparison is assumed to be equal.
  70229. **
  70230. ** Fall through to next instruction if the two records compare equal to
  70231. ** each other. Jump to P2 if they are different.
  70232. */
  70233. case OP_SorterCompare: {
  70234. VdbeCursor *pC;
  70235. int res;
  70236. int nKeyCol;
  70237. pC = p->apCsr[pOp->p1];
  70238. assert( isSorter(pC) );
  70239. assert( pOp->p4type==P4_INT32 );
  70240. pIn3 = &aMem[pOp->p3];
  70241. nKeyCol = pOp->p4.i;
  70242. res = 0;
  70243. rc = sqlite3VdbeSorterCompare(pC, pIn3, nKeyCol, &res);
  70244. VdbeBranchTaken(res!=0,2);
  70245. if( res ) goto jump_to_p2;
  70246. break;
  70247. };
  70248. /* Opcode: SorterData P1 P2 P3 * *
  70249. ** Synopsis: r[P2]=data
  70250. **
  70251. ** Write into register P2 the current sorter data for sorter cursor P1.
  70252. ** Then clear the column header cache on cursor P3.
  70253. **
  70254. ** This opcode is normally use to move a record out of the sorter and into
  70255. ** a register that is the source for a pseudo-table cursor created using
  70256. ** OpenPseudo. That pseudo-table cursor is the one that is identified by
  70257. ** parameter P3. Clearing the P3 column cache as part of this opcode saves
  70258. ** us from having to issue a separate NullRow instruction to clear that cache.
  70259. */
  70260. case OP_SorterData: {
  70261. VdbeCursor *pC;
  70262. pOut = &aMem[pOp->p2];
  70263. pC = p->apCsr[pOp->p1];
  70264. assert( isSorter(pC) );
  70265. rc = sqlite3VdbeSorterRowkey(pC, pOut);
  70266. assert( rc!=SQLITE_OK || (pOut->flags & MEM_Blob) );
  70267. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  70268. p->apCsr[pOp->p3]->cacheStatus = CACHE_STALE;
  70269. break;
  70270. }
  70271. /* Opcode: RowData P1 P2 * * *
  70272. ** Synopsis: r[P2]=data
  70273. **
  70274. ** Write into register P2 the complete row data for cursor P1.
  70275. ** There is no interpretation of the data.
  70276. ** It is just copied onto the P2 register exactly as
  70277. ** it is found in the database file.
  70278. **
  70279. ** If the P1 cursor must be pointing to a valid row (not a NULL row)
  70280. ** of a real table, not a pseudo-table.
  70281. */
  70282. /* Opcode: RowKey P1 P2 * * *
  70283. ** Synopsis: r[P2]=key
  70284. **
  70285. ** Write into register P2 the complete row key for cursor P1.
  70286. ** There is no interpretation of the data.
  70287. ** The key is copied onto the P2 register exactly as
  70288. ** it is found in the database file.
  70289. **
  70290. ** If the P1 cursor must be pointing to a valid row (not a NULL row)
  70291. ** of a real table, not a pseudo-table.
  70292. */
  70293. case OP_RowKey:
  70294. case OP_RowData: {
  70295. VdbeCursor *pC;
  70296. BtCursor *pCrsr;
  70297. u32 n;
  70298. i64 n64;
  70299. pOut = &aMem[pOp->p2];
  70300. memAboutToChange(p, pOut);
  70301. /* Note that RowKey and RowData are really exactly the same instruction */
  70302. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  70303. pC = p->apCsr[pOp->p1];
  70304. assert( isSorter(pC)==0 );
  70305. assert( pC->isTable || pOp->opcode!=OP_RowData );
  70306. assert( pC->isTable==0 || pOp->opcode==OP_RowData );
  70307. assert( pC!=0 );
  70308. assert( pC->nullRow==0 );
  70309. assert( pC->pseudoTableReg==0 );
  70310. assert( pC->pCursor!=0 );
  70311. pCrsr = pC->pCursor;
  70312. /* The OP_RowKey and OP_RowData opcodes always follow OP_NotExists or
  70313. ** OP_Rewind/Op_Next with no intervening instructions that might invalidate
  70314. ** the cursor. If this where not the case, on of the following assert()s
  70315. ** would fail. Should this ever change (because of changes in the code
  70316. ** generator) then the fix would be to insert a call to
  70317. ** sqlite3VdbeCursorMoveto().
  70318. */
  70319. assert( pC->deferredMoveto==0 );
  70320. assert( sqlite3BtreeCursorIsValid(pCrsr) );
  70321. #if 0 /* Not required due to the previous to assert() statements */
  70322. rc = sqlite3VdbeCursorMoveto(pC);
  70323. if( rc!=SQLITE_OK ) goto abort_due_to_error;
  70324. #endif
  70325. if( pC->isTable==0 ){
  70326. assert( !pC->isTable );
  70327. VVA_ONLY(rc =) sqlite3BtreeKeySize(pCrsr, &n64);
  70328. assert( rc==SQLITE_OK ); /* True because of CursorMoveto() call above */
  70329. if( n64>db->aLimit[SQLITE_LIMIT_LENGTH] ){
  70330. goto too_big;
  70331. }
  70332. n = (u32)n64;
  70333. }else{
  70334. VVA_ONLY(rc =) sqlite3BtreeDataSize(pCrsr, &n);
  70335. assert( rc==SQLITE_OK ); /* DataSize() cannot fail */
  70336. if( n>(u32)db->aLimit[SQLITE_LIMIT_LENGTH] ){
  70337. goto too_big;
  70338. }
  70339. }
  70340. testcase( n==0 );
  70341. if( sqlite3VdbeMemClearAndResize(pOut, MAX(n,32)) ){
  70342. goto no_mem;
  70343. }
  70344. pOut->n = n;
  70345. MemSetTypeFlag(pOut, MEM_Blob);
  70346. if( pC->isTable==0 ){
  70347. rc = sqlite3BtreeKey(pCrsr, 0, n, pOut->z);
  70348. }else{
  70349. rc = sqlite3BtreeData(pCrsr, 0, n, pOut->z);
  70350. }
  70351. pOut->enc = SQLITE_UTF8; /* In case the blob is ever cast to text */
  70352. UPDATE_MAX_BLOBSIZE(pOut);
  70353. REGISTER_TRACE(pOp->p2, pOut);
  70354. break;
  70355. }
  70356. /* Opcode: Rowid P1 P2 * * *
  70357. ** Synopsis: r[P2]=rowid
  70358. **
  70359. ** Store in register P2 an integer which is the key of the table entry that
  70360. ** P1 is currently point to.
  70361. **
  70362. ** P1 can be either an ordinary table or a virtual table. There used to
  70363. ** be a separate OP_VRowid opcode for use with virtual tables, but this
  70364. ** one opcode now works for both table types.
  70365. */
  70366. case OP_Rowid: { /* out2 */
  70367. VdbeCursor *pC;
  70368. i64 v;
  70369. sqlite3_vtab *pVtab;
  70370. const sqlite3_module *pModule;
  70371. pOut = out2Prerelease(p, pOp);
  70372. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  70373. pC = p->apCsr[pOp->p1];
  70374. assert( pC!=0 );
  70375. assert( pC->pseudoTableReg==0 || pC->nullRow );
  70376. if( pC->nullRow ){
  70377. pOut->flags = MEM_Null;
  70378. break;
  70379. }else if( pC->deferredMoveto ){
  70380. v = pC->movetoTarget;
  70381. #ifndef SQLITE_OMIT_VIRTUALTABLE
  70382. }else if( pC->pVtabCursor ){
  70383. pVtab = pC->pVtabCursor->pVtab;
  70384. pModule = pVtab->pModule;
  70385. assert( pModule->xRowid );
  70386. rc = pModule->xRowid(pC->pVtabCursor, &v);
  70387. sqlite3VtabImportErrmsg(p, pVtab);
  70388. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  70389. }else{
  70390. assert( pC->pCursor!=0 );
  70391. rc = sqlite3VdbeCursorRestore(pC);
  70392. if( rc ) goto abort_due_to_error;
  70393. if( pC->nullRow ){
  70394. pOut->flags = MEM_Null;
  70395. break;
  70396. }
  70397. rc = sqlite3BtreeKeySize(pC->pCursor, &v);
  70398. assert( rc==SQLITE_OK ); /* Always so because of CursorRestore() above */
  70399. }
  70400. pOut->u.i = v;
  70401. break;
  70402. }
  70403. /* Opcode: NullRow P1 * * * *
  70404. **
  70405. ** Move the cursor P1 to a null row. Any OP_Column operations
  70406. ** that occur while the cursor is on the null row will always
  70407. ** write a NULL.
  70408. */
  70409. case OP_NullRow: {
  70410. VdbeCursor *pC;
  70411. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  70412. pC = p->apCsr[pOp->p1];
  70413. assert( pC!=0 );
  70414. pC->nullRow = 1;
  70415. pC->cacheStatus = CACHE_STALE;
  70416. if( pC->pCursor ){
  70417. sqlite3BtreeClearCursor(pC->pCursor);
  70418. }
  70419. break;
  70420. }
  70421. /* Opcode: Last P1 P2 P3 * *
  70422. **
  70423. ** The next use of the Rowid or Column or Prev instruction for P1
  70424. ** will refer to the last entry in the database table or index.
  70425. ** If the table or index is empty and P2>0, then jump immediately to P2.
  70426. ** If P2 is 0 or if the table or index is not empty, fall through
  70427. ** to the following instruction.
  70428. **
  70429. ** This opcode leaves the cursor configured to move in reverse order,
  70430. ** from the end toward the beginning. In other words, the cursor is
  70431. ** configured to use Prev, not Next.
  70432. */
  70433. case OP_Last: { /* jump */
  70434. VdbeCursor *pC;
  70435. BtCursor *pCrsr;
  70436. int res;
  70437. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  70438. pC = p->apCsr[pOp->p1];
  70439. assert( pC!=0 );
  70440. pCrsr = pC->pCursor;
  70441. res = 0;
  70442. assert( pCrsr!=0 );
  70443. rc = sqlite3BtreeLast(pCrsr, &res);
  70444. pC->nullRow = (u8)res;
  70445. pC->deferredMoveto = 0;
  70446. pC->cacheStatus = CACHE_STALE;
  70447. pC->seekResult = pOp->p3;
  70448. #ifdef SQLITE_DEBUG
  70449. pC->seekOp = OP_Last;
  70450. #endif
  70451. if( pOp->p2>0 ){
  70452. VdbeBranchTaken(res!=0,2);
  70453. if( res ) goto jump_to_p2;
  70454. }
  70455. break;
  70456. }
  70457. /* Opcode: Sort P1 P2 * * *
  70458. **
  70459. ** This opcode does exactly the same thing as OP_Rewind except that
  70460. ** it increments an undocumented global variable used for testing.
  70461. **
  70462. ** Sorting is accomplished by writing records into a sorting index,
  70463. ** then rewinding that index and playing it back from beginning to
  70464. ** end. We use the OP_Sort opcode instead of OP_Rewind to do the
  70465. ** rewinding so that the global variable will be incremented and
  70466. ** regression tests can determine whether or not the optimizer is
  70467. ** correctly optimizing out sorts.
  70468. */
  70469. case OP_SorterSort: /* jump */
  70470. case OP_Sort: { /* jump */
  70471. #ifdef SQLITE_TEST
  70472. sqlite3_sort_count++;
  70473. sqlite3_search_count--;
  70474. #endif
  70475. p->aCounter[SQLITE_STMTSTATUS_SORT]++;
  70476. /* Fall through into OP_Rewind */
  70477. }
  70478. /* Opcode: Rewind P1 P2 * * *
  70479. **
  70480. ** The next use of the Rowid or Column or Next instruction for P1
  70481. ** will refer to the first entry in the database table or index.
  70482. ** If the table or index is empty, jump immediately to P2.
  70483. ** If the table or index is not empty, fall through to the following
  70484. ** instruction.
  70485. **
  70486. ** This opcode leaves the cursor configured to move in forward order,
  70487. ** from the beginning toward the end. In other words, the cursor is
  70488. ** configured to use Next, not Prev.
  70489. */
  70490. case OP_Rewind: { /* jump */
  70491. VdbeCursor *pC;
  70492. BtCursor *pCrsr;
  70493. int res;
  70494. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  70495. pC = p->apCsr[pOp->p1];
  70496. assert( pC!=0 );
  70497. assert( isSorter(pC)==(pOp->opcode==OP_SorterSort) );
  70498. res = 1;
  70499. #ifdef SQLITE_DEBUG
  70500. pC->seekOp = OP_Rewind;
  70501. #endif
  70502. if( isSorter(pC) ){
  70503. rc = sqlite3VdbeSorterRewind(pC, &res);
  70504. }else{
  70505. pCrsr = pC->pCursor;
  70506. assert( pCrsr );
  70507. rc = sqlite3BtreeFirst(pCrsr, &res);
  70508. pC->deferredMoveto = 0;
  70509. pC->cacheStatus = CACHE_STALE;
  70510. }
  70511. pC->nullRow = (u8)res;
  70512. assert( pOp->p2>0 && pOp->p2<p->nOp );
  70513. VdbeBranchTaken(res!=0,2);
  70514. if( res ) goto jump_to_p2;
  70515. break;
  70516. }
  70517. /* Opcode: Next P1 P2 P3 P4 P5
  70518. **
  70519. ** Advance cursor P1 so that it points to the next key/data pair in its
  70520. ** table or index. If there are no more key/value pairs then fall through
  70521. ** to the following instruction. But if the cursor advance was successful,
  70522. ** jump immediately to P2.
  70523. **
  70524. ** The Next opcode is only valid following an SeekGT, SeekGE, or
  70525. ** OP_Rewind opcode used to position the cursor. Next is not allowed
  70526. ** to follow SeekLT, SeekLE, or OP_Last.
  70527. **
  70528. ** The P1 cursor must be for a real table, not a pseudo-table. P1 must have
  70529. ** been opened prior to this opcode or the program will segfault.
  70530. **
  70531. ** The P3 value is a hint to the btree implementation. If P3==1, that
  70532. ** means P1 is an SQL index and that this instruction could have been
  70533. ** omitted if that index had been unique. P3 is usually 0. P3 is
  70534. ** always either 0 or 1.
  70535. **
  70536. ** P4 is always of type P4_ADVANCE. The function pointer points to
  70537. ** sqlite3BtreeNext().
  70538. **
  70539. ** If P5 is positive and the jump is taken, then event counter
  70540. ** number P5-1 in the prepared statement is incremented.
  70541. **
  70542. ** See also: Prev, NextIfOpen
  70543. */
  70544. /* Opcode: NextIfOpen P1 P2 P3 P4 P5
  70545. **
  70546. ** This opcode works just like Next except that if cursor P1 is not
  70547. ** open it behaves a no-op.
  70548. */
  70549. /* Opcode: Prev P1 P2 P3 P4 P5
  70550. **
  70551. ** Back up cursor P1 so that it points to the previous key/data pair in its
  70552. ** table or index. If there is no previous key/value pairs then fall through
  70553. ** to the following instruction. But if the cursor backup was successful,
  70554. ** jump immediately to P2.
  70555. **
  70556. **
  70557. ** The Prev opcode is only valid following an SeekLT, SeekLE, or
  70558. ** OP_Last opcode used to position the cursor. Prev is not allowed
  70559. ** to follow SeekGT, SeekGE, or OP_Rewind.
  70560. **
  70561. ** The P1 cursor must be for a real table, not a pseudo-table. If P1 is
  70562. ** not open then the behavior is undefined.
  70563. **
  70564. ** The P3 value is a hint to the btree implementation. If P3==1, that
  70565. ** means P1 is an SQL index and that this instruction could have been
  70566. ** omitted if that index had been unique. P3 is usually 0. P3 is
  70567. ** always either 0 or 1.
  70568. **
  70569. ** P4 is always of type P4_ADVANCE. The function pointer points to
  70570. ** sqlite3BtreePrevious().
  70571. **
  70572. ** If P5 is positive and the jump is taken, then event counter
  70573. ** number P5-1 in the prepared statement is incremented.
  70574. */
  70575. /* Opcode: PrevIfOpen P1 P2 P3 P4 P5
  70576. **
  70577. ** This opcode works just like Prev except that if cursor P1 is not
  70578. ** open it behaves a no-op.
  70579. */
  70580. case OP_SorterNext: { /* jump */
  70581. VdbeCursor *pC;
  70582. int res;
  70583. pC = p->apCsr[pOp->p1];
  70584. assert( isSorter(pC) );
  70585. res = 0;
  70586. rc = sqlite3VdbeSorterNext(db, pC, &res);
  70587. goto next_tail;
  70588. case OP_PrevIfOpen: /* jump */
  70589. case OP_NextIfOpen: /* jump */
  70590. if( p->apCsr[pOp->p1]==0 ) break;
  70591. /* Fall through */
  70592. case OP_Prev: /* jump */
  70593. case OP_Next: /* jump */
  70594. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  70595. assert( pOp->p5<ArraySize(p->aCounter) );
  70596. pC = p->apCsr[pOp->p1];
  70597. res = pOp->p3;
  70598. assert( pC!=0 );
  70599. assert( pC->deferredMoveto==0 );
  70600. assert( pC->pCursor );
  70601. assert( res==0 || (res==1 && pC->isTable==0) );
  70602. testcase( res==1 );
  70603. assert( pOp->opcode!=OP_Next || pOp->p4.xAdvance==sqlite3BtreeNext );
  70604. assert( pOp->opcode!=OP_Prev || pOp->p4.xAdvance==sqlite3BtreePrevious );
  70605. assert( pOp->opcode!=OP_NextIfOpen || pOp->p4.xAdvance==sqlite3BtreeNext );
  70606. assert( pOp->opcode!=OP_PrevIfOpen || pOp->p4.xAdvance==sqlite3BtreePrevious);
  70607. /* The Next opcode is only used after SeekGT, SeekGE, and Rewind.
  70608. ** The Prev opcode is only used after SeekLT, SeekLE, and Last. */
  70609. assert( pOp->opcode!=OP_Next || pOp->opcode!=OP_NextIfOpen
  70610. || pC->seekOp==OP_SeekGT || pC->seekOp==OP_SeekGE
  70611. || pC->seekOp==OP_Rewind || pC->seekOp==OP_Found);
  70612. assert( pOp->opcode!=OP_Prev || pOp->opcode!=OP_PrevIfOpen
  70613. || pC->seekOp==OP_SeekLT || pC->seekOp==OP_SeekLE
  70614. || pC->seekOp==OP_Last );
  70615. rc = pOp->p4.xAdvance(pC->pCursor, &res);
  70616. next_tail:
  70617. pC->cacheStatus = CACHE_STALE;
  70618. VdbeBranchTaken(res==0,2);
  70619. if( res==0 ){
  70620. pC->nullRow = 0;
  70621. p->aCounter[pOp->p5]++;
  70622. #ifdef SQLITE_TEST
  70623. sqlite3_search_count++;
  70624. #endif
  70625. goto jump_to_p2_and_check_for_interrupt;
  70626. }else{
  70627. pC->nullRow = 1;
  70628. }
  70629. goto check_for_interrupt;
  70630. }
  70631. /* Opcode: IdxInsert P1 P2 P3 * P5
  70632. ** Synopsis: key=r[P2]
  70633. **
  70634. ** Register P2 holds an SQL index key made using the
  70635. ** MakeRecord instructions. This opcode writes that key
  70636. ** into the index P1. Data for the entry is nil.
  70637. **
  70638. ** P3 is a flag that provides a hint to the b-tree layer that this
  70639. ** insert is likely to be an append.
  70640. **
  70641. ** If P5 has the OPFLAG_NCHANGE bit set, then the change counter is
  70642. ** incremented by this instruction. If the OPFLAG_NCHANGE bit is clear,
  70643. ** then the change counter is unchanged.
  70644. **
  70645. ** If P5 has the OPFLAG_USESEEKRESULT bit set, then the cursor must have
  70646. ** just done a seek to the spot where the new entry is to be inserted.
  70647. ** This flag avoids doing an extra seek.
  70648. **
  70649. ** This instruction only works for indices. The equivalent instruction
  70650. ** for tables is OP_Insert.
  70651. */
  70652. case OP_SorterInsert: /* in2 */
  70653. case OP_IdxInsert: { /* in2 */
  70654. VdbeCursor *pC;
  70655. BtCursor *pCrsr;
  70656. int nKey;
  70657. const char *zKey;
  70658. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  70659. pC = p->apCsr[pOp->p1];
  70660. assert( pC!=0 );
  70661. assert( isSorter(pC)==(pOp->opcode==OP_SorterInsert) );
  70662. pIn2 = &aMem[pOp->p2];
  70663. assert( pIn2->flags & MEM_Blob );
  70664. pCrsr = pC->pCursor;
  70665. if( pOp->p5 & OPFLAG_NCHANGE ) p->nChange++;
  70666. assert( pCrsr!=0 );
  70667. assert( pC->isTable==0 );
  70668. rc = ExpandBlob(pIn2);
  70669. if( rc==SQLITE_OK ){
  70670. if( isSorter(pC) ){
  70671. rc = sqlite3VdbeSorterWrite(pC, pIn2);
  70672. }else{
  70673. nKey = pIn2->n;
  70674. zKey = pIn2->z;
  70675. rc = sqlite3BtreeInsert(pCrsr, zKey, nKey, "", 0, 0, pOp->p3,
  70676. ((pOp->p5 & OPFLAG_USESEEKRESULT) ? pC->seekResult : 0)
  70677. );
  70678. assert( pC->deferredMoveto==0 );
  70679. pC->cacheStatus = CACHE_STALE;
  70680. }
  70681. }
  70682. break;
  70683. }
  70684. /* Opcode: IdxDelete P1 P2 P3 * *
  70685. ** Synopsis: key=r[P2@P3]
  70686. **
  70687. ** The content of P3 registers starting at register P2 form
  70688. ** an unpacked index key. This opcode removes that entry from the
  70689. ** index opened by cursor P1.
  70690. */
  70691. case OP_IdxDelete: {
  70692. VdbeCursor *pC;
  70693. BtCursor *pCrsr;
  70694. int res;
  70695. UnpackedRecord r;
  70696. assert( pOp->p3>0 );
  70697. assert( pOp->p2>0 && pOp->p2+pOp->p3<=(p->nMem-p->nCursor)+1 );
  70698. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  70699. pC = p->apCsr[pOp->p1];
  70700. assert( pC!=0 );
  70701. pCrsr = pC->pCursor;
  70702. assert( pCrsr!=0 );
  70703. assert( pOp->p5==0 );
  70704. r.pKeyInfo = pC->pKeyInfo;
  70705. r.nField = (u16)pOp->p3;
  70706. r.default_rc = 0;
  70707. r.aMem = &aMem[pOp->p2];
  70708. #ifdef SQLITE_DEBUG
  70709. { int i; for(i=0; i<r.nField; i++) assert( memIsValid(&r.aMem[i]) ); }
  70710. #endif
  70711. rc = sqlite3BtreeMovetoUnpacked(pCrsr, &r, 0, 0, &res);
  70712. if( rc==SQLITE_OK && res==0 ){
  70713. rc = sqlite3BtreeDelete(pCrsr);
  70714. }
  70715. assert( pC->deferredMoveto==0 );
  70716. pC->cacheStatus = CACHE_STALE;
  70717. break;
  70718. }
  70719. /* Opcode: IdxRowid P1 P2 * * *
  70720. ** Synopsis: r[P2]=rowid
  70721. **
  70722. ** Write into register P2 an integer which is the last entry in the record at
  70723. ** the end of the index key pointed to by cursor P1. This integer should be
  70724. ** the rowid of the table entry to which this index entry points.
  70725. **
  70726. ** See also: Rowid, MakeRecord.
  70727. */
  70728. case OP_IdxRowid: { /* out2 */
  70729. BtCursor *pCrsr;
  70730. VdbeCursor *pC;
  70731. i64 rowid;
  70732. pOut = out2Prerelease(p, pOp);
  70733. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  70734. pC = p->apCsr[pOp->p1];
  70735. assert( pC!=0 );
  70736. pCrsr = pC->pCursor;
  70737. assert( pCrsr!=0 );
  70738. pOut->flags = MEM_Null;
  70739. assert( pC->isTable==0 );
  70740. assert( pC->deferredMoveto==0 );
  70741. /* sqlite3VbeCursorRestore() can only fail if the record has been deleted
  70742. ** out from under the cursor. That will never happend for an IdxRowid
  70743. ** opcode, hence the NEVER() arround the check of the return value.
  70744. */
  70745. rc = sqlite3VdbeCursorRestore(pC);
  70746. if( NEVER(rc!=SQLITE_OK) ) goto abort_due_to_error;
  70747. if( !pC->nullRow ){
  70748. rowid = 0; /* Not needed. Only used to silence a warning. */
  70749. rc = sqlite3VdbeIdxRowid(db, pCrsr, &rowid);
  70750. if( rc!=SQLITE_OK ){
  70751. goto abort_due_to_error;
  70752. }
  70753. pOut->u.i = rowid;
  70754. pOut->flags = MEM_Int;
  70755. }
  70756. break;
  70757. }
  70758. /* Opcode: IdxGE P1 P2 P3 P4 P5
  70759. ** Synopsis: key=r[P3@P4]
  70760. **
  70761. ** The P4 register values beginning with P3 form an unpacked index
  70762. ** key that omits the PRIMARY KEY. Compare this key value against the index
  70763. ** that P1 is currently pointing to, ignoring the PRIMARY KEY or ROWID
  70764. ** fields at the end.
  70765. **
  70766. ** If the P1 index entry is greater than or equal to the key value
  70767. ** then jump to P2. Otherwise fall through to the next instruction.
  70768. */
  70769. /* Opcode: IdxGT P1 P2 P3 P4 P5
  70770. ** Synopsis: key=r[P3@P4]
  70771. **
  70772. ** The P4 register values beginning with P3 form an unpacked index
  70773. ** key that omits the PRIMARY KEY. Compare this key value against the index
  70774. ** that P1 is currently pointing to, ignoring the PRIMARY KEY or ROWID
  70775. ** fields at the end.
  70776. **
  70777. ** If the P1 index entry is greater than the key value
  70778. ** then jump to P2. Otherwise fall through to the next instruction.
  70779. */
  70780. /* Opcode: IdxLT P1 P2 P3 P4 P5
  70781. ** Synopsis: key=r[P3@P4]
  70782. **
  70783. ** The P4 register values beginning with P3 form an unpacked index
  70784. ** key that omits the PRIMARY KEY or ROWID. Compare this key value against
  70785. ** the index that P1 is currently pointing to, ignoring the PRIMARY KEY or
  70786. ** ROWID on the P1 index.
  70787. **
  70788. ** If the P1 index entry is less than the key value then jump to P2.
  70789. ** Otherwise fall through to the next instruction.
  70790. */
  70791. /* Opcode: IdxLE P1 P2 P3 P4 P5
  70792. ** Synopsis: key=r[P3@P4]
  70793. **
  70794. ** The P4 register values beginning with P3 form an unpacked index
  70795. ** key that omits the PRIMARY KEY or ROWID. Compare this key value against
  70796. ** the index that P1 is currently pointing to, ignoring the PRIMARY KEY or
  70797. ** ROWID on the P1 index.
  70798. **
  70799. ** If the P1 index entry is less than or equal to the key value then jump
  70800. ** to P2. Otherwise fall through to the next instruction.
  70801. */
  70802. case OP_IdxLE: /* jump */
  70803. case OP_IdxGT: /* jump */
  70804. case OP_IdxLT: /* jump */
  70805. case OP_IdxGE: { /* jump */
  70806. VdbeCursor *pC;
  70807. int res;
  70808. UnpackedRecord r;
  70809. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  70810. pC = p->apCsr[pOp->p1];
  70811. assert( pC!=0 );
  70812. assert( pC->isOrdered );
  70813. assert( pC->pCursor!=0);
  70814. assert( pC->deferredMoveto==0 );
  70815. assert( pOp->p5==0 || pOp->p5==1 );
  70816. assert( pOp->p4type==P4_INT32 );
  70817. r.pKeyInfo = pC->pKeyInfo;
  70818. r.nField = (u16)pOp->p4.i;
  70819. if( pOp->opcode<OP_IdxLT ){
  70820. assert( pOp->opcode==OP_IdxLE || pOp->opcode==OP_IdxGT );
  70821. r.default_rc = -1;
  70822. }else{
  70823. assert( pOp->opcode==OP_IdxGE || pOp->opcode==OP_IdxLT );
  70824. r.default_rc = 0;
  70825. }
  70826. r.aMem = &aMem[pOp->p3];
  70827. #ifdef SQLITE_DEBUG
  70828. { int i; for(i=0; i<r.nField; i++) assert( memIsValid(&r.aMem[i]) ); }
  70829. #endif
  70830. res = 0; /* Not needed. Only used to silence a warning. */
  70831. rc = sqlite3VdbeIdxKeyCompare(db, pC, &r, &res);
  70832. assert( (OP_IdxLE&1)==(OP_IdxLT&1) && (OP_IdxGE&1)==(OP_IdxGT&1) );
  70833. if( (pOp->opcode&1)==(OP_IdxLT&1) ){
  70834. assert( pOp->opcode==OP_IdxLE || pOp->opcode==OP_IdxLT );
  70835. res = -res;
  70836. }else{
  70837. assert( pOp->opcode==OP_IdxGE || pOp->opcode==OP_IdxGT );
  70838. res++;
  70839. }
  70840. VdbeBranchTaken(res>0,2);
  70841. if( res>0 ) goto jump_to_p2;
  70842. break;
  70843. }
  70844. /* Opcode: Destroy P1 P2 P3 * *
  70845. **
  70846. ** Delete an entire database table or index whose root page in the database
  70847. ** file is given by P1.
  70848. **
  70849. ** The table being destroyed is in the main database file if P3==0. If
  70850. ** P3==1 then the table to be clear is in the auxiliary database file
  70851. ** that is used to store tables create using CREATE TEMPORARY TABLE.
  70852. **
  70853. ** If AUTOVACUUM is enabled then it is possible that another root page
  70854. ** might be moved into the newly deleted root page in order to keep all
  70855. ** root pages contiguous at the beginning of the database. The former
  70856. ** value of the root page that moved - its value before the move occurred -
  70857. ** is stored in register P2. If no page
  70858. ** movement was required (because the table being dropped was already
  70859. ** the last one in the database) then a zero is stored in register P2.
  70860. ** If AUTOVACUUM is disabled then a zero is stored in register P2.
  70861. **
  70862. ** See also: Clear
  70863. */
  70864. case OP_Destroy: { /* out2 */
  70865. int iMoved;
  70866. int iDb;
  70867. assert( p->readOnly==0 );
  70868. pOut = out2Prerelease(p, pOp);
  70869. pOut->flags = MEM_Null;
  70870. if( db->nVdbeRead > db->nVDestroy+1 ){
  70871. rc = SQLITE_LOCKED;
  70872. p->errorAction = OE_Abort;
  70873. }else{
  70874. iDb = pOp->p3;
  70875. assert( DbMaskTest(p->btreeMask, iDb) );
  70876. iMoved = 0; /* Not needed. Only to silence a warning. */
  70877. rc = sqlite3BtreeDropTable(db->aDb[iDb].pBt, pOp->p1, &iMoved);
  70878. pOut->flags = MEM_Int;
  70879. pOut->u.i = iMoved;
  70880. #ifndef SQLITE_OMIT_AUTOVACUUM
  70881. if( rc==SQLITE_OK && iMoved!=0 ){
  70882. sqlite3RootPageMoved(db, iDb, iMoved, pOp->p1);
  70883. /* All OP_Destroy operations occur on the same btree */
  70884. assert( resetSchemaOnFault==0 || resetSchemaOnFault==iDb+1 );
  70885. resetSchemaOnFault = iDb+1;
  70886. }
  70887. #endif
  70888. }
  70889. break;
  70890. }
  70891. /* Opcode: Clear P1 P2 P3
  70892. **
  70893. ** Delete all contents of the database table or index whose root page
  70894. ** in the database file is given by P1. But, unlike Destroy, do not
  70895. ** remove the table or index from the database file.
  70896. **
  70897. ** The table being clear is in the main database file if P2==0. If
  70898. ** P2==1 then the table to be clear is in the auxiliary database file
  70899. ** that is used to store tables create using CREATE TEMPORARY TABLE.
  70900. **
  70901. ** If the P3 value is non-zero, then the table referred to must be an
  70902. ** intkey table (an SQL table, not an index). In this case the row change
  70903. ** count is incremented by the number of rows in the table being cleared.
  70904. ** If P3 is greater than zero, then the value stored in register P3 is
  70905. ** also incremented by the number of rows in the table being cleared.
  70906. **
  70907. ** See also: Destroy
  70908. */
  70909. case OP_Clear: {
  70910. int nChange;
  70911. nChange = 0;
  70912. assert( p->readOnly==0 );
  70913. assert( DbMaskTest(p->btreeMask, pOp->p2) );
  70914. rc = sqlite3BtreeClearTable(
  70915. db->aDb[pOp->p2].pBt, pOp->p1, (pOp->p3 ? &nChange : 0)
  70916. );
  70917. if( pOp->p3 ){
  70918. p->nChange += nChange;
  70919. if( pOp->p3>0 ){
  70920. assert( memIsValid(&aMem[pOp->p3]) );
  70921. memAboutToChange(p, &aMem[pOp->p3]);
  70922. aMem[pOp->p3].u.i += nChange;
  70923. }
  70924. }
  70925. break;
  70926. }
  70927. /* Opcode: ResetSorter P1 * * * *
  70928. **
  70929. ** Delete all contents from the ephemeral table or sorter
  70930. ** that is open on cursor P1.
  70931. **
  70932. ** This opcode only works for cursors used for sorting and
  70933. ** opened with OP_OpenEphemeral or OP_SorterOpen.
  70934. */
  70935. case OP_ResetSorter: {
  70936. VdbeCursor *pC;
  70937. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  70938. pC = p->apCsr[pOp->p1];
  70939. assert( pC!=0 );
  70940. if( pC->pSorter ){
  70941. sqlite3VdbeSorterReset(db, pC->pSorter);
  70942. }else{
  70943. assert( pC->isEphemeral );
  70944. rc = sqlite3BtreeClearTableOfCursor(pC->pCursor);
  70945. }
  70946. break;
  70947. }
  70948. /* Opcode: CreateTable P1 P2 * * *
  70949. ** Synopsis: r[P2]=root iDb=P1
  70950. **
  70951. ** Allocate a new table in the main database file if P1==0 or in the
  70952. ** auxiliary database file if P1==1 or in an attached database if
  70953. ** P1>1. Write the root page number of the new table into
  70954. ** register P2
  70955. **
  70956. ** The difference between a table and an index is this: A table must
  70957. ** have a 4-byte integer key and can have arbitrary data. An index
  70958. ** has an arbitrary key but no data.
  70959. **
  70960. ** See also: CreateIndex
  70961. */
  70962. /* Opcode: CreateIndex P1 P2 * * *
  70963. ** Synopsis: r[P2]=root iDb=P1
  70964. **
  70965. ** Allocate a new index in the main database file if P1==0 or in the
  70966. ** auxiliary database file if P1==1 or in an attached database if
  70967. ** P1>1. Write the root page number of the new table into
  70968. ** register P2.
  70969. **
  70970. ** See documentation on OP_CreateTable for additional information.
  70971. */
  70972. case OP_CreateIndex: /* out2 */
  70973. case OP_CreateTable: { /* out2 */
  70974. int pgno;
  70975. int flags;
  70976. Db *pDb;
  70977. pOut = out2Prerelease(p, pOp);
  70978. pgno = 0;
  70979. assert( pOp->p1>=0 && pOp->p1<db->nDb );
  70980. assert( DbMaskTest(p->btreeMask, pOp->p1) );
  70981. assert( p->readOnly==0 );
  70982. pDb = &db->aDb[pOp->p1];
  70983. assert( pDb->pBt!=0 );
  70984. if( pOp->opcode==OP_CreateTable ){
  70985. /* flags = BTREE_INTKEY; */
  70986. flags = BTREE_INTKEY;
  70987. }else{
  70988. flags = BTREE_BLOBKEY;
  70989. }
  70990. rc = sqlite3BtreeCreateTable(pDb->pBt, &pgno, flags);
  70991. pOut->u.i = pgno;
  70992. break;
  70993. }
  70994. /* Opcode: ParseSchema P1 * * P4 *
  70995. **
  70996. ** Read and parse all entries from the SQLITE_MASTER table of database P1
  70997. ** that match the WHERE clause P4.
  70998. **
  70999. ** This opcode invokes the parser to create a new virtual machine,
  71000. ** then runs the new virtual machine. It is thus a re-entrant opcode.
  71001. */
  71002. case OP_ParseSchema: {
  71003. int iDb;
  71004. const char *zMaster;
  71005. char *zSql;
  71006. InitData initData;
  71007. /* Any prepared statement that invokes this opcode will hold mutexes
  71008. ** on every btree. This is a prerequisite for invoking
  71009. ** sqlite3InitCallback().
  71010. */
  71011. #ifdef SQLITE_DEBUG
  71012. for(iDb=0; iDb<db->nDb; iDb++){
  71013. assert( iDb==1 || sqlite3BtreeHoldsMutex(db->aDb[iDb].pBt) );
  71014. }
  71015. #endif
  71016. iDb = pOp->p1;
  71017. assert( iDb>=0 && iDb<db->nDb );
  71018. assert( DbHasProperty(db, iDb, DB_SchemaLoaded) );
  71019. /* Used to be a conditional */ {
  71020. zMaster = SCHEMA_TABLE(iDb);
  71021. initData.db = db;
  71022. initData.iDb = pOp->p1;
  71023. initData.pzErrMsg = &p->zErrMsg;
  71024. zSql = sqlite3MPrintf(db,
  71025. "SELECT name, rootpage, sql FROM '%q'.%s WHERE %s ORDER BY rowid",
  71026. db->aDb[iDb].zName, zMaster, pOp->p4.z);
  71027. if( zSql==0 ){
  71028. rc = SQLITE_NOMEM;
  71029. }else{
  71030. assert( db->init.busy==0 );
  71031. db->init.busy = 1;
  71032. initData.rc = SQLITE_OK;
  71033. assert( !db->mallocFailed );
  71034. rc = sqlite3_exec(db, zSql, sqlite3InitCallback, &initData, 0);
  71035. if( rc==SQLITE_OK ) rc = initData.rc;
  71036. sqlite3DbFree(db, zSql);
  71037. db->init.busy = 0;
  71038. }
  71039. }
  71040. if( rc ) sqlite3ResetAllSchemasOfConnection(db);
  71041. if( rc==SQLITE_NOMEM ){
  71042. goto no_mem;
  71043. }
  71044. break;
  71045. }
  71046. #if !defined(SQLITE_OMIT_ANALYZE)
  71047. /* Opcode: LoadAnalysis P1 * * * *
  71048. **
  71049. ** Read the sqlite_stat1 table for database P1 and load the content
  71050. ** of that table into the internal index hash table. This will cause
  71051. ** the analysis to be used when preparing all subsequent queries.
  71052. */
  71053. case OP_LoadAnalysis: {
  71054. assert( pOp->p1>=0 && pOp->p1<db->nDb );
  71055. rc = sqlite3AnalysisLoad(db, pOp->p1);
  71056. break;
  71057. }
  71058. #endif /* !defined(SQLITE_OMIT_ANALYZE) */
  71059. /* Opcode: DropTable P1 * * P4 *
  71060. **
  71061. ** Remove the internal (in-memory) data structures that describe
  71062. ** the table named P4 in database P1. This is called after a table
  71063. ** is dropped from disk (using the Destroy opcode) in order to keep
  71064. ** the internal representation of the
  71065. ** schema consistent with what is on disk.
  71066. */
  71067. case OP_DropTable: {
  71068. sqlite3UnlinkAndDeleteTable(db, pOp->p1, pOp->p4.z);
  71069. break;
  71070. }
  71071. /* Opcode: DropIndex P1 * * P4 *
  71072. **
  71073. ** Remove the internal (in-memory) data structures that describe
  71074. ** the index named P4 in database P1. This is called after an index
  71075. ** is dropped from disk (using the Destroy opcode)
  71076. ** in order to keep the internal representation of the
  71077. ** schema consistent with what is on disk.
  71078. */
  71079. case OP_DropIndex: {
  71080. sqlite3UnlinkAndDeleteIndex(db, pOp->p1, pOp->p4.z);
  71081. break;
  71082. }
  71083. /* Opcode: DropTrigger P1 * * P4 *
  71084. **
  71085. ** Remove the internal (in-memory) data structures that describe
  71086. ** the trigger named P4 in database P1. This is called after a trigger
  71087. ** is dropped from disk (using the Destroy opcode) in order to keep
  71088. ** the internal representation of the
  71089. ** schema consistent with what is on disk.
  71090. */
  71091. case OP_DropTrigger: {
  71092. sqlite3UnlinkAndDeleteTrigger(db, pOp->p1, pOp->p4.z);
  71093. break;
  71094. }
  71095. #ifndef SQLITE_OMIT_INTEGRITY_CHECK
  71096. /* Opcode: IntegrityCk P1 P2 P3 * P5
  71097. **
  71098. ** Do an analysis of the currently open database. Store in
  71099. ** register P1 the text of an error message describing any problems.
  71100. ** If no problems are found, store a NULL in register P1.
  71101. **
  71102. ** The register P3 contains the maximum number of allowed errors.
  71103. ** At most reg(P3) errors will be reported.
  71104. ** In other words, the analysis stops as soon as reg(P1) errors are
  71105. ** seen. Reg(P1) is updated with the number of errors remaining.
  71106. **
  71107. ** The root page numbers of all tables in the database are integer
  71108. ** stored in reg(P1), reg(P1+1), reg(P1+2), .... There are P2 tables
  71109. ** total.
  71110. **
  71111. ** If P5 is not zero, the check is done on the auxiliary database
  71112. ** file, not the main database file.
  71113. **
  71114. ** This opcode is used to implement the integrity_check pragma.
  71115. */
  71116. case OP_IntegrityCk: {
  71117. int nRoot; /* Number of tables to check. (Number of root pages.) */
  71118. int *aRoot; /* Array of rootpage numbers for tables to be checked */
  71119. int j; /* Loop counter */
  71120. int nErr; /* Number of errors reported */
  71121. char *z; /* Text of the error report */
  71122. Mem *pnErr; /* Register keeping track of errors remaining */
  71123. assert( p->bIsReader );
  71124. nRoot = pOp->p2;
  71125. assert( nRoot>0 );
  71126. aRoot = sqlite3DbMallocRaw(db, sizeof(int)*(nRoot+1) );
  71127. if( aRoot==0 ) goto no_mem;
  71128. assert( pOp->p3>0 && pOp->p3<=(p->nMem-p->nCursor) );
  71129. pnErr = &aMem[pOp->p3];
  71130. assert( (pnErr->flags & MEM_Int)!=0 );
  71131. assert( (pnErr->flags & (MEM_Str|MEM_Blob))==0 );
  71132. pIn1 = &aMem[pOp->p1];
  71133. for(j=0; j<nRoot; j++){
  71134. aRoot[j] = (int)sqlite3VdbeIntValue(&pIn1[j]);
  71135. }
  71136. aRoot[j] = 0;
  71137. assert( pOp->p5<db->nDb );
  71138. assert( DbMaskTest(p->btreeMask, pOp->p5) );
  71139. z = sqlite3BtreeIntegrityCheck(db->aDb[pOp->p5].pBt, aRoot, nRoot,
  71140. (int)pnErr->u.i, &nErr);
  71141. sqlite3DbFree(db, aRoot);
  71142. pnErr->u.i -= nErr;
  71143. sqlite3VdbeMemSetNull(pIn1);
  71144. if( nErr==0 ){
  71145. assert( z==0 );
  71146. }else if( z==0 ){
  71147. goto no_mem;
  71148. }else{
  71149. sqlite3VdbeMemSetStr(pIn1, z, -1, SQLITE_UTF8, sqlite3_free);
  71150. }
  71151. UPDATE_MAX_BLOBSIZE(pIn1);
  71152. sqlite3VdbeChangeEncoding(pIn1, encoding);
  71153. break;
  71154. }
  71155. #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
  71156. /* Opcode: RowSetAdd P1 P2 * * *
  71157. ** Synopsis: rowset(P1)=r[P2]
  71158. **
  71159. ** Insert the integer value held by register P2 into a boolean index
  71160. ** held in register P1.
  71161. **
  71162. ** An assertion fails if P2 is not an integer.
  71163. */
  71164. case OP_RowSetAdd: { /* in1, in2 */
  71165. pIn1 = &aMem[pOp->p1];
  71166. pIn2 = &aMem[pOp->p2];
  71167. assert( (pIn2->flags & MEM_Int)!=0 );
  71168. if( (pIn1->flags & MEM_RowSet)==0 ){
  71169. sqlite3VdbeMemSetRowSet(pIn1);
  71170. if( (pIn1->flags & MEM_RowSet)==0 ) goto no_mem;
  71171. }
  71172. sqlite3RowSetInsert(pIn1->u.pRowSet, pIn2->u.i);
  71173. break;
  71174. }
  71175. /* Opcode: RowSetRead P1 P2 P3 * *
  71176. ** Synopsis: r[P3]=rowset(P1)
  71177. **
  71178. ** Extract the smallest value from boolean index P1 and put that value into
  71179. ** register P3. Or, if boolean index P1 is initially empty, leave P3
  71180. ** unchanged and jump to instruction P2.
  71181. */
  71182. case OP_RowSetRead: { /* jump, in1, out3 */
  71183. i64 val;
  71184. pIn1 = &aMem[pOp->p1];
  71185. if( (pIn1->flags & MEM_RowSet)==0
  71186. || sqlite3RowSetNext(pIn1->u.pRowSet, &val)==0
  71187. ){
  71188. /* The boolean index is empty */
  71189. sqlite3VdbeMemSetNull(pIn1);
  71190. VdbeBranchTaken(1,2);
  71191. goto jump_to_p2_and_check_for_interrupt;
  71192. }else{
  71193. /* A value was pulled from the index */
  71194. VdbeBranchTaken(0,2);
  71195. sqlite3VdbeMemSetInt64(&aMem[pOp->p3], val);
  71196. }
  71197. goto check_for_interrupt;
  71198. }
  71199. /* Opcode: RowSetTest P1 P2 P3 P4
  71200. ** Synopsis: if r[P3] in rowset(P1) goto P2
  71201. **
  71202. ** Register P3 is assumed to hold a 64-bit integer value. If register P1
  71203. ** contains a RowSet object and that RowSet object contains
  71204. ** the value held in P3, jump to register P2. Otherwise, insert the
  71205. ** integer in P3 into the RowSet and continue on to the
  71206. ** next opcode.
  71207. **
  71208. ** The RowSet object is optimized for the case where successive sets
  71209. ** of integers, where each set contains no duplicates. Each set
  71210. ** of values is identified by a unique P4 value. The first set
  71211. ** must have P4==0, the final set P4=-1. P4 must be either -1 or
  71212. ** non-negative. For non-negative values of P4 only the lower 4
  71213. ** bits are significant.
  71214. **
  71215. ** This allows optimizations: (a) when P4==0 there is no need to test
  71216. ** the rowset object for P3, as it is guaranteed not to contain it,
  71217. ** (b) when P4==-1 there is no need to insert the value, as it will
  71218. ** never be tested for, and (c) when a value that is part of set X is
  71219. ** inserted, there is no need to search to see if the same value was
  71220. ** previously inserted as part of set X (only if it was previously
  71221. ** inserted as part of some other set).
  71222. */
  71223. case OP_RowSetTest: { /* jump, in1, in3 */
  71224. int iSet;
  71225. int exists;
  71226. pIn1 = &aMem[pOp->p1];
  71227. pIn3 = &aMem[pOp->p3];
  71228. iSet = pOp->p4.i;
  71229. assert( pIn3->flags&MEM_Int );
  71230. /* If there is anything other than a rowset object in memory cell P1,
  71231. ** delete it now and initialize P1 with an empty rowset
  71232. */
  71233. if( (pIn1->flags & MEM_RowSet)==0 ){
  71234. sqlite3VdbeMemSetRowSet(pIn1);
  71235. if( (pIn1->flags & MEM_RowSet)==0 ) goto no_mem;
  71236. }
  71237. assert( pOp->p4type==P4_INT32 );
  71238. assert( iSet==-1 || iSet>=0 );
  71239. if( iSet ){
  71240. exists = sqlite3RowSetTest(pIn1->u.pRowSet, iSet, pIn3->u.i);
  71241. VdbeBranchTaken(exists!=0,2);
  71242. if( exists ) goto jump_to_p2;
  71243. }
  71244. if( iSet>=0 ){
  71245. sqlite3RowSetInsert(pIn1->u.pRowSet, pIn3->u.i);
  71246. }
  71247. break;
  71248. }
  71249. #ifndef SQLITE_OMIT_TRIGGER
  71250. /* Opcode: Program P1 P2 P3 P4 P5
  71251. **
  71252. ** Execute the trigger program passed as P4 (type P4_SUBPROGRAM).
  71253. **
  71254. ** P1 contains the address of the memory cell that contains the first memory
  71255. ** cell in an array of values used as arguments to the sub-program. P2
  71256. ** contains the address to jump to if the sub-program throws an IGNORE
  71257. ** exception using the RAISE() function. Register P3 contains the address
  71258. ** of a memory cell in this (the parent) VM that is used to allocate the
  71259. ** memory required by the sub-vdbe at runtime.
  71260. **
  71261. ** P4 is a pointer to the VM containing the trigger program.
  71262. **
  71263. ** If P5 is non-zero, then recursive program invocation is enabled.
  71264. */
  71265. case OP_Program: { /* jump */
  71266. int nMem; /* Number of memory registers for sub-program */
  71267. int nByte; /* Bytes of runtime space required for sub-program */
  71268. Mem *pRt; /* Register to allocate runtime space */
  71269. Mem *pMem; /* Used to iterate through memory cells */
  71270. Mem *pEnd; /* Last memory cell in new array */
  71271. VdbeFrame *pFrame; /* New vdbe frame to execute in */
  71272. SubProgram *pProgram; /* Sub-program to execute */
  71273. void *t; /* Token identifying trigger */
  71274. pProgram = pOp->p4.pProgram;
  71275. pRt = &aMem[pOp->p3];
  71276. assert( pProgram->nOp>0 );
  71277. /* If the p5 flag is clear, then recursive invocation of triggers is
  71278. ** disabled for backwards compatibility (p5 is set if this sub-program
  71279. ** is really a trigger, not a foreign key action, and the flag set
  71280. ** and cleared by the "PRAGMA recursive_triggers" command is clear).
  71281. **
  71282. ** It is recursive invocation of triggers, at the SQL level, that is
  71283. ** disabled. In some cases a single trigger may generate more than one
  71284. ** SubProgram (if the trigger may be executed with more than one different
  71285. ** ON CONFLICT algorithm). SubProgram structures associated with a
  71286. ** single trigger all have the same value for the SubProgram.token
  71287. ** variable. */
  71288. if( pOp->p5 ){
  71289. t = pProgram->token;
  71290. for(pFrame=p->pFrame; pFrame && pFrame->token!=t; pFrame=pFrame->pParent);
  71291. if( pFrame ) break;
  71292. }
  71293. if( p->nFrame>=db->aLimit[SQLITE_LIMIT_TRIGGER_DEPTH] ){
  71294. rc = SQLITE_ERROR;
  71295. sqlite3SetString(&p->zErrMsg, db, "too many levels of trigger recursion");
  71296. break;
  71297. }
  71298. /* Register pRt is used to store the memory required to save the state
  71299. ** of the current program, and the memory required at runtime to execute
  71300. ** the trigger program. If this trigger has been fired before, then pRt
  71301. ** is already allocated. Otherwise, it must be initialized. */
  71302. if( (pRt->flags&MEM_Frame)==0 ){
  71303. /* SubProgram.nMem is set to the number of memory cells used by the
  71304. ** program stored in SubProgram.aOp. As well as these, one memory
  71305. ** cell is required for each cursor used by the program. Set local
  71306. ** variable nMem (and later, VdbeFrame.nChildMem) to this value.
  71307. */
  71308. nMem = pProgram->nMem + pProgram->nCsr;
  71309. nByte = ROUND8(sizeof(VdbeFrame))
  71310. + nMem * sizeof(Mem)
  71311. + pProgram->nCsr * sizeof(VdbeCursor *)
  71312. + pProgram->nOnce * sizeof(u8);
  71313. pFrame = sqlite3DbMallocZero(db, nByte);
  71314. if( !pFrame ){
  71315. goto no_mem;
  71316. }
  71317. sqlite3VdbeMemRelease(pRt);
  71318. pRt->flags = MEM_Frame;
  71319. pRt->u.pFrame = pFrame;
  71320. pFrame->v = p;
  71321. pFrame->nChildMem = nMem;
  71322. pFrame->nChildCsr = pProgram->nCsr;
  71323. pFrame->pc = (int)(pOp - aOp);
  71324. pFrame->aMem = p->aMem;
  71325. pFrame->nMem = p->nMem;
  71326. pFrame->apCsr = p->apCsr;
  71327. pFrame->nCursor = p->nCursor;
  71328. pFrame->aOp = p->aOp;
  71329. pFrame->nOp = p->nOp;
  71330. pFrame->token = pProgram->token;
  71331. pFrame->aOnceFlag = p->aOnceFlag;
  71332. pFrame->nOnceFlag = p->nOnceFlag;
  71333. #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
  71334. pFrame->anExec = p->anExec;
  71335. #endif
  71336. pEnd = &VdbeFrameMem(pFrame)[pFrame->nChildMem];
  71337. for(pMem=VdbeFrameMem(pFrame); pMem!=pEnd; pMem++){
  71338. pMem->flags = MEM_Undefined;
  71339. pMem->db = db;
  71340. }
  71341. }else{
  71342. pFrame = pRt->u.pFrame;
  71343. assert( pProgram->nMem+pProgram->nCsr==pFrame->nChildMem );
  71344. assert( pProgram->nCsr==pFrame->nChildCsr );
  71345. assert( (int)(pOp - aOp)==pFrame->pc );
  71346. }
  71347. p->nFrame++;
  71348. pFrame->pParent = p->pFrame;
  71349. pFrame->lastRowid = lastRowid;
  71350. pFrame->nChange = p->nChange;
  71351. pFrame->nDbChange = p->db->nChange;
  71352. p->nChange = 0;
  71353. p->pFrame = pFrame;
  71354. p->aMem = aMem = &VdbeFrameMem(pFrame)[-1];
  71355. p->nMem = pFrame->nChildMem;
  71356. p->nCursor = (u16)pFrame->nChildCsr;
  71357. p->apCsr = (VdbeCursor **)&aMem[p->nMem+1];
  71358. p->aOp = aOp = pProgram->aOp;
  71359. p->nOp = pProgram->nOp;
  71360. p->aOnceFlag = (u8 *)&p->apCsr[p->nCursor];
  71361. p->nOnceFlag = pProgram->nOnce;
  71362. #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
  71363. p->anExec = 0;
  71364. #endif
  71365. pOp = &aOp[-1];
  71366. memset(p->aOnceFlag, 0, p->nOnceFlag);
  71367. break;
  71368. }
  71369. /* Opcode: Param P1 P2 * * *
  71370. **
  71371. ** This opcode is only ever present in sub-programs called via the
  71372. ** OP_Program instruction. Copy a value currently stored in a memory
  71373. ** cell of the calling (parent) frame to cell P2 in the current frames
  71374. ** address space. This is used by trigger programs to access the new.*
  71375. ** and old.* values.
  71376. **
  71377. ** The address of the cell in the parent frame is determined by adding
  71378. ** the value of the P1 argument to the value of the P1 argument to the
  71379. ** calling OP_Program instruction.
  71380. */
  71381. case OP_Param: { /* out2 */
  71382. VdbeFrame *pFrame;
  71383. Mem *pIn;
  71384. pOut = out2Prerelease(p, pOp);
  71385. pFrame = p->pFrame;
  71386. pIn = &pFrame->aMem[pOp->p1 + pFrame->aOp[pFrame->pc].p1];
  71387. sqlite3VdbeMemShallowCopy(pOut, pIn, MEM_Ephem);
  71388. break;
  71389. }
  71390. #endif /* #ifndef SQLITE_OMIT_TRIGGER */
  71391. #ifndef SQLITE_OMIT_FOREIGN_KEY
  71392. /* Opcode: FkCounter P1 P2 * * *
  71393. ** Synopsis: fkctr[P1]+=P2
  71394. **
  71395. ** Increment a "constraint counter" by P2 (P2 may be negative or positive).
  71396. ** If P1 is non-zero, the database constraint counter is incremented
  71397. ** (deferred foreign key constraints). Otherwise, if P1 is zero, the
  71398. ** statement counter is incremented (immediate foreign key constraints).
  71399. */
  71400. case OP_FkCounter: {
  71401. if( db->flags & SQLITE_DeferFKs ){
  71402. db->nDeferredImmCons += pOp->p2;
  71403. }else if( pOp->p1 ){
  71404. db->nDeferredCons += pOp->p2;
  71405. }else{
  71406. p->nFkConstraint += pOp->p2;
  71407. }
  71408. break;
  71409. }
  71410. /* Opcode: FkIfZero P1 P2 * * *
  71411. ** Synopsis: if fkctr[P1]==0 goto P2
  71412. **
  71413. ** This opcode tests if a foreign key constraint-counter is currently zero.
  71414. ** If so, jump to instruction P2. Otherwise, fall through to the next
  71415. ** instruction.
  71416. **
  71417. ** If P1 is non-zero, then the jump is taken if the database constraint-counter
  71418. ** is zero (the one that counts deferred constraint violations). If P1 is
  71419. ** zero, the jump is taken if the statement constraint-counter is zero
  71420. ** (immediate foreign key constraint violations).
  71421. */
  71422. case OP_FkIfZero: { /* jump */
  71423. if( pOp->p1 ){
  71424. VdbeBranchTaken(db->nDeferredCons==0 && db->nDeferredImmCons==0, 2);
  71425. if( db->nDeferredCons==0 && db->nDeferredImmCons==0 ) goto jump_to_p2;
  71426. }else{
  71427. VdbeBranchTaken(p->nFkConstraint==0 && db->nDeferredImmCons==0, 2);
  71428. if( p->nFkConstraint==0 && db->nDeferredImmCons==0 ) goto jump_to_p2;
  71429. }
  71430. break;
  71431. }
  71432. #endif /* #ifndef SQLITE_OMIT_FOREIGN_KEY */
  71433. #ifndef SQLITE_OMIT_AUTOINCREMENT
  71434. /* Opcode: MemMax P1 P2 * * *
  71435. ** Synopsis: r[P1]=max(r[P1],r[P2])
  71436. **
  71437. ** P1 is a register in the root frame of this VM (the root frame is
  71438. ** different from the current frame if this instruction is being executed
  71439. ** within a sub-program). Set the value of register P1 to the maximum of
  71440. ** its current value and the value in register P2.
  71441. **
  71442. ** This instruction throws an error if the memory cell is not initially
  71443. ** an integer.
  71444. */
  71445. case OP_MemMax: { /* in2 */
  71446. VdbeFrame *pFrame;
  71447. if( p->pFrame ){
  71448. for(pFrame=p->pFrame; pFrame->pParent; pFrame=pFrame->pParent);
  71449. pIn1 = &pFrame->aMem[pOp->p1];
  71450. }else{
  71451. pIn1 = &aMem[pOp->p1];
  71452. }
  71453. assert( memIsValid(pIn1) );
  71454. sqlite3VdbeMemIntegerify(pIn1);
  71455. pIn2 = &aMem[pOp->p2];
  71456. sqlite3VdbeMemIntegerify(pIn2);
  71457. if( pIn1->u.i<pIn2->u.i){
  71458. pIn1->u.i = pIn2->u.i;
  71459. }
  71460. break;
  71461. }
  71462. #endif /* SQLITE_OMIT_AUTOINCREMENT */
  71463. /* Opcode: IfPos P1 P2 * * *
  71464. ** Synopsis: if r[P1]>0 goto P2
  71465. **
  71466. ** Register P1 must contain an integer.
  71467. ** If the value of register P1 is 1 or greater, jump to P2 and
  71468. ** add the literal value P3 to register P1.
  71469. **
  71470. ** If the initial value of register P1 is less than 1, then the
  71471. ** value is unchanged and control passes through to the next instruction.
  71472. */
  71473. case OP_IfPos: { /* jump, in1 */
  71474. pIn1 = &aMem[pOp->p1];
  71475. assert( pIn1->flags&MEM_Int );
  71476. VdbeBranchTaken( pIn1->u.i>0, 2);
  71477. if( pIn1->u.i>0 ) goto jump_to_p2;
  71478. break;
  71479. }
  71480. /* Opcode: IfNeg P1 P2 P3 * *
  71481. ** Synopsis: r[P1]+=P3, if r[P1]<0 goto P2
  71482. **
  71483. ** Register P1 must contain an integer. Add literal P3 to the value in
  71484. ** register P1 then if the value of register P1 is less than zero, jump to P2.
  71485. */
  71486. case OP_IfNeg: { /* jump, in1 */
  71487. pIn1 = &aMem[pOp->p1];
  71488. assert( pIn1->flags&MEM_Int );
  71489. pIn1->u.i += pOp->p3;
  71490. VdbeBranchTaken(pIn1->u.i<0, 2);
  71491. if( pIn1->u.i<0 ) goto jump_to_p2;
  71492. break;
  71493. }
  71494. /* Opcode: IfNotZero P1 P2 P3 * *
  71495. ** Synopsis: if r[P1]!=0 then r[P1]+=P3, goto P2
  71496. **
  71497. ** Register P1 must contain an integer. If the content of register P1 is
  71498. ** initially nonzero, then add P3 to P1 and jump to P2. If register P1 is
  71499. ** initially zero, leave it unchanged and fall through.
  71500. */
  71501. case OP_IfNotZero: { /* jump, in1 */
  71502. pIn1 = &aMem[pOp->p1];
  71503. assert( pIn1->flags&MEM_Int );
  71504. VdbeBranchTaken(pIn1->u.i<0, 2);
  71505. if( pIn1->u.i ){
  71506. pIn1->u.i += pOp->p3;
  71507. goto jump_to_p2;
  71508. }
  71509. break;
  71510. }
  71511. /* Opcode: DecrJumpZero P1 P2 * * *
  71512. ** Synopsis: if (--r[P1])==0 goto P2
  71513. **
  71514. ** Register P1 must hold an integer. Decrement the value in register P1
  71515. ** then jump to P2 if the new value is exactly zero.
  71516. */
  71517. case OP_DecrJumpZero: { /* jump, in1 */
  71518. pIn1 = &aMem[pOp->p1];
  71519. assert( pIn1->flags&MEM_Int );
  71520. pIn1->u.i--;
  71521. VdbeBranchTaken(pIn1->u.i==0, 2);
  71522. if( pIn1->u.i==0 ) goto jump_to_p2;
  71523. break;
  71524. }
  71525. /* Opcode: JumpZeroIncr P1 P2 * * *
  71526. ** Synopsis: if (r[P1]++)==0 ) goto P2
  71527. **
  71528. ** The register P1 must contain an integer. If register P1 is initially
  71529. ** zero, then jump to P2. Increment register P1 regardless of whether or
  71530. ** not the jump is taken.
  71531. */
  71532. case OP_JumpZeroIncr: { /* jump, in1 */
  71533. pIn1 = &aMem[pOp->p1];
  71534. assert( pIn1->flags&MEM_Int );
  71535. VdbeBranchTaken(pIn1->u.i==0, 2);
  71536. if( (pIn1->u.i++)==0 ) goto jump_to_p2;
  71537. break;
  71538. }
  71539. /* Opcode: AggStep * P2 P3 P4 P5
  71540. ** Synopsis: accum=r[P3] step(r[P2@P5])
  71541. **
  71542. ** Execute the step function for an aggregate. The
  71543. ** function has P5 arguments. P4 is a pointer to the FuncDef
  71544. ** structure that specifies the function. Use register
  71545. ** P3 as the accumulator.
  71546. **
  71547. ** The P5 arguments are taken from register P2 and its
  71548. ** successors.
  71549. */
  71550. case OP_AggStep: {
  71551. int n;
  71552. int i;
  71553. Mem *pMem;
  71554. Mem *pRec;
  71555. Mem t;
  71556. sqlite3_context ctx;
  71557. sqlite3_value **apVal;
  71558. n = pOp->p5;
  71559. assert( n>=0 );
  71560. pRec = &aMem[pOp->p2];
  71561. apVal = p->apArg;
  71562. assert( apVal || n==0 );
  71563. for(i=0; i<n; i++, pRec++){
  71564. assert( memIsValid(pRec) );
  71565. apVal[i] = pRec;
  71566. memAboutToChange(p, pRec);
  71567. }
  71568. ctx.pFunc = pOp->p4.pFunc;
  71569. assert( pOp->p3>0 && pOp->p3<=(p->nMem-p->nCursor) );
  71570. ctx.pMem = pMem = &aMem[pOp->p3];
  71571. pMem->n++;
  71572. sqlite3VdbeMemInit(&t, db, MEM_Null);
  71573. ctx.pOut = &t;
  71574. ctx.isError = 0;
  71575. ctx.pVdbe = p;
  71576. ctx.iOp = (int)(pOp - aOp);
  71577. ctx.skipFlag = 0;
  71578. (ctx.pFunc->xStep)(&ctx, n, apVal); /* IMP: R-24505-23230 */
  71579. if( ctx.isError ){
  71580. sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3_value_text(&t));
  71581. rc = ctx.isError;
  71582. }
  71583. if( ctx.skipFlag ){
  71584. assert( pOp[-1].opcode==OP_CollSeq );
  71585. i = pOp[-1].p1;
  71586. if( i ) sqlite3VdbeMemSetInt64(&aMem[i], 1);
  71587. }
  71588. sqlite3VdbeMemRelease(&t);
  71589. break;
  71590. }
  71591. /* Opcode: AggFinal P1 P2 * P4 *
  71592. ** Synopsis: accum=r[P1] N=P2
  71593. **
  71594. ** Execute the finalizer function for an aggregate. P1 is
  71595. ** the memory location that is the accumulator for the aggregate.
  71596. **
  71597. ** P2 is the number of arguments that the step function takes and
  71598. ** P4 is a pointer to the FuncDef for this function. The P2
  71599. ** argument is not used by this opcode. It is only there to disambiguate
  71600. ** functions that can take varying numbers of arguments. The
  71601. ** P4 argument is only needed for the degenerate case where
  71602. ** the step function was not previously called.
  71603. */
  71604. case OP_AggFinal: {
  71605. Mem *pMem;
  71606. assert( pOp->p1>0 && pOp->p1<=(p->nMem-p->nCursor) );
  71607. pMem = &aMem[pOp->p1];
  71608. assert( (pMem->flags & ~(MEM_Null|MEM_Agg))==0 );
  71609. rc = sqlite3VdbeMemFinalize(pMem, pOp->p4.pFunc);
  71610. if( rc ){
  71611. sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3_value_text(pMem));
  71612. }
  71613. sqlite3VdbeChangeEncoding(pMem, encoding);
  71614. UPDATE_MAX_BLOBSIZE(pMem);
  71615. if( sqlite3VdbeMemTooBig(pMem) ){
  71616. goto too_big;
  71617. }
  71618. break;
  71619. }
  71620. #ifndef SQLITE_OMIT_WAL
  71621. /* Opcode: Checkpoint P1 P2 P3 * *
  71622. **
  71623. ** Checkpoint database P1. This is a no-op if P1 is not currently in
  71624. ** WAL mode. Parameter P2 is one of SQLITE_CHECKPOINT_PASSIVE, FULL,
  71625. ** RESTART, or TRUNCATE. Write 1 or 0 into mem[P3] if the checkpoint returns
  71626. ** SQLITE_BUSY or not, respectively. Write the number of pages in the
  71627. ** WAL after the checkpoint into mem[P3+1] and the number of pages
  71628. ** in the WAL that have been checkpointed after the checkpoint
  71629. ** completes into mem[P3+2]. However on an error, mem[P3+1] and
  71630. ** mem[P3+2] are initialized to -1.
  71631. */
  71632. case OP_Checkpoint: {
  71633. int i; /* Loop counter */
  71634. int aRes[3]; /* Results */
  71635. Mem *pMem; /* Write results here */
  71636. assert( p->readOnly==0 );
  71637. aRes[0] = 0;
  71638. aRes[1] = aRes[2] = -1;
  71639. assert( pOp->p2==SQLITE_CHECKPOINT_PASSIVE
  71640. || pOp->p2==SQLITE_CHECKPOINT_FULL
  71641. || pOp->p2==SQLITE_CHECKPOINT_RESTART
  71642. || pOp->p2==SQLITE_CHECKPOINT_TRUNCATE
  71643. );
  71644. rc = sqlite3Checkpoint(db, pOp->p1, pOp->p2, &aRes[1], &aRes[2]);
  71645. if( rc==SQLITE_BUSY ){
  71646. rc = SQLITE_OK;
  71647. aRes[0] = 1;
  71648. }
  71649. for(i=0, pMem = &aMem[pOp->p3]; i<3; i++, pMem++){
  71650. sqlite3VdbeMemSetInt64(pMem, (i64)aRes[i]);
  71651. }
  71652. break;
  71653. };
  71654. #endif
  71655. #ifndef SQLITE_OMIT_PRAGMA
  71656. /* Opcode: JournalMode P1 P2 P3 * *
  71657. **
  71658. ** Change the journal mode of database P1 to P3. P3 must be one of the
  71659. ** PAGER_JOURNALMODE_XXX values. If changing between the various rollback
  71660. ** modes (delete, truncate, persist, off and memory), this is a simple
  71661. ** operation. No IO is required.
  71662. **
  71663. ** If changing into or out of WAL mode the procedure is more complicated.
  71664. **
  71665. ** Write a string containing the final journal-mode to register P2.
  71666. */
  71667. case OP_JournalMode: { /* out2 */
  71668. Btree *pBt; /* Btree to change journal mode of */
  71669. Pager *pPager; /* Pager associated with pBt */
  71670. int eNew; /* New journal mode */
  71671. int eOld; /* The old journal mode */
  71672. #ifndef SQLITE_OMIT_WAL
  71673. const char *zFilename; /* Name of database file for pPager */
  71674. #endif
  71675. pOut = out2Prerelease(p, pOp);
  71676. eNew = pOp->p3;
  71677. assert( eNew==PAGER_JOURNALMODE_DELETE
  71678. || eNew==PAGER_JOURNALMODE_TRUNCATE
  71679. || eNew==PAGER_JOURNALMODE_PERSIST
  71680. || eNew==PAGER_JOURNALMODE_OFF
  71681. || eNew==PAGER_JOURNALMODE_MEMORY
  71682. || eNew==PAGER_JOURNALMODE_WAL
  71683. || eNew==PAGER_JOURNALMODE_QUERY
  71684. );
  71685. assert( pOp->p1>=0 && pOp->p1<db->nDb );
  71686. assert( p->readOnly==0 );
  71687. pBt = db->aDb[pOp->p1].pBt;
  71688. pPager = sqlite3BtreePager(pBt);
  71689. eOld = sqlite3PagerGetJournalMode(pPager);
  71690. if( eNew==PAGER_JOURNALMODE_QUERY ) eNew = eOld;
  71691. if( !sqlite3PagerOkToChangeJournalMode(pPager) ) eNew = eOld;
  71692. #ifndef SQLITE_OMIT_WAL
  71693. zFilename = sqlite3PagerFilename(pPager, 1);
  71694. /* Do not allow a transition to journal_mode=WAL for a database
  71695. ** in temporary storage or if the VFS does not support shared memory
  71696. */
  71697. if( eNew==PAGER_JOURNALMODE_WAL
  71698. && (sqlite3Strlen30(zFilename)==0 /* Temp file */
  71699. || !sqlite3PagerWalSupported(pPager)) /* No shared-memory support */
  71700. ){
  71701. eNew = eOld;
  71702. }
  71703. if( (eNew!=eOld)
  71704. && (eOld==PAGER_JOURNALMODE_WAL || eNew==PAGER_JOURNALMODE_WAL)
  71705. ){
  71706. if( !db->autoCommit || db->nVdbeRead>1 ){
  71707. rc = SQLITE_ERROR;
  71708. sqlite3SetString(&p->zErrMsg, db,
  71709. "cannot change %s wal mode from within a transaction",
  71710. (eNew==PAGER_JOURNALMODE_WAL ? "into" : "out of")
  71711. );
  71712. break;
  71713. }else{
  71714. if( eOld==PAGER_JOURNALMODE_WAL ){
  71715. /* If leaving WAL mode, close the log file. If successful, the call
  71716. ** to PagerCloseWal() checkpoints and deletes the write-ahead-log
  71717. ** file. An EXCLUSIVE lock may still be held on the database file
  71718. ** after a successful return.
  71719. */
  71720. rc = sqlite3PagerCloseWal(pPager);
  71721. if( rc==SQLITE_OK ){
  71722. sqlite3PagerSetJournalMode(pPager, eNew);
  71723. }
  71724. }else if( eOld==PAGER_JOURNALMODE_MEMORY ){
  71725. /* Cannot transition directly from MEMORY to WAL. Use mode OFF
  71726. ** as an intermediate */
  71727. sqlite3PagerSetJournalMode(pPager, PAGER_JOURNALMODE_OFF);
  71728. }
  71729. /* Open a transaction on the database file. Regardless of the journal
  71730. ** mode, this transaction always uses a rollback journal.
  71731. */
  71732. assert( sqlite3BtreeIsInTrans(pBt)==0 );
  71733. if( rc==SQLITE_OK ){
  71734. rc = sqlite3BtreeSetVersion(pBt, (eNew==PAGER_JOURNALMODE_WAL ? 2 : 1));
  71735. }
  71736. }
  71737. }
  71738. #endif /* ifndef SQLITE_OMIT_WAL */
  71739. if( rc ){
  71740. eNew = eOld;
  71741. }
  71742. eNew = sqlite3PagerSetJournalMode(pPager, eNew);
  71743. pOut->flags = MEM_Str|MEM_Static|MEM_Term;
  71744. pOut->z = (char *)sqlite3JournalModename(eNew);
  71745. pOut->n = sqlite3Strlen30(pOut->z);
  71746. pOut->enc = SQLITE_UTF8;
  71747. sqlite3VdbeChangeEncoding(pOut, encoding);
  71748. break;
  71749. };
  71750. #endif /* SQLITE_OMIT_PRAGMA */
  71751. #if !defined(SQLITE_OMIT_VACUUM) && !defined(SQLITE_OMIT_ATTACH)
  71752. /* Opcode: Vacuum * * * * *
  71753. **
  71754. ** Vacuum the entire database. This opcode will cause other virtual
  71755. ** machines to be created and run. It may not be called from within
  71756. ** a transaction.
  71757. */
  71758. case OP_Vacuum: {
  71759. assert( p->readOnly==0 );
  71760. rc = sqlite3RunVacuum(&p->zErrMsg, db);
  71761. break;
  71762. }
  71763. #endif
  71764. #if !defined(SQLITE_OMIT_AUTOVACUUM)
  71765. /* Opcode: IncrVacuum P1 P2 * * *
  71766. **
  71767. ** Perform a single step of the incremental vacuum procedure on
  71768. ** the P1 database. If the vacuum has finished, jump to instruction
  71769. ** P2. Otherwise, fall through to the next instruction.
  71770. */
  71771. case OP_IncrVacuum: { /* jump */
  71772. Btree *pBt;
  71773. assert( pOp->p1>=0 && pOp->p1<db->nDb );
  71774. assert( DbMaskTest(p->btreeMask, pOp->p1) );
  71775. assert( p->readOnly==0 );
  71776. pBt = db->aDb[pOp->p1].pBt;
  71777. rc = sqlite3BtreeIncrVacuum(pBt);
  71778. VdbeBranchTaken(rc==SQLITE_DONE,2);
  71779. if( rc==SQLITE_DONE ){
  71780. rc = SQLITE_OK;
  71781. goto jump_to_p2;
  71782. }
  71783. break;
  71784. }
  71785. #endif
  71786. /* Opcode: Expire P1 * * * *
  71787. **
  71788. ** Cause precompiled statements to expire. When an expired statement
  71789. ** is executed using sqlite3_step() it will either automatically
  71790. ** reprepare itself (if it was originally created using sqlite3_prepare_v2())
  71791. ** or it will fail with SQLITE_SCHEMA.
  71792. **
  71793. ** If P1 is 0, then all SQL statements become expired. If P1 is non-zero,
  71794. ** then only the currently executing statement is expired.
  71795. */
  71796. case OP_Expire: {
  71797. if( !pOp->p1 ){
  71798. sqlite3ExpirePreparedStatements(db);
  71799. }else{
  71800. p->expired = 1;
  71801. }
  71802. break;
  71803. }
  71804. #ifndef SQLITE_OMIT_SHARED_CACHE
  71805. /* Opcode: TableLock P1 P2 P3 P4 *
  71806. ** Synopsis: iDb=P1 root=P2 write=P3
  71807. **
  71808. ** Obtain a lock on a particular table. This instruction is only used when
  71809. ** the shared-cache feature is enabled.
  71810. **
  71811. ** P1 is the index of the database in sqlite3.aDb[] of the database
  71812. ** on which the lock is acquired. A readlock is obtained if P3==0 or
  71813. ** a write lock if P3==1.
  71814. **
  71815. ** P2 contains the root-page of the table to lock.
  71816. **
  71817. ** P4 contains a pointer to the name of the table being locked. This is only
  71818. ** used to generate an error message if the lock cannot be obtained.
  71819. */
  71820. case OP_TableLock: {
  71821. u8 isWriteLock = (u8)pOp->p3;
  71822. if( isWriteLock || 0==(db->flags&SQLITE_ReadUncommitted) ){
  71823. int p1 = pOp->p1;
  71824. assert( p1>=0 && p1<db->nDb );
  71825. assert( DbMaskTest(p->btreeMask, p1) );
  71826. assert( isWriteLock==0 || isWriteLock==1 );
  71827. rc = sqlite3BtreeLockTable(db->aDb[p1].pBt, pOp->p2, isWriteLock);
  71828. if( (rc&0xFF)==SQLITE_LOCKED ){
  71829. const char *z = pOp->p4.z;
  71830. sqlite3SetString(&p->zErrMsg, db, "database table is locked: %s", z);
  71831. }
  71832. }
  71833. break;
  71834. }
  71835. #endif /* SQLITE_OMIT_SHARED_CACHE */
  71836. #ifndef SQLITE_OMIT_VIRTUALTABLE
  71837. /* Opcode: VBegin * * * P4 *
  71838. **
  71839. ** P4 may be a pointer to an sqlite3_vtab structure. If so, call the
  71840. ** xBegin method for that table.
  71841. **
  71842. ** Also, whether or not P4 is set, check that this is not being called from
  71843. ** within a callback to a virtual table xSync() method. If it is, the error
  71844. ** code will be set to SQLITE_LOCKED.
  71845. */
  71846. case OP_VBegin: {
  71847. VTable *pVTab;
  71848. pVTab = pOp->p4.pVtab;
  71849. rc = sqlite3VtabBegin(db, pVTab);
  71850. if( pVTab ) sqlite3VtabImportErrmsg(p, pVTab->pVtab);
  71851. break;
  71852. }
  71853. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  71854. #ifndef SQLITE_OMIT_VIRTUALTABLE
  71855. /* Opcode: VCreate P1 P2 * * *
  71856. **
  71857. ** P2 is a register that holds the name of a virtual table in database
  71858. ** P1. Call the xCreate method for that table.
  71859. */
  71860. case OP_VCreate: {
  71861. Mem sMem; /* For storing the record being decoded */
  71862. const char *zTab; /* Name of the virtual table */
  71863. memset(&sMem, 0, sizeof(sMem));
  71864. sMem.db = db;
  71865. /* Because P2 is always a static string, it is impossible for the
  71866. ** sqlite3VdbeMemCopy() to fail */
  71867. assert( (aMem[pOp->p2].flags & MEM_Str)!=0 );
  71868. assert( (aMem[pOp->p2].flags & MEM_Static)!=0 );
  71869. rc = sqlite3VdbeMemCopy(&sMem, &aMem[pOp->p2]);
  71870. assert( rc==SQLITE_OK );
  71871. zTab = (const char*)sqlite3_value_text(&sMem);
  71872. assert( zTab || db->mallocFailed );
  71873. if( zTab ){
  71874. rc = sqlite3VtabCallCreate(db, pOp->p1, zTab, &p->zErrMsg);
  71875. }
  71876. sqlite3VdbeMemRelease(&sMem);
  71877. break;
  71878. }
  71879. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  71880. #ifndef SQLITE_OMIT_VIRTUALTABLE
  71881. /* Opcode: VDestroy P1 * * P4 *
  71882. **
  71883. ** P4 is the name of a virtual table in database P1. Call the xDestroy method
  71884. ** of that table.
  71885. */
  71886. case OP_VDestroy: {
  71887. db->nVDestroy++;
  71888. rc = sqlite3VtabCallDestroy(db, pOp->p1, pOp->p4.z);
  71889. db->nVDestroy--;
  71890. break;
  71891. }
  71892. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  71893. #ifndef SQLITE_OMIT_VIRTUALTABLE
  71894. /* Opcode: VOpen P1 * * P4 *
  71895. **
  71896. ** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
  71897. ** P1 is a cursor number. This opcode opens a cursor to the virtual
  71898. ** table and stores that cursor in P1.
  71899. */
  71900. case OP_VOpen: {
  71901. VdbeCursor *pCur;
  71902. sqlite3_vtab_cursor *pVtabCursor;
  71903. sqlite3_vtab *pVtab;
  71904. const sqlite3_module *pModule;
  71905. assert( p->bIsReader );
  71906. pCur = 0;
  71907. pVtabCursor = 0;
  71908. pVtab = pOp->p4.pVtab->pVtab;
  71909. if( pVtab==0 || NEVER(pVtab->pModule==0) ){
  71910. rc = SQLITE_LOCKED;
  71911. break;
  71912. }
  71913. pModule = pVtab->pModule;
  71914. rc = pModule->xOpen(pVtab, &pVtabCursor);
  71915. sqlite3VtabImportErrmsg(p, pVtab);
  71916. if( SQLITE_OK==rc ){
  71917. /* Initialize sqlite3_vtab_cursor base class */
  71918. pVtabCursor->pVtab = pVtab;
  71919. /* Initialize vdbe cursor object */
  71920. pCur = allocateCursor(p, pOp->p1, 0, -1, 0);
  71921. if( pCur ){
  71922. pCur->pVtabCursor = pVtabCursor;
  71923. pVtab->nRef++;
  71924. }else{
  71925. assert( db->mallocFailed );
  71926. pModule->xClose(pVtabCursor);
  71927. goto no_mem;
  71928. }
  71929. }
  71930. break;
  71931. }
  71932. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  71933. #ifndef SQLITE_OMIT_VIRTUALTABLE
  71934. /* Opcode: VFilter P1 P2 P3 P4 *
  71935. ** Synopsis: iplan=r[P3] zplan='P4'
  71936. **
  71937. ** P1 is a cursor opened using VOpen. P2 is an address to jump to if
  71938. ** the filtered result set is empty.
  71939. **
  71940. ** P4 is either NULL or a string that was generated by the xBestIndex
  71941. ** method of the module. The interpretation of the P4 string is left
  71942. ** to the module implementation.
  71943. **
  71944. ** This opcode invokes the xFilter method on the virtual table specified
  71945. ** by P1. The integer query plan parameter to xFilter is stored in register
  71946. ** P3. Register P3+1 stores the argc parameter to be passed to the
  71947. ** xFilter method. Registers P3+2..P3+1+argc are the argc
  71948. ** additional parameters which are passed to
  71949. ** xFilter as argv. Register P3+2 becomes argv[0] when passed to xFilter.
  71950. **
  71951. ** A jump is made to P2 if the result set after filtering would be empty.
  71952. */
  71953. case OP_VFilter: { /* jump */
  71954. int nArg;
  71955. int iQuery;
  71956. const sqlite3_module *pModule;
  71957. Mem *pQuery;
  71958. Mem *pArgc;
  71959. sqlite3_vtab_cursor *pVtabCursor;
  71960. sqlite3_vtab *pVtab;
  71961. VdbeCursor *pCur;
  71962. int res;
  71963. int i;
  71964. Mem **apArg;
  71965. pQuery = &aMem[pOp->p3];
  71966. pArgc = &pQuery[1];
  71967. pCur = p->apCsr[pOp->p1];
  71968. assert( memIsValid(pQuery) );
  71969. REGISTER_TRACE(pOp->p3, pQuery);
  71970. assert( pCur->pVtabCursor );
  71971. pVtabCursor = pCur->pVtabCursor;
  71972. pVtab = pVtabCursor->pVtab;
  71973. pModule = pVtab->pModule;
  71974. /* Grab the index number and argc parameters */
  71975. assert( (pQuery->flags&MEM_Int)!=0 && pArgc->flags==MEM_Int );
  71976. nArg = (int)pArgc->u.i;
  71977. iQuery = (int)pQuery->u.i;
  71978. /* Invoke the xFilter method */
  71979. res = 0;
  71980. apArg = p->apArg;
  71981. for(i = 0; i<nArg; i++){
  71982. apArg[i] = &pArgc[i+1];
  71983. }
  71984. rc = pModule->xFilter(pVtabCursor, iQuery, pOp->p4.z, nArg, apArg);
  71985. sqlite3VtabImportErrmsg(p, pVtab);
  71986. if( rc==SQLITE_OK ){
  71987. res = pModule->xEof(pVtabCursor);
  71988. }
  71989. pCur->nullRow = 0;
  71990. VdbeBranchTaken(res!=0,2);
  71991. if( res ) goto jump_to_p2;
  71992. break;
  71993. }
  71994. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  71995. #ifndef SQLITE_OMIT_VIRTUALTABLE
  71996. /* Opcode: VColumn P1 P2 P3 * *
  71997. ** Synopsis: r[P3]=vcolumn(P2)
  71998. **
  71999. ** Store the value of the P2-th column of
  72000. ** the row of the virtual-table that the
  72001. ** P1 cursor is pointing to into register P3.
  72002. */
  72003. case OP_VColumn: {
  72004. sqlite3_vtab *pVtab;
  72005. const sqlite3_module *pModule;
  72006. Mem *pDest;
  72007. sqlite3_context sContext;
  72008. VdbeCursor *pCur = p->apCsr[pOp->p1];
  72009. assert( pCur->pVtabCursor );
  72010. assert( pOp->p3>0 && pOp->p3<=(p->nMem-p->nCursor) );
  72011. pDest = &aMem[pOp->p3];
  72012. memAboutToChange(p, pDest);
  72013. if( pCur->nullRow ){
  72014. sqlite3VdbeMemSetNull(pDest);
  72015. break;
  72016. }
  72017. pVtab = pCur->pVtabCursor->pVtab;
  72018. pModule = pVtab->pModule;
  72019. assert( pModule->xColumn );
  72020. memset(&sContext, 0, sizeof(sContext));
  72021. sContext.pOut = pDest;
  72022. MemSetTypeFlag(pDest, MEM_Null);
  72023. rc = pModule->xColumn(pCur->pVtabCursor, &sContext, pOp->p2);
  72024. sqlite3VtabImportErrmsg(p, pVtab);
  72025. if( sContext.isError ){
  72026. rc = sContext.isError;
  72027. }
  72028. sqlite3VdbeChangeEncoding(pDest, encoding);
  72029. REGISTER_TRACE(pOp->p3, pDest);
  72030. UPDATE_MAX_BLOBSIZE(pDest);
  72031. if( sqlite3VdbeMemTooBig(pDest) ){
  72032. goto too_big;
  72033. }
  72034. break;
  72035. }
  72036. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  72037. #ifndef SQLITE_OMIT_VIRTUALTABLE
  72038. /* Opcode: VNext P1 P2 * * *
  72039. **
  72040. ** Advance virtual table P1 to the next row in its result set and
  72041. ** jump to instruction P2. Or, if the virtual table has reached
  72042. ** the end of its result set, then fall through to the next instruction.
  72043. */
  72044. case OP_VNext: { /* jump */
  72045. sqlite3_vtab *pVtab;
  72046. const sqlite3_module *pModule;
  72047. int res;
  72048. VdbeCursor *pCur;
  72049. res = 0;
  72050. pCur = p->apCsr[pOp->p1];
  72051. assert( pCur->pVtabCursor );
  72052. if( pCur->nullRow ){
  72053. break;
  72054. }
  72055. pVtab = pCur->pVtabCursor->pVtab;
  72056. pModule = pVtab->pModule;
  72057. assert( pModule->xNext );
  72058. /* Invoke the xNext() method of the module. There is no way for the
  72059. ** underlying implementation to return an error if one occurs during
  72060. ** xNext(). Instead, if an error occurs, true is returned (indicating that
  72061. ** data is available) and the error code returned when xColumn or
  72062. ** some other method is next invoked on the save virtual table cursor.
  72063. */
  72064. rc = pModule->xNext(pCur->pVtabCursor);
  72065. sqlite3VtabImportErrmsg(p, pVtab);
  72066. if( rc==SQLITE_OK ){
  72067. res = pModule->xEof(pCur->pVtabCursor);
  72068. }
  72069. VdbeBranchTaken(!res,2);
  72070. if( !res ){
  72071. /* If there is data, jump to P2 */
  72072. goto jump_to_p2_and_check_for_interrupt;
  72073. }
  72074. goto check_for_interrupt;
  72075. }
  72076. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  72077. #ifndef SQLITE_OMIT_VIRTUALTABLE
  72078. /* Opcode: VRename P1 * * P4 *
  72079. **
  72080. ** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
  72081. ** This opcode invokes the corresponding xRename method. The value
  72082. ** in register P1 is passed as the zName argument to the xRename method.
  72083. */
  72084. case OP_VRename: {
  72085. sqlite3_vtab *pVtab;
  72086. Mem *pName;
  72087. pVtab = pOp->p4.pVtab->pVtab;
  72088. pName = &aMem[pOp->p1];
  72089. assert( pVtab->pModule->xRename );
  72090. assert( memIsValid(pName) );
  72091. assert( p->readOnly==0 );
  72092. REGISTER_TRACE(pOp->p1, pName);
  72093. assert( pName->flags & MEM_Str );
  72094. testcase( pName->enc==SQLITE_UTF8 );
  72095. testcase( pName->enc==SQLITE_UTF16BE );
  72096. testcase( pName->enc==SQLITE_UTF16LE );
  72097. rc = sqlite3VdbeChangeEncoding(pName, SQLITE_UTF8);
  72098. if( rc==SQLITE_OK ){
  72099. rc = pVtab->pModule->xRename(pVtab, pName->z);
  72100. sqlite3VtabImportErrmsg(p, pVtab);
  72101. p->expired = 0;
  72102. }
  72103. break;
  72104. }
  72105. #endif
  72106. #ifndef SQLITE_OMIT_VIRTUALTABLE
  72107. /* Opcode: VUpdate P1 P2 P3 P4 P5
  72108. ** Synopsis: data=r[P3@P2]
  72109. **
  72110. ** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
  72111. ** This opcode invokes the corresponding xUpdate method. P2 values
  72112. ** are contiguous memory cells starting at P3 to pass to the xUpdate
  72113. ** invocation. The value in register (P3+P2-1) corresponds to the
  72114. ** p2th element of the argv array passed to xUpdate.
  72115. **
  72116. ** The xUpdate method will do a DELETE or an INSERT or both.
  72117. ** The argv[0] element (which corresponds to memory cell P3)
  72118. ** is the rowid of a row to delete. If argv[0] is NULL then no
  72119. ** deletion occurs. The argv[1] element is the rowid of the new
  72120. ** row. This can be NULL to have the virtual table select the new
  72121. ** rowid for itself. The subsequent elements in the array are
  72122. ** the values of columns in the new row.
  72123. **
  72124. ** If P2==1 then no insert is performed. argv[0] is the rowid of
  72125. ** a row to delete.
  72126. **
  72127. ** P1 is a boolean flag. If it is set to true and the xUpdate call
  72128. ** is successful, then the value returned by sqlite3_last_insert_rowid()
  72129. ** is set to the value of the rowid for the row just inserted.
  72130. **
  72131. ** P5 is the error actions (OE_Replace, OE_Fail, OE_Ignore, etc) to
  72132. ** apply in the case of a constraint failure on an insert or update.
  72133. */
  72134. case OP_VUpdate: {
  72135. sqlite3_vtab *pVtab;
  72136. const sqlite3_module *pModule;
  72137. int nArg;
  72138. int i;
  72139. sqlite_int64 rowid;
  72140. Mem **apArg;
  72141. Mem *pX;
  72142. assert( pOp->p2==1 || pOp->p5==OE_Fail || pOp->p5==OE_Rollback
  72143. || pOp->p5==OE_Abort || pOp->p5==OE_Ignore || pOp->p5==OE_Replace
  72144. );
  72145. assert( p->readOnly==0 );
  72146. pVtab = pOp->p4.pVtab->pVtab;
  72147. if( pVtab==0 || NEVER(pVtab->pModule==0) ){
  72148. rc = SQLITE_LOCKED;
  72149. break;
  72150. }
  72151. pModule = pVtab->pModule;
  72152. nArg = pOp->p2;
  72153. assert( pOp->p4type==P4_VTAB );
  72154. if( ALWAYS(pModule->xUpdate) ){
  72155. u8 vtabOnConflict = db->vtabOnConflict;
  72156. apArg = p->apArg;
  72157. pX = &aMem[pOp->p3];
  72158. for(i=0; i<nArg; i++){
  72159. assert( memIsValid(pX) );
  72160. memAboutToChange(p, pX);
  72161. apArg[i] = pX;
  72162. pX++;
  72163. }
  72164. db->vtabOnConflict = pOp->p5;
  72165. rc = pModule->xUpdate(pVtab, nArg, apArg, &rowid);
  72166. db->vtabOnConflict = vtabOnConflict;
  72167. sqlite3VtabImportErrmsg(p, pVtab);
  72168. if( rc==SQLITE_OK && pOp->p1 ){
  72169. assert( nArg>1 && apArg[0] && (apArg[0]->flags&MEM_Null) );
  72170. db->lastRowid = lastRowid = rowid;
  72171. }
  72172. if( (rc&0xff)==SQLITE_CONSTRAINT && pOp->p4.pVtab->bConstraint ){
  72173. if( pOp->p5==OE_Ignore ){
  72174. rc = SQLITE_OK;
  72175. }else{
  72176. p->errorAction = ((pOp->p5==OE_Replace) ? OE_Abort : pOp->p5);
  72177. }
  72178. }else{
  72179. p->nChange++;
  72180. }
  72181. }
  72182. break;
  72183. }
  72184. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  72185. #ifndef SQLITE_OMIT_PAGER_PRAGMAS
  72186. /* Opcode: Pagecount P1 P2 * * *
  72187. **
  72188. ** Write the current number of pages in database P1 to memory cell P2.
  72189. */
  72190. case OP_Pagecount: { /* out2 */
  72191. pOut = out2Prerelease(p, pOp);
  72192. pOut->u.i = sqlite3BtreeLastPage(db->aDb[pOp->p1].pBt);
  72193. break;
  72194. }
  72195. #endif
  72196. #ifndef SQLITE_OMIT_PAGER_PRAGMAS
  72197. /* Opcode: MaxPgcnt P1 P2 P3 * *
  72198. **
  72199. ** Try to set the maximum page count for database P1 to the value in P3.
  72200. ** Do not let the maximum page count fall below the current page count and
  72201. ** do not change the maximum page count value if P3==0.
  72202. **
  72203. ** Store the maximum page count after the change in register P2.
  72204. */
  72205. case OP_MaxPgcnt: { /* out2 */
  72206. unsigned int newMax;
  72207. Btree *pBt;
  72208. pOut = out2Prerelease(p, pOp);
  72209. pBt = db->aDb[pOp->p1].pBt;
  72210. newMax = 0;
  72211. if( pOp->p3 ){
  72212. newMax = sqlite3BtreeLastPage(pBt);
  72213. if( newMax < (unsigned)pOp->p3 ) newMax = (unsigned)pOp->p3;
  72214. }
  72215. pOut->u.i = sqlite3BtreeMaxPageCount(pBt, newMax);
  72216. break;
  72217. }
  72218. #endif
  72219. /* Opcode: Init * P2 * P4 *
  72220. ** Synopsis: Start at P2
  72221. **
  72222. ** Programs contain a single instance of this opcode as the very first
  72223. ** opcode.
  72224. **
  72225. ** If tracing is enabled (by the sqlite3_trace()) interface, then
  72226. ** the UTF-8 string contained in P4 is emitted on the trace callback.
  72227. ** Or if P4 is blank, use the string returned by sqlite3_sql().
  72228. **
  72229. ** If P2 is not zero, jump to instruction P2.
  72230. */
  72231. case OP_Init: { /* jump */
  72232. char *zTrace;
  72233. char *z;
  72234. #ifndef SQLITE_OMIT_TRACE
  72235. if( db->xTrace
  72236. && !p->doingRerun
  72237. && (zTrace = (pOp->p4.z ? pOp->p4.z : p->zSql))!=0
  72238. ){
  72239. z = sqlite3VdbeExpandSql(p, zTrace);
  72240. db->xTrace(db->pTraceArg, z);
  72241. sqlite3DbFree(db, z);
  72242. }
  72243. #ifdef SQLITE_USE_FCNTL_TRACE
  72244. zTrace = (pOp->p4.z ? pOp->p4.z : p->zSql);
  72245. if( zTrace ){
  72246. int i;
  72247. for(i=0; i<db->nDb; i++){
  72248. if( DbMaskTest(p->btreeMask, i)==0 ) continue;
  72249. sqlite3_file_control(db, db->aDb[i].zName, SQLITE_FCNTL_TRACE, zTrace);
  72250. }
  72251. }
  72252. #endif /* SQLITE_USE_FCNTL_TRACE */
  72253. #ifdef SQLITE_DEBUG
  72254. if( (db->flags & SQLITE_SqlTrace)!=0
  72255. && (zTrace = (pOp->p4.z ? pOp->p4.z : p->zSql))!=0
  72256. ){
  72257. sqlite3DebugPrintf("SQL-trace: %s\n", zTrace);
  72258. }
  72259. #endif /* SQLITE_DEBUG */
  72260. #endif /* SQLITE_OMIT_TRACE */
  72261. if( pOp->p2 ) goto jump_to_p2;
  72262. break;
  72263. }
  72264. /* Opcode: Noop * * * * *
  72265. **
  72266. ** Do nothing. This instruction is often useful as a jump
  72267. ** destination.
  72268. */
  72269. /*
  72270. ** The magic Explain opcode are only inserted when explain==2 (which
  72271. ** is to say when the EXPLAIN QUERY PLAN syntax is used.)
  72272. ** This opcode records information from the optimizer. It is the
  72273. ** the same as a no-op. This opcodesnever appears in a real VM program.
  72274. */
  72275. default: { /* This is really OP_Noop and OP_Explain */
  72276. assert( pOp->opcode==OP_Noop || pOp->opcode==OP_Explain );
  72277. break;
  72278. }
  72279. /*****************************************************************************
  72280. ** The cases of the switch statement above this line should all be indented
  72281. ** by 6 spaces. But the left-most 6 spaces have been removed to improve the
  72282. ** readability. From this point on down, the normal indentation rules are
  72283. ** restored.
  72284. *****************************************************************************/
  72285. }
  72286. #ifdef VDBE_PROFILE
  72287. {
  72288. u64 endTime = sqlite3Hwtime();
  72289. if( endTime>start ) pOrigOp->cycles += endTime - start;
  72290. pOrigOp->cnt++;
  72291. }
  72292. #endif
  72293. /* The following code adds nothing to the actual functionality
  72294. ** of the program. It is only here for testing and debugging.
  72295. ** On the other hand, it does burn CPU cycles every time through
  72296. ** the evaluator loop. So we can leave it out when NDEBUG is defined.
  72297. */
  72298. #ifndef NDEBUG
  72299. assert( pOp>=&aOp[-1] && pOp<&aOp[p->nOp-1] );
  72300. #ifdef SQLITE_DEBUG
  72301. if( db->flags & SQLITE_VdbeTrace ){
  72302. if( rc!=0 ) printf("rc=%d\n",rc);
  72303. if( pOrigOp->opflags & (OPFLG_OUT2) ){
  72304. registerTrace(pOrigOp->p2, &aMem[pOrigOp->p2]);
  72305. }
  72306. if( pOrigOp->opflags & OPFLG_OUT3 ){
  72307. registerTrace(pOrigOp->p3, &aMem[pOrigOp->p3]);
  72308. }
  72309. }
  72310. #endif /* SQLITE_DEBUG */
  72311. #endif /* NDEBUG */
  72312. } /* The end of the for(;;) loop the loops through opcodes */
  72313. /* If we reach this point, it means that execution is finished with
  72314. ** an error of some kind.
  72315. */
  72316. vdbe_error_halt:
  72317. assert( rc );
  72318. p->rc = rc;
  72319. testcase( sqlite3GlobalConfig.xLog!=0 );
  72320. sqlite3_log(rc, "statement aborts at %d: [%s] %s",
  72321. (int)(pOp - aOp), p->zSql, p->zErrMsg);
  72322. sqlite3VdbeHalt(p);
  72323. if( rc==SQLITE_IOERR_NOMEM ) db->mallocFailed = 1;
  72324. rc = SQLITE_ERROR;
  72325. if( resetSchemaOnFault>0 ){
  72326. sqlite3ResetOneSchema(db, resetSchemaOnFault-1);
  72327. }
  72328. /* This is the only way out of this procedure. We have to
  72329. ** release the mutexes on btrees that were acquired at the
  72330. ** top. */
  72331. vdbe_return:
  72332. db->lastRowid = lastRowid;
  72333. testcase( nVmStep>0 );
  72334. p->aCounter[SQLITE_STMTSTATUS_VM_STEP] += (int)nVmStep;
  72335. sqlite3VdbeLeave(p);
  72336. return rc;
  72337. /* Jump to here if a string or blob larger than SQLITE_MAX_LENGTH
  72338. ** is encountered.
  72339. */
  72340. too_big:
  72341. sqlite3SetString(&p->zErrMsg, db, "string or blob too big");
  72342. rc = SQLITE_TOOBIG;
  72343. goto vdbe_error_halt;
  72344. /* Jump to here if a malloc() fails.
  72345. */
  72346. no_mem:
  72347. db->mallocFailed = 1;
  72348. sqlite3SetString(&p->zErrMsg, db, "out of memory");
  72349. rc = SQLITE_NOMEM;
  72350. goto vdbe_error_halt;
  72351. /* Jump to here for any other kind of fatal error. The "rc" variable
  72352. ** should hold the error number.
  72353. */
  72354. abort_due_to_error:
  72355. assert( p->zErrMsg==0 );
  72356. if( db->mallocFailed ) rc = SQLITE_NOMEM;
  72357. if( rc!=SQLITE_IOERR_NOMEM ){
  72358. sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3ErrStr(rc));
  72359. }
  72360. goto vdbe_error_halt;
  72361. /* Jump to here if the sqlite3_interrupt() API sets the interrupt
  72362. ** flag.
  72363. */
  72364. abort_due_to_interrupt:
  72365. assert( db->u1.isInterrupted );
  72366. rc = SQLITE_INTERRUPT;
  72367. p->rc = rc;
  72368. sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3ErrStr(rc));
  72369. goto vdbe_error_halt;
  72370. }
  72371. /************** End of vdbe.c ************************************************/
  72372. /************** Begin file vdbeblob.c ****************************************/
  72373. /*
  72374. ** 2007 May 1
  72375. **
  72376. ** The author disclaims copyright to this source code. In place of
  72377. ** a legal notice, here is a blessing:
  72378. **
  72379. ** May you do good and not evil.
  72380. ** May you find forgiveness for yourself and forgive others.
  72381. ** May you share freely, never taking more than you give.
  72382. **
  72383. *************************************************************************
  72384. **
  72385. ** This file contains code used to implement incremental BLOB I/O.
  72386. */
  72387. #ifndef SQLITE_OMIT_INCRBLOB
  72388. /*
  72389. ** Valid sqlite3_blob* handles point to Incrblob structures.
  72390. */
  72391. typedef struct Incrblob Incrblob;
  72392. struct Incrblob {
  72393. int flags; /* Copy of "flags" passed to sqlite3_blob_open() */
  72394. int nByte; /* Size of open blob, in bytes */
  72395. int iOffset; /* Byte offset of blob in cursor data */
  72396. int iCol; /* Table column this handle is open on */
  72397. BtCursor *pCsr; /* Cursor pointing at blob row */
  72398. sqlite3_stmt *pStmt; /* Statement holding cursor open */
  72399. sqlite3 *db; /* The associated database */
  72400. };
  72401. /*
  72402. ** This function is used by both blob_open() and blob_reopen(). It seeks
  72403. ** the b-tree cursor associated with blob handle p to point to row iRow.
  72404. ** If successful, SQLITE_OK is returned and subsequent calls to
  72405. ** sqlite3_blob_read() or sqlite3_blob_write() access the specified row.
  72406. **
  72407. ** If an error occurs, or if the specified row does not exist or does not
  72408. ** contain a value of type TEXT or BLOB in the column nominated when the
  72409. ** blob handle was opened, then an error code is returned and *pzErr may
  72410. ** be set to point to a buffer containing an error message. It is the
  72411. ** responsibility of the caller to free the error message buffer using
  72412. ** sqlite3DbFree().
  72413. **
  72414. ** If an error does occur, then the b-tree cursor is closed. All subsequent
  72415. ** calls to sqlite3_blob_read(), blob_write() or blob_reopen() will
  72416. ** immediately return SQLITE_ABORT.
  72417. */
  72418. static int blobSeekToRow(Incrblob *p, sqlite3_int64 iRow, char **pzErr){
  72419. int rc; /* Error code */
  72420. char *zErr = 0; /* Error message */
  72421. Vdbe *v = (Vdbe *)p->pStmt;
  72422. /* Set the value of the SQL statements only variable to integer iRow.
  72423. ** This is done directly instead of using sqlite3_bind_int64() to avoid
  72424. ** triggering asserts related to mutexes.
  72425. */
  72426. assert( v->aVar[0].flags&MEM_Int );
  72427. v->aVar[0].u.i = iRow;
  72428. rc = sqlite3_step(p->pStmt);
  72429. if( rc==SQLITE_ROW ){
  72430. VdbeCursor *pC = v->apCsr[0];
  72431. u32 type = pC->aType[p->iCol];
  72432. if( type<12 ){
  72433. zErr = sqlite3MPrintf(p->db, "cannot open value of type %s",
  72434. type==0?"null": type==7?"real": "integer"
  72435. );
  72436. rc = SQLITE_ERROR;
  72437. sqlite3_finalize(p->pStmt);
  72438. p->pStmt = 0;
  72439. }else{
  72440. p->iOffset = pC->aType[p->iCol + pC->nField];
  72441. p->nByte = sqlite3VdbeSerialTypeLen(type);
  72442. p->pCsr = pC->pCursor;
  72443. sqlite3BtreeIncrblobCursor(p->pCsr);
  72444. }
  72445. }
  72446. if( rc==SQLITE_ROW ){
  72447. rc = SQLITE_OK;
  72448. }else if( p->pStmt ){
  72449. rc = sqlite3_finalize(p->pStmt);
  72450. p->pStmt = 0;
  72451. if( rc==SQLITE_OK ){
  72452. zErr = sqlite3MPrintf(p->db, "no such rowid: %lld", iRow);
  72453. rc = SQLITE_ERROR;
  72454. }else{
  72455. zErr = sqlite3MPrintf(p->db, "%s", sqlite3_errmsg(p->db));
  72456. }
  72457. }
  72458. assert( rc!=SQLITE_OK || zErr==0 );
  72459. assert( rc!=SQLITE_ROW && rc!=SQLITE_DONE );
  72460. *pzErr = zErr;
  72461. return rc;
  72462. }
  72463. /*
  72464. ** Open a blob handle.
  72465. */
  72466. SQLITE_API int SQLITE_STDCALL sqlite3_blob_open(
  72467. sqlite3* db, /* The database connection */
  72468. const char *zDb, /* The attached database containing the blob */
  72469. const char *zTable, /* The table containing the blob */
  72470. const char *zColumn, /* The column containing the blob */
  72471. sqlite_int64 iRow, /* The row containing the glob */
  72472. int flags, /* True -> read/write access, false -> read-only */
  72473. sqlite3_blob **ppBlob /* Handle for accessing the blob returned here */
  72474. ){
  72475. int nAttempt = 0;
  72476. int iCol; /* Index of zColumn in row-record */
  72477. /* This VDBE program seeks a btree cursor to the identified
  72478. ** db/table/row entry. The reason for using a vdbe program instead
  72479. ** of writing code to use the b-tree layer directly is that the
  72480. ** vdbe program will take advantage of the various transaction,
  72481. ** locking and error handling infrastructure built into the vdbe.
  72482. **
  72483. ** After seeking the cursor, the vdbe executes an OP_ResultRow.
  72484. ** Code external to the Vdbe then "borrows" the b-tree cursor and
  72485. ** uses it to implement the blob_read(), blob_write() and
  72486. ** blob_bytes() functions.
  72487. **
  72488. ** The sqlite3_blob_close() function finalizes the vdbe program,
  72489. ** which closes the b-tree cursor and (possibly) commits the
  72490. ** transaction.
  72491. */
  72492. static const int iLn = VDBE_OFFSET_LINENO(4);
  72493. static const VdbeOpList openBlob[] = {
  72494. /* {OP_Transaction, 0, 0, 0}, // 0: Inserted separately */
  72495. {OP_TableLock, 0, 0, 0}, /* 1: Acquire a read or write lock */
  72496. /* One of the following two instructions is replaced by an OP_Noop. */
  72497. {OP_OpenRead, 0, 0, 0}, /* 2: Open cursor 0 for reading */
  72498. {OP_OpenWrite, 0, 0, 0}, /* 3: Open cursor 0 for read/write */
  72499. {OP_Variable, 1, 1, 1}, /* 4: Push the rowid to the stack */
  72500. {OP_NotExists, 0, 10, 1}, /* 5: Seek the cursor */
  72501. {OP_Column, 0, 0, 1}, /* 6 */
  72502. {OP_ResultRow, 1, 0, 0}, /* 7 */
  72503. {OP_Goto, 0, 4, 0}, /* 8 */
  72504. {OP_Close, 0, 0, 0}, /* 9 */
  72505. {OP_Halt, 0, 0, 0}, /* 10 */
  72506. };
  72507. int rc = SQLITE_OK;
  72508. char *zErr = 0;
  72509. Table *pTab;
  72510. Parse *pParse = 0;
  72511. Incrblob *pBlob = 0;
  72512. #ifdef SQLITE_ENABLE_API_ARMOR
  72513. if( ppBlob==0 ){
  72514. return SQLITE_MISUSE_BKPT;
  72515. }
  72516. #endif
  72517. *ppBlob = 0;
  72518. #ifdef SQLITE_ENABLE_API_ARMOR
  72519. if( !sqlite3SafetyCheckOk(db) || zTable==0 ){
  72520. return SQLITE_MISUSE_BKPT;
  72521. }
  72522. #endif
  72523. flags = !!flags; /* flags = (flags ? 1 : 0); */
  72524. sqlite3_mutex_enter(db->mutex);
  72525. pBlob = (Incrblob *)sqlite3DbMallocZero(db, sizeof(Incrblob));
  72526. if( !pBlob ) goto blob_open_out;
  72527. pParse = sqlite3StackAllocRaw(db, sizeof(*pParse));
  72528. if( !pParse ) goto blob_open_out;
  72529. do {
  72530. memset(pParse, 0, sizeof(Parse));
  72531. pParse->db = db;
  72532. sqlite3DbFree(db, zErr);
  72533. zErr = 0;
  72534. sqlite3BtreeEnterAll(db);
  72535. pTab = sqlite3LocateTable(pParse, 0, zTable, zDb);
  72536. if( pTab && IsVirtual(pTab) ){
  72537. pTab = 0;
  72538. sqlite3ErrorMsg(pParse, "cannot open virtual table: %s", zTable);
  72539. }
  72540. if( pTab && !HasRowid(pTab) ){
  72541. pTab = 0;
  72542. sqlite3ErrorMsg(pParse, "cannot open table without rowid: %s", zTable);
  72543. }
  72544. #ifndef SQLITE_OMIT_VIEW
  72545. if( pTab && pTab->pSelect ){
  72546. pTab = 0;
  72547. sqlite3ErrorMsg(pParse, "cannot open view: %s", zTable);
  72548. }
  72549. #endif
  72550. if( !pTab ){
  72551. if( pParse->zErrMsg ){
  72552. sqlite3DbFree(db, zErr);
  72553. zErr = pParse->zErrMsg;
  72554. pParse->zErrMsg = 0;
  72555. }
  72556. rc = SQLITE_ERROR;
  72557. sqlite3BtreeLeaveAll(db);
  72558. goto blob_open_out;
  72559. }
  72560. /* Now search pTab for the exact column. */
  72561. for(iCol=0; iCol<pTab->nCol; iCol++) {
  72562. if( sqlite3StrICmp(pTab->aCol[iCol].zName, zColumn)==0 ){
  72563. break;
  72564. }
  72565. }
  72566. if( iCol==pTab->nCol ){
  72567. sqlite3DbFree(db, zErr);
  72568. zErr = sqlite3MPrintf(db, "no such column: \"%s\"", zColumn);
  72569. rc = SQLITE_ERROR;
  72570. sqlite3BtreeLeaveAll(db);
  72571. goto blob_open_out;
  72572. }
  72573. /* If the value is being opened for writing, check that the
  72574. ** column is not indexed, and that it is not part of a foreign key.
  72575. ** It is against the rules to open a column to which either of these
  72576. ** descriptions applies for writing. */
  72577. if( flags ){
  72578. const char *zFault = 0;
  72579. Index *pIdx;
  72580. #ifndef SQLITE_OMIT_FOREIGN_KEY
  72581. if( db->flags&SQLITE_ForeignKeys ){
  72582. /* Check that the column is not part of an FK child key definition. It
  72583. ** is not necessary to check if it is part of a parent key, as parent
  72584. ** key columns must be indexed. The check below will pick up this
  72585. ** case. */
  72586. FKey *pFKey;
  72587. for(pFKey=pTab->pFKey; pFKey; pFKey=pFKey->pNextFrom){
  72588. int j;
  72589. for(j=0; j<pFKey->nCol; j++){
  72590. if( pFKey->aCol[j].iFrom==iCol ){
  72591. zFault = "foreign key";
  72592. }
  72593. }
  72594. }
  72595. }
  72596. #endif
  72597. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  72598. int j;
  72599. for(j=0; j<pIdx->nKeyCol; j++){
  72600. if( pIdx->aiColumn[j]==iCol ){
  72601. zFault = "indexed";
  72602. }
  72603. }
  72604. }
  72605. if( zFault ){
  72606. sqlite3DbFree(db, zErr);
  72607. zErr = sqlite3MPrintf(db, "cannot open %s column for writing", zFault);
  72608. rc = SQLITE_ERROR;
  72609. sqlite3BtreeLeaveAll(db);
  72610. goto blob_open_out;
  72611. }
  72612. }
  72613. pBlob->pStmt = (sqlite3_stmt *)sqlite3VdbeCreate(pParse);
  72614. assert( pBlob->pStmt || db->mallocFailed );
  72615. if( pBlob->pStmt ){
  72616. Vdbe *v = (Vdbe *)pBlob->pStmt;
  72617. int iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  72618. sqlite3VdbeAddOp4Int(v, OP_Transaction, iDb, flags,
  72619. pTab->pSchema->schema_cookie,
  72620. pTab->pSchema->iGeneration);
  72621. sqlite3VdbeChangeP5(v, 1);
  72622. sqlite3VdbeAddOpList(v, ArraySize(openBlob), openBlob, iLn);
  72623. /* Make sure a mutex is held on the table to be accessed */
  72624. sqlite3VdbeUsesBtree(v, iDb);
  72625. /* Configure the OP_TableLock instruction */
  72626. #ifdef SQLITE_OMIT_SHARED_CACHE
  72627. sqlite3VdbeChangeToNoop(v, 1);
  72628. #else
  72629. sqlite3VdbeChangeP1(v, 1, iDb);
  72630. sqlite3VdbeChangeP2(v, 1, pTab->tnum);
  72631. sqlite3VdbeChangeP3(v, 1, flags);
  72632. sqlite3VdbeChangeP4(v, 1, pTab->zName, P4_TRANSIENT);
  72633. #endif
  72634. /* Remove either the OP_OpenWrite or OpenRead. Set the P2
  72635. ** parameter of the other to pTab->tnum. */
  72636. sqlite3VdbeChangeToNoop(v, 3 - flags);
  72637. sqlite3VdbeChangeP2(v, 2 + flags, pTab->tnum);
  72638. sqlite3VdbeChangeP3(v, 2 + flags, iDb);
  72639. /* Configure the number of columns. Configure the cursor to
  72640. ** think that the table has one more column than it really
  72641. ** does. An OP_Column to retrieve this imaginary column will
  72642. ** always return an SQL NULL. This is useful because it means
  72643. ** we can invoke OP_Column to fill in the vdbe cursors type
  72644. ** and offset cache without causing any IO.
  72645. */
  72646. sqlite3VdbeChangeP4(v, 2+flags, SQLITE_INT_TO_PTR(pTab->nCol+1),P4_INT32);
  72647. sqlite3VdbeChangeP2(v, 6, pTab->nCol);
  72648. if( !db->mallocFailed ){
  72649. pParse->nVar = 1;
  72650. pParse->nMem = 1;
  72651. pParse->nTab = 1;
  72652. sqlite3VdbeMakeReady(v, pParse);
  72653. }
  72654. }
  72655. pBlob->flags = flags;
  72656. pBlob->iCol = iCol;
  72657. pBlob->db = db;
  72658. sqlite3BtreeLeaveAll(db);
  72659. if( db->mallocFailed ){
  72660. goto blob_open_out;
  72661. }
  72662. sqlite3_bind_int64(pBlob->pStmt, 1, iRow);
  72663. rc = blobSeekToRow(pBlob, iRow, &zErr);
  72664. } while( (++nAttempt)<SQLITE_MAX_SCHEMA_RETRY && rc==SQLITE_SCHEMA );
  72665. blob_open_out:
  72666. if( rc==SQLITE_OK && db->mallocFailed==0 ){
  72667. *ppBlob = (sqlite3_blob *)pBlob;
  72668. }else{
  72669. if( pBlob && pBlob->pStmt ) sqlite3VdbeFinalize((Vdbe *)pBlob->pStmt);
  72670. sqlite3DbFree(db, pBlob);
  72671. }
  72672. sqlite3ErrorWithMsg(db, rc, (zErr ? "%s" : 0), zErr);
  72673. sqlite3DbFree(db, zErr);
  72674. sqlite3ParserReset(pParse);
  72675. sqlite3StackFree(db, pParse);
  72676. rc = sqlite3ApiExit(db, rc);
  72677. sqlite3_mutex_leave(db->mutex);
  72678. return rc;
  72679. }
  72680. /*
  72681. ** Close a blob handle that was previously created using
  72682. ** sqlite3_blob_open().
  72683. */
  72684. SQLITE_API int SQLITE_STDCALL sqlite3_blob_close(sqlite3_blob *pBlob){
  72685. Incrblob *p = (Incrblob *)pBlob;
  72686. int rc;
  72687. sqlite3 *db;
  72688. if( p ){
  72689. db = p->db;
  72690. sqlite3_mutex_enter(db->mutex);
  72691. rc = sqlite3_finalize(p->pStmt);
  72692. sqlite3DbFree(db, p);
  72693. sqlite3_mutex_leave(db->mutex);
  72694. }else{
  72695. rc = SQLITE_OK;
  72696. }
  72697. return rc;
  72698. }
  72699. /*
  72700. ** Perform a read or write operation on a blob
  72701. */
  72702. static int blobReadWrite(
  72703. sqlite3_blob *pBlob,
  72704. void *z,
  72705. int n,
  72706. int iOffset,
  72707. int (*xCall)(BtCursor*, u32, u32, void*)
  72708. ){
  72709. int rc;
  72710. Incrblob *p = (Incrblob *)pBlob;
  72711. Vdbe *v;
  72712. sqlite3 *db;
  72713. if( p==0 ) return SQLITE_MISUSE_BKPT;
  72714. db = p->db;
  72715. sqlite3_mutex_enter(db->mutex);
  72716. v = (Vdbe*)p->pStmt;
  72717. if( n<0 || iOffset<0 || ((sqlite3_int64)iOffset+n)>p->nByte ){
  72718. /* Request is out of range. Return a transient error. */
  72719. rc = SQLITE_ERROR;
  72720. }else if( v==0 ){
  72721. /* If there is no statement handle, then the blob-handle has
  72722. ** already been invalidated. Return SQLITE_ABORT in this case.
  72723. */
  72724. rc = SQLITE_ABORT;
  72725. }else{
  72726. /* Call either BtreeData() or BtreePutData(). If SQLITE_ABORT is
  72727. ** returned, clean-up the statement handle.
  72728. */
  72729. assert( db == v->db );
  72730. sqlite3BtreeEnterCursor(p->pCsr);
  72731. rc = xCall(p->pCsr, iOffset+p->iOffset, n, z);
  72732. sqlite3BtreeLeaveCursor(p->pCsr);
  72733. if( rc==SQLITE_ABORT ){
  72734. sqlite3VdbeFinalize(v);
  72735. p->pStmt = 0;
  72736. }else{
  72737. v->rc = rc;
  72738. }
  72739. }
  72740. sqlite3Error(db, rc);
  72741. rc = sqlite3ApiExit(db, rc);
  72742. sqlite3_mutex_leave(db->mutex);
  72743. return rc;
  72744. }
  72745. /*
  72746. ** Read data from a blob handle.
  72747. */
  72748. SQLITE_API int SQLITE_STDCALL sqlite3_blob_read(sqlite3_blob *pBlob, void *z, int n, int iOffset){
  72749. return blobReadWrite(pBlob, z, n, iOffset, sqlite3BtreeData);
  72750. }
  72751. /*
  72752. ** Write data to a blob handle.
  72753. */
  72754. SQLITE_API int SQLITE_STDCALL sqlite3_blob_write(sqlite3_blob *pBlob, const void *z, int n, int iOffset){
  72755. return blobReadWrite(pBlob, (void *)z, n, iOffset, sqlite3BtreePutData);
  72756. }
  72757. /*
  72758. ** Query a blob handle for the size of the data.
  72759. **
  72760. ** The Incrblob.nByte field is fixed for the lifetime of the Incrblob
  72761. ** so no mutex is required for access.
  72762. */
  72763. SQLITE_API int SQLITE_STDCALL sqlite3_blob_bytes(sqlite3_blob *pBlob){
  72764. Incrblob *p = (Incrblob *)pBlob;
  72765. return (p && p->pStmt) ? p->nByte : 0;
  72766. }
  72767. /*
  72768. ** Move an existing blob handle to point to a different row of the same
  72769. ** database table.
  72770. **
  72771. ** If an error occurs, or if the specified row does not exist or does not
  72772. ** contain a blob or text value, then an error code is returned and the
  72773. ** database handle error code and message set. If this happens, then all
  72774. ** subsequent calls to sqlite3_blob_xxx() functions (except blob_close())
  72775. ** immediately return SQLITE_ABORT.
  72776. */
  72777. SQLITE_API int SQLITE_STDCALL sqlite3_blob_reopen(sqlite3_blob *pBlob, sqlite3_int64 iRow){
  72778. int rc;
  72779. Incrblob *p = (Incrblob *)pBlob;
  72780. sqlite3 *db;
  72781. if( p==0 ) return SQLITE_MISUSE_BKPT;
  72782. db = p->db;
  72783. sqlite3_mutex_enter(db->mutex);
  72784. if( p->pStmt==0 ){
  72785. /* If there is no statement handle, then the blob-handle has
  72786. ** already been invalidated. Return SQLITE_ABORT in this case.
  72787. */
  72788. rc = SQLITE_ABORT;
  72789. }else{
  72790. char *zErr;
  72791. rc = blobSeekToRow(p, iRow, &zErr);
  72792. if( rc!=SQLITE_OK ){
  72793. sqlite3ErrorWithMsg(db, rc, (zErr ? "%s" : 0), zErr);
  72794. sqlite3DbFree(db, zErr);
  72795. }
  72796. assert( rc!=SQLITE_SCHEMA );
  72797. }
  72798. rc = sqlite3ApiExit(db, rc);
  72799. assert( rc==SQLITE_OK || p->pStmt==0 );
  72800. sqlite3_mutex_leave(db->mutex);
  72801. return rc;
  72802. }
  72803. #endif /* #ifndef SQLITE_OMIT_INCRBLOB */
  72804. /************** End of vdbeblob.c ********************************************/
  72805. /************** Begin file vdbesort.c ****************************************/
  72806. /*
  72807. ** 2011-07-09
  72808. **
  72809. ** The author disclaims copyright to this source code. In place of
  72810. ** a legal notice, here is a blessing:
  72811. **
  72812. ** May you do good and not evil.
  72813. ** May you find forgiveness for yourself and forgive others.
  72814. ** May you share freely, never taking more than you give.
  72815. **
  72816. *************************************************************************
  72817. ** This file contains code for the VdbeSorter object, used in concert with
  72818. ** a VdbeCursor to sort large numbers of keys for CREATE INDEX statements
  72819. ** or by SELECT statements with ORDER BY clauses that cannot be satisfied
  72820. ** using indexes and without LIMIT clauses.
  72821. **
  72822. ** The VdbeSorter object implements a multi-threaded external merge sort
  72823. ** algorithm that is efficient even if the number of elements being sorted
  72824. ** exceeds the available memory.
  72825. **
  72826. ** Here is the (internal, non-API) interface between this module and the
  72827. ** rest of the SQLite system:
  72828. **
  72829. ** sqlite3VdbeSorterInit() Create a new VdbeSorter object.
  72830. **
  72831. ** sqlite3VdbeSorterWrite() Add a single new row to the VdbeSorter
  72832. ** object. The row is a binary blob in the
  72833. ** OP_MakeRecord format that contains both
  72834. ** the ORDER BY key columns and result columns
  72835. ** in the case of a SELECT w/ ORDER BY, or
  72836. ** the complete record for an index entry
  72837. ** in the case of a CREATE INDEX.
  72838. **
  72839. ** sqlite3VdbeSorterRewind() Sort all content previously added.
  72840. ** Position the read cursor on the
  72841. ** first sorted element.
  72842. **
  72843. ** sqlite3VdbeSorterNext() Advance the read cursor to the next sorted
  72844. ** element.
  72845. **
  72846. ** sqlite3VdbeSorterRowkey() Return the complete binary blob for the
  72847. ** row currently under the read cursor.
  72848. **
  72849. ** sqlite3VdbeSorterCompare() Compare the binary blob for the row
  72850. ** currently under the read cursor against
  72851. ** another binary blob X and report if
  72852. ** X is strictly less than the read cursor.
  72853. ** Used to enforce uniqueness in a
  72854. ** CREATE UNIQUE INDEX statement.
  72855. **
  72856. ** sqlite3VdbeSorterClose() Close the VdbeSorter object and reclaim
  72857. ** all resources.
  72858. **
  72859. ** sqlite3VdbeSorterReset() Refurbish the VdbeSorter for reuse. This
  72860. ** is like Close() followed by Init() only
  72861. ** much faster.
  72862. **
  72863. ** The interfaces above must be called in a particular order. Write() can
  72864. ** only occur in between Init()/Reset() and Rewind(). Next(), Rowkey(), and
  72865. ** Compare() can only occur in between Rewind() and Close()/Reset(). i.e.
  72866. **
  72867. ** Init()
  72868. ** for each record: Write()
  72869. ** Rewind()
  72870. ** Rowkey()/Compare()
  72871. ** Next()
  72872. ** Close()
  72873. **
  72874. ** Algorithm:
  72875. **
  72876. ** Records passed to the sorter via calls to Write() are initially held
  72877. ** unsorted in main memory. Assuming the amount of memory used never exceeds
  72878. ** a threshold, when Rewind() is called the set of records is sorted using
  72879. ** an in-memory merge sort. In this case, no temporary files are required
  72880. ** and subsequent calls to Rowkey(), Next() and Compare() read records
  72881. ** directly from main memory.
  72882. **
  72883. ** If the amount of space used to store records in main memory exceeds the
  72884. ** threshold, then the set of records currently in memory are sorted and
  72885. ** written to a temporary file in "Packed Memory Array" (PMA) format.
  72886. ** A PMA created at this point is known as a "level-0 PMA". Higher levels
  72887. ** of PMAs may be created by merging existing PMAs together - for example
  72888. ** merging two or more level-0 PMAs together creates a level-1 PMA.
  72889. **
  72890. ** The threshold for the amount of main memory to use before flushing
  72891. ** records to a PMA is roughly the same as the limit configured for the
  72892. ** page-cache of the main database. Specifically, the threshold is set to
  72893. ** the value returned by "PRAGMA main.page_size" multipled by
  72894. ** that returned by "PRAGMA main.cache_size", in bytes.
  72895. **
  72896. ** If the sorter is running in single-threaded mode, then all PMAs generated
  72897. ** are appended to a single temporary file. Or, if the sorter is running in
  72898. ** multi-threaded mode then up to (N+1) temporary files may be opened, where
  72899. ** N is the configured number of worker threads. In this case, instead of
  72900. ** sorting the records and writing the PMA to a temporary file itself, the
  72901. ** calling thread usually launches a worker thread to do so. Except, if
  72902. ** there are already N worker threads running, the main thread does the work
  72903. ** itself.
  72904. **
  72905. ** The sorter is running in multi-threaded mode if (a) the library was built
  72906. ** with pre-processor symbol SQLITE_MAX_WORKER_THREADS set to a value greater
  72907. ** than zero, and (b) worker threads have been enabled at runtime by calling
  72908. ** "PRAGMA threads=N" with some value of N greater than 0.
  72909. **
  72910. ** When Rewind() is called, any data remaining in memory is flushed to a
  72911. ** final PMA. So at this point the data is stored in some number of sorted
  72912. ** PMAs within temporary files on disk.
  72913. **
  72914. ** If there are fewer than SORTER_MAX_MERGE_COUNT PMAs in total and the
  72915. ** sorter is running in single-threaded mode, then these PMAs are merged
  72916. ** incrementally as keys are retreived from the sorter by the VDBE. The
  72917. ** MergeEngine object, described in further detail below, performs this
  72918. ** merge.
  72919. **
  72920. ** Or, if running in multi-threaded mode, then a background thread is
  72921. ** launched to merge the existing PMAs. Once the background thread has
  72922. ** merged T bytes of data into a single sorted PMA, the main thread
  72923. ** begins reading keys from that PMA while the background thread proceeds
  72924. ** with merging the next T bytes of data. And so on.
  72925. **
  72926. ** Parameter T is set to half the value of the memory threshold used
  72927. ** by Write() above to determine when to create a new PMA.
  72928. **
  72929. ** If there are more than SORTER_MAX_MERGE_COUNT PMAs in total when
  72930. ** Rewind() is called, then a hierarchy of incremental-merges is used.
  72931. ** First, T bytes of data from the first SORTER_MAX_MERGE_COUNT PMAs on
  72932. ** disk are merged together. Then T bytes of data from the second set, and
  72933. ** so on, such that no operation ever merges more than SORTER_MAX_MERGE_COUNT
  72934. ** PMAs at a time. This done is to improve locality.
  72935. **
  72936. ** If running in multi-threaded mode and there are more than
  72937. ** SORTER_MAX_MERGE_COUNT PMAs on disk when Rewind() is called, then more
  72938. ** than one background thread may be created. Specifically, there may be
  72939. ** one background thread for each temporary file on disk, and one background
  72940. ** thread to merge the output of each of the others to a single PMA for
  72941. ** the main thread to read from.
  72942. */
  72943. /*
  72944. ** If SQLITE_DEBUG_SORTER_THREADS is defined, this module outputs various
  72945. ** messages to stderr that may be helpful in understanding the performance
  72946. ** characteristics of the sorter in multi-threaded mode.
  72947. */
  72948. #if 0
  72949. # define SQLITE_DEBUG_SORTER_THREADS 1
  72950. #endif
  72951. /*
  72952. ** Hard-coded maximum amount of data to accumulate in memory before flushing
  72953. ** to a level 0 PMA. The purpose of this limit is to prevent various integer
  72954. ** overflows. 512MiB.
  72955. */
  72956. #define SQLITE_MAX_PMASZ (1<<29)
  72957. /*
  72958. ** Private objects used by the sorter
  72959. */
  72960. typedef struct MergeEngine MergeEngine; /* Merge PMAs together */
  72961. typedef struct PmaReader PmaReader; /* Incrementally read one PMA */
  72962. typedef struct PmaWriter PmaWriter; /* Incrementally write one PMA */
  72963. typedef struct SorterRecord SorterRecord; /* A record being sorted */
  72964. typedef struct SortSubtask SortSubtask; /* A sub-task in the sort process */
  72965. typedef struct SorterFile SorterFile; /* Temporary file object wrapper */
  72966. typedef struct SorterList SorterList; /* In-memory list of records */
  72967. typedef struct IncrMerger IncrMerger; /* Read & merge multiple PMAs */
  72968. /*
  72969. ** A container for a temp file handle and the current amount of data
  72970. ** stored in the file.
  72971. */
  72972. struct SorterFile {
  72973. sqlite3_file *pFd; /* File handle */
  72974. i64 iEof; /* Bytes of data stored in pFd */
  72975. };
  72976. /*
  72977. ** An in-memory list of objects to be sorted.
  72978. **
  72979. ** If aMemory==0 then each object is allocated separately and the objects
  72980. ** are connected using SorterRecord.u.pNext. If aMemory!=0 then all objects
  72981. ** are stored in the aMemory[] bulk memory, one right after the other, and
  72982. ** are connected using SorterRecord.u.iNext.
  72983. */
  72984. struct SorterList {
  72985. SorterRecord *pList; /* Linked list of records */
  72986. u8 *aMemory; /* If non-NULL, bulk memory to hold pList */
  72987. int szPMA; /* Size of pList as PMA in bytes */
  72988. };
  72989. /*
  72990. ** The MergeEngine object is used to combine two or more smaller PMAs into
  72991. ** one big PMA using a merge operation. Separate PMAs all need to be
  72992. ** combined into one big PMA in order to be able to step through the sorted
  72993. ** records in order.
  72994. **
  72995. ** The aReadr[] array contains a PmaReader object for each of the PMAs being
  72996. ** merged. An aReadr[] object either points to a valid key or else is at EOF.
  72997. ** ("EOF" means "End Of File". When aReadr[] is at EOF there is no more data.)
  72998. ** For the purposes of the paragraphs below, we assume that the array is
  72999. ** actually N elements in size, where N is the smallest power of 2 greater
  73000. ** to or equal to the number of PMAs being merged. The extra aReadr[] elements
  73001. ** are treated as if they are empty (always at EOF).
  73002. **
  73003. ** The aTree[] array is also N elements in size. The value of N is stored in
  73004. ** the MergeEngine.nTree variable.
  73005. **
  73006. ** The final (N/2) elements of aTree[] contain the results of comparing
  73007. ** pairs of PMA keys together. Element i contains the result of
  73008. ** comparing aReadr[2*i-N] and aReadr[2*i-N+1]. Whichever key is smaller, the
  73009. ** aTree element is set to the index of it.
  73010. **
  73011. ** For the purposes of this comparison, EOF is considered greater than any
  73012. ** other key value. If the keys are equal (only possible with two EOF
  73013. ** values), it doesn't matter which index is stored.
  73014. **
  73015. ** The (N/4) elements of aTree[] that precede the final (N/2) described
  73016. ** above contains the index of the smallest of each block of 4 PmaReaders
  73017. ** And so on. So that aTree[1] contains the index of the PmaReader that
  73018. ** currently points to the smallest key value. aTree[0] is unused.
  73019. **
  73020. ** Example:
  73021. **
  73022. ** aReadr[0] -> Banana
  73023. ** aReadr[1] -> Feijoa
  73024. ** aReadr[2] -> Elderberry
  73025. ** aReadr[3] -> Currant
  73026. ** aReadr[4] -> Grapefruit
  73027. ** aReadr[5] -> Apple
  73028. ** aReadr[6] -> Durian
  73029. ** aReadr[7] -> EOF
  73030. **
  73031. ** aTree[] = { X, 5 0, 5 0, 3, 5, 6 }
  73032. **
  73033. ** The current element is "Apple" (the value of the key indicated by
  73034. ** PmaReader 5). When the Next() operation is invoked, PmaReader 5 will
  73035. ** be advanced to the next key in its segment. Say the next key is
  73036. ** "Eggplant":
  73037. **
  73038. ** aReadr[5] -> Eggplant
  73039. **
  73040. ** The contents of aTree[] are updated first by comparing the new PmaReader
  73041. ** 5 key to the current key of PmaReader 4 (still "Grapefruit"). The PmaReader
  73042. ** 5 value is still smaller, so aTree[6] is set to 5. And so on up the tree.
  73043. ** The value of PmaReader 6 - "Durian" - is now smaller than that of PmaReader
  73044. ** 5, so aTree[3] is set to 6. Key 0 is smaller than key 6 (Banana<Durian),
  73045. ** so the value written into element 1 of the array is 0. As follows:
  73046. **
  73047. ** aTree[] = { X, 0 0, 6 0, 3, 5, 6 }
  73048. **
  73049. ** In other words, each time we advance to the next sorter element, log2(N)
  73050. ** key comparison operations are required, where N is the number of segments
  73051. ** being merged (rounded up to the next power of 2).
  73052. */
  73053. struct MergeEngine {
  73054. int nTree; /* Used size of aTree/aReadr (power of 2) */
  73055. SortSubtask *pTask; /* Used by this thread only */
  73056. int *aTree; /* Current state of incremental merge */
  73057. PmaReader *aReadr; /* Array of PmaReaders to merge data from */
  73058. };
  73059. /*
  73060. ** This object represents a single thread of control in a sort operation.
  73061. ** Exactly VdbeSorter.nTask instances of this object are allocated
  73062. ** as part of each VdbeSorter object. Instances are never allocated any
  73063. ** other way. VdbeSorter.nTask is set to the number of worker threads allowed
  73064. ** (see SQLITE_CONFIG_WORKER_THREADS) plus one (the main thread). Thus for
  73065. ** single-threaded operation, there is exactly one instance of this object
  73066. ** and for multi-threaded operation there are two or more instances.
  73067. **
  73068. ** Essentially, this structure contains all those fields of the VdbeSorter
  73069. ** structure for which each thread requires a separate instance. For example,
  73070. ** each thread requries its own UnpackedRecord object to unpack records in
  73071. ** as part of comparison operations.
  73072. **
  73073. ** Before a background thread is launched, variable bDone is set to 0. Then,
  73074. ** right before it exits, the thread itself sets bDone to 1. This is used for
  73075. ** two purposes:
  73076. **
  73077. ** 1. When flushing the contents of memory to a level-0 PMA on disk, to
  73078. ** attempt to select a SortSubtask for which there is not already an
  73079. ** active background thread (since doing so causes the main thread
  73080. ** to block until it finishes).
  73081. **
  73082. ** 2. If SQLITE_DEBUG_SORTER_THREADS is defined, to determine if a call
  73083. ** to sqlite3ThreadJoin() is likely to block. Cases that are likely to
  73084. ** block provoke debugging output.
  73085. **
  73086. ** In both cases, the effects of the main thread seeing (bDone==0) even
  73087. ** after the thread has finished are not dire. So we don't worry about
  73088. ** memory barriers and such here.
  73089. */
  73090. typedef int (*SorterCompare)(SortSubtask*,int*,const void*,int,const void*,int);
  73091. struct SortSubtask {
  73092. SQLiteThread *pThread; /* Background thread, if any */
  73093. int bDone; /* Set if thread is finished but not joined */
  73094. VdbeSorter *pSorter; /* Sorter that owns this sub-task */
  73095. UnpackedRecord *pUnpacked; /* Space to unpack a record */
  73096. SorterList list; /* List for thread to write to a PMA */
  73097. int nPMA; /* Number of PMAs currently in file */
  73098. SorterCompare xCompare; /* Compare function to use */
  73099. SorterFile file; /* Temp file for level-0 PMAs */
  73100. SorterFile file2; /* Space for other PMAs */
  73101. };
  73102. /*
  73103. ** Main sorter structure. A single instance of this is allocated for each
  73104. ** sorter cursor created by the VDBE.
  73105. **
  73106. ** mxKeysize:
  73107. ** As records are added to the sorter by calls to sqlite3VdbeSorterWrite(),
  73108. ** this variable is updated so as to be set to the size on disk of the
  73109. ** largest record in the sorter.
  73110. */
  73111. struct VdbeSorter {
  73112. int mnPmaSize; /* Minimum PMA size, in bytes */
  73113. int mxPmaSize; /* Maximum PMA size, in bytes. 0==no limit */
  73114. int mxKeysize; /* Largest serialized key seen so far */
  73115. int pgsz; /* Main database page size */
  73116. PmaReader *pReader; /* Readr data from here after Rewind() */
  73117. MergeEngine *pMerger; /* Or here, if bUseThreads==0 */
  73118. sqlite3 *db; /* Database connection */
  73119. KeyInfo *pKeyInfo; /* How to compare records */
  73120. UnpackedRecord *pUnpacked; /* Used by VdbeSorterCompare() */
  73121. SorterList list; /* List of in-memory records */
  73122. int iMemory; /* Offset of free space in list.aMemory */
  73123. int nMemory; /* Size of list.aMemory allocation in bytes */
  73124. u8 bUsePMA; /* True if one or more PMAs created */
  73125. u8 bUseThreads; /* True to use background threads */
  73126. u8 iPrev; /* Previous thread used to flush PMA */
  73127. u8 nTask; /* Size of aTask[] array */
  73128. u8 typeMask;
  73129. SortSubtask aTask[1]; /* One or more subtasks */
  73130. };
  73131. #define SORTER_TYPE_INTEGER 0x01
  73132. #define SORTER_TYPE_TEXT 0x02
  73133. /*
  73134. ** An instance of the following object is used to read records out of a
  73135. ** PMA, in sorted order. The next key to be read is cached in nKey/aKey.
  73136. ** aKey might point into aMap or into aBuffer. If neither of those locations
  73137. ** contain a contiguous representation of the key, then aAlloc is allocated
  73138. ** and the key is copied into aAlloc and aKey is made to poitn to aAlloc.
  73139. **
  73140. ** pFd==0 at EOF.
  73141. */
  73142. struct PmaReader {
  73143. i64 iReadOff; /* Current read offset */
  73144. i64 iEof; /* 1 byte past EOF for this PmaReader */
  73145. int nAlloc; /* Bytes of space at aAlloc */
  73146. int nKey; /* Number of bytes in key */
  73147. sqlite3_file *pFd; /* File handle we are reading from */
  73148. u8 *aAlloc; /* Space for aKey if aBuffer and pMap wont work */
  73149. u8 *aKey; /* Pointer to current key */
  73150. u8 *aBuffer; /* Current read buffer */
  73151. int nBuffer; /* Size of read buffer in bytes */
  73152. u8 *aMap; /* Pointer to mapping of entire file */
  73153. IncrMerger *pIncr; /* Incremental merger */
  73154. };
  73155. /*
  73156. ** Normally, a PmaReader object iterates through an existing PMA stored
  73157. ** within a temp file. However, if the PmaReader.pIncr variable points to
  73158. ** an object of the following type, it may be used to iterate/merge through
  73159. ** multiple PMAs simultaneously.
  73160. **
  73161. ** There are two types of IncrMerger object - single (bUseThread==0) and
  73162. ** multi-threaded (bUseThread==1).
  73163. **
  73164. ** A multi-threaded IncrMerger object uses two temporary files - aFile[0]
  73165. ** and aFile[1]. Neither file is allowed to grow to more than mxSz bytes in
  73166. ** size. When the IncrMerger is initialized, it reads enough data from
  73167. ** pMerger to populate aFile[0]. It then sets variables within the
  73168. ** corresponding PmaReader object to read from that file and kicks off
  73169. ** a background thread to populate aFile[1] with the next mxSz bytes of
  73170. ** sorted record data from pMerger.
  73171. **
  73172. ** When the PmaReader reaches the end of aFile[0], it blocks until the
  73173. ** background thread has finished populating aFile[1]. It then exchanges
  73174. ** the contents of the aFile[0] and aFile[1] variables within this structure,
  73175. ** sets the PmaReader fields to read from the new aFile[0] and kicks off
  73176. ** another background thread to populate the new aFile[1]. And so on, until
  73177. ** the contents of pMerger are exhausted.
  73178. **
  73179. ** A single-threaded IncrMerger does not open any temporary files of its
  73180. ** own. Instead, it has exclusive access to mxSz bytes of space beginning
  73181. ** at offset iStartOff of file pTask->file2. And instead of using a
  73182. ** background thread to prepare data for the PmaReader, with a single
  73183. ** threaded IncrMerger the allocate part of pTask->file2 is "refilled" with
  73184. ** keys from pMerger by the calling thread whenever the PmaReader runs out
  73185. ** of data.
  73186. */
  73187. struct IncrMerger {
  73188. SortSubtask *pTask; /* Task that owns this merger */
  73189. MergeEngine *pMerger; /* Merge engine thread reads data from */
  73190. i64 iStartOff; /* Offset to start writing file at */
  73191. int mxSz; /* Maximum bytes of data to store */
  73192. int bEof; /* Set to true when merge is finished */
  73193. int bUseThread; /* True to use a bg thread for this object */
  73194. SorterFile aFile[2]; /* aFile[0] for reading, [1] for writing */
  73195. };
  73196. /*
  73197. ** An instance of this object is used for writing a PMA.
  73198. **
  73199. ** The PMA is written one record at a time. Each record is of an arbitrary
  73200. ** size. But I/O is more efficient if it occurs in page-sized blocks where
  73201. ** each block is aligned on a page boundary. This object caches writes to
  73202. ** the PMA so that aligned, page-size blocks are written.
  73203. */
  73204. struct PmaWriter {
  73205. int eFWErr; /* Non-zero if in an error state */
  73206. u8 *aBuffer; /* Pointer to write buffer */
  73207. int nBuffer; /* Size of write buffer in bytes */
  73208. int iBufStart; /* First byte of buffer to write */
  73209. int iBufEnd; /* Last byte of buffer to write */
  73210. i64 iWriteOff; /* Offset of start of buffer in file */
  73211. sqlite3_file *pFd; /* File handle to write to */
  73212. };
  73213. /*
  73214. ** This object is the header on a single record while that record is being
  73215. ** held in memory and prior to being written out as part of a PMA.
  73216. **
  73217. ** How the linked list is connected depends on how memory is being managed
  73218. ** by this module. If using a separate allocation for each in-memory record
  73219. ** (VdbeSorter.list.aMemory==0), then the list is always connected using the
  73220. ** SorterRecord.u.pNext pointers.
  73221. **
  73222. ** Or, if using the single large allocation method (VdbeSorter.list.aMemory!=0),
  73223. ** then while records are being accumulated the list is linked using the
  73224. ** SorterRecord.u.iNext offset. This is because the aMemory[] array may
  73225. ** be sqlite3Realloc()ed while records are being accumulated. Once the VM
  73226. ** has finished passing records to the sorter, or when the in-memory buffer
  73227. ** is full, the list is sorted. As part of the sorting process, it is
  73228. ** converted to use the SorterRecord.u.pNext pointers. See function
  73229. ** vdbeSorterSort() for details.
  73230. */
  73231. struct SorterRecord {
  73232. int nVal; /* Size of the record in bytes */
  73233. union {
  73234. SorterRecord *pNext; /* Pointer to next record in list */
  73235. int iNext; /* Offset within aMemory of next record */
  73236. } u;
  73237. /* The data for the record immediately follows this header */
  73238. };
  73239. /* Return a pointer to the buffer containing the record data for SorterRecord
  73240. ** object p. Should be used as if:
  73241. **
  73242. ** void *SRVAL(SorterRecord *p) { return (void*)&p[1]; }
  73243. */
  73244. #define SRVAL(p) ((void*)((SorterRecord*)(p) + 1))
  73245. /* Maximum number of PMAs that a single MergeEngine can merge */
  73246. #define SORTER_MAX_MERGE_COUNT 16
  73247. static int vdbeIncrSwap(IncrMerger*);
  73248. static void vdbeIncrFree(IncrMerger *);
  73249. /*
  73250. ** Free all memory belonging to the PmaReader object passed as the
  73251. ** argument. All structure fields are set to zero before returning.
  73252. */
  73253. static void vdbePmaReaderClear(PmaReader *pReadr){
  73254. sqlite3_free(pReadr->aAlloc);
  73255. sqlite3_free(pReadr->aBuffer);
  73256. if( pReadr->aMap ) sqlite3OsUnfetch(pReadr->pFd, 0, pReadr->aMap);
  73257. vdbeIncrFree(pReadr->pIncr);
  73258. memset(pReadr, 0, sizeof(PmaReader));
  73259. }
  73260. /*
  73261. ** Read the next nByte bytes of data from the PMA p.
  73262. ** If successful, set *ppOut to point to a buffer containing the data
  73263. ** and return SQLITE_OK. Otherwise, if an error occurs, return an SQLite
  73264. ** error code.
  73265. **
  73266. ** The buffer returned in *ppOut is only valid until the
  73267. ** next call to this function.
  73268. */
  73269. static int vdbePmaReadBlob(
  73270. PmaReader *p, /* PmaReader from which to take the blob */
  73271. int nByte, /* Bytes of data to read */
  73272. u8 **ppOut /* OUT: Pointer to buffer containing data */
  73273. ){
  73274. int iBuf; /* Offset within buffer to read from */
  73275. int nAvail; /* Bytes of data available in buffer */
  73276. if( p->aMap ){
  73277. *ppOut = &p->aMap[p->iReadOff];
  73278. p->iReadOff += nByte;
  73279. return SQLITE_OK;
  73280. }
  73281. assert( p->aBuffer );
  73282. /* If there is no more data to be read from the buffer, read the next
  73283. ** p->nBuffer bytes of data from the file into it. Or, if there are less
  73284. ** than p->nBuffer bytes remaining in the PMA, read all remaining data. */
  73285. iBuf = p->iReadOff % p->nBuffer;
  73286. if( iBuf==0 ){
  73287. int nRead; /* Bytes to read from disk */
  73288. int rc; /* sqlite3OsRead() return code */
  73289. /* Determine how many bytes of data to read. */
  73290. if( (p->iEof - p->iReadOff) > (i64)p->nBuffer ){
  73291. nRead = p->nBuffer;
  73292. }else{
  73293. nRead = (int)(p->iEof - p->iReadOff);
  73294. }
  73295. assert( nRead>0 );
  73296. /* Readr data from the file. Return early if an error occurs. */
  73297. rc = sqlite3OsRead(p->pFd, p->aBuffer, nRead, p->iReadOff);
  73298. assert( rc!=SQLITE_IOERR_SHORT_READ );
  73299. if( rc!=SQLITE_OK ) return rc;
  73300. }
  73301. nAvail = p->nBuffer - iBuf;
  73302. if( nByte<=nAvail ){
  73303. /* The requested data is available in the in-memory buffer. In this
  73304. ** case there is no need to make a copy of the data, just return a
  73305. ** pointer into the buffer to the caller. */
  73306. *ppOut = &p->aBuffer[iBuf];
  73307. p->iReadOff += nByte;
  73308. }else{
  73309. /* The requested data is not all available in the in-memory buffer.
  73310. ** In this case, allocate space at p->aAlloc[] to copy the requested
  73311. ** range into. Then return a copy of pointer p->aAlloc to the caller. */
  73312. int nRem; /* Bytes remaining to copy */
  73313. /* Extend the p->aAlloc[] allocation if required. */
  73314. if( p->nAlloc<nByte ){
  73315. u8 *aNew;
  73316. int nNew = MAX(128, p->nAlloc*2);
  73317. while( nByte>nNew ) nNew = nNew*2;
  73318. aNew = sqlite3Realloc(p->aAlloc, nNew);
  73319. if( !aNew ) return SQLITE_NOMEM;
  73320. p->nAlloc = nNew;
  73321. p->aAlloc = aNew;
  73322. }
  73323. /* Copy as much data as is available in the buffer into the start of
  73324. ** p->aAlloc[]. */
  73325. memcpy(p->aAlloc, &p->aBuffer[iBuf], nAvail);
  73326. p->iReadOff += nAvail;
  73327. nRem = nByte - nAvail;
  73328. /* The following loop copies up to p->nBuffer bytes per iteration into
  73329. ** the p->aAlloc[] buffer. */
  73330. while( nRem>0 ){
  73331. int rc; /* vdbePmaReadBlob() return code */
  73332. int nCopy; /* Number of bytes to copy */
  73333. u8 *aNext; /* Pointer to buffer to copy data from */
  73334. nCopy = nRem;
  73335. if( nRem>p->nBuffer ) nCopy = p->nBuffer;
  73336. rc = vdbePmaReadBlob(p, nCopy, &aNext);
  73337. if( rc!=SQLITE_OK ) return rc;
  73338. assert( aNext!=p->aAlloc );
  73339. memcpy(&p->aAlloc[nByte - nRem], aNext, nCopy);
  73340. nRem -= nCopy;
  73341. }
  73342. *ppOut = p->aAlloc;
  73343. }
  73344. return SQLITE_OK;
  73345. }
  73346. /*
  73347. ** Read a varint from the stream of data accessed by p. Set *pnOut to
  73348. ** the value read.
  73349. */
  73350. static int vdbePmaReadVarint(PmaReader *p, u64 *pnOut){
  73351. int iBuf;
  73352. if( p->aMap ){
  73353. p->iReadOff += sqlite3GetVarint(&p->aMap[p->iReadOff], pnOut);
  73354. }else{
  73355. iBuf = p->iReadOff % p->nBuffer;
  73356. if( iBuf && (p->nBuffer-iBuf)>=9 ){
  73357. p->iReadOff += sqlite3GetVarint(&p->aBuffer[iBuf], pnOut);
  73358. }else{
  73359. u8 aVarint[16], *a;
  73360. int i = 0, rc;
  73361. do{
  73362. rc = vdbePmaReadBlob(p, 1, &a);
  73363. if( rc ) return rc;
  73364. aVarint[(i++)&0xf] = a[0];
  73365. }while( (a[0]&0x80)!=0 );
  73366. sqlite3GetVarint(aVarint, pnOut);
  73367. }
  73368. }
  73369. return SQLITE_OK;
  73370. }
  73371. /*
  73372. ** Attempt to memory map file pFile. If successful, set *pp to point to the
  73373. ** new mapping and return SQLITE_OK. If the mapping is not attempted
  73374. ** (because the file is too large or the VFS layer is configured not to use
  73375. ** mmap), return SQLITE_OK and set *pp to NULL.
  73376. **
  73377. ** Or, if an error occurs, return an SQLite error code. The final value of
  73378. ** *pp is undefined in this case.
  73379. */
  73380. static int vdbeSorterMapFile(SortSubtask *pTask, SorterFile *pFile, u8 **pp){
  73381. int rc = SQLITE_OK;
  73382. if( pFile->iEof<=(i64)(pTask->pSorter->db->nMaxSorterMmap) ){
  73383. sqlite3_file *pFd = pFile->pFd;
  73384. if( pFd->pMethods->iVersion>=3 ){
  73385. rc = sqlite3OsFetch(pFd, 0, (int)pFile->iEof, (void**)pp);
  73386. testcase( rc!=SQLITE_OK );
  73387. }
  73388. }
  73389. return rc;
  73390. }
  73391. /*
  73392. ** Attach PmaReader pReadr to file pFile (if it is not already attached to
  73393. ** that file) and seek it to offset iOff within the file. Return SQLITE_OK
  73394. ** if successful, or an SQLite error code if an error occurs.
  73395. */
  73396. static int vdbePmaReaderSeek(
  73397. SortSubtask *pTask, /* Task context */
  73398. PmaReader *pReadr, /* Reader whose cursor is to be moved */
  73399. SorterFile *pFile, /* Sorter file to read from */
  73400. i64 iOff /* Offset in pFile */
  73401. ){
  73402. int rc = SQLITE_OK;
  73403. assert( pReadr->pIncr==0 || pReadr->pIncr->bEof==0 );
  73404. if( sqlite3FaultSim(201) ) return SQLITE_IOERR_READ;
  73405. if( pReadr->aMap ){
  73406. sqlite3OsUnfetch(pReadr->pFd, 0, pReadr->aMap);
  73407. pReadr->aMap = 0;
  73408. }
  73409. pReadr->iReadOff = iOff;
  73410. pReadr->iEof = pFile->iEof;
  73411. pReadr->pFd = pFile->pFd;
  73412. rc = vdbeSorterMapFile(pTask, pFile, &pReadr->aMap);
  73413. if( rc==SQLITE_OK && pReadr->aMap==0 ){
  73414. int pgsz = pTask->pSorter->pgsz;
  73415. int iBuf = pReadr->iReadOff % pgsz;
  73416. if( pReadr->aBuffer==0 ){
  73417. pReadr->aBuffer = (u8*)sqlite3Malloc(pgsz);
  73418. if( pReadr->aBuffer==0 ) rc = SQLITE_NOMEM;
  73419. pReadr->nBuffer = pgsz;
  73420. }
  73421. if( rc==SQLITE_OK && iBuf ){
  73422. int nRead = pgsz - iBuf;
  73423. if( (pReadr->iReadOff + nRead) > pReadr->iEof ){
  73424. nRead = (int)(pReadr->iEof - pReadr->iReadOff);
  73425. }
  73426. rc = sqlite3OsRead(
  73427. pReadr->pFd, &pReadr->aBuffer[iBuf], nRead, pReadr->iReadOff
  73428. );
  73429. testcase( rc!=SQLITE_OK );
  73430. }
  73431. }
  73432. return rc;
  73433. }
  73434. /*
  73435. ** Advance PmaReader pReadr to the next key in its PMA. Return SQLITE_OK if
  73436. ** no error occurs, or an SQLite error code if one does.
  73437. */
  73438. static int vdbePmaReaderNext(PmaReader *pReadr){
  73439. int rc = SQLITE_OK; /* Return Code */
  73440. u64 nRec = 0; /* Size of record in bytes */
  73441. if( pReadr->iReadOff>=pReadr->iEof ){
  73442. IncrMerger *pIncr = pReadr->pIncr;
  73443. int bEof = 1;
  73444. if( pIncr ){
  73445. rc = vdbeIncrSwap(pIncr);
  73446. if( rc==SQLITE_OK && pIncr->bEof==0 ){
  73447. rc = vdbePmaReaderSeek(
  73448. pIncr->pTask, pReadr, &pIncr->aFile[0], pIncr->iStartOff
  73449. );
  73450. bEof = 0;
  73451. }
  73452. }
  73453. if( bEof ){
  73454. /* This is an EOF condition */
  73455. vdbePmaReaderClear(pReadr);
  73456. testcase( rc!=SQLITE_OK );
  73457. return rc;
  73458. }
  73459. }
  73460. if( rc==SQLITE_OK ){
  73461. rc = vdbePmaReadVarint(pReadr, &nRec);
  73462. }
  73463. if( rc==SQLITE_OK ){
  73464. pReadr->nKey = (int)nRec;
  73465. rc = vdbePmaReadBlob(pReadr, (int)nRec, &pReadr->aKey);
  73466. testcase( rc!=SQLITE_OK );
  73467. }
  73468. return rc;
  73469. }
  73470. /*
  73471. ** Initialize PmaReader pReadr to scan through the PMA stored in file pFile
  73472. ** starting at offset iStart and ending at offset iEof-1. This function
  73473. ** leaves the PmaReader pointing to the first key in the PMA (or EOF if the
  73474. ** PMA is empty).
  73475. **
  73476. ** If the pnByte parameter is NULL, then it is assumed that the file
  73477. ** contains a single PMA, and that that PMA omits the initial length varint.
  73478. */
  73479. static int vdbePmaReaderInit(
  73480. SortSubtask *pTask, /* Task context */
  73481. SorterFile *pFile, /* Sorter file to read from */
  73482. i64 iStart, /* Start offset in pFile */
  73483. PmaReader *pReadr, /* PmaReader to populate */
  73484. i64 *pnByte /* IN/OUT: Increment this value by PMA size */
  73485. ){
  73486. int rc;
  73487. assert( pFile->iEof>iStart );
  73488. assert( pReadr->aAlloc==0 && pReadr->nAlloc==0 );
  73489. assert( pReadr->aBuffer==0 );
  73490. assert( pReadr->aMap==0 );
  73491. rc = vdbePmaReaderSeek(pTask, pReadr, pFile, iStart);
  73492. if( rc==SQLITE_OK ){
  73493. u64 nByte; /* Size of PMA in bytes */
  73494. rc = vdbePmaReadVarint(pReadr, &nByte);
  73495. pReadr->iEof = pReadr->iReadOff + nByte;
  73496. *pnByte += nByte;
  73497. }
  73498. if( rc==SQLITE_OK ){
  73499. rc = vdbePmaReaderNext(pReadr);
  73500. }
  73501. return rc;
  73502. }
  73503. /*
  73504. ** A version of vdbeSorterCompare() that assumes that it has already been
  73505. ** determined that the first field of key1 is equal to the first field of
  73506. ** key2.
  73507. */
  73508. static int vdbeSorterCompareTail(
  73509. SortSubtask *pTask, /* Subtask context (for pKeyInfo) */
  73510. int *pbKey2Cached, /* True if pTask->pUnpacked is pKey2 */
  73511. const void *pKey1, int nKey1, /* Left side of comparison */
  73512. const void *pKey2, int nKey2 /* Right side of comparison */
  73513. ){
  73514. UnpackedRecord *r2 = pTask->pUnpacked;
  73515. if( *pbKey2Cached==0 ){
  73516. sqlite3VdbeRecordUnpack(pTask->pSorter->pKeyInfo, nKey2, pKey2, r2);
  73517. *pbKey2Cached = 1;
  73518. }
  73519. return sqlite3VdbeRecordCompareWithSkip(nKey1, pKey1, r2, 1);
  73520. }
  73521. /*
  73522. ** Compare key1 (buffer pKey1, size nKey1 bytes) with key2 (buffer pKey2,
  73523. ** size nKey2 bytes). Use (pTask->pKeyInfo) for the collation sequences
  73524. ** used by the comparison. Return the result of the comparison.
  73525. **
  73526. ** If IN/OUT parameter *pbKey2Cached is true when this function is called,
  73527. ** it is assumed that (pTask->pUnpacked) contains the unpacked version
  73528. ** of key2. If it is false, (pTask->pUnpacked) is populated with the unpacked
  73529. ** version of key2 and *pbKey2Cached set to true before returning.
  73530. **
  73531. ** If an OOM error is encountered, (pTask->pUnpacked->error_rc) is set
  73532. ** to SQLITE_NOMEM.
  73533. */
  73534. static int vdbeSorterCompare(
  73535. SortSubtask *pTask, /* Subtask context (for pKeyInfo) */
  73536. int *pbKey2Cached, /* True if pTask->pUnpacked is pKey2 */
  73537. const void *pKey1, int nKey1, /* Left side of comparison */
  73538. const void *pKey2, int nKey2 /* Right side of comparison */
  73539. ){
  73540. UnpackedRecord *r2 = pTask->pUnpacked;
  73541. if( !*pbKey2Cached ){
  73542. sqlite3VdbeRecordUnpack(pTask->pSorter->pKeyInfo, nKey2, pKey2, r2);
  73543. *pbKey2Cached = 1;
  73544. }
  73545. return sqlite3VdbeRecordCompare(nKey1, pKey1, r2);
  73546. }
  73547. /*
  73548. ** A specially optimized version of vdbeSorterCompare() that assumes that
  73549. ** the first field of each key is a TEXT value and that the collation
  73550. ** sequence to compare them with is BINARY.
  73551. */
  73552. static int vdbeSorterCompareText(
  73553. SortSubtask *pTask, /* Subtask context (for pKeyInfo) */
  73554. int *pbKey2Cached, /* True if pTask->pUnpacked is pKey2 */
  73555. const void *pKey1, int nKey1, /* Left side of comparison */
  73556. const void *pKey2, int nKey2 /* Right side of comparison */
  73557. ){
  73558. const u8 * const p1 = (const u8 * const)pKey1;
  73559. const u8 * const p2 = (const u8 * const)pKey2;
  73560. const u8 * const v1 = &p1[ p1[0] ]; /* Pointer to value 1 */
  73561. const u8 * const v2 = &p2[ p2[0] ]; /* Pointer to value 2 */
  73562. int n1;
  73563. int n2;
  73564. int res;
  73565. getVarint32(&p1[1], n1); n1 = (n1 - 13) / 2;
  73566. getVarint32(&p2[1], n2); n2 = (n2 - 13) / 2;
  73567. res = memcmp(v1, v2, MIN(n1, n2));
  73568. if( res==0 ){
  73569. res = n1 - n2;
  73570. }
  73571. if( res==0 ){
  73572. if( pTask->pSorter->pKeyInfo->nField>1 ){
  73573. res = vdbeSorterCompareTail(
  73574. pTask, pbKey2Cached, pKey1, nKey1, pKey2, nKey2
  73575. );
  73576. }
  73577. }else{
  73578. if( pTask->pSorter->pKeyInfo->aSortOrder[0] ){
  73579. res = res * -1;
  73580. }
  73581. }
  73582. return res;
  73583. }
  73584. /*
  73585. ** A specially optimized version of vdbeSorterCompare() that assumes that
  73586. ** the first field of each key is an INTEGER value.
  73587. */
  73588. static int vdbeSorterCompareInt(
  73589. SortSubtask *pTask, /* Subtask context (for pKeyInfo) */
  73590. int *pbKey2Cached, /* True if pTask->pUnpacked is pKey2 */
  73591. const void *pKey1, int nKey1, /* Left side of comparison */
  73592. const void *pKey2, int nKey2 /* Right side of comparison */
  73593. ){
  73594. const u8 * const p1 = (const u8 * const)pKey1;
  73595. const u8 * const p2 = (const u8 * const)pKey2;
  73596. const int s1 = p1[1]; /* Left hand serial type */
  73597. const int s2 = p2[1]; /* Right hand serial type */
  73598. const u8 * const v1 = &p1[ p1[0] ]; /* Pointer to value 1 */
  73599. const u8 * const v2 = &p2[ p2[0] ]; /* Pointer to value 2 */
  73600. int res; /* Return value */
  73601. assert( (s1>0 && s1<7) || s1==8 || s1==9 );
  73602. assert( (s2>0 && s2<7) || s2==8 || s2==9 );
  73603. if( s1>7 && s2>7 ){
  73604. res = s1 - s2;
  73605. }else{
  73606. if( s1==s2 ){
  73607. if( (*v1 ^ *v2) & 0x80 ){
  73608. /* The two values have different signs */
  73609. res = (*v1 & 0x80) ? -1 : +1;
  73610. }else{
  73611. /* The two values have the same sign. Compare using memcmp(). */
  73612. static const u8 aLen[] = {0, 1, 2, 3, 4, 6, 8 };
  73613. int i;
  73614. res = 0;
  73615. for(i=0; i<aLen[s1]; i++){
  73616. if( (res = v1[i] - v2[i]) ) break;
  73617. }
  73618. }
  73619. }else{
  73620. if( s2>7 ){
  73621. res = +1;
  73622. }else if( s1>7 ){
  73623. res = -1;
  73624. }else{
  73625. res = s1 - s2;
  73626. }
  73627. assert( res!=0 );
  73628. if( res>0 ){
  73629. if( *v1 & 0x80 ) res = -1;
  73630. }else{
  73631. if( *v2 & 0x80 ) res = +1;
  73632. }
  73633. }
  73634. }
  73635. if( res==0 ){
  73636. if( pTask->pSorter->pKeyInfo->nField>1 ){
  73637. res = vdbeSorterCompareTail(
  73638. pTask, pbKey2Cached, pKey1, nKey1, pKey2, nKey2
  73639. );
  73640. }
  73641. }else if( pTask->pSorter->pKeyInfo->aSortOrder[0] ){
  73642. res = res * -1;
  73643. }
  73644. return res;
  73645. }
  73646. /*
  73647. ** Initialize the temporary index cursor just opened as a sorter cursor.
  73648. **
  73649. ** Usually, the sorter module uses the value of (pCsr->pKeyInfo->nField)
  73650. ** to determine the number of fields that should be compared from the
  73651. ** records being sorted. However, if the value passed as argument nField
  73652. ** is non-zero and the sorter is able to guarantee a stable sort, nField
  73653. ** is used instead. This is used when sorting records for a CREATE INDEX
  73654. ** statement. In this case, keys are always delivered to the sorter in
  73655. ** order of the primary key, which happens to be make up the final part
  73656. ** of the records being sorted. So if the sort is stable, there is never
  73657. ** any reason to compare PK fields and they can be ignored for a small
  73658. ** performance boost.
  73659. **
  73660. ** The sorter can guarantee a stable sort when running in single-threaded
  73661. ** mode, but not in multi-threaded mode.
  73662. **
  73663. ** SQLITE_OK is returned if successful, or an SQLite error code otherwise.
  73664. */
  73665. SQLITE_PRIVATE int sqlite3VdbeSorterInit(
  73666. sqlite3 *db, /* Database connection (for malloc()) */
  73667. int nField, /* Number of key fields in each record */
  73668. VdbeCursor *pCsr /* Cursor that holds the new sorter */
  73669. ){
  73670. int pgsz; /* Page size of main database */
  73671. int i; /* Used to iterate through aTask[] */
  73672. int mxCache; /* Cache size */
  73673. VdbeSorter *pSorter; /* The new sorter */
  73674. KeyInfo *pKeyInfo; /* Copy of pCsr->pKeyInfo with db==0 */
  73675. int szKeyInfo; /* Size of pCsr->pKeyInfo in bytes */
  73676. int sz; /* Size of pSorter in bytes */
  73677. int rc = SQLITE_OK;
  73678. #if SQLITE_MAX_WORKER_THREADS==0
  73679. # define nWorker 0
  73680. #else
  73681. int nWorker;
  73682. #endif
  73683. /* Initialize the upper limit on the number of worker threads */
  73684. #if SQLITE_MAX_WORKER_THREADS>0
  73685. if( sqlite3TempInMemory(db) || sqlite3GlobalConfig.bCoreMutex==0 ){
  73686. nWorker = 0;
  73687. }else{
  73688. nWorker = db->aLimit[SQLITE_LIMIT_WORKER_THREADS];
  73689. }
  73690. #endif
  73691. /* Do not allow the total number of threads (main thread + all workers)
  73692. ** to exceed the maximum merge count */
  73693. #if SQLITE_MAX_WORKER_THREADS>=SORTER_MAX_MERGE_COUNT
  73694. if( nWorker>=SORTER_MAX_MERGE_COUNT ){
  73695. nWorker = SORTER_MAX_MERGE_COUNT-1;
  73696. }
  73697. #endif
  73698. assert( pCsr->pKeyInfo && pCsr->pBt==0 );
  73699. szKeyInfo = sizeof(KeyInfo) + (pCsr->pKeyInfo->nField-1)*sizeof(CollSeq*);
  73700. sz = sizeof(VdbeSorter) + nWorker * sizeof(SortSubtask);
  73701. pSorter = (VdbeSorter*)sqlite3DbMallocZero(db, sz + szKeyInfo);
  73702. pCsr->pSorter = pSorter;
  73703. if( pSorter==0 ){
  73704. rc = SQLITE_NOMEM;
  73705. }else{
  73706. pSorter->pKeyInfo = pKeyInfo = (KeyInfo*)((u8*)pSorter + sz);
  73707. memcpy(pKeyInfo, pCsr->pKeyInfo, szKeyInfo);
  73708. pKeyInfo->db = 0;
  73709. if( nField && nWorker==0 ){
  73710. pKeyInfo->nXField += (pKeyInfo->nField - nField);
  73711. pKeyInfo->nField = nField;
  73712. }
  73713. pSorter->pgsz = pgsz = sqlite3BtreeGetPageSize(db->aDb[0].pBt);
  73714. pSorter->nTask = nWorker + 1;
  73715. pSorter->iPrev = nWorker-1;
  73716. pSorter->bUseThreads = (pSorter->nTask>1);
  73717. pSorter->db = db;
  73718. for(i=0; i<pSorter->nTask; i++){
  73719. SortSubtask *pTask = &pSorter->aTask[i];
  73720. pTask->pSorter = pSorter;
  73721. }
  73722. if( !sqlite3TempInMemory(db) ){
  73723. u32 szPma = sqlite3GlobalConfig.szPma;
  73724. pSorter->mnPmaSize = szPma * pgsz;
  73725. mxCache = db->aDb[0].pSchema->cache_size;
  73726. if( mxCache<(int)szPma ) mxCache = (int)szPma;
  73727. pSorter->mxPmaSize = MIN((i64)mxCache*pgsz, SQLITE_MAX_PMASZ);
  73728. /* EVIDENCE-OF: R-26747-61719 When the application provides any amount of
  73729. ** scratch memory using SQLITE_CONFIG_SCRATCH, SQLite avoids unnecessary
  73730. ** large heap allocations.
  73731. */
  73732. if( sqlite3GlobalConfig.pScratch==0 ){
  73733. assert( pSorter->iMemory==0 );
  73734. pSorter->nMemory = pgsz;
  73735. pSorter->list.aMemory = (u8*)sqlite3Malloc(pgsz);
  73736. if( !pSorter->list.aMemory ) rc = SQLITE_NOMEM;
  73737. }
  73738. }
  73739. if( (pKeyInfo->nField+pKeyInfo->nXField)<13
  73740. && (pKeyInfo->aColl[0]==0 || pKeyInfo->aColl[0]==db->pDfltColl)
  73741. ){
  73742. pSorter->typeMask = SORTER_TYPE_INTEGER | SORTER_TYPE_TEXT;
  73743. }
  73744. }
  73745. return rc;
  73746. }
  73747. #undef nWorker /* Defined at the top of this function */
  73748. /*
  73749. ** Free the list of sorted records starting at pRecord.
  73750. */
  73751. static void vdbeSorterRecordFree(sqlite3 *db, SorterRecord *pRecord){
  73752. SorterRecord *p;
  73753. SorterRecord *pNext;
  73754. for(p=pRecord; p; p=pNext){
  73755. pNext = p->u.pNext;
  73756. sqlite3DbFree(db, p);
  73757. }
  73758. }
  73759. /*
  73760. ** Free all resources owned by the object indicated by argument pTask. All
  73761. ** fields of *pTask are zeroed before returning.
  73762. */
  73763. static void vdbeSortSubtaskCleanup(sqlite3 *db, SortSubtask *pTask){
  73764. sqlite3DbFree(db, pTask->pUnpacked);
  73765. #if SQLITE_MAX_WORKER_THREADS>0
  73766. /* pTask->list.aMemory can only be non-zero if it was handed memory
  73767. ** from the main thread. That only occurs SQLITE_MAX_WORKER_THREADS>0 */
  73768. if( pTask->list.aMemory ){
  73769. sqlite3_free(pTask->list.aMemory);
  73770. }else
  73771. #endif
  73772. {
  73773. assert( pTask->list.aMemory==0 );
  73774. vdbeSorterRecordFree(0, pTask->list.pList);
  73775. }
  73776. if( pTask->file.pFd ){
  73777. sqlite3OsCloseFree(pTask->file.pFd);
  73778. }
  73779. if( pTask->file2.pFd ){
  73780. sqlite3OsCloseFree(pTask->file2.pFd);
  73781. }
  73782. memset(pTask, 0, sizeof(SortSubtask));
  73783. }
  73784. #ifdef SQLITE_DEBUG_SORTER_THREADS
  73785. static void vdbeSorterWorkDebug(SortSubtask *pTask, const char *zEvent){
  73786. i64 t;
  73787. int iTask = (pTask - pTask->pSorter->aTask);
  73788. sqlite3OsCurrentTimeInt64(pTask->pSorter->db->pVfs, &t);
  73789. fprintf(stderr, "%lld:%d %s\n", t, iTask, zEvent);
  73790. }
  73791. static void vdbeSorterRewindDebug(const char *zEvent){
  73792. i64 t;
  73793. sqlite3OsCurrentTimeInt64(sqlite3_vfs_find(0), &t);
  73794. fprintf(stderr, "%lld:X %s\n", t, zEvent);
  73795. }
  73796. static void vdbeSorterPopulateDebug(
  73797. SortSubtask *pTask,
  73798. const char *zEvent
  73799. ){
  73800. i64 t;
  73801. int iTask = (pTask - pTask->pSorter->aTask);
  73802. sqlite3OsCurrentTimeInt64(pTask->pSorter->db->pVfs, &t);
  73803. fprintf(stderr, "%lld:bg%d %s\n", t, iTask, zEvent);
  73804. }
  73805. static void vdbeSorterBlockDebug(
  73806. SortSubtask *pTask,
  73807. int bBlocked,
  73808. const char *zEvent
  73809. ){
  73810. if( bBlocked ){
  73811. i64 t;
  73812. sqlite3OsCurrentTimeInt64(pTask->pSorter->db->pVfs, &t);
  73813. fprintf(stderr, "%lld:main %s\n", t, zEvent);
  73814. }
  73815. }
  73816. #else
  73817. # define vdbeSorterWorkDebug(x,y)
  73818. # define vdbeSorterRewindDebug(y)
  73819. # define vdbeSorterPopulateDebug(x,y)
  73820. # define vdbeSorterBlockDebug(x,y,z)
  73821. #endif
  73822. #if SQLITE_MAX_WORKER_THREADS>0
  73823. /*
  73824. ** Join thread pTask->thread.
  73825. */
  73826. static int vdbeSorterJoinThread(SortSubtask *pTask){
  73827. int rc = SQLITE_OK;
  73828. if( pTask->pThread ){
  73829. #ifdef SQLITE_DEBUG_SORTER_THREADS
  73830. int bDone = pTask->bDone;
  73831. #endif
  73832. void *pRet = SQLITE_INT_TO_PTR(SQLITE_ERROR);
  73833. vdbeSorterBlockDebug(pTask, !bDone, "enter");
  73834. (void)sqlite3ThreadJoin(pTask->pThread, &pRet);
  73835. vdbeSorterBlockDebug(pTask, !bDone, "exit");
  73836. rc = SQLITE_PTR_TO_INT(pRet);
  73837. assert( pTask->bDone==1 );
  73838. pTask->bDone = 0;
  73839. pTask->pThread = 0;
  73840. }
  73841. return rc;
  73842. }
  73843. /*
  73844. ** Launch a background thread to run xTask(pIn).
  73845. */
  73846. static int vdbeSorterCreateThread(
  73847. SortSubtask *pTask, /* Thread will use this task object */
  73848. void *(*xTask)(void*), /* Routine to run in a separate thread */
  73849. void *pIn /* Argument passed into xTask() */
  73850. ){
  73851. assert( pTask->pThread==0 && pTask->bDone==0 );
  73852. return sqlite3ThreadCreate(&pTask->pThread, xTask, pIn);
  73853. }
  73854. /*
  73855. ** Join all outstanding threads launched by SorterWrite() to create
  73856. ** level-0 PMAs.
  73857. */
  73858. static int vdbeSorterJoinAll(VdbeSorter *pSorter, int rcin){
  73859. int rc = rcin;
  73860. int i;
  73861. /* This function is always called by the main user thread.
  73862. **
  73863. ** If this function is being called after SorterRewind() has been called,
  73864. ** it is possible that thread pSorter->aTask[pSorter->nTask-1].pThread
  73865. ** is currently attempt to join one of the other threads. To avoid a race
  73866. ** condition where this thread also attempts to join the same object, join
  73867. ** thread pSorter->aTask[pSorter->nTask-1].pThread first. */
  73868. for(i=pSorter->nTask-1; i>=0; i--){
  73869. SortSubtask *pTask = &pSorter->aTask[i];
  73870. int rc2 = vdbeSorterJoinThread(pTask);
  73871. if( rc==SQLITE_OK ) rc = rc2;
  73872. }
  73873. return rc;
  73874. }
  73875. #else
  73876. # define vdbeSorterJoinAll(x,rcin) (rcin)
  73877. # define vdbeSorterJoinThread(pTask) SQLITE_OK
  73878. #endif
  73879. /*
  73880. ** Allocate a new MergeEngine object capable of handling up to
  73881. ** nReader PmaReader inputs.
  73882. **
  73883. ** nReader is automatically rounded up to the next power of two.
  73884. ** nReader may not exceed SORTER_MAX_MERGE_COUNT even after rounding up.
  73885. */
  73886. static MergeEngine *vdbeMergeEngineNew(int nReader){
  73887. int N = 2; /* Smallest power of two >= nReader */
  73888. int nByte; /* Total bytes of space to allocate */
  73889. MergeEngine *pNew; /* Pointer to allocated object to return */
  73890. assert( nReader<=SORTER_MAX_MERGE_COUNT );
  73891. while( N<nReader ) N += N;
  73892. nByte = sizeof(MergeEngine) + N * (sizeof(int) + sizeof(PmaReader));
  73893. pNew = sqlite3FaultSim(100) ? 0 : (MergeEngine*)sqlite3MallocZero(nByte);
  73894. if( pNew ){
  73895. pNew->nTree = N;
  73896. pNew->pTask = 0;
  73897. pNew->aReadr = (PmaReader*)&pNew[1];
  73898. pNew->aTree = (int*)&pNew->aReadr[N];
  73899. }
  73900. return pNew;
  73901. }
  73902. /*
  73903. ** Free the MergeEngine object passed as the only argument.
  73904. */
  73905. static void vdbeMergeEngineFree(MergeEngine *pMerger){
  73906. int i;
  73907. if( pMerger ){
  73908. for(i=0; i<pMerger->nTree; i++){
  73909. vdbePmaReaderClear(&pMerger->aReadr[i]);
  73910. }
  73911. }
  73912. sqlite3_free(pMerger);
  73913. }
  73914. /*
  73915. ** Free all resources associated with the IncrMerger object indicated by
  73916. ** the first argument.
  73917. */
  73918. static void vdbeIncrFree(IncrMerger *pIncr){
  73919. if( pIncr ){
  73920. #if SQLITE_MAX_WORKER_THREADS>0
  73921. if( pIncr->bUseThread ){
  73922. vdbeSorterJoinThread(pIncr->pTask);
  73923. if( pIncr->aFile[0].pFd ) sqlite3OsCloseFree(pIncr->aFile[0].pFd);
  73924. if( pIncr->aFile[1].pFd ) sqlite3OsCloseFree(pIncr->aFile[1].pFd);
  73925. }
  73926. #endif
  73927. vdbeMergeEngineFree(pIncr->pMerger);
  73928. sqlite3_free(pIncr);
  73929. }
  73930. }
  73931. /*
  73932. ** Reset a sorting cursor back to its original empty state.
  73933. */
  73934. SQLITE_PRIVATE void sqlite3VdbeSorterReset(sqlite3 *db, VdbeSorter *pSorter){
  73935. int i;
  73936. (void)vdbeSorterJoinAll(pSorter, SQLITE_OK);
  73937. assert( pSorter->bUseThreads || pSorter->pReader==0 );
  73938. #if SQLITE_MAX_WORKER_THREADS>0
  73939. if( pSorter->pReader ){
  73940. vdbePmaReaderClear(pSorter->pReader);
  73941. sqlite3DbFree(db, pSorter->pReader);
  73942. pSorter->pReader = 0;
  73943. }
  73944. #endif
  73945. vdbeMergeEngineFree(pSorter->pMerger);
  73946. pSorter->pMerger = 0;
  73947. for(i=0; i<pSorter->nTask; i++){
  73948. SortSubtask *pTask = &pSorter->aTask[i];
  73949. vdbeSortSubtaskCleanup(db, pTask);
  73950. pTask->pSorter = pSorter;
  73951. }
  73952. if( pSorter->list.aMemory==0 ){
  73953. vdbeSorterRecordFree(0, pSorter->list.pList);
  73954. }
  73955. pSorter->list.pList = 0;
  73956. pSorter->list.szPMA = 0;
  73957. pSorter->bUsePMA = 0;
  73958. pSorter->iMemory = 0;
  73959. pSorter->mxKeysize = 0;
  73960. sqlite3DbFree(db, pSorter->pUnpacked);
  73961. pSorter->pUnpacked = 0;
  73962. }
  73963. /*
  73964. ** Free any cursor components allocated by sqlite3VdbeSorterXXX routines.
  73965. */
  73966. SQLITE_PRIVATE void sqlite3VdbeSorterClose(sqlite3 *db, VdbeCursor *pCsr){
  73967. VdbeSorter *pSorter = pCsr->pSorter;
  73968. if( pSorter ){
  73969. sqlite3VdbeSorterReset(db, pSorter);
  73970. sqlite3_free(pSorter->list.aMemory);
  73971. sqlite3DbFree(db, pSorter);
  73972. pCsr->pSorter = 0;
  73973. }
  73974. }
  73975. #if SQLITE_MAX_MMAP_SIZE>0
  73976. /*
  73977. ** The first argument is a file-handle open on a temporary file. The file
  73978. ** is guaranteed to be nByte bytes or smaller in size. This function
  73979. ** attempts to extend the file to nByte bytes in size and to ensure that
  73980. ** the VFS has memory mapped it.
  73981. **
  73982. ** Whether or not the file does end up memory mapped of course depends on
  73983. ** the specific VFS implementation.
  73984. */
  73985. static void vdbeSorterExtendFile(sqlite3 *db, sqlite3_file *pFd, i64 nByte){
  73986. if( nByte<=(i64)(db->nMaxSorterMmap) && pFd->pMethods->iVersion>=3 ){
  73987. void *p = 0;
  73988. int chunksize = 4*1024;
  73989. sqlite3OsFileControlHint(pFd, SQLITE_FCNTL_CHUNK_SIZE, &chunksize);
  73990. sqlite3OsFileControlHint(pFd, SQLITE_FCNTL_SIZE_HINT, &nByte);
  73991. sqlite3OsFetch(pFd, 0, (int)nByte, &p);
  73992. sqlite3OsUnfetch(pFd, 0, p);
  73993. }
  73994. }
  73995. #else
  73996. # define vdbeSorterExtendFile(x,y,z)
  73997. #endif
  73998. /*
  73999. ** Allocate space for a file-handle and open a temporary file. If successful,
  74000. ** set *ppFd to point to the malloc'd file-handle and return SQLITE_OK.
  74001. ** Otherwise, set *ppFd to 0 and return an SQLite error code.
  74002. */
  74003. static int vdbeSorterOpenTempFile(
  74004. sqlite3 *db, /* Database handle doing sort */
  74005. i64 nExtend, /* Attempt to extend file to this size */
  74006. sqlite3_file **ppFd
  74007. ){
  74008. int rc;
  74009. if( sqlite3FaultSim(202) ) return SQLITE_IOERR_ACCESS;
  74010. rc = sqlite3OsOpenMalloc(db->pVfs, 0, ppFd,
  74011. SQLITE_OPEN_TEMP_JOURNAL |
  74012. SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE |
  74013. SQLITE_OPEN_EXCLUSIVE | SQLITE_OPEN_DELETEONCLOSE, &rc
  74014. );
  74015. if( rc==SQLITE_OK ){
  74016. i64 max = SQLITE_MAX_MMAP_SIZE;
  74017. sqlite3OsFileControlHint(*ppFd, SQLITE_FCNTL_MMAP_SIZE, (void*)&max);
  74018. if( nExtend>0 ){
  74019. vdbeSorterExtendFile(db, *ppFd, nExtend);
  74020. }
  74021. }
  74022. return rc;
  74023. }
  74024. /*
  74025. ** If it has not already been allocated, allocate the UnpackedRecord
  74026. ** structure at pTask->pUnpacked. Return SQLITE_OK if successful (or
  74027. ** if no allocation was required), or SQLITE_NOMEM otherwise.
  74028. */
  74029. static int vdbeSortAllocUnpacked(SortSubtask *pTask){
  74030. if( pTask->pUnpacked==0 ){
  74031. char *pFree;
  74032. pTask->pUnpacked = sqlite3VdbeAllocUnpackedRecord(
  74033. pTask->pSorter->pKeyInfo, 0, 0, &pFree
  74034. );
  74035. assert( pTask->pUnpacked==(UnpackedRecord*)pFree );
  74036. if( pFree==0 ) return SQLITE_NOMEM;
  74037. pTask->pUnpacked->nField = pTask->pSorter->pKeyInfo->nField;
  74038. pTask->pUnpacked->errCode = 0;
  74039. }
  74040. return SQLITE_OK;
  74041. }
  74042. /*
  74043. ** Merge the two sorted lists p1 and p2 into a single list.
  74044. ** Set *ppOut to the head of the new list.
  74045. */
  74046. static void vdbeSorterMerge(
  74047. SortSubtask *pTask, /* Calling thread context */
  74048. SorterRecord *p1, /* First list to merge */
  74049. SorterRecord *p2, /* Second list to merge */
  74050. SorterRecord **ppOut /* OUT: Head of merged list */
  74051. ){
  74052. SorterRecord *pFinal = 0;
  74053. SorterRecord **pp = &pFinal;
  74054. int bCached = 0;
  74055. while( p1 && p2 ){
  74056. int res;
  74057. res = pTask->xCompare(
  74058. pTask, &bCached, SRVAL(p1), p1->nVal, SRVAL(p2), p2->nVal
  74059. );
  74060. if( res<=0 ){
  74061. *pp = p1;
  74062. pp = &p1->u.pNext;
  74063. p1 = p1->u.pNext;
  74064. }else{
  74065. *pp = p2;
  74066. pp = &p2->u.pNext;
  74067. p2 = p2->u.pNext;
  74068. bCached = 0;
  74069. }
  74070. }
  74071. *pp = p1 ? p1 : p2;
  74072. *ppOut = pFinal;
  74073. }
  74074. /*
  74075. ** Return the SorterCompare function to compare values collected by the
  74076. ** sorter object passed as the only argument.
  74077. */
  74078. static SorterCompare vdbeSorterGetCompare(VdbeSorter *p){
  74079. if( p->typeMask==SORTER_TYPE_INTEGER ){
  74080. return vdbeSorterCompareInt;
  74081. }else if( p->typeMask==SORTER_TYPE_TEXT ){
  74082. return vdbeSorterCompareText;
  74083. }
  74084. return vdbeSorterCompare;
  74085. }
  74086. /*
  74087. ** Sort the linked list of records headed at pTask->pList. Return
  74088. ** SQLITE_OK if successful, or an SQLite error code (i.e. SQLITE_NOMEM) if
  74089. ** an error occurs.
  74090. */
  74091. static int vdbeSorterSort(SortSubtask *pTask, SorterList *pList){
  74092. int i;
  74093. SorterRecord **aSlot;
  74094. SorterRecord *p;
  74095. int rc;
  74096. rc = vdbeSortAllocUnpacked(pTask);
  74097. if( rc!=SQLITE_OK ) return rc;
  74098. p = pList->pList;
  74099. pTask->xCompare = vdbeSorterGetCompare(pTask->pSorter);
  74100. aSlot = (SorterRecord **)sqlite3MallocZero(64 * sizeof(SorterRecord *));
  74101. if( !aSlot ){
  74102. return SQLITE_NOMEM;
  74103. }
  74104. while( p ){
  74105. SorterRecord *pNext;
  74106. if( pList->aMemory ){
  74107. if( (u8*)p==pList->aMemory ){
  74108. pNext = 0;
  74109. }else{
  74110. assert( p->u.iNext<sqlite3MallocSize(pList->aMemory) );
  74111. pNext = (SorterRecord*)&pList->aMemory[p->u.iNext];
  74112. }
  74113. }else{
  74114. pNext = p->u.pNext;
  74115. }
  74116. p->u.pNext = 0;
  74117. for(i=0; aSlot[i]; i++){
  74118. vdbeSorterMerge(pTask, p, aSlot[i], &p);
  74119. aSlot[i] = 0;
  74120. }
  74121. aSlot[i] = p;
  74122. p = pNext;
  74123. }
  74124. p = 0;
  74125. for(i=0; i<64; i++){
  74126. vdbeSorterMerge(pTask, p, aSlot[i], &p);
  74127. }
  74128. pList->pList = p;
  74129. sqlite3_free(aSlot);
  74130. assert( pTask->pUnpacked->errCode==SQLITE_OK
  74131. || pTask->pUnpacked->errCode==SQLITE_NOMEM
  74132. );
  74133. return pTask->pUnpacked->errCode;
  74134. }
  74135. /*
  74136. ** Initialize a PMA-writer object.
  74137. */
  74138. static void vdbePmaWriterInit(
  74139. sqlite3_file *pFd, /* File handle to write to */
  74140. PmaWriter *p, /* Object to populate */
  74141. int nBuf, /* Buffer size */
  74142. i64 iStart /* Offset of pFd to begin writing at */
  74143. ){
  74144. memset(p, 0, sizeof(PmaWriter));
  74145. p->aBuffer = (u8*)sqlite3Malloc(nBuf);
  74146. if( !p->aBuffer ){
  74147. p->eFWErr = SQLITE_NOMEM;
  74148. }else{
  74149. p->iBufEnd = p->iBufStart = (iStart % nBuf);
  74150. p->iWriteOff = iStart - p->iBufStart;
  74151. p->nBuffer = nBuf;
  74152. p->pFd = pFd;
  74153. }
  74154. }
  74155. /*
  74156. ** Write nData bytes of data to the PMA. Return SQLITE_OK
  74157. ** if successful, or an SQLite error code if an error occurs.
  74158. */
  74159. static void vdbePmaWriteBlob(PmaWriter *p, u8 *pData, int nData){
  74160. int nRem = nData;
  74161. while( nRem>0 && p->eFWErr==0 ){
  74162. int nCopy = nRem;
  74163. if( nCopy>(p->nBuffer - p->iBufEnd) ){
  74164. nCopy = p->nBuffer - p->iBufEnd;
  74165. }
  74166. memcpy(&p->aBuffer[p->iBufEnd], &pData[nData-nRem], nCopy);
  74167. p->iBufEnd += nCopy;
  74168. if( p->iBufEnd==p->nBuffer ){
  74169. p->eFWErr = sqlite3OsWrite(p->pFd,
  74170. &p->aBuffer[p->iBufStart], p->iBufEnd - p->iBufStart,
  74171. p->iWriteOff + p->iBufStart
  74172. );
  74173. p->iBufStart = p->iBufEnd = 0;
  74174. p->iWriteOff += p->nBuffer;
  74175. }
  74176. assert( p->iBufEnd<p->nBuffer );
  74177. nRem -= nCopy;
  74178. }
  74179. }
  74180. /*
  74181. ** Flush any buffered data to disk and clean up the PMA-writer object.
  74182. ** The results of using the PMA-writer after this call are undefined.
  74183. ** Return SQLITE_OK if flushing the buffered data succeeds or is not
  74184. ** required. Otherwise, return an SQLite error code.
  74185. **
  74186. ** Before returning, set *piEof to the offset immediately following the
  74187. ** last byte written to the file.
  74188. */
  74189. static int vdbePmaWriterFinish(PmaWriter *p, i64 *piEof){
  74190. int rc;
  74191. if( p->eFWErr==0 && ALWAYS(p->aBuffer) && p->iBufEnd>p->iBufStart ){
  74192. p->eFWErr = sqlite3OsWrite(p->pFd,
  74193. &p->aBuffer[p->iBufStart], p->iBufEnd - p->iBufStart,
  74194. p->iWriteOff + p->iBufStart
  74195. );
  74196. }
  74197. *piEof = (p->iWriteOff + p->iBufEnd);
  74198. sqlite3_free(p->aBuffer);
  74199. rc = p->eFWErr;
  74200. memset(p, 0, sizeof(PmaWriter));
  74201. return rc;
  74202. }
  74203. /*
  74204. ** Write value iVal encoded as a varint to the PMA. Return
  74205. ** SQLITE_OK if successful, or an SQLite error code if an error occurs.
  74206. */
  74207. static void vdbePmaWriteVarint(PmaWriter *p, u64 iVal){
  74208. int nByte;
  74209. u8 aByte[10];
  74210. nByte = sqlite3PutVarint(aByte, iVal);
  74211. vdbePmaWriteBlob(p, aByte, nByte);
  74212. }
  74213. /*
  74214. ** Write the current contents of in-memory linked-list pList to a level-0
  74215. ** PMA in the temp file belonging to sub-task pTask. Return SQLITE_OK if
  74216. ** successful, or an SQLite error code otherwise.
  74217. **
  74218. ** The format of a PMA is:
  74219. **
  74220. ** * A varint. This varint contains the total number of bytes of content
  74221. ** in the PMA (not including the varint itself).
  74222. **
  74223. ** * One or more records packed end-to-end in order of ascending keys.
  74224. ** Each record consists of a varint followed by a blob of data (the
  74225. ** key). The varint is the number of bytes in the blob of data.
  74226. */
  74227. static int vdbeSorterListToPMA(SortSubtask *pTask, SorterList *pList){
  74228. sqlite3 *db = pTask->pSorter->db;
  74229. int rc = SQLITE_OK; /* Return code */
  74230. PmaWriter writer; /* Object used to write to the file */
  74231. #ifdef SQLITE_DEBUG
  74232. /* Set iSz to the expected size of file pTask->file after writing the PMA.
  74233. ** This is used by an assert() statement at the end of this function. */
  74234. i64 iSz = pList->szPMA + sqlite3VarintLen(pList->szPMA) + pTask->file.iEof;
  74235. #endif
  74236. vdbeSorterWorkDebug(pTask, "enter");
  74237. memset(&writer, 0, sizeof(PmaWriter));
  74238. assert( pList->szPMA>0 );
  74239. /* If the first temporary PMA file has not been opened, open it now. */
  74240. if( pTask->file.pFd==0 ){
  74241. rc = vdbeSorterOpenTempFile(db, 0, &pTask->file.pFd);
  74242. assert( rc!=SQLITE_OK || pTask->file.pFd );
  74243. assert( pTask->file.iEof==0 );
  74244. assert( pTask->nPMA==0 );
  74245. }
  74246. /* Try to get the file to memory map */
  74247. if( rc==SQLITE_OK ){
  74248. vdbeSorterExtendFile(db, pTask->file.pFd, pTask->file.iEof+pList->szPMA+9);
  74249. }
  74250. /* Sort the list */
  74251. if( rc==SQLITE_OK ){
  74252. rc = vdbeSorterSort(pTask, pList);
  74253. }
  74254. if( rc==SQLITE_OK ){
  74255. SorterRecord *p;
  74256. SorterRecord *pNext = 0;
  74257. vdbePmaWriterInit(pTask->file.pFd, &writer, pTask->pSorter->pgsz,
  74258. pTask->file.iEof);
  74259. pTask->nPMA++;
  74260. vdbePmaWriteVarint(&writer, pList->szPMA);
  74261. for(p=pList->pList; p; p=pNext){
  74262. pNext = p->u.pNext;
  74263. vdbePmaWriteVarint(&writer, p->nVal);
  74264. vdbePmaWriteBlob(&writer, SRVAL(p), p->nVal);
  74265. if( pList->aMemory==0 ) sqlite3_free(p);
  74266. }
  74267. pList->pList = p;
  74268. rc = vdbePmaWriterFinish(&writer, &pTask->file.iEof);
  74269. }
  74270. vdbeSorterWorkDebug(pTask, "exit");
  74271. assert( rc!=SQLITE_OK || pList->pList==0 );
  74272. assert( rc!=SQLITE_OK || pTask->file.iEof==iSz );
  74273. return rc;
  74274. }
  74275. /*
  74276. ** Advance the MergeEngine to its next entry.
  74277. ** Set *pbEof to true there is no next entry because
  74278. ** the MergeEngine has reached the end of all its inputs.
  74279. **
  74280. ** Return SQLITE_OK if successful or an error code if an error occurs.
  74281. */
  74282. static int vdbeMergeEngineStep(
  74283. MergeEngine *pMerger, /* The merge engine to advance to the next row */
  74284. int *pbEof /* Set TRUE at EOF. Set false for more content */
  74285. ){
  74286. int rc;
  74287. int iPrev = pMerger->aTree[1];/* Index of PmaReader to advance */
  74288. SortSubtask *pTask = pMerger->pTask;
  74289. /* Advance the current PmaReader */
  74290. rc = vdbePmaReaderNext(&pMerger->aReadr[iPrev]);
  74291. /* Update contents of aTree[] */
  74292. if( rc==SQLITE_OK ){
  74293. int i; /* Index of aTree[] to recalculate */
  74294. PmaReader *pReadr1; /* First PmaReader to compare */
  74295. PmaReader *pReadr2; /* Second PmaReader to compare */
  74296. int bCached = 0;
  74297. /* Find the first two PmaReaders to compare. The one that was just
  74298. ** advanced (iPrev) and the one next to it in the array. */
  74299. pReadr1 = &pMerger->aReadr[(iPrev & 0xFFFE)];
  74300. pReadr2 = &pMerger->aReadr[(iPrev | 0x0001)];
  74301. for(i=(pMerger->nTree+iPrev)/2; i>0; i=i/2){
  74302. /* Compare pReadr1 and pReadr2. Store the result in variable iRes. */
  74303. int iRes;
  74304. if( pReadr1->pFd==0 ){
  74305. iRes = +1;
  74306. }else if( pReadr2->pFd==0 ){
  74307. iRes = -1;
  74308. }else{
  74309. iRes = pTask->xCompare(pTask, &bCached,
  74310. pReadr1->aKey, pReadr1->nKey, pReadr2->aKey, pReadr2->nKey
  74311. );
  74312. }
  74313. /* If pReadr1 contained the smaller value, set aTree[i] to its index.
  74314. ** Then set pReadr2 to the next PmaReader to compare to pReadr1. In this
  74315. ** case there is no cache of pReadr2 in pTask->pUnpacked, so set
  74316. ** pKey2 to point to the record belonging to pReadr2.
  74317. **
  74318. ** Alternatively, if pReadr2 contains the smaller of the two values,
  74319. ** set aTree[i] to its index and update pReadr1. If vdbeSorterCompare()
  74320. ** was actually called above, then pTask->pUnpacked now contains
  74321. ** a value equivalent to pReadr2. So set pKey2 to NULL to prevent
  74322. ** vdbeSorterCompare() from decoding pReadr2 again.
  74323. **
  74324. ** If the two values were equal, then the value from the oldest
  74325. ** PMA should be considered smaller. The VdbeSorter.aReadr[] array
  74326. ** is sorted from oldest to newest, so pReadr1 contains older values
  74327. ** than pReadr2 iff (pReadr1<pReadr2). */
  74328. if( iRes<0 || (iRes==0 && pReadr1<pReadr2) ){
  74329. pMerger->aTree[i] = (int)(pReadr1 - pMerger->aReadr);
  74330. pReadr2 = &pMerger->aReadr[ pMerger->aTree[i ^ 0x0001] ];
  74331. bCached = 0;
  74332. }else{
  74333. if( pReadr1->pFd ) bCached = 0;
  74334. pMerger->aTree[i] = (int)(pReadr2 - pMerger->aReadr);
  74335. pReadr1 = &pMerger->aReadr[ pMerger->aTree[i ^ 0x0001] ];
  74336. }
  74337. }
  74338. *pbEof = (pMerger->aReadr[pMerger->aTree[1]].pFd==0);
  74339. }
  74340. return (rc==SQLITE_OK ? pTask->pUnpacked->errCode : rc);
  74341. }
  74342. #if SQLITE_MAX_WORKER_THREADS>0
  74343. /*
  74344. ** The main routine for background threads that write level-0 PMAs.
  74345. */
  74346. static void *vdbeSorterFlushThread(void *pCtx){
  74347. SortSubtask *pTask = (SortSubtask*)pCtx;
  74348. int rc; /* Return code */
  74349. assert( pTask->bDone==0 );
  74350. rc = vdbeSorterListToPMA(pTask, &pTask->list);
  74351. pTask->bDone = 1;
  74352. return SQLITE_INT_TO_PTR(rc);
  74353. }
  74354. #endif /* SQLITE_MAX_WORKER_THREADS>0 */
  74355. /*
  74356. ** Flush the current contents of VdbeSorter.list to a new PMA, possibly
  74357. ** using a background thread.
  74358. */
  74359. static int vdbeSorterFlushPMA(VdbeSorter *pSorter){
  74360. #if SQLITE_MAX_WORKER_THREADS==0
  74361. pSorter->bUsePMA = 1;
  74362. return vdbeSorterListToPMA(&pSorter->aTask[0], &pSorter->list);
  74363. #else
  74364. int rc = SQLITE_OK;
  74365. int i;
  74366. SortSubtask *pTask = 0; /* Thread context used to create new PMA */
  74367. int nWorker = (pSorter->nTask-1);
  74368. /* Set the flag to indicate that at least one PMA has been written.
  74369. ** Or will be, anyhow. */
  74370. pSorter->bUsePMA = 1;
  74371. /* Select a sub-task to sort and flush the current list of in-memory
  74372. ** records to disk. If the sorter is running in multi-threaded mode,
  74373. ** round-robin between the first (pSorter->nTask-1) tasks. Except, if
  74374. ** the background thread from a sub-tasks previous turn is still running,
  74375. ** skip it. If the first (pSorter->nTask-1) sub-tasks are all still busy,
  74376. ** fall back to using the final sub-task. The first (pSorter->nTask-1)
  74377. ** sub-tasks are prefered as they use background threads - the final
  74378. ** sub-task uses the main thread. */
  74379. for(i=0; i<nWorker; i++){
  74380. int iTest = (pSorter->iPrev + i + 1) % nWorker;
  74381. pTask = &pSorter->aTask[iTest];
  74382. if( pTask->bDone ){
  74383. rc = vdbeSorterJoinThread(pTask);
  74384. }
  74385. if( rc!=SQLITE_OK || pTask->pThread==0 ) break;
  74386. }
  74387. if( rc==SQLITE_OK ){
  74388. if( i==nWorker ){
  74389. /* Use the foreground thread for this operation */
  74390. rc = vdbeSorterListToPMA(&pSorter->aTask[nWorker], &pSorter->list);
  74391. }else{
  74392. /* Launch a background thread for this operation */
  74393. u8 *aMem = pTask->list.aMemory;
  74394. void *pCtx = (void*)pTask;
  74395. assert( pTask->pThread==0 && pTask->bDone==0 );
  74396. assert( pTask->list.pList==0 );
  74397. assert( pTask->list.aMemory==0 || pSorter->list.aMemory!=0 );
  74398. pSorter->iPrev = (u8)(pTask - pSorter->aTask);
  74399. pTask->list = pSorter->list;
  74400. pSorter->list.pList = 0;
  74401. pSorter->list.szPMA = 0;
  74402. if( aMem ){
  74403. pSorter->list.aMemory = aMem;
  74404. pSorter->nMemory = sqlite3MallocSize(aMem);
  74405. }else if( pSorter->list.aMemory ){
  74406. pSorter->list.aMemory = sqlite3Malloc(pSorter->nMemory);
  74407. if( !pSorter->list.aMemory ) return SQLITE_NOMEM;
  74408. }
  74409. rc = vdbeSorterCreateThread(pTask, vdbeSorterFlushThread, pCtx);
  74410. }
  74411. }
  74412. return rc;
  74413. #endif /* SQLITE_MAX_WORKER_THREADS!=0 */
  74414. }
  74415. /*
  74416. ** Add a record to the sorter.
  74417. */
  74418. SQLITE_PRIVATE int sqlite3VdbeSorterWrite(
  74419. const VdbeCursor *pCsr, /* Sorter cursor */
  74420. Mem *pVal /* Memory cell containing record */
  74421. ){
  74422. VdbeSorter *pSorter = pCsr->pSorter;
  74423. int rc = SQLITE_OK; /* Return Code */
  74424. SorterRecord *pNew; /* New list element */
  74425. int bFlush; /* True to flush contents of memory to PMA */
  74426. int nReq; /* Bytes of memory required */
  74427. int nPMA; /* Bytes of PMA space required */
  74428. int t; /* serial type of first record field */
  74429. getVarint32((const u8*)&pVal->z[1], t);
  74430. if( t>0 && t<10 && t!=7 ){
  74431. pSorter->typeMask &= SORTER_TYPE_INTEGER;
  74432. }else if( t>10 && (t & 0x01) ){
  74433. pSorter->typeMask &= SORTER_TYPE_TEXT;
  74434. }else{
  74435. pSorter->typeMask = 0;
  74436. }
  74437. assert( pSorter );
  74438. /* Figure out whether or not the current contents of memory should be
  74439. ** flushed to a PMA before continuing. If so, do so.
  74440. **
  74441. ** If using the single large allocation mode (pSorter->aMemory!=0), then
  74442. ** flush the contents of memory to a new PMA if (a) at least one value is
  74443. ** already in memory and (b) the new value will not fit in memory.
  74444. **
  74445. ** Or, if using separate allocations for each record, flush the contents
  74446. ** of memory to a PMA if either of the following are true:
  74447. **
  74448. ** * The total memory allocated for the in-memory list is greater
  74449. ** than (page-size * cache-size), or
  74450. **
  74451. ** * The total memory allocated for the in-memory list is greater
  74452. ** than (page-size * 10) and sqlite3HeapNearlyFull() returns true.
  74453. */
  74454. nReq = pVal->n + sizeof(SorterRecord);
  74455. nPMA = pVal->n + sqlite3VarintLen(pVal->n);
  74456. if( pSorter->mxPmaSize ){
  74457. if( pSorter->list.aMemory ){
  74458. bFlush = pSorter->iMemory && (pSorter->iMemory+nReq) > pSorter->mxPmaSize;
  74459. }else{
  74460. bFlush = (
  74461. (pSorter->list.szPMA > pSorter->mxPmaSize)
  74462. || (pSorter->list.szPMA > pSorter->mnPmaSize && sqlite3HeapNearlyFull())
  74463. );
  74464. }
  74465. if( bFlush ){
  74466. rc = vdbeSorterFlushPMA(pSorter);
  74467. pSorter->list.szPMA = 0;
  74468. pSorter->iMemory = 0;
  74469. assert( rc!=SQLITE_OK || pSorter->list.pList==0 );
  74470. }
  74471. }
  74472. pSorter->list.szPMA += nPMA;
  74473. if( nPMA>pSorter->mxKeysize ){
  74474. pSorter->mxKeysize = nPMA;
  74475. }
  74476. if( pSorter->list.aMemory ){
  74477. int nMin = pSorter->iMemory + nReq;
  74478. if( nMin>pSorter->nMemory ){
  74479. u8 *aNew;
  74480. int nNew = pSorter->nMemory * 2;
  74481. while( nNew < nMin ) nNew = nNew*2;
  74482. if( nNew > pSorter->mxPmaSize ) nNew = pSorter->mxPmaSize;
  74483. if( nNew < nMin ) nNew = nMin;
  74484. aNew = sqlite3Realloc(pSorter->list.aMemory, nNew);
  74485. if( !aNew ) return SQLITE_NOMEM;
  74486. pSorter->list.pList = (SorterRecord*)(
  74487. aNew + ((u8*)pSorter->list.pList - pSorter->list.aMemory)
  74488. );
  74489. pSorter->list.aMemory = aNew;
  74490. pSorter->nMemory = nNew;
  74491. }
  74492. pNew = (SorterRecord*)&pSorter->list.aMemory[pSorter->iMemory];
  74493. pSorter->iMemory += ROUND8(nReq);
  74494. pNew->u.iNext = (int)((u8*)(pSorter->list.pList) - pSorter->list.aMemory);
  74495. }else{
  74496. pNew = (SorterRecord *)sqlite3Malloc(nReq);
  74497. if( pNew==0 ){
  74498. return SQLITE_NOMEM;
  74499. }
  74500. pNew->u.pNext = pSorter->list.pList;
  74501. }
  74502. memcpy(SRVAL(pNew), pVal->z, pVal->n);
  74503. pNew->nVal = pVal->n;
  74504. pSorter->list.pList = pNew;
  74505. return rc;
  74506. }
  74507. /*
  74508. ** Read keys from pIncr->pMerger and populate pIncr->aFile[1]. The format
  74509. ** of the data stored in aFile[1] is the same as that used by regular PMAs,
  74510. ** except that the number-of-bytes varint is omitted from the start.
  74511. */
  74512. static int vdbeIncrPopulate(IncrMerger *pIncr){
  74513. int rc = SQLITE_OK;
  74514. int rc2;
  74515. i64 iStart = pIncr->iStartOff;
  74516. SorterFile *pOut = &pIncr->aFile[1];
  74517. SortSubtask *pTask = pIncr->pTask;
  74518. MergeEngine *pMerger = pIncr->pMerger;
  74519. PmaWriter writer;
  74520. assert( pIncr->bEof==0 );
  74521. vdbeSorterPopulateDebug(pTask, "enter");
  74522. vdbePmaWriterInit(pOut->pFd, &writer, pTask->pSorter->pgsz, iStart);
  74523. while( rc==SQLITE_OK ){
  74524. int dummy;
  74525. PmaReader *pReader = &pMerger->aReadr[ pMerger->aTree[1] ];
  74526. int nKey = pReader->nKey;
  74527. i64 iEof = writer.iWriteOff + writer.iBufEnd;
  74528. /* Check if the output file is full or if the input has been exhausted.
  74529. ** In either case exit the loop. */
  74530. if( pReader->pFd==0 ) break;
  74531. if( (iEof + nKey + sqlite3VarintLen(nKey))>(iStart + pIncr->mxSz) ) break;
  74532. /* Write the next key to the output. */
  74533. vdbePmaWriteVarint(&writer, nKey);
  74534. vdbePmaWriteBlob(&writer, pReader->aKey, nKey);
  74535. assert( pIncr->pMerger->pTask==pTask );
  74536. rc = vdbeMergeEngineStep(pIncr->pMerger, &dummy);
  74537. }
  74538. rc2 = vdbePmaWriterFinish(&writer, &pOut->iEof);
  74539. if( rc==SQLITE_OK ) rc = rc2;
  74540. vdbeSorterPopulateDebug(pTask, "exit");
  74541. return rc;
  74542. }
  74543. #if SQLITE_MAX_WORKER_THREADS>0
  74544. /*
  74545. ** The main routine for background threads that populate aFile[1] of
  74546. ** multi-threaded IncrMerger objects.
  74547. */
  74548. static void *vdbeIncrPopulateThread(void *pCtx){
  74549. IncrMerger *pIncr = (IncrMerger*)pCtx;
  74550. void *pRet = SQLITE_INT_TO_PTR( vdbeIncrPopulate(pIncr) );
  74551. pIncr->pTask->bDone = 1;
  74552. return pRet;
  74553. }
  74554. /*
  74555. ** Launch a background thread to populate aFile[1] of pIncr.
  74556. */
  74557. static int vdbeIncrBgPopulate(IncrMerger *pIncr){
  74558. void *p = (void*)pIncr;
  74559. assert( pIncr->bUseThread );
  74560. return vdbeSorterCreateThread(pIncr->pTask, vdbeIncrPopulateThread, p);
  74561. }
  74562. #endif
  74563. /*
  74564. ** This function is called when the PmaReader corresponding to pIncr has
  74565. ** finished reading the contents of aFile[0]. Its purpose is to "refill"
  74566. ** aFile[0] such that the PmaReader should start rereading it from the
  74567. ** beginning.
  74568. **
  74569. ** For single-threaded objects, this is accomplished by literally reading
  74570. ** keys from pIncr->pMerger and repopulating aFile[0].
  74571. **
  74572. ** For multi-threaded objects, all that is required is to wait until the
  74573. ** background thread is finished (if it is not already) and then swap
  74574. ** aFile[0] and aFile[1] in place. If the contents of pMerger have not
  74575. ** been exhausted, this function also launches a new background thread
  74576. ** to populate the new aFile[1].
  74577. **
  74578. ** SQLITE_OK is returned on success, or an SQLite error code otherwise.
  74579. */
  74580. static int vdbeIncrSwap(IncrMerger *pIncr){
  74581. int rc = SQLITE_OK;
  74582. #if SQLITE_MAX_WORKER_THREADS>0
  74583. if( pIncr->bUseThread ){
  74584. rc = vdbeSorterJoinThread(pIncr->pTask);
  74585. if( rc==SQLITE_OK ){
  74586. SorterFile f0 = pIncr->aFile[0];
  74587. pIncr->aFile[0] = pIncr->aFile[1];
  74588. pIncr->aFile[1] = f0;
  74589. }
  74590. if( rc==SQLITE_OK ){
  74591. if( pIncr->aFile[0].iEof==pIncr->iStartOff ){
  74592. pIncr->bEof = 1;
  74593. }else{
  74594. rc = vdbeIncrBgPopulate(pIncr);
  74595. }
  74596. }
  74597. }else
  74598. #endif
  74599. {
  74600. rc = vdbeIncrPopulate(pIncr);
  74601. pIncr->aFile[0] = pIncr->aFile[1];
  74602. if( pIncr->aFile[0].iEof==pIncr->iStartOff ){
  74603. pIncr->bEof = 1;
  74604. }
  74605. }
  74606. return rc;
  74607. }
  74608. /*
  74609. ** Allocate and return a new IncrMerger object to read data from pMerger.
  74610. **
  74611. ** If an OOM condition is encountered, return NULL. In this case free the
  74612. ** pMerger argument before returning.
  74613. */
  74614. static int vdbeIncrMergerNew(
  74615. SortSubtask *pTask, /* The thread that will be using the new IncrMerger */
  74616. MergeEngine *pMerger, /* The MergeEngine that the IncrMerger will control */
  74617. IncrMerger **ppOut /* Write the new IncrMerger here */
  74618. ){
  74619. int rc = SQLITE_OK;
  74620. IncrMerger *pIncr = *ppOut = (IncrMerger*)
  74621. (sqlite3FaultSim(100) ? 0 : sqlite3MallocZero(sizeof(*pIncr)));
  74622. if( pIncr ){
  74623. pIncr->pMerger = pMerger;
  74624. pIncr->pTask = pTask;
  74625. pIncr->mxSz = MAX(pTask->pSorter->mxKeysize+9,pTask->pSorter->mxPmaSize/2);
  74626. pTask->file2.iEof += pIncr->mxSz;
  74627. }else{
  74628. vdbeMergeEngineFree(pMerger);
  74629. rc = SQLITE_NOMEM;
  74630. }
  74631. return rc;
  74632. }
  74633. #if SQLITE_MAX_WORKER_THREADS>0
  74634. /*
  74635. ** Set the "use-threads" flag on object pIncr.
  74636. */
  74637. static void vdbeIncrMergerSetThreads(IncrMerger *pIncr){
  74638. pIncr->bUseThread = 1;
  74639. pIncr->pTask->file2.iEof -= pIncr->mxSz;
  74640. }
  74641. #endif /* SQLITE_MAX_WORKER_THREADS>0 */
  74642. /*
  74643. ** Recompute pMerger->aTree[iOut] by comparing the next keys on the
  74644. ** two PmaReaders that feed that entry. Neither of the PmaReaders
  74645. ** are advanced. This routine merely does the comparison.
  74646. */
  74647. static void vdbeMergeEngineCompare(
  74648. MergeEngine *pMerger, /* Merge engine containing PmaReaders to compare */
  74649. int iOut /* Store the result in pMerger->aTree[iOut] */
  74650. ){
  74651. int i1;
  74652. int i2;
  74653. int iRes;
  74654. PmaReader *p1;
  74655. PmaReader *p2;
  74656. assert( iOut<pMerger->nTree && iOut>0 );
  74657. if( iOut>=(pMerger->nTree/2) ){
  74658. i1 = (iOut - pMerger->nTree/2) * 2;
  74659. i2 = i1 + 1;
  74660. }else{
  74661. i1 = pMerger->aTree[iOut*2];
  74662. i2 = pMerger->aTree[iOut*2+1];
  74663. }
  74664. p1 = &pMerger->aReadr[i1];
  74665. p2 = &pMerger->aReadr[i2];
  74666. if( p1->pFd==0 ){
  74667. iRes = i2;
  74668. }else if( p2->pFd==0 ){
  74669. iRes = i1;
  74670. }else{
  74671. SortSubtask *pTask = pMerger->pTask;
  74672. int bCached = 0;
  74673. int res;
  74674. assert( pTask->pUnpacked!=0 ); /* from vdbeSortSubtaskMain() */
  74675. res = pTask->xCompare(
  74676. pTask, &bCached, p1->aKey, p1->nKey, p2->aKey, p2->nKey
  74677. );
  74678. if( res<=0 ){
  74679. iRes = i1;
  74680. }else{
  74681. iRes = i2;
  74682. }
  74683. }
  74684. pMerger->aTree[iOut] = iRes;
  74685. }
  74686. /*
  74687. ** Allowed values for the eMode parameter to vdbeMergeEngineInit()
  74688. ** and vdbePmaReaderIncrMergeInit().
  74689. **
  74690. ** Only INCRINIT_NORMAL is valid in single-threaded builds (when
  74691. ** SQLITE_MAX_WORKER_THREADS==0). The other values are only used
  74692. ** when there exists one or more separate worker threads.
  74693. */
  74694. #define INCRINIT_NORMAL 0
  74695. #define INCRINIT_TASK 1
  74696. #define INCRINIT_ROOT 2
  74697. /*
  74698. ** Forward reference required as the vdbeIncrMergeInit() and
  74699. ** vdbePmaReaderIncrInit() routines are called mutually recursively when
  74700. ** building a merge tree.
  74701. */
  74702. static int vdbePmaReaderIncrInit(PmaReader *pReadr, int eMode);
  74703. /*
  74704. ** Initialize the MergeEngine object passed as the second argument. Once this
  74705. ** function returns, the first key of merged data may be read from the
  74706. ** MergeEngine object in the usual fashion.
  74707. **
  74708. ** If argument eMode is INCRINIT_ROOT, then it is assumed that any IncrMerge
  74709. ** objects attached to the PmaReader objects that the merger reads from have
  74710. ** already been populated, but that they have not yet populated aFile[0] and
  74711. ** set the PmaReader objects up to read from it. In this case all that is
  74712. ** required is to call vdbePmaReaderNext() on each PmaReader to point it at
  74713. ** its first key.
  74714. **
  74715. ** Otherwise, if eMode is any value other than INCRINIT_ROOT, then use
  74716. ** vdbePmaReaderIncrMergeInit() to initialize each PmaReader that feeds data
  74717. ** to pMerger.
  74718. **
  74719. ** SQLITE_OK is returned if successful, or an SQLite error code otherwise.
  74720. */
  74721. static int vdbeMergeEngineInit(
  74722. SortSubtask *pTask, /* Thread that will run pMerger */
  74723. MergeEngine *pMerger, /* MergeEngine to initialize */
  74724. int eMode /* One of the INCRINIT_XXX constants */
  74725. ){
  74726. int rc = SQLITE_OK; /* Return code */
  74727. int i; /* For looping over PmaReader objects */
  74728. int nTree = pMerger->nTree;
  74729. /* eMode is always INCRINIT_NORMAL in single-threaded mode */
  74730. assert( SQLITE_MAX_WORKER_THREADS>0 || eMode==INCRINIT_NORMAL );
  74731. /* Verify that the MergeEngine is assigned to a single thread */
  74732. assert( pMerger->pTask==0 );
  74733. pMerger->pTask = pTask;
  74734. for(i=0; i<nTree; i++){
  74735. if( SQLITE_MAX_WORKER_THREADS>0 && eMode==INCRINIT_ROOT ){
  74736. /* PmaReaders should be normally initialized in order, as if they are
  74737. ** reading from the same temp file this makes for more linear file IO.
  74738. ** However, in the INCRINIT_ROOT case, if PmaReader aReadr[nTask-1] is
  74739. ** in use it will block the vdbePmaReaderNext() call while it uses
  74740. ** the main thread to fill its buffer. So calling PmaReaderNext()
  74741. ** on this PmaReader before any of the multi-threaded PmaReaders takes
  74742. ** better advantage of multi-processor hardware. */
  74743. rc = vdbePmaReaderNext(&pMerger->aReadr[nTree-i-1]);
  74744. }else{
  74745. rc = vdbePmaReaderIncrInit(&pMerger->aReadr[i], INCRINIT_NORMAL);
  74746. }
  74747. if( rc!=SQLITE_OK ) return rc;
  74748. }
  74749. for(i=pMerger->nTree-1; i>0; i--){
  74750. vdbeMergeEngineCompare(pMerger, i);
  74751. }
  74752. return pTask->pUnpacked->errCode;
  74753. }
  74754. /*
  74755. ** The PmaReader passed as the first argument is guaranteed to be an
  74756. ** incremental-reader (pReadr->pIncr!=0). This function serves to open
  74757. ** and/or initialize the temp file related fields of the IncrMerge
  74758. ** object at (pReadr->pIncr).
  74759. **
  74760. ** If argument eMode is set to INCRINIT_NORMAL, then all PmaReaders
  74761. ** in the sub-tree headed by pReadr are also initialized. Data is then
  74762. ** loaded into the buffers belonging to pReadr and it is set to point to
  74763. ** the first key in its range.
  74764. **
  74765. ** If argument eMode is set to INCRINIT_TASK, then pReadr is guaranteed
  74766. ** to be a multi-threaded PmaReader and this function is being called in a
  74767. ** background thread. In this case all PmaReaders in the sub-tree are
  74768. ** initialized as for INCRINIT_NORMAL and the aFile[1] buffer belonging to
  74769. ** pReadr is populated. However, pReadr itself is not set up to point
  74770. ** to its first key. A call to vdbePmaReaderNext() is still required to do
  74771. ** that.
  74772. **
  74773. ** The reason this function does not call vdbePmaReaderNext() immediately
  74774. ** in the INCRINIT_TASK case is that vdbePmaReaderNext() assumes that it has
  74775. ** to block on thread (pTask->thread) before accessing aFile[1]. But, since
  74776. ** this entire function is being run by thread (pTask->thread), that will
  74777. ** lead to the current background thread attempting to join itself.
  74778. **
  74779. ** Finally, if argument eMode is set to INCRINIT_ROOT, it may be assumed
  74780. ** that pReadr->pIncr is a multi-threaded IncrMerge objects, and that all
  74781. ** child-trees have already been initialized using IncrInit(INCRINIT_TASK).
  74782. ** In this case vdbePmaReaderNext() is called on all child PmaReaders and
  74783. ** the current PmaReader set to point to the first key in its range.
  74784. **
  74785. ** SQLITE_OK is returned if successful, or an SQLite error code otherwise.
  74786. */
  74787. static int vdbePmaReaderIncrMergeInit(PmaReader *pReadr, int eMode){
  74788. int rc = SQLITE_OK;
  74789. IncrMerger *pIncr = pReadr->pIncr;
  74790. SortSubtask *pTask = pIncr->pTask;
  74791. sqlite3 *db = pTask->pSorter->db;
  74792. /* eMode is always INCRINIT_NORMAL in single-threaded mode */
  74793. assert( SQLITE_MAX_WORKER_THREADS>0 || eMode==INCRINIT_NORMAL );
  74794. rc = vdbeMergeEngineInit(pTask, pIncr->pMerger, eMode);
  74795. /* Set up the required files for pIncr. A multi-theaded IncrMerge object
  74796. ** requires two temp files to itself, whereas a single-threaded object
  74797. ** only requires a region of pTask->file2. */
  74798. if( rc==SQLITE_OK ){
  74799. int mxSz = pIncr->mxSz;
  74800. #if SQLITE_MAX_WORKER_THREADS>0
  74801. if( pIncr->bUseThread ){
  74802. rc = vdbeSorterOpenTempFile(db, mxSz, &pIncr->aFile[0].pFd);
  74803. if( rc==SQLITE_OK ){
  74804. rc = vdbeSorterOpenTempFile(db, mxSz, &pIncr->aFile[1].pFd);
  74805. }
  74806. }else
  74807. #endif
  74808. /*if( !pIncr->bUseThread )*/{
  74809. if( pTask->file2.pFd==0 ){
  74810. assert( pTask->file2.iEof>0 );
  74811. rc = vdbeSorterOpenTempFile(db, pTask->file2.iEof, &pTask->file2.pFd);
  74812. pTask->file2.iEof = 0;
  74813. }
  74814. if( rc==SQLITE_OK ){
  74815. pIncr->aFile[1].pFd = pTask->file2.pFd;
  74816. pIncr->iStartOff = pTask->file2.iEof;
  74817. pTask->file2.iEof += mxSz;
  74818. }
  74819. }
  74820. }
  74821. #if SQLITE_MAX_WORKER_THREADS>0
  74822. if( rc==SQLITE_OK && pIncr->bUseThread ){
  74823. /* Use the current thread to populate aFile[1], even though this
  74824. ** PmaReader is multi-threaded. If this is an INCRINIT_TASK object,
  74825. ** then this function is already running in background thread
  74826. ** pIncr->pTask->thread.
  74827. **
  74828. ** If this is the INCRINIT_ROOT object, then it is running in the
  74829. ** main VDBE thread. But that is Ok, as that thread cannot return
  74830. ** control to the VDBE or proceed with anything useful until the
  74831. ** first results are ready from this merger object anyway.
  74832. */
  74833. assert( eMode==INCRINIT_ROOT || eMode==INCRINIT_TASK );
  74834. rc = vdbeIncrPopulate(pIncr);
  74835. }
  74836. #endif
  74837. if( rc==SQLITE_OK && (SQLITE_MAX_WORKER_THREADS==0 || eMode!=INCRINIT_TASK) ){
  74838. rc = vdbePmaReaderNext(pReadr);
  74839. }
  74840. return rc;
  74841. }
  74842. #if SQLITE_MAX_WORKER_THREADS>0
  74843. /*
  74844. ** The main routine for vdbePmaReaderIncrMergeInit() operations run in
  74845. ** background threads.
  74846. */
  74847. static void *vdbePmaReaderBgIncrInit(void *pCtx){
  74848. PmaReader *pReader = (PmaReader*)pCtx;
  74849. void *pRet = SQLITE_INT_TO_PTR(
  74850. vdbePmaReaderIncrMergeInit(pReader,INCRINIT_TASK)
  74851. );
  74852. pReader->pIncr->pTask->bDone = 1;
  74853. return pRet;
  74854. }
  74855. #endif
  74856. /*
  74857. ** If the PmaReader passed as the first argument is not an incremental-reader
  74858. ** (if pReadr->pIncr==0), then this function is a no-op. Otherwise, it invokes
  74859. ** the vdbePmaReaderIncrMergeInit() function with the parameters passed to
  74860. ** this routine to initialize the incremental merge.
  74861. **
  74862. ** If the IncrMerger object is multi-threaded (IncrMerger.bUseThread==1),
  74863. ** then a background thread is launched to call vdbePmaReaderIncrMergeInit().
  74864. ** Or, if the IncrMerger is single threaded, the same function is called
  74865. ** using the current thread.
  74866. */
  74867. static int vdbePmaReaderIncrInit(PmaReader *pReadr, int eMode){
  74868. IncrMerger *pIncr = pReadr->pIncr; /* Incremental merger */
  74869. int rc = SQLITE_OK; /* Return code */
  74870. if( pIncr ){
  74871. #if SQLITE_MAX_WORKER_THREADS>0
  74872. assert( pIncr->bUseThread==0 || eMode==INCRINIT_TASK );
  74873. if( pIncr->bUseThread ){
  74874. void *pCtx = (void*)pReadr;
  74875. rc = vdbeSorterCreateThread(pIncr->pTask, vdbePmaReaderBgIncrInit, pCtx);
  74876. }else
  74877. #endif
  74878. {
  74879. rc = vdbePmaReaderIncrMergeInit(pReadr, eMode);
  74880. }
  74881. }
  74882. return rc;
  74883. }
  74884. /*
  74885. ** Allocate a new MergeEngine object to merge the contents of nPMA level-0
  74886. ** PMAs from pTask->file. If no error occurs, set *ppOut to point to
  74887. ** the new object and return SQLITE_OK. Or, if an error does occur, set *ppOut
  74888. ** to NULL and return an SQLite error code.
  74889. **
  74890. ** When this function is called, *piOffset is set to the offset of the
  74891. ** first PMA to read from pTask->file. Assuming no error occurs, it is
  74892. ** set to the offset immediately following the last byte of the last
  74893. ** PMA before returning. If an error does occur, then the final value of
  74894. ** *piOffset is undefined.
  74895. */
  74896. static int vdbeMergeEngineLevel0(
  74897. SortSubtask *pTask, /* Sorter task to read from */
  74898. int nPMA, /* Number of PMAs to read */
  74899. i64 *piOffset, /* IN/OUT: Readr offset in pTask->file */
  74900. MergeEngine **ppOut /* OUT: New merge-engine */
  74901. ){
  74902. MergeEngine *pNew; /* Merge engine to return */
  74903. i64 iOff = *piOffset;
  74904. int i;
  74905. int rc = SQLITE_OK;
  74906. *ppOut = pNew = vdbeMergeEngineNew(nPMA);
  74907. if( pNew==0 ) rc = SQLITE_NOMEM;
  74908. for(i=0; i<nPMA && rc==SQLITE_OK; i++){
  74909. i64 nDummy;
  74910. PmaReader *pReadr = &pNew->aReadr[i];
  74911. rc = vdbePmaReaderInit(pTask, &pTask->file, iOff, pReadr, &nDummy);
  74912. iOff = pReadr->iEof;
  74913. }
  74914. if( rc!=SQLITE_OK ){
  74915. vdbeMergeEngineFree(pNew);
  74916. *ppOut = 0;
  74917. }
  74918. *piOffset = iOff;
  74919. return rc;
  74920. }
  74921. /*
  74922. ** Return the depth of a tree comprising nPMA PMAs, assuming a fanout of
  74923. ** SORTER_MAX_MERGE_COUNT. The returned value does not include leaf nodes.
  74924. **
  74925. ** i.e.
  74926. **
  74927. ** nPMA<=16 -> TreeDepth() == 0
  74928. ** nPMA<=256 -> TreeDepth() == 1
  74929. ** nPMA<=65536 -> TreeDepth() == 2
  74930. */
  74931. static int vdbeSorterTreeDepth(int nPMA){
  74932. int nDepth = 0;
  74933. i64 nDiv = SORTER_MAX_MERGE_COUNT;
  74934. while( nDiv < (i64)nPMA ){
  74935. nDiv = nDiv * SORTER_MAX_MERGE_COUNT;
  74936. nDepth++;
  74937. }
  74938. return nDepth;
  74939. }
  74940. /*
  74941. ** pRoot is the root of an incremental merge-tree with depth nDepth (according
  74942. ** to vdbeSorterTreeDepth()). pLeaf is the iSeq'th leaf to be added to the
  74943. ** tree, counting from zero. This function adds pLeaf to the tree.
  74944. **
  74945. ** If successful, SQLITE_OK is returned. If an error occurs, an SQLite error
  74946. ** code is returned and pLeaf is freed.
  74947. */
  74948. static int vdbeSorterAddToTree(
  74949. SortSubtask *pTask, /* Task context */
  74950. int nDepth, /* Depth of tree according to TreeDepth() */
  74951. int iSeq, /* Sequence number of leaf within tree */
  74952. MergeEngine *pRoot, /* Root of tree */
  74953. MergeEngine *pLeaf /* Leaf to add to tree */
  74954. ){
  74955. int rc = SQLITE_OK;
  74956. int nDiv = 1;
  74957. int i;
  74958. MergeEngine *p = pRoot;
  74959. IncrMerger *pIncr;
  74960. rc = vdbeIncrMergerNew(pTask, pLeaf, &pIncr);
  74961. for(i=1; i<nDepth; i++){
  74962. nDiv = nDiv * SORTER_MAX_MERGE_COUNT;
  74963. }
  74964. for(i=1; i<nDepth && rc==SQLITE_OK; i++){
  74965. int iIter = (iSeq / nDiv) % SORTER_MAX_MERGE_COUNT;
  74966. PmaReader *pReadr = &p->aReadr[iIter];
  74967. if( pReadr->pIncr==0 ){
  74968. MergeEngine *pNew = vdbeMergeEngineNew(SORTER_MAX_MERGE_COUNT);
  74969. if( pNew==0 ){
  74970. rc = SQLITE_NOMEM;
  74971. }else{
  74972. rc = vdbeIncrMergerNew(pTask, pNew, &pReadr->pIncr);
  74973. }
  74974. }
  74975. if( rc==SQLITE_OK ){
  74976. p = pReadr->pIncr->pMerger;
  74977. nDiv = nDiv / SORTER_MAX_MERGE_COUNT;
  74978. }
  74979. }
  74980. if( rc==SQLITE_OK ){
  74981. p->aReadr[iSeq % SORTER_MAX_MERGE_COUNT].pIncr = pIncr;
  74982. }else{
  74983. vdbeIncrFree(pIncr);
  74984. }
  74985. return rc;
  74986. }
  74987. /*
  74988. ** This function is called as part of a SorterRewind() operation on a sorter
  74989. ** that has already written two or more level-0 PMAs to one or more temp
  74990. ** files. It builds a tree of MergeEngine/IncrMerger/PmaReader objects that
  74991. ** can be used to incrementally merge all PMAs on disk.
  74992. **
  74993. ** If successful, SQLITE_OK is returned and *ppOut set to point to the
  74994. ** MergeEngine object at the root of the tree before returning. Or, if an
  74995. ** error occurs, an SQLite error code is returned and the final value
  74996. ** of *ppOut is undefined.
  74997. */
  74998. static int vdbeSorterMergeTreeBuild(
  74999. VdbeSorter *pSorter, /* The VDBE cursor that implements the sort */
  75000. MergeEngine **ppOut /* Write the MergeEngine here */
  75001. ){
  75002. MergeEngine *pMain = 0;
  75003. int rc = SQLITE_OK;
  75004. int iTask;
  75005. #if SQLITE_MAX_WORKER_THREADS>0
  75006. /* If the sorter uses more than one task, then create the top-level
  75007. ** MergeEngine here. This MergeEngine will read data from exactly
  75008. ** one PmaReader per sub-task. */
  75009. assert( pSorter->bUseThreads || pSorter->nTask==1 );
  75010. if( pSorter->nTask>1 ){
  75011. pMain = vdbeMergeEngineNew(pSorter->nTask);
  75012. if( pMain==0 ) rc = SQLITE_NOMEM;
  75013. }
  75014. #endif
  75015. for(iTask=0; rc==SQLITE_OK && iTask<pSorter->nTask; iTask++){
  75016. SortSubtask *pTask = &pSorter->aTask[iTask];
  75017. assert( pTask->nPMA>0 || SQLITE_MAX_WORKER_THREADS>0 );
  75018. if( SQLITE_MAX_WORKER_THREADS==0 || pTask->nPMA ){
  75019. MergeEngine *pRoot = 0; /* Root node of tree for this task */
  75020. int nDepth = vdbeSorterTreeDepth(pTask->nPMA);
  75021. i64 iReadOff = 0;
  75022. if( pTask->nPMA<=SORTER_MAX_MERGE_COUNT ){
  75023. rc = vdbeMergeEngineLevel0(pTask, pTask->nPMA, &iReadOff, &pRoot);
  75024. }else{
  75025. int i;
  75026. int iSeq = 0;
  75027. pRoot = vdbeMergeEngineNew(SORTER_MAX_MERGE_COUNT);
  75028. if( pRoot==0 ) rc = SQLITE_NOMEM;
  75029. for(i=0; i<pTask->nPMA && rc==SQLITE_OK; i += SORTER_MAX_MERGE_COUNT){
  75030. MergeEngine *pMerger = 0; /* New level-0 PMA merger */
  75031. int nReader; /* Number of level-0 PMAs to merge */
  75032. nReader = MIN(pTask->nPMA - i, SORTER_MAX_MERGE_COUNT);
  75033. rc = vdbeMergeEngineLevel0(pTask, nReader, &iReadOff, &pMerger);
  75034. if( rc==SQLITE_OK ){
  75035. rc = vdbeSorterAddToTree(pTask, nDepth, iSeq++, pRoot, pMerger);
  75036. }
  75037. }
  75038. }
  75039. if( rc==SQLITE_OK ){
  75040. #if SQLITE_MAX_WORKER_THREADS>0
  75041. if( pMain!=0 ){
  75042. rc = vdbeIncrMergerNew(pTask, pRoot, &pMain->aReadr[iTask].pIncr);
  75043. }else
  75044. #endif
  75045. {
  75046. assert( pMain==0 );
  75047. pMain = pRoot;
  75048. }
  75049. }else{
  75050. vdbeMergeEngineFree(pRoot);
  75051. }
  75052. }
  75053. }
  75054. if( rc!=SQLITE_OK ){
  75055. vdbeMergeEngineFree(pMain);
  75056. pMain = 0;
  75057. }
  75058. *ppOut = pMain;
  75059. return rc;
  75060. }
  75061. /*
  75062. ** This function is called as part of an sqlite3VdbeSorterRewind() operation
  75063. ** on a sorter that has written two or more PMAs to temporary files. It sets
  75064. ** up either VdbeSorter.pMerger (for single threaded sorters) or pReader
  75065. ** (for multi-threaded sorters) so that it can be used to iterate through
  75066. ** all records stored in the sorter.
  75067. **
  75068. ** SQLITE_OK is returned if successful, or an SQLite error code otherwise.
  75069. */
  75070. static int vdbeSorterSetupMerge(VdbeSorter *pSorter){
  75071. int rc; /* Return code */
  75072. SortSubtask *pTask0 = &pSorter->aTask[0];
  75073. MergeEngine *pMain = 0;
  75074. #if SQLITE_MAX_WORKER_THREADS
  75075. sqlite3 *db = pTask0->pSorter->db;
  75076. int i;
  75077. SorterCompare xCompare = vdbeSorterGetCompare(pSorter);
  75078. for(i=0; i<pSorter->nTask; i++){
  75079. pSorter->aTask[i].xCompare = xCompare;
  75080. }
  75081. #endif
  75082. rc = vdbeSorterMergeTreeBuild(pSorter, &pMain);
  75083. if( rc==SQLITE_OK ){
  75084. #if SQLITE_MAX_WORKER_THREADS
  75085. assert( pSorter->bUseThreads==0 || pSorter->nTask>1 );
  75086. if( pSorter->bUseThreads ){
  75087. int iTask;
  75088. PmaReader *pReadr = 0;
  75089. SortSubtask *pLast = &pSorter->aTask[pSorter->nTask-1];
  75090. rc = vdbeSortAllocUnpacked(pLast);
  75091. if( rc==SQLITE_OK ){
  75092. pReadr = (PmaReader*)sqlite3DbMallocZero(db, sizeof(PmaReader));
  75093. pSorter->pReader = pReadr;
  75094. if( pReadr==0 ) rc = SQLITE_NOMEM;
  75095. }
  75096. if( rc==SQLITE_OK ){
  75097. rc = vdbeIncrMergerNew(pLast, pMain, &pReadr->pIncr);
  75098. if( rc==SQLITE_OK ){
  75099. vdbeIncrMergerSetThreads(pReadr->pIncr);
  75100. for(iTask=0; iTask<(pSorter->nTask-1); iTask++){
  75101. IncrMerger *pIncr;
  75102. if( (pIncr = pMain->aReadr[iTask].pIncr) ){
  75103. vdbeIncrMergerSetThreads(pIncr);
  75104. assert( pIncr->pTask!=pLast );
  75105. }
  75106. }
  75107. for(iTask=0; rc==SQLITE_OK && iTask<pSorter->nTask; iTask++){
  75108. /* Check that:
  75109. **
  75110. ** a) The incremental merge object is configured to use the
  75111. ** right task, and
  75112. ** b) If it is using task (nTask-1), it is configured to run
  75113. ** in single-threaded mode. This is important, as the
  75114. ** root merge (INCRINIT_ROOT) will be using the same task
  75115. ** object.
  75116. */
  75117. PmaReader *p = &pMain->aReadr[iTask];
  75118. assert( p->pIncr==0 || (
  75119. (p->pIncr->pTask==&pSorter->aTask[iTask]) /* a */
  75120. && (iTask!=pSorter->nTask-1 || p->pIncr->bUseThread==0) /* b */
  75121. ));
  75122. rc = vdbePmaReaderIncrInit(p, INCRINIT_TASK);
  75123. }
  75124. }
  75125. pMain = 0;
  75126. }
  75127. if( rc==SQLITE_OK ){
  75128. rc = vdbePmaReaderIncrMergeInit(pReadr, INCRINIT_ROOT);
  75129. }
  75130. }else
  75131. #endif
  75132. {
  75133. rc = vdbeMergeEngineInit(pTask0, pMain, INCRINIT_NORMAL);
  75134. pSorter->pMerger = pMain;
  75135. pMain = 0;
  75136. }
  75137. }
  75138. if( rc!=SQLITE_OK ){
  75139. vdbeMergeEngineFree(pMain);
  75140. }
  75141. return rc;
  75142. }
  75143. /*
  75144. ** Once the sorter has been populated by calls to sqlite3VdbeSorterWrite,
  75145. ** this function is called to prepare for iterating through the records
  75146. ** in sorted order.
  75147. */
  75148. SQLITE_PRIVATE int sqlite3VdbeSorterRewind(const VdbeCursor *pCsr, int *pbEof){
  75149. VdbeSorter *pSorter = pCsr->pSorter;
  75150. int rc = SQLITE_OK; /* Return code */
  75151. assert( pSorter );
  75152. /* If no data has been written to disk, then do not do so now. Instead,
  75153. ** sort the VdbeSorter.pRecord list. The vdbe layer will read data directly
  75154. ** from the in-memory list. */
  75155. if( pSorter->bUsePMA==0 ){
  75156. if( pSorter->list.pList ){
  75157. *pbEof = 0;
  75158. rc = vdbeSorterSort(&pSorter->aTask[0], &pSorter->list);
  75159. }else{
  75160. *pbEof = 1;
  75161. }
  75162. return rc;
  75163. }
  75164. /* Write the current in-memory list to a PMA. When the VdbeSorterWrite()
  75165. ** function flushes the contents of memory to disk, it immediately always
  75166. ** creates a new list consisting of a single key immediately afterwards.
  75167. ** So the list is never empty at this point. */
  75168. assert( pSorter->list.pList );
  75169. rc = vdbeSorterFlushPMA(pSorter);
  75170. /* Join all threads */
  75171. rc = vdbeSorterJoinAll(pSorter, rc);
  75172. vdbeSorterRewindDebug("rewind");
  75173. /* Assuming no errors have occurred, set up a merger structure to
  75174. ** incrementally read and merge all remaining PMAs. */
  75175. assert( pSorter->pReader==0 );
  75176. if( rc==SQLITE_OK ){
  75177. rc = vdbeSorterSetupMerge(pSorter);
  75178. *pbEof = 0;
  75179. }
  75180. vdbeSorterRewindDebug("rewinddone");
  75181. return rc;
  75182. }
  75183. /*
  75184. ** Advance to the next element in the sorter.
  75185. */
  75186. SQLITE_PRIVATE int sqlite3VdbeSorterNext(sqlite3 *db, const VdbeCursor *pCsr, int *pbEof){
  75187. VdbeSorter *pSorter = pCsr->pSorter;
  75188. int rc; /* Return code */
  75189. assert( pSorter->bUsePMA || (pSorter->pReader==0 && pSorter->pMerger==0) );
  75190. if( pSorter->bUsePMA ){
  75191. assert( pSorter->pReader==0 || pSorter->pMerger==0 );
  75192. assert( pSorter->bUseThreads==0 || pSorter->pReader );
  75193. assert( pSorter->bUseThreads==1 || pSorter->pMerger );
  75194. #if SQLITE_MAX_WORKER_THREADS>0
  75195. if( pSorter->bUseThreads ){
  75196. rc = vdbePmaReaderNext(pSorter->pReader);
  75197. *pbEof = (pSorter->pReader->pFd==0);
  75198. }else
  75199. #endif
  75200. /*if( !pSorter->bUseThreads )*/ {
  75201. assert( pSorter->pMerger!=0 );
  75202. assert( pSorter->pMerger->pTask==(&pSorter->aTask[0]) );
  75203. rc = vdbeMergeEngineStep(pSorter->pMerger, pbEof);
  75204. }
  75205. }else{
  75206. SorterRecord *pFree = pSorter->list.pList;
  75207. pSorter->list.pList = pFree->u.pNext;
  75208. pFree->u.pNext = 0;
  75209. if( pSorter->list.aMemory==0 ) vdbeSorterRecordFree(db, pFree);
  75210. *pbEof = !pSorter->list.pList;
  75211. rc = SQLITE_OK;
  75212. }
  75213. return rc;
  75214. }
  75215. /*
  75216. ** Return a pointer to a buffer owned by the sorter that contains the
  75217. ** current key.
  75218. */
  75219. static void *vdbeSorterRowkey(
  75220. const VdbeSorter *pSorter, /* Sorter object */
  75221. int *pnKey /* OUT: Size of current key in bytes */
  75222. ){
  75223. void *pKey;
  75224. if( pSorter->bUsePMA ){
  75225. PmaReader *pReader;
  75226. #if SQLITE_MAX_WORKER_THREADS>0
  75227. if( pSorter->bUseThreads ){
  75228. pReader = pSorter->pReader;
  75229. }else
  75230. #endif
  75231. /*if( !pSorter->bUseThreads )*/{
  75232. pReader = &pSorter->pMerger->aReadr[pSorter->pMerger->aTree[1]];
  75233. }
  75234. *pnKey = pReader->nKey;
  75235. pKey = pReader->aKey;
  75236. }else{
  75237. *pnKey = pSorter->list.pList->nVal;
  75238. pKey = SRVAL(pSorter->list.pList);
  75239. }
  75240. return pKey;
  75241. }
  75242. /*
  75243. ** Copy the current sorter key into the memory cell pOut.
  75244. */
  75245. SQLITE_PRIVATE int sqlite3VdbeSorterRowkey(const VdbeCursor *pCsr, Mem *pOut){
  75246. VdbeSorter *pSorter = pCsr->pSorter;
  75247. void *pKey; int nKey; /* Sorter key to copy into pOut */
  75248. pKey = vdbeSorterRowkey(pSorter, &nKey);
  75249. if( sqlite3VdbeMemClearAndResize(pOut, nKey) ){
  75250. return SQLITE_NOMEM;
  75251. }
  75252. pOut->n = nKey;
  75253. MemSetTypeFlag(pOut, MEM_Blob);
  75254. memcpy(pOut->z, pKey, nKey);
  75255. return SQLITE_OK;
  75256. }
  75257. /*
  75258. ** Compare the key in memory cell pVal with the key that the sorter cursor
  75259. ** passed as the first argument currently points to. For the purposes of
  75260. ** the comparison, ignore the rowid field at the end of each record.
  75261. **
  75262. ** If the sorter cursor key contains any NULL values, consider it to be
  75263. ** less than pVal. Even if pVal also contains NULL values.
  75264. **
  75265. ** If an error occurs, return an SQLite error code (i.e. SQLITE_NOMEM).
  75266. ** Otherwise, set *pRes to a negative, zero or positive value if the
  75267. ** key in pVal is smaller than, equal to or larger than the current sorter
  75268. ** key.
  75269. **
  75270. ** This routine forms the core of the OP_SorterCompare opcode, which in
  75271. ** turn is used to verify uniqueness when constructing a UNIQUE INDEX.
  75272. */
  75273. SQLITE_PRIVATE int sqlite3VdbeSorterCompare(
  75274. const VdbeCursor *pCsr, /* Sorter cursor */
  75275. Mem *pVal, /* Value to compare to current sorter key */
  75276. int nKeyCol, /* Compare this many columns */
  75277. int *pRes /* OUT: Result of comparison */
  75278. ){
  75279. VdbeSorter *pSorter = pCsr->pSorter;
  75280. UnpackedRecord *r2 = pSorter->pUnpacked;
  75281. KeyInfo *pKeyInfo = pCsr->pKeyInfo;
  75282. int i;
  75283. void *pKey; int nKey; /* Sorter key to compare pVal with */
  75284. if( r2==0 ){
  75285. char *p;
  75286. r2 = pSorter->pUnpacked = sqlite3VdbeAllocUnpackedRecord(pKeyInfo,0,0,&p);
  75287. assert( pSorter->pUnpacked==(UnpackedRecord*)p );
  75288. if( r2==0 ) return SQLITE_NOMEM;
  75289. r2->nField = nKeyCol;
  75290. }
  75291. assert( r2->nField==nKeyCol );
  75292. pKey = vdbeSorterRowkey(pSorter, &nKey);
  75293. sqlite3VdbeRecordUnpack(pKeyInfo, nKey, pKey, r2);
  75294. for(i=0; i<nKeyCol; i++){
  75295. if( r2->aMem[i].flags & MEM_Null ){
  75296. *pRes = -1;
  75297. return SQLITE_OK;
  75298. }
  75299. }
  75300. *pRes = sqlite3VdbeRecordCompare(pVal->n, pVal->z, r2);
  75301. return SQLITE_OK;
  75302. }
  75303. /************** End of vdbesort.c ********************************************/
  75304. /************** Begin file journal.c *****************************************/
  75305. /*
  75306. ** 2007 August 22
  75307. **
  75308. ** The author disclaims copyright to this source code. In place of
  75309. ** a legal notice, here is a blessing:
  75310. **
  75311. ** May you do good and not evil.
  75312. ** May you find forgiveness for yourself and forgive others.
  75313. ** May you share freely, never taking more than you give.
  75314. **
  75315. *************************************************************************
  75316. **
  75317. ** This file implements a special kind of sqlite3_file object used
  75318. ** by SQLite to create journal files if the atomic-write optimization
  75319. ** is enabled.
  75320. **
  75321. ** The distinctive characteristic of this sqlite3_file is that the
  75322. ** actual on disk file is created lazily. When the file is created,
  75323. ** the caller specifies a buffer size for an in-memory buffer to
  75324. ** be used to service read() and write() requests. The actual file
  75325. ** on disk is not created or populated until either:
  75326. **
  75327. ** 1) The in-memory representation grows too large for the allocated
  75328. ** buffer, or
  75329. ** 2) The sqlite3JournalCreate() function is called.
  75330. */
  75331. #ifdef SQLITE_ENABLE_ATOMIC_WRITE
  75332. /*
  75333. ** A JournalFile object is a subclass of sqlite3_file used by
  75334. ** as an open file handle for journal files.
  75335. */
  75336. struct JournalFile {
  75337. sqlite3_io_methods *pMethod; /* I/O methods on journal files */
  75338. int nBuf; /* Size of zBuf[] in bytes */
  75339. char *zBuf; /* Space to buffer journal writes */
  75340. int iSize; /* Amount of zBuf[] currently used */
  75341. int flags; /* xOpen flags */
  75342. sqlite3_vfs *pVfs; /* The "real" underlying VFS */
  75343. sqlite3_file *pReal; /* The "real" underlying file descriptor */
  75344. const char *zJournal; /* Name of the journal file */
  75345. };
  75346. typedef struct JournalFile JournalFile;
  75347. /*
  75348. ** If it does not already exists, create and populate the on-disk file
  75349. ** for JournalFile p.
  75350. */
  75351. static int createFile(JournalFile *p){
  75352. int rc = SQLITE_OK;
  75353. if( !p->pReal ){
  75354. sqlite3_file *pReal = (sqlite3_file *)&p[1];
  75355. rc = sqlite3OsOpen(p->pVfs, p->zJournal, pReal, p->flags, 0);
  75356. if( rc==SQLITE_OK ){
  75357. p->pReal = pReal;
  75358. if( p->iSize>0 ){
  75359. assert(p->iSize<=p->nBuf);
  75360. rc = sqlite3OsWrite(p->pReal, p->zBuf, p->iSize, 0);
  75361. }
  75362. if( rc!=SQLITE_OK ){
  75363. /* If an error occurred while writing to the file, close it before
  75364. ** returning. This way, SQLite uses the in-memory journal data to
  75365. ** roll back changes made to the internal page-cache before this
  75366. ** function was called. */
  75367. sqlite3OsClose(pReal);
  75368. p->pReal = 0;
  75369. }
  75370. }
  75371. }
  75372. return rc;
  75373. }
  75374. /*
  75375. ** Close the file.
  75376. */
  75377. static int jrnlClose(sqlite3_file *pJfd){
  75378. JournalFile *p = (JournalFile *)pJfd;
  75379. if( p->pReal ){
  75380. sqlite3OsClose(p->pReal);
  75381. }
  75382. sqlite3_free(p->zBuf);
  75383. return SQLITE_OK;
  75384. }
  75385. /*
  75386. ** Read data from the file.
  75387. */
  75388. static int jrnlRead(
  75389. sqlite3_file *pJfd, /* The journal file from which to read */
  75390. void *zBuf, /* Put the results here */
  75391. int iAmt, /* Number of bytes to read */
  75392. sqlite_int64 iOfst /* Begin reading at this offset */
  75393. ){
  75394. int rc = SQLITE_OK;
  75395. JournalFile *p = (JournalFile *)pJfd;
  75396. if( p->pReal ){
  75397. rc = sqlite3OsRead(p->pReal, zBuf, iAmt, iOfst);
  75398. }else if( (iAmt+iOfst)>p->iSize ){
  75399. rc = SQLITE_IOERR_SHORT_READ;
  75400. }else{
  75401. memcpy(zBuf, &p->zBuf[iOfst], iAmt);
  75402. }
  75403. return rc;
  75404. }
  75405. /*
  75406. ** Write data to the file.
  75407. */
  75408. static int jrnlWrite(
  75409. sqlite3_file *pJfd, /* The journal file into which to write */
  75410. const void *zBuf, /* Take data to be written from here */
  75411. int iAmt, /* Number of bytes to write */
  75412. sqlite_int64 iOfst /* Begin writing at this offset into the file */
  75413. ){
  75414. int rc = SQLITE_OK;
  75415. JournalFile *p = (JournalFile *)pJfd;
  75416. if( !p->pReal && (iOfst+iAmt)>p->nBuf ){
  75417. rc = createFile(p);
  75418. }
  75419. if( rc==SQLITE_OK ){
  75420. if( p->pReal ){
  75421. rc = sqlite3OsWrite(p->pReal, zBuf, iAmt, iOfst);
  75422. }else{
  75423. memcpy(&p->zBuf[iOfst], zBuf, iAmt);
  75424. if( p->iSize<(iOfst+iAmt) ){
  75425. p->iSize = (iOfst+iAmt);
  75426. }
  75427. }
  75428. }
  75429. return rc;
  75430. }
  75431. /*
  75432. ** Truncate the file.
  75433. */
  75434. static int jrnlTruncate(sqlite3_file *pJfd, sqlite_int64 size){
  75435. int rc = SQLITE_OK;
  75436. JournalFile *p = (JournalFile *)pJfd;
  75437. if( p->pReal ){
  75438. rc = sqlite3OsTruncate(p->pReal, size);
  75439. }else if( size<p->iSize ){
  75440. p->iSize = size;
  75441. }
  75442. return rc;
  75443. }
  75444. /*
  75445. ** Sync the file.
  75446. */
  75447. static int jrnlSync(sqlite3_file *pJfd, int flags){
  75448. int rc;
  75449. JournalFile *p = (JournalFile *)pJfd;
  75450. if( p->pReal ){
  75451. rc = sqlite3OsSync(p->pReal, flags);
  75452. }else{
  75453. rc = SQLITE_OK;
  75454. }
  75455. return rc;
  75456. }
  75457. /*
  75458. ** Query the size of the file in bytes.
  75459. */
  75460. static int jrnlFileSize(sqlite3_file *pJfd, sqlite_int64 *pSize){
  75461. int rc = SQLITE_OK;
  75462. JournalFile *p = (JournalFile *)pJfd;
  75463. if( p->pReal ){
  75464. rc = sqlite3OsFileSize(p->pReal, pSize);
  75465. }else{
  75466. *pSize = (sqlite_int64) p->iSize;
  75467. }
  75468. return rc;
  75469. }
  75470. /*
  75471. ** Table of methods for JournalFile sqlite3_file object.
  75472. */
  75473. static struct sqlite3_io_methods JournalFileMethods = {
  75474. 1, /* iVersion */
  75475. jrnlClose, /* xClose */
  75476. jrnlRead, /* xRead */
  75477. jrnlWrite, /* xWrite */
  75478. jrnlTruncate, /* xTruncate */
  75479. jrnlSync, /* xSync */
  75480. jrnlFileSize, /* xFileSize */
  75481. 0, /* xLock */
  75482. 0, /* xUnlock */
  75483. 0, /* xCheckReservedLock */
  75484. 0, /* xFileControl */
  75485. 0, /* xSectorSize */
  75486. 0, /* xDeviceCharacteristics */
  75487. 0, /* xShmMap */
  75488. 0, /* xShmLock */
  75489. 0, /* xShmBarrier */
  75490. 0 /* xShmUnmap */
  75491. };
  75492. /*
  75493. ** Open a journal file.
  75494. */
  75495. SQLITE_PRIVATE int sqlite3JournalOpen(
  75496. sqlite3_vfs *pVfs, /* The VFS to use for actual file I/O */
  75497. const char *zName, /* Name of the journal file */
  75498. sqlite3_file *pJfd, /* Preallocated, blank file handle */
  75499. int flags, /* Opening flags */
  75500. int nBuf /* Bytes buffered before opening the file */
  75501. ){
  75502. JournalFile *p = (JournalFile *)pJfd;
  75503. memset(p, 0, sqlite3JournalSize(pVfs));
  75504. if( nBuf>0 ){
  75505. p->zBuf = sqlite3MallocZero(nBuf);
  75506. if( !p->zBuf ){
  75507. return SQLITE_NOMEM;
  75508. }
  75509. }else{
  75510. return sqlite3OsOpen(pVfs, zName, pJfd, flags, 0);
  75511. }
  75512. p->pMethod = &JournalFileMethods;
  75513. p->nBuf = nBuf;
  75514. p->flags = flags;
  75515. p->zJournal = zName;
  75516. p->pVfs = pVfs;
  75517. return SQLITE_OK;
  75518. }
  75519. /*
  75520. ** If the argument p points to a JournalFile structure, and the underlying
  75521. ** file has not yet been created, create it now.
  75522. */
  75523. SQLITE_PRIVATE int sqlite3JournalCreate(sqlite3_file *p){
  75524. if( p->pMethods!=&JournalFileMethods ){
  75525. return SQLITE_OK;
  75526. }
  75527. return createFile((JournalFile *)p);
  75528. }
  75529. /*
  75530. ** The file-handle passed as the only argument is guaranteed to be an open
  75531. ** file. It may or may not be of class JournalFile. If the file is a
  75532. ** JournalFile, and the underlying file on disk has not yet been opened,
  75533. ** return 0. Otherwise, return 1.
  75534. */
  75535. SQLITE_PRIVATE int sqlite3JournalExists(sqlite3_file *p){
  75536. return (p->pMethods!=&JournalFileMethods || ((JournalFile *)p)->pReal!=0);
  75537. }
  75538. /*
  75539. ** Return the number of bytes required to store a JournalFile that uses vfs
  75540. ** pVfs to create the underlying on-disk files.
  75541. */
  75542. SQLITE_PRIVATE int sqlite3JournalSize(sqlite3_vfs *pVfs){
  75543. return (pVfs->szOsFile+sizeof(JournalFile));
  75544. }
  75545. #endif
  75546. /************** End of journal.c *********************************************/
  75547. /************** Begin file memjournal.c **************************************/
  75548. /*
  75549. ** 2008 October 7
  75550. **
  75551. ** The author disclaims copyright to this source code. In place of
  75552. ** a legal notice, here is a blessing:
  75553. **
  75554. ** May you do good and not evil.
  75555. ** May you find forgiveness for yourself and forgive others.
  75556. ** May you share freely, never taking more than you give.
  75557. **
  75558. *************************************************************************
  75559. **
  75560. ** This file contains code use to implement an in-memory rollback journal.
  75561. ** The in-memory rollback journal is used to journal transactions for
  75562. ** ":memory:" databases and when the journal_mode=MEMORY pragma is used.
  75563. */
  75564. /* Forward references to internal structures */
  75565. typedef struct MemJournal MemJournal;
  75566. typedef struct FilePoint FilePoint;
  75567. typedef struct FileChunk FileChunk;
  75568. /* Space to hold the rollback journal is allocated in increments of
  75569. ** this many bytes.
  75570. **
  75571. ** The size chosen is a little less than a power of two. That way,
  75572. ** the FileChunk object will have a size that almost exactly fills
  75573. ** a power-of-two allocation. This minimizes wasted space in power-of-two
  75574. ** memory allocators.
  75575. */
  75576. #define JOURNAL_CHUNKSIZE ((int)(1024-sizeof(FileChunk*)))
  75577. /*
  75578. ** The rollback journal is composed of a linked list of these structures.
  75579. */
  75580. struct FileChunk {
  75581. FileChunk *pNext; /* Next chunk in the journal */
  75582. u8 zChunk[JOURNAL_CHUNKSIZE]; /* Content of this chunk */
  75583. };
  75584. /*
  75585. ** An instance of this object serves as a cursor into the rollback journal.
  75586. ** The cursor can be either for reading or writing.
  75587. */
  75588. struct FilePoint {
  75589. sqlite3_int64 iOffset; /* Offset from the beginning of the file */
  75590. FileChunk *pChunk; /* Specific chunk into which cursor points */
  75591. };
  75592. /*
  75593. ** This subclass is a subclass of sqlite3_file. Each open memory-journal
  75594. ** is an instance of this class.
  75595. */
  75596. struct MemJournal {
  75597. sqlite3_io_methods *pMethod; /* Parent class. MUST BE FIRST */
  75598. FileChunk *pFirst; /* Head of in-memory chunk-list */
  75599. FilePoint endpoint; /* Pointer to the end of the file */
  75600. FilePoint readpoint; /* Pointer to the end of the last xRead() */
  75601. };
  75602. /*
  75603. ** Read data from the in-memory journal file. This is the implementation
  75604. ** of the sqlite3_vfs.xRead method.
  75605. */
  75606. static int memjrnlRead(
  75607. sqlite3_file *pJfd, /* The journal file from which to read */
  75608. void *zBuf, /* Put the results here */
  75609. int iAmt, /* Number of bytes to read */
  75610. sqlite_int64 iOfst /* Begin reading at this offset */
  75611. ){
  75612. MemJournal *p = (MemJournal *)pJfd;
  75613. u8 *zOut = zBuf;
  75614. int nRead = iAmt;
  75615. int iChunkOffset;
  75616. FileChunk *pChunk;
  75617. /* SQLite never tries to read past the end of a rollback journal file */
  75618. assert( iOfst+iAmt<=p->endpoint.iOffset );
  75619. if( p->readpoint.iOffset!=iOfst || iOfst==0 ){
  75620. sqlite3_int64 iOff = 0;
  75621. for(pChunk=p->pFirst;
  75622. ALWAYS(pChunk) && (iOff+JOURNAL_CHUNKSIZE)<=iOfst;
  75623. pChunk=pChunk->pNext
  75624. ){
  75625. iOff += JOURNAL_CHUNKSIZE;
  75626. }
  75627. }else{
  75628. pChunk = p->readpoint.pChunk;
  75629. }
  75630. iChunkOffset = (int)(iOfst%JOURNAL_CHUNKSIZE);
  75631. do {
  75632. int iSpace = JOURNAL_CHUNKSIZE - iChunkOffset;
  75633. int nCopy = MIN(nRead, (JOURNAL_CHUNKSIZE - iChunkOffset));
  75634. memcpy(zOut, &pChunk->zChunk[iChunkOffset], nCopy);
  75635. zOut += nCopy;
  75636. nRead -= iSpace;
  75637. iChunkOffset = 0;
  75638. } while( nRead>=0 && (pChunk=pChunk->pNext)!=0 && nRead>0 );
  75639. p->readpoint.iOffset = iOfst+iAmt;
  75640. p->readpoint.pChunk = pChunk;
  75641. return SQLITE_OK;
  75642. }
  75643. /*
  75644. ** Write data to the file.
  75645. */
  75646. static int memjrnlWrite(
  75647. sqlite3_file *pJfd, /* The journal file into which to write */
  75648. const void *zBuf, /* Take data to be written from here */
  75649. int iAmt, /* Number of bytes to write */
  75650. sqlite_int64 iOfst /* Begin writing at this offset into the file */
  75651. ){
  75652. MemJournal *p = (MemJournal *)pJfd;
  75653. int nWrite = iAmt;
  75654. u8 *zWrite = (u8 *)zBuf;
  75655. /* An in-memory journal file should only ever be appended to. Random
  75656. ** access writes are not required by sqlite.
  75657. */
  75658. assert( iOfst==p->endpoint.iOffset );
  75659. UNUSED_PARAMETER(iOfst);
  75660. while( nWrite>0 ){
  75661. FileChunk *pChunk = p->endpoint.pChunk;
  75662. int iChunkOffset = (int)(p->endpoint.iOffset%JOURNAL_CHUNKSIZE);
  75663. int iSpace = MIN(nWrite, JOURNAL_CHUNKSIZE - iChunkOffset);
  75664. if( iChunkOffset==0 ){
  75665. /* New chunk is required to extend the file. */
  75666. FileChunk *pNew = sqlite3_malloc(sizeof(FileChunk));
  75667. if( !pNew ){
  75668. return SQLITE_IOERR_NOMEM;
  75669. }
  75670. pNew->pNext = 0;
  75671. if( pChunk ){
  75672. assert( p->pFirst );
  75673. pChunk->pNext = pNew;
  75674. }else{
  75675. assert( !p->pFirst );
  75676. p->pFirst = pNew;
  75677. }
  75678. p->endpoint.pChunk = pNew;
  75679. }
  75680. memcpy(&p->endpoint.pChunk->zChunk[iChunkOffset], zWrite, iSpace);
  75681. zWrite += iSpace;
  75682. nWrite -= iSpace;
  75683. p->endpoint.iOffset += iSpace;
  75684. }
  75685. return SQLITE_OK;
  75686. }
  75687. /*
  75688. ** Truncate the file.
  75689. */
  75690. static int memjrnlTruncate(sqlite3_file *pJfd, sqlite_int64 size){
  75691. MemJournal *p = (MemJournal *)pJfd;
  75692. FileChunk *pChunk;
  75693. assert(size==0);
  75694. UNUSED_PARAMETER(size);
  75695. pChunk = p->pFirst;
  75696. while( pChunk ){
  75697. FileChunk *pTmp = pChunk;
  75698. pChunk = pChunk->pNext;
  75699. sqlite3_free(pTmp);
  75700. }
  75701. sqlite3MemJournalOpen(pJfd);
  75702. return SQLITE_OK;
  75703. }
  75704. /*
  75705. ** Close the file.
  75706. */
  75707. static int memjrnlClose(sqlite3_file *pJfd){
  75708. memjrnlTruncate(pJfd, 0);
  75709. return SQLITE_OK;
  75710. }
  75711. /*
  75712. ** Sync the file.
  75713. **
  75714. ** Syncing an in-memory journal is a no-op. And, in fact, this routine
  75715. ** is never called in a working implementation. This implementation
  75716. ** exists purely as a contingency, in case some malfunction in some other
  75717. ** part of SQLite causes Sync to be called by mistake.
  75718. */
  75719. static int memjrnlSync(sqlite3_file *NotUsed, int NotUsed2){
  75720. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  75721. return SQLITE_OK;
  75722. }
  75723. /*
  75724. ** Query the size of the file in bytes.
  75725. */
  75726. static int memjrnlFileSize(sqlite3_file *pJfd, sqlite_int64 *pSize){
  75727. MemJournal *p = (MemJournal *)pJfd;
  75728. *pSize = (sqlite_int64) p->endpoint.iOffset;
  75729. return SQLITE_OK;
  75730. }
  75731. /*
  75732. ** Table of methods for MemJournal sqlite3_file object.
  75733. */
  75734. static const struct sqlite3_io_methods MemJournalMethods = {
  75735. 1, /* iVersion */
  75736. memjrnlClose, /* xClose */
  75737. memjrnlRead, /* xRead */
  75738. memjrnlWrite, /* xWrite */
  75739. memjrnlTruncate, /* xTruncate */
  75740. memjrnlSync, /* xSync */
  75741. memjrnlFileSize, /* xFileSize */
  75742. 0, /* xLock */
  75743. 0, /* xUnlock */
  75744. 0, /* xCheckReservedLock */
  75745. 0, /* xFileControl */
  75746. 0, /* xSectorSize */
  75747. 0, /* xDeviceCharacteristics */
  75748. 0, /* xShmMap */
  75749. 0, /* xShmLock */
  75750. 0, /* xShmBarrier */
  75751. 0, /* xShmUnmap */
  75752. 0, /* xFetch */
  75753. 0 /* xUnfetch */
  75754. };
  75755. /*
  75756. ** Open a journal file.
  75757. */
  75758. SQLITE_PRIVATE void sqlite3MemJournalOpen(sqlite3_file *pJfd){
  75759. MemJournal *p = (MemJournal *)pJfd;
  75760. assert( EIGHT_BYTE_ALIGNMENT(p) );
  75761. memset(p, 0, sqlite3MemJournalSize());
  75762. p->pMethod = (sqlite3_io_methods*)&MemJournalMethods;
  75763. }
  75764. /*
  75765. ** Return true if the file-handle passed as an argument is
  75766. ** an in-memory journal
  75767. */
  75768. SQLITE_PRIVATE int sqlite3IsMemJournal(sqlite3_file *pJfd){
  75769. return pJfd->pMethods==&MemJournalMethods;
  75770. }
  75771. /*
  75772. ** Return the number of bytes required to store a MemJournal file descriptor.
  75773. */
  75774. SQLITE_PRIVATE int sqlite3MemJournalSize(void){
  75775. return sizeof(MemJournal);
  75776. }
  75777. /************** End of memjournal.c ******************************************/
  75778. /************** Begin file walker.c ******************************************/
  75779. /*
  75780. ** 2008 August 16
  75781. **
  75782. ** The author disclaims copyright to this source code. In place of
  75783. ** a legal notice, here is a blessing:
  75784. **
  75785. ** May you do good and not evil.
  75786. ** May you find forgiveness for yourself and forgive others.
  75787. ** May you share freely, never taking more than you give.
  75788. **
  75789. *************************************************************************
  75790. ** This file contains routines used for walking the parser tree for
  75791. ** an SQL statement.
  75792. */
  75793. /* #include <stdlib.h> */
  75794. /* #include <string.h> */
  75795. /*
  75796. ** Walk an expression tree. Invoke the callback once for each node
  75797. ** of the expression, while descending. (In other words, the callback
  75798. ** is invoked before visiting children.)
  75799. **
  75800. ** The return value from the callback should be one of the WRC_*
  75801. ** constants to specify how to proceed with the walk.
  75802. **
  75803. ** WRC_Continue Continue descending down the tree.
  75804. **
  75805. ** WRC_Prune Do not descend into child nodes. But allow
  75806. ** the walk to continue with sibling nodes.
  75807. **
  75808. ** WRC_Abort Do no more callbacks. Unwind the stack and
  75809. ** return the top-level walk call.
  75810. **
  75811. ** The return value from this routine is WRC_Abort to abandon the tree walk
  75812. ** and WRC_Continue to continue.
  75813. */
  75814. SQLITE_PRIVATE int sqlite3WalkExpr(Walker *pWalker, Expr *pExpr){
  75815. int rc;
  75816. if( pExpr==0 ) return WRC_Continue;
  75817. testcase( ExprHasProperty(pExpr, EP_TokenOnly) );
  75818. testcase( ExprHasProperty(pExpr, EP_Reduced) );
  75819. rc = pWalker->xExprCallback(pWalker, pExpr);
  75820. if( rc==WRC_Continue
  75821. && !ExprHasProperty(pExpr,EP_TokenOnly) ){
  75822. if( sqlite3WalkExpr(pWalker, pExpr->pLeft) ) return WRC_Abort;
  75823. if( sqlite3WalkExpr(pWalker, pExpr->pRight) ) return WRC_Abort;
  75824. if( ExprHasProperty(pExpr, EP_xIsSelect) ){
  75825. if( sqlite3WalkSelect(pWalker, pExpr->x.pSelect) ) return WRC_Abort;
  75826. }else{
  75827. if( sqlite3WalkExprList(pWalker, pExpr->x.pList) ) return WRC_Abort;
  75828. }
  75829. }
  75830. return rc & WRC_Abort;
  75831. }
  75832. /*
  75833. ** Call sqlite3WalkExpr() for every expression in list p or until
  75834. ** an abort request is seen.
  75835. */
  75836. SQLITE_PRIVATE int sqlite3WalkExprList(Walker *pWalker, ExprList *p){
  75837. int i;
  75838. struct ExprList_item *pItem;
  75839. if( p ){
  75840. for(i=p->nExpr, pItem=p->a; i>0; i--, pItem++){
  75841. if( sqlite3WalkExpr(pWalker, pItem->pExpr) ) return WRC_Abort;
  75842. }
  75843. }
  75844. return WRC_Continue;
  75845. }
  75846. /*
  75847. ** Walk all expressions associated with SELECT statement p. Do
  75848. ** not invoke the SELECT callback on p, but do (of course) invoke
  75849. ** any expr callbacks and SELECT callbacks that come from subqueries.
  75850. ** Return WRC_Abort or WRC_Continue.
  75851. */
  75852. SQLITE_PRIVATE int sqlite3WalkSelectExpr(Walker *pWalker, Select *p){
  75853. if( sqlite3WalkExprList(pWalker, p->pEList) ) return WRC_Abort;
  75854. if( sqlite3WalkExpr(pWalker, p->pWhere) ) return WRC_Abort;
  75855. if( sqlite3WalkExprList(pWalker, p->pGroupBy) ) return WRC_Abort;
  75856. if( sqlite3WalkExpr(pWalker, p->pHaving) ) return WRC_Abort;
  75857. if( sqlite3WalkExprList(pWalker, p->pOrderBy) ) return WRC_Abort;
  75858. if( sqlite3WalkExpr(pWalker, p->pLimit) ) return WRC_Abort;
  75859. if( sqlite3WalkExpr(pWalker, p->pOffset) ) return WRC_Abort;
  75860. return WRC_Continue;
  75861. }
  75862. /*
  75863. ** Walk the parse trees associated with all subqueries in the
  75864. ** FROM clause of SELECT statement p. Do not invoke the select
  75865. ** callback on p, but do invoke it on each FROM clause subquery
  75866. ** and on any subqueries further down in the tree. Return
  75867. ** WRC_Abort or WRC_Continue;
  75868. */
  75869. SQLITE_PRIVATE int sqlite3WalkSelectFrom(Walker *pWalker, Select *p){
  75870. SrcList *pSrc;
  75871. int i;
  75872. struct SrcList_item *pItem;
  75873. pSrc = p->pSrc;
  75874. if( ALWAYS(pSrc) ){
  75875. for(i=pSrc->nSrc, pItem=pSrc->a; i>0; i--, pItem++){
  75876. if( sqlite3WalkSelect(pWalker, pItem->pSelect) ){
  75877. return WRC_Abort;
  75878. }
  75879. }
  75880. }
  75881. return WRC_Continue;
  75882. }
  75883. /*
  75884. ** Call sqlite3WalkExpr() for every expression in Select statement p.
  75885. ** Invoke sqlite3WalkSelect() for subqueries in the FROM clause and
  75886. ** on the compound select chain, p->pPrior.
  75887. **
  75888. ** If it is not NULL, the xSelectCallback() callback is invoked before
  75889. ** the walk of the expressions and FROM clause. The xSelectCallback2()
  75890. ** method, if it is not NULL, is invoked following the walk of the
  75891. ** expressions and FROM clause.
  75892. **
  75893. ** Return WRC_Continue under normal conditions. Return WRC_Abort if
  75894. ** there is an abort request.
  75895. **
  75896. ** If the Walker does not have an xSelectCallback() then this routine
  75897. ** is a no-op returning WRC_Continue.
  75898. */
  75899. SQLITE_PRIVATE int sqlite3WalkSelect(Walker *pWalker, Select *p){
  75900. int rc;
  75901. if( p==0 || (pWalker->xSelectCallback==0 && pWalker->xSelectCallback2==0) ){
  75902. return WRC_Continue;
  75903. }
  75904. rc = WRC_Continue;
  75905. pWalker->walkerDepth++;
  75906. while( p ){
  75907. if( pWalker->xSelectCallback ){
  75908. rc = pWalker->xSelectCallback(pWalker, p);
  75909. if( rc ) break;
  75910. }
  75911. if( sqlite3WalkSelectExpr(pWalker, p)
  75912. || sqlite3WalkSelectFrom(pWalker, p)
  75913. ){
  75914. pWalker->walkerDepth--;
  75915. return WRC_Abort;
  75916. }
  75917. if( pWalker->xSelectCallback2 ){
  75918. pWalker->xSelectCallback2(pWalker, p);
  75919. }
  75920. p = p->pPrior;
  75921. }
  75922. pWalker->walkerDepth--;
  75923. return rc & WRC_Abort;
  75924. }
  75925. /************** End of walker.c **********************************************/
  75926. /************** Begin file resolve.c *****************************************/
  75927. /*
  75928. ** 2008 August 18
  75929. **
  75930. ** The author disclaims copyright to this source code. In place of
  75931. ** a legal notice, here is a blessing:
  75932. **
  75933. ** May you do good and not evil.
  75934. ** May you find forgiveness for yourself and forgive others.
  75935. ** May you share freely, never taking more than you give.
  75936. **
  75937. *************************************************************************
  75938. **
  75939. ** This file contains routines used for walking the parser tree and
  75940. ** resolve all identifiers by associating them with a particular
  75941. ** table and column.
  75942. */
  75943. /* #include <stdlib.h> */
  75944. /* #include <string.h> */
  75945. /*
  75946. ** Walk the expression tree pExpr and increase the aggregate function
  75947. ** depth (the Expr.op2 field) by N on every TK_AGG_FUNCTION node.
  75948. ** This needs to occur when copying a TK_AGG_FUNCTION node from an
  75949. ** outer query into an inner subquery.
  75950. **
  75951. ** incrAggFunctionDepth(pExpr,n) is the main routine. incrAggDepth(..)
  75952. ** is a helper function - a callback for the tree walker.
  75953. */
  75954. static int incrAggDepth(Walker *pWalker, Expr *pExpr){
  75955. if( pExpr->op==TK_AGG_FUNCTION ) pExpr->op2 += pWalker->u.n;
  75956. return WRC_Continue;
  75957. }
  75958. static void incrAggFunctionDepth(Expr *pExpr, int N){
  75959. if( N>0 ){
  75960. Walker w;
  75961. memset(&w, 0, sizeof(w));
  75962. w.xExprCallback = incrAggDepth;
  75963. w.u.n = N;
  75964. sqlite3WalkExpr(&w, pExpr);
  75965. }
  75966. }
  75967. /*
  75968. ** Turn the pExpr expression into an alias for the iCol-th column of the
  75969. ** result set in pEList.
  75970. **
  75971. ** If the result set column is a simple column reference, then this routine
  75972. ** makes an exact copy. But for any other kind of expression, this
  75973. ** routine make a copy of the result set column as the argument to the
  75974. ** TK_AS operator. The TK_AS operator causes the expression to be
  75975. ** evaluated just once and then reused for each alias.
  75976. **
  75977. ** The reason for suppressing the TK_AS term when the expression is a simple
  75978. ** column reference is so that the column reference will be recognized as
  75979. ** usable by indices within the WHERE clause processing logic.
  75980. **
  75981. ** The TK_AS operator is inhibited if zType[0]=='G'. This means
  75982. ** that in a GROUP BY clause, the expression is evaluated twice. Hence:
  75983. **
  75984. ** SELECT random()%5 AS x, count(*) FROM tab GROUP BY x
  75985. **
  75986. ** Is equivalent to:
  75987. **
  75988. ** SELECT random()%5 AS x, count(*) FROM tab GROUP BY random()%5
  75989. **
  75990. ** The result of random()%5 in the GROUP BY clause is probably different
  75991. ** from the result in the result-set. On the other hand Standard SQL does
  75992. ** not allow the GROUP BY clause to contain references to result-set columns.
  75993. ** So this should never come up in well-formed queries.
  75994. **
  75995. ** If the reference is followed by a COLLATE operator, then make sure
  75996. ** the COLLATE operator is preserved. For example:
  75997. **
  75998. ** SELECT a+b, c+d FROM t1 ORDER BY 1 COLLATE nocase;
  75999. **
  76000. ** Should be transformed into:
  76001. **
  76002. ** SELECT a+b, c+d FROM t1 ORDER BY (a+b) COLLATE nocase;
  76003. **
  76004. ** The nSubquery parameter specifies how many levels of subquery the
  76005. ** alias is removed from the original expression. The usual value is
  76006. ** zero but it might be more if the alias is contained within a subquery
  76007. ** of the original expression. The Expr.op2 field of TK_AGG_FUNCTION
  76008. ** structures must be increased by the nSubquery amount.
  76009. */
  76010. static void resolveAlias(
  76011. Parse *pParse, /* Parsing context */
  76012. ExprList *pEList, /* A result set */
  76013. int iCol, /* A column in the result set. 0..pEList->nExpr-1 */
  76014. Expr *pExpr, /* Transform this into an alias to the result set */
  76015. const char *zType, /* "GROUP" or "ORDER" or "" */
  76016. int nSubquery /* Number of subqueries that the label is moving */
  76017. ){
  76018. Expr *pOrig; /* The iCol-th column of the result set */
  76019. Expr *pDup; /* Copy of pOrig */
  76020. sqlite3 *db; /* The database connection */
  76021. assert( iCol>=0 && iCol<pEList->nExpr );
  76022. pOrig = pEList->a[iCol].pExpr;
  76023. assert( pOrig!=0 );
  76024. db = pParse->db;
  76025. pDup = sqlite3ExprDup(db, pOrig, 0);
  76026. if( pDup==0 ) return;
  76027. if( pOrig->op!=TK_COLUMN && zType[0]!='G' ){
  76028. incrAggFunctionDepth(pDup, nSubquery);
  76029. pDup = sqlite3PExpr(pParse, TK_AS, pDup, 0, 0);
  76030. if( pDup==0 ) return;
  76031. ExprSetProperty(pDup, EP_Skip);
  76032. if( pEList->a[iCol].u.x.iAlias==0 ){
  76033. pEList->a[iCol].u.x.iAlias = (u16)(++pParse->nAlias);
  76034. }
  76035. pDup->iTable = pEList->a[iCol].u.x.iAlias;
  76036. }
  76037. if( pExpr->op==TK_COLLATE ){
  76038. pDup = sqlite3ExprAddCollateString(pParse, pDup, pExpr->u.zToken);
  76039. }
  76040. /* Before calling sqlite3ExprDelete(), set the EP_Static flag. This
  76041. ** prevents ExprDelete() from deleting the Expr structure itself,
  76042. ** allowing it to be repopulated by the memcpy() on the following line.
  76043. ** The pExpr->u.zToken might point into memory that will be freed by the
  76044. ** sqlite3DbFree(db, pDup) on the last line of this block, so be sure to
  76045. ** make a copy of the token before doing the sqlite3DbFree().
  76046. */
  76047. ExprSetProperty(pExpr, EP_Static);
  76048. sqlite3ExprDelete(db, pExpr);
  76049. memcpy(pExpr, pDup, sizeof(*pExpr));
  76050. if( !ExprHasProperty(pExpr, EP_IntValue) && pExpr->u.zToken!=0 ){
  76051. assert( (pExpr->flags & (EP_Reduced|EP_TokenOnly))==0 );
  76052. pExpr->u.zToken = sqlite3DbStrDup(db, pExpr->u.zToken);
  76053. pExpr->flags |= EP_MemToken;
  76054. }
  76055. sqlite3DbFree(db, pDup);
  76056. }
  76057. /*
  76058. ** Return TRUE if the name zCol occurs anywhere in the USING clause.
  76059. **
  76060. ** Return FALSE if the USING clause is NULL or if it does not contain
  76061. ** zCol.
  76062. */
  76063. static int nameInUsingClause(IdList *pUsing, const char *zCol){
  76064. if( pUsing ){
  76065. int k;
  76066. for(k=0; k<pUsing->nId; k++){
  76067. if( sqlite3StrICmp(pUsing->a[k].zName, zCol)==0 ) return 1;
  76068. }
  76069. }
  76070. return 0;
  76071. }
  76072. /*
  76073. ** Subqueries stores the original database, table and column names for their
  76074. ** result sets in ExprList.a[].zSpan, in the form "DATABASE.TABLE.COLUMN".
  76075. ** Check to see if the zSpan given to this routine matches the zDb, zTab,
  76076. ** and zCol. If any of zDb, zTab, and zCol are NULL then those fields will
  76077. ** match anything.
  76078. */
  76079. SQLITE_PRIVATE int sqlite3MatchSpanName(
  76080. const char *zSpan,
  76081. const char *zCol,
  76082. const char *zTab,
  76083. const char *zDb
  76084. ){
  76085. int n;
  76086. for(n=0; ALWAYS(zSpan[n]) && zSpan[n]!='.'; n++){}
  76087. if( zDb && (sqlite3StrNICmp(zSpan, zDb, n)!=0 || zDb[n]!=0) ){
  76088. return 0;
  76089. }
  76090. zSpan += n+1;
  76091. for(n=0; ALWAYS(zSpan[n]) && zSpan[n]!='.'; n++){}
  76092. if( zTab && (sqlite3StrNICmp(zSpan, zTab, n)!=0 || zTab[n]!=0) ){
  76093. return 0;
  76094. }
  76095. zSpan += n+1;
  76096. if( zCol && sqlite3StrICmp(zSpan, zCol)!=0 ){
  76097. return 0;
  76098. }
  76099. return 1;
  76100. }
  76101. /*
  76102. ** Given the name of a column of the form X.Y.Z or Y.Z or just Z, look up
  76103. ** that name in the set of source tables in pSrcList and make the pExpr
  76104. ** expression node refer back to that source column. The following changes
  76105. ** are made to pExpr:
  76106. **
  76107. ** pExpr->iDb Set the index in db->aDb[] of the database X
  76108. ** (even if X is implied).
  76109. ** pExpr->iTable Set to the cursor number for the table obtained
  76110. ** from pSrcList.
  76111. ** pExpr->pTab Points to the Table structure of X.Y (even if
  76112. ** X and/or Y are implied.)
  76113. ** pExpr->iColumn Set to the column number within the table.
  76114. ** pExpr->op Set to TK_COLUMN.
  76115. ** pExpr->pLeft Any expression this points to is deleted
  76116. ** pExpr->pRight Any expression this points to is deleted.
  76117. **
  76118. ** The zDb variable is the name of the database (the "X"). This value may be
  76119. ** NULL meaning that name is of the form Y.Z or Z. Any available database
  76120. ** can be used. The zTable variable is the name of the table (the "Y"). This
  76121. ** value can be NULL if zDb is also NULL. If zTable is NULL it
  76122. ** means that the form of the name is Z and that columns from any table
  76123. ** can be used.
  76124. **
  76125. ** If the name cannot be resolved unambiguously, leave an error message
  76126. ** in pParse and return WRC_Abort. Return WRC_Prune on success.
  76127. */
  76128. static int lookupName(
  76129. Parse *pParse, /* The parsing context */
  76130. const char *zDb, /* Name of the database containing table, or NULL */
  76131. const char *zTab, /* Name of table containing column, or NULL */
  76132. const char *zCol, /* Name of the column. */
  76133. NameContext *pNC, /* The name context used to resolve the name */
  76134. Expr *pExpr /* Make this EXPR node point to the selected column */
  76135. ){
  76136. int i, j; /* Loop counters */
  76137. int cnt = 0; /* Number of matching column names */
  76138. int cntTab = 0; /* Number of matching table names */
  76139. int nSubquery = 0; /* How many levels of subquery */
  76140. sqlite3 *db = pParse->db; /* The database connection */
  76141. struct SrcList_item *pItem; /* Use for looping over pSrcList items */
  76142. struct SrcList_item *pMatch = 0; /* The matching pSrcList item */
  76143. NameContext *pTopNC = pNC; /* First namecontext in the list */
  76144. Schema *pSchema = 0; /* Schema of the expression */
  76145. int isTrigger = 0; /* True if resolved to a trigger column */
  76146. Table *pTab = 0; /* Table hold the row */
  76147. Column *pCol; /* A column of pTab */
  76148. assert( pNC ); /* the name context cannot be NULL. */
  76149. assert( zCol ); /* The Z in X.Y.Z cannot be NULL */
  76150. assert( !ExprHasProperty(pExpr, EP_TokenOnly|EP_Reduced) );
  76151. /* Initialize the node to no-match */
  76152. pExpr->iTable = -1;
  76153. pExpr->pTab = 0;
  76154. ExprSetVVAProperty(pExpr, EP_NoReduce);
  76155. /* Translate the schema name in zDb into a pointer to the corresponding
  76156. ** schema. If not found, pSchema will remain NULL and nothing will match
  76157. ** resulting in an appropriate error message toward the end of this routine
  76158. */
  76159. if( zDb ){
  76160. testcase( pNC->ncFlags & NC_PartIdx );
  76161. testcase( pNC->ncFlags & NC_IsCheck );
  76162. if( (pNC->ncFlags & (NC_PartIdx|NC_IsCheck))!=0 ){
  76163. /* Silently ignore database qualifiers inside CHECK constraints and
  76164. ** partial indices. Do not raise errors because that might break
  76165. ** legacy and because it does not hurt anything to just ignore the
  76166. ** database name. */
  76167. zDb = 0;
  76168. }else{
  76169. for(i=0; i<db->nDb; i++){
  76170. assert( db->aDb[i].zName );
  76171. if( sqlite3StrICmp(db->aDb[i].zName,zDb)==0 ){
  76172. pSchema = db->aDb[i].pSchema;
  76173. break;
  76174. }
  76175. }
  76176. }
  76177. }
  76178. /* Start at the inner-most context and move outward until a match is found */
  76179. while( pNC && cnt==0 ){
  76180. ExprList *pEList;
  76181. SrcList *pSrcList = pNC->pSrcList;
  76182. if( pSrcList ){
  76183. for(i=0, pItem=pSrcList->a; i<pSrcList->nSrc; i++, pItem++){
  76184. pTab = pItem->pTab;
  76185. assert( pTab!=0 && pTab->zName!=0 );
  76186. assert( pTab->nCol>0 );
  76187. if( pItem->pSelect && (pItem->pSelect->selFlags & SF_NestedFrom)!=0 ){
  76188. int hit = 0;
  76189. pEList = pItem->pSelect->pEList;
  76190. for(j=0; j<pEList->nExpr; j++){
  76191. if( sqlite3MatchSpanName(pEList->a[j].zSpan, zCol, zTab, zDb) ){
  76192. cnt++;
  76193. cntTab = 2;
  76194. pMatch = pItem;
  76195. pExpr->iColumn = j;
  76196. hit = 1;
  76197. }
  76198. }
  76199. if( hit || zTab==0 ) continue;
  76200. }
  76201. if( zDb && pTab->pSchema!=pSchema ){
  76202. continue;
  76203. }
  76204. if( zTab ){
  76205. const char *zTabName = pItem->zAlias ? pItem->zAlias : pTab->zName;
  76206. assert( zTabName!=0 );
  76207. if( sqlite3StrICmp(zTabName, zTab)!=0 ){
  76208. continue;
  76209. }
  76210. }
  76211. if( 0==(cntTab++) ){
  76212. pMatch = pItem;
  76213. }
  76214. for(j=0, pCol=pTab->aCol; j<pTab->nCol; j++, pCol++){
  76215. if( sqlite3StrICmp(pCol->zName, zCol)==0 ){
  76216. /* If there has been exactly one prior match and this match
  76217. ** is for the right-hand table of a NATURAL JOIN or is in a
  76218. ** USING clause, then skip this match.
  76219. */
  76220. if( cnt==1 ){
  76221. if( pItem->jointype & JT_NATURAL ) continue;
  76222. if( nameInUsingClause(pItem->pUsing, zCol) ) continue;
  76223. }
  76224. cnt++;
  76225. pMatch = pItem;
  76226. /* Substitute the rowid (column -1) for the INTEGER PRIMARY KEY */
  76227. pExpr->iColumn = j==pTab->iPKey ? -1 : (i16)j;
  76228. break;
  76229. }
  76230. }
  76231. }
  76232. if( pMatch ){
  76233. pExpr->iTable = pMatch->iCursor;
  76234. pExpr->pTab = pMatch->pTab;
  76235. /* RIGHT JOIN not (yet) supported */
  76236. assert( (pMatch->jointype & JT_RIGHT)==0 );
  76237. if( (pMatch->jointype & JT_LEFT)!=0 ){
  76238. ExprSetProperty(pExpr, EP_CanBeNull);
  76239. }
  76240. pSchema = pExpr->pTab->pSchema;
  76241. }
  76242. } /* if( pSrcList ) */
  76243. #ifndef SQLITE_OMIT_TRIGGER
  76244. /* If we have not already resolved the name, then maybe
  76245. ** it is a new.* or old.* trigger argument reference
  76246. */
  76247. if( zDb==0 && zTab!=0 && cntTab==0 && pParse->pTriggerTab!=0 ){
  76248. int op = pParse->eTriggerOp;
  76249. assert( op==TK_DELETE || op==TK_UPDATE || op==TK_INSERT );
  76250. if( op!=TK_DELETE && sqlite3StrICmp("new",zTab) == 0 ){
  76251. pExpr->iTable = 1;
  76252. pTab = pParse->pTriggerTab;
  76253. }else if( op!=TK_INSERT && sqlite3StrICmp("old",zTab)==0 ){
  76254. pExpr->iTable = 0;
  76255. pTab = pParse->pTriggerTab;
  76256. }else{
  76257. pTab = 0;
  76258. }
  76259. if( pTab ){
  76260. int iCol;
  76261. pSchema = pTab->pSchema;
  76262. cntTab++;
  76263. for(iCol=0, pCol=pTab->aCol; iCol<pTab->nCol; iCol++, pCol++){
  76264. if( sqlite3StrICmp(pCol->zName, zCol)==0 ){
  76265. if( iCol==pTab->iPKey ){
  76266. iCol = -1;
  76267. }
  76268. break;
  76269. }
  76270. }
  76271. if( iCol>=pTab->nCol && sqlite3IsRowid(zCol) && HasRowid(pTab) ){
  76272. /* IMP: R-51414-32910 */
  76273. /* IMP: R-44911-55124 */
  76274. iCol = -1;
  76275. }
  76276. if( iCol<pTab->nCol ){
  76277. cnt++;
  76278. if( iCol<0 ){
  76279. pExpr->affinity = SQLITE_AFF_INTEGER;
  76280. }else if( pExpr->iTable==0 ){
  76281. testcase( iCol==31 );
  76282. testcase( iCol==32 );
  76283. pParse->oldmask |= (iCol>=32 ? 0xffffffff : (((u32)1)<<iCol));
  76284. }else{
  76285. testcase( iCol==31 );
  76286. testcase( iCol==32 );
  76287. pParse->newmask |= (iCol>=32 ? 0xffffffff : (((u32)1)<<iCol));
  76288. }
  76289. pExpr->iColumn = (i16)iCol;
  76290. pExpr->pTab = pTab;
  76291. isTrigger = 1;
  76292. }
  76293. }
  76294. }
  76295. #endif /* !defined(SQLITE_OMIT_TRIGGER) */
  76296. /*
  76297. ** Perhaps the name is a reference to the ROWID
  76298. */
  76299. if( cnt==0 && cntTab==1 && pMatch && sqlite3IsRowid(zCol)
  76300. && HasRowid(pMatch->pTab) ){
  76301. cnt = 1;
  76302. pExpr->iColumn = -1; /* IMP: R-44911-55124 */
  76303. pExpr->affinity = SQLITE_AFF_INTEGER;
  76304. }
  76305. /*
  76306. ** If the input is of the form Z (not Y.Z or X.Y.Z) then the name Z
  76307. ** might refer to an result-set alias. This happens, for example, when
  76308. ** we are resolving names in the WHERE clause of the following command:
  76309. **
  76310. ** SELECT a+b AS x FROM table WHERE x<10;
  76311. **
  76312. ** In cases like this, replace pExpr with a copy of the expression that
  76313. ** forms the result set entry ("a+b" in the example) and return immediately.
  76314. ** Note that the expression in the result set should have already been
  76315. ** resolved by the time the WHERE clause is resolved.
  76316. **
  76317. ** The ability to use an output result-set column in the WHERE, GROUP BY,
  76318. ** or HAVING clauses, or as part of a larger expression in the ORDRE BY
  76319. ** clause is not standard SQL. This is a (goofy) SQLite extension, that
  76320. ** is supported for backwards compatibility only. TO DO: Issue a warning
  76321. ** on sqlite3_log() whenever the capability is used.
  76322. */
  76323. if( (pEList = pNC->pEList)!=0
  76324. && zTab==0
  76325. && cnt==0
  76326. ){
  76327. for(j=0; j<pEList->nExpr; j++){
  76328. char *zAs = pEList->a[j].zName;
  76329. if( zAs!=0 && sqlite3StrICmp(zAs, zCol)==0 ){
  76330. Expr *pOrig;
  76331. assert( pExpr->pLeft==0 && pExpr->pRight==0 );
  76332. assert( pExpr->x.pList==0 );
  76333. assert( pExpr->x.pSelect==0 );
  76334. pOrig = pEList->a[j].pExpr;
  76335. if( (pNC->ncFlags&NC_AllowAgg)==0 && ExprHasProperty(pOrig, EP_Agg) ){
  76336. sqlite3ErrorMsg(pParse, "misuse of aliased aggregate %s", zAs);
  76337. return WRC_Abort;
  76338. }
  76339. resolveAlias(pParse, pEList, j, pExpr, "", nSubquery);
  76340. cnt = 1;
  76341. pMatch = 0;
  76342. assert( zTab==0 && zDb==0 );
  76343. goto lookupname_end;
  76344. }
  76345. }
  76346. }
  76347. /* Advance to the next name context. The loop will exit when either
  76348. ** we have a match (cnt>0) or when we run out of name contexts.
  76349. */
  76350. if( cnt==0 ){
  76351. pNC = pNC->pNext;
  76352. nSubquery++;
  76353. }
  76354. }
  76355. /*
  76356. ** If X and Y are NULL (in other words if only the column name Z is
  76357. ** supplied) and the value of Z is enclosed in double-quotes, then
  76358. ** Z is a string literal if it doesn't match any column names. In that
  76359. ** case, we need to return right away and not make any changes to
  76360. ** pExpr.
  76361. **
  76362. ** Because no reference was made to outer contexts, the pNC->nRef
  76363. ** fields are not changed in any context.
  76364. */
  76365. if( cnt==0 && zTab==0 && ExprHasProperty(pExpr,EP_DblQuoted) ){
  76366. pExpr->op = TK_STRING;
  76367. pExpr->pTab = 0;
  76368. return WRC_Prune;
  76369. }
  76370. /*
  76371. ** cnt==0 means there was not match. cnt>1 means there were two or
  76372. ** more matches. Either way, we have an error.
  76373. */
  76374. if( cnt!=1 ){
  76375. const char *zErr;
  76376. zErr = cnt==0 ? "no such column" : "ambiguous column name";
  76377. if( zDb ){
  76378. sqlite3ErrorMsg(pParse, "%s: %s.%s.%s", zErr, zDb, zTab, zCol);
  76379. }else if( zTab ){
  76380. sqlite3ErrorMsg(pParse, "%s: %s.%s", zErr, zTab, zCol);
  76381. }else{
  76382. sqlite3ErrorMsg(pParse, "%s: %s", zErr, zCol);
  76383. }
  76384. pParse->checkSchema = 1;
  76385. pTopNC->nErr++;
  76386. }
  76387. /* If a column from a table in pSrcList is referenced, then record
  76388. ** this fact in the pSrcList.a[].colUsed bitmask. Column 0 causes
  76389. ** bit 0 to be set. Column 1 sets bit 1. And so forth. If the
  76390. ** column number is greater than the number of bits in the bitmask
  76391. ** then set the high-order bit of the bitmask.
  76392. */
  76393. if( pExpr->iColumn>=0 && pMatch!=0 ){
  76394. int n = pExpr->iColumn;
  76395. testcase( n==BMS-1 );
  76396. if( n>=BMS ){
  76397. n = BMS-1;
  76398. }
  76399. assert( pMatch->iCursor==pExpr->iTable );
  76400. pMatch->colUsed |= ((Bitmask)1)<<n;
  76401. }
  76402. /* Clean up and return
  76403. */
  76404. sqlite3ExprDelete(db, pExpr->pLeft);
  76405. pExpr->pLeft = 0;
  76406. sqlite3ExprDelete(db, pExpr->pRight);
  76407. pExpr->pRight = 0;
  76408. pExpr->op = (isTrigger ? TK_TRIGGER : TK_COLUMN);
  76409. lookupname_end:
  76410. if( cnt==1 ){
  76411. assert( pNC!=0 );
  76412. if( pExpr->op!=TK_AS ){
  76413. sqlite3AuthRead(pParse, pExpr, pSchema, pNC->pSrcList);
  76414. }
  76415. /* Increment the nRef value on all name contexts from TopNC up to
  76416. ** the point where the name matched. */
  76417. for(;;){
  76418. assert( pTopNC!=0 );
  76419. pTopNC->nRef++;
  76420. if( pTopNC==pNC ) break;
  76421. pTopNC = pTopNC->pNext;
  76422. }
  76423. return WRC_Prune;
  76424. } else {
  76425. return WRC_Abort;
  76426. }
  76427. }
  76428. /*
  76429. ** Allocate and return a pointer to an expression to load the column iCol
  76430. ** from datasource iSrc in SrcList pSrc.
  76431. */
  76432. SQLITE_PRIVATE Expr *sqlite3CreateColumnExpr(sqlite3 *db, SrcList *pSrc, int iSrc, int iCol){
  76433. Expr *p = sqlite3ExprAlloc(db, TK_COLUMN, 0, 0);
  76434. if( p ){
  76435. struct SrcList_item *pItem = &pSrc->a[iSrc];
  76436. p->pTab = pItem->pTab;
  76437. p->iTable = pItem->iCursor;
  76438. if( p->pTab->iPKey==iCol ){
  76439. p->iColumn = -1;
  76440. }else{
  76441. p->iColumn = (ynVar)iCol;
  76442. testcase( iCol==BMS );
  76443. testcase( iCol==BMS-1 );
  76444. pItem->colUsed |= ((Bitmask)1)<<(iCol>=BMS ? BMS-1 : iCol);
  76445. }
  76446. ExprSetProperty(p, EP_Resolved);
  76447. }
  76448. return p;
  76449. }
  76450. /*
  76451. ** Report an error that an expression is not valid for a partial index WHERE
  76452. ** clause.
  76453. */
  76454. static void notValidPartIdxWhere(
  76455. Parse *pParse, /* Leave error message here */
  76456. NameContext *pNC, /* The name context */
  76457. const char *zMsg /* Type of error */
  76458. ){
  76459. if( (pNC->ncFlags & NC_PartIdx)!=0 ){
  76460. sqlite3ErrorMsg(pParse, "%s prohibited in partial index WHERE clauses",
  76461. zMsg);
  76462. }
  76463. }
  76464. #ifndef SQLITE_OMIT_CHECK
  76465. /*
  76466. ** Report an error that an expression is not valid for a CHECK constraint.
  76467. */
  76468. static void notValidCheckConstraint(
  76469. Parse *pParse, /* Leave error message here */
  76470. NameContext *pNC, /* The name context */
  76471. const char *zMsg /* Type of error */
  76472. ){
  76473. if( (pNC->ncFlags & NC_IsCheck)!=0 ){
  76474. sqlite3ErrorMsg(pParse,"%s prohibited in CHECK constraints", zMsg);
  76475. }
  76476. }
  76477. #else
  76478. # define notValidCheckConstraint(P,N,M)
  76479. #endif
  76480. /*
  76481. ** Expression p should encode a floating point value between 1.0 and 0.0.
  76482. ** Return 1024 times this value. Or return -1 if p is not a floating point
  76483. ** value between 1.0 and 0.0.
  76484. */
  76485. static int exprProbability(Expr *p){
  76486. double r = -1.0;
  76487. if( p->op!=TK_FLOAT ) return -1;
  76488. sqlite3AtoF(p->u.zToken, &r, sqlite3Strlen30(p->u.zToken), SQLITE_UTF8);
  76489. assert( r>=0.0 );
  76490. if( r>1.0 ) return -1;
  76491. return (int)(r*134217728.0);
  76492. }
  76493. /*
  76494. ** This routine is callback for sqlite3WalkExpr().
  76495. **
  76496. ** Resolve symbolic names into TK_COLUMN operators for the current
  76497. ** node in the expression tree. Return 0 to continue the search down
  76498. ** the tree or 2 to abort the tree walk.
  76499. **
  76500. ** This routine also does error checking and name resolution for
  76501. ** function names. The operator for aggregate functions is changed
  76502. ** to TK_AGG_FUNCTION.
  76503. */
  76504. static int resolveExprStep(Walker *pWalker, Expr *pExpr){
  76505. NameContext *pNC;
  76506. Parse *pParse;
  76507. pNC = pWalker->u.pNC;
  76508. assert( pNC!=0 );
  76509. pParse = pNC->pParse;
  76510. assert( pParse==pWalker->pParse );
  76511. if( ExprHasProperty(pExpr, EP_Resolved) ) return WRC_Prune;
  76512. ExprSetProperty(pExpr, EP_Resolved);
  76513. #ifndef NDEBUG
  76514. if( pNC->pSrcList && pNC->pSrcList->nAlloc>0 ){
  76515. SrcList *pSrcList = pNC->pSrcList;
  76516. int i;
  76517. for(i=0; i<pNC->pSrcList->nSrc; i++){
  76518. assert( pSrcList->a[i].iCursor>=0 && pSrcList->a[i].iCursor<pParse->nTab);
  76519. }
  76520. }
  76521. #endif
  76522. switch( pExpr->op ){
  76523. #if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)
  76524. /* The special operator TK_ROW means use the rowid for the first
  76525. ** column in the FROM clause. This is used by the LIMIT and ORDER BY
  76526. ** clause processing on UPDATE and DELETE statements.
  76527. */
  76528. case TK_ROW: {
  76529. SrcList *pSrcList = pNC->pSrcList;
  76530. struct SrcList_item *pItem;
  76531. assert( pSrcList && pSrcList->nSrc==1 );
  76532. pItem = pSrcList->a;
  76533. pExpr->op = TK_COLUMN;
  76534. pExpr->pTab = pItem->pTab;
  76535. pExpr->iTable = pItem->iCursor;
  76536. pExpr->iColumn = -1;
  76537. pExpr->affinity = SQLITE_AFF_INTEGER;
  76538. break;
  76539. }
  76540. #endif /* defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT)
  76541. && !defined(SQLITE_OMIT_SUBQUERY) */
  76542. /* A lone identifier is the name of a column.
  76543. */
  76544. case TK_ID: {
  76545. return lookupName(pParse, 0, 0, pExpr->u.zToken, pNC, pExpr);
  76546. }
  76547. /* A table name and column name: ID.ID
  76548. ** Or a database, table and column: ID.ID.ID
  76549. */
  76550. case TK_DOT: {
  76551. const char *zColumn;
  76552. const char *zTable;
  76553. const char *zDb;
  76554. Expr *pRight;
  76555. /* if( pSrcList==0 ) break; */
  76556. pRight = pExpr->pRight;
  76557. if( pRight->op==TK_ID ){
  76558. zDb = 0;
  76559. zTable = pExpr->pLeft->u.zToken;
  76560. zColumn = pRight->u.zToken;
  76561. }else{
  76562. assert( pRight->op==TK_DOT );
  76563. zDb = pExpr->pLeft->u.zToken;
  76564. zTable = pRight->pLeft->u.zToken;
  76565. zColumn = pRight->pRight->u.zToken;
  76566. }
  76567. return lookupName(pParse, zDb, zTable, zColumn, pNC, pExpr);
  76568. }
  76569. /* Resolve function names
  76570. */
  76571. case TK_FUNCTION: {
  76572. ExprList *pList = pExpr->x.pList; /* The argument list */
  76573. int n = pList ? pList->nExpr : 0; /* Number of arguments */
  76574. int no_such_func = 0; /* True if no such function exists */
  76575. int wrong_num_args = 0; /* True if wrong number of arguments */
  76576. int is_agg = 0; /* True if is an aggregate function */
  76577. int auth; /* Authorization to use the function */
  76578. int nId; /* Number of characters in function name */
  76579. const char *zId; /* The function name. */
  76580. FuncDef *pDef; /* Information about the function */
  76581. u8 enc = ENC(pParse->db); /* The database encoding */
  76582. assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
  76583. notValidPartIdxWhere(pParse, pNC, "functions");
  76584. zId = pExpr->u.zToken;
  76585. nId = sqlite3Strlen30(zId);
  76586. pDef = sqlite3FindFunction(pParse->db, zId, nId, n, enc, 0);
  76587. if( pDef==0 ){
  76588. pDef = sqlite3FindFunction(pParse->db, zId, nId, -2, enc, 0);
  76589. if( pDef==0 ){
  76590. no_such_func = 1;
  76591. }else{
  76592. wrong_num_args = 1;
  76593. }
  76594. }else{
  76595. is_agg = pDef->xFunc==0;
  76596. if( pDef->funcFlags & SQLITE_FUNC_UNLIKELY ){
  76597. ExprSetProperty(pExpr, EP_Unlikely|EP_Skip);
  76598. if( n==2 ){
  76599. pExpr->iTable = exprProbability(pList->a[1].pExpr);
  76600. if( pExpr->iTable<0 ){
  76601. sqlite3ErrorMsg(pParse,
  76602. "second argument to likelihood() must be a "
  76603. "constant between 0.0 and 1.0");
  76604. pNC->nErr++;
  76605. }
  76606. }else{
  76607. /* EVIDENCE-OF: R-61304-29449 The unlikely(X) function is
  76608. ** equivalent to likelihood(X, 0.0625).
  76609. ** EVIDENCE-OF: R-01283-11636 The unlikely(X) function is
  76610. ** short-hand for likelihood(X,0.0625).
  76611. ** EVIDENCE-OF: R-36850-34127 The likely(X) function is short-hand
  76612. ** for likelihood(X,0.9375).
  76613. ** EVIDENCE-OF: R-53436-40973 The likely(X) function is equivalent
  76614. ** to likelihood(X,0.9375). */
  76615. /* TUNING: unlikely() probability is 0.0625. likely() is 0.9375 */
  76616. pExpr->iTable = pDef->zName[0]=='u' ? 8388608 : 125829120;
  76617. }
  76618. }
  76619. #ifndef SQLITE_OMIT_AUTHORIZATION
  76620. auth = sqlite3AuthCheck(pParse, SQLITE_FUNCTION, 0, pDef->zName, 0);
  76621. if( auth!=SQLITE_OK ){
  76622. if( auth==SQLITE_DENY ){
  76623. sqlite3ErrorMsg(pParse, "not authorized to use function: %s",
  76624. pDef->zName);
  76625. pNC->nErr++;
  76626. }
  76627. pExpr->op = TK_NULL;
  76628. return WRC_Prune;
  76629. }
  76630. #endif
  76631. if( pDef->funcFlags & SQLITE_FUNC_CONSTANT ){
  76632. ExprSetProperty(pExpr,EP_ConstFunc);
  76633. }
  76634. }
  76635. if( is_agg && (pNC->ncFlags & NC_AllowAgg)==0 ){
  76636. sqlite3ErrorMsg(pParse, "misuse of aggregate function %.*s()", nId,zId);
  76637. pNC->nErr++;
  76638. is_agg = 0;
  76639. }else if( no_such_func && pParse->db->init.busy==0 ){
  76640. sqlite3ErrorMsg(pParse, "no such function: %.*s", nId, zId);
  76641. pNC->nErr++;
  76642. }else if( wrong_num_args ){
  76643. sqlite3ErrorMsg(pParse,"wrong number of arguments to function %.*s()",
  76644. nId, zId);
  76645. pNC->nErr++;
  76646. }
  76647. if( is_agg ) pNC->ncFlags &= ~NC_AllowAgg;
  76648. sqlite3WalkExprList(pWalker, pList);
  76649. if( is_agg ){
  76650. NameContext *pNC2 = pNC;
  76651. pExpr->op = TK_AGG_FUNCTION;
  76652. pExpr->op2 = 0;
  76653. while( pNC2 && !sqlite3FunctionUsesThisSrc(pExpr, pNC2->pSrcList) ){
  76654. pExpr->op2++;
  76655. pNC2 = pNC2->pNext;
  76656. }
  76657. assert( pDef!=0 );
  76658. if( pNC2 ){
  76659. assert( SQLITE_FUNC_MINMAX==NC_MinMaxAgg );
  76660. testcase( (pDef->funcFlags & SQLITE_FUNC_MINMAX)!=0 );
  76661. pNC2->ncFlags |= NC_HasAgg | (pDef->funcFlags & SQLITE_FUNC_MINMAX);
  76662. }
  76663. pNC->ncFlags |= NC_AllowAgg;
  76664. }
  76665. /* FIX ME: Compute pExpr->affinity based on the expected return
  76666. ** type of the function
  76667. */
  76668. return WRC_Prune;
  76669. }
  76670. #ifndef SQLITE_OMIT_SUBQUERY
  76671. case TK_SELECT:
  76672. case TK_EXISTS: testcase( pExpr->op==TK_EXISTS );
  76673. #endif
  76674. case TK_IN: {
  76675. testcase( pExpr->op==TK_IN );
  76676. if( ExprHasProperty(pExpr, EP_xIsSelect) ){
  76677. int nRef = pNC->nRef;
  76678. notValidCheckConstraint(pParse, pNC, "subqueries");
  76679. notValidPartIdxWhere(pParse, pNC, "subqueries");
  76680. sqlite3WalkSelect(pWalker, pExpr->x.pSelect);
  76681. assert( pNC->nRef>=nRef );
  76682. if( nRef!=pNC->nRef ){
  76683. ExprSetProperty(pExpr, EP_VarSelect);
  76684. }
  76685. }
  76686. break;
  76687. }
  76688. case TK_VARIABLE: {
  76689. notValidCheckConstraint(pParse, pNC, "parameters");
  76690. notValidPartIdxWhere(pParse, pNC, "parameters");
  76691. break;
  76692. }
  76693. }
  76694. return (pParse->nErr || pParse->db->mallocFailed) ? WRC_Abort : WRC_Continue;
  76695. }
  76696. /*
  76697. ** pEList is a list of expressions which are really the result set of the
  76698. ** a SELECT statement. pE is a term in an ORDER BY or GROUP BY clause.
  76699. ** This routine checks to see if pE is a simple identifier which corresponds
  76700. ** to the AS-name of one of the terms of the expression list. If it is,
  76701. ** this routine return an integer between 1 and N where N is the number of
  76702. ** elements in pEList, corresponding to the matching entry. If there is
  76703. ** no match, or if pE is not a simple identifier, then this routine
  76704. ** return 0.
  76705. **
  76706. ** pEList has been resolved. pE has not.
  76707. */
  76708. static int resolveAsName(
  76709. Parse *pParse, /* Parsing context for error messages */
  76710. ExprList *pEList, /* List of expressions to scan */
  76711. Expr *pE /* Expression we are trying to match */
  76712. ){
  76713. int i; /* Loop counter */
  76714. UNUSED_PARAMETER(pParse);
  76715. if( pE->op==TK_ID ){
  76716. char *zCol = pE->u.zToken;
  76717. for(i=0; i<pEList->nExpr; i++){
  76718. char *zAs = pEList->a[i].zName;
  76719. if( zAs!=0 && sqlite3StrICmp(zAs, zCol)==0 ){
  76720. return i+1;
  76721. }
  76722. }
  76723. }
  76724. return 0;
  76725. }
  76726. /*
  76727. ** pE is a pointer to an expression which is a single term in the
  76728. ** ORDER BY of a compound SELECT. The expression has not been
  76729. ** name resolved.
  76730. **
  76731. ** At the point this routine is called, we already know that the
  76732. ** ORDER BY term is not an integer index into the result set. That
  76733. ** case is handled by the calling routine.
  76734. **
  76735. ** Attempt to match pE against result set columns in the left-most
  76736. ** SELECT statement. Return the index i of the matching column,
  76737. ** as an indication to the caller that it should sort by the i-th column.
  76738. ** The left-most column is 1. In other words, the value returned is the
  76739. ** same integer value that would be used in the SQL statement to indicate
  76740. ** the column.
  76741. **
  76742. ** If there is no match, return 0. Return -1 if an error occurs.
  76743. */
  76744. static int resolveOrderByTermToExprList(
  76745. Parse *pParse, /* Parsing context for error messages */
  76746. Select *pSelect, /* The SELECT statement with the ORDER BY clause */
  76747. Expr *pE /* The specific ORDER BY term */
  76748. ){
  76749. int i; /* Loop counter */
  76750. ExprList *pEList; /* The columns of the result set */
  76751. NameContext nc; /* Name context for resolving pE */
  76752. sqlite3 *db; /* Database connection */
  76753. int rc; /* Return code from subprocedures */
  76754. u8 savedSuppErr; /* Saved value of db->suppressErr */
  76755. assert( sqlite3ExprIsInteger(pE, &i)==0 );
  76756. pEList = pSelect->pEList;
  76757. /* Resolve all names in the ORDER BY term expression
  76758. */
  76759. memset(&nc, 0, sizeof(nc));
  76760. nc.pParse = pParse;
  76761. nc.pSrcList = pSelect->pSrc;
  76762. nc.pEList = pEList;
  76763. nc.ncFlags = NC_AllowAgg;
  76764. nc.nErr = 0;
  76765. db = pParse->db;
  76766. savedSuppErr = db->suppressErr;
  76767. db->suppressErr = 1;
  76768. rc = sqlite3ResolveExprNames(&nc, pE);
  76769. db->suppressErr = savedSuppErr;
  76770. if( rc ) return 0;
  76771. /* Try to match the ORDER BY expression against an expression
  76772. ** in the result set. Return an 1-based index of the matching
  76773. ** result-set entry.
  76774. */
  76775. for(i=0; i<pEList->nExpr; i++){
  76776. if( sqlite3ExprCompare(pEList->a[i].pExpr, pE, -1)<2 ){
  76777. return i+1;
  76778. }
  76779. }
  76780. /* If no match, return 0. */
  76781. return 0;
  76782. }
  76783. /*
  76784. ** Generate an ORDER BY or GROUP BY term out-of-range error.
  76785. */
  76786. static void resolveOutOfRangeError(
  76787. Parse *pParse, /* The error context into which to write the error */
  76788. const char *zType, /* "ORDER" or "GROUP" */
  76789. int i, /* The index (1-based) of the term out of range */
  76790. int mx /* Largest permissible value of i */
  76791. ){
  76792. sqlite3ErrorMsg(pParse,
  76793. "%r %s BY term out of range - should be "
  76794. "between 1 and %d", i, zType, mx);
  76795. }
  76796. /*
  76797. ** Analyze the ORDER BY clause in a compound SELECT statement. Modify
  76798. ** each term of the ORDER BY clause is a constant integer between 1
  76799. ** and N where N is the number of columns in the compound SELECT.
  76800. **
  76801. ** ORDER BY terms that are already an integer between 1 and N are
  76802. ** unmodified. ORDER BY terms that are integers outside the range of
  76803. ** 1 through N generate an error. ORDER BY terms that are expressions
  76804. ** are matched against result set expressions of compound SELECT
  76805. ** beginning with the left-most SELECT and working toward the right.
  76806. ** At the first match, the ORDER BY expression is transformed into
  76807. ** the integer column number.
  76808. **
  76809. ** Return the number of errors seen.
  76810. */
  76811. static int resolveCompoundOrderBy(
  76812. Parse *pParse, /* Parsing context. Leave error messages here */
  76813. Select *pSelect /* The SELECT statement containing the ORDER BY */
  76814. ){
  76815. int i;
  76816. ExprList *pOrderBy;
  76817. ExprList *pEList;
  76818. sqlite3 *db;
  76819. int moreToDo = 1;
  76820. pOrderBy = pSelect->pOrderBy;
  76821. if( pOrderBy==0 ) return 0;
  76822. db = pParse->db;
  76823. #if SQLITE_MAX_COLUMN
  76824. if( pOrderBy->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
  76825. sqlite3ErrorMsg(pParse, "too many terms in ORDER BY clause");
  76826. return 1;
  76827. }
  76828. #endif
  76829. for(i=0; i<pOrderBy->nExpr; i++){
  76830. pOrderBy->a[i].done = 0;
  76831. }
  76832. pSelect->pNext = 0;
  76833. while( pSelect->pPrior ){
  76834. pSelect->pPrior->pNext = pSelect;
  76835. pSelect = pSelect->pPrior;
  76836. }
  76837. while( pSelect && moreToDo ){
  76838. struct ExprList_item *pItem;
  76839. moreToDo = 0;
  76840. pEList = pSelect->pEList;
  76841. assert( pEList!=0 );
  76842. for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
  76843. int iCol = -1;
  76844. Expr *pE, *pDup;
  76845. if( pItem->done ) continue;
  76846. pE = sqlite3ExprSkipCollate(pItem->pExpr);
  76847. if( sqlite3ExprIsInteger(pE, &iCol) ){
  76848. if( iCol<=0 || iCol>pEList->nExpr ){
  76849. resolveOutOfRangeError(pParse, "ORDER", i+1, pEList->nExpr);
  76850. return 1;
  76851. }
  76852. }else{
  76853. iCol = resolveAsName(pParse, pEList, pE);
  76854. if( iCol==0 ){
  76855. pDup = sqlite3ExprDup(db, pE, 0);
  76856. if( !db->mallocFailed ){
  76857. assert(pDup);
  76858. iCol = resolveOrderByTermToExprList(pParse, pSelect, pDup);
  76859. }
  76860. sqlite3ExprDelete(db, pDup);
  76861. }
  76862. }
  76863. if( iCol>0 ){
  76864. /* Convert the ORDER BY term into an integer column number iCol,
  76865. ** taking care to preserve the COLLATE clause if it exists */
  76866. Expr *pNew = sqlite3Expr(db, TK_INTEGER, 0);
  76867. if( pNew==0 ) return 1;
  76868. pNew->flags |= EP_IntValue;
  76869. pNew->u.iValue = iCol;
  76870. if( pItem->pExpr==pE ){
  76871. pItem->pExpr = pNew;
  76872. }else{
  76873. Expr *pParent = pItem->pExpr;
  76874. assert( pParent->op==TK_COLLATE );
  76875. while( pParent->pLeft->op==TK_COLLATE ) pParent = pParent->pLeft;
  76876. assert( pParent->pLeft==pE );
  76877. pParent->pLeft = pNew;
  76878. }
  76879. sqlite3ExprDelete(db, pE);
  76880. pItem->u.x.iOrderByCol = (u16)iCol;
  76881. pItem->done = 1;
  76882. }else{
  76883. moreToDo = 1;
  76884. }
  76885. }
  76886. pSelect = pSelect->pNext;
  76887. }
  76888. for(i=0; i<pOrderBy->nExpr; i++){
  76889. if( pOrderBy->a[i].done==0 ){
  76890. sqlite3ErrorMsg(pParse, "%r ORDER BY term does not match any "
  76891. "column in the result set", i+1);
  76892. return 1;
  76893. }
  76894. }
  76895. return 0;
  76896. }
  76897. /*
  76898. ** Check every term in the ORDER BY or GROUP BY clause pOrderBy of
  76899. ** the SELECT statement pSelect. If any term is reference to a
  76900. ** result set expression (as determined by the ExprList.a.u.x.iOrderByCol
  76901. ** field) then convert that term into a copy of the corresponding result set
  76902. ** column.
  76903. **
  76904. ** If any errors are detected, add an error message to pParse and
  76905. ** return non-zero. Return zero if no errors are seen.
  76906. */
  76907. SQLITE_PRIVATE int sqlite3ResolveOrderGroupBy(
  76908. Parse *pParse, /* Parsing context. Leave error messages here */
  76909. Select *pSelect, /* The SELECT statement containing the clause */
  76910. ExprList *pOrderBy, /* The ORDER BY or GROUP BY clause to be processed */
  76911. const char *zType /* "ORDER" or "GROUP" */
  76912. ){
  76913. int i;
  76914. sqlite3 *db = pParse->db;
  76915. ExprList *pEList;
  76916. struct ExprList_item *pItem;
  76917. if( pOrderBy==0 || pParse->db->mallocFailed ) return 0;
  76918. #if SQLITE_MAX_COLUMN
  76919. if( pOrderBy->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
  76920. sqlite3ErrorMsg(pParse, "too many terms in %s BY clause", zType);
  76921. return 1;
  76922. }
  76923. #endif
  76924. pEList = pSelect->pEList;
  76925. assert( pEList!=0 ); /* sqlite3SelectNew() guarantees this */
  76926. for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
  76927. if( pItem->u.x.iOrderByCol ){
  76928. if( pItem->u.x.iOrderByCol>pEList->nExpr ){
  76929. resolveOutOfRangeError(pParse, zType, i+1, pEList->nExpr);
  76930. return 1;
  76931. }
  76932. resolveAlias(pParse, pEList, pItem->u.x.iOrderByCol-1, pItem->pExpr,
  76933. zType,0);
  76934. }
  76935. }
  76936. return 0;
  76937. }
  76938. /*
  76939. ** pOrderBy is an ORDER BY or GROUP BY clause in SELECT statement pSelect.
  76940. ** The Name context of the SELECT statement is pNC. zType is either
  76941. ** "ORDER" or "GROUP" depending on which type of clause pOrderBy is.
  76942. **
  76943. ** This routine resolves each term of the clause into an expression.
  76944. ** If the order-by term is an integer I between 1 and N (where N is the
  76945. ** number of columns in the result set of the SELECT) then the expression
  76946. ** in the resolution is a copy of the I-th result-set expression. If
  76947. ** the order-by term is an identifier that corresponds to the AS-name of
  76948. ** a result-set expression, then the term resolves to a copy of the
  76949. ** result-set expression. Otherwise, the expression is resolved in
  76950. ** the usual way - using sqlite3ResolveExprNames().
  76951. **
  76952. ** This routine returns the number of errors. If errors occur, then
  76953. ** an appropriate error message might be left in pParse. (OOM errors
  76954. ** excepted.)
  76955. */
  76956. static int resolveOrderGroupBy(
  76957. NameContext *pNC, /* The name context of the SELECT statement */
  76958. Select *pSelect, /* The SELECT statement holding pOrderBy */
  76959. ExprList *pOrderBy, /* An ORDER BY or GROUP BY clause to resolve */
  76960. const char *zType /* Either "ORDER" or "GROUP", as appropriate */
  76961. ){
  76962. int i, j; /* Loop counters */
  76963. int iCol; /* Column number */
  76964. struct ExprList_item *pItem; /* A term of the ORDER BY clause */
  76965. Parse *pParse; /* Parsing context */
  76966. int nResult; /* Number of terms in the result set */
  76967. if( pOrderBy==0 ) return 0;
  76968. nResult = pSelect->pEList->nExpr;
  76969. pParse = pNC->pParse;
  76970. for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
  76971. Expr *pE = pItem->pExpr;
  76972. Expr *pE2 = sqlite3ExprSkipCollate(pE);
  76973. if( zType[0]!='G' ){
  76974. iCol = resolveAsName(pParse, pSelect->pEList, pE2);
  76975. if( iCol>0 ){
  76976. /* If an AS-name match is found, mark this ORDER BY column as being
  76977. ** a copy of the iCol-th result-set column. The subsequent call to
  76978. ** sqlite3ResolveOrderGroupBy() will convert the expression to a
  76979. ** copy of the iCol-th result-set expression. */
  76980. pItem->u.x.iOrderByCol = (u16)iCol;
  76981. continue;
  76982. }
  76983. }
  76984. if( sqlite3ExprIsInteger(pE2, &iCol) ){
  76985. /* The ORDER BY term is an integer constant. Again, set the column
  76986. ** number so that sqlite3ResolveOrderGroupBy() will convert the
  76987. ** order-by term to a copy of the result-set expression */
  76988. if( iCol<1 || iCol>0xffff ){
  76989. resolveOutOfRangeError(pParse, zType, i+1, nResult);
  76990. return 1;
  76991. }
  76992. pItem->u.x.iOrderByCol = (u16)iCol;
  76993. continue;
  76994. }
  76995. /* Otherwise, treat the ORDER BY term as an ordinary expression */
  76996. pItem->u.x.iOrderByCol = 0;
  76997. if( sqlite3ResolveExprNames(pNC, pE) ){
  76998. return 1;
  76999. }
  77000. for(j=0; j<pSelect->pEList->nExpr; j++){
  77001. if( sqlite3ExprCompare(pE, pSelect->pEList->a[j].pExpr, -1)==0 ){
  77002. pItem->u.x.iOrderByCol = j+1;
  77003. }
  77004. }
  77005. }
  77006. return sqlite3ResolveOrderGroupBy(pParse, pSelect, pOrderBy, zType);
  77007. }
  77008. /*
  77009. ** Resolve names in the SELECT statement p and all of its descendants.
  77010. */
  77011. static int resolveSelectStep(Walker *pWalker, Select *p){
  77012. NameContext *pOuterNC; /* Context that contains this SELECT */
  77013. NameContext sNC; /* Name context of this SELECT */
  77014. int isCompound; /* True if p is a compound select */
  77015. int nCompound; /* Number of compound terms processed so far */
  77016. Parse *pParse; /* Parsing context */
  77017. ExprList *pEList; /* Result set expression list */
  77018. int i; /* Loop counter */
  77019. ExprList *pGroupBy; /* The GROUP BY clause */
  77020. Select *pLeftmost; /* Left-most of SELECT of a compound */
  77021. sqlite3 *db; /* Database connection */
  77022. assert( p!=0 );
  77023. if( p->selFlags & SF_Resolved ){
  77024. return WRC_Prune;
  77025. }
  77026. pOuterNC = pWalker->u.pNC;
  77027. pParse = pWalker->pParse;
  77028. db = pParse->db;
  77029. /* Normally sqlite3SelectExpand() will be called first and will have
  77030. ** already expanded this SELECT. However, if this is a subquery within
  77031. ** an expression, sqlite3ResolveExprNames() will be called without a
  77032. ** prior call to sqlite3SelectExpand(). When that happens, let
  77033. ** sqlite3SelectPrep() do all of the processing for this SELECT.
  77034. ** sqlite3SelectPrep() will invoke both sqlite3SelectExpand() and
  77035. ** this routine in the correct order.
  77036. */
  77037. if( (p->selFlags & SF_Expanded)==0 ){
  77038. sqlite3SelectPrep(pParse, p, pOuterNC);
  77039. return (pParse->nErr || db->mallocFailed) ? WRC_Abort : WRC_Prune;
  77040. }
  77041. isCompound = p->pPrior!=0;
  77042. nCompound = 0;
  77043. pLeftmost = p;
  77044. while( p ){
  77045. assert( (p->selFlags & SF_Expanded)!=0 );
  77046. assert( (p->selFlags & SF_Resolved)==0 );
  77047. p->selFlags |= SF_Resolved;
  77048. /* Resolve the expressions in the LIMIT and OFFSET clauses. These
  77049. ** are not allowed to refer to any names, so pass an empty NameContext.
  77050. */
  77051. memset(&sNC, 0, sizeof(sNC));
  77052. sNC.pParse = pParse;
  77053. if( sqlite3ResolveExprNames(&sNC, p->pLimit) ||
  77054. sqlite3ResolveExprNames(&sNC, p->pOffset) ){
  77055. return WRC_Abort;
  77056. }
  77057. /* If the SF_Converted flags is set, then this Select object was
  77058. ** was created by the convertCompoundSelectToSubquery() function.
  77059. ** In this case the ORDER BY clause (p->pOrderBy) should be resolved
  77060. ** as if it were part of the sub-query, not the parent. This block
  77061. ** moves the pOrderBy down to the sub-query. It will be moved back
  77062. ** after the names have been resolved. */
  77063. if( p->selFlags & SF_Converted ){
  77064. Select *pSub = p->pSrc->a[0].pSelect;
  77065. assert( p->pSrc->nSrc==1 && p->pOrderBy );
  77066. assert( pSub->pPrior && pSub->pOrderBy==0 );
  77067. pSub->pOrderBy = p->pOrderBy;
  77068. p->pOrderBy = 0;
  77069. }
  77070. /* Recursively resolve names in all subqueries
  77071. */
  77072. for(i=0; i<p->pSrc->nSrc; i++){
  77073. struct SrcList_item *pItem = &p->pSrc->a[i];
  77074. if( pItem->pSelect ){
  77075. NameContext *pNC; /* Used to iterate name contexts */
  77076. int nRef = 0; /* Refcount for pOuterNC and outer contexts */
  77077. const char *zSavedContext = pParse->zAuthContext;
  77078. /* Count the total number of references to pOuterNC and all of its
  77079. ** parent contexts. After resolving references to expressions in
  77080. ** pItem->pSelect, check if this value has changed. If so, then
  77081. ** SELECT statement pItem->pSelect must be correlated. Set the
  77082. ** pItem->isCorrelated flag if this is the case. */
  77083. for(pNC=pOuterNC; pNC; pNC=pNC->pNext) nRef += pNC->nRef;
  77084. if( pItem->zName ) pParse->zAuthContext = pItem->zName;
  77085. sqlite3ResolveSelectNames(pParse, pItem->pSelect, pOuterNC);
  77086. pParse->zAuthContext = zSavedContext;
  77087. if( pParse->nErr || db->mallocFailed ) return WRC_Abort;
  77088. for(pNC=pOuterNC; pNC; pNC=pNC->pNext) nRef -= pNC->nRef;
  77089. assert( pItem->isCorrelated==0 && nRef<=0 );
  77090. pItem->isCorrelated = (nRef!=0);
  77091. }
  77092. }
  77093. /* Set up the local name-context to pass to sqlite3ResolveExprNames() to
  77094. ** resolve the result-set expression list.
  77095. */
  77096. sNC.ncFlags = NC_AllowAgg;
  77097. sNC.pSrcList = p->pSrc;
  77098. sNC.pNext = pOuterNC;
  77099. /* Resolve names in the result set. */
  77100. pEList = p->pEList;
  77101. assert( pEList!=0 );
  77102. for(i=0; i<pEList->nExpr; i++){
  77103. Expr *pX = pEList->a[i].pExpr;
  77104. if( sqlite3ResolveExprNames(&sNC, pX) ){
  77105. return WRC_Abort;
  77106. }
  77107. }
  77108. /* If there are no aggregate functions in the result-set, and no GROUP BY
  77109. ** expression, do not allow aggregates in any of the other expressions.
  77110. */
  77111. assert( (p->selFlags & SF_Aggregate)==0 );
  77112. pGroupBy = p->pGroupBy;
  77113. if( pGroupBy || (sNC.ncFlags & NC_HasAgg)!=0 ){
  77114. assert( NC_MinMaxAgg==SF_MinMaxAgg );
  77115. p->selFlags |= SF_Aggregate | (sNC.ncFlags&NC_MinMaxAgg);
  77116. }else{
  77117. sNC.ncFlags &= ~NC_AllowAgg;
  77118. }
  77119. /* If a HAVING clause is present, then there must be a GROUP BY clause.
  77120. */
  77121. if( p->pHaving && !pGroupBy ){
  77122. sqlite3ErrorMsg(pParse, "a GROUP BY clause is required before HAVING");
  77123. return WRC_Abort;
  77124. }
  77125. /* Add the output column list to the name-context before parsing the
  77126. ** other expressions in the SELECT statement. This is so that
  77127. ** expressions in the WHERE clause (etc.) can refer to expressions by
  77128. ** aliases in the result set.
  77129. **
  77130. ** Minor point: If this is the case, then the expression will be
  77131. ** re-evaluated for each reference to it.
  77132. */
  77133. sNC.pEList = p->pEList;
  77134. if( sqlite3ResolveExprNames(&sNC, p->pHaving) ) return WRC_Abort;
  77135. if( sqlite3ResolveExprNames(&sNC, p->pWhere) ) return WRC_Abort;
  77136. /* The ORDER BY and GROUP BY clauses may not refer to terms in
  77137. ** outer queries
  77138. */
  77139. sNC.pNext = 0;
  77140. sNC.ncFlags |= NC_AllowAgg;
  77141. /* If this is a converted compound query, move the ORDER BY clause from
  77142. ** the sub-query back to the parent query. At this point each term
  77143. ** within the ORDER BY clause has been transformed to an integer value.
  77144. ** These integers will be replaced by copies of the corresponding result
  77145. ** set expressions by the call to resolveOrderGroupBy() below. */
  77146. if( p->selFlags & SF_Converted ){
  77147. Select *pSub = p->pSrc->a[0].pSelect;
  77148. p->pOrderBy = pSub->pOrderBy;
  77149. pSub->pOrderBy = 0;
  77150. }
  77151. /* Process the ORDER BY clause for singleton SELECT statements.
  77152. ** The ORDER BY clause for compounds SELECT statements is handled
  77153. ** below, after all of the result-sets for all of the elements of
  77154. ** the compound have been resolved.
  77155. **
  77156. ** If there is an ORDER BY clause on a term of a compound-select other
  77157. ** than the right-most term, then that is a syntax error. But the error
  77158. ** is not detected until much later, and so we need to go ahead and
  77159. ** resolve those symbols on the incorrect ORDER BY for consistency.
  77160. */
  77161. if( isCompound<=nCompound /* Defer right-most ORDER BY of a compound */
  77162. && resolveOrderGroupBy(&sNC, p, p->pOrderBy, "ORDER")
  77163. ){
  77164. return WRC_Abort;
  77165. }
  77166. if( db->mallocFailed ){
  77167. return WRC_Abort;
  77168. }
  77169. /* Resolve the GROUP BY clause. At the same time, make sure
  77170. ** the GROUP BY clause does not contain aggregate functions.
  77171. */
  77172. if( pGroupBy ){
  77173. struct ExprList_item *pItem;
  77174. if( resolveOrderGroupBy(&sNC, p, pGroupBy, "GROUP") || db->mallocFailed ){
  77175. return WRC_Abort;
  77176. }
  77177. for(i=0, pItem=pGroupBy->a; i<pGroupBy->nExpr; i++, pItem++){
  77178. if( ExprHasProperty(pItem->pExpr, EP_Agg) ){
  77179. sqlite3ErrorMsg(pParse, "aggregate functions are not allowed in "
  77180. "the GROUP BY clause");
  77181. return WRC_Abort;
  77182. }
  77183. }
  77184. }
  77185. /* Advance to the next term of the compound
  77186. */
  77187. p = p->pPrior;
  77188. nCompound++;
  77189. }
  77190. /* Resolve the ORDER BY on a compound SELECT after all terms of
  77191. ** the compound have been resolved.
  77192. */
  77193. if( isCompound && resolveCompoundOrderBy(pParse, pLeftmost) ){
  77194. return WRC_Abort;
  77195. }
  77196. return WRC_Prune;
  77197. }
  77198. /*
  77199. ** This routine walks an expression tree and resolves references to
  77200. ** table columns and result-set columns. At the same time, do error
  77201. ** checking on function usage and set a flag if any aggregate functions
  77202. ** are seen.
  77203. **
  77204. ** To resolve table columns references we look for nodes (or subtrees) of the
  77205. ** form X.Y.Z or Y.Z or just Z where
  77206. **
  77207. ** X: The name of a database. Ex: "main" or "temp" or
  77208. ** the symbolic name assigned to an ATTACH-ed database.
  77209. **
  77210. ** Y: The name of a table in a FROM clause. Or in a trigger
  77211. ** one of the special names "old" or "new".
  77212. **
  77213. ** Z: The name of a column in table Y.
  77214. **
  77215. ** The node at the root of the subtree is modified as follows:
  77216. **
  77217. ** Expr.op Changed to TK_COLUMN
  77218. ** Expr.pTab Points to the Table object for X.Y
  77219. ** Expr.iColumn The column index in X.Y. -1 for the rowid.
  77220. ** Expr.iTable The VDBE cursor number for X.Y
  77221. **
  77222. **
  77223. ** To resolve result-set references, look for expression nodes of the
  77224. ** form Z (with no X and Y prefix) where the Z matches the right-hand
  77225. ** size of an AS clause in the result-set of a SELECT. The Z expression
  77226. ** is replaced by a copy of the left-hand side of the result-set expression.
  77227. ** Table-name and function resolution occurs on the substituted expression
  77228. ** tree. For example, in:
  77229. **
  77230. ** SELECT a+b AS x, c+d AS y FROM t1 ORDER BY x;
  77231. **
  77232. ** The "x" term of the order by is replaced by "a+b" to render:
  77233. **
  77234. ** SELECT a+b AS x, c+d AS y FROM t1 ORDER BY a+b;
  77235. **
  77236. ** Function calls are checked to make sure that the function is
  77237. ** defined and that the correct number of arguments are specified.
  77238. ** If the function is an aggregate function, then the NC_HasAgg flag is
  77239. ** set and the opcode is changed from TK_FUNCTION to TK_AGG_FUNCTION.
  77240. ** If an expression contains aggregate functions then the EP_Agg
  77241. ** property on the expression is set.
  77242. **
  77243. ** An error message is left in pParse if anything is amiss. The number
  77244. ** if errors is returned.
  77245. */
  77246. SQLITE_PRIVATE int sqlite3ResolveExprNames(
  77247. NameContext *pNC, /* Namespace to resolve expressions in. */
  77248. Expr *pExpr /* The expression to be analyzed. */
  77249. ){
  77250. u16 savedHasAgg;
  77251. Walker w;
  77252. if( pExpr==0 ) return 0;
  77253. #if SQLITE_MAX_EXPR_DEPTH>0
  77254. {
  77255. Parse *pParse = pNC->pParse;
  77256. if( sqlite3ExprCheckHeight(pParse, pExpr->nHeight+pNC->pParse->nHeight) ){
  77257. return 1;
  77258. }
  77259. pParse->nHeight += pExpr->nHeight;
  77260. }
  77261. #endif
  77262. savedHasAgg = pNC->ncFlags & (NC_HasAgg|NC_MinMaxAgg);
  77263. pNC->ncFlags &= ~(NC_HasAgg|NC_MinMaxAgg);
  77264. memset(&w, 0, sizeof(w));
  77265. w.xExprCallback = resolveExprStep;
  77266. w.xSelectCallback = resolveSelectStep;
  77267. w.pParse = pNC->pParse;
  77268. w.u.pNC = pNC;
  77269. sqlite3WalkExpr(&w, pExpr);
  77270. #if SQLITE_MAX_EXPR_DEPTH>0
  77271. pNC->pParse->nHeight -= pExpr->nHeight;
  77272. #endif
  77273. if( pNC->nErr>0 || w.pParse->nErr>0 ){
  77274. ExprSetProperty(pExpr, EP_Error);
  77275. }
  77276. if( pNC->ncFlags & NC_HasAgg ){
  77277. ExprSetProperty(pExpr, EP_Agg);
  77278. }
  77279. pNC->ncFlags |= savedHasAgg;
  77280. return ExprHasProperty(pExpr, EP_Error);
  77281. }
  77282. /*
  77283. ** Resolve all names in all expressions of a SELECT and in all
  77284. ** decendents of the SELECT, including compounds off of p->pPrior,
  77285. ** subqueries in expressions, and subqueries used as FROM clause
  77286. ** terms.
  77287. **
  77288. ** See sqlite3ResolveExprNames() for a description of the kinds of
  77289. ** transformations that occur.
  77290. **
  77291. ** All SELECT statements should have been expanded using
  77292. ** sqlite3SelectExpand() prior to invoking this routine.
  77293. */
  77294. SQLITE_PRIVATE void sqlite3ResolveSelectNames(
  77295. Parse *pParse, /* The parser context */
  77296. Select *p, /* The SELECT statement being coded. */
  77297. NameContext *pOuterNC /* Name context for parent SELECT statement */
  77298. ){
  77299. Walker w;
  77300. assert( p!=0 );
  77301. memset(&w, 0, sizeof(w));
  77302. w.xExprCallback = resolveExprStep;
  77303. w.xSelectCallback = resolveSelectStep;
  77304. w.pParse = pParse;
  77305. w.u.pNC = pOuterNC;
  77306. sqlite3WalkSelect(&w, p);
  77307. }
  77308. /*
  77309. ** Resolve names in expressions that can only reference a single table:
  77310. **
  77311. ** * CHECK constraints
  77312. ** * WHERE clauses on partial indices
  77313. **
  77314. ** The Expr.iTable value for Expr.op==TK_COLUMN nodes of the expression
  77315. ** is set to -1 and the Expr.iColumn value is set to the column number.
  77316. **
  77317. ** Any errors cause an error message to be set in pParse.
  77318. */
  77319. SQLITE_PRIVATE void sqlite3ResolveSelfReference(
  77320. Parse *pParse, /* Parsing context */
  77321. Table *pTab, /* The table being referenced */
  77322. int type, /* NC_IsCheck or NC_PartIdx */
  77323. Expr *pExpr, /* Expression to resolve. May be NULL. */
  77324. ExprList *pList /* Expression list to resolve. May be NUL. */
  77325. ){
  77326. SrcList sSrc; /* Fake SrcList for pParse->pNewTable */
  77327. NameContext sNC; /* Name context for pParse->pNewTable */
  77328. int i; /* Loop counter */
  77329. assert( type==NC_IsCheck || type==NC_PartIdx );
  77330. memset(&sNC, 0, sizeof(sNC));
  77331. memset(&sSrc, 0, sizeof(sSrc));
  77332. sSrc.nSrc = 1;
  77333. sSrc.a[0].zName = pTab->zName;
  77334. sSrc.a[0].pTab = pTab;
  77335. sSrc.a[0].iCursor = -1;
  77336. sNC.pParse = pParse;
  77337. sNC.pSrcList = &sSrc;
  77338. sNC.ncFlags = type;
  77339. if( sqlite3ResolveExprNames(&sNC, pExpr) ) return;
  77340. if( pList ){
  77341. for(i=0; i<pList->nExpr; i++){
  77342. if( sqlite3ResolveExprNames(&sNC, pList->a[i].pExpr) ){
  77343. return;
  77344. }
  77345. }
  77346. }
  77347. }
  77348. /************** End of resolve.c *********************************************/
  77349. /************** Begin file expr.c ********************************************/
  77350. /*
  77351. ** 2001 September 15
  77352. **
  77353. ** The author disclaims copyright to this source code. In place of
  77354. ** a legal notice, here is a blessing:
  77355. **
  77356. ** May you do good and not evil.
  77357. ** May you find forgiveness for yourself and forgive others.
  77358. ** May you share freely, never taking more than you give.
  77359. **
  77360. *************************************************************************
  77361. ** This file contains routines used for analyzing expressions and
  77362. ** for generating VDBE code that evaluates expressions in SQLite.
  77363. */
  77364. /*
  77365. ** Return the 'affinity' of the expression pExpr if any.
  77366. **
  77367. ** If pExpr is a column, a reference to a column via an 'AS' alias,
  77368. ** or a sub-select with a column as the return value, then the
  77369. ** affinity of that column is returned. Otherwise, 0x00 is returned,
  77370. ** indicating no affinity for the expression.
  77371. **
  77372. ** i.e. the WHERE clause expressions in the following statements all
  77373. ** have an affinity:
  77374. **
  77375. ** CREATE TABLE t1(a);
  77376. ** SELECT * FROM t1 WHERE a;
  77377. ** SELECT a AS b FROM t1 WHERE b;
  77378. ** SELECT * FROM t1 WHERE (select a from t1);
  77379. */
  77380. SQLITE_PRIVATE char sqlite3ExprAffinity(Expr *pExpr){
  77381. int op;
  77382. pExpr = sqlite3ExprSkipCollate(pExpr);
  77383. if( pExpr->flags & EP_Generic ) return 0;
  77384. op = pExpr->op;
  77385. if( op==TK_SELECT ){
  77386. assert( pExpr->flags&EP_xIsSelect );
  77387. return sqlite3ExprAffinity(pExpr->x.pSelect->pEList->a[0].pExpr);
  77388. }
  77389. #ifndef SQLITE_OMIT_CAST
  77390. if( op==TK_CAST ){
  77391. assert( !ExprHasProperty(pExpr, EP_IntValue) );
  77392. return sqlite3AffinityType(pExpr->u.zToken, 0);
  77393. }
  77394. #endif
  77395. if( (op==TK_AGG_COLUMN || op==TK_COLUMN || op==TK_REGISTER)
  77396. && pExpr->pTab!=0
  77397. ){
  77398. /* op==TK_REGISTER && pExpr->pTab!=0 happens when pExpr was originally
  77399. ** a TK_COLUMN but was previously evaluated and cached in a register */
  77400. int j = pExpr->iColumn;
  77401. if( j<0 ) return SQLITE_AFF_INTEGER;
  77402. assert( pExpr->pTab && j<pExpr->pTab->nCol );
  77403. return pExpr->pTab->aCol[j].affinity;
  77404. }
  77405. return pExpr->affinity;
  77406. }
  77407. /*
  77408. ** Set the collating sequence for expression pExpr to be the collating
  77409. ** sequence named by pToken. Return a pointer to a new Expr node that
  77410. ** implements the COLLATE operator.
  77411. **
  77412. ** If a memory allocation error occurs, that fact is recorded in pParse->db
  77413. ** and the pExpr parameter is returned unchanged.
  77414. */
  77415. SQLITE_PRIVATE Expr *sqlite3ExprAddCollateToken(
  77416. Parse *pParse, /* Parsing context */
  77417. Expr *pExpr, /* Add the "COLLATE" clause to this expression */
  77418. const Token *pCollName, /* Name of collating sequence */
  77419. int dequote /* True to dequote pCollName */
  77420. ){
  77421. if( pCollName->n>0 ){
  77422. Expr *pNew = sqlite3ExprAlloc(pParse->db, TK_COLLATE, pCollName, dequote);
  77423. if( pNew ){
  77424. pNew->pLeft = pExpr;
  77425. pNew->flags |= EP_Collate|EP_Skip;
  77426. pExpr = pNew;
  77427. }
  77428. }
  77429. return pExpr;
  77430. }
  77431. SQLITE_PRIVATE Expr *sqlite3ExprAddCollateString(Parse *pParse, Expr *pExpr, const char *zC){
  77432. Token s;
  77433. assert( zC!=0 );
  77434. s.z = zC;
  77435. s.n = sqlite3Strlen30(s.z);
  77436. return sqlite3ExprAddCollateToken(pParse, pExpr, &s, 0);
  77437. }
  77438. /*
  77439. ** Skip over any TK_COLLATE or TK_AS operators and any unlikely()
  77440. ** or likelihood() function at the root of an expression.
  77441. */
  77442. SQLITE_PRIVATE Expr *sqlite3ExprSkipCollate(Expr *pExpr){
  77443. while( pExpr && ExprHasProperty(pExpr, EP_Skip) ){
  77444. if( ExprHasProperty(pExpr, EP_Unlikely) ){
  77445. assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
  77446. assert( pExpr->x.pList->nExpr>0 );
  77447. assert( pExpr->op==TK_FUNCTION );
  77448. pExpr = pExpr->x.pList->a[0].pExpr;
  77449. }else{
  77450. assert( pExpr->op==TK_COLLATE || pExpr->op==TK_AS );
  77451. pExpr = pExpr->pLeft;
  77452. }
  77453. }
  77454. return pExpr;
  77455. }
  77456. /*
  77457. ** Return the collation sequence for the expression pExpr. If
  77458. ** there is no defined collating sequence, return NULL.
  77459. **
  77460. ** The collating sequence might be determined by a COLLATE operator
  77461. ** or by the presence of a column with a defined collating sequence.
  77462. ** COLLATE operators take first precedence. Left operands take
  77463. ** precedence over right operands.
  77464. */
  77465. SQLITE_PRIVATE CollSeq *sqlite3ExprCollSeq(Parse *pParse, Expr *pExpr){
  77466. sqlite3 *db = pParse->db;
  77467. CollSeq *pColl = 0;
  77468. Expr *p = pExpr;
  77469. while( p ){
  77470. int op = p->op;
  77471. if( p->flags & EP_Generic ) break;
  77472. if( op==TK_CAST || op==TK_UPLUS ){
  77473. p = p->pLeft;
  77474. continue;
  77475. }
  77476. if( op==TK_COLLATE || (op==TK_REGISTER && p->op2==TK_COLLATE) ){
  77477. pColl = sqlite3GetCollSeq(pParse, ENC(db), 0, p->u.zToken);
  77478. break;
  77479. }
  77480. if( (op==TK_AGG_COLUMN || op==TK_COLUMN
  77481. || op==TK_REGISTER || op==TK_TRIGGER)
  77482. && p->pTab!=0
  77483. ){
  77484. /* op==TK_REGISTER && p->pTab!=0 happens when pExpr was originally
  77485. ** a TK_COLUMN but was previously evaluated and cached in a register */
  77486. int j = p->iColumn;
  77487. if( j>=0 ){
  77488. const char *zColl = p->pTab->aCol[j].zColl;
  77489. pColl = sqlite3FindCollSeq(db, ENC(db), zColl, 0);
  77490. }
  77491. break;
  77492. }
  77493. if( p->flags & EP_Collate ){
  77494. if( p->pLeft && (p->pLeft->flags & EP_Collate)!=0 ){
  77495. p = p->pLeft;
  77496. }else{
  77497. Expr *pNext = p->pRight;
  77498. /* The Expr.x union is never used at the same time as Expr.pRight */
  77499. assert( p->x.pList==0 || p->pRight==0 );
  77500. /* p->flags holds EP_Collate and p->pLeft->flags does not. And
  77501. ** p->x.pSelect cannot. So if p->x.pLeft exists, it must hold at
  77502. ** least one EP_Collate. Thus the following two ALWAYS. */
  77503. if( p->x.pList!=0 && ALWAYS(!ExprHasProperty(p, EP_xIsSelect)) ){
  77504. int i;
  77505. for(i=0; ALWAYS(i<p->x.pList->nExpr); i++){
  77506. if( ExprHasProperty(p->x.pList->a[i].pExpr, EP_Collate) ){
  77507. pNext = p->x.pList->a[i].pExpr;
  77508. break;
  77509. }
  77510. }
  77511. }
  77512. p = pNext;
  77513. }
  77514. }else{
  77515. break;
  77516. }
  77517. }
  77518. if( sqlite3CheckCollSeq(pParse, pColl) ){
  77519. pColl = 0;
  77520. }
  77521. return pColl;
  77522. }
  77523. /*
  77524. ** pExpr is an operand of a comparison operator. aff2 is the
  77525. ** type affinity of the other operand. This routine returns the
  77526. ** type affinity that should be used for the comparison operator.
  77527. */
  77528. SQLITE_PRIVATE char sqlite3CompareAffinity(Expr *pExpr, char aff2){
  77529. char aff1 = sqlite3ExprAffinity(pExpr);
  77530. if( aff1 && aff2 ){
  77531. /* Both sides of the comparison are columns. If one has numeric
  77532. ** affinity, use that. Otherwise use no affinity.
  77533. */
  77534. if( sqlite3IsNumericAffinity(aff1) || sqlite3IsNumericAffinity(aff2) ){
  77535. return SQLITE_AFF_NUMERIC;
  77536. }else{
  77537. return SQLITE_AFF_NONE;
  77538. }
  77539. }else if( !aff1 && !aff2 ){
  77540. /* Neither side of the comparison is a column. Compare the
  77541. ** results directly.
  77542. */
  77543. return SQLITE_AFF_NONE;
  77544. }else{
  77545. /* One side is a column, the other is not. Use the columns affinity. */
  77546. assert( aff1==0 || aff2==0 );
  77547. return (aff1 + aff2);
  77548. }
  77549. }
  77550. /*
  77551. ** pExpr is a comparison operator. Return the type affinity that should
  77552. ** be applied to both operands prior to doing the comparison.
  77553. */
  77554. static char comparisonAffinity(Expr *pExpr){
  77555. char aff;
  77556. assert( pExpr->op==TK_EQ || pExpr->op==TK_IN || pExpr->op==TK_LT ||
  77557. pExpr->op==TK_GT || pExpr->op==TK_GE || pExpr->op==TK_LE ||
  77558. pExpr->op==TK_NE || pExpr->op==TK_IS || pExpr->op==TK_ISNOT );
  77559. assert( pExpr->pLeft );
  77560. aff = sqlite3ExprAffinity(pExpr->pLeft);
  77561. if( pExpr->pRight ){
  77562. aff = sqlite3CompareAffinity(pExpr->pRight, aff);
  77563. }else if( ExprHasProperty(pExpr, EP_xIsSelect) ){
  77564. aff = sqlite3CompareAffinity(pExpr->x.pSelect->pEList->a[0].pExpr, aff);
  77565. }else if( !aff ){
  77566. aff = SQLITE_AFF_NONE;
  77567. }
  77568. return aff;
  77569. }
  77570. /*
  77571. ** pExpr is a comparison expression, eg. '=', '<', IN(...) etc.
  77572. ** idx_affinity is the affinity of an indexed column. Return true
  77573. ** if the index with affinity idx_affinity may be used to implement
  77574. ** the comparison in pExpr.
  77575. */
  77576. SQLITE_PRIVATE int sqlite3IndexAffinityOk(Expr *pExpr, char idx_affinity){
  77577. char aff = comparisonAffinity(pExpr);
  77578. switch( aff ){
  77579. case SQLITE_AFF_NONE:
  77580. return 1;
  77581. case SQLITE_AFF_TEXT:
  77582. return idx_affinity==SQLITE_AFF_TEXT;
  77583. default:
  77584. return sqlite3IsNumericAffinity(idx_affinity);
  77585. }
  77586. }
  77587. /*
  77588. ** Return the P5 value that should be used for a binary comparison
  77589. ** opcode (OP_Eq, OP_Ge etc.) used to compare pExpr1 and pExpr2.
  77590. */
  77591. static u8 binaryCompareP5(Expr *pExpr1, Expr *pExpr2, int jumpIfNull){
  77592. u8 aff = (char)sqlite3ExprAffinity(pExpr2);
  77593. aff = (u8)sqlite3CompareAffinity(pExpr1, aff) | (u8)jumpIfNull;
  77594. return aff;
  77595. }
  77596. /*
  77597. ** Return a pointer to the collation sequence that should be used by
  77598. ** a binary comparison operator comparing pLeft and pRight.
  77599. **
  77600. ** If the left hand expression has a collating sequence type, then it is
  77601. ** used. Otherwise the collation sequence for the right hand expression
  77602. ** is used, or the default (BINARY) if neither expression has a collating
  77603. ** type.
  77604. **
  77605. ** Argument pRight (but not pLeft) may be a null pointer. In this case,
  77606. ** it is not considered.
  77607. */
  77608. SQLITE_PRIVATE CollSeq *sqlite3BinaryCompareCollSeq(
  77609. Parse *pParse,
  77610. Expr *pLeft,
  77611. Expr *pRight
  77612. ){
  77613. CollSeq *pColl;
  77614. assert( pLeft );
  77615. if( pLeft->flags & EP_Collate ){
  77616. pColl = sqlite3ExprCollSeq(pParse, pLeft);
  77617. }else if( pRight && (pRight->flags & EP_Collate)!=0 ){
  77618. pColl = sqlite3ExprCollSeq(pParse, pRight);
  77619. }else{
  77620. pColl = sqlite3ExprCollSeq(pParse, pLeft);
  77621. if( !pColl ){
  77622. pColl = sqlite3ExprCollSeq(pParse, pRight);
  77623. }
  77624. }
  77625. return pColl;
  77626. }
  77627. /*
  77628. ** Generate code for a comparison operator.
  77629. */
  77630. static int codeCompare(
  77631. Parse *pParse, /* The parsing (and code generating) context */
  77632. Expr *pLeft, /* The left operand */
  77633. Expr *pRight, /* The right operand */
  77634. int opcode, /* The comparison opcode */
  77635. int in1, int in2, /* Register holding operands */
  77636. int dest, /* Jump here if true. */
  77637. int jumpIfNull /* If true, jump if either operand is NULL */
  77638. ){
  77639. int p5;
  77640. int addr;
  77641. CollSeq *p4;
  77642. p4 = sqlite3BinaryCompareCollSeq(pParse, pLeft, pRight);
  77643. p5 = binaryCompareP5(pLeft, pRight, jumpIfNull);
  77644. addr = sqlite3VdbeAddOp4(pParse->pVdbe, opcode, in2, dest, in1,
  77645. (void*)p4, P4_COLLSEQ);
  77646. sqlite3VdbeChangeP5(pParse->pVdbe, (u8)p5);
  77647. return addr;
  77648. }
  77649. #if SQLITE_MAX_EXPR_DEPTH>0
  77650. /*
  77651. ** Check that argument nHeight is less than or equal to the maximum
  77652. ** expression depth allowed. If it is not, leave an error message in
  77653. ** pParse.
  77654. */
  77655. SQLITE_PRIVATE int sqlite3ExprCheckHeight(Parse *pParse, int nHeight){
  77656. int rc = SQLITE_OK;
  77657. int mxHeight = pParse->db->aLimit[SQLITE_LIMIT_EXPR_DEPTH];
  77658. if( nHeight>mxHeight ){
  77659. sqlite3ErrorMsg(pParse,
  77660. "Expression tree is too large (maximum depth %d)", mxHeight
  77661. );
  77662. rc = SQLITE_ERROR;
  77663. }
  77664. return rc;
  77665. }
  77666. /* The following three functions, heightOfExpr(), heightOfExprList()
  77667. ** and heightOfSelect(), are used to determine the maximum height
  77668. ** of any expression tree referenced by the structure passed as the
  77669. ** first argument.
  77670. **
  77671. ** If this maximum height is greater than the current value pointed
  77672. ** to by pnHeight, the second parameter, then set *pnHeight to that
  77673. ** value.
  77674. */
  77675. static void heightOfExpr(Expr *p, int *pnHeight){
  77676. if( p ){
  77677. if( p->nHeight>*pnHeight ){
  77678. *pnHeight = p->nHeight;
  77679. }
  77680. }
  77681. }
  77682. static void heightOfExprList(ExprList *p, int *pnHeight){
  77683. if( p ){
  77684. int i;
  77685. for(i=0; i<p->nExpr; i++){
  77686. heightOfExpr(p->a[i].pExpr, pnHeight);
  77687. }
  77688. }
  77689. }
  77690. static void heightOfSelect(Select *p, int *pnHeight){
  77691. if( p ){
  77692. heightOfExpr(p->pWhere, pnHeight);
  77693. heightOfExpr(p->pHaving, pnHeight);
  77694. heightOfExpr(p->pLimit, pnHeight);
  77695. heightOfExpr(p->pOffset, pnHeight);
  77696. heightOfExprList(p->pEList, pnHeight);
  77697. heightOfExprList(p->pGroupBy, pnHeight);
  77698. heightOfExprList(p->pOrderBy, pnHeight);
  77699. heightOfSelect(p->pPrior, pnHeight);
  77700. }
  77701. }
  77702. /*
  77703. ** Set the Expr.nHeight variable in the structure passed as an
  77704. ** argument. An expression with no children, Expr.pList or
  77705. ** Expr.pSelect member has a height of 1. Any other expression
  77706. ** has a height equal to the maximum height of any other
  77707. ** referenced Expr plus one.
  77708. **
  77709. ** Also propagate EP_Propagate flags up from Expr.x.pList to Expr.flags,
  77710. ** if appropriate.
  77711. */
  77712. static void exprSetHeight(Expr *p){
  77713. int nHeight = 0;
  77714. heightOfExpr(p->pLeft, &nHeight);
  77715. heightOfExpr(p->pRight, &nHeight);
  77716. if( ExprHasProperty(p, EP_xIsSelect) ){
  77717. heightOfSelect(p->x.pSelect, &nHeight);
  77718. }else if( p->x.pList ){
  77719. heightOfExprList(p->x.pList, &nHeight);
  77720. p->flags |= EP_Propagate & sqlite3ExprListFlags(p->x.pList);
  77721. }
  77722. p->nHeight = nHeight + 1;
  77723. }
  77724. /*
  77725. ** Set the Expr.nHeight variable using the exprSetHeight() function. If
  77726. ** the height is greater than the maximum allowed expression depth,
  77727. ** leave an error in pParse.
  77728. **
  77729. ** Also propagate all EP_Propagate flags from the Expr.x.pList into
  77730. ** Expr.flags.
  77731. */
  77732. SQLITE_PRIVATE void sqlite3ExprSetHeightAndFlags(Parse *pParse, Expr *p){
  77733. if( pParse->nErr ) return;
  77734. exprSetHeight(p);
  77735. sqlite3ExprCheckHeight(pParse, p->nHeight);
  77736. }
  77737. /*
  77738. ** Return the maximum height of any expression tree referenced
  77739. ** by the select statement passed as an argument.
  77740. */
  77741. SQLITE_PRIVATE int sqlite3SelectExprHeight(Select *p){
  77742. int nHeight = 0;
  77743. heightOfSelect(p, &nHeight);
  77744. return nHeight;
  77745. }
  77746. #else /* ABOVE: Height enforcement enabled. BELOW: Height enforcement off */
  77747. /*
  77748. ** Propagate all EP_Propagate flags from the Expr.x.pList into
  77749. ** Expr.flags.
  77750. */
  77751. SQLITE_PRIVATE void sqlite3ExprSetHeightAndFlags(Parse *pParse, Expr *p){
  77752. if( p && p->x.pList && !ExprHasProperty(p, EP_xIsSelect) ){
  77753. p->flags |= EP_Propagate & sqlite3ExprListFlags(p->x.pList);
  77754. }
  77755. }
  77756. #define exprSetHeight(y)
  77757. #endif /* SQLITE_MAX_EXPR_DEPTH>0 */
  77758. /*
  77759. ** This routine is the core allocator for Expr nodes.
  77760. **
  77761. ** Construct a new expression node and return a pointer to it. Memory
  77762. ** for this node and for the pToken argument is a single allocation
  77763. ** obtained from sqlite3DbMalloc(). The calling function
  77764. ** is responsible for making sure the node eventually gets freed.
  77765. **
  77766. ** If dequote is true, then the token (if it exists) is dequoted.
  77767. ** If dequote is false, no dequoting is performance. The deQuote
  77768. ** parameter is ignored if pToken is NULL or if the token does not
  77769. ** appear to be quoted. If the quotes were of the form "..." (double-quotes)
  77770. ** then the EP_DblQuoted flag is set on the expression node.
  77771. **
  77772. ** Special case: If op==TK_INTEGER and pToken points to a string that
  77773. ** can be translated into a 32-bit integer, then the token is not
  77774. ** stored in u.zToken. Instead, the integer values is written
  77775. ** into u.iValue and the EP_IntValue flag is set. No extra storage
  77776. ** is allocated to hold the integer text and the dequote flag is ignored.
  77777. */
  77778. SQLITE_PRIVATE Expr *sqlite3ExprAlloc(
  77779. sqlite3 *db, /* Handle for sqlite3DbMallocZero() (may be null) */
  77780. int op, /* Expression opcode */
  77781. const Token *pToken, /* Token argument. Might be NULL */
  77782. int dequote /* True to dequote */
  77783. ){
  77784. Expr *pNew;
  77785. int nExtra = 0;
  77786. int iValue = 0;
  77787. if( pToken ){
  77788. if( op!=TK_INTEGER || pToken->z==0
  77789. || sqlite3GetInt32(pToken->z, &iValue)==0 ){
  77790. nExtra = pToken->n+1;
  77791. assert( iValue>=0 );
  77792. }
  77793. }
  77794. pNew = sqlite3DbMallocZero(db, sizeof(Expr)+nExtra);
  77795. if( pNew ){
  77796. pNew->op = (u8)op;
  77797. pNew->iAgg = -1;
  77798. if( pToken ){
  77799. if( nExtra==0 ){
  77800. pNew->flags |= EP_IntValue;
  77801. pNew->u.iValue = iValue;
  77802. }else{
  77803. int c;
  77804. pNew->u.zToken = (char*)&pNew[1];
  77805. assert( pToken->z!=0 || pToken->n==0 );
  77806. if( pToken->n ) memcpy(pNew->u.zToken, pToken->z, pToken->n);
  77807. pNew->u.zToken[pToken->n] = 0;
  77808. if( dequote && nExtra>=3
  77809. && ((c = pToken->z[0])=='\'' || c=='"' || c=='[' || c=='`') ){
  77810. sqlite3Dequote(pNew->u.zToken);
  77811. if( c=='"' ) pNew->flags |= EP_DblQuoted;
  77812. }
  77813. }
  77814. }
  77815. #if SQLITE_MAX_EXPR_DEPTH>0
  77816. pNew->nHeight = 1;
  77817. #endif
  77818. }
  77819. return pNew;
  77820. }
  77821. /*
  77822. ** Allocate a new expression node from a zero-terminated token that has
  77823. ** already been dequoted.
  77824. */
  77825. SQLITE_PRIVATE Expr *sqlite3Expr(
  77826. sqlite3 *db, /* Handle for sqlite3DbMallocZero() (may be null) */
  77827. int op, /* Expression opcode */
  77828. const char *zToken /* Token argument. Might be NULL */
  77829. ){
  77830. Token x;
  77831. x.z = zToken;
  77832. x.n = zToken ? sqlite3Strlen30(zToken) : 0;
  77833. return sqlite3ExprAlloc(db, op, &x, 0);
  77834. }
  77835. /*
  77836. ** Attach subtrees pLeft and pRight to the Expr node pRoot.
  77837. **
  77838. ** If pRoot==NULL that means that a memory allocation error has occurred.
  77839. ** In that case, delete the subtrees pLeft and pRight.
  77840. */
  77841. SQLITE_PRIVATE void sqlite3ExprAttachSubtrees(
  77842. sqlite3 *db,
  77843. Expr *pRoot,
  77844. Expr *pLeft,
  77845. Expr *pRight
  77846. ){
  77847. if( pRoot==0 ){
  77848. assert( db->mallocFailed );
  77849. sqlite3ExprDelete(db, pLeft);
  77850. sqlite3ExprDelete(db, pRight);
  77851. }else{
  77852. if( pRight ){
  77853. pRoot->pRight = pRight;
  77854. pRoot->flags |= EP_Propagate & pRight->flags;
  77855. }
  77856. if( pLeft ){
  77857. pRoot->pLeft = pLeft;
  77858. pRoot->flags |= EP_Propagate & pLeft->flags;
  77859. }
  77860. exprSetHeight(pRoot);
  77861. }
  77862. }
  77863. /*
  77864. ** Allocate an Expr node which joins as many as two subtrees.
  77865. **
  77866. ** One or both of the subtrees can be NULL. Return a pointer to the new
  77867. ** Expr node. Or, if an OOM error occurs, set pParse->db->mallocFailed,
  77868. ** free the subtrees and return NULL.
  77869. */
  77870. SQLITE_PRIVATE Expr *sqlite3PExpr(
  77871. Parse *pParse, /* Parsing context */
  77872. int op, /* Expression opcode */
  77873. Expr *pLeft, /* Left operand */
  77874. Expr *pRight, /* Right operand */
  77875. const Token *pToken /* Argument token */
  77876. ){
  77877. Expr *p;
  77878. if( op==TK_AND && pLeft && pRight && pParse->nErr==0 ){
  77879. /* Take advantage of short-circuit false optimization for AND */
  77880. p = sqlite3ExprAnd(pParse->db, pLeft, pRight);
  77881. }else{
  77882. p = sqlite3ExprAlloc(pParse->db, op, pToken, 1);
  77883. sqlite3ExprAttachSubtrees(pParse->db, p, pLeft, pRight);
  77884. }
  77885. if( p ) {
  77886. sqlite3ExprCheckHeight(pParse, p->nHeight);
  77887. }
  77888. return p;
  77889. }
  77890. /*
  77891. ** If the expression is always either TRUE or FALSE (respectively),
  77892. ** then return 1. If one cannot determine the truth value of the
  77893. ** expression at compile-time return 0.
  77894. **
  77895. ** This is an optimization. If is OK to return 0 here even if
  77896. ** the expression really is always false or false (a false negative).
  77897. ** But it is a bug to return 1 if the expression might have different
  77898. ** boolean values in different circumstances (a false positive.)
  77899. **
  77900. ** Note that if the expression is part of conditional for a
  77901. ** LEFT JOIN, then we cannot determine at compile-time whether or not
  77902. ** is it true or false, so always return 0.
  77903. */
  77904. static int exprAlwaysTrue(Expr *p){
  77905. int v = 0;
  77906. if( ExprHasProperty(p, EP_FromJoin) ) return 0;
  77907. if( !sqlite3ExprIsInteger(p, &v) ) return 0;
  77908. return v!=0;
  77909. }
  77910. static int exprAlwaysFalse(Expr *p){
  77911. int v = 0;
  77912. if( ExprHasProperty(p, EP_FromJoin) ) return 0;
  77913. if( !sqlite3ExprIsInteger(p, &v) ) return 0;
  77914. return v==0;
  77915. }
  77916. /*
  77917. ** Join two expressions using an AND operator. If either expression is
  77918. ** NULL, then just return the other expression.
  77919. **
  77920. ** If one side or the other of the AND is known to be false, then instead
  77921. ** of returning an AND expression, just return a constant expression with
  77922. ** a value of false.
  77923. */
  77924. SQLITE_PRIVATE Expr *sqlite3ExprAnd(sqlite3 *db, Expr *pLeft, Expr *pRight){
  77925. if( pLeft==0 ){
  77926. return pRight;
  77927. }else if( pRight==0 ){
  77928. return pLeft;
  77929. }else if( exprAlwaysFalse(pLeft) || exprAlwaysFalse(pRight) ){
  77930. sqlite3ExprDelete(db, pLeft);
  77931. sqlite3ExprDelete(db, pRight);
  77932. return sqlite3ExprAlloc(db, TK_INTEGER, &sqlite3IntTokens[0], 0);
  77933. }else{
  77934. Expr *pNew = sqlite3ExprAlloc(db, TK_AND, 0, 0);
  77935. sqlite3ExprAttachSubtrees(db, pNew, pLeft, pRight);
  77936. return pNew;
  77937. }
  77938. }
  77939. /*
  77940. ** Construct a new expression node for a function with multiple
  77941. ** arguments.
  77942. */
  77943. SQLITE_PRIVATE Expr *sqlite3ExprFunction(Parse *pParse, ExprList *pList, Token *pToken){
  77944. Expr *pNew;
  77945. sqlite3 *db = pParse->db;
  77946. assert( pToken );
  77947. pNew = sqlite3ExprAlloc(db, TK_FUNCTION, pToken, 1);
  77948. if( pNew==0 ){
  77949. sqlite3ExprListDelete(db, pList); /* Avoid memory leak when malloc fails */
  77950. return 0;
  77951. }
  77952. pNew->x.pList = pList;
  77953. assert( !ExprHasProperty(pNew, EP_xIsSelect) );
  77954. sqlite3ExprSetHeightAndFlags(pParse, pNew);
  77955. return pNew;
  77956. }
  77957. /*
  77958. ** Assign a variable number to an expression that encodes a wildcard
  77959. ** in the original SQL statement.
  77960. **
  77961. ** Wildcards consisting of a single "?" are assigned the next sequential
  77962. ** variable number.
  77963. **
  77964. ** Wildcards of the form "?nnn" are assigned the number "nnn". We make
  77965. ** sure "nnn" is not too be to avoid a denial of service attack when
  77966. ** the SQL statement comes from an external source.
  77967. **
  77968. ** Wildcards of the form ":aaa", "@aaa", or "$aaa" are assigned the same number
  77969. ** as the previous instance of the same wildcard. Or if this is the first
  77970. ** instance of the wildcard, the next sequential variable number is
  77971. ** assigned.
  77972. */
  77973. SQLITE_PRIVATE void sqlite3ExprAssignVarNumber(Parse *pParse, Expr *pExpr){
  77974. sqlite3 *db = pParse->db;
  77975. const char *z;
  77976. if( pExpr==0 ) return;
  77977. assert( !ExprHasProperty(pExpr, EP_IntValue|EP_Reduced|EP_TokenOnly) );
  77978. z = pExpr->u.zToken;
  77979. assert( z!=0 );
  77980. assert( z[0]!=0 );
  77981. if( z[1]==0 ){
  77982. /* Wildcard of the form "?". Assign the next variable number */
  77983. assert( z[0]=='?' );
  77984. pExpr->iColumn = (ynVar)(++pParse->nVar);
  77985. }else{
  77986. ynVar x = 0;
  77987. u32 n = sqlite3Strlen30(z);
  77988. if( z[0]=='?' ){
  77989. /* Wildcard of the form "?nnn". Convert "nnn" to an integer and
  77990. ** use it as the variable number */
  77991. i64 i;
  77992. int bOk = 0==sqlite3Atoi64(&z[1], &i, n-1, SQLITE_UTF8);
  77993. pExpr->iColumn = x = (ynVar)i;
  77994. testcase( i==0 );
  77995. testcase( i==1 );
  77996. testcase( i==db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER]-1 );
  77997. testcase( i==db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] );
  77998. if( bOk==0 || i<1 || i>db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] ){
  77999. sqlite3ErrorMsg(pParse, "variable number must be between ?1 and ?%d",
  78000. db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER]);
  78001. x = 0;
  78002. }
  78003. if( i>pParse->nVar ){
  78004. pParse->nVar = (int)i;
  78005. }
  78006. }else{
  78007. /* Wildcards like ":aaa", "$aaa" or "@aaa". Reuse the same variable
  78008. ** number as the prior appearance of the same name, or if the name
  78009. ** has never appeared before, reuse the same variable number
  78010. */
  78011. ynVar i;
  78012. for(i=0; i<pParse->nzVar; i++){
  78013. if( pParse->azVar[i] && strcmp(pParse->azVar[i],z)==0 ){
  78014. pExpr->iColumn = x = (ynVar)i+1;
  78015. break;
  78016. }
  78017. }
  78018. if( x==0 ) x = pExpr->iColumn = (ynVar)(++pParse->nVar);
  78019. }
  78020. if( x>0 ){
  78021. if( x>pParse->nzVar ){
  78022. char **a;
  78023. a = sqlite3DbRealloc(db, pParse->azVar, x*sizeof(a[0]));
  78024. if( a==0 ) return; /* Error reported through db->mallocFailed */
  78025. pParse->azVar = a;
  78026. memset(&a[pParse->nzVar], 0, (x-pParse->nzVar)*sizeof(a[0]));
  78027. pParse->nzVar = x;
  78028. }
  78029. if( z[0]!='?' || pParse->azVar[x-1]==0 ){
  78030. sqlite3DbFree(db, pParse->azVar[x-1]);
  78031. pParse->azVar[x-1] = sqlite3DbStrNDup(db, z, n);
  78032. }
  78033. }
  78034. }
  78035. if( !pParse->nErr && pParse->nVar>db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] ){
  78036. sqlite3ErrorMsg(pParse, "too many SQL variables");
  78037. }
  78038. }
  78039. /*
  78040. ** Recursively delete an expression tree.
  78041. */
  78042. SQLITE_PRIVATE void sqlite3ExprDelete(sqlite3 *db, Expr *p){
  78043. if( p==0 ) return;
  78044. /* Sanity check: Assert that the IntValue is non-negative if it exists */
  78045. assert( !ExprHasProperty(p, EP_IntValue) || p->u.iValue>=0 );
  78046. if( !ExprHasProperty(p, EP_TokenOnly) ){
  78047. /* The Expr.x union is never used at the same time as Expr.pRight */
  78048. assert( p->x.pList==0 || p->pRight==0 );
  78049. sqlite3ExprDelete(db, p->pLeft);
  78050. sqlite3ExprDelete(db, p->pRight);
  78051. if( ExprHasProperty(p, EP_MemToken) ) sqlite3DbFree(db, p->u.zToken);
  78052. if( ExprHasProperty(p, EP_xIsSelect) ){
  78053. sqlite3SelectDelete(db, p->x.pSelect);
  78054. }else{
  78055. sqlite3ExprListDelete(db, p->x.pList);
  78056. }
  78057. }
  78058. if( !ExprHasProperty(p, EP_Static) ){
  78059. sqlite3DbFree(db, p);
  78060. }
  78061. }
  78062. /*
  78063. ** Return the number of bytes allocated for the expression structure
  78064. ** passed as the first argument. This is always one of EXPR_FULLSIZE,
  78065. ** EXPR_REDUCEDSIZE or EXPR_TOKENONLYSIZE.
  78066. */
  78067. static int exprStructSize(Expr *p){
  78068. if( ExprHasProperty(p, EP_TokenOnly) ) return EXPR_TOKENONLYSIZE;
  78069. if( ExprHasProperty(p, EP_Reduced) ) return EXPR_REDUCEDSIZE;
  78070. return EXPR_FULLSIZE;
  78071. }
  78072. /*
  78073. ** The dupedExpr*Size() routines each return the number of bytes required
  78074. ** to store a copy of an expression or expression tree. They differ in
  78075. ** how much of the tree is measured.
  78076. **
  78077. ** dupedExprStructSize() Size of only the Expr structure
  78078. ** dupedExprNodeSize() Size of Expr + space for token
  78079. ** dupedExprSize() Expr + token + subtree components
  78080. **
  78081. ***************************************************************************
  78082. **
  78083. ** The dupedExprStructSize() function returns two values OR-ed together:
  78084. ** (1) the space required for a copy of the Expr structure only and
  78085. ** (2) the EP_xxx flags that indicate what the structure size should be.
  78086. ** The return values is always one of:
  78087. **
  78088. ** EXPR_FULLSIZE
  78089. ** EXPR_REDUCEDSIZE | EP_Reduced
  78090. ** EXPR_TOKENONLYSIZE | EP_TokenOnly
  78091. **
  78092. ** The size of the structure can be found by masking the return value
  78093. ** of this routine with 0xfff. The flags can be found by masking the
  78094. ** return value with EP_Reduced|EP_TokenOnly.
  78095. **
  78096. ** Note that with flags==EXPRDUP_REDUCE, this routines works on full-size
  78097. ** (unreduced) Expr objects as they or originally constructed by the parser.
  78098. ** During expression analysis, extra information is computed and moved into
  78099. ** later parts of teh Expr object and that extra information might get chopped
  78100. ** off if the expression is reduced. Note also that it does not work to
  78101. ** make an EXPRDUP_REDUCE copy of a reduced expression. It is only legal
  78102. ** to reduce a pristine expression tree from the parser. The implementation
  78103. ** of dupedExprStructSize() contain multiple assert() statements that attempt
  78104. ** to enforce this constraint.
  78105. */
  78106. static int dupedExprStructSize(Expr *p, int flags){
  78107. int nSize;
  78108. assert( flags==EXPRDUP_REDUCE || flags==0 ); /* Only one flag value allowed */
  78109. assert( EXPR_FULLSIZE<=0xfff );
  78110. assert( (0xfff & (EP_Reduced|EP_TokenOnly))==0 );
  78111. if( 0==(flags&EXPRDUP_REDUCE) ){
  78112. nSize = EXPR_FULLSIZE;
  78113. }else{
  78114. assert( !ExprHasProperty(p, EP_TokenOnly|EP_Reduced) );
  78115. assert( !ExprHasProperty(p, EP_FromJoin) );
  78116. assert( !ExprHasProperty(p, EP_MemToken) );
  78117. assert( !ExprHasProperty(p, EP_NoReduce) );
  78118. if( p->pLeft || p->x.pList ){
  78119. nSize = EXPR_REDUCEDSIZE | EP_Reduced;
  78120. }else{
  78121. assert( p->pRight==0 );
  78122. nSize = EXPR_TOKENONLYSIZE | EP_TokenOnly;
  78123. }
  78124. }
  78125. return nSize;
  78126. }
  78127. /*
  78128. ** This function returns the space in bytes required to store the copy
  78129. ** of the Expr structure and a copy of the Expr.u.zToken string (if that
  78130. ** string is defined.)
  78131. */
  78132. static int dupedExprNodeSize(Expr *p, int flags){
  78133. int nByte = dupedExprStructSize(p, flags) & 0xfff;
  78134. if( !ExprHasProperty(p, EP_IntValue) && p->u.zToken ){
  78135. nByte += sqlite3Strlen30(p->u.zToken)+1;
  78136. }
  78137. return ROUND8(nByte);
  78138. }
  78139. /*
  78140. ** Return the number of bytes required to create a duplicate of the
  78141. ** expression passed as the first argument. The second argument is a
  78142. ** mask containing EXPRDUP_XXX flags.
  78143. **
  78144. ** The value returned includes space to create a copy of the Expr struct
  78145. ** itself and the buffer referred to by Expr.u.zToken, if any.
  78146. **
  78147. ** If the EXPRDUP_REDUCE flag is set, then the return value includes
  78148. ** space to duplicate all Expr nodes in the tree formed by Expr.pLeft
  78149. ** and Expr.pRight variables (but not for any structures pointed to or
  78150. ** descended from the Expr.x.pList or Expr.x.pSelect variables).
  78151. */
  78152. static int dupedExprSize(Expr *p, int flags){
  78153. int nByte = 0;
  78154. if( p ){
  78155. nByte = dupedExprNodeSize(p, flags);
  78156. if( flags&EXPRDUP_REDUCE ){
  78157. nByte += dupedExprSize(p->pLeft, flags) + dupedExprSize(p->pRight, flags);
  78158. }
  78159. }
  78160. return nByte;
  78161. }
  78162. /*
  78163. ** This function is similar to sqlite3ExprDup(), except that if pzBuffer
  78164. ** is not NULL then *pzBuffer is assumed to point to a buffer large enough
  78165. ** to store the copy of expression p, the copies of p->u.zToken
  78166. ** (if applicable), and the copies of the p->pLeft and p->pRight expressions,
  78167. ** if any. Before returning, *pzBuffer is set to the first byte past the
  78168. ** portion of the buffer copied into by this function.
  78169. */
  78170. static Expr *exprDup(sqlite3 *db, Expr *p, int flags, u8 **pzBuffer){
  78171. Expr *pNew = 0; /* Value to return */
  78172. if( p ){
  78173. const int isReduced = (flags&EXPRDUP_REDUCE);
  78174. u8 *zAlloc;
  78175. u32 staticFlag = 0;
  78176. assert( pzBuffer==0 || isReduced );
  78177. /* Figure out where to write the new Expr structure. */
  78178. if( pzBuffer ){
  78179. zAlloc = *pzBuffer;
  78180. staticFlag = EP_Static;
  78181. }else{
  78182. zAlloc = sqlite3DbMallocRaw(db, dupedExprSize(p, flags));
  78183. }
  78184. pNew = (Expr *)zAlloc;
  78185. if( pNew ){
  78186. /* Set nNewSize to the size allocated for the structure pointed to
  78187. ** by pNew. This is either EXPR_FULLSIZE, EXPR_REDUCEDSIZE or
  78188. ** EXPR_TOKENONLYSIZE. nToken is set to the number of bytes consumed
  78189. ** by the copy of the p->u.zToken string (if any).
  78190. */
  78191. const unsigned nStructSize = dupedExprStructSize(p, flags);
  78192. const int nNewSize = nStructSize & 0xfff;
  78193. int nToken;
  78194. if( !ExprHasProperty(p, EP_IntValue) && p->u.zToken ){
  78195. nToken = sqlite3Strlen30(p->u.zToken) + 1;
  78196. }else{
  78197. nToken = 0;
  78198. }
  78199. if( isReduced ){
  78200. assert( ExprHasProperty(p, EP_Reduced)==0 );
  78201. memcpy(zAlloc, p, nNewSize);
  78202. }else{
  78203. int nSize = exprStructSize(p);
  78204. memcpy(zAlloc, p, nSize);
  78205. memset(&zAlloc[nSize], 0, EXPR_FULLSIZE-nSize);
  78206. }
  78207. /* Set the EP_Reduced, EP_TokenOnly, and EP_Static flags appropriately. */
  78208. pNew->flags &= ~(EP_Reduced|EP_TokenOnly|EP_Static|EP_MemToken);
  78209. pNew->flags |= nStructSize & (EP_Reduced|EP_TokenOnly);
  78210. pNew->flags |= staticFlag;
  78211. /* Copy the p->u.zToken string, if any. */
  78212. if( nToken ){
  78213. char *zToken = pNew->u.zToken = (char*)&zAlloc[nNewSize];
  78214. memcpy(zToken, p->u.zToken, nToken);
  78215. }
  78216. if( 0==((p->flags|pNew->flags) & EP_TokenOnly) ){
  78217. /* Fill in the pNew->x.pSelect or pNew->x.pList member. */
  78218. if( ExprHasProperty(p, EP_xIsSelect) ){
  78219. pNew->x.pSelect = sqlite3SelectDup(db, p->x.pSelect, isReduced);
  78220. }else{
  78221. pNew->x.pList = sqlite3ExprListDup(db, p->x.pList, isReduced);
  78222. }
  78223. }
  78224. /* Fill in pNew->pLeft and pNew->pRight. */
  78225. if( ExprHasProperty(pNew, EP_Reduced|EP_TokenOnly) ){
  78226. zAlloc += dupedExprNodeSize(p, flags);
  78227. if( ExprHasProperty(pNew, EP_Reduced) ){
  78228. pNew->pLeft = exprDup(db, p->pLeft, EXPRDUP_REDUCE, &zAlloc);
  78229. pNew->pRight = exprDup(db, p->pRight, EXPRDUP_REDUCE, &zAlloc);
  78230. }
  78231. if( pzBuffer ){
  78232. *pzBuffer = zAlloc;
  78233. }
  78234. }else{
  78235. if( !ExprHasProperty(p, EP_TokenOnly) ){
  78236. pNew->pLeft = sqlite3ExprDup(db, p->pLeft, 0);
  78237. pNew->pRight = sqlite3ExprDup(db, p->pRight, 0);
  78238. }
  78239. }
  78240. }
  78241. }
  78242. return pNew;
  78243. }
  78244. /*
  78245. ** Create and return a deep copy of the object passed as the second
  78246. ** argument. If an OOM condition is encountered, NULL is returned
  78247. ** and the db->mallocFailed flag set.
  78248. */
  78249. #ifndef SQLITE_OMIT_CTE
  78250. static With *withDup(sqlite3 *db, With *p){
  78251. With *pRet = 0;
  78252. if( p ){
  78253. int nByte = sizeof(*p) + sizeof(p->a[0]) * (p->nCte-1);
  78254. pRet = sqlite3DbMallocZero(db, nByte);
  78255. if( pRet ){
  78256. int i;
  78257. pRet->nCte = p->nCte;
  78258. for(i=0; i<p->nCte; i++){
  78259. pRet->a[i].pSelect = sqlite3SelectDup(db, p->a[i].pSelect, 0);
  78260. pRet->a[i].pCols = sqlite3ExprListDup(db, p->a[i].pCols, 0);
  78261. pRet->a[i].zName = sqlite3DbStrDup(db, p->a[i].zName);
  78262. }
  78263. }
  78264. }
  78265. return pRet;
  78266. }
  78267. #else
  78268. # define withDup(x,y) 0
  78269. #endif
  78270. /*
  78271. ** The following group of routines make deep copies of expressions,
  78272. ** expression lists, ID lists, and select statements. The copies can
  78273. ** be deleted (by being passed to their respective ...Delete() routines)
  78274. ** without effecting the originals.
  78275. **
  78276. ** The expression list, ID, and source lists return by sqlite3ExprListDup(),
  78277. ** sqlite3IdListDup(), and sqlite3SrcListDup() can not be further expanded
  78278. ** by subsequent calls to sqlite*ListAppend() routines.
  78279. **
  78280. ** Any tables that the SrcList might point to are not duplicated.
  78281. **
  78282. ** The flags parameter contains a combination of the EXPRDUP_XXX flags.
  78283. ** If the EXPRDUP_REDUCE flag is set, then the structure returned is a
  78284. ** truncated version of the usual Expr structure that will be stored as
  78285. ** part of the in-memory representation of the database schema.
  78286. */
  78287. SQLITE_PRIVATE Expr *sqlite3ExprDup(sqlite3 *db, Expr *p, int flags){
  78288. return exprDup(db, p, flags, 0);
  78289. }
  78290. SQLITE_PRIVATE ExprList *sqlite3ExprListDup(sqlite3 *db, ExprList *p, int flags){
  78291. ExprList *pNew;
  78292. struct ExprList_item *pItem, *pOldItem;
  78293. int i;
  78294. if( p==0 ) return 0;
  78295. pNew = sqlite3DbMallocRaw(db, sizeof(*pNew) );
  78296. if( pNew==0 ) return 0;
  78297. pNew->nExpr = i = p->nExpr;
  78298. if( (flags & EXPRDUP_REDUCE)==0 ) for(i=1; i<p->nExpr; i+=i){}
  78299. pNew->a = pItem = sqlite3DbMallocRaw(db, i*sizeof(p->a[0]) );
  78300. if( pItem==0 ){
  78301. sqlite3DbFree(db, pNew);
  78302. return 0;
  78303. }
  78304. pOldItem = p->a;
  78305. for(i=0; i<p->nExpr; i++, pItem++, pOldItem++){
  78306. Expr *pOldExpr = pOldItem->pExpr;
  78307. pItem->pExpr = sqlite3ExprDup(db, pOldExpr, flags);
  78308. pItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
  78309. pItem->zSpan = sqlite3DbStrDup(db, pOldItem->zSpan);
  78310. pItem->sortOrder = pOldItem->sortOrder;
  78311. pItem->done = 0;
  78312. pItem->bSpanIsTab = pOldItem->bSpanIsTab;
  78313. pItem->u = pOldItem->u;
  78314. }
  78315. return pNew;
  78316. }
  78317. /*
  78318. ** If cursors, triggers, views and subqueries are all omitted from
  78319. ** the build, then none of the following routines, except for
  78320. ** sqlite3SelectDup(), can be called. sqlite3SelectDup() is sometimes
  78321. ** called with a NULL argument.
  78322. */
  78323. #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER) \
  78324. || !defined(SQLITE_OMIT_SUBQUERY)
  78325. SQLITE_PRIVATE SrcList *sqlite3SrcListDup(sqlite3 *db, SrcList *p, int flags){
  78326. SrcList *pNew;
  78327. int i;
  78328. int nByte;
  78329. if( p==0 ) return 0;
  78330. nByte = sizeof(*p) + (p->nSrc>0 ? sizeof(p->a[0]) * (p->nSrc-1) : 0);
  78331. pNew = sqlite3DbMallocRaw(db, nByte );
  78332. if( pNew==0 ) return 0;
  78333. pNew->nSrc = pNew->nAlloc = p->nSrc;
  78334. for(i=0; i<p->nSrc; i++){
  78335. struct SrcList_item *pNewItem = &pNew->a[i];
  78336. struct SrcList_item *pOldItem = &p->a[i];
  78337. Table *pTab;
  78338. pNewItem->pSchema = pOldItem->pSchema;
  78339. pNewItem->zDatabase = sqlite3DbStrDup(db, pOldItem->zDatabase);
  78340. pNewItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
  78341. pNewItem->zAlias = sqlite3DbStrDup(db, pOldItem->zAlias);
  78342. pNewItem->jointype = pOldItem->jointype;
  78343. pNewItem->iCursor = pOldItem->iCursor;
  78344. pNewItem->addrFillSub = pOldItem->addrFillSub;
  78345. pNewItem->regReturn = pOldItem->regReturn;
  78346. pNewItem->isCorrelated = pOldItem->isCorrelated;
  78347. pNewItem->viaCoroutine = pOldItem->viaCoroutine;
  78348. pNewItem->isRecursive = pOldItem->isRecursive;
  78349. pNewItem->zIndex = sqlite3DbStrDup(db, pOldItem->zIndex);
  78350. pNewItem->notIndexed = pOldItem->notIndexed;
  78351. pNewItem->pIndex = pOldItem->pIndex;
  78352. pTab = pNewItem->pTab = pOldItem->pTab;
  78353. if( pTab ){
  78354. pTab->nRef++;
  78355. }
  78356. pNewItem->pSelect = sqlite3SelectDup(db, pOldItem->pSelect, flags);
  78357. pNewItem->pOn = sqlite3ExprDup(db, pOldItem->pOn, flags);
  78358. pNewItem->pUsing = sqlite3IdListDup(db, pOldItem->pUsing);
  78359. pNewItem->colUsed = pOldItem->colUsed;
  78360. }
  78361. return pNew;
  78362. }
  78363. SQLITE_PRIVATE IdList *sqlite3IdListDup(sqlite3 *db, IdList *p){
  78364. IdList *pNew;
  78365. int i;
  78366. if( p==0 ) return 0;
  78367. pNew = sqlite3DbMallocRaw(db, sizeof(*pNew) );
  78368. if( pNew==0 ) return 0;
  78369. pNew->nId = p->nId;
  78370. pNew->a = sqlite3DbMallocRaw(db, p->nId*sizeof(p->a[0]) );
  78371. if( pNew->a==0 ){
  78372. sqlite3DbFree(db, pNew);
  78373. return 0;
  78374. }
  78375. /* Note that because the size of the allocation for p->a[] is not
  78376. ** necessarily a power of two, sqlite3IdListAppend() may not be called
  78377. ** on the duplicate created by this function. */
  78378. for(i=0; i<p->nId; i++){
  78379. struct IdList_item *pNewItem = &pNew->a[i];
  78380. struct IdList_item *pOldItem = &p->a[i];
  78381. pNewItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
  78382. pNewItem->idx = pOldItem->idx;
  78383. }
  78384. return pNew;
  78385. }
  78386. SQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3 *db, Select *p, int flags){
  78387. Select *pNew, *pPrior;
  78388. if( p==0 ) return 0;
  78389. pNew = sqlite3DbMallocRaw(db, sizeof(*p) );
  78390. if( pNew==0 ) return 0;
  78391. pNew->pEList = sqlite3ExprListDup(db, p->pEList, flags);
  78392. pNew->pSrc = sqlite3SrcListDup(db, p->pSrc, flags);
  78393. pNew->pWhere = sqlite3ExprDup(db, p->pWhere, flags);
  78394. pNew->pGroupBy = sqlite3ExprListDup(db, p->pGroupBy, flags);
  78395. pNew->pHaving = sqlite3ExprDup(db, p->pHaving, flags);
  78396. pNew->pOrderBy = sqlite3ExprListDup(db, p->pOrderBy, flags);
  78397. pNew->op = p->op;
  78398. pNew->pPrior = pPrior = sqlite3SelectDup(db, p->pPrior, flags);
  78399. if( pPrior ) pPrior->pNext = pNew;
  78400. pNew->pNext = 0;
  78401. pNew->pLimit = sqlite3ExprDup(db, p->pLimit, flags);
  78402. pNew->pOffset = sqlite3ExprDup(db, p->pOffset, flags);
  78403. pNew->iLimit = 0;
  78404. pNew->iOffset = 0;
  78405. pNew->selFlags = p->selFlags & ~SF_UsesEphemeral;
  78406. pNew->addrOpenEphm[0] = -1;
  78407. pNew->addrOpenEphm[1] = -1;
  78408. pNew->nSelectRow = p->nSelectRow;
  78409. pNew->pWith = withDup(db, p->pWith);
  78410. sqlite3SelectSetName(pNew, p->zSelName);
  78411. return pNew;
  78412. }
  78413. #else
  78414. SQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3 *db, Select *p, int flags){
  78415. assert( p==0 );
  78416. return 0;
  78417. }
  78418. #endif
  78419. /*
  78420. ** Add a new element to the end of an expression list. If pList is
  78421. ** initially NULL, then create a new expression list.
  78422. **
  78423. ** If a memory allocation error occurs, the entire list is freed and
  78424. ** NULL is returned. If non-NULL is returned, then it is guaranteed
  78425. ** that the new entry was successfully appended.
  78426. */
  78427. SQLITE_PRIVATE ExprList *sqlite3ExprListAppend(
  78428. Parse *pParse, /* Parsing context */
  78429. ExprList *pList, /* List to which to append. Might be NULL */
  78430. Expr *pExpr /* Expression to be appended. Might be NULL */
  78431. ){
  78432. sqlite3 *db = pParse->db;
  78433. if( pList==0 ){
  78434. pList = sqlite3DbMallocZero(db, sizeof(ExprList) );
  78435. if( pList==0 ){
  78436. goto no_mem;
  78437. }
  78438. pList->a = sqlite3DbMallocRaw(db, sizeof(pList->a[0]));
  78439. if( pList->a==0 ) goto no_mem;
  78440. }else if( (pList->nExpr & (pList->nExpr-1))==0 ){
  78441. struct ExprList_item *a;
  78442. assert( pList->nExpr>0 );
  78443. a = sqlite3DbRealloc(db, pList->a, pList->nExpr*2*sizeof(pList->a[0]));
  78444. if( a==0 ){
  78445. goto no_mem;
  78446. }
  78447. pList->a = a;
  78448. }
  78449. assert( pList->a!=0 );
  78450. if( 1 ){
  78451. struct ExprList_item *pItem = &pList->a[pList->nExpr++];
  78452. memset(pItem, 0, sizeof(*pItem));
  78453. pItem->pExpr = pExpr;
  78454. }
  78455. return pList;
  78456. no_mem:
  78457. /* Avoid leaking memory if malloc has failed. */
  78458. sqlite3ExprDelete(db, pExpr);
  78459. sqlite3ExprListDelete(db, pList);
  78460. return 0;
  78461. }
  78462. /*
  78463. ** Set the ExprList.a[].zName element of the most recently added item
  78464. ** on the expression list.
  78465. **
  78466. ** pList might be NULL following an OOM error. But pName should never be
  78467. ** NULL. If a memory allocation fails, the pParse->db->mallocFailed flag
  78468. ** is set.
  78469. */
  78470. SQLITE_PRIVATE void sqlite3ExprListSetName(
  78471. Parse *pParse, /* Parsing context */
  78472. ExprList *pList, /* List to which to add the span. */
  78473. Token *pName, /* Name to be added */
  78474. int dequote /* True to cause the name to be dequoted */
  78475. ){
  78476. assert( pList!=0 || pParse->db->mallocFailed!=0 );
  78477. if( pList ){
  78478. struct ExprList_item *pItem;
  78479. assert( pList->nExpr>0 );
  78480. pItem = &pList->a[pList->nExpr-1];
  78481. assert( pItem->zName==0 );
  78482. pItem->zName = sqlite3DbStrNDup(pParse->db, pName->z, pName->n);
  78483. if( dequote && pItem->zName ) sqlite3Dequote(pItem->zName);
  78484. }
  78485. }
  78486. /*
  78487. ** Set the ExprList.a[].zSpan element of the most recently added item
  78488. ** on the expression list.
  78489. **
  78490. ** pList might be NULL following an OOM error. But pSpan should never be
  78491. ** NULL. If a memory allocation fails, the pParse->db->mallocFailed flag
  78492. ** is set.
  78493. */
  78494. SQLITE_PRIVATE void sqlite3ExprListSetSpan(
  78495. Parse *pParse, /* Parsing context */
  78496. ExprList *pList, /* List to which to add the span. */
  78497. ExprSpan *pSpan /* The span to be added */
  78498. ){
  78499. sqlite3 *db = pParse->db;
  78500. assert( pList!=0 || db->mallocFailed!=0 );
  78501. if( pList ){
  78502. struct ExprList_item *pItem = &pList->a[pList->nExpr-1];
  78503. assert( pList->nExpr>0 );
  78504. assert( db->mallocFailed || pItem->pExpr==pSpan->pExpr );
  78505. sqlite3DbFree(db, pItem->zSpan);
  78506. pItem->zSpan = sqlite3DbStrNDup(db, (char*)pSpan->zStart,
  78507. (int)(pSpan->zEnd - pSpan->zStart));
  78508. }
  78509. }
  78510. /*
  78511. ** If the expression list pEList contains more than iLimit elements,
  78512. ** leave an error message in pParse.
  78513. */
  78514. SQLITE_PRIVATE void sqlite3ExprListCheckLength(
  78515. Parse *pParse,
  78516. ExprList *pEList,
  78517. const char *zObject
  78518. ){
  78519. int mx = pParse->db->aLimit[SQLITE_LIMIT_COLUMN];
  78520. testcase( pEList && pEList->nExpr==mx );
  78521. testcase( pEList && pEList->nExpr==mx+1 );
  78522. if( pEList && pEList->nExpr>mx ){
  78523. sqlite3ErrorMsg(pParse, "too many columns in %s", zObject);
  78524. }
  78525. }
  78526. /*
  78527. ** Delete an entire expression list.
  78528. */
  78529. SQLITE_PRIVATE void sqlite3ExprListDelete(sqlite3 *db, ExprList *pList){
  78530. int i;
  78531. struct ExprList_item *pItem;
  78532. if( pList==0 ) return;
  78533. assert( pList->a!=0 || pList->nExpr==0 );
  78534. for(pItem=pList->a, i=0; i<pList->nExpr; i++, pItem++){
  78535. sqlite3ExprDelete(db, pItem->pExpr);
  78536. sqlite3DbFree(db, pItem->zName);
  78537. sqlite3DbFree(db, pItem->zSpan);
  78538. }
  78539. sqlite3DbFree(db, pList->a);
  78540. sqlite3DbFree(db, pList);
  78541. }
  78542. /*
  78543. ** Return the bitwise-OR of all Expr.flags fields in the given
  78544. ** ExprList.
  78545. */
  78546. SQLITE_PRIVATE u32 sqlite3ExprListFlags(const ExprList *pList){
  78547. int i;
  78548. u32 m = 0;
  78549. if( pList ){
  78550. for(i=0; i<pList->nExpr; i++){
  78551. Expr *pExpr = pList->a[i].pExpr;
  78552. if( ALWAYS(pExpr) ) m |= pExpr->flags;
  78553. }
  78554. }
  78555. return m;
  78556. }
  78557. /*
  78558. ** These routines are Walker callbacks used to check expressions to
  78559. ** see if they are "constant" for some definition of constant. The
  78560. ** Walker.eCode value determines the type of "constant" we are looking
  78561. ** for.
  78562. **
  78563. ** These callback routines are used to implement the following:
  78564. **
  78565. ** sqlite3ExprIsConstant() pWalker->eCode==1
  78566. ** sqlite3ExprIsConstantNotJoin() pWalker->eCode==2
  78567. ** sqlite3ExprRefOneTableOnly() pWalker->eCode==3
  78568. ** sqlite3ExprIsConstantOrFunction() pWalker->eCode==4 or 5
  78569. **
  78570. ** In all cases, the callbacks set Walker.eCode=0 and abort if the expression
  78571. ** is found to not be a constant.
  78572. **
  78573. ** The sqlite3ExprIsConstantOrFunction() is used for evaluating expressions
  78574. ** in a CREATE TABLE statement. The Walker.eCode value is 5 when parsing
  78575. ** an existing schema and 4 when processing a new statement. A bound
  78576. ** parameter raises an error for new statements, but is silently converted
  78577. ** to NULL for existing schemas. This allows sqlite_master tables that
  78578. ** contain a bound parameter because they were generated by older versions
  78579. ** of SQLite to be parsed by newer versions of SQLite without raising a
  78580. ** malformed schema error.
  78581. */
  78582. static int exprNodeIsConstant(Walker *pWalker, Expr *pExpr){
  78583. /* If pWalker->eCode is 2 then any term of the expression that comes from
  78584. ** the ON or USING clauses of a left join disqualifies the expression
  78585. ** from being considered constant. */
  78586. if( pWalker->eCode==2 && ExprHasProperty(pExpr, EP_FromJoin) ){
  78587. pWalker->eCode = 0;
  78588. return WRC_Abort;
  78589. }
  78590. switch( pExpr->op ){
  78591. /* Consider functions to be constant if all their arguments are constant
  78592. ** and either pWalker->eCode==4 or 5 or the function has the
  78593. ** SQLITE_FUNC_CONST flag. */
  78594. case TK_FUNCTION:
  78595. if( pWalker->eCode>=4 || ExprHasProperty(pExpr,EP_ConstFunc) ){
  78596. return WRC_Continue;
  78597. }else{
  78598. pWalker->eCode = 0;
  78599. return WRC_Abort;
  78600. }
  78601. case TK_ID:
  78602. case TK_COLUMN:
  78603. case TK_AGG_FUNCTION:
  78604. case TK_AGG_COLUMN:
  78605. testcase( pExpr->op==TK_ID );
  78606. testcase( pExpr->op==TK_COLUMN );
  78607. testcase( pExpr->op==TK_AGG_FUNCTION );
  78608. testcase( pExpr->op==TK_AGG_COLUMN );
  78609. if( pWalker->eCode==3 && pExpr->iTable==pWalker->u.iCur ){
  78610. return WRC_Continue;
  78611. }else{
  78612. pWalker->eCode = 0;
  78613. return WRC_Abort;
  78614. }
  78615. case TK_VARIABLE:
  78616. if( pWalker->eCode==5 ){
  78617. /* Silently convert bound parameters that appear inside of CREATE
  78618. ** statements into a NULL when parsing the CREATE statement text out
  78619. ** of the sqlite_master table */
  78620. pExpr->op = TK_NULL;
  78621. }else if( pWalker->eCode==4 ){
  78622. /* A bound parameter in a CREATE statement that originates from
  78623. ** sqlite3_prepare() causes an error */
  78624. pWalker->eCode = 0;
  78625. return WRC_Abort;
  78626. }
  78627. /* Fall through */
  78628. default:
  78629. testcase( pExpr->op==TK_SELECT ); /* selectNodeIsConstant will disallow */
  78630. testcase( pExpr->op==TK_EXISTS ); /* selectNodeIsConstant will disallow */
  78631. return WRC_Continue;
  78632. }
  78633. }
  78634. static int selectNodeIsConstant(Walker *pWalker, Select *NotUsed){
  78635. UNUSED_PARAMETER(NotUsed);
  78636. pWalker->eCode = 0;
  78637. return WRC_Abort;
  78638. }
  78639. static int exprIsConst(Expr *p, int initFlag, int iCur){
  78640. Walker w;
  78641. memset(&w, 0, sizeof(w));
  78642. w.eCode = initFlag;
  78643. w.xExprCallback = exprNodeIsConstant;
  78644. w.xSelectCallback = selectNodeIsConstant;
  78645. w.u.iCur = iCur;
  78646. sqlite3WalkExpr(&w, p);
  78647. return w.eCode;
  78648. }
  78649. /*
  78650. ** Walk an expression tree. Return non-zero if the expression is constant
  78651. ** and 0 if it involves variables or function calls.
  78652. **
  78653. ** For the purposes of this function, a double-quoted string (ex: "abc")
  78654. ** is considered a variable but a single-quoted string (ex: 'abc') is
  78655. ** a constant.
  78656. */
  78657. SQLITE_PRIVATE int sqlite3ExprIsConstant(Expr *p){
  78658. return exprIsConst(p, 1, 0);
  78659. }
  78660. /*
  78661. ** Walk an expression tree. Return non-zero if the expression is constant
  78662. ** that does no originate from the ON or USING clauses of a join.
  78663. ** Return 0 if it involves variables or function calls or terms from
  78664. ** an ON or USING clause.
  78665. */
  78666. SQLITE_PRIVATE int sqlite3ExprIsConstantNotJoin(Expr *p){
  78667. return exprIsConst(p, 2, 0);
  78668. }
  78669. /*
  78670. ** Walk an expression tree. Return non-zero if the expression constant
  78671. ** for any single row of the table with cursor iCur. In other words, the
  78672. ** expression must not refer to any non-deterministic function nor any
  78673. ** table other than iCur.
  78674. */
  78675. SQLITE_PRIVATE int sqlite3ExprIsTableConstant(Expr *p, int iCur){
  78676. return exprIsConst(p, 3, iCur);
  78677. }
  78678. /*
  78679. ** Walk an expression tree. Return non-zero if the expression is constant
  78680. ** or a function call with constant arguments. Return and 0 if there
  78681. ** are any variables.
  78682. **
  78683. ** For the purposes of this function, a double-quoted string (ex: "abc")
  78684. ** is considered a variable but a single-quoted string (ex: 'abc') is
  78685. ** a constant.
  78686. */
  78687. SQLITE_PRIVATE int sqlite3ExprIsConstantOrFunction(Expr *p, u8 isInit){
  78688. assert( isInit==0 || isInit==1 );
  78689. return exprIsConst(p, 4+isInit, 0);
  78690. }
  78691. /*
  78692. ** If the expression p codes a constant integer that is small enough
  78693. ** to fit in a 32-bit integer, return 1 and put the value of the integer
  78694. ** in *pValue. If the expression is not an integer or if it is too big
  78695. ** to fit in a signed 32-bit integer, return 0 and leave *pValue unchanged.
  78696. */
  78697. SQLITE_PRIVATE int sqlite3ExprIsInteger(Expr *p, int *pValue){
  78698. int rc = 0;
  78699. /* If an expression is an integer literal that fits in a signed 32-bit
  78700. ** integer, then the EP_IntValue flag will have already been set */
  78701. assert( p->op!=TK_INTEGER || (p->flags & EP_IntValue)!=0
  78702. || sqlite3GetInt32(p->u.zToken, &rc)==0 );
  78703. if( p->flags & EP_IntValue ){
  78704. *pValue = p->u.iValue;
  78705. return 1;
  78706. }
  78707. switch( p->op ){
  78708. case TK_UPLUS: {
  78709. rc = sqlite3ExprIsInteger(p->pLeft, pValue);
  78710. break;
  78711. }
  78712. case TK_UMINUS: {
  78713. int v;
  78714. if( sqlite3ExprIsInteger(p->pLeft, &v) ){
  78715. assert( v!=(-2147483647-1) );
  78716. *pValue = -v;
  78717. rc = 1;
  78718. }
  78719. break;
  78720. }
  78721. default: break;
  78722. }
  78723. return rc;
  78724. }
  78725. /*
  78726. ** Return FALSE if there is no chance that the expression can be NULL.
  78727. **
  78728. ** If the expression might be NULL or if the expression is too complex
  78729. ** to tell return TRUE.
  78730. **
  78731. ** This routine is used as an optimization, to skip OP_IsNull opcodes
  78732. ** when we know that a value cannot be NULL. Hence, a false positive
  78733. ** (returning TRUE when in fact the expression can never be NULL) might
  78734. ** be a small performance hit but is otherwise harmless. On the other
  78735. ** hand, a false negative (returning FALSE when the result could be NULL)
  78736. ** will likely result in an incorrect answer. So when in doubt, return
  78737. ** TRUE.
  78738. */
  78739. SQLITE_PRIVATE int sqlite3ExprCanBeNull(const Expr *p){
  78740. u8 op;
  78741. while( p->op==TK_UPLUS || p->op==TK_UMINUS ){ p = p->pLeft; }
  78742. op = p->op;
  78743. if( op==TK_REGISTER ) op = p->op2;
  78744. switch( op ){
  78745. case TK_INTEGER:
  78746. case TK_STRING:
  78747. case TK_FLOAT:
  78748. case TK_BLOB:
  78749. return 0;
  78750. case TK_COLUMN:
  78751. assert( p->pTab!=0 );
  78752. return ExprHasProperty(p, EP_CanBeNull) ||
  78753. (p->iColumn>=0 && p->pTab->aCol[p->iColumn].notNull==0);
  78754. default:
  78755. return 1;
  78756. }
  78757. }
  78758. /*
  78759. ** Return TRUE if the given expression is a constant which would be
  78760. ** unchanged by OP_Affinity with the affinity given in the second
  78761. ** argument.
  78762. **
  78763. ** This routine is used to determine if the OP_Affinity operation
  78764. ** can be omitted. When in doubt return FALSE. A false negative
  78765. ** is harmless. A false positive, however, can result in the wrong
  78766. ** answer.
  78767. */
  78768. SQLITE_PRIVATE int sqlite3ExprNeedsNoAffinityChange(const Expr *p, char aff){
  78769. u8 op;
  78770. if( aff==SQLITE_AFF_NONE ) return 1;
  78771. while( p->op==TK_UPLUS || p->op==TK_UMINUS ){ p = p->pLeft; }
  78772. op = p->op;
  78773. if( op==TK_REGISTER ) op = p->op2;
  78774. switch( op ){
  78775. case TK_INTEGER: {
  78776. return aff==SQLITE_AFF_INTEGER || aff==SQLITE_AFF_NUMERIC;
  78777. }
  78778. case TK_FLOAT: {
  78779. return aff==SQLITE_AFF_REAL || aff==SQLITE_AFF_NUMERIC;
  78780. }
  78781. case TK_STRING: {
  78782. return aff==SQLITE_AFF_TEXT;
  78783. }
  78784. case TK_BLOB: {
  78785. return 1;
  78786. }
  78787. case TK_COLUMN: {
  78788. assert( p->iTable>=0 ); /* p cannot be part of a CHECK constraint */
  78789. return p->iColumn<0
  78790. && (aff==SQLITE_AFF_INTEGER || aff==SQLITE_AFF_NUMERIC);
  78791. }
  78792. default: {
  78793. return 0;
  78794. }
  78795. }
  78796. }
  78797. /*
  78798. ** Return TRUE if the given string is a row-id column name.
  78799. */
  78800. SQLITE_PRIVATE int sqlite3IsRowid(const char *z){
  78801. if( sqlite3StrICmp(z, "_ROWID_")==0 ) return 1;
  78802. if( sqlite3StrICmp(z, "ROWID")==0 ) return 1;
  78803. if( sqlite3StrICmp(z, "OID")==0 ) return 1;
  78804. return 0;
  78805. }
  78806. /*
  78807. ** Return true if we are able to the IN operator optimization on a
  78808. ** query of the form
  78809. **
  78810. ** x IN (SELECT ...)
  78811. **
  78812. ** Where the SELECT... clause is as specified by the parameter to this
  78813. ** routine.
  78814. **
  78815. ** The Select object passed in has already been preprocessed and no
  78816. ** errors have been found.
  78817. */
  78818. #ifndef SQLITE_OMIT_SUBQUERY
  78819. static int isCandidateForInOpt(Select *p){
  78820. SrcList *pSrc;
  78821. ExprList *pEList;
  78822. Table *pTab;
  78823. if( p==0 ) return 0; /* right-hand side of IN is SELECT */
  78824. if( p->pPrior ) return 0; /* Not a compound SELECT */
  78825. if( p->selFlags & (SF_Distinct|SF_Aggregate) ){
  78826. testcase( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct );
  78827. testcase( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Aggregate );
  78828. return 0; /* No DISTINCT keyword and no aggregate functions */
  78829. }
  78830. assert( p->pGroupBy==0 ); /* Has no GROUP BY clause */
  78831. if( p->pLimit ) return 0; /* Has no LIMIT clause */
  78832. assert( p->pOffset==0 ); /* No LIMIT means no OFFSET */
  78833. if( p->pWhere ) return 0; /* Has no WHERE clause */
  78834. pSrc = p->pSrc;
  78835. assert( pSrc!=0 );
  78836. if( pSrc->nSrc!=1 ) return 0; /* Single term in FROM clause */
  78837. if( pSrc->a[0].pSelect ) return 0; /* FROM is not a subquery or view */
  78838. pTab = pSrc->a[0].pTab;
  78839. if( NEVER(pTab==0) ) return 0;
  78840. assert( pTab->pSelect==0 ); /* FROM clause is not a view */
  78841. if( IsVirtual(pTab) ) return 0; /* FROM clause not a virtual table */
  78842. pEList = p->pEList;
  78843. if( pEList->nExpr!=1 ) return 0; /* One column in the result set */
  78844. if( pEList->a[0].pExpr->op!=TK_COLUMN ) return 0; /* Result is a column */
  78845. return 1;
  78846. }
  78847. #endif /* SQLITE_OMIT_SUBQUERY */
  78848. /*
  78849. ** Code an OP_Once instruction and allocate space for its flag. Return the
  78850. ** address of the new instruction.
  78851. */
  78852. SQLITE_PRIVATE int sqlite3CodeOnce(Parse *pParse){
  78853. Vdbe *v = sqlite3GetVdbe(pParse); /* Virtual machine being coded */
  78854. return sqlite3VdbeAddOp1(v, OP_Once, pParse->nOnce++);
  78855. }
  78856. /*
  78857. ** Generate code that checks the left-most column of index table iCur to see if
  78858. ** it contains any NULL entries. Cause the register at regHasNull to be set
  78859. ** to a non-NULL value if iCur contains no NULLs. Cause register regHasNull
  78860. ** to be set to NULL if iCur contains one or more NULL values.
  78861. */
  78862. static void sqlite3SetHasNullFlag(Vdbe *v, int iCur, int regHasNull){
  78863. int j1;
  78864. sqlite3VdbeAddOp2(v, OP_Integer, 0, regHasNull);
  78865. j1 = sqlite3VdbeAddOp1(v, OP_Rewind, iCur); VdbeCoverage(v);
  78866. sqlite3VdbeAddOp3(v, OP_Column, iCur, 0, regHasNull);
  78867. sqlite3VdbeChangeP5(v, OPFLAG_TYPEOFARG);
  78868. VdbeComment((v, "first_entry_in(%d)", iCur));
  78869. sqlite3VdbeJumpHere(v, j1);
  78870. }
  78871. #ifndef SQLITE_OMIT_SUBQUERY
  78872. /*
  78873. ** The argument is an IN operator with a list (not a subquery) on the
  78874. ** right-hand side. Return TRUE if that list is constant.
  78875. */
  78876. static int sqlite3InRhsIsConstant(Expr *pIn){
  78877. Expr *pLHS;
  78878. int res;
  78879. assert( !ExprHasProperty(pIn, EP_xIsSelect) );
  78880. pLHS = pIn->pLeft;
  78881. pIn->pLeft = 0;
  78882. res = sqlite3ExprIsConstant(pIn);
  78883. pIn->pLeft = pLHS;
  78884. return res;
  78885. }
  78886. #endif
  78887. /*
  78888. ** This function is used by the implementation of the IN (...) operator.
  78889. ** The pX parameter is the expression on the RHS of the IN operator, which
  78890. ** might be either a list of expressions or a subquery.
  78891. **
  78892. ** The job of this routine is to find or create a b-tree object that can
  78893. ** be used either to test for membership in the RHS set or to iterate through
  78894. ** all members of the RHS set, skipping duplicates.
  78895. **
  78896. ** A cursor is opened on the b-tree object that is the RHS of the IN operator
  78897. ** and pX->iTable is set to the index of that cursor.
  78898. **
  78899. ** The returned value of this function indicates the b-tree type, as follows:
  78900. **
  78901. ** IN_INDEX_ROWID - The cursor was opened on a database table.
  78902. ** IN_INDEX_INDEX_ASC - The cursor was opened on an ascending index.
  78903. ** IN_INDEX_INDEX_DESC - The cursor was opened on a descending index.
  78904. ** IN_INDEX_EPH - The cursor was opened on a specially created and
  78905. ** populated epheremal table.
  78906. ** IN_INDEX_NOOP - No cursor was allocated. The IN operator must be
  78907. ** implemented as a sequence of comparisons.
  78908. **
  78909. ** An existing b-tree might be used if the RHS expression pX is a simple
  78910. ** subquery such as:
  78911. **
  78912. ** SELECT <column> FROM <table>
  78913. **
  78914. ** If the RHS of the IN operator is a list or a more complex subquery, then
  78915. ** an ephemeral table might need to be generated from the RHS and then
  78916. ** pX->iTable made to point to the ephemeral table instead of an
  78917. ** existing table.
  78918. **
  78919. ** The inFlags parameter must contain exactly one of the bits
  78920. ** IN_INDEX_MEMBERSHIP or IN_INDEX_LOOP. If inFlags contains
  78921. ** IN_INDEX_MEMBERSHIP, then the generated table will be used for a
  78922. ** fast membership test. When the IN_INDEX_LOOP bit is set, the
  78923. ** IN index will be used to loop over all values of the RHS of the
  78924. ** IN operator.
  78925. **
  78926. ** When IN_INDEX_LOOP is used (and the b-tree will be used to iterate
  78927. ** through the set members) then the b-tree must not contain duplicates.
  78928. ** An epheremal table must be used unless the selected <column> is guaranteed
  78929. ** to be unique - either because it is an INTEGER PRIMARY KEY or it
  78930. ** has a UNIQUE constraint or UNIQUE index.
  78931. **
  78932. ** When IN_INDEX_MEMBERSHIP is used (and the b-tree will be used
  78933. ** for fast set membership tests) then an epheremal table must
  78934. ** be used unless <column> is an INTEGER PRIMARY KEY or an index can
  78935. ** be found with <column> as its left-most column.
  78936. **
  78937. ** If the IN_INDEX_NOOP_OK and IN_INDEX_MEMBERSHIP are both set and
  78938. ** if the RHS of the IN operator is a list (not a subquery) then this
  78939. ** routine might decide that creating an ephemeral b-tree for membership
  78940. ** testing is too expensive and return IN_INDEX_NOOP. In that case, the
  78941. ** calling routine should implement the IN operator using a sequence
  78942. ** of Eq or Ne comparison operations.
  78943. **
  78944. ** When the b-tree is being used for membership tests, the calling function
  78945. ** might need to know whether or not the RHS side of the IN operator
  78946. ** contains a NULL. If prRhsHasNull is not a NULL pointer and
  78947. ** if there is any chance that the (...) might contain a NULL value at
  78948. ** runtime, then a register is allocated and the register number written
  78949. ** to *prRhsHasNull. If there is no chance that the (...) contains a
  78950. ** NULL value, then *prRhsHasNull is left unchanged.
  78951. **
  78952. ** If a register is allocated and its location stored in *prRhsHasNull, then
  78953. ** the value in that register will be NULL if the b-tree contains one or more
  78954. ** NULL values, and it will be some non-NULL value if the b-tree contains no
  78955. ** NULL values.
  78956. */
  78957. #ifndef SQLITE_OMIT_SUBQUERY
  78958. SQLITE_PRIVATE int sqlite3FindInIndex(Parse *pParse, Expr *pX, u32 inFlags, int *prRhsHasNull){
  78959. Select *p; /* SELECT to the right of IN operator */
  78960. int eType = 0; /* Type of RHS table. IN_INDEX_* */
  78961. int iTab = pParse->nTab++; /* Cursor of the RHS table */
  78962. int mustBeUnique; /* True if RHS must be unique */
  78963. Vdbe *v = sqlite3GetVdbe(pParse); /* Virtual machine being coded */
  78964. assert( pX->op==TK_IN );
  78965. mustBeUnique = (inFlags & IN_INDEX_LOOP)!=0;
  78966. /* Check to see if an existing table or index can be used to
  78967. ** satisfy the query. This is preferable to generating a new
  78968. ** ephemeral table.
  78969. */
  78970. p = (ExprHasProperty(pX, EP_xIsSelect) ? pX->x.pSelect : 0);
  78971. if( pParse->nErr==0 && isCandidateForInOpt(p) ){
  78972. sqlite3 *db = pParse->db; /* Database connection */
  78973. Table *pTab; /* Table <table>. */
  78974. Expr *pExpr; /* Expression <column> */
  78975. i16 iCol; /* Index of column <column> */
  78976. i16 iDb; /* Database idx for pTab */
  78977. assert( p ); /* Because of isCandidateForInOpt(p) */
  78978. assert( p->pEList!=0 ); /* Because of isCandidateForInOpt(p) */
  78979. assert( p->pEList->a[0].pExpr!=0 ); /* Because of isCandidateForInOpt(p) */
  78980. assert( p->pSrc!=0 ); /* Because of isCandidateForInOpt(p) */
  78981. pTab = p->pSrc->a[0].pTab;
  78982. pExpr = p->pEList->a[0].pExpr;
  78983. iCol = (i16)pExpr->iColumn;
  78984. /* Code an OP_Transaction and OP_TableLock for <table>. */
  78985. iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  78986. sqlite3CodeVerifySchema(pParse, iDb);
  78987. sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
  78988. /* This function is only called from two places. In both cases the vdbe
  78989. ** has already been allocated. So assume sqlite3GetVdbe() is always
  78990. ** successful here.
  78991. */
  78992. assert(v);
  78993. if( iCol<0 ){
  78994. int iAddr = sqlite3CodeOnce(pParse);
  78995. VdbeCoverage(v);
  78996. sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead);
  78997. eType = IN_INDEX_ROWID;
  78998. sqlite3VdbeJumpHere(v, iAddr);
  78999. }else{
  79000. Index *pIdx; /* Iterator variable */
  79001. /* The collation sequence used by the comparison. If an index is to
  79002. ** be used in place of a temp-table, it must be ordered according
  79003. ** to this collation sequence. */
  79004. CollSeq *pReq = sqlite3BinaryCompareCollSeq(pParse, pX->pLeft, pExpr);
  79005. /* Check that the affinity that will be used to perform the
  79006. ** comparison is the same as the affinity of the column. If
  79007. ** it is not, it is not possible to use any index.
  79008. */
  79009. int affinity_ok = sqlite3IndexAffinityOk(pX, pTab->aCol[iCol].affinity);
  79010. for(pIdx=pTab->pIndex; pIdx && eType==0 && affinity_ok; pIdx=pIdx->pNext){
  79011. if( (pIdx->aiColumn[0]==iCol)
  79012. && sqlite3FindCollSeq(db, ENC(db), pIdx->azColl[0], 0)==pReq
  79013. && (!mustBeUnique || (pIdx->nKeyCol==1 && IsUniqueIndex(pIdx)))
  79014. ){
  79015. int iAddr = sqlite3CodeOnce(pParse); VdbeCoverage(v);
  79016. sqlite3VdbeAddOp3(v, OP_OpenRead, iTab, pIdx->tnum, iDb);
  79017. sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
  79018. VdbeComment((v, "%s", pIdx->zName));
  79019. assert( IN_INDEX_INDEX_DESC == IN_INDEX_INDEX_ASC+1 );
  79020. eType = IN_INDEX_INDEX_ASC + pIdx->aSortOrder[0];
  79021. if( prRhsHasNull && !pTab->aCol[iCol].notNull ){
  79022. *prRhsHasNull = ++pParse->nMem;
  79023. sqlite3SetHasNullFlag(v, iTab, *prRhsHasNull);
  79024. }
  79025. sqlite3VdbeJumpHere(v, iAddr);
  79026. }
  79027. }
  79028. }
  79029. }
  79030. /* If no preexisting index is available for the IN clause
  79031. ** and IN_INDEX_NOOP is an allowed reply
  79032. ** and the RHS of the IN operator is a list, not a subquery
  79033. ** and the RHS is not contant or has two or fewer terms,
  79034. ** then it is not worth creating an ephemeral table to evaluate
  79035. ** the IN operator so return IN_INDEX_NOOP.
  79036. */
  79037. if( eType==0
  79038. && (inFlags & IN_INDEX_NOOP_OK)
  79039. && !ExprHasProperty(pX, EP_xIsSelect)
  79040. && (!sqlite3InRhsIsConstant(pX) || pX->x.pList->nExpr<=2)
  79041. ){
  79042. eType = IN_INDEX_NOOP;
  79043. }
  79044. if( eType==0 ){
  79045. /* Could not find an existing table or index to use as the RHS b-tree.
  79046. ** We will have to generate an ephemeral table to do the job.
  79047. */
  79048. u32 savedNQueryLoop = pParse->nQueryLoop;
  79049. int rMayHaveNull = 0;
  79050. eType = IN_INDEX_EPH;
  79051. if( inFlags & IN_INDEX_LOOP ){
  79052. pParse->nQueryLoop = 0;
  79053. if( pX->pLeft->iColumn<0 && !ExprHasProperty(pX, EP_xIsSelect) ){
  79054. eType = IN_INDEX_ROWID;
  79055. }
  79056. }else if( prRhsHasNull ){
  79057. *prRhsHasNull = rMayHaveNull = ++pParse->nMem;
  79058. }
  79059. sqlite3CodeSubselect(pParse, pX, rMayHaveNull, eType==IN_INDEX_ROWID);
  79060. pParse->nQueryLoop = savedNQueryLoop;
  79061. }else{
  79062. pX->iTable = iTab;
  79063. }
  79064. return eType;
  79065. }
  79066. #endif
  79067. /*
  79068. ** Generate code for scalar subqueries used as a subquery expression, EXISTS,
  79069. ** or IN operators. Examples:
  79070. **
  79071. ** (SELECT a FROM b) -- subquery
  79072. ** EXISTS (SELECT a FROM b) -- EXISTS subquery
  79073. ** x IN (4,5,11) -- IN operator with list on right-hand side
  79074. ** x IN (SELECT a FROM b) -- IN operator with subquery on the right
  79075. **
  79076. ** The pExpr parameter describes the expression that contains the IN
  79077. ** operator or subquery.
  79078. **
  79079. ** If parameter isRowid is non-zero, then expression pExpr is guaranteed
  79080. ** to be of the form "<rowid> IN (?, ?, ?)", where <rowid> is a reference
  79081. ** to some integer key column of a table B-Tree. In this case, use an
  79082. ** intkey B-Tree to store the set of IN(...) values instead of the usual
  79083. ** (slower) variable length keys B-Tree.
  79084. **
  79085. ** If rMayHaveNull is non-zero, that means that the operation is an IN
  79086. ** (not a SELECT or EXISTS) and that the RHS might contains NULLs.
  79087. ** All this routine does is initialize the register given by rMayHaveNull
  79088. ** to NULL. Calling routines will take care of changing this register
  79089. ** value to non-NULL if the RHS is NULL-free.
  79090. **
  79091. ** For a SELECT or EXISTS operator, return the register that holds the
  79092. ** result. For IN operators or if an error occurs, the return value is 0.
  79093. */
  79094. #ifndef SQLITE_OMIT_SUBQUERY
  79095. SQLITE_PRIVATE int sqlite3CodeSubselect(
  79096. Parse *pParse, /* Parsing context */
  79097. Expr *pExpr, /* The IN, SELECT, or EXISTS operator */
  79098. int rHasNullFlag, /* Register that records whether NULLs exist in RHS */
  79099. int isRowid /* If true, LHS of IN operator is a rowid */
  79100. ){
  79101. int jmpIfDynamic = -1; /* One-time test address */
  79102. int rReg = 0; /* Register storing resulting */
  79103. Vdbe *v = sqlite3GetVdbe(pParse);
  79104. if( NEVER(v==0) ) return 0;
  79105. sqlite3ExprCachePush(pParse);
  79106. /* This code must be run in its entirety every time it is encountered
  79107. ** if any of the following is true:
  79108. **
  79109. ** * The right-hand side is a correlated subquery
  79110. ** * The right-hand side is an expression list containing variables
  79111. ** * We are inside a trigger
  79112. **
  79113. ** If all of the above are false, then we can run this code just once
  79114. ** save the results, and reuse the same result on subsequent invocations.
  79115. */
  79116. if( !ExprHasProperty(pExpr, EP_VarSelect) ){
  79117. jmpIfDynamic = sqlite3CodeOnce(pParse); VdbeCoverage(v);
  79118. }
  79119. #ifndef SQLITE_OMIT_EXPLAIN
  79120. if( pParse->explain==2 ){
  79121. char *zMsg = sqlite3MPrintf(
  79122. pParse->db, "EXECUTE %s%s SUBQUERY %d", jmpIfDynamic>=0?"":"CORRELATED ",
  79123. pExpr->op==TK_IN?"LIST":"SCALAR", pParse->iNextSelectId
  79124. );
  79125. sqlite3VdbeAddOp4(v, OP_Explain, pParse->iSelectId, 0, 0, zMsg, P4_DYNAMIC);
  79126. }
  79127. #endif
  79128. switch( pExpr->op ){
  79129. case TK_IN: {
  79130. char affinity; /* Affinity of the LHS of the IN */
  79131. int addr; /* Address of OP_OpenEphemeral instruction */
  79132. Expr *pLeft = pExpr->pLeft; /* the LHS of the IN operator */
  79133. KeyInfo *pKeyInfo = 0; /* Key information */
  79134. affinity = sqlite3ExprAffinity(pLeft);
  79135. /* Whether this is an 'x IN(SELECT...)' or an 'x IN(<exprlist>)'
  79136. ** expression it is handled the same way. An ephemeral table is
  79137. ** filled with single-field index keys representing the results
  79138. ** from the SELECT or the <exprlist>.
  79139. **
  79140. ** If the 'x' expression is a column value, or the SELECT...
  79141. ** statement returns a column value, then the affinity of that
  79142. ** column is used to build the index keys. If both 'x' and the
  79143. ** SELECT... statement are columns, then numeric affinity is used
  79144. ** if either column has NUMERIC or INTEGER affinity. If neither
  79145. ** 'x' nor the SELECT... statement are columns, then numeric affinity
  79146. ** is used.
  79147. */
  79148. pExpr->iTable = pParse->nTab++;
  79149. addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pExpr->iTable, !isRowid);
  79150. pKeyInfo = isRowid ? 0 : sqlite3KeyInfoAlloc(pParse->db, 1, 1);
  79151. if( ExprHasProperty(pExpr, EP_xIsSelect) ){
  79152. /* Case 1: expr IN (SELECT ...)
  79153. **
  79154. ** Generate code to write the results of the select into the temporary
  79155. ** table allocated and opened above.
  79156. */
  79157. Select *pSelect = pExpr->x.pSelect;
  79158. SelectDest dest;
  79159. ExprList *pEList;
  79160. assert( !isRowid );
  79161. sqlite3SelectDestInit(&dest, SRT_Set, pExpr->iTable);
  79162. dest.affSdst = (u8)affinity;
  79163. assert( (pExpr->iTable&0x0000FFFF)==pExpr->iTable );
  79164. pSelect->iLimit = 0;
  79165. testcase( pSelect->selFlags & SF_Distinct );
  79166. testcase( pKeyInfo==0 ); /* Caused by OOM in sqlite3KeyInfoAlloc() */
  79167. if( sqlite3Select(pParse, pSelect, &dest) ){
  79168. sqlite3KeyInfoUnref(pKeyInfo);
  79169. return 0;
  79170. }
  79171. pEList = pSelect->pEList;
  79172. assert( pKeyInfo!=0 ); /* OOM will cause exit after sqlite3Select() */
  79173. assert( pEList!=0 );
  79174. assert( pEList->nExpr>0 );
  79175. assert( sqlite3KeyInfoIsWriteable(pKeyInfo) );
  79176. pKeyInfo->aColl[0] = sqlite3BinaryCompareCollSeq(pParse, pExpr->pLeft,
  79177. pEList->a[0].pExpr);
  79178. }else if( ALWAYS(pExpr->x.pList!=0) ){
  79179. /* Case 2: expr IN (exprlist)
  79180. **
  79181. ** For each expression, build an index key from the evaluation and
  79182. ** store it in the temporary table. If <expr> is a column, then use
  79183. ** that columns affinity when building index keys. If <expr> is not
  79184. ** a column, use numeric affinity.
  79185. */
  79186. int i;
  79187. ExprList *pList = pExpr->x.pList;
  79188. struct ExprList_item *pItem;
  79189. int r1, r2, r3;
  79190. if( !affinity ){
  79191. affinity = SQLITE_AFF_NONE;
  79192. }
  79193. if( pKeyInfo ){
  79194. assert( sqlite3KeyInfoIsWriteable(pKeyInfo) );
  79195. pKeyInfo->aColl[0] = sqlite3ExprCollSeq(pParse, pExpr->pLeft);
  79196. }
  79197. /* Loop through each expression in <exprlist>. */
  79198. r1 = sqlite3GetTempReg(pParse);
  79199. r2 = sqlite3GetTempReg(pParse);
  79200. if( isRowid ) sqlite3VdbeAddOp2(v, OP_Null, 0, r2);
  79201. for(i=pList->nExpr, pItem=pList->a; i>0; i--, pItem++){
  79202. Expr *pE2 = pItem->pExpr;
  79203. int iValToIns;
  79204. /* If the expression is not constant then we will need to
  79205. ** disable the test that was generated above that makes sure
  79206. ** this code only executes once. Because for a non-constant
  79207. ** expression we need to rerun this code each time.
  79208. */
  79209. if( jmpIfDynamic>=0 && !sqlite3ExprIsConstant(pE2) ){
  79210. sqlite3VdbeChangeToNoop(v, jmpIfDynamic);
  79211. jmpIfDynamic = -1;
  79212. }
  79213. /* Evaluate the expression and insert it into the temp table */
  79214. if( isRowid && sqlite3ExprIsInteger(pE2, &iValToIns) ){
  79215. sqlite3VdbeAddOp3(v, OP_InsertInt, pExpr->iTable, r2, iValToIns);
  79216. }else{
  79217. r3 = sqlite3ExprCodeTarget(pParse, pE2, r1);
  79218. if( isRowid ){
  79219. sqlite3VdbeAddOp2(v, OP_MustBeInt, r3,
  79220. sqlite3VdbeCurrentAddr(v)+2);
  79221. VdbeCoverage(v);
  79222. sqlite3VdbeAddOp3(v, OP_Insert, pExpr->iTable, r2, r3);
  79223. }else{
  79224. sqlite3VdbeAddOp4(v, OP_MakeRecord, r3, 1, r2, &affinity, 1);
  79225. sqlite3ExprCacheAffinityChange(pParse, r3, 1);
  79226. sqlite3VdbeAddOp2(v, OP_IdxInsert, pExpr->iTable, r2);
  79227. }
  79228. }
  79229. }
  79230. sqlite3ReleaseTempReg(pParse, r1);
  79231. sqlite3ReleaseTempReg(pParse, r2);
  79232. }
  79233. if( pKeyInfo ){
  79234. sqlite3VdbeChangeP4(v, addr, (void *)pKeyInfo, P4_KEYINFO);
  79235. }
  79236. break;
  79237. }
  79238. case TK_EXISTS:
  79239. case TK_SELECT:
  79240. default: {
  79241. /* If this has to be a scalar SELECT. Generate code to put the
  79242. ** value of this select in a memory cell and record the number
  79243. ** of the memory cell in iColumn. If this is an EXISTS, write
  79244. ** an integer 0 (not exists) or 1 (exists) into a memory cell
  79245. ** and record that memory cell in iColumn.
  79246. */
  79247. Select *pSel; /* SELECT statement to encode */
  79248. SelectDest dest; /* How to deal with SELECt result */
  79249. testcase( pExpr->op==TK_EXISTS );
  79250. testcase( pExpr->op==TK_SELECT );
  79251. assert( pExpr->op==TK_EXISTS || pExpr->op==TK_SELECT );
  79252. assert( ExprHasProperty(pExpr, EP_xIsSelect) );
  79253. pSel = pExpr->x.pSelect;
  79254. sqlite3SelectDestInit(&dest, 0, ++pParse->nMem);
  79255. if( pExpr->op==TK_SELECT ){
  79256. dest.eDest = SRT_Mem;
  79257. dest.iSdst = dest.iSDParm;
  79258. sqlite3VdbeAddOp2(v, OP_Null, 0, dest.iSDParm);
  79259. VdbeComment((v, "Init subquery result"));
  79260. }else{
  79261. dest.eDest = SRT_Exists;
  79262. sqlite3VdbeAddOp2(v, OP_Integer, 0, dest.iSDParm);
  79263. VdbeComment((v, "Init EXISTS result"));
  79264. }
  79265. sqlite3ExprDelete(pParse->db, pSel->pLimit);
  79266. pSel->pLimit = sqlite3PExpr(pParse, TK_INTEGER, 0, 0,
  79267. &sqlite3IntTokens[1]);
  79268. pSel->iLimit = 0;
  79269. pSel->selFlags &= ~SF_MultiValue;
  79270. if( sqlite3Select(pParse, pSel, &dest) ){
  79271. return 0;
  79272. }
  79273. rReg = dest.iSDParm;
  79274. ExprSetVVAProperty(pExpr, EP_NoReduce);
  79275. break;
  79276. }
  79277. }
  79278. if( rHasNullFlag ){
  79279. sqlite3SetHasNullFlag(v, pExpr->iTable, rHasNullFlag);
  79280. }
  79281. if( jmpIfDynamic>=0 ){
  79282. sqlite3VdbeJumpHere(v, jmpIfDynamic);
  79283. }
  79284. sqlite3ExprCachePop(pParse);
  79285. return rReg;
  79286. }
  79287. #endif /* SQLITE_OMIT_SUBQUERY */
  79288. #ifndef SQLITE_OMIT_SUBQUERY
  79289. /*
  79290. ** Generate code for an IN expression.
  79291. **
  79292. ** x IN (SELECT ...)
  79293. ** x IN (value, value, ...)
  79294. **
  79295. ** The left-hand side (LHS) is a scalar expression. The right-hand side (RHS)
  79296. ** is an array of zero or more values. The expression is true if the LHS is
  79297. ** contained within the RHS. The value of the expression is unknown (NULL)
  79298. ** if the LHS is NULL or if the LHS is not contained within the RHS and the
  79299. ** RHS contains one or more NULL values.
  79300. **
  79301. ** This routine generates code that jumps to destIfFalse if the LHS is not
  79302. ** contained within the RHS. If due to NULLs we cannot determine if the LHS
  79303. ** is contained in the RHS then jump to destIfNull. If the LHS is contained
  79304. ** within the RHS then fall through.
  79305. */
  79306. static void sqlite3ExprCodeIN(
  79307. Parse *pParse, /* Parsing and code generating context */
  79308. Expr *pExpr, /* The IN expression */
  79309. int destIfFalse, /* Jump here if LHS is not contained in the RHS */
  79310. int destIfNull /* Jump here if the results are unknown due to NULLs */
  79311. ){
  79312. int rRhsHasNull = 0; /* Register that is true if RHS contains NULL values */
  79313. char affinity; /* Comparison affinity to use */
  79314. int eType; /* Type of the RHS */
  79315. int r1; /* Temporary use register */
  79316. Vdbe *v; /* Statement under construction */
  79317. /* Compute the RHS. After this step, the table with cursor
  79318. ** pExpr->iTable will contains the values that make up the RHS.
  79319. */
  79320. v = pParse->pVdbe;
  79321. assert( v!=0 ); /* OOM detected prior to this routine */
  79322. VdbeNoopComment((v, "begin IN expr"));
  79323. eType = sqlite3FindInIndex(pParse, pExpr,
  79324. IN_INDEX_MEMBERSHIP | IN_INDEX_NOOP_OK,
  79325. destIfFalse==destIfNull ? 0 : &rRhsHasNull);
  79326. /* Figure out the affinity to use to create a key from the results
  79327. ** of the expression. affinityStr stores a static string suitable for
  79328. ** P4 of OP_MakeRecord.
  79329. */
  79330. affinity = comparisonAffinity(pExpr);
  79331. /* Code the LHS, the <expr> from "<expr> IN (...)".
  79332. */
  79333. sqlite3ExprCachePush(pParse);
  79334. r1 = sqlite3GetTempReg(pParse);
  79335. sqlite3ExprCode(pParse, pExpr->pLeft, r1);
  79336. /* If sqlite3FindInIndex() did not find or create an index that is
  79337. ** suitable for evaluating the IN operator, then evaluate using a
  79338. ** sequence of comparisons.
  79339. */
  79340. if( eType==IN_INDEX_NOOP ){
  79341. ExprList *pList = pExpr->x.pList;
  79342. CollSeq *pColl = sqlite3ExprCollSeq(pParse, pExpr->pLeft);
  79343. int labelOk = sqlite3VdbeMakeLabel(v);
  79344. int r2, regToFree;
  79345. int regCkNull = 0;
  79346. int ii;
  79347. assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
  79348. if( destIfNull!=destIfFalse ){
  79349. regCkNull = sqlite3GetTempReg(pParse);
  79350. sqlite3VdbeAddOp3(v, OP_BitAnd, r1, r1, regCkNull);
  79351. }
  79352. for(ii=0; ii<pList->nExpr; ii++){
  79353. r2 = sqlite3ExprCodeTemp(pParse, pList->a[ii].pExpr, &regToFree);
  79354. if( regCkNull && sqlite3ExprCanBeNull(pList->a[ii].pExpr) ){
  79355. sqlite3VdbeAddOp3(v, OP_BitAnd, regCkNull, r2, regCkNull);
  79356. }
  79357. if( ii<pList->nExpr-1 || destIfNull!=destIfFalse ){
  79358. sqlite3VdbeAddOp4(v, OP_Eq, r1, labelOk, r2,
  79359. (void*)pColl, P4_COLLSEQ);
  79360. VdbeCoverageIf(v, ii<pList->nExpr-1);
  79361. VdbeCoverageIf(v, ii==pList->nExpr-1);
  79362. sqlite3VdbeChangeP5(v, affinity);
  79363. }else{
  79364. assert( destIfNull==destIfFalse );
  79365. sqlite3VdbeAddOp4(v, OP_Ne, r1, destIfFalse, r2,
  79366. (void*)pColl, P4_COLLSEQ); VdbeCoverage(v);
  79367. sqlite3VdbeChangeP5(v, affinity | SQLITE_JUMPIFNULL);
  79368. }
  79369. sqlite3ReleaseTempReg(pParse, regToFree);
  79370. }
  79371. if( regCkNull ){
  79372. sqlite3VdbeAddOp2(v, OP_IsNull, regCkNull, destIfNull); VdbeCoverage(v);
  79373. sqlite3VdbeAddOp2(v, OP_Goto, 0, destIfFalse);
  79374. }
  79375. sqlite3VdbeResolveLabel(v, labelOk);
  79376. sqlite3ReleaseTempReg(pParse, regCkNull);
  79377. }else{
  79378. /* If the LHS is NULL, then the result is either false or NULL depending
  79379. ** on whether the RHS is empty or not, respectively.
  79380. */
  79381. if( sqlite3ExprCanBeNull(pExpr->pLeft) ){
  79382. if( destIfNull==destIfFalse ){
  79383. /* Shortcut for the common case where the false and NULL outcomes are
  79384. ** the same. */
  79385. sqlite3VdbeAddOp2(v, OP_IsNull, r1, destIfNull); VdbeCoverage(v);
  79386. }else{
  79387. int addr1 = sqlite3VdbeAddOp1(v, OP_NotNull, r1); VdbeCoverage(v);
  79388. sqlite3VdbeAddOp2(v, OP_Rewind, pExpr->iTable, destIfFalse);
  79389. VdbeCoverage(v);
  79390. sqlite3VdbeAddOp2(v, OP_Goto, 0, destIfNull);
  79391. sqlite3VdbeJumpHere(v, addr1);
  79392. }
  79393. }
  79394. if( eType==IN_INDEX_ROWID ){
  79395. /* In this case, the RHS is the ROWID of table b-tree
  79396. */
  79397. sqlite3VdbeAddOp2(v, OP_MustBeInt, r1, destIfFalse); VdbeCoverage(v);
  79398. sqlite3VdbeAddOp3(v, OP_NotExists, pExpr->iTable, destIfFalse, r1);
  79399. VdbeCoverage(v);
  79400. }else{
  79401. /* In this case, the RHS is an index b-tree.
  79402. */
  79403. sqlite3VdbeAddOp4(v, OP_Affinity, r1, 1, 0, &affinity, 1);
  79404. /* If the set membership test fails, then the result of the
  79405. ** "x IN (...)" expression must be either 0 or NULL. If the set
  79406. ** contains no NULL values, then the result is 0. If the set
  79407. ** contains one or more NULL values, then the result of the
  79408. ** expression is also NULL.
  79409. */
  79410. assert( destIfFalse!=destIfNull || rRhsHasNull==0 );
  79411. if( rRhsHasNull==0 ){
  79412. /* This branch runs if it is known at compile time that the RHS
  79413. ** cannot contain NULL values. This happens as the result
  79414. ** of a "NOT NULL" constraint in the database schema.
  79415. **
  79416. ** Also run this branch if NULL is equivalent to FALSE
  79417. ** for this particular IN operator.
  79418. */
  79419. sqlite3VdbeAddOp4Int(v, OP_NotFound, pExpr->iTable, destIfFalse, r1, 1);
  79420. VdbeCoverage(v);
  79421. }else{
  79422. /* In this branch, the RHS of the IN might contain a NULL and
  79423. ** the presence of a NULL on the RHS makes a difference in the
  79424. ** outcome.
  79425. */
  79426. int j1;
  79427. /* First check to see if the LHS is contained in the RHS. If so,
  79428. ** then the answer is TRUE the presence of NULLs in the RHS does
  79429. ** not matter. If the LHS is not contained in the RHS, then the
  79430. ** answer is NULL if the RHS contains NULLs and the answer is
  79431. ** FALSE if the RHS is NULL-free.
  79432. */
  79433. j1 = sqlite3VdbeAddOp4Int(v, OP_Found, pExpr->iTable, 0, r1, 1);
  79434. VdbeCoverage(v);
  79435. sqlite3VdbeAddOp2(v, OP_IsNull, rRhsHasNull, destIfNull);
  79436. VdbeCoverage(v);
  79437. sqlite3VdbeAddOp2(v, OP_Goto, 0, destIfFalse);
  79438. sqlite3VdbeJumpHere(v, j1);
  79439. }
  79440. }
  79441. }
  79442. sqlite3ReleaseTempReg(pParse, r1);
  79443. sqlite3ExprCachePop(pParse);
  79444. VdbeComment((v, "end IN expr"));
  79445. }
  79446. #endif /* SQLITE_OMIT_SUBQUERY */
  79447. /*
  79448. ** Duplicate an 8-byte value
  79449. */
  79450. static char *dup8bytes(Vdbe *v, const char *in){
  79451. char *out = sqlite3DbMallocRaw(sqlite3VdbeDb(v), 8);
  79452. if( out ){
  79453. memcpy(out, in, 8);
  79454. }
  79455. return out;
  79456. }
  79457. #ifndef SQLITE_OMIT_FLOATING_POINT
  79458. /*
  79459. ** Generate an instruction that will put the floating point
  79460. ** value described by z[0..n-1] into register iMem.
  79461. **
  79462. ** The z[] string will probably not be zero-terminated. But the
  79463. ** z[n] character is guaranteed to be something that does not look
  79464. ** like the continuation of the number.
  79465. */
  79466. static void codeReal(Vdbe *v, const char *z, int negateFlag, int iMem){
  79467. if( ALWAYS(z!=0) ){
  79468. double value;
  79469. char *zV;
  79470. sqlite3AtoF(z, &value, sqlite3Strlen30(z), SQLITE_UTF8);
  79471. assert( !sqlite3IsNaN(value) ); /* The new AtoF never returns NaN */
  79472. if( negateFlag ) value = -value;
  79473. zV = dup8bytes(v, (char*)&value);
  79474. sqlite3VdbeAddOp4(v, OP_Real, 0, iMem, 0, zV, P4_REAL);
  79475. }
  79476. }
  79477. #endif
  79478. /*
  79479. ** Generate an instruction that will put the integer describe by
  79480. ** text z[0..n-1] into register iMem.
  79481. **
  79482. ** Expr.u.zToken is always UTF8 and zero-terminated.
  79483. */
  79484. static void codeInteger(Parse *pParse, Expr *pExpr, int negFlag, int iMem){
  79485. Vdbe *v = pParse->pVdbe;
  79486. if( pExpr->flags & EP_IntValue ){
  79487. int i = pExpr->u.iValue;
  79488. assert( i>=0 );
  79489. if( negFlag ) i = -i;
  79490. sqlite3VdbeAddOp2(v, OP_Integer, i, iMem);
  79491. }else{
  79492. int c;
  79493. i64 value;
  79494. const char *z = pExpr->u.zToken;
  79495. assert( z!=0 );
  79496. c = sqlite3DecOrHexToI64(z, &value);
  79497. if( c==0 || (c==2 && negFlag) ){
  79498. char *zV;
  79499. if( negFlag ){ value = c==2 ? SMALLEST_INT64 : -value; }
  79500. zV = dup8bytes(v, (char*)&value);
  79501. sqlite3VdbeAddOp4(v, OP_Int64, 0, iMem, 0, zV, P4_INT64);
  79502. }else{
  79503. #ifdef SQLITE_OMIT_FLOATING_POINT
  79504. sqlite3ErrorMsg(pParse, "oversized integer: %s%s", negFlag ? "-" : "", z);
  79505. #else
  79506. #ifndef SQLITE_OMIT_HEX_INTEGER
  79507. if( sqlite3_strnicmp(z,"0x",2)==0 ){
  79508. sqlite3ErrorMsg(pParse, "hex literal too big: %s", z);
  79509. }else
  79510. #endif
  79511. {
  79512. codeReal(v, z, negFlag, iMem);
  79513. }
  79514. #endif
  79515. }
  79516. }
  79517. }
  79518. /*
  79519. ** Clear a cache entry.
  79520. */
  79521. static void cacheEntryClear(Parse *pParse, struct yColCache *p){
  79522. if( p->tempReg ){
  79523. if( pParse->nTempReg<ArraySize(pParse->aTempReg) ){
  79524. pParse->aTempReg[pParse->nTempReg++] = p->iReg;
  79525. }
  79526. p->tempReg = 0;
  79527. }
  79528. }
  79529. /*
  79530. ** Record in the column cache that a particular column from a
  79531. ** particular table is stored in a particular register.
  79532. */
  79533. SQLITE_PRIVATE void sqlite3ExprCacheStore(Parse *pParse, int iTab, int iCol, int iReg){
  79534. int i;
  79535. int minLru;
  79536. int idxLru;
  79537. struct yColCache *p;
  79538. /* Unless an error has occurred, register numbers are always positive. */
  79539. assert( iReg>0 || pParse->nErr || pParse->db->mallocFailed );
  79540. assert( iCol>=-1 && iCol<32768 ); /* Finite column numbers */
  79541. /* The SQLITE_ColumnCache flag disables the column cache. This is used
  79542. ** for testing only - to verify that SQLite always gets the same answer
  79543. ** with and without the column cache.
  79544. */
  79545. if( OptimizationDisabled(pParse->db, SQLITE_ColumnCache) ) return;
  79546. /* First replace any existing entry.
  79547. **
  79548. ** Actually, the way the column cache is currently used, we are guaranteed
  79549. ** that the object will never already be in cache. Verify this guarantee.
  79550. */
  79551. #ifndef NDEBUG
  79552. for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
  79553. assert( p->iReg==0 || p->iTable!=iTab || p->iColumn!=iCol );
  79554. }
  79555. #endif
  79556. /* Find an empty slot and replace it */
  79557. for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
  79558. if( p->iReg==0 ){
  79559. p->iLevel = pParse->iCacheLevel;
  79560. p->iTable = iTab;
  79561. p->iColumn = iCol;
  79562. p->iReg = iReg;
  79563. p->tempReg = 0;
  79564. p->lru = pParse->iCacheCnt++;
  79565. return;
  79566. }
  79567. }
  79568. /* Replace the last recently used */
  79569. minLru = 0x7fffffff;
  79570. idxLru = -1;
  79571. for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
  79572. if( p->lru<minLru ){
  79573. idxLru = i;
  79574. minLru = p->lru;
  79575. }
  79576. }
  79577. if( ALWAYS(idxLru>=0) ){
  79578. p = &pParse->aColCache[idxLru];
  79579. p->iLevel = pParse->iCacheLevel;
  79580. p->iTable = iTab;
  79581. p->iColumn = iCol;
  79582. p->iReg = iReg;
  79583. p->tempReg = 0;
  79584. p->lru = pParse->iCacheCnt++;
  79585. return;
  79586. }
  79587. }
  79588. /*
  79589. ** Indicate that registers between iReg..iReg+nReg-1 are being overwritten.
  79590. ** Purge the range of registers from the column cache.
  79591. */
  79592. SQLITE_PRIVATE void sqlite3ExprCacheRemove(Parse *pParse, int iReg, int nReg){
  79593. int i;
  79594. int iLast = iReg + nReg - 1;
  79595. struct yColCache *p;
  79596. for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
  79597. int r = p->iReg;
  79598. if( r>=iReg && r<=iLast ){
  79599. cacheEntryClear(pParse, p);
  79600. p->iReg = 0;
  79601. }
  79602. }
  79603. }
  79604. /*
  79605. ** Remember the current column cache context. Any new entries added
  79606. ** added to the column cache after this call are removed when the
  79607. ** corresponding pop occurs.
  79608. */
  79609. SQLITE_PRIVATE void sqlite3ExprCachePush(Parse *pParse){
  79610. pParse->iCacheLevel++;
  79611. #ifdef SQLITE_DEBUG
  79612. if( pParse->db->flags & SQLITE_VdbeAddopTrace ){
  79613. printf("PUSH to %d\n", pParse->iCacheLevel);
  79614. }
  79615. #endif
  79616. }
  79617. /*
  79618. ** Remove from the column cache any entries that were added since the
  79619. ** the previous sqlite3ExprCachePush operation. In other words, restore
  79620. ** the cache to the state it was in prior the most recent Push.
  79621. */
  79622. SQLITE_PRIVATE void sqlite3ExprCachePop(Parse *pParse){
  79623. int i;
  79624. struct yColCache *p;
  79625. assert( pParse->iCacheLevel>=1 );
  79626. pParse->iCacheLevel--;
  79627. #ifdef SQLITE_DEBUG
  79628. if( pParse->db->flags & SQLITE_VdbeAddopTrace ){
  79629. printf("POP to %d\n", pParse->iCacheLevel);
  79630. }
  79631. #endif
  79632. for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
  79633. if( p->iReg && p->iLevel>pParse->iCacheLevel ){
  79634. cacheEntryClear(pParse, p);
  79635. p->iReg = 0;
  79636. }
  79637. }
  79638. }
  79639. /*
  79640. ** When a cached column is reused, make sure that its register is
  79641. ** no longer available as a temp register. ticket #3879: that same
  79642. ** register might be in the cache in multiple places, so be sure to
  79643. ** get them all.
  79644. */
  79645. static void sqlite3ExprCachePinRegister(Parse *pParse, int iReg){
  79646. int i;
  79647. struct yColCache *p;
  79648. for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
  79649. if( p->iReg==iReg ){
  79650. p->tempReg = 0;
  79651. }
  79652. }
  79653. }
  79654. /*
  79655. ** Generate code to extract the value of the iCol-th column of a table.
  79656. */
  79657. SQLITE_PRIVATE void sqlite3ExprCodeGetColumnOfTable(
  79658. Vdbe *v, /* The VDBE under construction */
  79659. Table *pTab, /* The table containing the value */
  79660. int iTabCur, /* The table cursor. Or the PK cursor for WITHOUT ROWID */
  79661. int iCol, /* Index of the column to extract */
  79662. int regOut /* Extract the value into this register */
  79663. ){
  79664. if( iCol<0 || iCol==pTab->iPKey ){
  79665. sqlite3VdbeAddOp2(v, OP_Rowid, iTabCur, regOut);
  79666. }else{
  79667. int op = IsVirtual(pTab) ? OP_VColumn : OP_Column;
  79668. int x = iCol;
  79669. if( !HasRowid(pTab) ){
  79670. x = sqlite3ColumnOfIndex(sqlite3PrimaryKeyIndex(pTab), iCol);
  79671. }
  79672. sqlite3VdbeAddOp3(v, op, iTabCur, x, regOut);
  79673. }
  79674. if( iCol>=0 ){
  79675. sqlite3ColumnDefault(v, pTab, iCol, regOut);
  79676. }
  79677. }
  79678. /*
  79679. ** Generate code that will extract the iColumn-th column from
  79680. ** table pTab and store the column value in a register. An effort
  79681. ** is made to store the column value in register iReg, but this is
  79682. ** not guaranteed. The location of the column value is returned.
  79683. **
  79684. ** There must be an open cursor to pTab in iTable when this routine
  79685. ** is called. If iColumn<0 then code is generated that extracts the rowid.
  79686. */
  79687. SQLITE_PRIVATE int sqlite3ExprCodeGetColumn(
  79688. Parse *pParse, /* Parsing and code generating context */
  79689. Table *pTab, /* Description of the table we are reading from */
  79690. int iColumn, /* Index of the table column */
  79691. int iTable, /* The cursor pointing to the table */
  79692. int iReg, /* Store results here */
  79693. u8 p5 /* P5 value for OP_Column */
  79694. ){
  79695. Vdbe *v = pParse->pVdbe;
  79696. int i;
  79697. struct yColCache *p;
  79698. for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
  79699. if( p->iReg>0 && p->iTable==iTable && p->iColumn==iColumn ){
  79700. p->lru = pParse->iCacheCnt++;
  79701. sqlite3ExprCachePinRegister(pParse, p->iReg);
  79702. return p->iReg;
  79703. }
  79704. }
  79705. assert( v!=0 );
  79706. sqlite3ExprCodeGetColumnOfTable(v, pTab, iTable, iColumn, iReg);
  79707. if( p5 ){
  79708. sqlite3VdbeChangeP5(v, p5);
  79709. }else{
  79710. sqlite3ExprCacheStore(pParse, iTable, iColumn, iReg);
  79711. }
  79712. return iReg;
  79713. }
  79714. /*
  79715. ** Clear all column cache entries.
  79716. */
  79717. SQLITE_PRIVATE void sqlite3ExprCacheClear(Parse *pParse){
  79718. int i;
  79719. struct yColCache *p;
  79720. #if SQLITE_DEBUG
  79721. if( pParse->db->flags & SQLITE_VdbeAddopTrace ){
  79722. printf("CLEAR\n");
  79723. }
  79724. #endif
  79725. for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
  79726. if( p->iReg ){
  79727. cacheEntryClear(pParse, p);
  79728. p->iReg = 0;
  79729. }
  79730. }
  79731. }
  79732. /*
  79733. ** Record the fact that an affinity change has occurred on iCount
  79734. ** registers starting with iStart.
  79735. */
  79736. SQLITE_PRIVATE void sqlite3ExprCacheAffinityChange(Parse *pParse, int iStart, int iCount){
  79737. sqlite3ExprCacheRemove(pParse, iStart, iCount);
  79738. }
  79739. /*
  79740. ** Generate code to move content from registers iFrom...iFrom+nReg-1
  79741. ** over to iTo..iTo+nReg-1. Keep the column cache up-to-date.
  79742. */
  79743. SQLITE_PRIVATE void sqlite3ExprCodeMove(Parse *pParse, int iFrom, int iTo, int nReg){
  79744. assert( iFrom>=iTo+nReg || iFrom+nReg<=iTo );
  79745. sqlite3VdbeAddOp3(pParse->pVdbe, OP_Move, iFrom, iTo, nReg);
  79746. sqlite3ExprCacheRemove(pParse, iFrom, nReg);
  79747. }
  79748. #if defined(SQLITE_DEBUG) || defined(SQLITE_COVERAGE_TEST)
  79749. /*
  79750. ** Return true if any register in the range iFrom..iTo (inclusive)
  79751. ** is used as part of the column cache.
  79752. **
  79753. ** This routine is used within assert() and testcase() macros only
  79754. ** and does not appear in a normal build.
  79755. */
  79756. static int usedAsColumnCache(Parse *pParse, int iFrom, int iTo){
  79757. int i;
  79758. struct yColCache *p;
  79759. for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
  79760. int r = p->iReg;
  79761. if( r>=iFrom && r<=iTo ) return 1; /*NO_TEST*/
  79762. }
  79763. return 0;
  79764. }
  79765. #endif /* SQLITE_DEBUG || SQLITE_COVERAGE_TEST */
  79766. /*
  79767. ** Convert an expression node to a TK_REGISTER
  79768. */
  79769. static void exprToRegister(Expr *p, int iReg){
  79770. p->op2 = p->op;
  79771. p->op = TK_REGISTER;
  79772. p->iTable = iReg;
  79773. ExprClearProperty(p, EP_Skip);
  79774. }
  79775. /*
  79776. ** Generate code into the current Vdbe to evaluate the given
  79777. ** expression. Attempt to store the results in register "target".
  79778. ** Return the register where results are stored.
  79779. **
  79780. ** With this routine, there is no guarantee that results will
  79781. ** be stored in target. The result might be stored in some other
  79782. ** register if it is convenient to do so. The calling function
  79783. ** must check the return code and move the results to the desired
  79784. ** register.
  79785. */
  79786. SQLITE_PRIVATE int sqlite3ExprCodeTarget(Parse *pParse, Expr *pExpr, int target){
  79787. Vdbe *v = pParse->pVdbe; /* The VM under construction */
  79788. int op; /* The opcode being coded */
  79789. int inReg = target; /* Results stored in register inReg */
  79790. int regFree1 = 0; /* If non-zero free this temporary register */
  79791. int regFree2 = 0; /* If non-zero free this temporary register */
  79792. int r1, r2, r3, r4; /* Various register numbers */
  79793. sqlite3 *db = pParse->db; /* The database connection */
  79794. Expr tempX; /* Temporary expression node */
  79795. assert( target>0 && target<=pParse->nMem );
  79796. if( v==0 ){
  79797. assert( pParse->db->mallocFailed );
  79798. return 0;
  79799. }
  79800. if( pExpr==0 ){
  79801. op = TK_NULL;
  79802. }else{
  79803. op = pExpr->op;
  79804. }
  79805. switch( op ){
  79806. case TK_AGG_COLUMN: {
  79807. AggInfo *pAggInfo = pExpr->pAggInfo;
  79808. struct AggInfo_col *pCol = &pAggInfo->aCol[pExpr->iAgg];
  79809. if( !pAggInfo->directMode ){
  79810. assert( pCol->iMem>0 );
  79811. inReg = pCol->iMem;
  79812. break;
  79813. }else if( pAggInfo->useSortingIdx ){
  79814. sqlite3VdbeAddOp3(v, OP_Column, pAggInfo->sortingIdxPTab,
  79815. pCol->iSorterColumn, target);
  79816. break;
  79817. }
  79818. /* Otherwise, fall thru into the TK_COLUMN case */
  79819. }
  79820. case TK_COLUMN: {
  79821. int iTab = pExpr->iTable;
  79822. if( iTab<0 ){
  79823. if( pParse->ckBase>0 ){
  79824. /* Generating CHECK constraints or inserting into partial index */
  79825. inReg = pExpr->iColumn + pParse->ckBase;
  79826. break;
  79827. }else{
  79828. /* Deleting from a partial index */
  79829. iTab = pParse->iPartIdxTab;
  79830. }
  79831. }
  79832. inReg = sqlite3ExprCodeGetColumn(pParse, pExpr->pTab,
  79833. pExpr->iColumn, iTab, target,
  79834. pExpr->op2);
  79835. break;
  79836. }
  79837. case TK_INTEGER: {
  79838. codeInteger(pParse, pExpr, 0, target);
  79839. break;
  79840. }
  79841. #ifndef SQLITE_OMIT_FLOATING_POINT
  79842. case TK_FLOAT: {
  79843. assert( !ExprHasProperty(pExpr, EP_IntValue) );
  79844. codeReal(v, pExpr->u.zToken, 0, target);
  79845. break;
  79846. }
  79847. #endif
  79848. case TK_STRING: {
  79849. assert( !ExprHasProperty(pExpr, EP_IntValue) );
  79850. sqlite3VdbeAddOp4(v, OP_String8, 0, target, 0, pExpr->u.zToken, 0);
  79851. break;
  79852. }
  79853. case TK_NULL: {
  79854. sqlite3VdbeAddOp2(v, OP_Null, 0, target);
  79855. break;
  79856. }
  79857. #ifndef SQLITE_OMIT_BLOB_LITERAL
  79858. case TK_BLOB: {
  79859. int n;
  79860. const char *z;
  79861. char *zBlob;
  79862. assert( !ExprHasProperty(pExpr, EP_IntValue) );
  79863. assert( pExpr->u.zToken[0]=='x' || pExpr->u.zToken[0]=='X' );
  79864. assert( pExpr->u.zToken[1]=='\'' );
  79865. z = &pExpr->u.zToken[2];
  79866. n = sqlite3Strlen30(z) - 1;
  79867. assert( z[n]=='\'' );
  79868. zBlob = sqlite3HexToBlob(sqlite3VdbeDb(v), z, n);
  79869. sqlite3VdbeAddOp4(v, OP_Blob, n/2, target, 0, zBlob, P4_DYNAMIC);
  79870. break;
  79871. }
  79872. #endif
  79873. case TK_VARIABLE: {
  79874. assert( !ExprHasProperty(pExpr, EP_IntValue) );
  79875. assert( pExpr->u.zToken!=0 );
  79876. assert( pExpr->u.zToken[0]!=0 );
  79877. sqlite3VdbeAddOp2(v, OP_Variable, pExpr->iColumn, target);
  79878. if( pExpr->u.zToken[1]!=0 ){
  79879. assert( pExpr->u.zToken[0]=='?'
  79880. || strcmp(pExpr->u.zToken, pParse->azVar[pExpr->iColumn-1])==0 );
  79881. sqlite3VdbeChangeP4(v, -1, pParse->azVar[pExpr->iColumn-1], P4_STATIC);
  79882. }
  79883. break;
  79884. }
  79885. case TK_REGISTER: {
  79886. inReg = pExpr->iTable;
  79887. break;
  79888. }
  79889. case TK_AS: {
  79890. inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
  79891. break;
  79892. }
  79893. #ifndef SQLITE_OMIT_CAST
  79894. case TK_CAST: {
  79895. /* Expressions of the form: CAST(pLeft AS token) */
  79896. inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
  79897. if( inReg!=target ){
  79898. sqlite3VdbeAddOp2(v, OP_SCopy, inReg, target);
  79899. inReg = target;
  79900. }
  79901. sqlite3VdbeAddOp2(v, OP_Cast, target,
  79902. sqlite3AffinityType(pExpr->u.zToken, 0));
  79903. testcase( usedAsColumnCache(pParse, inReg, inReg) );
  79904. sqlite3ExprCacheAffinityChange(pParse, inReg, 1);
  79905. break;
  79906. }
  79907. #endif /* SQLITE_OMIT_CAST */
  79908. case TK_LT:
  79909. case TK_LE:
  79910. case TK_GT:
  79911. case TK_GE:
  79912. case TK_NE:
  79913. case TK_EQ: {
  79914. r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
  79915. r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
  79916. codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
  79917. r1, r2, inReg, SQLITE_STOREP2);
  79918. assert(TK_LT==OP_Lt); testcase(op==OP_Lt); VdbeCoverageIf(v,op==OP_Lt);
  79919. assert(TK_LE==OP_Le); testcase(op==OP_Le); VdbeCoverageIf(v,op==OP_Le);
  79920. assert(TK_GT==OP_Gt); testcase(op==OP_Gt); VdbeCoverageIf(v,op==OP_Gt);
  79921. assert(TK_GE==OP_Ge); testcase(op==OP_Ge); VdbeCoverageIf(v,op==OP_Ge);
  79922. assert(TK_EQ==OP_Eq); testcase(op==OP_Eq); VdbeCoverageIf(v,op==OP_Eq);
  79923. assert(TK_NE==OP_Ne); testcase(op==OP_Ne); VdbeCoverageIf(v,op==OP_Ne);
  79924. testcase( regFree1==0 );
  79925. testcase( regFree2==0 );
  79926. break;
  79927. }
  79928. case TK_IS:
  79929. case TK_ISNOT: {
  79930. testcase( op==TK_IS );
  79931. testcase( op==TK_ISNOT );
  79932. r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
  79933. r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
  79934. op = (op==TK_IS) ? TK_EQ : TK_NE;
  79935. codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
  79936. r1, r2, inReg, SQLITE_STOREP2 | SQLITE_NULLEQ);
  79937. VdbeCoverageIf(v, op==TK_EQ);
  79938. VdbeCoverageIf(v, op==TK_NE);
  79939. testcase( regFree1==0 );
  79940. testcase( regFree2==0 );
  79941. break;
  79942. }
  79943. case TK_AND:
  79944. case TK_OR:
  79945. case TK_PLUS:
  79946. case TK_STAR:
  79947. case TK_MINUS:
  79948. case TK_REM:
  79949. case TK_BITAND:
  79950. case TK_BITOR:
  79951. case TK_SLASH:
  79952. case TK_LSHIFT:
  79953. case TK_RSHIFT:
  79954. case TK_CONCAT: {
  79955. assert( TK_AND==OP_And ); testcase( op==TK_AND );
  79956. assert( TK_OR==OP_Or ); testcase( op==TK_OR );
  79957. assert( TK_PLUS==OP_Add ); testcase( op==TK_PLUS );
  79958. assert( TK_MINUS==OP_Subtract ); testcase( op==TK_MINUS );
  79959. assert( TK_REM==OP_Remainder ); testcase( op==TK_REM );
  79960. assert( TK_BITAND==OP_BitAnd ); testcase( op==TK_BITAND );
  79961. assert( TK_BITOR==OP_BitOr ); testcase( op==TK_BITOR );
  79962. assert( TK_SLASH==OP_Divide ); testcase( op==TK_SLASH );
  79963. assert( TK_LSHIFT==OP_ShiftLeft ); testcase( op==TK_LSHIFT );
  79964. assert( TK_RSHIFT==OP_ShiftRight ); testcase( op==TK_RSHIFT );
  79965. assert( TK_CONCAT==OP_Concat ); testcase( op==TK_CONCAT );
  79966. r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
  79967. r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
  79968. sqlite3VdbeAddOp3(v, op, r2, r1, target);
  79969. testcase( regFree1==0 );
  79970. testcase( regFree2==0 );
  79971. break;
  79972. }
  79973. case TK_UMINUS: {
  79974. Expr *pLeft = pExpr->pLeft;
  79975. assert( pLeft );
  79976. if( pLeft->op==TK_INTEGER ){
  79977. codeInteger(pParse, pLeft, 1, target);
  79978. #ifndef SQLITE_OMIT_FLOATING_POINT
  79979. }else if( pLeft->op==TK_FLOAT ){
  79980. assert( !ExprHasProperty(pExpr, EP_IntValue) );
  79981. codeReal(v, pLeft->u.zToken, 1, target);
  79982. #endif
  79983. }else{
  79984. tempX.op = TK_INTEGER;
  79985. tempX.flags = EP_IntValue|EP_TokenOnly;
  79986. tempX.u.iValue = 0;
  79987. r1 = sqlite3ExprCodeTemp(pParse, &tempX, &regFree1);
  79988. r2 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree2);
  79989. sqlite3VdbeAddOp3(v, OP_Subtract, r2, r1, target);
  79990. testcase( regFree2==0 );
  79991. }
  79992. inReg = target;
  79993. break;
  79994. }
  79995. case TK_BITNOT:
  79996. case TK_NOT: {
  79997. assert( TK_BITNOT==OP_BitNot ); testcase( op==TK_BITNOT );
  79998. assert( TK_NOT==OP_Not ); testcase( op==TK_NOT );
  79999. r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
  80000. testcase( regFree1==0 );
  80001. inReg = target;
  80002. sqlite3VdbeAddOp2(v, op, r1, inReg);
  80003. break;
  80004. }
  80005. case TK_ISNULL:
  80006. case TK_NOTNULL: {
  80007. int addr;
  80008. assert( TK_ISNULL==OP_IsNull ); testcase( op==TK_ISNULL );
  80009. assert( TK_NOTNULL==OP_NotNull ); testcase( op==TK_NOTNULL );
  80010. sqlite3VdbeAddOp2(v, OP_Integer, 1, target);
  80011. r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
  80012. testcase( regFree1==0 );
  80013. addr = sqlite3VdbeAddOp1(v, op, r1);
  80014. VdbeCoverageIf(v, op==TK_ISNULL);
  80015. VdbeCoverageIf(v, op==TK_NOTNULL);
  80016. sqlite3VdbeAddOp2(v, OP_Integer, 0, target);
  80017. sqlite3VdbeJumpHere(v, addr);
  80018. break;
  80019. }
  80020. case TK_AGG_FUNCTION: {
  80021. AggInfo *pInfo = pExpr->pAggInfo;
  80022. if( pInfo==0 ){
  80023. assert( !ExprHasProperty(pExpr, EP_IntValue) );
  80024. sqlite3ErrorMsg(pParse, "misuse of aggregate: %s()", pExpr->u.zToken);
  80025. }else{
  80026. inReg = pInfo->aFunc[pExpr->iAgg].iMem;
  80027. }
  80028. break;
  80029. }
  80030. case TK_FUNCTION: {
  80031. ExprList *pFarg; /* List of function arguments */
  80032. int nFarg; /* Number of function arguments */
  80033. FuncDef *pDef; /* The function definition object */
  80034. int nId; /* Length of the function name in bytes */
  80035. const char *zId; /* The function name */
  80036. u32 constMask = 0; /* Mask of function arguments that are constant */
  80037. int i; /* Loop counter */
  80038. u8 enc = ENC(db); /* The text encoding used by this database */
  80039. CollSeq *pColl = 0; /* A collating sequence */
  80040. assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
  80041. if( ExprHasProperty(pExpr, EP_TokenOnly) ){
  80042. pFarg = 0;
  80043. }else{
  80044. pFarg = pExpr->x.pList;
  80045. }
  80046. nFarg = pFarg ? pFarg->nExpr : 0;
  80047. assert( !ExprHasProperty(pExpr, EP_IntValue) );
  80048. zId = pExpr->u.zToken;
  80049. nId = sqlite3Strlen30(zId);
  80050. pDef = sqlite3FindFunction(db, zId, nId, nFarg, enc, 0);
  80051. if( pDef==0 || pDef->xFunc==0 ){
  80052. sqlite3ErrorMsg(pParse, "unknown function: %.*s()", nId, zId);
  80053. break;
  80054. }
  80055. /* Attempt a direct implementation of the built-in COALESCE() and
  80056. ** IFNULL() functions. This avoids unnecessary evaluation of
  80057. ** arguments past the first non-NULL argument.
  80058. */
  80059. if( pDef->funcFlags & SQLITE_FUNC_COALESCE ){
  80060. int endCoalesce = sqlite3VdbeMakeLabel(v);
  80061. assert( nFarg>=2 );
  80062. sqlite3ExprCode(pParse, pFarg->a[0].pExpr, target);
  80063. for(i=1; i<nFarg; i++){
  80064. sqlite3VdbeAddOp2(v, OP_NotNull, target, endCoalesce);
  80065. VdbeCoverage(v);
  80066. sqlite3ExprCacheRemove(pParse, target, 1);
  80067. sqlite3ExprCachePush(pParse);
  80068. sqlite3ExprCode(pParse, pFarg->a[i].pExpr, target);
  80069. sqlite3ExprCachePop(pParse);
  80070. }
  80071. sqlite3VdbeResolveLabel(v, endCoalesce);
  80072. break;
  80073. }
  80074. /* The UNLIKELY() function is a no-op. The result is the value
  80075. ** of the first argument.
  80076. */
  80077. if( pDef->funcFlags & SQLITE_FUNC_UNLIKELY ){
  80078. assert( nFarg>=1 );
  80079. sqlite3ExprCode(pParse, pFarg->a[0].pExpr, target);
  80080. break;
  80081. }
  80082. for(i=0; i<nFarg; i++){
  80083. if( i<32 && sqlite3ExprIsConstant(pFarg->a[i].pExpr) ){
  80084. testcase( i==31 );
  80085. constMask |= MASKBIT32(i);
  80086. }
  80087. if( (pDef->funcFlags & SQLITE_FUNC_NEEDCOLL)!=0 && !pColl ){
  80088. pColl = sqlite3ExprCollSeq(pParse, pFarg->a[i].pExpr);
  80089. }
  80090. }
  80091. if( pFarg ){
  80092. if( constMask ){
  80093. r1 = pParse->nMem+1;
  80094. pParse->nMem += nFarg;
  80095. }else{
  80096. r1 = sqlite3GetTempRange(pParse, nFarg);
  80097. }
  80098. /* For length() and typeof() functions with a column argument,
  80099. ** set the P5 parameter to the OP_Column opcode to OPFLAG_LENGTHARG
  80100. ** or OPFLAG_TYPEOFARG respectively, to avoid unnecessary data
  80101. ** loading.
  80102. */
  80103. if( (pDef->funcFlags & (SQLITE_FUNC_LENGTH|SQLITE_FUNC_TYPEOF))!=0 ){
  80104. u8 exprOp;
  80105. assert( nFarg==1 );
  80106. assert( pFarg->a[0].pExpr!=0 );
  80107. exprOp = pFarg->a[0].pExpr->op;
  80108. if( exprOp==TK_COLUMN || exprOp==TK_AGG_COLUMN ){
  80109. assert( SQLITE_FUNC_LENGTH==OPFLAG_LENGTHARG );
  80110. assert( SQLITE_FUNC_TYPEOF==OPFLAG_TYPEOFARG );
  80111. testcase( pDef->funcFlags & OPFLAG_LENGTHARG );
  80112. pFarg->a[0].pExpr->op2 =
  80113. pDef->funcFlags & (OPFLAG_LENGTHARG|OPFLAG_TYPEOFARG);
  80114. }
  80115. }
  80116. sqlite3ExprCachePush(pParse); /* Ticket 2ea2425d34be */
  80117. sqlite3ExprCodeExprList(pParse, pFarg, r1,
  80118. SQLITE_ECEL_DUP|SQLITE_ECEL_FACTOR);
  80119. sqlite3ExprCachePop(pParse); /* Ticket 2ea2425d34be */
  80120. }else{
  80121. r1 = 0;
  80122. }
  80123. #ifndef SQLITE_OMIT_VIRTUALTABLE
  80124. /* Possibly overload the function if the first argument is
  80125. ** a virtual table column.
  80126. **
  80127. ** For infix functions (LIKE, GLOB, REGEXP, and MATCH) use the
  80128. ** second argument, not the first, as the argument to test to
  80129. ** see if it is a column in a virtual table. This is done because
  80130. ** the left operand of infix functions (the operand we want to
  80131. ** control overloading) ends up as the second argument to the
  80132. ** function. The expression "A glob B" is equivalent to
  80133. ** "glob(B,A). We want to use the A in "A glob B" to test
  80134. ** for function overloading. But we use the B term in "glob(B,A)".
  80135. */
  80136. if( nFarg>=2 && (pExpr->flags & EP_InfixFunc) ){
  80137. pDef = sqlite3VtabOverloadFunction(db, pDef, nFarg, pFarg->a[1].pExpr);
  80138. }else if( nFarg>0 ){
  80139. pDef = sqlite3VtabOverloadFunction(db, pDef, nFarg, pFarg->a[0].pExpr);
  80140. }
  80141. #endif
  80142. if( pDef->funcFlags & SQLITE_FUNC_NEEDCOLL ){
  80143. if( !pColl ) pColl = db->pDfltColl;
  80144. sqlite3VdbeAddOp4(v, OP_CollSeq, 0, 0, 0, (char *)pColl, P4_COLLSEQ);
  80145. }
  80146. sqlite3VdbeAddOp4(v, OP_Function, constMask, r1, target,
  80147. (char*)pDef, P4_FUNCDEF);
  80148. sqlite3VdbeChangeP5(v, (u8)nFarg);
  80149. if( nFarg && constMask==0 ){
  80150. sqlite3ReleaseTempRange(pParse, r1, nFarg);
  80151. }
  80152. break;
  80153. }
  80154. #ifndef SQLITE_OMIT_SUBQUERY
  80155. case TK_EXISTS:
  80156. case TK_SELECT: {
  80157. testcase( op==TK_EXISTS );
  80158. testcase( op==TK_SELECT );
  80159. inReg = sqlite3CodeSubselect(pParse, pExpr, 0, 0);
  80160. break;
  80161. }
  80162. case TK_IN: {
  80163. int destIfFalse = sqlite3VdbeMakeLabel(v);
  80164. int destIfNull = sqlite3VdbeMakeLabel(v);
  80165. sqlite3VdbeAddOp2(v, OP_Null, 0, target);
  80166. sqlite3ExprCodeIN(pParse, pExpr, destIfFalse, destIfNull);
  80167. sqlite3VdbeAddOp2(v, OP_Integer, 1, target);
  80168. sqlite3VdbeResolveLabel(v, destIfFalse);
  80169. sqlite3VdbeAddOp2(v, OP_AddImm, target, 0);
  80170. sqlite3VdbeResolveLabel(v, destIfNull);
  80171. break;
  80172. }
  80173. #endif /* SQLITE_OMIT_SUBQUERY */
  80174. /*
  80175. ** x BETWEEN y AND z
  80176. **
  80177. ** This is equivalent to
  80178. **
  80179. ** x>=y AND x<=z
  80180. **
  80181. ** X is stored in pExpr->pLeft.
  80182. ** Y is stored in pExpr->pList->a[0].pExpr.
  80183. ** Z is stored in pExpr->pList->a[1].pExpr.
  80184. */
  80185. case TK_BETWEEN: {
  80186. Expr *pLeft = pExpr->pLeft;
  80187. struct ExprList_item *pLItem = pExpr->x.pList->a;
  80188. Expr *pRight = pLItem->pExpr;
  80189. r1 = sqlite3ExprCodeTemp(pParse, pLeft, &regFree1);
  80190. r2 = sqlite3ExprCodeTemp(pParse, pRight, &regFree2);
  80191. testcase( regFree1==0 );
  80192. testcase( regFree2==0 );
  80193. r3 = sqlite3GetTempReg(pParse);
  80194. r4 = sqlite3GetTempReg(pParse);
  80195. codeCompare(pParse, pLeft, pRight, OP_Ge,
  80196. r1, r2, r3, SQLITE_STOREP2); VdbeCoverage(v);
  80197. pLItem++;
  80198. pRight = pLItem->pExpr;
  80199. sqlite3ReleaseTempReg(pParse, regFree2);
  80200. r2 = sqlite3ExprCodeTemp(pParse, pRight, &regFree2);
  80201. testcase( regFree2==0 );
  80202. codeCompare(pParse, pLeft, pRight, OP_Le, r1, r2, r4, SQLITE_STOREP2);
  80203. VdbeCoverage(v);
  80204. sqlite3VdbeAddOp3(v, OP_And, r3, r4, target);
  80205. sqlite3ReleaseTempReg(pParse, r3);
  80206. sqlite3ReleaseTempReg(pParse, r4);
  80207. break;
  80208. }
  80209. case TK_COLLATE:
  80210. case TK_UPLUS: {
  80211. inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
  80212. break;
  80213. }
  80214. case TK_TRIGGER: {
  80215. /* If the opcode is TK_TRIGGER, then the expression is a reference
  80216. ** to a column in the new.* or old.* pseudo-tables available to
  80217. ** trigger programs. In this case Expr.iTable is set to 1 for the
  80218. ** new.* pseudo-table, or 0 for the old.* pseudo-table. Expr.iColumn
  80219. ** is set to the column of the pseudo-table to read, or to -1 to
  80220. ** read the rowid field.
  80221. **
  80222. ** The expression is implemented using an OP_Param opcode. The p1
  80223. ** parameter is set to 0 for an old.rowid reference, or to (i+1)
  80224. ** to reference another column of the old.* pseudo-table, where
  80225. ** i is the index of the column. For a new.rowid reference, p1 is
  80226. ** set to (n+1), where n is the number of columns in each pseudo-table.
  80227. ** For a reference to any other column in the new.* pseudo-table, p1
  80228. ** is set to (n+2+i), where n and i are as defined previously. For
  80229. ** example, if the table on which triggers are being fired is
  80230. ** declared as:
  80231. **
  80232. ** CREATE TABLE t1(a, b);
  80233. **
  80234. ** Then p1 is interpreted as follows:
  80235. **
  80236. ** p1==0 -> old.rowid p1==3 -> new.rowid
  80237. ** p1==1 -> old.a p1==4 -> new.a
  80238. ** p1==2 -> old.b p1==5 -> new.b
  80239. */
  80240. Table *pTab = pExpr->pTab;
  80241. int p1 = pExpr->iTable * (pTab->nCol+1) + 1 + pExpr->iColumn;
  80242. assert( pExpr->iTable==0 || pExpr->iTable==1 );
  80243. assert( pExpr->iColumn>=-1 && pExpr->iColumn<pTab->nCol );
  80244. assert( pTab->iPKey<0 || pExpr->iColumn!=pTab->iPKey );
  80245. assert( p1>=0 && p1<(pTab->nCol*2+2) );
  80246. sqlite3VdbeAddOp2(v, OP_Param, p1, target);
  80247. VdbeComment((v, "%s.%s -> $%d",
  80248. (pExpr->iTable ? "new" : "old"),
  80249. (pExpr->iColumn<0 ? "rowid" : pExpr->pTab->aCol[pExpr->iColumn].zName),
  80250. target
  80251. ));
  80252. #ifndef SQLITE_OMIT_FLOATING_POINT
  80253. /* If the column has REAL affinity, it may currently be stored as an
  80254. ** integer. Use OP_RealAffinity to make sure it is really real.
  80255. **
  80256. ** EVIDENCE-OF: R-60985-57662 SQLite will convert the value back to
  80257. ** floating point when extracting it from the record. */
  80258. if( pExpr->iColumn>=0
  80259. && pTab->aCol[pExpr->iColumn].affinity==SQLITE_AFF_REAL
  80260. ){
  80261. sqlite3VdbeAddOp1(v, OP_RealAffinity, target);
  80262. }
  80263. #endif
  80264. break;
  80265. }
  80266. /*
  80267. ** Form A:
  80268. ** CASE x WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END
  80269. **
  80270. ** Form B:
  80271. ** CASE WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END
  80272. **
  80273. ** Form A is can be transformed into the equivalent form B as follows:
  80274. ** CASE WHEN x=e1 THEN r1 WHEN x=e2 THEN r2 ...
  80275. ** WHEN x=eN THEN rN ELSE y END
  80276. **
  80277. ** X (if it exists) is in pExpr->pLeft.
  80278. ** Y is in the last element of pExpr->x.pList if pExpr->x.pList->nExpr is
  80279. ** odd. The Y is also optional. If the number of elements in x.pList
  80280. ** is even, then Y is omitted and the "otherwise" result is NULL.
  80281. ** Ei is in pExpr->pList->a[i*2] and Ri is pExpr->pList->a[i*2+1].
  80282. **
  80283. ** The result of the expression is the Ri for the first matching Ei,
  80284. ** or if there is no matching Ei, the ELSE term Y, or if there is
  80285. ** no ELSE term, NULL.
  80286. */
  80287. default: assert( op==TK_CASE ); {
  80288. int endLabel; /* GOTO label for end of CASE stmt */
  80289. int nextCase; /* GOTO label for next WHEN clause */
  80290. int nExpr; /* 2x number of WHEN terms */
  80291. int i; /* Loop counter */
  80292. ExprList *pEList; /* List of WHEN terms */
  80293. struct ExprList_item *aListelem; /* Array of WHEN terms */
  80294. Expr opCompare; /* The X==Ei expression */
  80295. Expr *pX; /* The X expression */
  80296. Expr *pTest = 0; /* X==Ei (form A) or just Ei (form B) */
  80297. VVA_ONLY( int iCacheLevel = pParse->iCacheLevel; )
  80298. assert( !ExprHasProperty(pExpr, EP_xIsSelect) && pExpr->x.pList );
  80299. assert(pExpr->x.pList->nExpr > 0);
  80300. pEList = pExpr->x.pList;
  80301. aListelem = pEList->a;
  80302. nExpr = pEList->nExpr;
  80303. endLabel = sqlite3VdbeMakeLabel(v);
  80304. if( (pX = pExpr->pLeft)!=0 ){
  80305. tempX = *pX;
  80306. testcase( pX->op==TK_COLUMN );
  80307. exprToRegister(&tempX, sqlite3ExprCodeTemp(pParse, pX, &regFree1));
  80308. testcase( regFree1==0 );
  80309. opCompare.op = TK_EQ;
  80310. opCompare.pLeft = &tempX;
  80311. pTest = &opCompare;
  80312. /* Ticket b351d95f9cd5ef17e9d9dbae18f5ca8611190001:
  80313. ** The value in regFree1 might get SCopy-ed into the file result.
  80314. ** So make sure that the regFree1 register is not reused for other
  80315. ** purposes and possibly overwritten. */
  80316. regFree1 = 0;
  80317. }
  80318. for(i=0; i<nExpr-1; i=i+2){
  80319. sqlite3ExprCachePush(pParse);
  80320. if( pX ){
  80321. assert( pTest!=0 );
  80322. opCompare.pRight = aListelem[i].pExpr;
  80323. }else{
  80324. pTest = aListelem[i].pExpr;
  80325. }
  80326. nextCase = sqlite3VdbeMakeLabel(v);
  80327. testcase( pTest->op==TK_COLUMN );
  80328. sqlite3ExprIfFalse(pParse, pTest, nextCase, SQLITE_JUMPIFNULL);
  80329. testcase( aListelem[i+1].pExpr->op==TK_COLUMN );
  80330. sqlite3ExprCode(pParse, aListelem[i+1].pExpr, target);
  80331. sqlite3VdbeAddOp2(v, OP_Goto, 0, endLabel);
  80332. sqlite3ExprCachePop(pParse);
  80333. sqlite3VdbeResolveLabel(v, nextCase);
  80334. }
  80335. if( (nExpr&1)!=0 ){
  80336. sqlite3ExprCachePush(pParse);
  80337. sqlite3ExprCode(pParse, pEList->a[nExpr-1].pExpr, target);
  80338. sqlite3ExprCachePop(pParse);
  80339. }else{
  80340. sqlite3VdbeAddOp2(v, OP_Null, 0, target);
  80341. }
  80342. assert( db->mallocFailed || pParse->nErr>0
  80343. || pParse->iCacheLevel==iCacheLevel );
  80344. sqlite3VdbeResolveLabel(v, endLabel);
  80345. break;
  80346. }
  80347. #ifndef SQLITE_OMIT_TRIGGER
  80348. case TK_RAISE: {
  80349. assert( pExpr->affinity==OE_Rollback
  80350. || pExpr->affinity==OE_Abort
  80351. || pExpr->affinity==OE_Fail
  80352. || pExpr->affinity==OE_Ignore
  80353. );
  80354. if( !pParse->pTriggerTab ){
  80355. sqlite3ErrorMsg(pParse,
  80356. "RAISE() may only be used within a trigger-program");
  80357. return 0;
  80358. }
  80359. if( pExpr->affinity==OE_Abort ){
  80360. sqlite3MayAbort(pParse);
  80361. }
  80362. assert( !ExprHasProperty(pExpr, EP_IntValue) );
  80363. if( pExpr->affinity==OE_Ignore ){
  80364. sqlite3VdbeAddOp4(
  80365. v, OP_Halt, SQLITE_OK, OE_Ignore, 0, pExpr->u.zToken,0);
  80366. VdbeCoverage(v);
  80367. }else{
  80368. sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_TRIGGER,
  80369. pExpr->affinity, pExpr->u.zToken, 0, 0);
  80370. }
  80371. break;
  80372. }
  80373. #endif
  80374. }
  80375. sqlite3ReleaseTempReg(pParse, regFree1);
  80376. sqlite3ReleaseTempReg(pParse, regFree2);
  80377. return inReg;
  80378. }
  80379. /*
  80380. ** Factor out the code of the given expression to initialization time.
  80381. */
  80382. SQLITE_PRIVATE void sqlite3ExprCodeAtInit(
  80383. Parse *pParse, /* Parsing context */
  80384. Expr *pExpr, /* The expression to code when the VDBE initializes */
  80385. int regDest, /* Store the value in this register */
  80386. u8 reusable /* True if this expression is reusable */
  80387. ){
  80388. ExprList *p;
  80389. assert( ConstFactorOk(pParse) );
  80390. p = pParse->pConstExpr;
  80391. pExpr = sqlite3ExprDup(pParse->db, pExpr, 0);
  80392. p = sqlite3ExprListAppend(pParse, p, pExpr);
  80393. if( p ){
  80394. struct ExprList_item *pItem = &p->a[p->nExpr-1];
  80395. pItem->u.iConstExprReg = regDest;
  80396. pItem->reusable = reusable;
  80397. }
  80398. pParse->pConstExpr = p;
  80399. }
  80400. /*
  80401. ** Generate code to evaluate an expression and store the results
  80402. ** into a register. Return the register number where the results
  80403. ** are stored.
  80404. **
  80405. ** If the register is a temporary register that can be deallocated,
  80406. ** then write its number into *pReg. If the result register is not
  80407. ** a temporary, then set *pReg to zero.
  80408. **
  80409. ** If pExpr is a constant, then this routine might generate this
  80410. ** code to fill the register in the initialization section of the
  80411. ** VDBE program, in order to factor it out of the evaluation loop.
  80412. */
  80413. SQLITE_PRIVATE int sqlite3ExprCodeTemp(Parse *pParse, Expr *pExpr, int *pReg){
  80414. int r2;
  80415. pExpr = sqlite3ExprSkipCollate(pExpr);
  80416. if( ConstFactorOk(pParse)
  80417. && pExpr->op!=TK_REGISTER
  80418. && sqlite3ExprIsConstantNotJoin(pExpr)
  80419. ){
  80420. ExprList *p = pParse->pConstExpr;
  80421. int i;
  80422. *pReg = 0;
  80423. if( p ){
  80424. struct ExprList_item *pItem;
  80425. for(pItem=p->a, i=p->nExpr; i>0; pItem++, i--){
  80426. if( pItem->reusable && sqlite3ExprCompare(pItem->pExpr,pExpr,-1)==0 ){
  80427. return pItem->u.iConstExprReg;
  80428. }
  80429. }
  80430. }
  80431. r2 = ++pParse->nMem;
  80432. sqlite3ExprCodeAtInit(pParse, pExpr, r2, 1);
  80433. }else{
  80434. int r1 = sqlite3GetTempReg(pParse);
  80435. r2 = sqlite3ExprCodeTarget(pParse, pExpr, r1);
  80436. if( r2==r1 ){
  80437. *pReg = r1;
  80438. }else{
  80439. sqlite3ReleaseTempReg(pParse, r1);
  80440. *pReg = 0;
  80441. }
  80442. }
  80443. return r2;
  80444. }
  80445. /*
  80446. ** Generate code that will evaluate expression pExpr and store the
  80447. ** results in register target. The results are guaranteed to appear
  80448. ** in register target.
  80449. */
  80450. SQLITE_PRIVATE void sqlite3ExprCode(Parse *pParse, Expr *pExpr, int target){
  80451. int inReg;
  80452. assert( target>0 && target<=pParse->nMem );
  80453. if( pExpr && pExpr->op==TK_REGISTER ){
  80454. sqlite3VdbeAddOp2(pParse->pVdbe, OP_Copy, pExpr->iTable, target);
  80455. }else{
  80456. inReg = sqlite3ExprCodeTarget(pParse, pExpr, target);
  80457. assert( pParse->pVdbe || pParse->db->mallocFailed );
  80458. if( inReg!=target && pParse->pVdbe ){
  80459. sqlite3VdbeAddOp2(pParse->pVdbe, OP_SCopy, inReg, target);
  80460. }
  80461. }
  80462. }
  80463. /*
  80464. ** Generate code that will evaluate expression pExpr and store the
  80465. ** results in register target. The results are guaranteed to appear
  80466. ** in register target. If the expression is constant, then this routine
  80467. ** might choose to code the expression at initialization time.
  80468. */
  80469. SQLITE_PRIVATE void sqlite3ExprCodeFactorable(Parse *pParse, Expr *pExpr, int target){
  80470. if( pParse->okConstFactor && sqlite3ExprIsConstant(pExpr) ){
  80471. sqlite3ExprCodeAtInit(pParse, pExpr, target, 0);
  80472. }else{
  80473. sqlite3ExprCode(pParse, pExpr, target);
  80474. }
  80475. }
  80476. /*
  80477. ** Generate code that evaluates the given expression and puts the result
  80478. ** in register target.
  80479. **
  80480. ** Also make a copy of the expression results into another "cache" register
  80481. ** and modify the expression so that the next time it is evaluated,
  80482. ** the result is a copy of the cache register.
  80483. **
  80484. ** This routine is used for expressions that are used multiple
  80485. ** times. They are evaluated once and the results of the expression
  80486. ** are reused.
  80487. */
  80488. SQLITE_PRIVATE void sqlite3ExprCodeAndCache(Parse *pParse, Expr *pExpr, int target){
  80489. Vdbe *v = pParse->pVdbe;
  80490. int iMem;
  80491. assert( target>0 );
  80492. assert( pExpr->op!=TK_REGISTER );
  80493. sqlite3ExprCode(pParse, pExpr, target);
  80494. iMem = ++pParse->nMem;
  80495. sqlite3VdbeAddOp2(v, OP_Copy, target, iMem);
  80496. exprToRegister(pExpr, iMem);
  80497. }
  80498. #ifdef SQLITE_DEBUG
  80499. /*
  80500. ** Generate a human-readable explanation of an expression tree.
  80501. */
  80502. SQLITE_PRIVATE void sqlite3TreeViewExpr(TreeView *pView, const Expr *pExpr, u8 moreToFollow){
  80503. const char *zBinOp = 0; /* Binary operator */
  80504. const char *zUniOp = 0; /* Unary operator */
  80505. pView = sqlite3TreeViewPush(pView, moreToFollow);
  80506. if( pExpr==0 ){
  80507. sqlite3TreeViewLine(pView, "nil");
  80508. sqlite3TreeViewPop(pView);
  80509. return;
  80510. }
  80511. switch( pExpr->op ){
  80512. case TK_AGG_COLUMN: {
  80513. sqlite3TreeViewLine(pView, "AGG{%d:%d}",
  80514. pExpr->iTable, pExpr->iColumn);
  80515. break;
  80516. }
  80517. case TK_COLUMN: {
  80518. if( pExpr->iTable<0 ){
  80519. /* This only happens when coding check constraints */
  80520. sqlite3TreeViewLine(pView, "COLUMN(%d)", pExpr->iColumn);
  80521. }else{
  80522. sqlite3TreeViewLine(pView, "{%d:%d}",
  80523. pExpr->iTable, pExpr->iColumn);
  80524. }
  80525. break;
  80526. }
  80527. case TK_INTEGER: {
  80528. if( pExpr->flags & EP_IntValue ){
  80529. sqlite3TreeViewLine(pView, "%d", pExpr->u.iValue);
  80530. }else{
  80531. sqlite3TreeViewLine(pView, "%s", pExpr->u.zToken);
  80532. }
  80533. break;
  80534. }
  80535. #ifndef SQLITE_OMIT_FLOATING_POINT
  80536. case TK_FLOAT: {
  80537. sqlite3TreeViewLine(pView,"%s", pExpr->u.zToken);
  80538. break;
  80539. }
  80540. #endif
  80541. case TK_STRING: {
  80542. sqlite3TreeViewLine(pView,"%Q", pExpr->u.zToken);
  80543. break;
  80544. }
  80545. case TK_NULL: {
  80546. sqlite3TreeViewLine(pView,"NULL");
  80547. break;
  80548. }
  80549. #ifndef SQLITE_OMIT_BLOB_LITERAL
  80550. case TK_BLOB: {
  80551. sqlite3TreeViewLine(pView,"%s", pExpr->u.zToken);
  80552. break;
  80553. }
  80554. #endif
  80555. case TK_VARIABLE: {
  80556. sqlite3TreeViewLine(pView,"VARIABLE(%s,%d)",
  80557. pExpr->u.zToken, pExpr->iColumn);
  80558. break;
  80559. }
  80560. case TK_REGISTER: {
  80561. sqlite3TreeViewLine(pView,"REGISTER(%d)", pExpr->iTable);
  80562. break;
  80563. }
  80564. case TK_AS: {
  80565. sqlite3TreeViewLine(pView,"AS %Q", pExpr->u.zToken);
  80566. sqlite3TreeViewExpr(pView, pExpr->pLeft, 0);
  80567. break;
  80568. }
  80569. case TK_ID: {
  80570. sqlite3TreeViewLine(pView,"ID \"%w\"", pExpr->u.zToken);
  80571. break;
  80572. }
  80573. #ifndef SQLITE_OMIT_CAST
  80574. case TK_CAST: {
  80575. /* Expressions of the form: CAST(pLeft AS token) */
  80576. sqlite3TreeViewLine(pView,"CAST %Q", pExpr->u.zToken);
  80577. sqlite3TreeViewExpr(pView, pExpr->pLeft, 0);
  80578. break;
  80579. }
  80580. #endif /* SQLITE_OMIT_CAST */
  80581. case TK_LT: zBinOp = "LT"; break;
  80582. case TK_LE: zBinOp = "LE"; break;
  80583. case TK_GT: zBinOp = "GT"; break;
  80584. case TK_GE: zBinOp = "GE"; break;
  80585. case TK_NE: zBinOp = "NE"; break;
  80586. case TK_EQ: zBinOp = "EQ"; break;
  80587. case TK_IS: zBinOp = "IS"; break;
  80588. case TK_ISNOT: zBinOp = "ISNOT"; break;
  80589. case TK_AND: zBinOp = "AND"; break;
  80590. case TK_OR: zBinOp = "OR"; break;
  80591. case TK_PLUS: zBinOp = "ADD"; break;
  80592. case TK_STAR: zBinOp = "MUL"; break;
  80593. case TK_MINUS: zBinOp = "SUB"; break;
  80594. case TK_REM: zBinOp = "REM"; break;
  80595. case TK_BITAND: zBinOp = "BITAND"; break;
  80596. case TK_BITOR: zBinOp = "BITOR"; break;
  80597. case TK_SLASH: zBinOp = "DIV"; break;
  80598. case TK_LSHIFT: zBinOp = "LSHIFT"; break;
  80599. case TK_RSHIFT: zBinOp = "RSHIFT"; break;
  80600. case TK_CONCAT: zBinOp = "CONCAT"; break;
  80601. case TK_DOT: zBinOp = "DOT"; break;
  80602. case TK_UMINUS: zUniOp = "UMINUS"; break;
  80603. case TK_UPLUS: zUniOp = "UPLUS"; break;
  80604. case TK_BITNOT: zUniOp = "BITNOT"; break;
  80605. case TK_NOT: zUniOp = "NOT"; break;
  80606. case TK_ISNULL: zUniOp = "ISNULL"; break;
  80607. case TK_NOTNULL: zUniOp = "NOTNULL"; break;
  80608. case TK_COLLATE: {
  80609. sqlite3TreeViewLine(pView, "COLLATE %Q", pExpr->u.zToken);
  80610. sqlite3TreeViewExpr(pView, pExpr->pLeft, 0);
  80611. break;
  80612. }
  80613. case TK_AGG_FUNCTION:
  80614. case TK_FUNCTION: {
  80615. ExprList *pFarg; /* List of function arguments */
  80616. if( ExprHasProperty(pExpr, EP_TokenOnly) ){
  80617. pFarg = 0;
  80618. }else{
  80619. pFarg = pExpr->x.pList;
  80620. }
  80621. if( pExpr->op==TK_AGG_FUNCTION ){
  80622. sqlite3TreeViewLine(pView, "AGG_FUNCTION%d %Q",
  80623. pExpr->op2, pExpr->u.zToken);
  80624. }else{
  80625. sqlite3TreeViewLine(pView, "FUNCTION %Q", pExpr->u.zToken);
  80626. }
  80627. if( pFarg ){
  80628. sqlite3TreeViewExprList(pView, pFarg, 0, 0);
  80629. }
  80630. break;
  80631. }
  80632. #ifndef SQLITE_OMIT_SUBQUERY
  80633. case TK_EXISTS: {
  80634. sqlite3TreeViewLine(pView, "EXISTS-expr");
  80635. sqlite3TreeViewSelect(pView, pExpr->x.pSelect, 0);
  80636. break;
  80637. }
  80638. case TK_SELECT: {
  80639. sqlite3TreeViewLine(pView, "SELECT-expr");
  80640. sqlite3TreeViewSelect(pView, pExpr->x.pSelect, 0);
  80641. break;
  80642. }
  80643. case TK_IN: {
  80644. sqlite3TreeViewLine(pView, "IN");
  80645. sqlite3TreeViewExpr(pView, pExpr->pLeft, 1);
  80646. if( ExprHasProperty(pExpr, EP_xIsSelect) ){
  80647. sqlite3TreeViewSelect(pView, pExpr->x.pSelect, 0);
  80648. }else{
  80649. sqlite3TreeViewExprList(pView, pExpr->x.pList, 0, 0);
  80650. }
  80651. break;
  80652. }
  80653. #endif /* SQLITE_OMIT_SUBQUERY */
  80654. /*
  80655. ** x BETWEEN y AND z
  80656. **
  80657. ** This is equivalent to
  80658. **
  80659. ** x>=y AND x<=z
  80660. **
  80661. ** X is stored in pExpr->pLeft.
  80662. ** Y is stored in pExpr->pList->a[0].pExpr.
  80663. ** Z is stored in pExpr->pList->a[1].pExpr.
  80664. */
  80665. case TK_BETWEEN: {
  80666. Expr *pX = pExpr->pLeft;
  80667. Expr *pY = pExpr->x.pList->a[0].pExpr;
  80668. Expr *pZ = pExpr->x.pList->a[1].pExpr;
  80669. sqlite3TreeViewLine(pView, "BETWEEN");
  80670. sqlite3TreeViewExpr(pView, pX, 1);
  80671. sqlite3TreeViewExpr(pView, pY, 1);
  80672. sqlite3TreeViewExpr(pView, pZ, 0);
  80673. break;
  80674. }
  80675. case TK_TRIGGER: {
  80676. /* If the opcode is TK_TRIGGER, then the expression is a reference
  80677. ** to a column in the new.* or old.* pseudo-tables available to
  80678. ** trigger programs. In this case Expr.iTable is set to 1 for the
  80679. ** new.* pseudo-table, or 0 for the old.* pseudo-table. Expr.iColumn
  80680. ** is set to the column of the pseudo-table to read, or to -1 to
  80681. ** read the rowid field.
  80682. */
  80683. sqlite3TreeViewLine(pView, "%s(%d)",
  80684. pExpr->iTable ? "NEW" : "OLD", pExpr->iColumn);
  80685. break;
  80686. }
  80687. case TK_CASE: {
  80688. sqlite3TreeViewLine(pView, "CASE");
  80689. sqlite3TreeViewExpr(pView, pExpr->pLeft, 1);
  80690. sqlite3TreeViewExprList(pView, pExpr->x.pList, 0, 0);
  80691. break;
  80692. }
  80693. #ifndef SQLITE_OMIT_TRIGGER
  80694. case TK_RAISE: {
  80695. const char *zType = "unk";
  80696. switch( pExpr->affinity ){
  80697. case OE_Rollback: zType = "rollback"; break;
  80698. case OE_Abort: zType = "abort"; break;
  80699. case OE_Fail: zType = "fail"; break;
  80700. case OE_Ignore: zType = "ignore"; break;
  80701. }
  80702. sqlite3TreeViewLine(pView, "RAISE %s(%Q)", zType, pExpr->u.zToken);
  80703. break;
  80704. }
  80705. #endif
  80706. default: {
  80707. sqlite3TreeViewLine(pView, "op=%d", pExpr->op);
  80708. break;
  80709. }
  80710. }
  80711. if( zBinOp ){
  80712. sqlite3TreeViewLine(pView, "%s", zBinOp);
  80713. sqlite3TreeViewExpr(pView, pExpr->pLeft, 1);
  80714. sqlite3TreeViewExpr(pView, pExpr->pRight, 0);
  80715. }else if( zUniOp ){
  80716. sqlite3TreeViewLine(pView, "%s", zUniOp);
  80717. sqlite3TreeViewExpr(pView, pExpr->pLeft, 0);
  80718. }
  80719. sqlite3TreeViewPop(pView);
  80720. }
  80721. #endif /* SQLITE_DEBUG */
  80722. #ifdef SQLITE_DEBUG
  80723. /*
  80724. ** Generate a human-readable explanation of an expression list.
  80725. */
  80726. SQLITE_PRIVATE void sqlite3TreeViewExprList(
  80727. TreeView *pView,
  80728. const ExprList *pList,
  80729. u8 moreToFollow,
  80730. const char *zLabel
  80731. ){
  80732. int i;
  80733. pView = sqlite3TreeViewPush(pView, moreToFollow);
  80734. if( zLabel==0 || zLabel[0]==0 ) zLabel = "LIST";
  80735. if( pList==0 ){
  80736. sqlite3TreeViewLine(pView, "%s (empty)", zLabel);
  80737. }else{
  80738. sqlite3TreeViewLine(pView, "%s", zLabel);
  80739. for(i=0; i<pList->nExpr; i++){
  80740. sqlite3TreeViewExpr(pView, pList->a[i].pExpr, i<pList->nExpr-1);
  80741. #if 0
  80742. if( pList->a[i].zName ){
  80743. sqlite3ExplainPrintf(pOut, " AS %s", pList->a[i].zName);
  80744. }
  80745. if( pList->a[i].bSpanIsTab ){
  80746. sqlite3ExplainPrintf(pOut, " (%s)", pList->a[i].zSpan);
  80747. }
  80748. #endif
  80749. }
  80750. }
  80751. sqlite3TreeViewPop(pView);
  80752. }
  80753. #endif /* SQLITE_DEBUG */
  80754. /*
  80755. ** Generate code that pushes the value of every element of the given
  80756. ** expression list into a sequence of registers beginning at target.
  80757. **
  80758. ** Return the number of elements evaluated.
  80759. **
  80760. ** The SQLITE_ECEL_DUP flag prevents the arguments from being
  80761. ** filled using OP_SCopy. OP_Copy must be used instead.
  80762. **
  80763. ** The SQLITE_ECEL_FACTOR argument allows constant arguments to be
  80764. ** factored out into initialization code.
  80765. */
  80766. SQLITE_PRIVATE int sqlite3ExprCodeExprList(
  80767. Parse *pParse, /* Parsing context */
  80768. ExprList *pList, /* The expression list to be coded */
  80769. int target, /* Where to write results */
  80770. u8 flags /* SQLITE_ECEL_* flags */
  80771. ){
  80772. struct ExprList_item *pItem;
  80773. int i, n;
  80774. u8 copyOp = (flags & SQLITE_ECEL_DUP) ? OP_Copy : OP_SCopy;
  80775. assert( pList!=0 );
  80776. assert( target>0 );
  80777. assert( pParse->pVdbe!=0 ); /* Never gets this far otherwise */
  80778. n = pList->nExpr;
  80779. if( !ConstFactorOk(pParse) ) flags &= ~SQLITE_ECEL_FACTOR;
  80780. for(pItem=pList->a, i=0; i<n; i++, pItem++){
  80781. Expr *pExpr = pItem->pExpr;
  80782. if( (flags & SQLITE_ECEL_FACTOR)!=0 && sqlite3ExprIsConstant(pExpr) ){
  80783. sqlite3ExprCodeAtInit(pParse, pExpr, target+i, 0);
  80784. }else{
  80785. int inReg = sqlite3ExprCodeTarget(pParse, pExpr, target+i);
  80786. if( inReg!=target+i ){
  80787. VdbeOp *pOp;
  80788. Vdbe *v = pParse->pVdbe;
  80789. if( copyOp==OP_Copy
  80790. && (pOp=sqlite3VdbeGetOp(v, -1))->opcode==OP_Copy
  80791. && pOp->p1+pOp->p3+1==inReg
  80792. && pOp->p2+pOp->p3+1==target+i
  80793. ){
  80794. pOp->p3++;
  80795. }else{
  80796. sqlite3VdbeAddOp2(v, copyOp, inReg, target+i);
  80797. }
  80798. }
  80799. }
  80800. }
  80801. return n;
  80802. }
  80803. /*
  80804. ** Generate code for a BETWEEN operator.
  80805. **
  80806. ** x BETWEEN y AND z
  80807. **
  80808. ** The above is equivalent to
  80809. **
  80810. ** x>=y AND x<=z
  80811. **
  80812. ** Code it as such, taking care to do the common subexpression
  80813. ** elimination of x.
  80814. */
  80815. static void exprCodeBetween(
  80816. Parse *pParse, /* Parsing and code generating context */
  80817. Expr *pExpr, /* The BETWEEN expression */
  80818. int dest, /* Jump here if the jump is taken */
  80819. int jumpIfTrue, /* Take the jump if the BETWEEN is true */
  80820. int jumpIfNull /* Take the jump if the BETWEEN is NULL */
  80821. ){
  80822. Expr exprAnd; /* The AND operator in x>=y AND x<=z */
  80823. Expr compLeft; /* The x>=y term */
  80824. Expr compRight; /* The x<=z term */
  80825. Expr exprX; /* The x subexpression */
  80826. int regFree1 = 0; /* Temporary use register */
  80827. assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
  80828. exprX = *pExpr->pLeft;
  80829. exprAnd.op = TK_AND;
  80830. exprAnd.pLeft = &compLeft;
  80831. exprAnd.pRight = &compRight;
  80832. compLeft.op = TK_GE;
  80833. compLeft.pLeft = &exprX;
  80834. compLeft.pRight = pExpr->x.pList->a[0].pExpr;
  80835. compRight.op = TK_LE;
  80836. compRight.pLeft = &exprX;
  80837. compRight.pRight = pExpr->x.pList->a[1].pExpr;
  80838. exprToRegister(&exprX, sqlite3ExprCodeTemp(pParse, &exprX, &regFree1));
  80839. if( jumpIfTrue ){
  80840. sqlite3ExprIfTrue(pParse, &exprAnd, dest, jumpIfNull);
  80841. }else{
  80842. sqlite3ExprIfFalse(pParse, &exprAnd, dest, jumpIfNull);
  80843. }
  80844. sqlite3ReleaseTempReg(pParse, regFree1);
  80845. /* Ensure adequate test coverage */
  80846. testcase( jumpIfTrue==0 && jumpIfNull==0 && regFree1==0 );
  80847. testcase( jumpIfTrue==0 && jumpIfNull==0 && regFree1!=0 );
  80848. testcase( jumpIfTrue==0 && jumpIfNull!=0 && regFree1==0 );
  80849. testcase( jumpIfTrue==0 && jumpIfNull!=0 && regFree1!=0 );
  80850. testcase( jumpIfTrue!=0 && jumpIfNull==0 && regFree1==0 );
  80851. testcase( jumpIfTrue!=0 && jumpIfNull==0 && regFree1!=0 );
  80852. testcase( jumpIfTrue!=0 && jumpIfNull!=0 && regFree1==0 );
  80853. testcase( jumpIfTrue!=0 && jumpIfNull!=0 && regFree1!=0 );
  80854. }
  80855. /*
  80856. ** Generate code for a boolean expression such that a jump is made
  80857. ** to the label "dest" if the expression is true but execution
  80858. ** continues straight thru if the expression is false.
  80859. **
  80860. ** If the expression evaluates to NULL (neither true nor false), then
  80861. ** take the jump if the jumpIfNull flag is SQLITE_JUMPIFNULL.
  80862. **
  80863. ** This code depends on the fact that certain token values (ex: TK_EQ)
  80864. ** are the same as opcode values (ex: OP_Eq) that implement the corresponding
  80865. ** operation. Special comments in vdbe.c and the mkopcodeh.awk script in
  80866. ** the make process cause these values to align. Assert()s in the code
  80867. ** below verify that the numbers are aligned correctly.
  80868. */
  80869. SQLITE_PRIVATE void sqlite3ExprIfTrue(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
  80870. Vdbe *v = pParse->pVdbe;
  80871. int op = 0;
  80872. int regFree1 = 0;
  80873. int regFree2 = 0;
  80874. int r1, r2;
  80875. assert( jumpIfNull==SQLITE_JUMPIFNULL || jumpIfNull==0 );
  80876. if( NEVER(v==0) ) return; /* Existence of VDBE checked by caller */
  80877. if( NEVER(pExpr==0) ) return; /* No way this can happen */
  80878. op = pExpr->op;
  80879. switch( op ){
  80880. case TK_AND: {
  80881. int d2 = sqlite3VdbeMakeLabel(v);
  80882. testcase( jumpIfNull==0 );
  80883. sqlite3ExprIfFalse(pParse, pExpr->pLeft, d2,jumpIfNull^SQLITE_JUMPIFNULL);
  80884. sqlite3ExprCachePush(pParse);
  80885. sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
  80886. sqlite3VdbeResolveLabel(v, d2);
  80887. sqlite3ExprCachePop(pParse);
  80888. break;
  80889. }
  80890. case TK_OR: {
  80891. testcase( jumpIfNull==0 );
  80892. sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
  80893. sqlite3ExprCachePush(pParse);
  80894. sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
  80895. sqlite3ExprCachePop(pParse);
  80896. break;
  80897. }
  80898. case TK_NOT: {
  80899. testcase( jumpIfNull==0 );
  80900. sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
  80901. break;
  80902. }
  80903. case TK_LT:
  80904. case TK_LE:
  80905. case TK_GT:
  80906. case TK_GE:
  80907. case TK_NE:
  80908. case TK_EQ: {
  80909. testcase( jumpIfNull==0 );
  80910. r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
  80911. r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
  80912. codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
  80913. r1, r2, dest, jumpIfNull);
  80914. assert(TK_LT==OP_Lt); testcase(op==OP_Lt); VdbeCoverageIf(v,op==OP_Lt);
  80915. assert(TK_LE==OP_Le); testcase(op==OP_Le); VdbeCoverageIf(v,op==OP_Le);
  80916. assert(TK_GT==OP_Gt); testcase(op==OP_Gt); VdbeCoverageIf(v,op==OP_Gt);
  80917. assert(TK_GE==OP_Ge); testcase(op==OP_Ge); VdbeCoverageIf(v,op==OP_Ge);
  80918. assert(TK_EQ==OP_Eq); testcase(op==OP_Eq); VdbeCoverageIf(v,op==OP_Eq);
  80919. assert(TK_NE==OP_Ne); testcase(op==OP_Ne); VdbeCoverageIf(v,op==OP_Ne);
  80920. testcase( regFree1==0 );
  80921. testcase( regFree2==0 );
  80922. break;
  80923. }
  80924. case TK_IS:
  80925. case TK_ISNOT: {
  80926. testcase( op==TK_IS );
  80927. testcase( op==TK_ISNOT );
  80928. r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
  80929. r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
  80930. op = (op==TK_IS) ? TK_EQ : TK_NE;
  80931. codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
  80932. r1, r2, dest, SQLITE_NULLEQ);
  80933. VdbeCoverageIf(v, op==TK_EQ);
  80934. VdbeCoverageIf(v, op==TK_NE);
  80935. testcase( regFree1==0 );
  80936. testcase( regFree2==0 );
  80937. break;
  80938. }
  80939. case TK_ISNULL:
  80940. case TK_NOTNULL: {
  80941. assert( TK_ISNULL==OP_IsNull ); testcase( op==TK_ISNULL );
  80942. assert( TK_NOTNULL==OP_NotNull ); testcase( op==TK_NOTNULL );
  80943. r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
  80944. sqlite3VdbeAddOp2(v, op, r1, dest);
  80945. VdbeCoverageIf(v, op==TK_ISNULL);
  80946. VdbeCoverageIf(v, op==TK_NOTNULL);
  80947. testcase( regFree1==0 );
  80948. break;
  80949. }
  80950. case TK_BETWEEN: {
  80951. testcase( jumpIfNull==0 );
  80952. exprCodeBetween(pParse, pExpr, dest, 1, jumpIfNull);
  80953. break;
  80954. }
  80955. #ifndef SQLITE_OMIT_SUBQUERY
  80956. case TK_IN: {
  80957. int destIfFalse = sqlite3VdbeMakeLabel(v);
  80958. int destIfNull = jumpIfNull ? dest : destIfFalse;
  80959. sqlite3ExprCodeIN(pParse, pExpr, destIfFalse, destIfNull);
  80960. sqlite3VdbeAddOp2(v, OP_Goto, 0, dest);
  80961. sqlite3VdbeResolveLabel(v, destIfFalse);
  80962. break;
  80963. }
  80964. #endif
  80965. default: {
  80966. if( exprAlwaysTrue(pExpr) ){
  80967. sqlite3VdbeAddOp2(v, OP_Goto, 0, dest);
  80968. }else if( exprAlwaysFalse(pExpr) ){
  80969. /* No-op */
  80970. }else{
  80971. r1 = sqlite3ExprCodeTemp(pParse, pExpr, &regFree1);
  80972. sqlite3VdbeAddOp3(v, OP_If, r1, dest, jumpIfNull!=0);
  80973. VdbeCoverage(v);
  80974. testcase( regFree1==0 );
  80975. testcase( jumpIfNull==0 );
  80976. }
  80977. break;
  80978. }
  80979. }
  80980. sqlite3ReleaseTempReg(pParse, regFree1);
  80981. sqlite3ReleaseTempReg(pParse, regFree2);
  80982. }
  80983. /*
  80984. ** Generate code for a boolean expression such that a jump is made
  80985. ** to the label "dest" if the expression is false but execution
  80986. ** continues straight thru if the expression is true.
  80987. **
  80988. ** If the expression evaluates to NULL (neither true nor false) then
  80989. ** jump if jumpIfNull is SQLITE_JUMPIFNULL or fall through if jumpIfNull
  80990. ** is 0.
  80991. */
  80992. SQLITE_PRIVATE void sqlite3ExprIfFalse(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
  80993. Vdbe *v = pParse->pVdbe;
  80994. int op = 0;
  80995. int regFree1 = 0;
  80996. int regFree2 = 0;
  80997. int r1, r2;
  80998. assert( jumpIfNull==SQLITE_JUMPIFNULL || jumpIfNull==0 );
  80999. if( NEVER(v==0) ) return; /* Existence of VDBE checked by caller */
  81000. if( pExpr==0 ) return;
  81001. /* The value of pExpr->op and op are related as follows:
  81002. **
  81003. ** pExpr->op op
  81004. ** --------- ----------
  81005. ** TK_ISNULL OP_NotNull
  81006. ** TK_NOTNULL OP_IsNull
  81007. ** TK_NE OP_Eq
  81008. ** TK_EQ OP_Ne
  81009. ** TK_GT OP_Le
  81010. ** TK_LE OP_Gt
  81011. ** TK_GE OP_Lt
  81012. ** TK_LT OP_Ge
  81013. **
  81014. ** For other values of pExpr->op, op is undefined and unused.
  81015. ** The value of TK_ and OP_ constants are arranged such that we
  81016. ** can compute the mapping above using the following expression.
  81017. ** Assert()s verify that the computation is correct.
  81018. */
  81019. op = ((pExpr->op+(TK_ISNULL&1))^1)-(TK_ISNULL&1);
  81020. /* Verify correct alignment of TK_ and OP_ constants
  81021. */
  81022. assert( pExpr->op!=TK_ISNULL || op==OP_NotNull );
  81023. assert( pExpr->op!=TK_NOTNULL || op==OP_IsNull );
  81024. assert( pExpr->op!=TK_NE || op==OP_Eq );
  81025. assert( pExpr->op!=TK_EQ || op==OP_Ne );
  81026. assert( pExpr->op!=TK_LT || op==OP_Ge );
  81027. assert( pExpr->op!=TK_LE || op==OP_Gt );
  81028. assert( pExpr->op!=TK_GT || op==OP_Le );
  81029. assert( pExpr->op!=TK_GE || op==OP_Lt );
  81030. switch( pExpr->op ){
  81031. case TK_AND: {
  81032. testcase( jumpIfNull==0 );
  81033. sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
  81034. sqlite3ExprCachePush(pParse);
  81035. sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
  81036. sqlite3ExprCachePop(pParse);
  81037. break;
  81038. }
  81039. case TK_OR: {
  81040. int d2 = sqlite3VdbeMakeLabel(v);
  81041. testcase( jumpIfNull==0 );
  81042. sqlite3ExprIfTrue(pParse, pExpr->pLeft, d2, jumpIfNull^SQLITE_JUMPIFNULL);
  81043. sqlite3ExprCachePush(pParse);
  81044. sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
  81045. sqlite3VdbeResolveLabel(v, d2);
  81046. sqlite3ExprCachePop(pParse);
  81047. break;
  81048. }
  81049. case TK_NOT: {
  81050. testcase( jumpIfNull==0 );
  81051. sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
  81052. break;
  81053. }
  81054. case TK_LT:
  81055. case TK_LE:
  81056. case TK_GT:
  81057. case TK_GE:
  81058. case TK_NE:
  81059. case TK_EQ: {
  81060. testcase( jumpIfNull==0 );
  81061. r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
  81062. r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
  81063. codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
  81064. r1, r2, dest, jumpIfNull);
  81065. assert(TK_LT==OP_Lt); testcase(op==OP_Lt); VdbeCoverageIf(v,op==OP_Lt);
  81066. assert(TK_LE==OP_Le); testcase(op==OP_Le); VdbeCoverageIf(v,op==OP_Le);
  81067. assert(TK_GT==OP_Gt); testcase(op==OP_Gt); VdbeCoverageIf(v,op==OP_Gt);
  81068. assert(TK_GE==OP_Ge); testcase(op==OP_Ge); VdbeCoverageIf(v,op==OP_Ge);
  81069. assert(TK_EQ==OP_Eq); testcase(op==OP_Eq); VdbeCoverageIf(v,op==OP_Eq);
  81070. assert(TK_NE==OP_Ne); testcase(op==OP_Ne); VdbeCoverageIf(v,op==OP_Ne);
  81071. testcase( regFree1==0 );
  81072. testcase( regFree2==0 );
  81073. break;
  81074. }
  81075. case TK_IS:
  81076. case TK_ISNOT: {
  81077. testcase( pExpr->op==TK_IS );
  81078. testcase( pExpr->op==TK_ISNOT );
  81079. r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
  81080. r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
  81081. op = (pExpr->op==TK_IS) ? TK_NE : TK_EQ;
  81082. codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
  81083. r1, r2, dest, SQLITE_NULLEQ);
  81084. VdbeCoverageIf(v, op==TK_EQ);
  81085. VdbeCoverageIf(v, op==TK_NE);
  81086. testcase( regFree1==0 );
  81087. testcase( regFree2==0 );
  81088. break;
  81089. }
  81090. case TK_ISNULL:
  81091. case TK_NOTNULL: {
  81092. r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
  81093. sqlite3VdbeAddOp2(v, op, r1, dest);
  81094. testcase( op==TK_ISNULL ); VdbeCoverageIf(v, op==TK_ISNULL);
  81095. testcase( op==TK_NOTNULL ); VdbeCoverageIf(v, op==TK_NOTNULL);
  81096. testcase( regFree1==0 );
  81097. break;
  81098. }
  81099. case TK_BETWEEN: {
  81100. testcase( jumpIfNull==0 );
  81101. exprCodeBetween(pParse, pExpr, dest, 0, jumpIfNull);
  81102. break;
  81103. }
  81104. #ifndef SQLITE_OMIT_SUBQUERY
  81105. case TK_IN: {
  81106. if( jumpIfNull ){
  81107. sqlite3ExprCodeIN(pParse, pExpr, dest, dest);
  81108. }else{
  81109. int destIfNull = sqlite3VdbeMakeLabel(v);
  81110. sqlite3ExprCodeIN(pParse, pExpr, dest, destIfNull);
  81111. sqlite3VdbeResolveLabel(v, destIfNull);
  81112. }
  81113. break;
  81114. }
  81115. #endif
  81116. default: {
  81117. if( exprAlwaysFalse(pExpr) ){
  81118. sqlite3VdbeAddOp2(v, OP_Goto, 0, dest);
  81119. }else if( exprAlwaysTrue(pExpr) ){
  81120. /* no-op */
  81121. }else{
  81122. r1 = sqlite3ExprCodeTemp(pParse, pExpr, &regFree1);
  81123. sqlite3VdbeAddOp3(v, OP_IfNot, r1, dest, jumpIfNull!=0);
  81124. VdbeCoverage(v);
  81125. testcase( regFree1==0 );
  81126. testcase( jumpIfNull==0 );
  81127. }
  81128. break;
  81129. }
  81130. }
  81131. sqlite3ReleaseTempReg(pParse, regFree1);
  81132. sqlite3ReleaseTempReg(pParse, regFree2);
  81133. }
  81134. /*
  81135. ** Do a deep comparison of two expression trees. Return 0 if the two
  81136. ** expressions are completely identical. Return 1 if they differ only
  81137. ** by a COLLATE operator at the top level. Return 2 if there are differences
  81138. ** other than the top-level COLLATE operator.
  81139. **
  81140. ** If any subelement of pB has Expr.iTable==(-1) then it is allowed
  81141. ** to compare equal to an equivalent element in pA with Expr.iTable==iTab.
  81142. **
  81143. ** The pA side might be using TK_REGISTER. If that is the case and pB is
  81144. ** not using TK_REGISTER but is otherwise equivalent, then still return 0.
  81145. **
  81146. ** Sometimes this routine will return 2 even if the two expressions
  81147. ** really are equivalent. If we cannot prove that the expressions are
  81148. ** identical, we return 2 just to be safe. So if this routine
  81149. ** returns 2, then you do not really know for certain if the two
  81150. ** expressions are the same. But if you get a 0 or 1 return, then you
  81151. ** can be sure the expressions are the same. In the places where
  81152. ** this routine is used, it does not hurt to get an extra 2 - that
  81153. ** just might result in some slightly slower code. But returning
  81154. ** an incorrect 0 or 1 could lead to a malfunction.
  81155. */
  81156. SQLITE_PRIVATE int sqlite3ExprCompare(Expr *pA, Expr *pB, int iTab){
  81157. u32 combinedFlags;
  81158. if( pA==0 || pB==0 ){
  81159. return pB==pA ? 0 : 2;
  81160. }
  81161. combinedFlags = pA->flags | pB->flags;
  81162. if( combinedFlags & EP_IntValue ){
  81163. if( (pA->flags&pB->flags&EP_IntValue)!=0 && pA->u.iValue==pB->u.iValue ){
  81164. return 0;
  81165. }
  81166. return 2;
  81167. }
  81168. if( pA->op!=pB->op ){
  81169. if( pA->op==TK_COLLATE && sqlite3ExprCompare(pA->pLeft, pB, iTab)<2 ){
  81170. return 1;
  81171. }
  81172. if( pB->op==TK_COLLATE && sqlite3ExprCompare(pA, pB->pLeft, iTab)<2 ){
  81173. return 1;
  81174. }
  81175. return 2;
  81176. }
  81177. if( pA->op!=TK_COLUMN && ALWAYS(pA->op!=TK_AGG_COLUMN) && pA->u.zToken ){
  81178. if( strcmp(pA->u.zToken,pB->u.zToken)!=0 ){
  81179. return pA->op==TK_COLLATE ? 1 : 2;
  81180. }
  81181. }
  81182. if( (pA->flags & EP_Distinct)!=(pB->flags & EP_Distinct) ) return 2;
  81183. if( ALWAYS((combinedFlags & EP_TokenOnly)==0) ){
  81184. if( combinedFlags & EP_xIsSelect ) return 2;
  81185. if( sqlite3ExprCompare(pA->pLeft, pB->pLeft, iTab) ) return 2;
  81186. if( sqlite3ExprCompare(pA->pRight, pB->pRight, iTab) ) return 2;
  81187. if( sqlite3ExprListCompare(pA->x.pList, pB->x.pList, iTab) ) return 2;
  81188. if( ALWAYS((combinedFlags & EP_Reduced)==0) && pA->op!=TK_STRING ){
  81189. if( pA->iColumn!=pB->iColumn ) return 2;
  81190. if( pA->iTable!=pB->iTable
  81191. && (pA->iTable!=iTab || NEVER(pB->iTable>=0)) ) return 2;
  81192. }
  81193. }
  81194. return 0;
  81195. }
  81196. /*
  81197. ** Compare two ExprList objects. Return 0 if they are identical and
  81198. ** non-zero if they differ in any way.
  81199. **
  81200. ** If any subelement of pB has Expr.iTable==(-1) then it is allowed
  81201. ** to compare equal to an equivalent element in pA with Expr.iTable==iTab.
  81202. **
  81203. ** This routine might return non-zero for equivalent ExprLists. The
  81204. ** only consequence will be disabled optimizations. But this routine
  81205. ** must never return 0 if the two ExprList objects are different, or
  81206. ** a malfunction will result.
  81207. **
  81208. ** Two NULL pointers are considered to be the same. But a NULL pointer
  81209. ** always differs from a non-NULL pointer.
  81210. */
  81211. SQLITE_PRIVATE int sqlite3ExprListCompare(ExprList *pA, ExprList *pB, int iTab){
  81212. int i;
  81213. if( pA==0 && pB==0 ) return 0;
  81214. if( pA==0 || pB==0 ) return 1;
  81215. if( pA->nExpr!=pB->nExpr ) return 1;
  81216. for(i=0; i<pA->nExpr; i++){
  81217. Expr *pExprA = pA->a[i].pExpr;
  81218. Expr *pExprB = pB->a[i].pExpr;
  81219. if( pA->a[i].sortOrder!=pB->a[i].sortOrder ) return 1;
  81220. if( sqlite3ExprCompare(pExprA, pExprB, iTab) ) return 1;
  81221. }
  81222. return 0;
  81223. }
  81224. /*
  81225. ** Return true if we can prove the pE2 will always be true if pE1 is
  81226. ** true. Return false if we cannot complete the proof or if pE2 might
  81227. ** be false. Examples:
  81228. **
  81229. ** pE1: x==5 pE2: x==5 Result: true
  81230. ** pE1: x>0 pE2: x==5 Result: false
  81231. ** pE1: x=21 pE2: x=21 OR y=43 Result: true
  81232. ** pE1: x!=123 pE2: x IS NOT NULL Result: true
  81233. ** pE1: x!=?1 pE2: x IS NOT NULL Result: true
  81234. ** pE1: x IS NULL pE2: x IS NOT NULL Result: false
  81235. ** pE1: x IS ?2 pE2: x IS NOT NULL Reuslt: false
  81236. **
  81237. ** When comparing TK_COLUMN nodes between pE1 and pE2, if pE2 has
  81238. ** Expr.iTable<0 then assume a table number given by iTab.
  81239. **
  81240. ** When in doubt, return false. Returning true might give a performance
  81241. ** improvement. Returning false might cause a performance reduction, but
  81242. ** it will always give the correct answer and is hence always safe.
  81243. */
  81244. SQLITE_PRIVATE int sqlite3ExprImpliesExpr(Expr *pE1, Expr *pE2, int iTab){
  81245. if( sqlite3ExprCompare(pE1, pE2, iTab)==0 ){
  81246. return 1;
  81247. }
  81248. if( pE2->op==TK_OR
  81249. && (sqlite3ExprImpliesExpr(pE1, pE2->pLeft, iTab)
  81250. || sqlite3ExprImpliesExpr(pE1, pE2->pRight, iTab) )
  81251. ){
  81252. return 1;
  81253. }
  81254. if( pE2->op==TK_NOTNULL
  81255. && sqlite3ExprCompare(pE1->pLeft, pE2->pLeft, iTab)==0
  81256. && (pE1->op!=TK_ISNULL && pE1->op!=TK_IS)
  81257. ){
  81258. return 1;
  81259. }
  81260. return 0;
  81261. }
  81262. /*
  81263. ** An instance of the following structure is used by the tree walker
  81264. ** to count references to table columns in the arguments of an
  81265. ** aggregate function, in order to implement the
  81266. ** sqlite3FunctionThisSrc() routine.
  81267. */
  81268. struct SrcCount {
  81269. SrcList *pSrc; /* One particular FROM clause in a nested query */
  81270. int nThis; /* Number of references to columns in pSrcList */
  81271. int nOther; /* Number of references to columns in other FROM clauses */
  81272. };
  81273. /*
  81274. ** Count the number of references to columns.
  81275. */
  81276. static int exprSrcCount(Walker *pWalker, Expr *pExpr){
  81277. /* The NEVER() on the second term is because sqlite3FunctionUsesThisSrc()
  81278. ** is always called before sqlite3ExprAnalyzeAggregates() and so the
  81279. ** TK_COLUMNs have not yet been converted into TK_AGG_COLUMN. If
  81280. ** sqlite3FunctionUsesThisSrc() is used differently in the future, the
  81281. ** NEVER() will need to be removed. */
  81282. if( pExpr->op==TK_COLUMN || NEVER(pExpr->op==TK_AGG_COLUMN) ){
  81283. int i;
  81284. struct SrcCount *p = pWalker->u.pSrcCount;
  81285. SrcList *pSrc = p->pSrc;
  81286. int nSrc = pSrc ? pSrc->nSrc : 0;
  81287. for(i=0; i<nSrc; i++){
  81288. if( pExpr->iTable==pSrc->a[i].iCursor ) break;
  81289. }
  81290. if( i<nSrc ){
  81291. p->nThis++;
  81292. }else{
  81293. p->nOther++;
  81294. }
  81295. }
  81296. return WRC_Continue;
  81297. }
  81298. /*
  81299. ** Determine if any of the arguments to the pExpr Function reference
  81300. ** pSrcList. Return true if they do. Also return true if the function
  81301. ** has no arguments or has only constant arguments. Return false if pExpr
  81302. ** references columns but not columns of tables found in pSrcList.
  81303. */
  81304. SQLITE_PRIVATE int sqlite3FunctionUsesThisSrc(Expr *pExpr, SrcList *pSrcList){
  81305. Walker w;
  81306. struct SrcCount cnt;
  81307. assert( pExpr->op==TK_AGG_FUNCTION );
  81308. memset(&w, 0, sizeof(w));
  81309. w.xExprCallback = exprSrcCount;
  81310. w.u.pSrcCount = &cnt;
  81311. cnt.pSrc = pSrcList;
  81312. cnt.nThis = 0;
  81313. cnt.nOther = 0;
  81314. sqlite3WalkExprList(&w, pExpr->x.pList);
  81315. return cnt.nThis>0 || cnt.nOther==0;
  81316. }
  81317. /*
  81318. ** Add a new element to the pAggInfo->aCol[] array. Return the index of
  81319. ** the new element. Return a negative number if malloc fails.
  81320. */
  81321. static int addAggInfoColumn(sqlite3 *db, AggInfo *pInfo){
  81322. int i;
  81323. pInfo->aCol = sqlite3ArrayAllocate(
  81324. db,
  81325. pInfo->aCol,
  81326. sizeof(pInfo->aCol[0]),
  81327. &pInfo->nColumn,
  81328. &i
  81329. );
  81330. return i;
  81331. }
  81332. /*
  81333. ** Add a new element to the pAggInfo->aFunc[] array. Return the index of
  81334. ** the new element. Return a negative number if malloc fails.
  81335. */
  81336. static int addAggInfoFunc(sqlite3 *db, AggInfo *pInfo){
  81337. int i;
  81338. pInfo->aFunc = sqlite3ArrayAllocate(
  81339. db,
  81340. pInfo->aFunc,
  81341. sizeof(pInfo->aFunc[0]),
  81342. &pInfo->nFunc,
  81343. &i
  81344. );
  81345. return i;
  81346. }
  81347. /*
  81348. ** This is the xExprCallback for a tree walker. It is used to
  81349. ** implement sqlite3ExprAnalyzeAggregates(). See sqlite3ExprAnalyzeAggregates
  81350. ** for additional information.
  81351. */
  81352. static int analyzeAggregate(Walker *pWalker, Expr *pExpr){
  81353. int i;
  81354. NameContext *pNC = pWalker->u.pNC;
  81355. Parse *pParse = pNC->pParse;
  81356. SrcList *pSrcList = pNC->pSrcList;
  81357. AggInfo *pAggInfo = pNC->pAggInfo;
  81358. switch( pExpr->op ){
  81359. case TK_AGG_COLUMN:
  81360. case TK_COLUMN: {
  81361. testcase( pExpr->op==TK_AGG_COLUMN );
  81362. testcase( pExpr->op==TK_COLUMN );
  81363. /* Check to see if the column is in one of the tables in the FROM
  81364. ** clause of the aggregate query */
  81365. if( ALWAYS(pSrcList!=0) ){
  81366. struct SrcList_item *pItem = pSrcList->a;
  81367. for(i=0; i<pSrcList->nSrc; i++, pItem++){
  81368. struct AggInfo_col *pCol;
  81369. assert( !ExprHasProperty(pExpr, EP_TokenOnly|EP_Reduced) );
  81370. if( pExpr->iTable==pItem->iCursor ){
  81371. /* If we reach this point, it means that pExpr refers to a table
  81372. ** that is in the FROM clause of the aggregate query.
  81373. **
  81374. ** Make an entry for the column in pAggInfo->aCol[] if there
  81375. ** is not an entry there already.
  81376. */
  81377. int k;
  81378. pCol = pAggInfo->aCol;
  81379. for(k=0; k<pAggInfo->nColumn; k++, pCol++){
  81380. if( pCol->iTable==pExpr->iTable &&
  81381. pCol->iColumn==pExpr->iColumn ){
  81382. break;
  81383. }
  81384. }
  81385. if( (k>=pAggInfo->nColumn)
  81386. && (k = addAggInfoColumn(pParse->db, pAggInfo))>=0
  81387. ){
  81388. pCol = &pAggInfo->aCol[k];
  81389. pCol->pTab = pExpr->pTab;
  81390. pCol->iTable = pExpr->iTable;
  81391. pCol->iColumn = pExpr->iColumn;
  81392. pCol->iMem = ++pParse->nMem;
  81393. pCol->iSorterColumn = -1;
  81394. pCol->pExpr = pExpr;
  81395. if( pAggInfo->pGroupBy ){
  81396. int j, n;
  81397. ExprList *pGB = pAggInfo->pGroupBy;
  81398. struct ExprList_item *pTerm = pGB->a;
  81399. n = pGB->nExpr;
  81400. for(j=0; j<n; j++, pTerm++){
  81401. Expr *pE = pTerm->pExpr;
  81402. if( pE->op==TK_COLUMN && pE->iTable==pExpr->iTable &&
  81403. pE->iColumn==pExpr->iColumn ){
  81404. pCol->iSorterColumn = j;
  81405. break;
  81406. }
  81407. }
  81408. }
  81409. if( pCol->iSorterColumn<0 ){
  81410. pCol->iSorterColumn = pAggInfo->nSortingColumn++;
  81411. }
  81412. }
  81413. /* There is now an entry for pExpr in pAggInfo->aCol[] (either
  81414. ** because it was there before or because we just created it).
  81415. ** Convert the pExpr to be a TK_AGG_COLUMN referring to that
  81416. ** pAggInfo->aCol[] entry.
  81417. */
  81418. ExprSetVVAProperty(pExpr, EP_NoReduce);
  81419. pExpr->pAggInfo = pAggInfo;
  81420. pExpr->op = TK_AGG_COLUMN;
  81421. pExpr->iAgg = (i16)k;
  81422. break;
  81423. } /* endif pExpr->iTable==pItem->iCursor */
  81424. } /* end loop over pSrcList */
  81425. }
  81426. return WRC_Prune;
  81427. }
  81428. case TK_AGG_FUNCTION: {
  81429. if( (pNC->ncFlags & NC_InAggFunc)==0
  81430. && pWalker->walkerDepth==pExpr->op2
  81431. ){
  81432. /* Check to see if pExpr is a duplicate of another aggregate
  81433. ** function that is already in the pAggInfo structure
  81434. */
  81435. struct AggInfo_func *pItem = pAggInfo->aFunc;
  81436. for(i=0; i<pAggInfo->nFunc; i++, pItem++){
  81437. if( sqlite3ExprCompare(pItem->pExpr, pExpr, -1)==0 ){
  81438. break;
  81439. }
  81440. }
  81441. if( i>=pAggInfo->nFunc ){
  81442. /* pExpr is original. Make a new entry in pAggInfo->aFunc[]
  81443. */
  81444. u8 enc = ENC(pParse->db);
  81445. i = addAggInfoFunc(pParse->db, pAggInfo);
  81446. if( i>=0 ){
  81447. assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
  81448. pItem = &pAggInfo->aFunc[i];
  81449. pItem->pExpr = pExpr;
  81450. pItem->iMem = ++pParse->nMem;
  81451. assert( !ExprHasProperty(pExpr, EP_IntValue) );
  81452. pItem->pFunc = sqlite3FindFunction(pParse->db,
  81453. pExpr->u.zToken, sqlite3Strlen30(pExpr->u.zToken),
  81454. pExpr->x.pList ? pExpr->x.pList->nExpr : 0, enc, 0);
  81455. if( pExpr->flags & EP_Distinct ){
  81456. pItem->iDistinct = pParse->nTab++;
  81457. }else{
  81458. pItem->iDistinct = -1;
  81459. }
  81460. }
  81461. }
  81462. /* Make pExpr point to the appropriate pAggInfo->aFunc[] entry
  81463. */
  81464. assert( !ExprHasProperty(pExpr, EP_TokenOnly|EP_Reduced) );
  81465. ExprSetVVAProperty(pExpr, EP_NoReduce);
  81466. pExpr->iAgg = (i16)i;
  81467. pExpr->pAggInfo = pAggInfo;
  81468. return WRC_Prune;
  81469. }else{
  81470. return WRC_Continue;
  81471. }
  81472. }
  81473. }
  81474. return WRC_Continue;
  81475. }
  81476. static int analyzeAggregatesInSelect(Walker *pWalker, Select *pSelect){
  81477. UNUSED_PARAMETER(pWalker);
  81478. UNUSED_PARAMETER(pSelect);
  81479. return WRC_Continue;
  81480. }
  81481. /*
  81482. ** Analyze the pExpr expression looking for aggregate functions and
  81483. ** for variables that need to be added to AggInfo object that pNC->pAggInfo
  81484. ** points to. Additional entries are made on the AggInfo object as
  81485. ** necessary.
  81486. **
  81487. ** This routine should only be called after the expression has been
  81488. ** analyzed by sqlite3ResolveExprNames().
  81489. */
  81490. SQLITE_PRIVATE void sqlite3ExprAnalyzeAggregates(NameContext *pNC, Expr *pExpr){
  81491. Walker w;
  81492. memset(&w, 0, sizeof(w));
  81493. w.xExprCallback = analyzeAggregate;
  81494. w.xSelectCallback = analyzeAggregatesInSelect;
  81495. w.u.pNC = pNC;
  81496. assert( pNC->pSrcList!=0 );
  81497. sqlite3WalkExpr(&w, pExpr);
  81498. }
  81499. /*
  81500. ** Call sqlite3ExprAnalyzeAggregates() for every expression in an
  81501. ** expression list. Return the number of errors.
  81502. **
  81503. ** If an error is found, the analysis is cut short.
  81504. */
  81505. SQLITE_PRIVATE void sqlite3ExprAnalyzeAggList(NameContext *pNC, ExprList *pList){
  81506. struct ExprList_item *pItem;
  81507. int i;
  81508. if( pList ){
  81509. for(pItem=pList->a, i=0; i<pList->nExpr; i++, pItem++){
  81510. sqlite3ExprAnalyzeAggregates(pNC, pItem->pExpr);
  81511. }
  81512. }
  81513. }
  81514. /*
  81515. ** Allocate a single new register for use to hold some intermediate result.
  81516. */
  81517. SQLITE_PRIVATE int sqlite3GetTempReg(Parse *pParse){
  81518. if( pParse->nTempReg==0 ){
  81519. return ++pParse->nMem;
  81520. }
  81521. return pParse->aTempReg[--pParse->nTempReg];
  81522. }
  81523. /*
  81524. ** Deallocate a register, making available for reuse for some other
  81525. ** purpose.
  81526. **
  81527. ** If a register is currently being used by the column cache, then
  81528. ** the deallocation is deferred until the column cache line that uses
  81529. ** the register becomes stale.
  81530. */
  81531. SQLITE_PRIVATE void sqlite3ReleaseTempReg(Parse *pParse, int iReg){
  81532. if( iReg && pParse->nTempReg<ArraySize(pParse->aTempReg) ){
  81533. int i;
  81534. struct yColCache *p;
  81535. for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
  81536. if( p->iReg==iReg ){
  81537. p->tempReg = 1;
  81538. return;
  81539. }
  81540. }
  81541. pParse->aTempReg[pParse->nTempReg++] = iReg;
  81542. }
  81543. }
  81544. /*
  81545. ** Allocate or deallocate a block of nReg consecutive registers
  81546. */
  81547. SQLITE_PRIVATE int sqlite3GetTempRange(Parse *pParse, int nReg){
  81548. int i, n;
  81549. i = pParse->iRangeReg;
  81550. n = pParse->nRangeReg;
  81551. if( nReg<=n ){
  81552. assert( !usedAsColumnCache(pParse, i, i+n-1) );
  81553. pParse->iRangeReg += nReg;
  81554. pParse->nRangeReg -= nReg;
  81555. }else{
  81556. i = pParse->nMem+1;
  81557. pParse->nMem += nReg;
  81558. }
  81559. return i;
  81560. }
  81561. SQLITE_PRIVATE void sqlite3ReleaseTempRange(Parse *pParse, int iReg, int nReg){
  81562. sqlite3ExprCacheRemove(pParse, iReg, nReg);
  81563. if( nReg>pParse->nRangeReg ){
  81564. pParse->nRangeReg = nReg;
  81565. pParse->iRangeReg = iReg;
  81566. }
  81567. }
  81568. /*
  81569. ** Mark all temporary registers as being unavailable for reuse.
  81570. */
  81571. SQLITE_PRIVATE void sqlite3ClearTempRegCache(Parse *pParse){
  81572. pParse->nTempReg = 0;
  81573. pParse->nRangeReg = 0;
  81574. }
  81575. /************** End of expr.c ************************************************/
  81576. /************** Begin file alter.c *******************************************/
  81577. /*
  81578. ** 2005 February 15
  81579. **
  81580. ** The author disclaims copyright to this source code. In place of
  81581. ** a legal notice, here is a blessing:
  81582. **
  81583. ** May you do good and not evil.
  81584. ** May you find forgiveness for yourself and forgive others.
  81585. ** May you share freely, never taking more than you give.
  81586. **
  81587. *************************************************************************
  81588. ** This file contains C code routines that used to generate VDBE code
  81589. ** that implements the ALTER TABLE command.
  81590. */
  81591. /*
  81592. ** The code in this file only exists if we are not omitting the
  81593. ** ALTER TABLE logic from the build.
  81594. */
  81595. #ifndef SQLITE_OMIT_ALTERTABLE
  81596. /*
  81597. ** This function is used by SQL generated to implement the
  81598. ** ALTER TABLE command. The first argument is the text of a CREATE TABLE or
  81599. ** CREATE INDEX command. The second is a table name. The table name in
  81600. ** the CREATE TABLE or CREATE INDEX statement is replaced with the third
  81601. ** argument and the result returned. Examples:
  81602. **
  81603. ** sqlite_rename_table('CREATE TABLE abc(a, b, c)', 'def')
  81604. ** -> 'CREATE TABLE def(a, b, c)'
  81605. **
  81606. ** sqlite_rename_table('CREATE INDEX i ON abc(a)', 'def')
  81607. ** -> 'CREATE INDEX i ON def(a, b, c)'
  81608. */
  81609. static void renameTableFunc(
  81610. sqlite3_context *context,
  81611. int NotUsed,
  81612. sqlite3_value **argv
  81613. ){
  81614. unsigned char const *zSql = sqlite3_value_text(argv[0]);
  81615. unsigned char const *zTableName = sqlite3_value_text(argv[1]);
  81616. int token;
  81617. Token tname;
  81618. unsigned char const *zCsr = zSql;
  81619. int len = 0;
  81620. char *zRet;
  81621. sqlite3 *db = sqlite3_context_db_handle(context);
  81622. UNUSED_PARAMETER(NotUsed);
  81623. /* The principle used to locate the table name in the CREATE TABLE
  81624. ** statement is that the table name is the first non-space token that
  81625. ** is immediately followed by a TK_LP or TK_USING token.
  81626. */
  81627. if( zSql ){
  81628. do {
  81629. if( !*zCsr ){
  81630. /* Ran out of input before finding an opening bracket. Return NULL. */
  81631. return;
  81632. }
  81633. /* Store the token that zCsr points to in tname. */
  81634. tname.z = (char*)zCsr;
  81635. tname.n = len;
  81636. /* Advance zCsr to the next token. Store that token type in 'token',
  81637. ** and its length in 'len' (to be used next iteration of this loop).
  81638. */
  81639. do {
  81640. zCsr += len;
  81641. len = sqlite3GetToken(zCsr, &token);
  81642. } while( token==TK_SPACE );
  81643. assert( len>0 );
  81644. } while( token!=TK_LP && token!=TK_USING );
  81645. zRet = sqlite3MPrintf(db, "%.*s\"%w\"%s", (int)(((u8*)tname.z) - zSql),
  81646. zSql, zTableName, tname.z+tname.n);
  81647. sqlite3_result_text(context, zRet, -1, SQLITE_DYNAMIC);
  81648. }
  81649. }
  81650. /*
  81651. ** This C function implements an SQL user function that is used by SQL code
  81652. ** generated by the ALTER TABLE ... RENAME command to modify the definition
  81653. ** of any foreign key constraints that use the table being renamed as the
  81654. ** parent table. It is passed three arguments:
  81655. **
  81656. ** 1) The complete text of the CREATE TABLE statement being modified,
  81657. ** 2) The old name of the table being renamed, and
  81658. ** 3) The new name of the table being renamed.
  81659. **
  81660. ** It returns the new CREATE TABLE statement. For example:
  81661. **
  81662. ** sqlite_rename_parent('CREATE TABLE t1(a REFERENCES t2)', 't2', 't3')
  81663. ** -> 'CREATE TABLE t1(a REFERENCES t3)'
  81664. */
  81665. #ifndef SQLITE_OMIT_FOREIGN_KEY
  81666. static void renameParentFunc(
  81667. sqlite3_context *context,
  81668. int NotUsed,
  81669. sqlite3_value **argv
  81670. ){
  81671. sqlite3 *db = sqlite3_context_db_handle(context);
  81672. char *zOutput = 0;
  81673. char *zResult;
  81674. unsigned char const *zInput = sqlite3_value_text(argv[0]);
  81675. unsigned char const *zOld = sqlite3_value_text(argv[1]);
  81676. unsigned char const *zNew = sqlite3_value_text(argv[2]);
  81677. unsigned const char *z; /* Pointer to token */
  81678. int n; /* Length of token z */
  81679. int token; /* Type of token */
  81680. UNUSED_PARAMETER(NotUsed);
  81681. if( zInput==0 || zOld==0 ) return;
  81682. for(z=zInput; *z; z=z+n){
  81683. n = sqlite3GetToken(z, &token);
  81684. if( token==TK_REFERENCES ){
  81685. char *zParent;
  81686. do {
  81687. z += n;
  81688. n = sqlite3GetToken(z, &token);
  81689. }while( token==TK_SPACE );
  81690. if( token==TK_ILLEGAL ) break;
  81691. zParent = sqlite3DbStrNDup(db, (const char *)z, n);
  81692. if( zParent==0 ) break;
  81693. sqlite3Dequote(zParent);
  81694. if( 0==sqlite3StrICmp((const char *)zOld, zParent) ){
  81695. char *zOut = sqlite3MPrintf(db, "%s%.*s\"%w\"",
  81696. (zOutput?zOutput:""), (int)(z-zInput), zInput, (const char *)zNew
  81697. );
  81698. sqlite3DbFree(db, zOutput);
  81699. zOutput = zOut;
  81700. zInput = &z[n];
  81701. }
  81702. sqlite3DbFree(db, zParent);
  81703. }
  81704. }
  81705. zResult = sqlite3MPrintf(db, "%s%s", (zOutput?zOutput:""), zInput),
  81706. sqlite3_result_text(context, zResult, -1, SQLITE_DYNAMIC);
  81707. sqlite3DbFree(db, zOutput);
  81708. }
  81709. #endif
  81710. #ifndef SQLITE_OMIT_TRIGGER
  81711. /* This function is used by SQL generated to implement the
  81712. ** ALTER TABLE command. The first argument is the text of a CREATE TRIGGER
  81713. ** statement. The second is a table name. The table name in the CREATE
  81714. ** TRIGGER statement is replaced with the third argument and the result
  81715. ** returned. This is analagous to renameTableFunc() above, except for CREATE
  81716. ** TRIGGER, not CREATE INDEX and CREATE TABLE.
  81717. */
  81718. static void renameTriggerFunc(
  81719. sqlite3_context *context,
  81720. int NotUsed,
  81721. sqlite3_value **argv
  81722. ){
  81723. unsigned char const *zSql = sqlite3_value_text(argv[0]);
  81724. unsigned char const *zTableName = sqlite3_value_text(argv[1]);
  81725. int token;
  81726. Token tname;
  81727. int dist = 3;
  81728. unsigned char const *zCsr = zSql;
  81729. int len = 0;
  81730. char *zRet;
  81731. sqlite3 *db = sqlite3_context_db_handle(context);
  81732. UNUSED_PARAMETER(NotUsed);
  81733. /* The principle used to locate the table name in the CREATE TRIGGER
  81734. ** statement is that the table name is the first token that is immediately
  81735. ** preceded by either TK_ON or TK_DOT and immediately followed by one
  81736. ** of TK_WHEN, TK_BEGIN or TK_FOR.
  81737. */
  81738. if( zSql ){
  81739. do {
  81740. if( !*zCsr ){
  81741. /* Ran out of input before finding the table name. Return NULL. */
  81742. return;
  81743. }
  81744. /* Store the token that zCsr points to in tname. */
  81745. tname.z = (char*)zCsr;
  81746. tname.n = len;
  81747. /* Advance zCsr to the next token. Store that token type in 'token',
  81748. ** and its length in 'len' (to be used next iteration of this loop).
  81749. */
  81750. do {
  81751. zCsr += len;
  81752. len = sqlite3GetToken(zCsr, &token);
  81753. }while( token==TK_SPACE );
  81754. assert( len>0 );
  81755. /* Variable 'dist' stores the number of tokens read since the most
  81756. ** recent TK_DOT or TK_ON. This means that when a WHEN, FOR or BEGIN
  81757. ** token is read and 'dist' equals 2, the condition stated above
  81758. ** to be met.
  81759. **
  81760. ** Note that ON cannot be a database, table or column name, so
  81761. ** there is no need to worry about syntax like
  81762. ** "CREATE TRIGGER ... ON ON.ON BEGIN ..." etc.
  81763. */
  81764. dist++;
  81765. if( token==TK_DOT || token==TK_ON ){
  81766. dist = 0;
  81767. }
  81768. } while( dist!=2 || (token!=TK_WHEN && token!=TK_FOR && token!=TK_BEGIN) );
  81769. /* Variable tname now contains the token that is the old table-name
  81770. ** in the CREATE TRIGGER statement.
  81771. */
  81772. zRet = sqlite3MPrintf(db, "%.*s\"%w\"%s", (int)(((u8*)tname.z) - zSql),
  81773. zSql, zTableName, tname.z+tname.n);
  81774. sqlite3_result_text(context, zRet, -1, SQLITE_DYNAMIC);
  81775. }
  81776. }
  81777. #endif /* !SQLITE_OMIT_TRIGGER */
  81778. /*
  81779. ** Register built-in functions used to help implement ALTER TABLE
  81780. */
  81781. SQLITE_PRIVATE void sqlite3AlterFunctions(void){
  81782. static SQLITE_WSD FuncDef aAlterTableFuncs[] = {
  81783. FUNCTION(sqlite_rename_table, 2, 0, 0, renameTableFunc),
  81784. #ifndef SQLITE_OMIT_TRIGGER
  81785. FUNCTION(sqlite_rename_trigger, 2, 0, 0, renameTriggerFunc),
  81786. #endif
  81787. #ifndef SQLITE_OMIT_FOREIGN_KEY
  81788. FUNCTION(sqlite_rename_parent, 3, 0, 0, renameParentFunc),
  81789. #endif
  81790. };
  81791. int i;
  81792. FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
  81793. FuncDef *aFunc = (FuncDef*)&GLOBAL(FuncDef, aAlterTableFuncs);
  81794. for(i=0; i<ArraySize(aAlterTableFuncs); i++){
  81795. sqlite3FuncDefInsert(pHash, &aFunc[i]);
  81796. }
  81797. }
  81798. /*
  81799. ** This function is used to create the text of expressions of the form:
  81800. **
  81801. ** name=<constant1> OR name=<constant2> OR ...
  81802. **
  81803. ** If argument zWhere is NULL, then a pointer string containing the text
  81804. ** "name=<constant>" is returned, where <constant> is the quoted version
  81805. ** of the string passed as argument zConstant. The returned buffer is
  81806. ** allocated using sqlite3DbMalloc(). It is the responsibility of the
  81807. ** caller to ensure that it is eventually freed.
  81808. **
  81809. ** If argument zWhere is not NULL, then the string returned is
  81810. ** "<where> OR name=<constant>", where <where> is the contents of zWhere.
  81811. ** In this case zWhere is passed to sqlite3DbFree() before returning.
  81812. **
  81813. */
  81814. static char *whereOrName(sqlite3 *db, char *zWhere, char *zConstant){
  81815. char *zNew;
  81816. if( !zWhere ){
  81817. zNew = sqlite3MPrintf(db, "name=%Q", zConstant);
  81818. }else{
  81819. zNew = sqlite3MPrintf(db, "%s OR name=%Q", zWhere, zConstant);
  81820. sqlite3DbFree(db, zWhere);
  81821. }
  81822. return zNew;
  81823. }
  81824. #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
  81825. /*
  81826. ** Generate the text of a WHERE expression which can be used to select all
  81827. ** tables that have foreign key constraints that refer to table pTab (i.e.
  81828. ** constraints for which pTab is the parent table) from the sqlite_master
  81829. ** table.
  81830. */
  81831. static char *whereForeignKeys(Parse *pParse, Table *pTab){
  81832. FKey *p;
  81833. char *zWhere = 0;
  81834. for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
  81835. zWhere = whereOrName(pParse->db, zWhere, p->pFrom->zName);
  81836. }
  81837. return zWhere;
  81838. }
  81839. #endif
  81840. /*
  81841. ** Generate the text of a WHERE expression which can be used to select all
  81842. ** temporary triggers on table pTab from the sqlite_temp_master table. If
  81843. ** table pTab has no temporary triggers, or is itself stored in the
  81844. ** temporary database, NULL is returned.
  81845. */
  81846. static char *whereTempTriggers(Parse *pParse, Table *pTab){
  81847. Trigger *pTrig;
  81848. char *zWhere = 0;
  81849. const Schema *pTempSchema = pParse->db->aDb[1].pSchema; /* Temp db schema */
  81850. /* If the table is not located in the temp-db (in which case NULL is
  81851. ** returned, loop through the tables list of triggers. For each trigger
  81852. ** that is not part of the temp-db schema, add a clause to the WHERE
  81853. ** expression being built up in zWhere.
  81854. */
  81855. if( pTab->pSchema!=pTempSchema ){
  81856. sqlite3 *db = pParse->db;
  81857. for(pTrig=sqlite3TriggerList(pParse, pTab); pTrig; pTrig=pTrig->pNext){
  81858. if( pTrig->pSchema==pTempSchema ){
  81859. zWhere = whereOrName(db, zWhere, pTrig->zName);
  81860. }
  81861. }
  81862. }
  81863. if( zWhere ){
  81864. char *zNew = sqlite3MPrintf(pParse->db, "type='trigger' AND (%s)", zWhere);
  81865. sqlite3DbFree(pParse->db, zWhere);
  81866. zWhere = zNew;
  81867. }
  81868. return zWhere;
  81869. }
  81870. /*
  81871. ** Generate code to drop and reload the internal representation of table
  81872. ** pTab from the database, including triggers and temporary triggers.
  81873. ** Argument zName is the name of the table in the database schema at
  81874. ** the time the generated code is executed. This can be different from
  81875. ** pTab->zName if this function is being called to code part of an
  81876. ** "ALTER TABLE RENAME TO" statement.
  81877. */
  81878. static void reloadTableSchema(Parse *pParse, Table *pTab, const char *zName){
  81879. Vdbe *v;
  81880. char *zWhere;
  81881. int iDb; /* Index of database containing pTab */
  81882. #ifndef SQLITE_OMIT_TRIGGER
  81883. Trigger *pTrig;
  81884. #endif
  81885. v = sqlite3GetVdbe(pParse);
  81886. if( NEVER(v==0) ) return;
  81887. assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
  81888. iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
  81889. assert( iDb>=0 );
  81890. #ifndef SQLITE_OMIT_TRIGGER
  81891. /* Drop any table triggers from the internal schema. */
  81892. for(pTrig=sqlite3TriggerList(pParse, pTab); pTrig; pTrig=pTrig->pNext){
  81893. int iTrigDb = sqlite3SchemaToIndex(pParse->db, pTrig->pSchema);
  81894. assert( iTrigDb==iDb || iTrigDb==1 );
  81895. sqlite3VdbeAddOp4(v, OP_DropTrigger, iTrigDb, 0, 0, pTrig->zName, 0);
  81896. }
  81897. #endif
  81898. /* Drop the table and index from the internal schema. */
  81899. sqlite3VdbeAddOp4(v, OP_DropTable, iDb, 0, 0, pTab->zName, 0);
  81900. /* Reload the table, index and permanent trigger schemas. */
  81901. zWhere = sqlite3MPrintf(pParse->db, "tbl_name=%Q", zName);
  81902. if( !zWhere ) return;
  81903. sqlite3VdbeAddParseSchemaOp(v, iDb, zWhere);
  81904. #ifndef SQLITE_OMIT_TRIGGER
  81905. /* Now, if the table is not stored in the temp database, reload any temp
  81906. ** triggers. Don't use IN(...) in case SQLITE_OMIT_SUBQUERY is defined.
  81907. */
  81908. if( (zWhere=whereTempTriggers(pParse, pTab))!=0 ){
  81909. sqlite3VdbeAddParseSchemaOp(v, 1, zWhere);
  81910. }
  81911. #endif
  81912. }
  81913. /*
  81914. ** Parameter zName is the name of a table that is about to be altered
  81915. ** (either with ALTER TABLE ... RENAME TO or ALTER TABLE ... ADD COLUMN).
  81916. ** If the table is a system table, this function leaves an error message
  81917. ** in pParse->zErr (system tables may not be altered) and returns non-zero.
  81918. **
  81919. ** Or, if zName is not a system table, zero is returned.
  81920. */
  81921. static int isSystemTable(Parse *pParse, const char *zName){
  81922. if( sqlite3Strlen30(zName)>6 && 0==sqlite3StrNICmp(zName, "sqlite_", 7) ){
  81923. sqlite3ErrorMsg(pParse, "table %s may not be altered", zName);
  81924. return 1;
  81925. }
  81926. return 0;
  81927. }
  81928. /*
  81929. ** Generate code to implement the "ALTER TABLE xxx RENAME TO yyy"
  81930. ** command.
  81931. */
  81932. SQLITE_PRIVATE void sqlite3AlterRenameTable(
  81933. Parse *pParse, /* Parser context. */
  81934. SrcList *pSrc, /* The table to rename. */
  81935. Token *pName /* The new table name. */
  81936. ){
  81937. int iDb; /* Database that contains the table */
  81938. char *zDb; /* Name of database iDb */
  81939. Table *pTab; /* Table being renamed */
  81940. char *zName = 0; /* NULL-terminated version of pName */
  81941. sqlite3 *db = pParse->db; /* Database connection */
  81942. int nTabName; /* Number of UTF-8 characters in zTabName */
  81943. const char *zTabName; /* Original name of the table */
  81944. Vdbe *v;
  81945. #ifndef SQLITE_OMIT_TRIGGER
  81946. char *zWhere = 0; /* Where clause to locate temp triggers */
  81947. #endif
  81948. VTable *pVTab = 0; /* Non-zero if this is a v-tab with an xRename() */
  81949. int savedDbFlags; /* Saved value of db->flags */
  81950. savedDbFlags = db->flags;
  81951. if( NEVER(db->mallocFailed) ) goto exit_rename_table;
  81952. assert( pSrc->nSrc==1 );
  81953. assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
  81954. pTab = sqlite3LocateTableItem(pParse, 0, &pSrc->a[0]);
  81955. if( !pTab ) goto exit_rename_table;
  81956. iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
  81957. zDb = db->aDb[iDb].zName;
  81958. db->flags |= SQLITE_PreferBuiltin;
  81959. /* Get a NULL terminated version of the new table name. */
  81960. zName = sqlite3NameFromToken(db, pName);
  81961. if( !zName ) goto exit_rename_table;
  81962. /* Check that a table or index named 'zName' does not already exist
  81963. ** in database iDb. If so, this is an error.
  81964. */
  81965. if( sqlite3FindTable(db, zName, zDb) || sqlite3FindIndex(db, zName, zDb) ){
  81966. sqlite3ErrorMsg(pParse,
  81967. "there is already another table or index with this name: %s", zName);
  81968. goto exit_rename_table;
  81969. }
  81970. /* Make sure it is not a system table being altered, or a reserved name
  81971. ** that the table is being renamed to.
  81972. */
  81973. if( SQLITE_OK!=isSystemTable(pParse, pTab->zName) ){
  81974. goto exit_rename_table;
  81975. }
  81976. if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){ goto
  81977. exit_rename_table;
  81978. }
  81979. #ifndef SQLITE_OMIT_VIEW
  81980. if( pTab->pSelect ){
  81981. sqlite3ErrorMsg(pParse, "view %s may not be altered", pTab->zName);
  81982. goto exit_rename_table;
  81983. }
  81984. #endif
  81985. #ifndef SQLITE_OMIT_AUTHORIZATION
  81986. /* Invoke the authorization callback. */
  81987. if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab->zName, 0) ){
  81988. goto exit_rename_table;
  81989. }
  81990. #endif
  81991. #ifndef SQLITE_OMIT_VIRTUALTABLE
  81992. if( sqlite3ViewGetColumnNames(pParse, pTab) ){
  81993. goto exit_rename_table;
  81994. }
  81995. if( IsVirtual(pTab) ){
  81996. pVTab = sqlite3GetVTable(db, pTab);
  81997. if( pVTab->pVtab->pModule->xRename==0 ){
  81998. pVTab = 0;
  81999. }
  82000. }
  82001. #endif
  82002. /* Begin a transaction for database iDb.
  82003. ** Then modify the schema cookie (since the ALTER TABLE modifies the
  82004. ** schema). Open a statement transaction if the table is a virtual
  82005. ** table.
  82006. */
  82007. v = sqlite3GetVdbe(pParse);
  82008. if( v==0 ){
  82009. goto exit_rename_table;
  82010. }
  82011. sqlite3BeginWriteOperation(pParse, pVTab!=0, iDb);
  82012. sqlite3ChangeCookie(pParse, iDb);
  82013. /* If this is a virtual table, invoke the xRename() function if
  82014. ** one is defined. The xRename() callback will modify the names
  82015. ** of any resources used by the v-table implementation (including other
  82016. ** SQLite tables) that are identified by the name of the virtual table.
  82017. */
  82018. #ifndef SQLITE_OMIT_VIRTUALTABLE
  82019. if( pVTab ){
  82020. int i = ++pParse->nMem;
  82021. sqlite3VdbeAddOp4(v, OP_String8, 0, i, 0, zName, 0);
  82022. sqlite3VdbeAddOp4(v, OP_VRename, i, 0, 0,(const char*)pVTab, P4_VTAB);
  82023. sqlite3MayAbort(pParse);
  82024. }
  82025. #endif
  82026. /* figure out how many UTF-8 characters are in zName */
  82027. zTabName = pTab->zName;
  82028. nTabName = sqlite3Utf8CharLen(zTabName, -1);
  82029. #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
  82030. if( db->flags&SQLITE_ForeignKeys ){
  82031. /* If foreign-key support is enabled, rewrite the CREATE TABLE
  82032. ** statements corresponding to all child tables of foreign key constraints
  82033. ** for which the renamed table is the parent table. */
  82034. if( (zWhere=whereForeignKeys(pParse, pTab))!=0 ){
  82035. sqlite3NestedParse(pParse,
  82036. "UPDATE \"%w\".%s SET "
  82037. "sql = sqlite_rename_parent(sql, %Q, %Q) "
  82038. "WHERE %s;", zDb, SCHEMA_TABLE(iDb), zTabName, zName, zWhere);
  82039. sqlite3DbFree(db, zWhere);
  82040. }
  82041. }
  82042. #endif
  82043. /* Modify the sqlite_master table to use the new table name. */
  82044. sqlite3NestedParse(pParse,
  82045. "UPDATE %Q.%s SET "
  82046. #ifdef SQLITE_OMIT_TRIGGER
  82047. "sql = sqlite_rename_table(sql, %Q), "
  82048. #else
  82049. "sql = CASE "
  82050. "WHEN type = 'trigger' THEN sqlite_rename_trigger(sql, %Q)"
  82051. "ELSE sqlite_rename_table(sql, %Q) END, "
  82052. #endif
  82053. "tbl_name = %Q, "
  82054. "name = CASE "
  82055. "WHEN type='table' THEN %Q "
  82056. "WHEN name LIKE 'sqlite_autoindex%%' AND type='index' THEN "
  82057. "'sqlite_autoindex_' || %Q || substr(name,%d+18) "
  82058. "ELSE name END "
  82059. "WHERE tbl_name=%Q COLLATE nocase AND "
  82060. "(type='table' OR type='index' OR type='trigger');",
  82061. zDb, SCHEMA_TABLE(iDb), zName, zName, zName,
  82062. #ifndef SQLITE_OMIT_TRIGGER
  82063. zName,
  82064. #endif
  82065. zName, nTabName, zTabName
  82066. );
  82067. #ifndef SQLITE_OMIT_AUTOINCREMENT
  82068. /* If the sqlite_sequence table exists in this database, then update
  82069. ** it with the new table name.
  82070. */
  82071. if( sqlite3FindTable(db, "sqlite_sequence", zDb) ){
  82072. sqlite3NestedParse(pParse,
  82073. "UPDATE \"%w\".sqlite_sequence set name = %Q WHERE name = %Q",
  82074. zDb, zName, pTab->zName);
  82075. }
  82076. #endif
  82077. #ifndef SQLITE_OMIT_TRIGGER
  82078. /* If there are TEMP triggers on this table, modify the sqlite_temp_master
  82079. ** table. Don't do this if the table being ALTERed is itself located in
  82080. ** the temp database.
  82081. */
  82082. if( (zWhere=whereTempTriggers(pParse, pTab))!=0 ){
  82083. sqlite3NestedParse(pParse,
  82084. "UPDATE sqlite_temp_master SET "
  82085. "sql = sqlite_rename_trigger(sql, %Q), "
  82086. "tbl_name = %Q "
  82087. "WHERE %s;", zName, zName, zWhere);
  82088. sqlite3DbFree(db, zWhere);
  82089. }
  82090. #endif
  82091. #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
  82092. if( db->flags&SQLITE_ForeignKeys ){
  82093. FKey *p;
  82094. for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
  82095. Table *pFrom = p->pFrom;
  82096. if( pFrom!=pTab ){
  82097. reloadTableSchema(pParse, p->pFrom, pFrom->zName);
  82098. }
  82099. }
  82100. }
  82101. #endif
  82102. /* Drop and reload the internal table schema. */
  82103. reloadTableSchema(pParse, pTab, zName);
  82104. exit_rename_table:
  82105. sqlite3SrcListDelete(db, pSrc);
  82106. sqlite3DbFree(db, zName);
  82107. db->flags = savedDbFlags;
  82108. }
  82109. /*
  82110. ** Generate code to make sure the file format number is at least minFormat.
  82111. ** The generated code will increase the file format number if necessary.
  82112. */
  82113. SQLITE_PRIVATE void sqlite3MinimumFileFormat(Parse *pParse, int iDb, int minFormat){
  82114. Vdbe *v;
  82115. v = sqlite3GetVdbe(pParse);
  82116. /* The VDBE should have been allocated before this routine is called.
  82117. ** If that allocation failed, we would have quit before reaching this
  82118. ** point */
  82119. if( ALWAYS(v) ){
  82120. int r1 = sqlite3GetTempReg(pParse);
  82121. int r2 = sqlite3GetTempReg(pParse);
  82122. int j1;
  82123. sqlite3VdbeAddOp3(v, OP_ReadCookie, iDb, r1, BTREE_FILE_FORMAT);
  82124. sqlite3VdbeUsesBtree(v, iDb);
  82125. sqlite3VdbeAddOp2(v, OP_Integer, minFormat, r2);
  82126. j1 = sqlite3VdbeAddOp3(v, OP_Ge, r2, 0, r1);
  82127. sqlite3VdbeChangeP5(v, SQLITE_NOTNULL); VdbeCoverage(v);
  82128. sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_FILE_FORMAT, r2);
  82129. sqlite3VdbeJumpHere(v, j1);
  82130. sqlite3ReleaseTempReg(pParse, r1);
  82131. sqlite3ReleaseTempReg(pParse, r2);
  82132. }
  82133. }
  82134. /*
  82135. ** This function is called after an "ALTER TABLE ... ADD" statement
  82136. ** has been parsed. Argument pColDef contains the text of the new
  82137. ** column definition.
  82138. **
  82139. ** The Table structure pParse->pNewTable was extended to include
  82140. ** the new column during parsing.
  82141. */
  82142. SQLITE_PRIVATE void sqlite3AlterFinishAddColumn(Parse *pParse, Token *pColDef){
  82143. Table *pNew; /* Copy of pParse->pNewTable */
  82144. Table *pTab; /* Table being altered */
  82145. int iDb; /* Database number */
  82146. const char *zDb; /* Database name */
  82147. const char *zTab; /* Table name */
  82148. char *zCol; /* Null-terminated column definition */
  82149. Column *pCol; /* The new column */
  82150. Expr *pDflt; /* Default value for the new column */
  82151. sqlite3 *db; /* The database connection; */
  82152. db = pParse->db;
  82153. if( pParse->nErr || db->mallocFailed ) return;
  82154. pNew = pParse->pNewTable;
  82155. assert( pNew );
  82156. assert( sqlite3BtreeHoldsAllMutexes(db) );
  82157. iDb = sqlite3SchemaToIndex(db, pNew->pSchema);
  82158. zDb = db->aDb[iDb].zName;
  82159. zTab = &pNew->zName[16]; /* Skip the "sqlite_altertab_" prefix on the name */
  82160. pCol = &pNew->aCol[pNew->nCol-1];
  82161. pDflt = pCol->pDflt;
  82162. pTab = sqlite3FindTable(db, zTab, zDb);
  82163. assert( pTab );
  82164. #ifndef SQLITE_OMIT_AUTHORIZATION
  82165. /* Invoke the authorization callback. */
  82166. if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab->zName, 0) ){
  82167. return;
  82168. }
  82169. #endif
  82170. /* If the default value for the new column was specified with a
  82171. ** literal NULL, then set pDflt to 0. This simplifies checking
  82172. ** for an SQL NULL default below.
  82173. */
  82174. if( pDflt && pDflt->op==TK_NULL ){
  82175. pDflt = 0;
  82176. }
  82177. /* Check that the new column is not specified as PRIMARY KEY or UNIQUE.
  82178. ** If there is a NOT NULL constraint, then the default value for the
  82179. ** column must not be NULL.
  82180. */
  82181. if( pCol->colFlags & COLFLAG_PRIMKEY ){
  82182. sqlite3ErrorMsg(pParse, "Cannot add a PRIMARY KEY column");
  82183. return;
  82184. }
  82185. if( pNew->pIndex ){
  82186. sqlite3ErrorMsg(pParse, "Cannot add a UNIQUE column");
  82187. return;
  82188. }
  82189. if( (db->flags&SQLITE_ForeignKeys) && pNew->pFKey && pDflt ){
  82190. sqlite3ErrorMsg(pParse,
  82191. "Cannot add a REFERENCES column with non-NULL default value");
  82192. return;
  82193. }
  82194. if( pCol->notNull && !pDflt ){
  82195. sqlite3ErrorMsg(pParse,
  82196. "Cannot add a NOT NULL column with default value NULL");
  82197. return;
  82198. }
  82199. /* Ensure the default expression is something that sqlite3ValueFromExpr()
  82200. ** can handle (i.e. not CURRENT_TIME etc.)
  82201. */
  82202. if( pDflt ){
  82203. sqlite3_value *pVal = 0;
  82204. int rc;
  82205. rc = sqlite3ValueFromExpr(db, pDflt, SQLITE_UTF8, SQLITE_AFF_NONE, &pVal);
  82206. assert( rc==SQLITE_OK || rc==SQLITE_NOMEM );
  82207. if( rc!=SQLITE_OK ){
  82208. db->mallocFailed = 1;
  82209. return;
  82210. }
  82211. if( !pVal ){
  82212. sqlite3ErrorMsg(pParse, "Cannot add a column with non-constant default");
  82213. return;
  82214. }
  82215. sqlite3ValueFree(pVal);
  82216. }
  82217. /* Modify the CREATE TABLE statement. */
  82218. zCol = sqlite3DbStrNDup(db, (char*)pColDef->z, pColDef->n);
  82219. if( zCol ){
  82220. char *zEnd = &zCol[pColDef->n-1];
  82221. int savedDbFlags = db->flags;
  82222. while( zEnd>zCol && (*zEnd==';' || sqlite3Isspace(*zEnd)) ){
  82223. *zEnd-- = '\0';
  82224. }
  82225. db->flags |= SQLITE_PreferBuiltin;
  82226. sqlite3NestedParse(pParse,
  82227. "UPDATE \"%w\".%s SET "
  82228. "sql = substr(sql,1,%d) || ', ' || %Q || substr(sql,%d) "
  82229. "WHERE type = 'table' AND name = %Q",
  82230. zDb, SCHEMA_TABLE(iDb), pNew->addColOffset, zCol, pNew->addColOffset+1,
  82231. zTab
  82232. );
  82233. sqlite3DbFree(db, zCol);
  82234. db->flags = savedDbFlags;
  82235. }
  82236. /* If the default value of the new column is NULL, then set the file
  82237. ** format to 2. If the default value of the new column is not NULL,
  82238. ** the file format becomes 3.
  82239. */
  82240. sqlite3MinimumFileFormat(pParse, iDb, pDflt ? 3 : 2);
  82241. /* Reload the schema of the modified table. */
  82242. reloadTableSchema(pParse, pTab, pTab->zName);
  82243. }
  82244. /*
  82245. ** This function is called by the parser after the table-name in
  82246. ** an "ALTER TABLE <table-name> ADD" statement is parsed. Argument
  82247. ** pSrc is the full-name of the table being altered.
  82248. **
  82249. ** This routine makes a (partial) copy of the Table structure
  82250. ** for the table being altered and sets Parse.pNewTable to point
  82251. ** to it. Routines called by the parser as the column definition
  82252. ** is parsed (i.e. sqlite3AddColumn()) add the new Column data to
  82253. ** the copy. The copy of the Table structure is deleted by tokenize.c
  82254. ** after parsing is finished.
  82255. **
  82256. ** Routine sqlite3AlterFinishAddColumn() will be called to complete
  82257. ** coding the "ALTER TABLE ... ADD" statement.
  82258. */
  82259. SQLITE_PRIVATE void sqlite3AlterBeginAddColumn(Parse *pParse, SrcList *pSrc){
  82260. Table *pNew;
  82261. Table *pTab;
  82262. Vdbe *v;
  82263. int iDb;
  82264. int i;
  82265. int nAlloc;
  82266. sqlite3 *db = pParse->db;
  82267. /* Look up the table being altered. */
  82268. assert( pParse->pNewTable==0 );
  82269. assert( sqlite3BtreeHoldsAllMutexes(db) );
  82270. if( db->mallocFailed ) goto exit_begin_add_column;
  82271. pTab = sqlite3LocateTableItem(pParse, 0, &pSrc->a[0]);
  82272. if( !pTab ) goto exit_begin_add_column;
  82273. #ifndef SQLITE_OMIT_VIRTUALTABLE
  82274. if( IsVirtual(pTab) ){
  82275. sqlite3ErrorMsg(pParse, "virtual tables may not be altered");
  82276. goto exit_begin_add_column;
  82277. }
  82278. #endif
  82279. /* Make sure this is not an attempt to ALTER a view. */
  82280. if( pTab->pSelect ){
  82281. sqlite3ErrorMsg(pParse, "Cannot add a column to a view");
  82282. goto exit_begin_add_column;
  82283. }
  82284. if( SQLITE_OK!=isSystemTable(pParse, pTab->zName) ){
  82285. goto exit_begin_add_column;
  82286. }
  82287. assert( pTab->addColOffset>0 );
  82288. iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  82289. /* Put a copy of the Table struct in Parse.pNewTable for the
  82290. ** sqlite3AddColumn() function and friends to modify. But modify
  82291. ** the name by adding an "sqlite_altertab_" prefix. By adding this
  82292. ** prefix, we insure that the name will not collide with an existing
  82293. ** table because user table are not allowed to have the "sqlite_"
  82294. ** prefix on their name.
  82295. */
  82296. pNew = (Table*)sqlite3DbMallocZero(db, sizeof(Table));
  82297. if( !pNew ) goto exit_begin_add_column;
  82298. pParse->pNewTable = pNew;
  82299. pNew->nRef = 1;
  82300. pNew->nCol = pTab->nCol;
  82301. assert( pNew->nCol>0 );
  82302. nAlloc = (((pNew->nCol-1)/8)*8)+8;
  82303. assert( nAlloc>=pNew->nCol && nAlloc%8==0 && nAlloc-pNew->nCol<8 );
  82304. pNew->aCol = (Column*)sqlite3DbMallocZero(db, sizeof(Column)*nAlloc);
  82305. pNew->zName = sqlite3MPrintf(db, "sqlite_altertab_%s", pTab->zName);
  82306. if( !pNew->aCol || !pNew->zName ){
  82307. db->mallocFailed = 1;
  82308. goto exit_begin_add_column;
  82309. }
  82310. memcpy(pNew->aCol, pTab->aCol, sizeof(Column)*pNew->nCol);
  82311. for(i=0; i<pNew->nCol; i++){
  82312. Column *pCol = &pNew->aCol[i];
  82313. pCol->zName = sqlite3DbStrDup(db, pCol->zName);
  82314. pCol->zColl = 0;
  82315. pCol->zType = 0;
  82316. pCol->pDflt = 0;
  82317. pCol->zDflt = 0;
  82318. }
  82319. pNew->pSchema = db->aDb[iDb].pSchema;
  82320. pNew->addColOffset = pTab->addColOffset;
  82321. pNew->nRef = 1;
  82322. /* Begin a transaction and increment the schema cookie. */
  82323. sqlite3BeginWriteOperation(pParse, 0, iDb);
  82324. v = sqlite3GetVdbe(pParse);
  82325. if( !v ) goto exit_begin_add_column;
  82326. sqlite3ChangeCookie(pParse, iDb);
  82327. exit_begin_add_column:
  82328. sqlite3SrcListDelete(db, pSrc);
  82329. return;
  82330. }
  82331. #endif /* SQLITE_ALTER_TABLE */
  82332. /************** End of alter.c ***********************************************/
  82333. /************** Begin file analyze.c *****************************************/
  82334. /*
  82335. ** 2005-07-08
  82336. **
  82337. ** The author disclaims copyright to this source code. In place of
  82338. ** a legal notice, here is a blessing:
  82339. **
  82340. ** May you do good and not evil.
  82341. ** May you find forgiveness for yourself and forgive others.
  82342. ** May you share freely, never taking more than you give.
  82343. **
  82344. *************************************************************************
  82345. ** This file contains code associated with the ANALYZE command.
  82346. **
  82347. ** The ANALYZE command gather statistics about the content of tables
  82348. ** and indices. These statistics are made available to the query planner
  82349. ** to help it make better decisions about how to perform queries.
  82350. **
  82351. ** The following system tables are or have been supported:
  82352. **
  82353. ** CREATE TABLE sqlite_stat1(tbl, idx, stat);
  82354. ** CREATE TABLE sqlite_stat2(tbl, idx, sampleno, sample);
  82355. ** CREATE TABLE sqlite_stat3(tbl, idx, nEq, nLt, nDLt, sample);
  82356. ** CREATE TABLE sqlite_stat4(tbl, idx, nEq, nLt, nDLt, sample);
  82357. **
  82358. ** Additional tables might be added in future releases of SQLite.
  82359. ** The sqlite_stat2 table is not created or used unless the SQLite version
  82360. ** is between 3.6.18 and 3.7.8, inclusive, and unless SQLite is compiled
  82361. ** with SQLITE_ENABLE_STAT2. The sqlite_stat2 table is deprecated.
  82362. ** The sqlite_stat2 table is superseded by sqlite_stat3, which is only
  82363. ** created and used by SQLite versions 3.7.9 and later and with
  82364. ** SQLITE_ENABLE_STAT3 defined. The functionality of sqlite_stat3
  82365. ** is a superset of sqlite_stat2. The sqlite_stat4 is an enhanced
  82366. ** version of sqlite_stat3 and is only available when compiled with
  82367. ** SQLITE_ENABLE_STAT4 and in SQLite versions 3.8.1 and later. It is
  82368. ** not possible to enable both STAT3 and STAT4 at the same time. If they
  82369. ** are both enabled, then STAT4 takes precedence.
  82370. **
  82371. ** For most applications, sqlite_stat1 provides all the statistics required
  82372. ** for the query planner to make good choices.
  82373. **
  82374. ** Format of sqlite_stat1:
  82375. **
  82376. ** There is normally one row per index, with the index identified by the
  82377. ** name in the idx column. The tbl column is the name of the table to
  82378. ** which the index belongs. In each such row, the stat column will be
  82379. ** a string consisting of a list of integers. The first integer in this
  82380. ** list is the number of rows in the index. (This is the same as the
  82381. ** number of rows in the table, except for partial indices.) The second
  82382. ** integer is the average number of rows in the index that have the same
  82383. ** value in the first column of the index. The third integer is the average
  82384. ** number of rows in the index that have the same value for the first two
  82385. ** columns. The N-th integer (for N>1) is the average number of rows in
  82386. ** the index which have the same value for the first N-1 columns. For
  82387. ** a K-column index, there will be K+1 integers in the stat column. If
  82388. ** the index is unique, then the last integer will be 1.
  82389. **
  82390. ** The list of integers in the stat column can optionally be followed
  82391. ** by the keyword "unordered". The "unordered" keyword, if it is present,
  82392. ** must be separated from the last integer by a single space. If the
  82393. ** "unordered" keyword is present, then the query planner assumes that
  82394. ** the index is unordered and will not use the index for a range query.
  82395. **
  82396. ** If the sqlite_stat1.idx column is NULL, then the sqlite_stat1.stat
  82397. ** column contains a single integer which is the (estimated) number of
  82398. ** rows in the table identified by sqlite_stat1.tbl.
  82399. **
  82400. ** Format of sqlite_stat2:
  82401. **
  82402. ** The sqlite_stat2 is only created and is only used if SQLite is compiled
  82403. ** with SQLITE_ENABLE_STAT2 and if the SQLite version number is between
  82404. ** 3.6.18 and 3.7.8. The "stat2" table contains additional information
  82405. ** about the distribution of keys within an index. The index is identified by
  82406. ** the "idx" column and the "tbl" column is the name of the table to which
  82407. ** the index belongs. There are usually 10 rows in the sqlite_stat2
  82408. ** table for each index.
  82409. **
  82410. ** The sqlite_stat2 entries for an index that have sampleno between 0 and 9
  82411. ** inclusive are samples of the left-most key value in the index taken at
  82412. ** evenly spaced points along the index. Let the number of samples be S
  82413. ** (10 in the standard build) and let C be the number of rows in the index.
  82414. ** Then the sampled rows are given by:
  82415. **
  82416. ** rownumber = (i*C*2 + C)/(S*2)
  82417. **
  82418. ** For i between 0 and S-1. Conceptually, the index space is divided into
  82419. ** S uniform buckets and the samples are the middle row from each bucket.
  82420. **
  82421. ** The format for sqlite_stat2 is recorded here for legacy reference. This
  82422. ** version of SQLite does not support sqlite_stat2. It neither reads nor
  82423. ** writes the sqlite_stat2 table. This version of SQLite only supports
  82424. ** sqlite_stat3.
  82425. **
  82426. ** Format for sqlite_stat3:
  82427. **
  82428. ** The sqlite_stat3 format is a subset of sqlite_stat4. Hence, the
  82429. ** sqlite_stat4 format will be described first. Further information
  82430. ** about sqlite_stat3 follows the sqlite_stat4 description.
  82431. **
  82432. ** Format for sqlite_stat4:
  82433. **
  82434. ** As with sqlite_stat2, the sqlite_stat4 table contains histogram data
  82435. ** to aid the query planner in choosing good indices based on the values
  82436. ** that indexed columns are compared against in the WHERE clauses of
  82437. ** queries.
  82438. **
  82439. ** The sqlite_stat4 table contains multiple entries for each index.
  82440. ** The idx column names the index and the tbl column is the table of the
  82441. ** index. If the idx and tbl columns are the same, then the sample is
  82442. ** of the INTEGER PRIMARY KEY. The sample column is a blob which is the
  82443. ** binary encoding of a key from the index. The nEq column is a
  82444. ** list of integers. The first integer is the approximate number
  82445. ** of entries in the index whose left-most column exactly matches
  82446. ** the left-most column of the sample. The second integer in nEq
  82447. ** is the approximate number of entries in the index where the
  82448. ** first two columns match the first two columns of the sample.
  82449. ** And so forth. nLt is another list of integers that show the approximate
  82450. ** number of entries that are strictly less than the sample. The first
  82451. ** integer in nLt contains the number of entries in the index where the
  82452. ** left-most column is less than the left-most column of the sample.
  82453. ** The K-th integer in the nLt entry is the number of index entries
  82454. ** where the first K columns are less than the first K columns of the
  82455. ** sample. The nDLt column is like nLt except that it contains the
  82456. ** number of distinct entries in the index that are less than the
  82457. ** sample.
  82458. **
  82459. ** There can be an arbitrary number of sqlite_stat4 entries per index.
  82460. ** The ANALYZE command will typically generate sqlite_stat4 tables
  82461. ** that contain between 10 and 40 samples which are distributed across
  82462. ** the key space, though not uniformly, and which include samples with
  82463. ** large nEq values.
  82464. **
  82465. ** Format for sqlite_stat3 redux:
  82466. **
  82467. ** The sqlite_stat3 table is like sqlite_stat4 except that it only
  82468. ** looks at the left-most column of the index. The sqlite_stat3.sample
  82469. ** column contains the actual value of the left-most column instead
  82470. ** of a blob encoding of the complete index key as is found in
  82471. ** sqlite_stat4.sample. The nEq, nLt, and nDLt entries of sqlite_stat3
  82472. ** all contain just a single integer which is the same as the first
  82473. ** integer in the equivalent columns in sqlite_stat4.
  82474. */
  82475. #ifndef SQLITE_OMIT_ANALYZE
  82476. #if defined(SQLITE_ENABLE_STAT4)
  82477. # define IsStat4 1
  82478. # define IsStat3 0
  82479. #elif defined(SQLITE_ENABLE_STAT3)
  82480. # define IsStat4 0
  82481. # define IsStat3 1
  82482. #else
  82483. # define IsStat4 0
  82484. # define IsStat3 0
  82485. # undef SQLITE_STAT4_SAMPLES
  82486. # define SQLITE_STAT4_SAMPLES 1
  82487. #endif
  82488. #define IsStat34 (IsStat3+IsStat4) /* 1 for STAT3 or STAT4. 0 otherwise */
  82489. /*
  82490. ** This routine generates code that opens the sqlite_statN tables.
  82491. ** The sqlite_stat1 table is always relevant. sqlite_stat2 is now
  82492. ** obsolete. sqlite_stat3 and sqlite_stat4 are only opened when
  82493. ** appropriate compile-time options are provided.
  82494. **
  82495. ** If the sqlite_statN tables do not previously exist, it is created.
  82496. **
  82497. ** Argument zWhere may be a pointer to a buffer containing a table name,
  82498. ** or it may be a NULL pointer. If it is not NULL, then all entries in
  82499. ** the sqlite_statN tables associated with the named table are deleted.
  82500. ** If zWhere==0, then code is generated to delete all stat table entries.
  82501. */
  82502. static void openStatTable(
  82503. Parse *pParse, /* Parsing context */
  82504. int iDb, /* The database we are looking in */
  82505. int iStatCur, /* Open the sqlite_stat1 table on this cursor */
  82506. const char *zWhere, /* Delete entries for this table or index */
  82507. const char *zWhereType /* Either "tbl" or "idx" */
  82508. ){
  82509. static const struct {
  82510. const char *zName;
  82511. const char *zCols;
  82512. } aTable[] = {
  82513. { "sqlite_stat1", "tbl,idx,stat" },
  82514. #if defined(SQLITE_ENABLE_STAT4)
  82515. { "sqlite_stat4", "tbl,idx,neq,nlt,ndlt,sample" },
  82516. { "sqlite_stat3", 0 },
  82517. #elif defined(SQLITE_ENABLE_STAT3)
  82518. { "sqlite_stat3", "tbl,idx,neq,nlt,ndlt,sample" },
  82519. { "sqlite_stat4", 0 },
  82520. #else
  82521. { "sqlite_stat3", 0 },
  82522. { "sqlite_stat4", 0 },
  82523. #endif
  82524. };
  82525. int i;
  82526. sqlite3 *db = pParse->db;
  82527. Db *pDb;
  82528. Vdbe *v = sqlite3GetVdbe(pParse);
  82529. int aRoot[ArraySize(aTable)];
  82530. u8 aCreateTbl[ArraySize(aTable)];
  82531. if( v==0 ) return;
  82532. assert( sqlite3BtreeHoldsAllMutexes(db) );
  82533. assert( sqlite3VdbeDb(v)==db );
  82534. pDb = &db->aDb[iDb];
  82535. /* Create new statistic tables if they do not exist, or clear them
  82536. ** if they do already exist.
  82537. */
  82538. for(i=0; i<ArraySize(aTable); i++){
  82539. const char *zTab = aTable[i].zName;
  82540. Table *pStat;
  82541. if( (pStat = sqlite3FindTable(db, zTab, pDb->zName))==0 ){
  82542. if( aTable[i].zCols ){
  82543. /* The sqlite_statN table does not exist. Create it. Note that a
  82544. ** side-effect of the CREATE TABLE statement is to leave the rootpage
  82545. ** of the new table in register pParse->regRoot. This is important
  82546. ** because the OpenWrite opcode below will be needing it. */
  82547. sqlite3NestedParse(pParse,
  82548. "CREATE TABLE %Q.%s(%s)", pDb->zName, zTab, aTable[i].zCols
  82549. );
  82550. aRoot[i] = pParse->regRoot;
  82551. aCreateTbl[i] = OPFLAG_P2ISREG;
  82552. }
  82553. }else{
  82554. /* The table already exists. If zWhere is not NULL, delete all entries
  82555. ** associated with the table zWhere. If zWhere is NULL, delete the
  82556. ** entire contents of the table. */
  82557. aRoot[i] = pStat->tnum;
  82558. aCreateTbl[i] = 0;
  82559. sqlite3TableLock(pParse, iDb, aRoot[i], 1, zTab);
  82560. if( zWhere ){
  82561. sqlite3NestedParse(pParse,
  82562. "DELETE FROM %Q.%s WHERE %s=%Q",
  82563. pDb->zName, zTab, zWhereType, zWhere
  82564. );
  82565. }else{
  82566. /* The sqlite_stat[134] table already exists. Delete all rows. */
  82567. sqlite3VdbeAddOp2(v, OP_Clear, aRoot[i], iDb);
  82568. }
  82569. }
  82570. }
  82571. /* Open the sqlite_stat[134] tables for writing. */
  82572. for(i=0; aTable[i].zCols; i++){
  82573. assert( i<ArraySize(aTable) );
  82574. sqlite3VdbeAddOp4Int(v, OP_OpenWrite, iStatCur+i, aRoot[i], iDb, 3);
  82575. sqlite3VdbeChangeP5(v, aCreateTbl[i]);
  82576. VdbeComment((v, aTable[i].zName));
  82577. }
  82578. }
  82579. /*
  82580. ** Recommended number of samples for sqlite_stat4
  82581. */
  82582. #ifndef SQLITE_STAT4_SAMPLES
  82583. # define SQLITE_STAT4_SAMPLES 24
  82584. #endif
  82585. /*
  82586. ** Three SQL functions - stat_init(), stat_push(), and stat_get() -
  82587. ** share an instance of the following structure to hold their state
  82588. ** information.
  82589. */
  82590. typedef struct Stat4Accum Stat4Accum;
  82591. typedef struct Stat4Sample Stat4Sample;
  82592. struct Stat4Sample {
  82593. tRowcnt *anEq; /* sqlite_stat4.nEq */
  82594. tRowcnt *anDLt; /* sqlite_stat4.nDLt */
  82595. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  82596. tRowcnt *anLt; /* sqlite_stat4.nLt */
  82597. union {
  82598. i64 iRowid; /* Rowid in main table of the key */
  82599. u8 *aRowid; /* Key for WITHOUT ROWID tables */
  82600. } u;
  82601. u32 nRowid; /* Sizeof aRowid[] */
  82602. u8 isPSample; /* True if a periodic sample */
  82603. int iCol; /* If !isPSample, the reason for inclusion */
  82604. u32 iHash; /* Tiebreaker hash */
  82605. #endif
  82606. };
  82607. struct Stat4Accum {
  82608. tRowcnt nRow; /* Number of rows in the entire table */
  82609. tRowcnt nPSample; /* How often to do a periodic sample */
  82610. int nCol; /* Number of columns in index + pk/rowid */
  82611. int nKeyCol; /* Number of index columns w/o the pk/rowid */
  82612. int mxSample; /* Maximum number of samples to accumulate */
  82613. Stat4Sample current; /* Current row as a Stat4Sample */
  82614. u32 iPrn; /* Pseudo-random number used for sampling */
  82615. Stat4Sample *aBest; /* Array of nCol best samples */
  82616. int iMin; /* Index in a[] of entry with minimum score */
  82617. int nSample; /* Current number of samples */
  82618. int iGet; /* Index of current sample accessed by stat_get() */
  82619. Stat4Sample *a; /* Array of mxSample Stat4Sample objects */
  82620. sqlite3 *db; /* Database connection, for malloc() */
  82621. };
  82622. /* Reclaim memory used by a Stat4Sample
  82623. */
  82624. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  82625. static void sampleClear(sqlite3 *db, Stat4Sample *p){
  82626. assert( db!=0 );
  82627. if( p->nRowid ){
  82628. sqlite3DbFree(db, p->u.aRowid);
  82629. p->nRowid = 0;
  82630. }
  82631. }
  82632. #endif
  82633. /* Initialize the BLOB value of a ROWID
  82634. */
  82635. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  82636. static void sampleSetRowid(sqlite3 *db, Stat4Sample *p, int n, const u8 *pData){
  82637. assert( db!=0 );
  82638. if( p->nRowid ) sqlite3DbFree(db, p->u.aRowid);
  82639. p->u.aRowid = sqlite3DbMallocRaw(db, n);
  82640. if( p->u.aRowid ){
  82641. p->nRowid = n;
  82642. memcpy(p->u.aRowid, pData, n);
  82643. }else{
  82644. p->nRowid = 0;
  82645. }
  82646. }
  82647. #endif
  82648. /* Initialize the INTEGER value of a ROWID.
  82649. */
  82650. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  82651. static void sampleSetRowidInt64(sqlite3 *db, Stat4Sample *p, i64 iRowid){
  82652. assert( db!=0 );
  82653. if( p->nRowid ) sqlite3DbFree(db, p->u.aRowid);
  82654. p->nRowid = 0;
  82655. p->u.iRowid = iRowid;
  82656. }
  82657. #endif
  82658. /*
  82659. ** Copy the contents of object (*pFrom) into (*pTo).
  82660. */
  82661. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  82662. static void sampleCopy(Stat4Accum *p, Stat4Sample *pTo, Stat4Sample *pFrom){
  82663. pTo->isPSample = pFrom->isPSample;
  82664. pTo->iCol = pFrom->iCol;
  82665. pTo->iHash = pFrom->iHash;
  82666. memcpy(pTo->anEq, pFrom->anEq, sizeof(tRowcnt)*p->nCol);
  82667. memcpy(pTo->anLt, pFrom->anLt, sizeof(tRowcnt)*p->nCol);
  82668. memcpy(pTo->anDLt, pFrom->anDLt, sizeof(tRowcnt)*p->nCol);
  82669. if( pFrom->nRowid ){
  82670. sampleSetRowid(p->db, pTo, pFrom->nRowid, pFrom->u.aRowid);
  82671. }else{
  82672. sampleSetRowidInt64(p->db, pTo, pFrom->u.iRowid);
  82673. }
  82674. }
  82675. #endif
  82676. /*
  82677. ** Reclaim all memory of a Stat4Accum structure.
  82678. */
  82679. static void stat4Destructor(void *pOld){
  82680. Stat4Accum *p = (Stat4Accum*)pOld;
  82681. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  82682. int i;
  82683. for(i=0; i<p->nCol; i++) sampleClear(p->db, p->aBest+i);
  82684. for(i=0; i<p->mxSample; i++) sampleClear(p->db, p->a+i);
  82685. sampleClear(p->db, &p->current);
  82686. #endif
  82687. sqlite3DbFree(p->db, p);
  82688. }
  82689. /*
  82690. ** Implementation of the stat_init(N,K,C) SQL function. The three parameters
  82691. ** are:
  82692. ** N: The number of columns in the index including the rowid/pk (note 1)
  82693. ** K: The number of columns in the index excluding the rowid/pk.
  82694. ** C: The number of rows in the index (note 2)
  82695. **
  82696. ** Note 1: In the special case of the covering index that implements a
  82697. ** WITHOUT ROWID table, N is the number of PRIMARY KEY columns, not the
  82698. ** total number of columns in the table.
  82699. **
  82700. ** Note 2: C is only used for STAT3 and STAT4.
  82701. **
  82702. ** For indexes on ordinary rowid tables, N==K+1. But for indexes on
  82703. ** WITHOUT ROWID tables, N=K+P where P is the number of columns in the
  82704. ** PRIMARY KEY of the table. The covering index that implements the
  82705. ** original WITHOUT ROWID table as N==K as a special case.
  82706. **
  82707. ** This routine allocates the Stat4Accum object in heap memory. The return
  82708. ** value is a pointer to the Stat4Accum object. The datatype of the
  82709. ** return value is BLOB, but it is really just a pointer to the Stat4Accum
  82710. ** object.
  82711. */
  82712. static void statInit(
  82713. sqlite3_context *context,
  82714. int argc,
  82715. sqlite3_value **argv
  82716. ){
  82717. Stat4Accum *p;
  82718. int nCol; /* Number of columns in index being sampled */
  82719. int nKeyCol; /* Number of key columns */
  82720. int nColUp; /* nCol rounded up for alignment */
  82721. int n; /* Bytes of space to allocate */
  82722. sqlite3 *db; /* Database connection */
  82723. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  82724. int mxSample = SQLITE_STAT4_SAMPLES;
  82725. #endif
  82726. /* Decode the three function arguments */
  82727. UNUSED_PARAMETER(argc);
  82728. nCol = sqlite3_value_int(argv[0]);
  82729. assert( nCol>0 );
  82730. nColUp = sizeof(tRowcnt)<8 ? (nCol+1)&~1 : nCol;
  82731. nKeyCol = sqlite3_value_int(argv[1]);
  82732. assert( nKeyCol<=nCol );
  82733. assert( nKeyCol>0 );
  82734. /* Allocate the space required for the Stat4Accum object */
  82735. n = sizeof(*p)
  82736. + sizeof(tRowcnt)*nColUp /* Stat4Accum.anEq */
  82737. + sizeof(tRowcnt)*nColUp /* Stat4Accum.anDLt */
  82738. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  82739. + sizeof(tRowcnt)*nColUp /* Stat4Accum.anLt */
  82740. + sizeof(Stat4Sample)*(nCol+mxSample) /* Stat4Accum.aBest[], a[] */
  82741. + sizeof(tRowcnt)*3*nColUp*(nCol+mxSample)
  82742. #endif
  82743. ;
  82744. db = sqlite3_context_db_handle(context);
  82745. p = sqlite3DbMallocZero(db, n);
  82746. if( p==0 ){
  82747. sqlite3_result_error_nomem(context);
  82748. return;
  82749. }
  82750. p->db = db;
  82751. p->nRow = 0;
  82752. p->nCol = nCol;
  82753. p->nKeyCol = nKeyCol;
  82754. p->current.anDLt = (tRowcnt*)&p[1];
  82755. p->current.anEq = &p->current.anDLt[nColUp];
  82756. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  82757. {
  82758. u8 *pSpace; /* Allocated space not yet assigned */
  82759. int i; /* Used to iterate through p->aSample[] */
  82760. p->iGet = -1;
  82761. p->mxSample = mxSample;
  82762. p->nPSample = (tRowcnt)(sqlite3_value_int64(argv[2])/(mxSample/3+1) + 1);
  82763. p->current.anLt = &p->current.anEq[nColUp];
  82764. p->iPrn = 0x689e962d*(u32)nCol ^ 0xd0944565*(u32)sqlite3_value_int(argv[2]);
  82765. /* Set up the Stat4Accum.a[] and aBest[] arrays */
  82766. p->a = (struct Stat4Sample*)&p->current.anLt[nColUp];
  82767. p->aBest = &p->a[mxSample];
  82768. pSpace = (u8*)(&p->a[mxSample+nCol]);
  82769. for(i=0; i<(mxSample+nCol); i++){
  82770. p->a[i].anEq = (tRowcnt *)pSpace; pSpace += (sizeof(tRowcnt) * nColUp);
  82771. p->a[i].anLt = (tRowcnt *)pSpace; pSpace += (sizeof(tRowcnt) * nColUp);
  82772. p->a[i].anDLt = (tRowcnt *)pSpace; pSpace += (sizeof(tRowcnt) * nColUp);
  82773. }
  82774. assert( (pSpace - (u8*)p)==n );
  82775. for(i=0; i<nCol; i++){
  82776. p->aBest[i].iCol = i;
  82777. }
  82778. }
  82779. #endif
  82780. /* Return a pointer to the allocated object to the caller. Note that
  82781. ** only the pointer (the 2nd parameter) matters. The size of the object
  82782. ** (given by the 3rd parameter) is never used and can be any positive
  82783. ** value. */
  82784. sqlite3_result_blob(context, p, sizeof(*p), stat4Destructor);
  82785. }
  82786. static const FuncDef statInitFuncdef = {
  82787. 2+IsStat34, /* nArg */
  82788. SQLITE_UTF8, /* funcFlags */
  82789. 0, /* pUserData */
  82790. 0, /* pNext */
  82791. statInit, /* xFunc */
  82792. 0, /* xStep */
  82793. 0, /* xFinalize */
  82794. "stat_init", /* zName */
  82795. 0, /* pHash */
  82796. 0 /* pDestructor */
  82797. };
  82798. #ifdef SQLITE_ENABLE_STAT4
  82799. /*
  82800. ** pNew and pOld are both candidate non-periodic samples selected for
  82801. ** the same column (pNew->iCol==pOld->iCol). Ignoring this column and
  82802. ** considering only any trailing columns and the sample hash value, this
  82803. ** function returns true if sample pNew is to be preferred over pOld.
  82804. ** In other words, if we assume that the cardinalities of the selected
  82805. ** column for pNew and pOld are equal, is pNew to be preferred over pOld.
  82806. **
  82807. ** This function assumes that for each argument sample, the contents of
  82808. ** the anEq[] array from pSample->anEq[pSample->iCol+1] onwards are valid.
  82809. */
  82810. static int sampleIsBetterPost(
  82811. Stat4Accum *pAccum,
  82812. Stat4Sample *pNew,
  82813. Stat4Sample *pOld
  82814. ){
  82815. int nCol = pAccum->nCol;
  82816. int i;
  82817. assert( pNew->iCol==pOld->iCol );
  82818. for(i=pNew->iCol+1; i<nCol; i++){
  82819. if( pNew->anEq[i]>pOld->anEq[i] ) return 1;
  82820. if( pNew->anEq[i]<pOld->anEq[i] ) return 0;
  82821. }
  82822. if( pNew->iHash>pOld->iHash ) return 1;
  82823. return 0;
  82824. }
  82825. #endif
  82826. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  82827. /*
  82828. ** Return true if pNew is to be preferred over pOld.
  82829. **
  82830. ** This function assumes that for each argument sample, the contents of
  82831. ** the anEq[] array from pSample->anEq[pSample->iCol] onwards are valid.
  82832. */
  82833. static int sampleIsBetter(
  82834. Stat4Accum *pAccum,
  82835. Stat4Sample *pNew,
  82836. Stat4Sample *pOld
  82837. ){
  82838. tRowcnt nEqNew = pNew->anEq[pNew->iCol];
  82839. tRowcnt nEqOld = pOld->anEq[pOld->iCol];
  82840. assert( pOld->isPSample==0 && pNew->isPSample==0 );
  82841. assert( IsStat4 || (pNew->iCol==0 && pOld->iCol==0) );
  82842. if( (nEqNew>nEqOld) ) return 1;
  82843. #ifdef SQLITE_ENABLE_STAT4
  82844. if( nEqNew==nEqOld ){
  82845. if( pNew->iCol<pOld->iCol ) return 1;
  82846. return (pNew->iCol==pOld->iCol && sampleIsBetterPost(pAccum, pNew, pOld));
  82847. }
  82848. return 0;
  82849. #else
  82850. return (nEqNew==nEqOld && pNew->iHash>pOld->iHash);
  82851. #endif
  82852. }
  82853. /*
  82854. ** Copy the contents of sample *pNew into the p->a[] array. If necessary,
  82855. ** remove the least desirable sample from p->a[] to make room.
  82856. */
  82857. static void sampleInsert(Stat4Accum *p, Stat4Sample *pNew, int nEqZero){
  82858. Stat4Sample *pSample = 0;
  82859. int i;
  82860. assert( IsStat4 || nEqZero==0 );
  82861. #ifdef SQLITE_ENABLE_STAT4
  82862. if( pNew->isPSample==0 ){
  82863. Stat4Sample *pUpgrade = 0;
  82864. assert( pNew->anEq[pNew->iCol]>0 );
  82865. /* This sample is being added because the prefix that ends in column
  82866. ** iCol occurs many times in the table. However, if we have already
  82867. ** added a sample that shares this prefix, there is no need to add
  82868. ** this one. Instead, upgrade the priority of the highest priority
  82869. ** existing sample that shares this prefix. */
  82870. for(i=p->nSample-1; i>=0; i--){
  82871. Stat4Sample *pOld = &p->a[i];
  82872. if( pOld->anEq[pNew->iCol]==0 ){
  82873. if( pOld->isPSample ) return;
  82874. assert( pOld->iCol>pNew->iCol );
  82875. assert( sampleIsBetter(p, pNew, pOld) );
  82876. if( pUpgrade==0 || sampleIsBetter(p, pOld, pUpgrade) ){
  82877. pUpgrade = pOld;
  82878. }
  82879. }
  82880. }
  82881. if( pUpgrade ){
  82882. pUpgrade->iCol = pNew->iCol;
  82883. pUpgrade->anEq[pUpgrade->iCol] = pNew->anEq[pUpgrade->iCol];
  82884. goto find_new_min;
  82885. }
  82886. }
  82887. #endif
  82888. /* If necessary, remove sample iMin to make room for the new sample. */
  82889. if( p->nSample>=p->mxSample ){
  82890. Stat4Sample *pMin = &p->a[p->iMin];
  82891. tRowcnt *anEq = pMin->anEq;
  82892. tRowcnt *anLt = pMin->anLt;
  82893. tRowcnt *anDLt = pMin->anDLt;
  82894. sampleClear(p->db, pMin);
  82895. memmove(pMin, &pMin[1], sizeof(p->a[0])*(p->nSample-p->iMin-1));
  82896. pSample = &p->a[p->nSample-1];
  82897. pSample->nRowid = 0;
  82898. pSample->anEq = anEq;
  82899. pSample->anDLt = anDLt;
  82900. pSample->anLt = anLt;
  82901. p->nSample = p->mxSample-1;
  82902. }
  82903. /* The "rows less-than" for the rowid column must be greater than that
  82904. ** for the last sample in the p->a[] array. Otherwise, the samples would
  82905. ** be out of order. */
  82906. #ifdef SQLITE_ENABLE_STAT4
  82907. assert( p->nSample==0
  82908. || pNew->anLt[p->nCol-1] > p->a[p->nSample-1].anLt[p->nCol-1] );
  82909. #endif
  82910. /* Insert the new sample */
  82911. pSample = &p->a[p->nSample];
  82912. sampleCopy(p, pSample, pNew);
  82913. p->nSample++;
  82914. /* Zero the first nEqZero entries in the anEq[] array. */
  82915. memset(pSample->anEq, 0, sizeof(tRowcnt)*nEqZero);
  82916. #ifdef SQLITE_ENABLE_STAT4
  82917. find_new_min:
  82918. #endif
  82919. if( p->nSample>=p->mxSample ){
  82920. int iMin = -1;
  82921. for(i=0; i<p->mxSample; i++){
  82922. if( p->a[i].isPSample ) continue;
  82923. if( iMin<0 || sampleIsBetter(p, &p->a[iMin], &p->a[i]) ){
  82924. iMin = i;
  82925. }
  82926. }
  82927. assert( iMin>=0 );
  82928. p->iMin = iMin;
  82929. }
  82930. }
  82931. #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
  82932. /*
  82933. ** Field iChng of the index being scanned has changed. So at this point
  82934. ** p->current contains a sample that reflects the previous row of the
  82935. ** index. The value of anEq[iChng] and subsequent anEq[] elements are
  82936. ** correct at this point.
  82937. */
  82938. static void samplePushPrevious(Stat4Accum *p, int iChng){
  82939. #ifdef SQLITE_ENABLE_STAT4
  82940. int i;
  82941. /* Check if any samples from the aBest[] array should be pushed
  82942. ** into IndexSample.a[] at this point. */
  82943. for(i=(p->nCol-2); i>=iChng; i--){
  82944. Stat4Sample *pBest = &p->aBest[i];
  82945. pBest->anEq[i] = p->current.anEq[i];
  82946. if( p->nSample<p->mxSample || sampleIsBetter(p, pBest, &p->a[p->iMin]) ){
  82947. sampleInsert(p, pBest, i);
  82948. }
  82949. }
  82950. /* Update the anEq[] fields of any samples already collected. */
  82951. for(i=p->nSample-1; i>=0; i--){
  82952. int j;
  82953. for(j=iChng; j<p->nCol; j++){
  82954. if( p->a[i].anEq[j]==0 ) p->a[i].anEq[j] = p->current.anEq[j];
  82955. }
  82956. }
  82957. #endif
  82958. #if defined(SQLITE_ENABLE_STAT3) && !defined(SQLITE_ENABLE_STAT4)
  82959. if( iChng==0 ){
  82960. tRowcnt nLt = p->current.anLt[0];
  82961. tRowcnt nEq = p->current.anEq[0];
  82962. /* Check if this is to be a periodic sample. If so, add it. */
  82963. if( (nLt/p->nPSample)!=(nLt+nEq)/p->nPSample ){
  82964. p->current.isPSample = 1;
  82965. sampleInsert(p, &p->current, 0);
  82966. p->current.isPSample = 0;
  82967. }else
  82968. /* Or if it is a non-periodic sample. Add it in this case too. */
  82969. if( p->nSample<p->mxSample
  82970. || sampleIsBetter(p, &p->current, &p->a[p->iMin])
  82971. ){
  82972. sampleInsert(p, &p->current, 0);
  82973. }
  82974. }
  82975. #endif
  82976. #ifndef SQLITE_ENABLE_STAT3_OR_STAT4
  82977. UNUSED_PARAMETER( p );
  82978. UNUSED_PARAMETER( iChng );
  82979. #endif
  82980. }
  82981. /*
  82982. ** Implementation of the stat_push SQL function: stat_push(P,C,R)
  82983. ** Arguments:
  82984. **
  82985. ** P Pointer to the Stat4Accum object created by stat_init()
  82986. ** C Index of left-most column to differ from previous row
  82987. ** R Rowid for the current row. Might be a key record for
  82988. ** WITHOUT ROWID tables.
  82989. **
  82990. ** This SQL function always returns NULL. It's purpose it to accumulate
  82991. ** statistical data and/or samples in the Stat4Accum object about the
  82992. ** index being analyzed. The stat_get() SQL function will later be used to
  82993. ** extract relevant information for constructing the sqlite_statN tables.
  82994. **
  82995. ** The R parameter is only used for STAT3 and STAT4
  82996. */
  82997. static void statPush(
  82998. sqlite3_context *context,
  82999. int argc,
  83000. sqlite3_value **argv
  83001. ){
  83002. int i;
  83003. /* The three function arguments */
  83004. Stat4Accum *p = (Stat4Accum*)sqlite3_value_blob(argv[0]);
  83005. int iChng = sqlite3_value_int(argv[1]);
  83006. UNUSED_PARAMETER( argc );
  83007. UNUSED_PARAMETER( context );
  83008. assert( p->nCol>0 );
  83009. assert( iChng<p->nCol );
  83010. if( p->nRow==0 ){
  83011. /* This is the first call to this function. Do initialization. */
  83012. for(i=0; i<p->nCol; i++) p->current.anEq[i] = 1;
  83013. }else{
  83014. /* Second and subsequent calls get processed here */
  83015. samplePushPrevious(p, iChng);
  83016. /* Update anDLt[], anLt[] and anEq[] to reflect the values that apply
  83017. ** to the current row of the index. */
  83018. for(i=0; i<iChng; i++){
  83019. p->current.anEq[i]++;
  83020. }
  83021. for(i=iChng; i<p->nCol; i++){
  83022. p->current.anDLt[i]++;
  83023. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  83024. p->current.anLt[i] += p->current.anEq[i];
  83025. #endif
  83026. p->current.anEq[i] = 1;
  83027. }
  83028. }
  83029. p->nRow++;
  83030. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  83031. if( sqlite3_value_type(argv[2])==SQLITE_INTEGER ){
  83032. sampleSetRowidInt64(p->db, &p->current, sqlite3_value_int64(argv[2]));
  83033. }else{
  83034. sampleSetRowid(p->db, &p->current, sqlite3_value_bytes(argv[2]),
  83035. sqlite3_value_blob(argv[2]));
  83036. }
  83037. p->current.iHash = p->iPrn = p->iPrn*1103515245 + 12345;
  83038. #endif
  83039. #ifdef SQLITE_ENABLE_STAT4
  83040. {
  83041. tRowcnt nLt = p->current.anLt[p->nCol-1];
  83042. /* Check if this is to be a periodic sample. If so, add it. */
  83043. if( (nLt/p->nPSample)!=(nLt+1)/p->nPSample ){
  83044. p->current.isPSample = 1;
  83045. p->current.iCol = 0;
  83046. sampleInsert(p, &p->current, p->nCol-1);
  83047. p->current.isPSample = 0;
  83048. }
  83049. /* Update the aBest[] array. */
  83050. for(i=0; i<(p->nCol-1); i++){
  83051. p->current.iCol = i;
  83052. if( i>=iChng || sampleIsBetterPost(p, &p->current, &p->aBest[i]) ){
  83053. sampleCopy(p, &p->aBest[i], &p->current);
  83054. }
  83055. }
  83056. }
  83057. #endif
  83058. }
  83059. static const FuncDef statPushFuncdef = {
  83060. 2+IsStat34, /* nArg */
  83061. SQLITE_UTF8, /* funcFlags */
  83062. 0, /* pUserData */
  83063. 0, /* pNext */
  83064. statPush, /* xFunc */
  83065. 0, /* xStep */
  83066. 0, /* xFinalize */
  83067. "stat_push", /* zName */
  83068. 0, /* pHash */
  83069. 0 /* pDestructor */
  83070. };
  83071. #define STAT_GET_STAT1 0 /* "stat" column of stat1 table */
  83072. #define STAT_GET_ROWID 1 /* "rowid" column of stat[34] entry */
  83073. #define STAT_GET_NEQ 2 /* "neq" column of stat[34] entry */
  83074. #define STAT_GET_NLT 3 /* "nlt" column of stat[34] entry */
  83075. #define STAT_GET_NDLT 4 /* "ndlt" column of stat[34] entry */
  83076. /*
  83077. ** Implementation of the stat_get(P,J) SQL function. This routine is
  83078. ** used to query statistical information that has been gathered into
  83079. ** the Stat4Accum object by prior calls to stat_push(). The P parameter
  83080. ** has type BLOB but it is really just a pointer to the Stat4Accum object.
  83081. ** The content to returned is determined by the parameter J
  83082. ** which is one of the STAT_GET_xxxx values defined above.
  83083. **
  83084. ** If neither STAT3 nor STAT4 are enabled, then J is always
  83085. ** STAT_GET_STAT1 and is hence omitted and this routine becomes
  83086. ** a one-parameter function, stat_get(P), that always returns the
  83087. ** stat1 table entry information.
  83088. */
  83089. static void statGet(
  83090. sqlite3_context *context,
  83091. int argc,
  83092. sqlite3_value **argv
  83093. ){
  83094. Stat4Accum *p = (Stat4Accum*)sqlite3_value_blob(argv[0]);
  83095. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  83096. /* STAT3 and STAT4 have a parameter on this routine. */
  83097. int eCall = sqlite3_value_int(argv[1]);
  83098. assert( argc==2 );
  83099. assert( eCall==STAT_GET_STAT1 || eCall==STAT_GET_NEQ
  83100. || eCall==STAT_GET_ROWID || eCall==STAT_GET_NLT
  83101. || eCall==STAT_GET_NDLT
  83102. );
  83103. if( eCall==STAT_GET_STAT1 )
  83104. #else
  83105. assert( argc==1 );
  83106. #endif
  83107. {
  83108. /* Return the value to store in the "stat" column of the sqlite_stat1
  83109. ** table for this index.
  83110. **
  83111. ** The value is a string composed of a list of integers describing
  83112. ** the index. The first integer in the list is the total number of
  83113. ** entries in the index. There is one additional integer in the list
  83114. ** for each indexed column. This additional integer is an estimate of
  83115. ** the number of rows matched by a stabbing query on the index using
  83116. ** a key with the corresponding number of fields. In other words,
  83117. ** if the index is on columns (a,b) and the sqlite_stat1 value is
  83118. ** "100 10 2", then SQLite estimates that:
  83119. **
  83120. ** * the index contains 100 rows,
  83121. ** * "WHERE a=?" matches 10 rows, and
  83122. ** * "WHERE a=? AND b=?" matches 2 rows.
  83123. **
  83124. ** If D is the count of distinct values and K is the total number of
  83125. ** rows, then each estimate is computed as:
  83126. **
  83127. ** I = (K+D-1)/D
  83128. */
  83129. char *z;
  83130. int i;
  83131. char *zRet = sqlite3MallocZero( (p->nKeyCol+1)*25 );
  83132. if( zRet==0 ){
  83133. sqlite3_result_error_nomem(context);
  83134. return;
  83135. }
  83136. sqlite3_snprintf(24, zRet, "%llu", (u64)p->nRow);
  83137. z = zRet + sqlite3Strlen30(zRet);
  83138. for(i=0; i<p->nKeyCol; i++){
  83139. u64 nDistinct = p->current.anDLt[i] + 1;
  83140. u64 iVal = (p->nRow + nDistinct - 1) / nDistinct;
  83141. sqlite3_snprintf(24, z, " %llu", iVal);
  83142. z += sqlite3Strlen30(z);
  83143. assert( p->current.anEq[i] );
  83144. }
  83145. assert( z[0]=='\0' && z>zRet );
  83146. sqlite3_result_text(context, zRet, -1, sqlite3_free);
  83147. }
  83148. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  83149. else if( eCall==STAT_GET_ROWID ){
  83150. if( p->iGet<0 ){
  83151. samplePushPrevious(p, 0);
  83152. p->iGet = 0;
  83153. }
  83154. if( p->iGet<p->nSample ){
  83155. Stat4Sample *pS = p->a + p->iGet;
  83156. if( pS->nRowid==0 ){
  83157. sqlite3_result_int64(context, pS->u.iRowid);
  83158. }else{
  83159. sqlite3_result_blob(context, pS->u.aRowid, pS->nRowid,
  83160. SQLITE_TRANSIENT);
  83161. }
  83162. }
  83163. }else{
  83164. tRowcnt *aCnt = 0;
  83165. assert( p->iGet<p->nSample );
  83166. switch( eCall ){
  83167. case STAT_GET_NEQ: aCnt = p->a[p->iGet].anEq; break;
  83168. case STAT_GET_NLT: aCnt = p->a[p->iGet].anLt; break;
  83169. default: {
  83170. aCnt = p->a[p->iGet].anDLt;
  83171. p->iGet++;
  83172. break;
  83173. }
  83174. }
  83175. if( IsStat3 ){
  83176. sqlite3_result_int64(context, (i64)aCnt[0]);
  83177. }else{
  83178. char *zRet = sqlite3MallocZero(p->nCol * 25);
  83179. if( zRet==0 ){
  83180. sqlite3_result_error_nomem(context);
  83181. }else{
  83182. int i;
  83183. char *z = zRet;
  83184. for(i=0; i<p->nCol; i++){
  83185. sqlite3_snprintf(24, z, "%llu ", (u64)aCnt[i]);
  83186. z += sqlite3Strlen30(z);
  83187. }
  83188. assert( z[0]=='\0' && z>zRet );
  83189. z[-1] = '\0';
  83190. sqlite3_result_text(context, zRet, -1, sqlite3_free);
  83191. }
  83192. }
  83193. }
  83194. #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
  83195. #ifndef SQLITE_DEBUG
  83196. UNUSED_PARAMETER( argc );
  83197. #endif
  83198. }
  83199. static const FuncDef statGetFuncdef = {
  83200. 1+IsStat34, /* nArg */
  83201. SQLITE_UTF8, /* funcFlags */
  83202. 0, /* pUserData */
  83203. 0, /* pNext */
  83204. statGet, /* xFunc */
  83205. 0, /* xStep */
  83206. 0, /* xFinalize */
  83207. "stat_get", /* zName */
  83208. 0, /* pHash */
  83209. 0 /* pDestructor */
  83210. };
  83211. static void callStatGet(Vdbe *v, int regStat4, int iParam, int regOut){
  83212. assert( regOut!=regStat4 && regOut!=regStat4+1 );
  83213. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  83214. sqlite3VdbeAddOp2(v, OP_Integer, iParam, regStat4+1);
  83215. #elif SQLITE_DEBUG
  83216. assert( iParam==STAT_GET_STAT1 );
  83217. #else
  83218. UNUSED_PARAMETER( iParam );
  83219. #endif
  83220. sqlite3VdbeAddOp3(v, OP_Function, 0, regStat4, regOut);
  83221. sqlite3VdbeChangeP4(v, -1, (char*)&statGetFuncdef, P4_FUNCDEF);
  83222. sqlite3VdbeChangeP5(v, 1 + IsStat34);
  83223. }
  83224. /*
  83225. ** Generate code to do an analysis of all indices associated with
  83226. ** a single table.
  83227. */
  83228. static void analyzeOneTable(
  83229. Parse *pParse, /* Parser context */
  83230. Table *pTab, /* Table whose indices are to be analyzed */
  83231. Index *pOnlyIdx, /* If not NULL, only analyze this one index */
  83232. int iStatCur, /* Index of VdbeCursor that writes the sqlite_stat1 table */
  83233. int iMem, /* Available memory locations begin here */
  83234. int iTab /* Next available cursor */
  83235. ){
  83236. sqlite3 *db = pParse->db; /* Database handle */
  83237. Index *pIdx; /* An index to being analyzed */
  83238. int iIdxCur; /* Cursor open on index being analyzed */
  83239. int iTabCur; /* Table cursor */
  83240. Vdbe *v; /* The virtual machine being built up */
  83241. int i; /* Loop counter */
  83242. int jZeroRows = -1; /* Jump from here if number of rows is zero */
  83243. int iDb; /* Index of database containing pTab */
  83244. u8 needTableCnt = 1; /* True to count the table */
  83245. int regNewRowid = iMem++; /* Rowid for the inserted record */
  83246. int regStat4 = iMem++; /* Register to hold Stat4Accum object */
  83247. int regChng = iMem++; /* Index of changed index field */
  83248. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  83249. int regRowid = iMem++; /* Rowid argument passed to stat_push() */
  83250. #endif
  83251. int regTemp = iMem++; /* Temporary use register */
  83252. int regTabname = iMem++; /* Register containing table name */
  83253. int regIdxname = iMem++; /* Register containing index name */
  83254. int regStat1 = iMem++; /* Value for the stat column of sqlite_stat1 */
  83255. int regPrev = iMem; /* MUST BE LAST (see below) */
  83256. pParse->nMem = MAX(pParse->nMem, iMem);
  83257. v = sqlite3GetVdbe(pParse);
  83258. if( v==0 || NEVER(pTab==0) ){
  83259. return;
  83260. }
  83261. if( pTab->tnum==0 ){
  83262. /* Do not gather statistics on views or virtual tables */
  83263. return;
  83264. }
  83265. if( sqlite3_strnicmp(pTab->zName, "sqlite_", 7)==0 ){
  83266. /* Do not gather statistics on system tables */
  83267. return;
  83268. }
  83269. assert( sqlite3BtreeHoldsAllMutexes(db) );
  83270. iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  83271. assert( iDb>=0 );
  83272. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  83273. #ifndef SQLITE_OMIT_AUTHORIZATION
  83274. if( sqlite3AuthCheck(pParse, SQLITE_ANALYZE, pTab->zName, 0,
  83275. db->aDb[iDb].zName ) ){
  83276. return;
  83277. }
  83278. #endif
  83279. /* Establish a read-lock on the table at the shared-cache level.
  83280. ** Open a read-only cursor on the table. Also allocate a cursor number
  83281. ** to use for scanning indexes (iIdxCur). No index cursor is opened at
  83282. ** this time though. */
  83283. sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
  83284. iTabCur = iTab++;
  83285. iIdxCur = iTab++;
  83286. pParse->nTab = MAX(pParse->nTab, iTab);
  83287. sqlite3OpenTable(pParse, iTabCur, iDb, pTab, OP_OpenRead);
  83288. sqlite3VdbeAddOp4(v, OP_String8, 0, regTabname, 0, pTab->zName, 0);
  83289. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  83290. int nCol; /* Number of columns in pIdx. "N" */
  83291. int addrRewind; /* Address of "OP_Rewind iIdxCur" */
  83292. int addrNextRow; /* Address of "next_row:" */
  83293. const char *zIdxName; /* Name of the index */
  83294. int nColTest; /* Number of columns to test for changes */
  83295. if( pOnlyIdx && pOnlyIdx!=pIdx ) continue;
  83296. if( pIdx->pPartIdxWhere==0 ) needTableCnt = 0;
  83297. if( !HasRowid(pTab) && IsPrimaryKeyIndex(pIdx) ){
  83298. nCol = pIdx->nKeyCol;
  83299. zIdxName = pTab->zName;
  83300. nColTest = nCol - 1;
  83301. }else{
  83302. nCol = pIdx->nColumn;
  83303. zIdxName = pIdx->zName;
  83304. nColTest = pIdx->uniqNotNull ? pIdx->nKeyCol-1 : nCol-1;
  83305. }
  83306. /* Populate the register containing the index name. */
  83307. sqlite3VdbeAddOp4(v, OP_String8, 0, regIdxname, 0, zIdxName, 0);
  83308. VdbeComment((v, "Analysis for %s.%s", pTab->zName, zIdxName));
  83309. /*
  83310. ** Pseudo-code for loop that calls stat_push():
  83311. **
  83312. ** Rewind csr
  83313. ** if eof(csr) goto end_of_scan;
  83314. ** regChng = 0
  83315. ** goto chng_addr_0;
  83316. **
  83317. ** next_row:
  83318. ** regChng = 0
  83319. ** if( idx(0) != regPrev(0) ) goto chng_addr_0
  83320. ** regChng = 1
  83321. ** if( idx(1) != regPrev(1) ) goto chng_addr_1
  83322. ** ...
  83323. ** regChng = N
  83324. ** goto chng_addr_N
  83325. **
  83326. ** chng_addr_0:
  83327. ** regPrev(0) = idx(0)
  83328. ** chng_addr_1:
  83329. ** regPrev(1) = idx(1)
  83330. ** ...
  83331. **
  83332. ** endDistinctTest:
  83333. ** regRowid = idx(rowid)
  83334. ** stat_push(P, regChng, regRowid)
  83335. ** Next csr
  83336. ** if !eof(csr) goto next_row;
  83337. **
  83338. ** end_of_scan:
  83339. */
  83340. /* Make sure there are enough memory cells allocated to accommodate
  83341. ** the regPrev array and a trailing rowid (the rowid slot is required
  83342. ** when building a record to insert into the sample column of
  83343. ** the sqlite_stat4 table. */
  83344. pParse->nMem = MAX(pParse->nMem, regPrev+nColTest);
  83345. /* Open a read-only cursor on the index being analyzed. */
  83346. assert( iDb==sqlite3SchemaToIndex(db, pIdx->pSchema) );
  83347. sqlite3VdbeAddOp3(v, OP_OpenRead, iIdxCur, pIdx->tnum, iDb);
  83348. sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
  83349. VdbeComment((v, "%s", pIdx->zName));
  83350. /* Invoke the stat_init() function. The arguments are:
  83351. **
  83352. ** (1) the number of columns in the index including the rowid
  83353. ** (or for a WITHOUT ROWID table, the number of PK columns),
  83354. ** (2) the number of columns in the key without the rowid/pk
  83355. ** (3) the number of rows in the index,
  83356. **
  83357. **
  83358. ** The third argument is only used for STAT3 and STAT4
  83359. */
  83360. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  83361. sqlite3VdbeAddOp2(v, OP_Count, iIdxCur, regStat4+3);
  83362. #endif
  83363. sqlite3VdbeAddOp2(v, OP_Integer, nCol, regStat4+1);
  83364. sqlite3VdbeAddOp2(v, OP_Integer, pIdx->nKeyCol, regStat4+2);
  83365. sqlite3VdbeAddOp3(v, OP_Function, 0, regStat4+1, regStat4);
  83366. sqlite3VdbeChangeP4(v, -1, (char*)&statInitFuncdef, P4_FUNCDEF);
  83367. sqlite3VdbeChangeP5(v, 2+IsStat34);
  83368. /* Implementation of the following:
  83369. **
  83370. ** Rewind csr
  83371. ** if eof(csr) goto end_of_scan;
  83372. ** regChng = 0
  83373. ** goto next_push_0;
  83374. **
  83375. */
  83376. addrRewind = sqlite3VdbeAddOp1(v, OP_Rewind, iIdxCur);
  83377. VdbeCoverage(v);
  83378. sqlite3VdbeAddOp2(v, OP_Integer, 0, regChng);
  83379. addrNextRow = sqlite3VdbeCurrentAddr(v);
  83380. if( nColTest>0 ){
  83381. int endDistinctTest = sqlite3VdbeMakeLabel(v);
  83382. int *aGotoChng; /* Array of jump instruction addresses */
  83383. aGotoChng = sqlite3DbMallocRaw(db, sizeof(int)*nColTest);
  83384. if( aGotoChng==0 ) continue;
  83385. /*
  83386. ** next_row:
  83387. ** regChng = 0
  83388. ** if( idx(0) != regPrev(0) ) goto chng_addr_0
  83389. ** regChng = 1
  83390. ** if( idx(1) != regPrev(1) ) goto chng_addr_1
  83391. ** ...
  83392. ** regChng = N
  83393. ** goto endDistinctTest
  83394. */
  83395. sqlite3VdbeAddOp0(v, OP_Goto);
  83396. addrNextRow = sqlite3VdbeCurrentAddr(v);
  83397. if( nColTest==1 && pIdx->nKeyCol==1 && IsUniqueIndex(pIdx) ){
  83398. /* For a single-column UNIQUE index, once we have found a non-NULL
  83399. ** row, we know that all the rest will be distinct, so skip
  83400. ** subsequent distinctness tests. */
  83401. sqlite3VdbeAddOp2(v, OP_NotNull, regPrev, endDistinctTest);
  83402. VdbeCoverage(v);
  83403. }
  83404. for(i=0; i<nColTest; i++){
  83405. char *pColl = (char*)sqlite3LocateCollSeq(pParse, pIdx->azColl[i]);
  83406. sqlite3VdbeAddOp2(v, OP_Integer, i, regChng);
  83407. sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, i, regTemp);
  83408. aGotoChng[i] =
  83409. sqlite3VdbeAddOp4(v, OP_Ne, regTemp, 0, regPrev+i, pColl, P4_COLLSEQ);
  83410. sqlite3VdbeChangeP5(v, SQLITE_NULLEQ);
  83411. VdbeCoverage(v);
  83412. }
  83413. sqlite3VdbeAddOp2(v, OP_Integer, nColTest, regChng);
  83414. sqlite3VdbeAddOp2(v, OP_Goto, 0, endDistinctTest);
  83415. /*
  83416. ** chng_addr_0:
  83417. ** regPrev(0) = idx(0)
  83418. ** chng_addr_1:
  83419. ** regPrev(1) = idx(1)
  83420. ** ...
  83421. */
  83422. sqlite3VdbeJumpHere(v, addrNextRow-1);
  83423. for(i=0; i<nColTest; i++){
  83424. sqlite3VdbeJumpHere(v, aGotoChng[i]);
  83425. sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, i, regPrev+i);
  83426. }
  83427. sqlite3VdbeResolveLabel(v, endDistinctTest);
  83428. sqlite3DbFree(db, aGotoChng);
  83429. }
  83430. /*
  83431. ** chng_addr_N:
  83432. ** regRowid = idx(rowid) // STAT34 only
  83433. ** stat_push(P, regChng, regRowid) // 3rd parameter STAT34 only
  83434. ** Next csr
  83435. ** if !eof(csr) goto next_row;
  83436. */
  83437. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  83438. assert( regRowid==(regStat4+2) );
  83439. if( HasRowid(pTab) ){
  83440. sqlite3VdbeAddOp2(v, OP_IdxRowid, iIdxCur, regRowid);
  83441. }else{
  83442. Index *pPk = sqlite3PrimaryKeyIndex(pIdx->pTable);
  83443. int j, k, regKey;
  83444. regKey = sqlite3GetTempRange(pParse, pPk->nKeyCol);
  83445. for(j=0; j<pPk->nKeyCol; j++){
  83446. k = sqlite3ColumnOfIndex(pIdx, pPk->aiColumn[j]);
  83447. sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, k, regKey+j);
  83448. VdbeComment((v, "%s", pTab->aCol[pPk->aiColumn[j]].zName));
  83449. }
  83450. sqlite3VdbeAddOp3(v, OP_MakeRecord, regKey, pPk->nKeyCol, regRowid);
  83451. sqlite3ReleaseTempRange(pParse, regKey, pPk->nKeyCol);
  83452. }
  83453. #endif
  83454. assert( regChng==(regStat4+1) );
  83455. sqlite3VdbeAddOp3(v, OP_Function, 1, regStat4, regTemp);
  83456. sqlite3VdbeChangeP4(v, -1, (char*)&statPushFuncdef, P4_FUNCDEF);
  83457. sqlite3VdbeChangeP5(v, 2+IsStat34);
  83458. sqlite3VdbeAddOp2(v, OP_Next, iIdxCur, addrNextRow); VdbeCoverage(v);
  83459. /* Add the entry to the stat1 table. */
  83460. callStatGet(v, regStat4, STAT_GET_STAT1, regStat1);
  83461. assert( "BBB"[0]==SQLITE_AFF_TEXT );
  83462. sqlite3VdbeAddOp4(v, OP_MakeRecord, regTabname, 3, regTemp, "BBB", 0);
  83463. sqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur, regNewRowid);
  83464. sqlite3VdbeAddOp3(v, OP_Insert, iStatCur, regTemp, regNewRowid);
  83465. sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
  83466. /* Add the entries to the stat3 or stat4 table. */
  83467. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  83468. {
  83469. int regEq = regStat1;
  83470. int regLt = regStat1+1;
  83471. int regDLt = regStat1+2;
  83472. int regSample = regStat1+3;
  83473. int regCol = regStat1+4;
  83474. int regSampleRowid = regCol + nCol;
  83475. int addrNext;
  83476. int addrIsNull;
  83477. u8 seekOp = HasRowid(pTab) ? OP_NotExists : OP_NotFound;
  83478. pParse->nMem = MAX(pParse->nMem, regCol+nCol);
  83479. addrNext = sqlite3VdbeCurrentAddr(v);
  83480. callStatGet(v, regStat4, STAT_GET_ROWID, regSampleRowid);
  83481. addrIsNull = sqlite3VdbeAddOp1(v, OP_IsNull, regSampleRowid);
  83482. VdbeCoverage(v);
  83483. callStatGet(v, regStat4, STAT_GET_NEQ, regEq);
  83484. callStatGet(v, regStat4, STAT_GET_NLT, regLt);
  83485. callStatGet(v, regStat4, STAT_GET_NDLT, regDLt);
  83486. sqlite3VdbeAddOp4Int(v, seekOp, iTabCur, addrNext, regSampleRowid, 0);
  83487. /* We know that the regSampleRowid row exists because it was read by
  83488. ** the previous loop. Thus the not-found jump of seekOp will never
  83489. ** be taken */
  83490. VdbeCoverageNeverTaken(v);
  83491. #ifdef SQLITE_ENABLE_STAT3
  83492. sqlite3ExprCodeGetColumnOfTable(v, pTab, iTabCur,
  83493. pIdx->aiColumn[0], regSample);
  83494. #else
  83495. for(i=0; i<nCol; i++){
  83496. i16 iCol = pIdx->aiColumn[i];
  83497. sqlite3ExprCodeGetColumnOfTable(v, pTab, iTabCur, iCol, regCol+i);
  83498. }
  83499. sqlite3VdbeAddOp3(v, OP_MakeRecord, regCol, nCol, regSample);
  83500. #endif
  83501. sqlite3VdbeAddOp3(v, OP_MakeRecord, regTabname, 6, regTemp);
  83502. sqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur+1, regNewRowid);
  83503. sqlite3VdbeAddOp3(v, OP_Insert, iStatCur+1, regTemp, regNewRowid);
  83504. sqlite3VdbeAddOp2(v, OP_Goto, 1, addrNext); /* P1==1 for end-of-loop */
  83505. sqlite3VdbeJumpHere(v, addrIsNull);
  83506. }
  83507. #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
  83508. /* End of analysis */
  83509. sqlite3VdbeJumpHere(v, addrRewind);
  83510. }
  83511. /* Create a single sqlite_stat1 entry containing NULL as the index
  83512. ** name and the row count as the content.
  83513. */
  83514. if( pOnlyIdx==0 && needTableCnt ){
  83515. VdbeComment((v, "%s", pTab->zName));
  83516. sqlite3VdbeAddOp2(v, OP_Count, iTabCur, regStat1);
  83517. jZeroRows = sqlite3VdbeAddOp1(v, OP_IfNot, regStat1); VdbeCoverage(v);
  83518. sqlite3VdbeAddOp2(v, OP_Null, 0, regIdxname);
  83519. assert( "BBB"[0]==SQLITE_AFF_TEXT );
  83520. sqlite3VdbeAddOp4(v, OP_MakeRecord, regTabname, 3, regTemp, "BBB", 0);
  83521. sqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur, regNewRowid);
  83522. sqlite3VdbeAddOp3(v, OP_Insert, iStatCur, regTemp, regNewRowid);
  83523. sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
  83524. sqlite3VdbeJumpHere(v, jZeroRows);
  83525. }
  83526. }
  83527. /*
  83528. ** Generate code that will cause the most recent index analysis to
  83529. ** be loaded into internal hash tables where is can be used.
  83530. */
  83531. static void loadAnalysis(Parse *pParse, int iDb){
  83532. Vdbe *v = sqlite3GetVdbe(pParse);
  83533. if( v ){
  83534. sqlite3VdbeAddOp1(v, OP_LoadAnalysis, iDb);
  83535. }
  83536. }
  83537. /*
  83538. ** Generate code that will do an analysis of an entire database
  83539. */
  83540. static void analyzeDatabase(Parse *pParse, int iDb){
  83541. sqlite3 *db = pParse->db;
  83542. Schema *pSchema = db->aDb[iDb].pSchema; /* Schema of database iDb */
  83543. HashElem *k;
  83544. int iStatCur;
  83545. int iMem;
  83546. int iTab;
  83547. sqlite3BeginWriteOperation(pParse, 0, iDb);
  83548. iStatCur = pParse->nTab;
  83549. pParse->nTab += 3;
  83550. openStatTable(pParse, iDb, iStatCur, 0, 0);
  83551. iMem = pParse->nMem+1;
  83552. iTab = pParse->nTab;
  83553. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  83554. for(k=sqliteHashFirst(&pSchema->tblHash); k; k=sqliteHashNext(k)){
  83555. Table *pTab = (Table*)sqliteHashData(k);
  83556. analyzeOneTable(pParse, pTab, 0, iStatCur, iMem, iTab);
  83557. }
  83558. loadAnalysis(pParse, iDb);
  83559. }
  83560. /*
  83561. ** Generate code that will do an analysis of a single table in
  83562. ** a database. If pOnlyIdx is not NULL then it is a single index
  83563. ** in pTab that should be analyzed.
  83564. */
  83565. static void analyzeTable(Parse *pParse, Table *pTab, Index *pOnlyIdx){
  83566. int iDb;
  83567. int iStatCur;
  83568. assert( pTab!=0 );
  83569. assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
  83570. iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
  83571. sqlite3BeginWriteOperation(pParse, 0, iDb);
  83572. iStatCur = pParse->nTab;
  83573. pParse->nTab += 3;
  83574. if( pOnlyIdx ){
  83575. openStatTable(pParse, iDb, iStatCur, pOnlyIdx->zName, "idx");
  83576. }else{
  83577. openStatTable(pParse, iDb, iStatCur, pTab->zName, "tbl");
  83578. }
  83579. analyzeOneTable(pParse, pTab, pOnlyIdx, iStatCur,pParse->nMem+1,pParse->nTab);
  83580. loadAnalysis(pParse, iDb);
  83581. }
  83582. /*
  83583. ** Generate code for the ANALYZE command. The parser calls this routine
  83584. ** when it recognizes an ANALYZE command.
  83585. **
  83586. ** ANALYZE -- 1
  83587. ** ANALYZE <database> -- 2
  83588. ** ANALYZE ?<database>.?<tablename> -- 3
  83589. **
  83590. ** Form 1 causes all indices in all attached databases to be analyzed.
  83591. ** Form 2 analyzes all indices the single database named.
  83592. ** Form 3 analyzes all indices associated with the named table.
  83593. */
  83594. SQLITE_PRIVATE void sqlite3Analyze(Parse *pParse, Token *pName1, Token *pName2){
  83595. sqlite3 *db = pParse->db;
  83596. int iDb;
  83597. int i;
  83598. char *z, *zDb;
  83599. Table *pTab;
  83600. Index *pIdx;
  83601. Token *pTableName;
  83602. Vdbe *v;
  83603. /* Read the database schema. If an error occurs, leave an error message
  83604. ** and code in pParse and return NULL. */
  83605. assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
  83606. if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
  83607. return;
  83608. }
  83609. assert( pName2!=0 || pName1==0 );
  83610. if( pName1==0 ){
  83611. /* Form 1: Analyze everything */
  83612. for(i=0; i<db->nDb; i++){
  83613. if( i==1 ) continue; /* Do not analyze the TEMP database */
  83614. analyzeDatabase(pParse, i);
  83615. }
  83616. }else if( pName2->n==0 ){
  83617. /* Form 2: Analyze the database or table named */
  83618. iDb = sqlite3FindDb(db, pName1);
  83619. if( iDb>=0 ){
  83620. analyzeDatabase(pParse, iDb);
  83621. }else{
  83622. z = sqlite3NameFromToken(db, pName1);
  83623. if( z ){
  83624. if( (pIdx = sqlite3FindIndex(db, z, 0))!=0 ){
  83625. analyzeTable(pParse, pIdx->pTable, pIdx);
  83626. }else if( (pTab = sqlite3LocateTable(pParse, 0, z, 0))!=0 ){
  83627. analyzeTable(pParse, pTab, 0);
  83628. }
  83629. sqlite3DbFree(db, z);
  83630. }
  83631. }
  83632. }else{
  83633. /* Form 3: Analyze the fully qualified table name */
  83634. iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pTableName);
  83635. if( iDb>=0 ){
  83636. zDb = db->aDb[iDb].zName;
  83637. z = sqlite3NameFromToken(db, pTableName);
  83638. if( z ){
  83639. if( (pIdx = sqlite3FindIndex(db, z, zDb))!=0 ){
  83640. analyzeTable(pParse, pIdx->pTable, pIdx);
  83641. }else if( (pTab = sqlite3LocateTable(pParse, 0, z, zDb))!=0 ){
  83642. analyzeTable(pParse, pTab, 0);
  83643. }
  83644. sqlite3DbFree(db, z);
  83645. }
  83646. }
  83647. }
  83648. v = sqlite3GetVdbe(pParse);
  83649. if( v ) sqlite3VdbeAddOp0(v, OP_Expire);
  83650. }
  83651. /*
  83652. ** Used to pass information from the analyzer reader through to the
  83653. ** callback routine.
  83654. */
  83655. typedef struct analysisInfo analysisInfo;
  83656. struct analysisInfo {
  83657. sqlite3 *db;
  83658. const char *zDatabase;
  83659. };
  83660. /*
  83661. ** The first argument points to a nul-terminated string containing a
  83662. ** list of space separated integers. Read the first nOut of these into
  83663. ** the array aOut[].
  83664. */
  83665. static void decodeIntArray(
  83666. char *zIntArray, /* String containing int array to decode */
  83667. int nOut, /* Number of slots in aOut[] */
  83668. tRowcnt *aOut, /* Store integers here */
  83669. LogEst *aLog, /* Or, if aOut==0, here */
  83670. Index *pIndex /* Handle extra flags for this index, if not NULL */
  83671. ){
  83672. char *z = zIntArray;
  83673. int c;
  83674. int i;
  83675. tRowcnt v;
  83676. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  83677. if( z==0 ) z = "";
  83678. #else
  83679. assert( z!=0 );
  83680. #endif
  83681. for(i=0; *z && i<nOut; i++){
  83682. v = 0;
  83683. while( (c=z[0])>='0' && c<='9' ){
  83684. v = v*10 + c - '0';
  83685. z++;
  83686. }
  83687. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  83688. if( aOut ) aOut[i] = v;
  83689. if( aLog ) aLog[i] = sqlite3LogEst(v);
  83690. #else
  83691. assert( aOut==0 );
  83692. UNUSED_PARAMETER(aOut);
  83693. assert( aLog!=0 );
  83694. aLog[i] = sqlite3LogEst(v);
  83695. #endif
  83696. if( *z==' ' ) z++;
  83697. }
  83698. #ifndef SQLITE_ENABLE_STAT3_OR_STAT4
  83699. assert( pIndex!=0 ); {
  83700. #else
  83701. if( pIndex ){
  83702. #endif
  83703. pIndex->bUnordered = 0;
  83704. pIndex->noSkipScan = 0;
  83705. while( z[0] ){
  83706. if( sqlite3_strglob("unordered*", z)==0 ){
  83707. pIndex->bUnordered = 1;
  83708. }else if( sqlite3_strglob("sz=[0-9]*", z)==0 ){
  83709. pIndex->szIdxRow = sqlite3LogEst(sqlite3Atoi(z+3));
  83710. }else if( sqlite3_strglob("noskipscan*", z)==0 ){
  83711. pIndex->noSkipScan = 1;
  83712. }
  83713. #ifdef SQLITE_ENABLE_COSTMULT
  83714. else if( sqlite3_strglob("costmult=[0-9]*",z)==0 ){
  83715. pIndex->pTable->costMult = sqlite3LogEst(sqlite3Atoi(z+9));
  83716. }
  83717. #endif
  83718. while( z[0]!=0 && z[0]!=' ' ) z++;
  83719. while( z[0]==' ' ) z++;
  83720. }
  83721. }
  83722. }
  83723. /*
  83724. ** This callback is invoked once for each index when reading the
  83725. ** sqlite_stat1 table.
  83726. **
  83727. ** argv[0] = name of the table
  83728. ** argv[1] = name of the index (might be NULL)
  83729. ** argv[2] = results of analysis - on integer for each column
  83730. **
  83731. ** Entries for which argv[1]==NULL simply record the number of rows in
  83732. ** the table.
  83733. */
  83734. static int analysisLoader(void *pData, int argc, char **argv, char **NotUsed){
  83735. analysisInfo *pInfo = (analysisInfo*)pData;
  83736. Index *pIndex;
  83737. Table *pTable;
  83738. const char *z;
  83739. assert( argc==3 );
  83740. UNUSED_PARAMETER2(NotUsed, argc);
  83741. if( argv==0 || argv[0]==0 || argv[2]==0 ){
  83742. return 0;
  83743. }
  83744. pTable = sqlite3FindTable(pInfo->db, argv[0], pInfo->zDatabase);
  83745. if( pTable==0 ){
  83746. return 0;
  83747. }
  83748. if( argv[1]==0 ){
  83749. pIndex = 0;
  83750. }else if( sqlite3_stricmp(argv[0],argv[1])==0 ){
  83751. pIndex = sqlite3PrimaryKeyIndex(pTable);
  83752. }else{
  83753. pIndex = sqlite3FindIndex(pInfo->db, argv[1], pInfo->zDatabase);
  83754. }
  83755. z = argv[2];
  83756. if( pIndex ){
  83757. tRowcnt *aiRowEst = 0;
  83758. int nCol = pIndex->nKeyCol+1;
  83759. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  83760. /* Index.aiRowEst may already be set here if there are duplicate
  83761. ** sqlite_stat1 entries for this index. In that case just clobber
  83762. ** the old data with the new instead of allocating a new array. */
  83763. if( pIndex->aiRowEst==0 ){
  83764. pIndex->aiRowEst = (tRowcnt*)sqlite3MallocZero(sizeof(tRowcnt) * nCol);
  83765. if( pIndex->aiRowEst==0 ) pInfo->db->mallocFailed = 1;
  83766. }
  83767. aiRowEst = pIndex->aiRowEst;
  83768. #endif
  83769. pIndex->bUnordered = 0;
  83770. decodeIntArray((char*)z, nCol, aiRowEst, pIndex->aiRowLogEst, pIndex);
  83771. if( pIndex->pPartIdxWhere==0 ) pTable->nRowLogEst = pIndex->aiRowLogEst[0];
  83772. }else{
  83773. Index fakeIdx;
  83774. fakeIdx.szIdxRow = pTable->szTabRow;
  83775. #ifdef SQLITE_ENABLE_COSTMULT
  83776. fakeIdx.pTable = pTable;
  83777. #endif
  83778. decodeIntArray((char*)z, 1, 0, &pTable->nRowLogEst, &fakeIdx);
  83779. pTable->szTabRow = fakeIdx.szIdxRow;
  83780. }
  83781. return 0;
  83782. }
  83783. /*
  83784. ** If the Index.aSample variable is not NULL, delete the aSample[] array
  83785. ** and its contents.
  83786. */
  83787. SQLITE_PRIVATE void sqlite3DeleteIndexSamples(sqlite3 *db, Index *pIdx){
  83788. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  83789. if( pIdx->aSample ){
  83790. int j;
  83791. for(j=0; j<pIdx->nSample; j++){
  83792. IndexSample *p = &pIdx->aSample[j];
  83793. sqlite3DbFree(db, p->p);
  83794. }
  83795. sqlite3DbFree(db, pIdx->aSample);
  83796. }
  83797. if( db && db->pnBytesFreed==0 ){
  83798. pIdx->nSample = 0;
  83799. pIdx->aSample = 0;
  83800. }
  83801. #else
  83802. UNUSED_PARAMETER(db);
  83803. UNUSED_PARAMETER(pIdx);
  83804. #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
  83805. }
  83806. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  83807. /*
  83808. ** Populate the pIdx->aAvgEq[] array based on the samples currently
  83809. ** stored in pIdx->aSample[].
  83810. */
  83811. static void initAvgEq(Index *pIdx){
  83812. if( pIdx ){
  83813. IndexSample *aSample = pIdx->aSample;
  83814. IndexSample *pFinal = &aSample[pIdx->nSample-1];
  83815. int iCol;
  83816. int nCol = 1;
  83817. if( pIdx->nSampleCol>1 ){
  83818. /* If this is stat4 data, then calculate aAvgEq[] values for all
  83819. ** sample columns except the last. The last is always set to 1, as
  83820. ** once the trailing PK fields are considered all index keys are
  83821. ** unique. */
  83822. nCol = pIdx->nSampleCol-1;
  83823. pIdx->aAvgEq[nCol] = 1;
  83824. }
  83825. for(iCol=0; iCol<nCol; iCol++){
  83826. int nSample = pIdx->nSample;
  83827. int i; /* Used to iterate through samples */
  83828. tRowcnt sumEq = 0; /* Sum of the nEq values */
  83829. tRowcnt avgEq = 0;
  83830. tRowcnt nRow; /* Number of rows in index */
  83831. i64 nSum100 = 0; /* Number of terms contributing to sumEq */
  83832. i64 nDist100; /* Number of distinct values in index */
  83833. if( !pIdx->aiRowEst || iCol>=pIdx->nKeyCol || pIdx->aiRowEst[iCol+1]==0 ){
  83834. nRow = pFinal->anLt[iCol];
  83835. nDist100 = (i64)100 * pFinal->anDLt[iCol];
  83836. nSample--;
  83837. }else{
  83838. nRow = pIdx->aiRowEst[0];
  83839. nDist100 = ((i64)100 * pIdx->aiRowEst[0]) / pIdx->aiRowEst[iCol+1];
  83840. }
  83841. pIdx->nRowEst0 = nRow;
  83842. /* Set nSum to the number of distinct (iCol+1) field prefixes that
  83843. ** occur in the stat4 table for this index. Set sumEq to the sum of
  83844. ** the nEq values for column iCol for the same set (adding the value
  83845. ** only once where there exist duplicate prefixes). */
  83846. for(i=0; i<nSample; i++){
  83847. if( i==(pIdx->nSample-1)
  83848. || aSample[i].anDLt[iCol]!=aSample[i+1].anDLt[iCol]
  83849. ){
  83850. sumEq += aSample[i].anEq[iCol];
  83851. nSum100 += 100;
  83852. }
  83853. }
  83854. if( nDist100>nSum100 ){
  83855. avgEq = ((i64)100 * (nRow - sumEq))/(nDist100 - nSum100);
  83856. }
  83857. if( avgEq==0 ) avgEq = 1;
  83858. pIdx->aAvgEq[iCol] = avgEq;
  83859. }
  83860. }
  83861. }
  83862. /*
  83863. ** Look up an index by name. Or, if the name of a WITHOUT ROWID table
  83864. ** is supplied instead, find the PRIMARY KEY index for that table.
  83865. */
  83866. static Index *findIndexOrPrimaryKey(
  83867. sqlite3 *db,
  83868. const char *zName,
  83869. const char *zDb
  83870. ){
  83871. Index *pIdx = sqlite3FindIndex(db, zName, zDb);
  83872. if( pIdx==0 ){
  83873. Table *pTab = sqlite3FindTable(db, zName, zDb);
  83874. if( pTab && !HasRowid(pTab) ) pIdx = sqlite3PrimaryKeyIndex(pTab);
  83875. }
  83876. return pIdx;
  83877. }
  83878. /*
  83879. ** Load the content from either the sqlite_stat4 or sqlite_stat3 table
  83880. ** into the relevant Index.aSample[] arrays.
  83881. **
  83882. ** Arguments zSql1 and zSql2 must point to SQL statements that return
  83883. ** data equivalent to the following (statements are different for stat3,
  83884. ** see the caller of this function for details):
  83885. **
  83886. ** zSql1: SELECT idx,count(*) FROM %Q.sqlite_stat4 GROUP BY idx
  83887. ** zSql2: SELECT idx,neq,nlt,ndlt,sample FROM %Q.sqlite_stat4
  83888. **
  83889. ** where %Q is replaced with the database name before the SQL is executed.
  83890. */
  83891. static int loadStatTbl(
  83892. sqlite3 *db, /* Database handle */
  83893. int bStat3, /* Assume single column records only */
  83894. const char *zSql1, /* SQL statement 1 (see above) */
  83895. const char *zSql2, /* SQL statement 2 (see above) */
  83896. const char *zDb /* Database name (e.g. "main") */
  83897. ){
  83898. int rc; /* Result codes from subroutines */
  83899. sqlite3_stmt *pStmt = 0; /* An SQL statement being run */
  83900. char *zSql; /* Text of the SQL statement */
  83901. Index *pPrevIdx = 0; /* Previous index in the loop */
  83902. IndexSample *pSample; /* A slot in pIdx->aSample[] */
  83903. assert( db->lookaside.bEnabled==0 );
  83904. zSql = sqlite3MPrintf(db, zSql1, zDb);
  83905. if( !zSql ){
  83906. return SQLITE_NOMEM;
  83907. }
  83908. rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
  83909. sqlite3DbFree(db, zSql);
  83910. if( rc ) return rc;
  83911. while( sqlite3_step(pStmt)==SQLITE_ROW ){
  83912. int nIdxCol = 1; /* Number of columns in stat4 records */
  83913. char *zIndex; /* Index name */
  83914. Index *pIdx; /* Pointer to the index object */
  83915. int nSample; /* Number of samples */
  83916. int nByte; /* Bytes of space required */
  83917. int i; /* Bytes of space required */
  83918. tRowcnt *pSpace;
  83919. zIndex = (char *)sqlite3_column_text(pStmt, 0);
  83920. if( zIndex==0 ) continue;
  83921. nSample = sqlite3_column_int(pStmt, 1);
  83922. pIdx = findIndexOrPrimaryKey(db, zIndex, zDb);
  83923. assert( pIdx==0 || bStat3 || pIdx->nSample==0 );
  83924. /* Index.nSample is non-zero at this point if data has already been
  83925. ** loaded from the stat4 table. In this case ignore stat3 data. */
  83926. if( pIdx==0 || pIdx->nSample ) continue;
  83927. if( bStat3==0 ){
  83928. assert( !HasRowid(pIdx->pTable) || pIdx->nColumn==pIdx->nKeyCol+1 );
  83929. if( !HasRowid(pIdx->pTable) && IsPrimaryKeyIndex(pIdx) ){
  83930. nIdxCol = pIdx->nKeyCol;
  83931. }else{
  83932. nIdxCol = pIdx->nColumn;
  83933. }
  83934. }
  83935. pIdx->nSampleCol = nIdxCol;
  83936. nByte = sizeof(IndexSample) * nSample;
  83937. nByte += sizeof(tRowcnt) * nIdxCol * 3 * nSample;
  83938. nByte += nIdxCol * sizeof(tRowcnt); /* Space for Index.aAvgEq[] */
  83939. pIdx->aSample = sqlite3DbMallocZero(db, nByte);
  83940. if( pIdx->aSample==0 ){
  83941. sqlite3_finalize(pStmt);
  83942. return SQLITE_NOMEM;
  83943. }
  83944. pSpace = (tRowcnt*)&pIdx->aSample[nSample];
  83945. pIdx->aAvgEq = pSpace; pSpace += nIdxCol;
  83946. for(i=0; i<nSample; i++){
  83947. pIdx->aSample[i].anEq = pSpace; pSpace += nIdxCol;
  83948. pIdx->aSample[i].anLt = pSpace; pSpace += nIdxCol;
  83949. pIdx->aSample[i].anDLt = pSpace; pSpace += nIdxCol;
  83950. }
  83951. assert( ((u8*)pSpace)-nByte==(u8*)(pIdx->aSample) );
  83952. }
  83953. rc = sqlite3_finalize(pStmt);
  83954. if( rc ) return rc;
  83955. zSql = sqlite3MPrintf(db, zSql2, zDb);
  83956. if( !zSql ){
  83957. return SQLITE_NOMEM;
  83958. }
  83959. rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
  83960. sqlite3DbFree(db, zSql);
  83961. if( rc ) return rc;
  83962. while( sqlite3_step(pStmt)==SQLITE_ROW ){
  83963. char *zIndex; /* Index name */
  83964. Index *pIdx; /* Pointer to the index object */
  83965. int nCol = 1; /* Number of columns in index */
  83966. zIndex = (char *)sqlite3_column_text(pStmt, 0);
  83967. if( zIndex==0 ) continue;
  83968. pIdx = findIndexOrPrimaryKey(db, zIndex, zDb);
  83969. if( pIdx==0 ) continue;
  83970. /* This next condition is true if data has already been loaded from
  83971. ** the sqlite_stat4 table. In this case ignore stat3 data. */
  83972. nCol = pIdx->nSampleCol;
  83973. if( bStat3 && nCol>1 ) continue;
  83974. if( pIdx!=pPrevIdx ){
  83975. initAvgEq(pPrevIdx);
  83976. pPrevIdx = pIdx;
  83977. }
  83978. pSample = &pIdx->aSample[pIdx->nSample];
  83979. decodeIntArray((char*)sqlite3_column_text(pStmt,1),nCol,pSample->anEq,0,0);
  83980. decodeIntArray((char*)sqlite3_column_text(pStmt,2),nCol,pSample->anLt,0,0);
  83981. decodeIntArray((char*)sqlite3_column_text(pStmt,3),nCol,pSample->anDLt,0,0);
  83982. /* Take a copy of the sample. Add two 0x00 bytes the end of the buffer.
  83983. ** This is in case the sample record is corrupted. In that case, the
  83984. ** sqlite3VdbeRecordCompare() may read up to two varints past the
  83985. ** end of the allocated buffer before it realizes it is dealing with
  83986. ** a corrupt record. Adding the two 0x00 bytes prevents this from causing
  83987. ** a buffer overread. */
  83988. pSample->n = sqlite3_column_bytes(pStmt, 4);
  83989. pSample->p = sqlite3DbMallocZero(db, pSample->n + 2);
  83990. if( pSample->p==0 ){
  83991. sqlite3_finalize(pStmt);
  83992. return SQLITE_NOMEM;
  83993. }
  83994. memcpy(pSample->p, sqlite3_column_blob(pStmt, 4), pSample->n);
  83995. pIdx->nSample++;
  83996. }
  83997. rc = sqlite3_finalize(pStmt);
  83998. if( rc==SQLITE_OK ) initAvgEq(pPrevIdx);
  83999. return rc;
  84000. }
  84001. /*
  84002. ** Load content from the sqlite_stat4 and sqlite_stat3 tables into
  84003. ** the Index.aSample[] arrays of all indices.
  84004. */
  84005. static int loadStat4(sqlite3 *db, const char *zDb){
  84006. int rc = SQLITE_OK; /* Result codes from subroutines */
  84007. assert( db->lookaside.bEnabled==0 );
  84008. if( sqlite3FindTable(db, "sqlite_stat4", zDb) ){
  84009. rc = loadStatTbl(db, 0,
  84010. "SELECT idx,count(*) FROM %Q.sqlite_stat4 GROUP BY idx",
  84011. "SELECT idx,neq,nlt,ndlt,sample FROM %Q.sqlite_stat4",
  84012. zDb
  84013. );
  84014. }
  84015. if( rc==SQLITE_OK && sqlite3FindTable(db, "sqlite_stat3", zDb) ){
  84016. rc = loadStatTbl(db, 1,
  84017. "SELECT idx,count(*) FROM %Q.sqlite_stat3 GROUP BY idx",
  84018. "SELECT idx,neq,nlt,ndlt,sqlite_record(sample) FROM %Q.sqlite_stat3",
  84019. zDb
  84020. );
  84021. }
  84022. return rc;
  84023. }
  84024. #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
  84025. /*
  84026. ** Load the content of the sqlite_stat1 and sqlite_stat3/4 tables. The
  84027. ** contents of sqlite_stat1 are used to populate the Index.aiRowEst[]
  84028. ** arrays. The contents of sqlite_stat3/4 are used to populate the
  84029. ** Index.aSample[] arrays.
  84030. **
  84031. ** If the sqlite_stat1 table is not present in the database, SQLITE_ERROR
  84032. ** is returned. In this case, even if SQLITE_ENABLE_STAT3/4 was defined
  84033. ** during compilation and the sqlite_stat3/4 table is present, no data is
  84034. ** read from it.
  84035. **
  84036. ** If SQLITE_ENABLE_STAT3/4 was defined during compilation and the
  84037. ** sqlite_stat4 table is not present in the database, SQLITE_ERROR is
  84038. ** returned. However, in this case, data is read from the sqlite_stat1
  84039. ** table (if it is present) before returning.
  84040. **
  84041. ** If an OOM error occurs, this function always sets db->mallocFailed.
  84042. ** This means if the caller does not care about other errors, the return
  84043. ** code may be ignored.
  84044. */
  84045. SQLITE_PRIVATE int sqlite3AnalysisLoad(sqlite3 *db, int iDb){
  84046. analysisInfo sInfo;
  84047. HashElem *i;
  84048. char *zSql;
  84049. int rc;
  84050. assert( iDb>=0 && iDb<db->nDb );
  84051. assert( db->aDb[iDb].pBt!=0 );
  84052. /* Clear any prior statistics */
  84053. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  84054. for(i=sqliteHashFirst(&db->aDb[iDb].pSchema->idxHash);i;i=sqliteHashNext(i)){
  84055. Index *pIdx = sqliteHashData(i);
  84056. sqlite3DefaultRowEst(pIdx);
  84057. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  84058. sqlite3DeleteIndexSamples(db, pIdx);
  84059. pIdx->aSample = 0;
  84060. #endif
  84061. }
  84062. /* Check to make sure the sqlite_stat1 table exists */
  84063. sInfo.db = db;
  84064. sInfo.zDatabase = db->aDb[iDb].zName;
  84065. if( sqlite3FindTable(db, "sqlite_stat1", sInfo.zDatabase)==0 ){
  84066. return SQLITE_ERROR;
  84067. }
  84068. /* Load new statistics out of the sqlite_stat1 table */
  84069. zSql = sqlite3MPrintf(db,
  84070. "SELECT tbl,idx,stat FROM %Q.sqlite_stat1", sInfo.zDatabase);
  84071. if( zSql==0 ){
  84072. rc = SQLITE_NOMEM;
  84073. }else{
  84074. rc = sqlite3_exec(db, zSql, analysisLoader, &sInfo, 0);
  84075. sqlite3DbFree(db, zSql);
  84076. }
  84077. /* Load the statistics from the sqlite_stat4 table. */
  84078. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  84079. if( rc==SQLITE_OK && OptimizationEnabled(db, SQLITE_Stat34) ){
  84080. int lookasideEnabled = db->lookaside.bEnabled;
  84081. db->lookaside.bEnabled = 0;
  84082. rc = loadStat4(db, sInfo.zDatabase);
  84083. db->lookaside.bEnabled = lookasideEnabled;
  84084. }
  84085. for(i=sqliteHashFirst(&db->aDb[iDb].pSchema->idxHash);i;i=sqliteHashNext(i)){
  84086. Index *pIdx = sqliteHashData(i);
  84087. sqlite3_free(pIdx->aiRowEst);
  84088. pIdx->aiRowEst = 0;
  84089. }
  84090. #endif
  84091. if( rc==SQLITE_NOMEM ){
  84092. db->mallocFailed = 1;
  84093. }
  84094. return rc;
  84095. }
  84096. #endif /* SQLITE_OMIT_ANALYZE */
  84097. /************** End of analyze.c *********************************************/
  84098. /************** Begin file attach.c ******************************************/
  84099. /*
  84100. ** 2003 April 6
  84101. **
  84102. ** The author disclaims copyright to this source code. In place of
  84103. ** a legal notice, here is a blessing:
  84104. **
  84105. ** May you do good and not evil.
  84106. ** May you find forgiveness for yourself and forgive others.
  84107. ** May you share freely, never taking more than you give.
  84108. **
  84109. *************************************************************************
  84110. ** This file contains code used to implement the ATTACH and DETACH commands.
  84111. */
  84112. #ifndef SQLITE_OMIT_ATTACH
  84113. /*
  84114. ** Resolve an expression that was part of an ATTACH or DETACH statement. This
  84115. ** is slightly different from resolving a normal SQL expression, because simple
  84116. ** identifiers are treated as strings, not possible column names or aliases.
  84117. **
  84118. ** i.e. if the parser sees:
  84119. **
  84120. ** ATTACH DATABASE abc AS def
  84121. **
  84122. ** it treats the two expressions as literal strings 'abc' and 'def' instead of
  84123. ** looking for columns of the same name.
  84124. **
  84125. ** This only applies to the root node of pExpr, so the statement:
  84126. **
  84127. ** ATTACH DATABASE abc||def AS 'db2'
  84128. **
  84129. ** will fail because neither abc or def can be resolved.
  84130. */
  84131. static int resolveAttachExpr(NameContext *pName, Expr *pExpr)
  84132. {
  84133. int rc = SQLITE_OK;
  84134. if( pExpr ){
  84135. if( pExpr->op!=TK_ID ){
  84136. rc = sqlite3ResolveExprNames(pName, pExpr);
  84137. }else{
  84138. pExpr->op = TK_STRING;
  84139. }
  84140. }
  84141. return rc;
  84142. }
  84143. /*
  84144. ** An SQL user-function registered to do the work of an ATTACH statement. The
  84145. ** three arguments to the function come directly from an attach statement:
  84146. **
  84147. ** ATTACH DATABASE x AS y KEY z
  84148. **
  84149. ** SELECT sqlite_attach(x, y, z)
  84150. **
  84151. ** If the optional "KEY z" syntax is omitted, an SQL NULL is passed as the
  84152. ** third argument.
  84153. */
  84154. static void attachFunc(
  84155. sqlite3_context *context,
  84156. int NotUsed,
  84157. sqlite3_value **argv
  84158. ){
  84159. int i;
  84160. int rc = 0;
  84161. sqlite3 *db = sqlite3_context_db_handle(context);
  84162. const char *zName;
  84163. const char *zFile;
  84164. char *zPath = 0;
  84165. char *zErr = 0;
  84166. unsigned int flags;
  84167. Db *aNew;
  84168. char *zErrDyn = 0;
  84169. sqlite3_vfs *pVfs;
  84170. UNUSED_PARAMETER(NotUsed);
  84171. zFile = (const char *)sqlite3_value_text(argv[0]);
  84172. zName = (const char *)sqlite3_value_text(argv[1]);
  84173. if( zFile==0 ) zFile = "";
  84174. if( zName==0 ) zName = "";
  84175. /* Check for the following errors:
  84176. **
  84177. ** * Too many attached databases,
  84178. ** * Transaction currently open
  84179. ** * Specified database name already being used.
  84180. */
  84181. if( db->nDb>=db->aLimit[SQLITE_LIMIT_ATTACHED]+2 ){
  84182. zErrDyn = sqlite3MPrintf(db, "too many attached databases - max %d",
  84183. db->aLimit[SQLITE_LIMIT_ATTACHED]
  84184. );
  84185. goto attach_error;
  84186. }
  84187. if( !db->autoCommit ){
  84188. zErrDyn = sqlite3MPrintf(db, "cannot ATTACH database within transaction");
  84189. goto attach_error;
  84190. }
  84191. for(i=0; i<db->nDb; i++){
  84192. char *z = db->aDb[i].zName;
  84193. assert( z && zName );
  84194. if( sqlite3StrICmp(z, zName)==0 ){
  84195. zErrDyn = sqlite3MPrintf(db, "database %s is already in use", zName);
  84196. goto attach_error;
  84197. }
  84198. }
  84199. /* Allocate the new entry in the db->aDb[] array and initialize the schema
  84200. ** hash tables.
  84201. */
  84202. if( db->aDb==db->aDbStatic ){
  84203. aNew = sqlite3DbMallocRaw(db, sizeof(db->aDb[0])*3 );
  84204. if( aNew==0 ) return;
  84205. memcpy(aNew, db->aDb, sizeof(db->aDb[0])*2);
  84206. }else{
  84207. aNew = sqlite3DbRealloc(db, db->aDb, sizeof(db->aDb[0])*(db->nDb+1) );
  84208. if( aNew==0 ) return;
  84209. }
  84210. db->aDb = aNew;
  84211. aNew = &db->aDb[db->nDb];
  84212. memset(aNew, 0, sizeof(*aNew));
  84213. /* Open the database file. If the btree is successfully opened, use
  84214. ** it to obtain the database schema. At this point the schema may
  84215. ** or may not be initialized.
  84216. */
  84217. flags = db->openFlags;
  84218. rc = sqlite3ParseUri(db->pVfs->zName, zFile, &flags, &pVfs, &zPath, &zErr);
  84219. if( rc!=SQLITE_OK ){
  84220. if( rc==SQLITE_NOMEM ) db->mallocFailed = 1;
  84221. sqlite3_result_error(context, zErr, -1);
  84222. sqlite3_free(zErr);
  84223. return;
  84224. }
  84225. assert( pVfs );
  84226. flags |= SQLITE_OPEN_MAIN_DB;
  84227. rc = sqlite3BtreeOpen(pVfs, zPath, db, &aNew->pBt, 0, flags);
  84228. sqlite3_free( zPath );
  84229. db->nDb++;
  84230. if( rc==SQLITE_CONSTRAINT ){
  84231. rc = SQLITE_ERROR;
  84232. zErrDyn = sqlite3MPrintf(db, "database is already attached");
  84233. }else if( rc==SQLITE_OK ){
  84234. Pager *pPager;
  84235. aNew->pSchema = sqlite3SchemaGet(db, aNew->pBt);
  84236. if( !aNew->pSchema ){
  84237. rc = SQLITE_NOMEM;
  84238. }else if( aNew->pSchema->file_format && aNew->pSchema->enc!=ENC(db) ){
  84239. zErrDyn = sqlite3MPrintf(db,
  84240. "attached databases must use the same text encoding as main database");
  84241. rc = SQLITE_ERROR;
  84242. }
  84243. sqlite3BtreeEnter(aNew->pBt);
  84244. pPager = sqlite3BtreePager(aNew->pBt);
  84245. sqlite3PagerLockingMode(pPager, db->dfltLockMode);
  84246. sqlite3BtreeSecureDelete(aNew->pBt,
  84247. sqlite3BtreeSecureDelete(db->aDb[0].pBt,-1) );
  84248. #ifndef SQLITE_OMIT_PAGER_PRAGMAS
  84249. sqlite3BtreeSetPagerFlags(aNew->pBt, 3 | (db->flags & PAGER_FLAGS_MASK));
  84250. #endif
  84251. sqlite3BtreeLeave(aNew->pBt);
  84252. }
  84253. aNew->safety_level = 3;
  84254. aNew->zName = sqlite3DbStrDup(db, zName);
  84255. if( rc==SQLITE_OK && aNew->zName==0 ){
  84256. rc = SQLITE_NOMEM;
  84257. }
  84258. #ifdef SQLITE_HAS_CODEC
  84259. if( rc==SQLITE_OK ){
  84260. extern int sqlite3CodecAttach(sqlite3*, int, const void*, int);
  84261. extern void sqlite3CodecGetKey(sqlite3*, int, void**, int*);
  84262. int nKey;
  84263. char *zKey;
  84264. int t = sqlite3_value_type(argv[2]);
  84265. switch( t ){
  84266. case SQLITE_INTEGER:
  84267. case SQLITE_FLOAT:
  84268. zErrDyn = sqlite3DbStrDup(db, "Invalid key value");
  84269. rc = SQLITE_ERROR;
  84270. break;
  84271. case SQLITE_TEXT:
  84272. case SQLITE_BLOB:
  84273. nKey = sqlite3_value_bytes(argv[2]);
  84274. zKey = (char *)sqlite3_value_blob(argv[2]);
  84275. rc = sqlite3CodecAttach(db, db->nDb-1, zKey, nKey);
  84276. break;
  84277. case SQLITE_NULL:
  84278. /* No key specified. Use the key from the main database */
  84279. sqlite3CodecGetKey(db, 0, (void**)&zKey, &nKey);
  84280. if( nKey>0 || sqlite3BtreeGetOptimalReserve(db->aDb[0].pBt)>0 ){
  84281. rc = sqlite3CodecAttach(db, db->nDb-1, zKey, nKey);
  84282. }
  84283. break;
  84284. }
  84285. }
  84286. #endif
  84287. /* If the file was opened successfully, read the schema for the new database.
  84288. ** If this fails, or if opening the file failed, then close the file and
  84289. ** remove the entry from the db->aDb[] array. i.e. put everything back the way
  84290. ** we found it.
  84291. */
  84292. if( rc==SQLITE_OK ){
  84293. sqlite3BtreeEnterAll(db);
  84294. rc = sqlite3Init(db, &zErrDyn);
  84295. sqlite3BtreeLeaveAll(db);
  84296. }
  84297. #ifdef SQLITE_USER_AUTHENTICATION
  84298. if( rc==SQLITE_OK ){
  84299. u8 newAuth = 0;
  84300. rc = sqlite3UserAuthCheckLogin(db, zName, &newAuth);
  84301. if( newAuth<db->auth.authLevel ){
  84302. rc = SQLITE_AUTH_USER;
  84303. }
  84304. }
  84305. #endif
  84306. if( rc ){
  84307. int iDb = db->nDb - 1;
  84308. assert( iDb>=2 );
  84309. if( db->aDb[iDb].pBt ){
  84310. sqlite3BtreeClose(db->aDb[iDb].pBt);
  84311. db->aDb[iDb].pBt = 0;
  84312. db->aDb[iDb].pSchema = 0;
  84313. }
  84314. sqlite3ResetAllSchemasOfConnection(db);
  84315. db->nDb = iDb;
  84316. if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){
  84317. db->mallocFailed = 1;
  84318. sqlite3DbFree(db, zErrDyn);
  84319. zErrDyn = sqlite3MPrintf(db, "out of memory");
  84320. }else if( zErrDyn==0 ){
  84321. zErrDyn = sqlite3MPrintf(db, "unable to open database: %s", zFile);
  84322. }
  84323. goto attach_error;
  84324. }
  84325. return;
  84326. attach_error:
  84327. /* Return an error if we get here */
  84328. if( zErrDyn ){
  84329. sqlite3_result_error(context, zErrDyn, -1);
  84330. sqlite3DbFree(db, zErrDyn);
  84331. }
  84332. if( rc ) sqlite3_result_error_code(context, rc);
  84333. }
  84334. /*
  84335. ** An SQL user-function registered to do the work of an DETACH statement. The
  84336. ** three arguments to the function come directly from a detach statement:
  84337. **
  84338. ** DETACH DATABASE x
  84339. **
  84340. ** SELECT sqlite_detach(x)
  84341. */
  84342. static void detachFunc(
  84343. sqlite3_context *context,
  84344. int NotUsed,
  84345. sqlite3_value **argv
  84346. ){
  84347. const char *zName = (const char *)sqlite3_value_text(argv[0]);
  84348. sqlite3 *db = sqlite3_context_db_handle(context);
  84349. int i;
  84350. Db *pDb = 0;
  84351. char zErr[128];
  84352. UNUSED_PARAMETER(NotUsed);
  84353. if( zName==0 ) zName = "";
  84354. for(i=0; i<db->nDb; i++){
  84355. pDb = &db->aDb[i];
  84356. if( pDb->pBt==0 ) continue;
  84357. if( sqlite3StrICmp(pDb->zName, zName)==0 ) break;
  84358. }
  84359. if( i>=db->nDb ){
  84360. sqlite3_snprintf(sizeof(zErr),zErr, "no such database: %s", zName);
  84361. goto detach_error;
  84362. }
  84363. if( i<2 ){
  84364. sqlite3_snprintf(sizeof(zErr),zErr, "cannot detach database %s", zName);
  84365. goto detach_error;
  84366. }
  84367. if( !db->autoCommit ){
  84368. sqlite3_snprintf(sizeof(zErr), zErr,
  84369. "cannot DETACH database within transaction");
  84370. goto detach_error;
  84371. }
  84372. if( sqlite3BtreeIsInReadTrans(pDb->pBt) || sqlite3BtreeIsInBackup(pDb->pBt) ){
  84373. sqlite3_snprintf(sizeof(zErr),zErr, "database %s is locked", zName);
  84374. goto detach_error;
  84375. }
  84376. sqlite3BtreeClose(pDb->pBt);
  84377. pDb->pBt = 0;
  84378. pDb->pSchema = 0;
  84379. sqlite3CollapseDatabaseArray(db);
  84380. return;
  84381. detach_error:
  84382. sqlite3_result_error(context, zErr, -1);
  84383. }
  84384. /*
  84385. ** This procedure generates VDBE code for a single invocation of either the
  84386. ** sqlite_detach() or sqlite_attach() SQL user functions.
  84387. */
  84388. static void codeAttach(
  84389. Parse *pParse, /* The parser context */
  84390. int type, /* Either SQLITE_ATTACH or SQLITE_DETACH */
  84391. FuncDef const *pFunc,/* FuncDef wrapper for detachFunc() or attachFunc() */
  84392. Expr *pAuthArg, /* Expression to pass to authorization callback */
  84393. Expr *pFilename, /* Name of database file */
  84394. Expr *pDbname, /* Name of the database to use internally */
  84395. Expr *pKey /* Database key for encryption extension */
  84396. ){
  84397. int rc;
  84398. NameContext sName;
  84399. Vdbe *v;
  84400. sqlite3* db = pParse->db;
  84401. int regArgs;
  84402. memset(&sName, 0, sizeof(NameContext));
  84403. sName.pParse = pParse;
  84404. if(
  84405. SQLITE_OK!=(rc = resolveAttachExpr(&sName, pFilename)) ||
  84406. SQLITE_OK!=(rc = resolveAttachExpr(&sName, pDbname)) ||
  84407. SQLITE_OK!=(rc = resolveAttachExpr(&sName, pKey))
  84408. ){
  84409. goto attach_end;
  84410. }
  84411. #ifndef SQLITE_OMIT_AUTHORIZATION
  84412. if( pAuthArg ){
  84413. char *zAuthArg;
  84414. if( pAuthArg->op==TK_STRING ){
  84415. zAuthArg = pAuthArg->u.zToken;
  84416. }else{
  84417. zAuthArg = 0;
  84418. }
  84419. rc = sqlite3AuthCheck(pParse, type, zAuthArg, 0, 0);
  84420. if(rc!=SQLITE_OK ){
  84421. goto attach_end;
  84422. }
  84423. }
  84424. #endif /* SQLITE_OMIT_AUTHORIZATION */
  84425. v = sqlite3GetVdbe(pParse);
  84426. regArgs = sqlite3GetTempRange(pParse, 4);
  84427. sqlite3ExprCode(pParse, pFilename, regArgs);
  84428. sqlite3ExprCode(pParse, pDbname, regArgs+1);
  84429. sqlite3ExprCode(pParse, pKey, regArgs+2);
  84430. assert( v || db->mallocFailed );
  84431. if( v ){
  84432. sqlite3VdbeAddOp3(v, OP_Function, 0, regArgs+3-pFunc->nArg, regArgs+3);
  84433. assert( pFunc->nArg==-1 || (pFunc->nArg&0xff)==pFunc->nArg );
  84434. sqlite3VdbeChangeP5(v, (u8)(pFunc->nArg));
  84435. sqlite3VdbeChangeP4(v, -1, (char *)pFunc, P4_FUNCDEF);
  84436. /* Code an OP_Expire. For an ATTACH statement, set P1 to true (expire this
  84437. ** statement only). For DETACH, set it to false (expire all existing
  84438. ** statements).
  84439. */
  84440. sqlite3VdbeAddOp1(v, OP_Expire, (type==SQLITE_ATTACH));
  84441. }
  84442. attach_end:
  84443. sqlite3ExprDelete(db, pFilename);
  84444. sqlite3ExprDelete(db, pDbname);
  84445. sqlite3ExprDelete(db, pKey);
  84446. }
  84447. /*
  84448. ** Called by the parser to compile a DETACH statement.
  84449. **
  84450. ** DETACH pDbname
  84451. */
  84452. SQLITE_PRIVATE void sqlite3Detach(Parse *pParse, Expr *pDbname){
  84453. static const FuncDef detach_func = {
  84454. 1, /* nArg */
  84455. SQLITE_UTF8, /* funcFlags */
  84456. 0, /* pUserData */
  84457. 0, /* pNext */
  84458. detachFunc, /* xFunc */
  84459. 0, /* xStep */
  84460. 0, /* xFinalize */
  84461. "sqlite_detach", /* zName */
  84462. 0, /* pHash */
  84463. 0 /* pDestructor */
  84464. };
  84465. codeAttach(pParse, SQLITE_DETACH, &detach_func, pDbname, 0, 0, pDbname);
  84466. }
  84467. /*
  84468. ** Called by the parser to compile an ATTACH statement.
  84469. **
  84470. ** ATTACH p AS pDbname KEY pKey
  84471. */
  84472. SQLITE_PRIVATE void sqlite3Attach(Parse *pParse, Expr *p, Expr *pDbname, Expr *pKey){
  84473. static const FuncDef attach_func = {
  84474. 3, /* nArg */
  84475. SQLITE_UTF8, /* funcFlags */
  84476. 0, /* pUserData */
  84477. 0, /* pNext */
  84478. attachFunc, /* xFunc */
  84479. 0, /* xStep */
  84480. 0, /* xFinalize */
  84481. "sqlite_attach", /* zName */
  84482. 0, /* pHash */
  84483. 0 /* pDestructor */
  84484. };
  84485. codeAttach(pParse, SQLITE_ATTACH, &attach_func, p, p, pDbname, pKey);
  84486. }
  84487. #endif /* SQLITE_OMIT_ATTACH */
  84488. /*
  84489. ** Initialize a DbFixer structure. This routine must be called prior
  84490. ** to passing the structure to one of the sqliteFixAAAA() routines below.
  84491. */
  84492. SQLITE_PRIVATE void sqlite3FixInit(
  84493. DbFixer *pFix, /* The fixer to be initialized */
  84494. Parse *pParse, /* Error messages will be written here */
  84495. int iDb, /* This is the database that must be used */
  84496. const char *zType, /* "view", "trigger", or "index" */
  84497. const Token *pName /* Name of the view, trigger, or index */
  84498. ){
  84499. sqlite3 *db;
  84500. db = pParse->db;
  84501. assert( db->nDb>iDb );
  84502. pFix->pParse = pParse;
  84503. pFix->zDb = db->aDb[iDb].zName;
  84504. pFix->pSchema = db->aDb[iDb].pSchema;
  84505. pFix->zType = zType;
  84506. pFix->pName = pName;
  84507. pFix->bVarOnly = (iDb==1);
  84508. }
  84509. /*
  84510. ** The following set of routines walk through the parse tree and assign
  84511. ** a specific database to all table references where the database name
  84512. ** was left unspecified in the original SQL statement. The pFix structure
  84513. ** must have been initialized by a prior call to sqlite3FixInit().
  84514. **
  84515. ** These routines are used to make sure that an index, trigger, or
  84516. ** view in one database does not refer to objects in a different database.
  84517. ** (Exception: indices, triggers, and views in the TEMP database are
  84518. ** allowed to refer to anything.) If a reference is explicitly made
  84519. ** to an object in a different database, an error message is added to
  84520. ** pParse->zErrMsg and these routines return non-zero. If everything
  84521. ** checks out, these routines return 0.
  84522. */
  84523. SQLITE_PRIVATE int sqlite3FixSrcList(
  84524. DbFixer *pFix, /* Context of the fixation */
  84525. SrcList *pList /* The Source list to check and modify */
  84526. ){
  84527. int i;
  84528. const char *zDb;
  84529. struct SrcList_item *pItem;
  84530. if( NEVER(pList==0) ) return 0;
  84531. zDb = pFix->zDb;
  84532. for(i=0, pItem=pList->a; i<pList->nSrc; i++, pItem++){
  84533. if( pFix->bVarOnly==0 ){
  84534. if( pItem->zDatabase && sqlite3StrICmp(pItem->zDatabase, zDb) ){
  84535. sqlite3ErrorMsg(pFix->pParse,
  84536. "%s %T cannot reference objects in database %s",
  84537. pFix->zType, pFix->pName, pItem->zDatabase);
  84538. return 1;
  84539. }
  84540. sqlite3DbFree(pFix->pParse->db, pItem->zDatabase);
  84541. pItem->zDatabase = 0;
  84542. pItem->pSchema = pFix->pSchema;
  84543. }
  84544. #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER)
  84545. if( sqlite3FixSelect(pFix, pItem->pSelect) ) return 1;
  84546. if( sqlite3FixExpr(pFix, pItem->pOn) ) return 1;
  84547. #endif
  84548. }
  84549. return 0;
  84550. }
  84551. #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER)
  84552. SQLITE_PRIVATE int sqlite3FixSelect(
  84553. DbFixer *pFix, /* Context of the fixation */
  84554. Select *pSelect /* The SELECT statement to be fixed to one database */
  84555. ){
  84556. while( pSelect ){
  84557. if( sqlite3FixExprList(pFix, pSelect->pEList) ){
  84558. return 1;
  84559. }
  84560. if( sqlite3FixSrcList(pFix, pSelect->pSrc) ){
  84561. return 1;
  84562. }
  84563. if( sqlite3FixExpr(pFix, pSelect->pWhere) ){
  84564. return 1;
  84565. }
  84566. if( sqlite3FixExprList(pFix, pSelect->pGroupBy) ){
  84567. return 1;
  84568. }
  84569. if( sqlite3FixExpr(pFix, pSelect->pHaving) ){
  84570. return 1;
  84571. }
  84572. if( sqlite3FixExprList(pFix, pSelect->pOrderBy) ){
  84573. return 1;
  84574. }
  84575. if( sqlite3FixExpr(pFix, pSelect->pLimit) ){
  84576. return 1;
  84577. }
  84578. if( sqlite3FixExpr(pFix, pSelect->pOffset) ){
  84579. return 1;
  84580. }
  84581. pSelect = pSelect->pPrior;
  84582. }
  84583. return 0;
  84584. }
  84585. SQLITE_PRIVATE int sqlite3FixExpr(
  84586. DbFixer *pFix, /* Context of the fixation */
  84587. Expr *pExpr /* The expression to be fixed to one database */
  84588. ){
  84589. while( pExpr ){
  84590. if( pExpr->op==TK_VARIABLE ){
  84591. if( pFix->pParse->db->init.busy ){
  84592. pExpr->op = TK_NULL;
  84593. }else{
  84594. sqlite3ErrorMsg(pFix->pParse, "%s cannot use variables", pFix->zType);
  84595. return 1;
  84596. }
  84597. }
  84598. if( ExprHasProperty(pExpr, EP_TokenOnly) ) break;
  84599. if( ExprHasProperty(pExpr, EP_xIsSelect) ){
  84600. if( sqlite3FixSelect(pFix, pExpr->x.pSelect) ) return 1;
  84601. }else{
  84602. if( sqlite3FixExprList(pFix, pExpr->x.pList) ) return 1;
  84603. }
  84604. if( sqlite3FixExpr(pFix, pExpr->pRight) ){
  84605. return 1;
  84606. }
  84607. pExpr = pExpr->pLeft;
  84608. }
  84609. return 0;
  84610. }
  84611. SQLITE_PRIVATE int sqlite3FixExprList(
  84612. DbFixer *pFix, /* Context of the fixation */
  84613. ExprList *pList /* The expression to be fixed to one database */
  84614. ){
  84615. int i;
  84616. struct ExprList_item *pItem;
  84617. if( pList==0 ) return 0;
  84618. for(i=0, pItem=pList->a; i<pList->nExpr; i++, pItem++){
  84619. if( sqlite3FixExpr(pFix, pItem->pExpr) ){
  84620. return 1;
  84621. }
  84622. }
  84623. return 0;
  84624. }
  84625. #endif
  84626. #ifndef SQLITE_OMIT_TRIGGER
  84627. SQLITE_PRIVATE int sqlite3FixTriggerStep(
  84628. DbFixer *pFix, /* Context of the fixation */
  84629. TriggerStep *pStep /* The trigger step be fixed to one database */
  84630. ){
  84631. while( pStep ){
  84632. if( sqlite3FixSelect(pFix, pStep->pSelect) ){
  84633. return 1;
  84634. }
  84635. if( sqlite3FixExpr(pFix, pStep->pWhere) ){
  84636. return 1;
  84637. }
  84638. if( sqlite3FixExprList(pFix, pStep->pExprList) ){
  84639. return 1;
  84640. }
  84641. pStep = pStep->pNext;
  84642. }
  84643. return 0;
  84644. }
  84645. #endif
  84646. /************** End of attach.c **********************************************/
  84647. /************** Begin file auth.c ********************************************/
  84648. /*
  84649. ** 2003 January 11
  84650. **
  84651. ** The author disclaims copyright to this source code. In place of
  84652. ** a legal notice, here is a blessing:
  84653. **
  84654. ** May you do good and not evil.
  84655. ** May you find forgiveness for yourself and forgive others.
  84656. ** May you share freely, never taking more than you give.
  84657. **
  84658. *************************************************************************
  84659. ** This file contains code used to implement the sqlite3_set_authorizer()
  84660. ** API. This facility is an optional feature of the library. Embedded
  84661. ** systems that do not need this facility may omit it by recompiling
  84662. ** the library with -DSQLITE_OMIT_AUTHORIZATION=1
  84663. */
  84664. /*
  84665. ** All of the code in this file may be omitted by defining a single
  84666. ** macro.
  84667. */
  84668. #ifndef SQLITE_OMIT_AUTHORIZATION
  84669. /*
  84670. ** Set or clear the access authorization function.
  84671. **
  84672. ** The access authorization function is be called during the compilation
  84673. ** phase to verify that the user has read and/or write access permission on
  84674. ** various fields of the database. The first argument to the auth function
  84675. ** is a copy of the 3rd argument to this routine. The second argument
  84676. ** to the auth function is one of these constants:
  84677. **
  84678. ** SQLITE_CREATE_INDEX
  84679. ** SQLITE_CREATE_TABLE
  84680. ** SQLITE_CREATE_TEMP_INDEX
  84681. ** SQLITE_CREATE_TEMP_TABLE
  84682. ** SQLITE_CREATE_TEMP_TRIGGER
  84683. ** SQLITE_CREATE_TEMP_VIEW
  84684. ** SQLITE_CREATE_TRIGGER
  84685. ** SQLITE_CREATE_VIEW
  84686. ** SQLITE_DELETE
  84687. ** SQLITE_DROP_INDEX
  84688. ** SQLITE_DROP_TABLE
  84689. ** SQLITE_DROP_TEMP_INDEX
  84690. ** SQLITE_DROP_TEMP_TABLE
  84691. ** SQLITE_DROP_TEMP_TRIGGER
  84692. ** SQLITE_DROP_TEMP_VIEW
  84693. ** SQLITE_DROP_TRIGGER
  84694. ** SQLITE_DROP_VIEW
  84695. ** SQLITE_INSERT
  84696. ** SQLITE_PRAGMA
  84697. ** SQLITE_READ
  84698. ** SQLITE_SELECT
  84699. ** SQLITE_TRANSACTION
  84700. ** SQLITE_UPDATE
  84701. **
  84702. ** The third and fourth arguments to the auth function are the name of
  84703. ** the table and the column that are being accessed. The auth function
  84704. ** should return either SQLITE_OK, SQLITE_DENY, or SQLITE_IGNORE. If
  84705. ** SQLITE_OK is returned, it means that access is allowed. SQLITE_DENY
  84706. ** means that the SQL statement will never-run - the sqlite3_exec() call
  84707. ** will return with an error. SQLITE_IGNORE means that the SQL statement
  84708. ** should run but attempts to read the specified column will return NULL
  84709. ** and attempts to write the column will be ignored.
  84710. **
  84711. ** Setting the auth function to NULL disables this hook. The default
  84712. ** setting of the auth function is NULL.
  84713. */
  84714. SQLITE_API int SQLITE_STDCALL sqlite3_set_authorizer(
  84715. sqlite3 *db,
  84716. int (*xAuth)(void*,int,const char*,const char*,const char*,const char*),
  84717. void *pArg
  84718. ){
  84719. #ifdef SQLITE_ENABLE_API_ARMOR
  84720. if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
  84721. #endif
  84722. sqlite3_mutex_enter(db->mutex);
  84723. db->xAuth = (sqlite3_xauth)xAuth;
  84724. db->pAuthArg = pArg;
  84725. sqlite3ExpirePreparedStatements(db);
  84726. sqlite3_mutex_leave(db->mutex);
  84727. return SQLITE_OK;
  84728. }
  84729. /*
  84730. ** Write an error message into pParse->zErrMsg that explains that the
  84731. ** user-supplied authorization function returned an illegal value.
  84732. */
  84733. static void sqliteAuthBadReturnCode(Parse *pParse){
  84734. sqlite3ErrorMsg(pParse, "authorizer malfunction");
  84735. pParse->rc = SQLITE_ERROR;
  84736. }
  84737. /*
  84738. ** Invoke the authorization callback for permission to read column zCol from
  84739. ** table zTab in database zDb. This function assumes that an authorization
  84740. ** callback has been registered (i.e. that sqlite3.xAuth is not NULL).
  84741. **
  84742. ** If SQLITE_IGNORE is returned and pExpr is not NULL, then pExpr is changed
  84743. ** to an SQL NULL expression. Otherwise, if pExpr is NULL, then SQLITE_IGNORE
  84744. ** is treated as SQLITE_DENY. In this case an error is left in pParse.
  84745. */
  84746. SQLITE_PRIVATE int sqlite3AuthReadCol(
  84747. Parse *pParse, /* The parser context */
  84748. const char *zTab, /* Table name */
  84749. const char *zCol, /* Column name */
  84750. int iDb /* Index of containing database. */
  84751. ){
  84752. sqlite3 *db = pParse->db; /* Database handle */
  84753. char *zDb = db->aDb[iDb].zName; /* Name of attached database */
  84754. int rc; /* Auth callback return code */
  84755. rc = db->xAuth(db->pAuthArg, SQLITE_READ, zTab,zCol,zDb,pParse->zAuthContext
  84756. #ifdef SQLITE_USER_AUTHENTICATION
  84757. ,db->auth.zAuthUser
  84758. #endif
  84759. );
  84760. if( rc==SQLITE_DENY ){
  84761. if( db->nDb>2 || iDb!=0 ){
  84762. sqlite3ErrorMsg(pParse, "access to %s.%s.%s is prohibited",zDb,zTab,zCol);
  84763. }else{
  84764. sqlite3ErrorMsg(pParse, "access to %s.%s is prohibited", zTab, zCol);
  84765. }
  84766. pParse->rc = SQLITE_AUTH;
  84767. }else if( rc!=SQLITE_IGNORE && rc!=SQLITE_OK ){
  84768. sqliteAuthBadReturnCode(pParse);
  84769. }
  84770. return rc;
  84771. }
  84772. /*
  84773. ** The pExpr should be a TK_COLUMN expression. The table referred to
  84774. ** is in pTabList or else it is the NEW or OLD table of a trigger.
  84775. ** Check to see if it is OK to read this particular column.
  84776. **
  84777. ** If the auth function returns SQLITE_IGNORE, change the TK_COLUMN
  84778. ** instruction into a TK_NULL. If the auth function returns SQLITE_DENY,
  84779. ** then generate an error.
  84780. */
  84781. SQLITE_PRIVATE void sqlite3AuthRead(
  84782. Parse *pParse, /* The parser context */
  84783. Expr *pExpr, /* The expression to check authorization on */
  84784. Schema *pSchema, /* The schema of the expression */
  84785. SrcList *pTabList /* All table that pExpr might refer to */
  84786. ){
  84787. sqlite3 *db = pParse->db;
  84788. Table *pTab = 0; /* The table being read */
  84789. const char *zCol; /* Name of the column of the table */
  84790. int iSrc; /* Index in pTabList->a[] of table being read */
  84791. int iDb; /* The index of the database the expression refers to */
  84792. int iCol; /* Index of column in table */
  84793. if( db->xAuth==0 ) return;
  84794. iDb = sqlite3SchemaToIndex(pParse->db, pSchema);
  84795. if( iDb<0 ){
  84796. /* An attempt to read a column out of a subquery or other
  84797. ** temporary table. */
  84798. return;
  84799. }
  84800. assert( pExpr->op==TK_COLUMN || pExpr->op==TK_TRIGGER );
  84801. if( pExpr->op==TK_TRIGGER ){
  84802. pTab = pParse->pTriggerTab;
  84803. }else{
  84804. assert( pTabList );
  84805. for(iSrc=0; ALWAYS(iSrc<pTabList->nSrc); iSrc++){
  84806. if( pExpr->iTable==pTabList->a[iSrc].iCursor ){
  84807. pTab = pTabList->a[iSrc].pTab;
  84808. break;
  84809. }
  84810. }
  84811. }
  84812. iCol = pExpr->iColumn;
  84813. if( NEVER(pTab==0) ) return;
  84814. if( iCol>=0 ){
  84815. assert( iCol<pTab->nCol );
  84816. zCol = pTab->aCol[iCol].zName;
  84817. }else if( pTab->iPKey>=0 ){
  84818. assert( pTab->iPKey<pTab->nCol );
  84819. zCol = pTab->aCol[pTab->iPKey].zName;
  84820. }else{
  84821. zCol = "ROWID";
  84822. }
  84823. assert( iDb>=0 && iDb<db->nDb );
  84824. if( SQLITE_IGNORE==sqlite3AuthReadCol(pParse, pTab->zName, zCol, iDb) ){
  84825. pExpr->op = TK_NULL;
  84826. }
  84827. }
  84828. /*
  84829. ** Do an authorization check using the code and arguments given. Return
  84830. ** either SQLITE_OK (zero) or SQLITE_IGNORE or SQLITE_DENY. If SQLITE_DENY
  84831. ** is returned, then the error count and error message in pParse are
  84832. ** modified appropriately.
  84833. */
  84834. SQLITE_PRIVATE int sqlite3AuthCheck(
  84835. Parse *pParse,
  84836. int code,
  84837. const char *zArg1,
  84838. const char *zArg2,
  84839. const char *zArg3
  84840. ){
  84841. sqlite3 *db = pParse->db;
  84842. int rc;
  84843. /* Don't do any authorization checks if the database is initialising
  84844. ** or if the parser is being invoked from within sqlite3_declare_vtab.
  84845. */
  84846. if( db->init.busy || IN_DECLARE_VTAB ){
  84847. return SQLITE_OK;
  84848. }
  84849. if( db->xAuth==0 ){
  84850. return SQLITE_OK;
  84851. }
  84852. rc = db->xAuth(db->pAuthArg, code, zArg1, zArg2, zArg3, pParse->zAuthContext
  84853. #ifdef SQLITE_USER_AUTHENTICATION
  84854. ,db->auth.zAuthUser
  84855. #endif
  84856. );
  84857. if( rc==SQLITE_DENY ){
  84858. sqlite3ErrorMsg(pParse, "not authorized");
  84859. pParse->rc = SQLITE_AUTH;
  84860. }else if( rc!=SQLITE_OK && rc!=SQLITE_IGNORE ){
  84861. rc = SQLITE_DENY;
  84862. sqliteAuthBadReturnCode(pParse);
  84863. }
  84864. return rc;
  84865. }
  84866. /*
  84867. ** Push an authorization context. After this routine is called, the
  84868. ** zArg3 argument to authorization callbacks will be zContext until
  84869. ** popped. Or if pParse==0, this routine is a no-op.
  84870. */
  84871. SQLITE_PRIVATE void sqlite3AuthContextPush(
  84872. Parse *pParse,
  84873. AuthContext *pContext,
  84874. const char *zContext
  84875. ){
  84876. assert( pParse );
  84877. pContext->pParse = pParse;
  84878. pContext->zAuthContext = pParse->zAuthContext;
  84879. pParse->zAuthContext = zContext;
  84880. }
  84881. /*
  84882. ** Pop an authorization context that was previously pushed
  84883. ** by sqlite3AuthContextPush
  84884. */
  84885. SQLITE_PRIVATE void sqlite3AuthContextPop(AuthContext *pContext){
  84886. if( pContext->pParse ){
  84887. pContext->pParse->zAuthContext = pContext->zAuthContext;
  84888. pContext->pParse = 0;
  84889. }
  84890. }
  84891. #endif /* SQLITE_OMIT_AUTHORIZATION */
  84892. /************** End of auth.c ************************************************/
  84893. /************** Begin file build.c *******************************************/
  84894. /*
  84895. ** 2001 September 15
  84896. **
  84897. ** The author disclaims copyright to this source code. In place of
  84898. ** a legal notice, here is a blessing:
  84899. **
  84900. ** May you do good and not evil.
  84901. ** May you find forgiveness for yourself and forgive others.
  84902. ** May you share freely, never taking more than you give.
  84903. **
  84904. *************************************************************************
  84905. ** This file contains C code routines that are called by the SQLite parser
  84906. ** when syntax rules are reduced. The routines in this file handle the
  84907. ** following kinds of SQL syntax:
  84908. **
  84909. ** CREATE TABLE
  84910. ** DROP TABLE
  84911. ** CREATE INDEX
  84912. ** DROP INDEX
  84913. ** creating ID lists
  84914. ** BEGIN TRANSACTION
  84915. ** COMMIT
  84916. ** ROLLBACK
  84917. */
  84918. /*
  84919. ** This routine is called when a new SQL statement is beginning to
  84920. ** be parsed. Initialize the pParse structure as needed.
  84921. */
  84922. SQLITE_PRIVATE void sqlite3BeginParse(Parse *pParse, int explainFlag){
  84923. pParse->explain = (u8)explainFlag;
  84924. pParse->nVar = 0;
  84925. }
  84926. #ifndef SQLITE_OMIT_SHARED_CACHE
  84927. /*
  84928. ** The TableLock structure is only used by the sqlite3TableLock() and
  84929. ** codeTableLocks() functions.
  84930. */
  84931. struct TableLock {
  84932. int iDb; /* The database containing the table to be locked */
  84933. int iTab; /* The root page of the table to be locked */
  84934. u8 isWriteLock; /* True for write lock. False for a read lock */
  84935. const char *zName; /* Name of the table */
  84936. };
  84937. /*
  84938. ** Record the fact that we want to lock a table at run-time.
  84939. **
  84940. ** The table to be locked has root page iTab and is found in database iDb.
  84941. ** A read or a write lock can be taken depending on isWritelock.
  84942. **
  84943. ** This routine just records the fact that the lock is desired. The
  84944. ** code to make the lock occur is generated by a later call to
  84945. ** codeTableLocks() which occurs during sqlite3FinishCoding().
  84946. */
  84947. SQLITE_PRIVATE void sqlite3TableLock(
  84948. Parse *pParse, /* Parsing context */
  84949. int iDb, /* Index of the database containing the table to lock */
  84950. int iTab, /* Root page number of the table to be locked */
  84951. u8 isWriteLock, /* True for a write lock */
  84952. const char *zName /* Name of the table to be locked */
  84953. ){
  84954. Parse *pToplevel = sqlite3ParseToplevel(pParse);
  84955. int i;
  84956. int nBytes;
  84957. TableLock *p;
  84958. assert( iDb>=0 );
  84959. for(i=0; i<pToplevel->nTableLock; i++){
  84960. p = &pToplevel->aTableLock[i];
  84961. if( p->iDb==iDb && p->iTab==iTab ){
  84962. p->isWriteLock = (p->isWriteLock || isWriteLock);
  84963. return;
  84964. }
  84965. }
  84966. nBytes = sizeof(TableLock) * (pToplevel->nTableLock+1);
  84967. pToplevel->aTableLock =
  84968. sqlite3DbReallocOrFree(pToplevel->db, pToplevel->aTableLock, nBytes);
  84969. if( pToplevel->aTableLock ){
  84970. p = &pToplevel->aTableLock[pToplevel->nTableLock++];
  84971. p->iDb = iDb;
  84972. p->iTab = iTab;
  84973. p->isWriteLock = isWriteLock;
  84974. p->zName = zName;
  84975. }else{
  84976. pToplevel->nTableLock = 0;
  84977. pToplevel->db->mallocFailed = 1;
  84978. }
  84979. }
  84980. /*
  84981. ** Code an OP_TableLock instruction for each table locked by the
  84982. ** statement (configured by calls to sqlite3TableLock()).
  84983. */
  84984. static void codeTableLocks(Parse *pParse){
  84985. int i;
  84986. Vdbe *pVdbe;
  84987. pVdbe = sqlite3GetVdbe(pParse);
  84988. assert( pVdbe!=0 ); /* sqlite3GetVdbe cannot fail: VDBE already allocated */
  84989. for(i=0; i<pParse->nTableLock; i++){
  84990. TableLock *p = &pParse->aTableLock[i];
  84991. int p1 = p->iDb;
  84992. sqlite3VdbeAddOp4(pVdbe, OP_TableLock, p1, p->iTab, p->isWriteLock,
  84993. p->zName, P4_STATIC);
  84994. }
  84995. }
  84996. #else
  84997. #define codeTableLocks(x)
  84998. #endif
  84999. /*
  85000. ** Return TRUE if the given yDbMask object is empty - if it contains no
  85001. ** 1 bits. This routine is used by the DbMaskAllZero() and DbMaskNotZero()
  85002. ** macros when SQLITE_MAX_ATTACHED is greater than 30.
  85003. */
  85004. #if SQLITE_MAX_ATTACHED>30
  85005. SQLITE_PRIVATE int sqlite3DbMaskAllZero(yDbMask m){
  85006. int i;
  85007. for(i=0; i<sizeof(yDbMask); i++) if( m[i] ) return 0;
  85008. return 1;
  85009. }
  85010. #endif
  85011. /*
  85012. ** This routine is called after a single SQL statement has been
  85013. ** parsed and a VDBE program to execute that statement has been
  85014. ** prepared. This routine puts the finishing touches on the
  85015. ** VDBE program and resets the pParse structure for the next
  85016. ** parse.
  85017. **
  85018. ** Note that if an error occurred, it might be the case that
  85019. ** no VDBE code was generated.
  85020. */
  85021. SQLITE_PRIVATE void sqlite3FinishCoding(Parse *pParse){
  85022. sqlite3 *db;
  85023. Vdbe *v;
  85024. assert( pParse->pToplevel==0 );
  85025. db = pParse->db;
  85026. if( pParse->nested ) return;
  85027. if( db->mallocFailed || pParse->nErr ){
  85028. if( pParse->rc==SQLITE_OK ) pParse->rc = SQLITE_ERROR;
  85029. return;
  85030. }
  85031. /* Begin by generating some termination code at the end of the
  85032. ** vdbe program
  85033. */
  85034. v = sqlite3GetVdbe(pParse);
  85035. assert( !pParse->isMultiWrite
  85036. || sqlite3VdbeAssertMayAbort(v, pParse->mayAbort));
  85037. if( v ){
  85038. while( sqlite3VdbeDeletePriorOpcode(v, OP_Close) ){}
  85039. sqlite3VdbeAddOp0(v, OP_Halt);
  85040. #if SQLITE_USER_AUTHENTICATION
  85041. if( pParse->nTableLock>0 && db->init.busy==0 ){
  85042. sqlite3UserAuthInit(db);
  85043. if( db->auth.authLevel<UAUTH_User ){
  85044. pParse->rc = SQLITE_AUTH_USER;
  85045. sqlite3ErrorMsg(pParse, "user not authenticated");
  85046. return;
  85047. }
  85048. }
  85049. #endif
  85050. /* The cookie mask contains one bit for each database file open.
  85051. ** (Bit 0 is for main, bit 1 is for temp, and so forth.) Bits are
  85052. ** set for each database that is used. Generate code to start a
  85053. ** transaction on each used database and to verify the schema cookie
  85054. ** on each used database.
  85055. */
  85056. if( db->mallocFailed==0
  85057. && (DbMaskNonZero(pParse->cookieMask) || pParse->pConstExpr)
  85058. ){
  85059. int iDb, i;
  85060. assert( sqlite3VdbeGetOp(v, 0)->opcode==OP_Init );
  85061. sqlite3VdbeJumpHere(v, 0);
  85062. for(iDb=0; iDb<db->nDb; iDb++){
  85063. if( DbMaskTest(pParse->cookieMask, iDb)==0 ) continue;
  85064. sqlite3VdbeUsesBtree(v, iDb);
  85065. sqlite3VdbeAddOp4Int(v,
  85066. OP_Transaction, /* Opcode */
  85067. iDb, /* P1 */
  85068. DbMaskTest(pParse->writeMask,iDb), /* P2 */
  85069. pParse->cookieValue[iDb], /* P3 */
  85070. db->aDb[iDb].pSchema->iGeneration /* P4 */
  85071. );
  85072. if( db->init.busy==0 ) sqlite3VdbeChangeP5(v, 1);
  85073. }
  85074. #ifndef SQLITE_OMIT_VIRTUALTABLE
  85075. for(i=0; i<pParse->nVtabLock; i++){
  85076. char *vtab = (char *)sqlite3GetVTable(db, pParse->apVtabLock[i]);
  85077. sqlite3VdbeAddOp4(v, OP_VBegin, 0, 0, 0, vtab, P4_VTAB);
  85078. }
  85079. pParse->nVtabLock = 0;
  85080. #endif
  85081. /* Once all the cookies have been verified and transactions opened,
  85082. ** obtain the required table-locks. This is a no-op unless the
  85083. ** shared-cache feature is enabled.
  85084. */
  85085. codeTableLocks(pParse);
  85086. /* Initialize any AUTOINCREMENT data structures required.
  85087. */
  85088. sqlite3AutoincrementBegin(pParse);
  85089. /* Code constant expressions that where factored out of inner loops */
  85090. if( pParse->pConstExpr ){
  85091. ExprList *pEL = pParse->pConstExpr;
  85092. pParse->okConstFactor = 0;
  85093. for(i=0; i<pEL->nExpr; i++){
  85094. sqlite3ExprCode(pParse, pEL->a[i].pExpr, pEL->a[i].u.iConstExprReg);
  85095. }
  85096. }
  85097. /* Finally, jump back to the beginning of the executable code. */
  85098. sqlite3VdbeAddOp2(v, OP_Goto, 0, 1);
  85099. }
  85100. }
  85101. /* Get the VDBE program ready for execution
  85102. */
  85103. if( v && pParse->nErr==0 && !db->mallocFailed ){
  85104. assert( pParse->iCacheLevel==0 ); /* Disables and re-enables match */
  85105. /* A minimum of one cursor is required if autoincrement is used
  85106. * See ticket [a696379c1f08866] */
  85107. if( pParse->pAinc!=0 && pParse->nTab==0 ) pParse->nTab = 1;
  85108. sqlite3VdbeMakeReady(v, pParse);
  85109. pParse->rc = SQLITE_DONE;
  85110. pParse->colNamesSet = 0;
  85111. }else{
  85112. pParse->rc = SQLITE_ERROR;
  85113. }
  85114. pParse->nTab = 0;
  85115. pParse->nMem = 0;
  85116. pParse->nSet = 0;
  85117. pParse->nVar = 0;
  85118. DbMaskZero(pParse->cookieMask);
  85119. }
  85120. /*
  85121. ** Run the parser and code generator recursively in order to generate
  85122. ** code for the SQL statement given onto the end of the pParse context
  85123. ** currently under construction. When the parser is run recursively
  85124. ** this way, the final OP_Halt is not appended and other initialization
  85125. ** and finalization steps are omitted because those are handling by the
  85126. ** outermost parser.
  85127. **
  85128. ** Not everything is nestable. This facility is designed to permit
  85129. ** INSERT, UPDATE, and DELETE operations against SQLITE_MASTER. Use
  85130. ** care if you decide to try to use this routine for some other purposes.
  85131. */
  85132. SQLITE_PRIVATE void sqlite3NestedParse(Parse *pParse, const char *zFormat, ...){
  85133. va_list ap;
  85134. char *zSql;
  85135. char *zErrMsg = 0;
  85136. sqlite3 *db = pParse->db;
  85137. # define SAVE_SZ (sizeof(Parse) - offsetof(Parse,nVar))
  85138. char saveBuf[SAVE_SZ];
  85139. if( pParse->nErr ) return;
  85140. assert( pParse->nested<10 ); /* Nesting should only be of limited depth */
  85141. va_start(ap, zFormat);
  85142. zSql = sqlite3VMPrintf(db, zFormat, ap);
  85143. va_end(ap);
  85144. if( zSql==0 ){
  85145. return; /* A malloc must have failed */
  85146. }
  85147. pParse->nested++;
  85148. memcpy(saveBuf, &pParse->nVar, SAVE_SZ);
  85149. memset(&pParse->nVar, 0, SAVE_SZ);
  85150. sqlite3RunParser(pParse, zSql, &zErrMsg);
  85151. sqlite3DbFree(db, zErrMsg);
  85152. sqlite3DbFree(db, zSql);
  85153. memcpy(&pParse->nVar, saveBuf, SAVE_SZ);
  85154. pParse->nested--;
  85155. }
  85156. #if SQLITE_USER_AUTHENTICATION
  85157. /*
  85158. ** Return TRUE if zTable is the name of the system table that stores the
  85159. ** list of users and their access credentials.
  85160. */
  85161. SQLITE_PRIVATE int sqlite3UserAuthTable(const char *zTable){
  85162. return sqlite3_stricmp(zTable, "sqlite_user")==0;
  85163. }
  85164. #endif
  85165. /*
  85166. ** Locate the in-memory structure that describes a particular database
  85167. ** table given the name of that table and (optionally) the name of the
  85168. ** database containing the table. Return NULL if not found.
  85169. **
  85170. ** If zDatabase is 0, all databases are searched for the table and the
  85171. ** first matching table is returned. (No checking for duplicate table
  85172. ** names is done.) The search order is TEMP first, then MAIN, then any
  85173. ** auxiliary databases added using the ATTACH command.
  85174. **
  85175. ** See also sqlite3LocateTable().
  85176. */
  85177. SQLITE_PRIVATE Table *sqlite3FindTable(sqlite3 *db, const char *zName, const char *zDatabase){
  85178. Table *p = 0;
  85179. int i;
  85180. /* All mutexes are required for schema access. Make sure we hold them. */
  85181. assert( zDatabase!=0 || sqlite3BtreeHoldsAllMutexes(db) );
  85182. #if SQLITE_USER_AUTHENTICATION
  85183. /* Only the admin user is allowed to know that the sqlite_user table
  85184. ** exists */
  85185. if( db->auth.authLevel<UAUTH_Admin && sqlite3UserAuthTable(zName)!=0 ){
  85186. return 0;
  85187. }
  85188. #endif
  85189. for(i=OMIT_TEMPDB; i<db->nDb; i++){
  85190. int j = (i<2) ? i^1 : i; /* Search TEMP before MAIN */
  85191. if( zDatabase!=0 && sqlite3StrICmp(zDatabase, db->aDb[j].zName) ) continue;
  85192. assert( sqlite3SchemaMutexHeld(db, j, 0) );
  85193. p = sqlite3HashFind(&db->aDb[j].pSchema->tblHash, zName);
  85194. if( p ) break;
  85195. }
  85196. return p;
  85197. }
  85198. /*
  85199. ** Locate the in-memory structure that describes a particular database
  85200. ** table given the name of that table and (optionally) the name of the
  85201. ** database containing the table. Return NULL if not found. Also leave an
  85202. ** error message in pParse->zErrMsg.
  85203. **
  85204. ** The difference between this routine and sqlite3FindTable() is that this
  85205. ** routine leaves an error message in pParse->zErrMsg where
  85206. ** sqlite3FindTable() does not.
  85207. */
  85208. SQLITE_PRIVATE Table *sqlite3LocateTable(
  85209. Parse *pParse, /* context in which to report errors */
  85210. int isView, /* True if looking for a VIEW rather than a TABLE */
  85211. const char *zName, /* Name of the table we are looking for */
  85212. const char *zDbase /* Name of the database. Might be NULL */
  85213. ){
  85214. Table *p;
  85215. /* Read the database schema. If an error occurs, leave an error message
  85216. ** and code in pParse and return NULL. */
  85217. if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
  85218. return 0;
  85219. }
  85220. p = sqlite3FindTable(pParse->db, zName, zDbase);
  85221. if( p==0 ){
  85222. const char *zMsg = isView ? "no such view" : "no such table";
  85223. if( zDbase ){
  85224. sqlite3ErrorMsg(pParse, "%s: %s.%s", zMsg, zDbase, zName);
  85225. }else{
  85226. sqlite3ErrorMsg(pParse, "%s: %s", zMsg, zName);
  85227. }
  85228. pParse->checkSchema = 1;
  85229. }
  85230. #if SQLITE_USER_AUTHENICATION
  85231. else if( pParse->db->auth.authLevel<UAUTH_User ){
  85232. sqlite3ErrorMsg(pParse, "user not authenticated");
  85233. p = 0;
  85234. }
  85235. #endif
  85236. return p;
  85237. }
  85238. /*
  85239. ** Locate the table identified by *p.
  85240. **
  85241. ** This is a wrapper around sqlite3LocateTable(). The difference between
  85242. ** sqlite3LocateTable() and this function is that this function restricts
  85243. ** the search to schema (p->pSchema) if it is not NULL. p->pSchema may be
  85244. ** non-NULL if it is part of a view or trigger program definition. See
  85245. ** sqlite3FixSrcList() for details.
  85246. */
  85247. SQLITE_PRIVATE Table *sqlite3LocateTableItem(
  85248. Parse *pParse,
  85249. int isView,
  85250. struct SrcList_item *p
  85251. ){
  85252. const char *zDb;
  85253. assert( p->pSchema==0 || p->zDatabase==0 );
  85254. if( p->pSchema ){
  85255. int iDb = sqlite3SchemaToIndex(pParse->db, p->pSchema);
  85256. zDb = pParse->db->aDb[iDb].zName;
  85257. }else{
  85258. zDb = p->zDatabase;
  85259. }
  85260. return sqlite3LocateTable(pParse, isView, p->zName, zDb);
  85261. }
  85262. /*
  85263. ** Locate the in-memory structure that describes
  85264. ** a particular index given the name of that index
  85265. ** and the name of the database that contains the index.
  85266. ** Return NULL if not found.
  85267. **
  85268. ** If zDatabase is 0, all databases are searched for the
  85269. ** table and the first matching index is returned. (No checking
  85270. ** for duplicate index names is done.) The search order is
  85271. ** TEMP first, then MAIN, then any auxiliary databases added
  85272. ** using the ATTACH command.
  85273. */
  85274. SQLITE_PRIVATE Index *sqlite3FindIndex(sqlite3 *db, const char *zName, const char *zDb){
  85275. Index *p = 0;
  85276. int i;
  85277. /* All mutexes are required for schema access. Make sure we hold them. */
  85278. assert( zDb!=0 || sqlite3BtreeHoldsAllMutexes(db) );
  85279. for(i=OMIT_TEMPDB; i<db->nDb; i++){
  85280. int j = (i<2) ? i^1 : i; /* Search TEMP before MAIN */
  85281. Schema *pSchema = db->aDb[j].pSchema;
  85282. assert( pSchema );
  85283. if( zDb && sqlite3StrICmp(zDb, db->aDb[j].zName) ) continue;
  85284. assert( sqlite3SchemaMutexHeld(db, j, 0) );
  85285. p = sqlite3HashFind(&pSchema->idxHash, zName);
  85286. if( p ) break;
  85287. }
  85288. return p;
  85289. }
  85290. /*
  85291. ** Reclaim the memory used by an index
  85292. */
  85293. static void freeIndex(sqlite3 *db, Index *p){
  85294. #ifndef SQLITE_OMIT_ANALYZE
  85295. sqlite3DeleteIndexSamples(db, p);
  85296. #endif
  85297. sqlite3ExprDelete(db, p->pPartIdxWhere);
  85298. sqlite3DbFree(db, p->zColAff);
  85299. if( p->isResized ) sqlite3DbFree(db, p->azColl);
  85300. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  85301. sqlite3_free(p->aiRowEst);
  85302. #endif
  85303. sqlite3DbFree(db, p);
  85304. }
  85305. /*
  85306. ** For the index called zIdxName which is found in the database iDb,
  85307. ** unlike that index from its Table then remove the index from
  85308. ** the index hash table and free all memory structures associated
  85309. ** with the index.
  85310. */
  85311. SQLITE_PRIVATE void sqlite3UnlinkAndDeleteIndex(sqlite3 *db, int iDb, const char *zIdxName){
  85312. Index *pIndex;
  85313. Hash *pHash;
  85314. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  85315. pHash = &db->aDb[iDb].pSchema->idxHash;
  85316. pIndex = sqlite3HashInsert(pHash, zIdxName, 0);
  85317. if( ALWAYS(pIndex) ){
  85318. if( pIndex->pTable->pIndex==pIndex ){
  85319. pIndex->pTable->pIndex = pIndex->pNext;
  85320. }else{
  85321. Index *p;
  85322. /* Justification of ALWAYS(); The index must be on the list of
  85323. ** indices. */
  85324. p = pIndex->pTable->pIndex;
  85325. while( ALWAYS(p) && p->pNext!=pIndex ){ p = p->pNext; }
  85326. if( ALWAYS(p && p->pNext==pIndex) ){
  85327. p->pNext = pIndex->pNext;
  85328. }
  85329. }
  85330. freeIndex(db, pIndex);
  85331. }
  85332. db->flags |= SQLITE_InternChanges;
  85333. }
  85334. /*
  85335. ** Look through the list of open database files in db->aDb[] and if
  85336. ** any have been closed, remove them from the list. Reallocate the
  85337. ** db->aDb[] structure to a smaller size, if possible.
  85338. **
  85339. ** Entry 0 (the "main" database) and entry 1 (the "temp" database)
  85340. ** are never candidates for being collapsed.
  85341. */
  85342. SQLITE_PRIVATE void sqlite3CollapseDatabaseArray(sqlite3 *db){
  85343. int i, j;
  85344. for(i=j=2; i<db->nDb; i++){
  85345. struct Db *pDb = &db->aDb[i];
  85346. if( pDb->pBt==0 ){
  85347. sqlite3DbFree(db, pDb->zName);
  85348. pDb->zName = 0;
  85349. continue;
  85350. }
  85351. if( j<i ){
  85352. db->aDb[j] = db->aDb[i];
  85353. }
  85354. j++;
  85355. }
  85356. memset(&db->aDb[j], 0, (db->nDb-j)*sizeof(db->aDb[j]));
  85357. db->nDb = j;
  85358. if( db->nDb<=2 && db->aDb!=db->aDbStatic ){
  85359. memcpy(db->aDbStatic, db->aDb, 2*sizeof(db->aDb[0]));
  85360. sqlite3DbFree(db, db->aDb);
  85361. db->aDb = db->aDbStatic;
  85362. }
  85363. }
  85364. /*
  85365. ** Reset the schema for the database at index iDb. Also reset the
  85366. ** TEMP schema.
  85367. */
  85368. SQLITE_PRIVATE void sqlite3ResetOneSchema(sqlite3 *db, int iDb){
  85369. Db *pDb;
  85370. assert( iDb<db->nDb );
  85371. /* Case 1: Reset the single schema identified by iDb */
  85372. pDb = &db->aDb[iDb];
  85373. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  85374. assert( pDb->pSchema!=0 );
  85375. sqlite3SchemaClear(pDb->pSchema);
  85376. /* If any database other than TEMP is reset, then also reset TEMP
  85377. ** since TEMP might be holding triggers that reference tables in the
  85378. ** other database.
  85379. */
  85380. if( iDb!=1 ){
  85381. pDb = &db->aDb[1];
  85382. assert( pDb->pSchema!=0 );
  85383. sqlite3SchemaClear(pDb->pSchema);
  85384. }
  85385. return;
  85386. }
  85387. /*
  85388. ** Erase all schema information from all attached databases (including
  85389. ** "main" and "temp") for a single database connection.
  85390. */
  85391. SQLITE_PRIVATE void sqlite3ResetAllSchemasOfConnection(sqlite3 *db){
  85392. int i;
  85393. sqlite3BtreeEnterAll(db);
  85394. for(i=0; i<db->nDb; i++){
  85395. Db *pDb = &db->aDb[i];
  85396. if( pDb->pSchema ){
  85397. sqlite3SchemaClear(pDb->pSchema);
  85398. }
  85399. }
  85400. db->flags &= ~SQLITE_InternChanges;
  85401. sqlite3VtabUnlockList(db);
  85402. sqlite3BtreeLeaveAll(db);
  85403. sqlite3CollapseDatabaseArray(db);
  85404. }
  85405. /*
  85406. ** This routine is called when a commit occurs.
  85407. */
  85408. SQLITE_PRIVATE void sqlite3CommitInternalChanges(sqlite3 *db){
  85409. db->flags &= ~SQLITE_InternChanges;
  85410. }
  85411. /*
  85412. ** Delete memory allocated for the column names of a table or view (the
  85413. ** Table.aCol[] array).
  85414. */
  85415. static void sqliteDeleteColumnNames(sqlite3 *db, Table *pTable){
  85416. int i;
  85417. Column *pCol;
  85418. assert( pTable!=0 );
  85419. if( (pCol = pTable->aCol)!=0 ){
  85420. for(i=0; i<pTable->nCol; i++, pCol++){
  85421. sqlite3DbFree(db, pCol->zName);
  85422. sqlite3ExprDelete(db, pCol->pDflt);
  85423. sqlite3DbFree(db, pCol->zDflt);
  85424. sqlite3DbFree(db, pCol->zType);
  85425. sqlite3DbFree(db, pCol->zColl);
  85426. }
  85427. sqlite3DbFree(db, pTable->aCol);
  85428. }
  85429. }
  85430. /*
  85431. ** Remove the memory data structures associated with the given
  85432. ** Table. No changes are made to disk by this routine.
  85433. **
  85434. ** This routine just deletes the data structure. It does not unlink
  85435. ** the table data structure from the hash table. But it does destroy
  85436. ** memory structures of the indices and foreign keys associated with
  85437. ** the table.
  85438. **
  85439. ** The db parameter is optional. It is needed if the Table object
  85440. ** contains lookaside memory. (Table objects in the schema do not use
  85441. ** lookaside memory, but some ephemeral Table objects do.) Or the
  85442. ** db parameter can be used with db->pnBytesFreed to measure the memory
  85443. ** used by the Table object.
  85444. */
  85445. SQLITE_PRIVATE void sqlite3DeleteTable(sqlite3 *db, Table *pTable){
  85446. Index *pIndex, *pNext;
  85447. TESTONLY( int nLookaside; ) /* Used to verify lookaside not used for schema */
  85448. assert( !pTable || pTable->nRef>0 );
  85449. /* Do not delete the table until the reference count reaches zero. */
  85450. if( !pTable ) return;
  85451. if( ((!db || db->pnBytesFreed==0) && (--pTable->nRef)>0) ) return;
  85452. /* Record the number of outstanding lookaside allocations in schema Tables
  85453. ** prior to doing any free() operations. Since schema Tables do not use
  85454. ** lookaside, this number should not change. */
  85455. TESTONLY( nLookaside = (db && (pTable->tabFlags & TF_Ephemeral)==0) ?
  85456. db->lookaside.nOut : 0 );
  85457. /* Delete all indices associated with this table. */
  85458. for(pIndex = pTable->pIndex; pIndex; pIndex=pNext){
  85459. pNext = pIndex->pNext;
  85460. assert( pIndex->pSchema==pTable->pSchema );
  85461. if( !db || db->pnBytesFreed==0 ){
  85462. char *zName = pIndex->zName;
  85463. TESTONLY ( Index *pOld = ) sqlite3HashInsert(
  85464. &pIndex->pSchema->idxHash, zName, 0
  85465. );
  85466. assert( db==0 || sqlite3SchemaMutexHeld(db, 0, pIndex->pSchema) );
  85467. assert( pOld==pIndex || pOld==0 );
  85468. }
  85469. freeIndex(db, pIndex);
  85470. }
  85471. /* Delete any foreign keys attached to this table. */
  85472. sqlite3FkDelete(db, pTable);
  85473. /* Delete the Table structure itself.
  85474. */
  85475. sqliteDeleteColumnNames(db, pTable);
  85476. sqlite3DbFree(db, pTable->zName);
  85477. sqlite3DbFree(db, pTable->zColAff);
  85478. sqlite3SelectDelete(db, pTable->pSelect);
  85479. #ifndef SQLITE_OMIT_CHECK
  85480. sqlite3ExprListDelete(db, pTable->pCheck);
  85481. #endif
  85482. #ifndef SQLITE_OMIT_VIRTUALTABLE
  85483. sqlite3VtabClear(db, pTable);
  85484. #endif
  85485. sqlite3DbFree(db, pTable);
  85486. /* Verify that no lookaside memory was used by schema tables */
  85487. assert( nLookaside==0 || nLookaside==db->lookaside.nOut );
  85488. }
  85489. /*
  85490. ** Unlink the given table from the hash tables and the delete the
  85491. ** table structure with all its indices and foreign keys.
  85492. */
  85493. SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTable(sqlite3 *db, int iDb, const char *zTabName){
  85494. Table *p;
  85495. Db *pDb;
  85496. assert( db!=0 );
  85497. assert( iDb>=0 && iDb<db->nDb );
  85498. assert( zTabName );
  85499. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  85500. testcase( zTabName[0]==0 ); /* Zero-length table names are allowed */
  85501. pDb = &db->aDb[iDb];
  85502. p = sqlite3HashInsert(&pDb->pSchema->tblHash, zTabName, 0);
  85503. sqlite3DeleteTable(db, p);
  85504. db->flags |= SQLITE_InternChanges;
  85505. }
  85506. /*
  85507. ** Given a token, return a string that consists of the text of that
  85508. ** token. Space to hold the returned string
  85509. ** is obtained from sqliteMalloc() and must be freed by the calling
  85510. ** function.
  85511. **
  85512. ** Any quotation marks (ex: "name", 'name', [name], or `name`) that
  85513. ** surround the body of the token are removed.
  85514. **
  85515. ** Tokens are often just pointers into the original SQL text and so
  85516. ** are not \000 terminated and are not persistent. The returned string
  85517. ** is \000 terminated and is persistent.
  85518. */
  85519. SQLITE_PRIVATE char *sqlite3NameFromToken(sqlite3 *db, Token *pName){
  85520. char *zName;
  85521. if( pName ){
  85522. zName = sqlite3DbStrNDup(db, (char*)pName->z, pName->n);
  85523. sqlite3Dequote(zName);
  85524. }else{
  85525. zName = 0;
  85526. }
  85527. return zName;
  85528. }
  85529. /*
  85530. ** Open the sqlite_master table stored in database number iDb for
  85531. ** writing. The table is opened using cursor 0.
  85532. */
  85533. SQLITE_PRIVATE void sqlite3OpenMasterTable(Parse *p, int iDb){
  85534. Vdbe *v = sqlite3GetVdbe(p);
  85535. sqlite3TableLock(p, iDb, MASTER_ROOT, 1, SCHEMA_TABLE(iDb));
  85536. sqlite3VdbeAddOp4Int(v, OP_OpenWrite, 0, MASTER_ROOT, iDb, 5);
  85537. if( p->nTab==0 ){
  85538. p->nTab = 1;
  85539. }
  85540. }
  85541. /*
  85542. ** Parameter zName points to a nul-terminated buffer containing the name
  85543. ** of a database ("main", "temp" or the name of an attached db). This
  85544. ** function returns the index of the named database in db->aDb[], or
  85545. ** -1 if the named db cannot be found.
  85546. */
  85547. SQLITE_PRIVATE int sqlite3FindDbName(sqlite3 *db, const char *zName){
  85548. int i = -1; /* Database number */
  85549. if( zName ){
  85550. Db *pDb;
  85551. int n = sqlite3Strlen30(zName);
  85552. for(i=(db->nDb-1), pDb=&db->aDb[i]; i>=0; i--, pDb--){
  85553. if( (!OMIT_TEMPDB || i!=1 ) && n==sqlite3Strlen30(pDb->zName) &&
  85554. 0==sqlite3StrICmp(pDb->zName, zName) ){
  85555. break;
  85556. }
  85557. }
  85558. }
  85559. return i;
  85560. }
  85561. /*
  85562. ** The token *pName contains the name of a database (either "main" or
  85563. ** "temp" or the name of an attached db). This routine returns the
  85564. ** index of the named database in db->aDb[], or -1 if the named db
  85565. ** does not exist.
  85566. */
  85567. SQLITE_PRIVATE int sqlite3FindDb(sqlite3 *db, Token *pName){
  85568. int i; /* Database number */
  85569. char *zName; /* Name we are searching for */
  85570. zName = sqlite3NameFromToken(db, pName);
  85571. i = sqlite3FindDbName(db, zName);
  85572. sqlite3DbFree(db, zName);
  85573. return i;
  85574. }
  85575. /* The table or view or trigger name is passed to this routine via tokens
  85576. ** pName1 and pName2. If the table name was fully qualified, for example:
  85577. **
  85578. ** CREATE TABLE xxx.yyy (...);
  85579. **
  85580. ** Then pName1 is set to "xxx" and pName2 "yyy". On the other hand if
  85581. ** the table name is not fully qualified, i.e.:
  85582. **
  85583. ** CREATE TABLE yyy(...);
  85584. **
  85585. ** Then pName1 is set to "yyy" and pName2 is "".
  85586. **
  85587. ** This routine sets the *ppUnqual pointer to point at the token (pName1 or
  85588. ** pName2) that stores the unqualified table name. The index of the
  85589. ** database "xxx" is returned.
  85590. */
  85591. SQLITE_PRIVATE int sqlite3TwoPartName(
  85592. Parse *pParse, /* Parsing and code generating context */
  85593. Token *pName1, /* The "xxx" in the name "xxx.yyy" or "xxx" */
  85594. Token *pName2, /* The "yyy" in the name "xxx.yyy" */
  85595. Token **pUnqual /* Write the unqualified object name here */
  85596. ){
  85597. int iDb; /* Database holding the object */
  85598. sqlite3 *db = pParse->db;
  85599. if( ALWAYS(pName2!=0) && pName2->n>0 ){
  85600. if( db->init.busy ) {
  85601. sqlite3ErrorMsg(pParse, "corrupt database");
  85602. return -1;
  85603. }
  85604. *pUnqual = pName2;
  85605. iDb = sqlite3FindDb(db, pName1);
  85606. if( iDb<0 ){
  85607. sqlite3ErrorMsg(pParse, "unknown database %T", pName1);
  85608. return -1;
  85609. }
  85610. }else{
  85611. assert( db->init.iDb==0 || db->init.busy );
  85612. iDb = db->init.iDb;
  85613. *pUnqual = pName1;
  85614. }
  85615. return iDb;
  85616. }
  85617. /*
  85618. ** This routine is used to check if the UTF-8 string zName is a legal
  85619. ** unqualified name for a new schema object (table, index, view or
  85620. ** trigger). All names are legal except those that begin with the string
  85621. ** "sqlite_" (in upper, lower or mixed case). This portion of the namespace
  85622. ** is reserved for internal use.
  85623. */
  85624. SQLITE_PRIVATE int sqlite3CheckObjectName(Parse *pParse, const char *zName){
  85625. if( !pParse->db->init.busy && pParse->nested==0
  85626. && (pParse->db->flags & SQLITE_WriteSchema)==0
  85627. && 0==sqlite3StrNICmp(zName, "sqlite_", 7) ){
  85628. sqlite3ErrorMsg(pParse, "object name reserved for internal use: %s", zName);
  85629. return SQLITE_ERROR;
  85630. }
  85631. return SQLITE_OK;
  85632. }
  85633. /*
  85634. ** Return the PRIMARY KEY index of a table
  85635. */
  85636. SQLITE_PRIVATE Index *sqlite3PrimaryKeyIndex(Table *pTab){
  85637. Index *p;
  85638. for(p=pTab->pIndex; p && !IsPrimaryKeyIndex(p); p=p->pNext){}
  85639. return p;
  85640. }
  85641. /*
  85642. ** Return the column of index pIdx that corresponds to table
  85643. ** column iCol. Return -1 if not found.
  85644. */
  85645. SQLITE_PRIVATE i16 sqlite3ColumnOfIndex(Index *pIdx, i16 iCol){
  85646. int i;
  85647. for(i=0; i<pIdx->nColumn; i++){
  85648. if( iCol==pIdx->aiColumn[i] ) return i;
  85649. }
  85650. return -1;
  85651. }
  85652. /*
  85653. ** Begin constructing a new table representation in memory. This is
  85654. ** the first of several action routines that get called in response
  85655. ** to a CREATE TABLE statement. In particular, this routine is called
  85656. ** after seeing tokens "CREATE" and "TABLE" and the table name. The isTemp
  85657. ** flag is true if the table should be stored in the auxiliary database
  85658. ** file instead of in the main database file. This is normally the case
  85659. ** when the "TEMP" or "TEMPORARY" keyword occurs in between
  85660. ** CREATE and TABLE.
  85661. **
  85662. ** The new table record is initialized and put in pParse->pNewTable.
  85663. ** As more of the CREATE TABLE statement is parsed, additional action
  85664. ** routines will be called to add more information to this record.
  85665. ** At the end of the CREATE TABLE statement, the sqlite3EndTable() routine
  85666. ** is called to complete the construction of the new table record.
  85667. */
  85668. SQLITE_PRIVATE void sqlite3StartTable(
  85669. Parse *pParse, /* Parser context */
  85670. Token *pName1, /* First part of the name of the table or view */
  85671. Token *pName2, /* Second part of the name of the table or view */
  85672. int isTemp, /* True if this is a TEMP table */
  85673. int isView, /* True if this is a VIEW */
  85674. int isVirtual, /* True if this is a VIRTUAL table */
  85675. int noErr /* Do nothing if table already exists */
  85676. ){
  85677. Table *pTable;
  85678. char *zName = 0; /* The name of the new table */
  85679. sqlite3 *db = pParse->db;
  85680. Vdbe *v;
  85681. int iDb; /* Database number to create the table in */
  85682. Token *pName; /* Unqualified name of the table to create */
  85683. /* The table or view name to create is passed to this routine via tokens
  85684. ** pName1 and pName2. If the table name was fully qualified, for example:
  85685. **
  85686. ** CREATE TABLE xxx.yyy (...);
  85687. **
  85688. ** Then pName1 is set to "xxx" and pName2 "yyy". On the other hand if
  85689. ** the table name is not fully qualified, i.e.:
  85690. **
  85691. ** CREATE TABLE yyy(...);
  85692. **
  85693. ** Then pName1 is set to "yyy" and pName2 is "".
  85694. **
  85695. ** The call below sets the pName pointer to point at the token (pName1 or
  85696. ** pName2) that stores the unqualified table name. The variable iDb is
  85697. ** set to the index of the database that the table or view is to be
  85698. ** created in.
  85699. */
  85700. iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
  85701. if( iDb<0 ) return;
  85702. if( !OMIT_TEMPDB && isTemp && pName2->n>0 && iDb!=1 ){
  85703. /* If creating a temp table, the name may not be qualified. Unless
  85704. ** the database name is "temp" anyway. */
  85705. sqlite3ErrorMsg(pParse, "temporary table name must be unqualified");
  85706. return;
  85707. }
  85708. if( !OMIT_TEMPDB && isTemp ) iDb = 1;
  85709. pParse->sNameToken = *pName;
  85710. zName = sqlite3NameFromToken(db, pName);
  85711. if( zName==0 ) return;
  85712. if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
  85713. goto begin_table_error;
  85714. }
  85715. if( db->init.iDb==1 ) isTemp = 1;
  85716. #ifndef SQLITE_OMIT_AUTHORIZATION
  85717. assert( (isTemp & 1)==isTemp );
  85718. {
  85719. int code;
  85720. char *zDb = db->aDb[iDb].zName;
  85721. if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(isTemp), 0, zDb) ){
  85722. goto begin_table_error;
  85723. }
  85724. if( isView ){
  85725. if( !OMIT_TEMPDB && isTemp ){
  85726. code = SQLITE_CREATE_TEMP_VIEW;
  85727. }else{
  85728. code = SQLITE_CREATE_VIEW;
  85729. }
  85730. }else{
  85731. if( !OMIT_TEMPDB && isTemp ){
  85732. code = SQLITE_CREATE_TEMP_TABLE;
  85733. }else{
  85734. code = SQLITE_CREATE_TABLE;
  85735. }
  85736. }
  85737. if( !isVirtual && sqlite3AuthCheck(pParse, code, zName, 0, zDb) ){
  85738. goto begin_table_error;
  85739. }
  85740. }
  85741. #endif
  85742. /* Make sure the new table name does not collide with an existing
  85743. ** index or table name in the same database. Issue an error message if
  85744. ** it does. The exception is if the statement being parsed was passed
  85745. ** to an sqlite3_declare_vtab() call. In that case only the column names
  85746. ** and types will be used, so there is no need to test for namespace
  85747. ** collisions.
  85748. */
  85749. if( !IN_DECLARE_VTAB ){
  85750. char *zDb = db->aDb[iDb].zName;
  85751. if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
  85752. goto begin_table_error;
  85753. }
  85754. pTable = sqlite3FindTable(db, zName, zDb);
  85755. if( pTable ){
  85756. if( !noErr ){
  85757. sqlite3ErrorMsg(pParse, "table %T already exists", pName);
  85758. }else{
  85759. assert( !db->init.busy || CORRUPT_DB );
  85760. sqlite3CodeVerifySchema(pParse, iDb);
  85761. }
  85762. goto begin_table_error;
  85763. }
  85764. if( sqlite3FindIndex(db, zName, zDb)!=0 ){
  85765. sqlite3ErrorMsg(pParse, "there is already an index named %s", zName);
  85766. goto begin_table_error;
  85767. }
  85768. }
  85769. pTable = sqlite3DbMallocZero(db, sizeof(Table));
  85770. if( pTable==0 ){
  85771. db->mallocFailed = 1;
  85772. pParse->rc = SQLITE_NOMEM;
  85773. pParse->nErr++;
  85774. goto begin_table_error;
  85775. }
  85776. pTable->zName = zName;
  85777. pTable->iPKey = -1;
  85778. pTable->pSchema = db->aDb[iDb].pSchema;
  85779. pTable->nRef = 1;
  85780. pTable->nRowLogEst = 200; assert( 200==sqlite3LogEst(1048576) );
  85781. assert( pParse->pNewTable==0 );
  85782. pParse->pNewTable = pTable;
  85783. /* If this is the magic sqlite_sequence table used by autoincrement,
  85784. ** then record a pointer to this table in the main database structure
  85785. ** so that INSERT can find the table easily.
  85786. */
  85787. #ifndef SQLITE_OMIT_AUTOINCREMENT
  85788. if( !pParse->nested && strcmp(zName, "sqlite_sequence")==0 ){
  85789. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  85790. pTable->pSchema->pSeqTab = pTable;
  85791. }
  85792. #endif
  85793. /* Begin generating the code that will insert the table record into
  85794. ** the SQLITE_MASTER table. Note in particular that we must go ahead
  85795. ** and allocate the record number for the table entry now. Before any
  85796. ** PRIMARY KEY or UNIQUE keywords are parsed. Those keywords will cause
  85797. ** indices to be created and the table record must come before the
  85798. ** indices. Hence, the record number for the table must be allocated
  85799. ** now.
  85800. */
  85801. if( !db->init.busy && (v = sqlite3GetVdbe(pParse))!=0 ){
  85802. int j1;
  85803. int fileFormat;
  85804. int reg1, reg2, reg3;
  85805. sqlite3BeginWriteOperation(pParse, 0, iDb);
  85806. #ifndef SQLITE_OMIT_VIRTUALTABLE
  85807. if( isVirtual ){
  85808. sqlite3VdbeAddOp0(v, OP_VBegin);
  85809. }
  85810. #endif
  85811. /* If the file format and encoding in the database have not been set,
  85812. ** set them now.
  85813. */
  85814. reg1 = pParse->regRowid = ++pParse->nMem;
  85815. reg2 = pParse->regRoot = ++pParse->nMem;
  85816. reg3 = ++pParse->nMem;
  85817. sqlite3VdbeAddOp3(v, OP_ReadCookie, iDb, reg3, BTREE_FILE_FORMAT);
  85818. sqlite3VdbeUsesBtree(v, iDb);
  85819. j1 = sqlite3VdbeAddOp1(v, OP_If, reg3); VdbeCoverage(v);
  85820. fileFormat = (db->flags & SQLITE_LegacyFileFmt)!=0 ?
  85821. 1 : SQLITE_MAX_FILE_FORMAT;
  85822. sqlite3VdbeAddOp2(v, OP_Integer, fileFormat, reg3);
  85823. sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_FILE_FORMAT, reg3);
  85824. sqlite3VdbeAddOp2(v, OP_Integer, ENC(db), reg3);
  85825. sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_TEXT_ENCODING, reg3);
  85826. sqlite3VdbeJumpHere(v, j1);
  85827. /* This just creates a place-holder record in the sqlite_master table.
  85828. ** The record created does not contain anything yet. It will be replaced
  85829. ** by the real entry in code generated at sqlite3EndTable().
  85830. **
  85831. ** The rowid for the new entry is left in register pParse->regRowid.
  85832. ** The root page number of the new table is left in reg pParse->regRoot.
  85833. ** The rowid and root page number values are needed by the code that
  85834. ** sqlite3EndTable will generate.
  85835. */
  85836. #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
  85837. if( isView || isVirtual ){
  85838. sqlite3VdbeAddOp2(v, OP_Integer, 0, reg2);
  85839. }else
  85840. #endif
  85841. {
  85842. pParse->addrCrTab = sqlite3VdbeAddOp2(v, OP_CreateTable, iDb, reg2);
  85843. }
  85844. sqlite3OpenMasterTable(pParse, iDb);
  85845. sqlite3VdbeAddOp2(v, OP_NewRowid, 0, reg1);
  85846. sqlite3VdbeAddOp2(v, OP_Null, 0, reg3);
  85847. sqlite3VdbeAddOp3(v, OP_Insert, 0, reg3, reg1);
  85848. sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
  85849. sqlite3VdbeAddOp0(v, OP_Close);
  85850. }
  85851. /* Normal (non-error) return. */
  85852. return;
  85853. /* If an error occurs, we jump here */
  85854. begin_table_error:
  85855. sqlite3DbFree(db, zName);
  85856. return;
  85857. }
  85858. /*
  85859. ** This macro is used to compare two strings in a case-insensitive manner.
  85860. ** It is slightly faster than calling sqlite3StrICmp() directly, but
  85861. ** produces larger code.
  85862. **
  85863. ** WARNING: This macro is not compatible with the strcmp() family. It
  85864. ** returns true if the two strings are equal, otherwise false.
  85865. */
  85866. #define STRICMP(x, y) (\
  85867. sqlite3UpperToLower[*(unsigned char *)(x)]== \
  85868. sqlite3UpperToLower[*(unsigned char *)(y)] \
  85869. && sqlite3StrICmp((x)+1,(y)+1)==0 )
  85870. /*
  85871. ** Add a new column to the table currently being constructed.
  85872. **
  85873. ** The parser calls this routine once for each column declaration
  85874. ** in a CREATE TABLE statement. sqlite3StartTable() gets called
  85875. ** first to get things going. Then this routine is called for each
  85876. ** column.
  85877. */
  85878. SQLITE_PRIVATE void sqlite3AddColumn(Parse *pParse, Token *pName){
  85879. Table *p;
  85880. int i;
  85881. char *z;
  85882. Column *pCol;
  85883. sqlite3 *db = pParse->db;
  85884. if( (p = pParse->pNewTable)==0 ) return;
  85885. #if SQLITE_MAX_COLUMN
  85886. if( p->nCol+1>db->aLimit[SQLITE_LIMIT_COLUMN] ){
  85887. sqlite3ErrorMsg(pParse, "too many columns on %s", p->zName);
  85888. return;
  85889. }
  85890. #endif
  85891. z = sqlite3NameFromToken(db, pName);
  85892. if( z==0 ) return;
  85893. for(i=0; i<p->nCol; i++){
  85894. if( STRICMP(z, p->aCol[i].zName) ){
  85895. sqlite3ErrorMsg(pParse, "duplicate column name: %s", z);
  85896. sqlite3DbFree(db, z);
  85897. return;
  85898. }
  85899. }
  85900. if( (p->nCol & 0x7)==0 ){
  85901. Column *aNew;
  85902. aNew = sqlite3DbRealloc(db,p->aCol,(p->nCol+8)*sizeof(p->aCol[0]));
  85903. if( aNew==0 ){
  85904. sqlite3DbFree(db, z);
  85905. return;
  85906. }
  85907. p->aCol = aNew;
  85908. }
  85909. pCol = &p->aCol[p->nCol];
  85910. memset(pCol, 0, sizeof(p->aCol[0]));
  85911. pCol->zName = z;
  85912. /* If there is no type specified, columns have the default affinity
  85913. ** 'NONE'. If there is a type specified, then sqlite3AddColumnType() will
  85914. ** be called next to set pCol->affinity correctly.
  85915. */
  85916. pCol->affinity = SQLITE_AFF_NONE;
  85917. pCol->szEst = 1;
  85918. p->nCol++;
  85919. }
  85920. /*
  85921. ** This routine is called by the parser while in the middle of
  85922. ** parsing a CREATE TABLE statement. A "NOT NULL" constraint has
  85923. ** been seen on a column. This routine sets the notNull flag on
  85924. ** the column currently under construction.
  85925. */
  85926. SQLITE_PRIVATE void sqlite3AddNotNull(Parse *pParse, int onError){
  85927. Table *p;
  85928. p = pParse->pNewTable;
  85929. if( p==0 || NEVER(p->nCol<1) ) return;
  85930. p->aCol[p->nCol-1].notNull = (u8)onError;
  85931. }
  85932. /*
  85933. ** Scan the column type name zType (length nType) and return the
  85934. ** associated affinity type.
  85935. **
  85936. ** This routine does a case-independent search of zType for the
  85937. ** substrings in the following table. If one of the substrings is
  85938. ** found, the corresponding affinity is returned. If zType contains
  85939. ** more than one of the substrings, entries toward the top of
  85940. ** the table take priority. For example, if zType is 'BLOBINT',
  85941. ** SQLITE_AFF_INTEGER is returned.
  85942. **
  85943. ** Substring | Affinity
  85944. ** --------------------------------
  85945. ** 'INT' | SQLITE_AFF_INTEGER
  85946. ** 'CHAR' | SQLITE_AFF_TEXT
  85947. ** 'CLOB' | SQLITE_AFF_TEXT
  85948. ** 'TEXT' | SQLITE_AFF_TEXT
  85949. ** 'BLOB' | SQLITE_AFF_NONE
  85950. ** 'REAL' | SQLITE_AFF_REAL
  85951. ** 'FLOA' | SQLITE_AFF_REAL
  85952. ** 'DOUB' | SQLITE_AFF_REAL
  85953. **
  85954. ** If none of the substrings in the above table are found,
  85955. ** SQLITE_AFF_NUMERIC is returned.
  85956. */
  85957. SQLITE_PRIVATE char sqlite3AffinityType(const char *zIn, u8 *pszEst){
  85958. u32 h = 0;
  85959. char aff = SQLITE_AFF_NUMERIC;
  85960. const char *zChar = 0;
  85961. if( zIn==0 ) return aff;
  85962. while( zIn[0] ){
  85963. h = (h<<8) + sqlite3UpperToLower[(*zIn)&0xff];
  85964. zIn++;
  85965. if( h==(('c'<<24)+('h'<<16)+('a'<<8)+'r') ){ /* CHAR */
  85966. aff = SQLITE_AFF_TEXT;
  85967. zChar = zIn;
  85968. }else if( h==(('c'<<24)+('l'<<16)+('o'<<8)+'b') ){ /* CLOB */
  85969. aff = SQLITE_AFF_TEXT;
  85970. }else if( h==(('t'<<24)+('e'<<16)+('x'<<8)+'t') ){ /* TEXT */
  85971. aff = SQLITE_AFF_TEXT;
  85972. }else if( h==(('b'<<24)+('l'<<16)+('o'<<8)+'b') /* BLOB */
  85973. && (aff==SQLITE_AFF_NUMERIC || aff==SQLITE_AFF_REAL) ){
  85974. aff = SQLITE_AFF_NONE;
  85975. if( zIn[0]=='(' ) zChar = zIn;
  85976. #ifndef SQLITE_OMIT_FLOATING_POINT
  85977. }else if( h==(('r'<<24)+('e'<<16)+('a'<<8)+'l') /* REAL */
  85978. && aff==SQLITE_AFF_NUMERIC ){
  85979. aff = SQLITE_AFF_REAL;
  85980. }else if( h==(('f'<<24)+('l'<<16)+('o'<<8)+'a') /* FLOA */
  85981. && aff==SQLITE_AFF_NUMERIC ){
  85982. aff = SQLITE_AFF_REAL;
  85983. }else if( h==(('d'<<24)+('o'<<16)+('u'<<8)+'b') /* DOUB */
  85984. && aff==SQLITE_AFF_NUMERIC ){
  85985. aff = SQLITE_AFF_REAL;
  85986. #endif
  85987. }else if( (h&0x00FFFFFF)==(('i'<<16)+('n'<<8)+'t') ){ /* INT */
  85988. aff = SQLITE_AFF_INTEGER;
  85989. break;
  85990. }
  85991. }
  85992. /* If pszEst is not NULL, store an estimate of the field size. The
  85993. ** estimate is scaled so that the size of an integer is 1. */
  85994. if( pszEst ){
  85995. *pszEst = 1; /* default size is approx 4 bytes */
  85996. if( aff<SQLITE_AFF_NUMERIC ){
  85997. if( zChar ){
  85998. while( zChar[0] ){
  85999. if( sqlite3Isdigit(zChar[0]) ){
  86000. int v = 0;
  86001. sqlite3GetInt32(zChar, &v);
  86002. v = v/4 + 1;
  86003. if( v>255 ) v = 255;
  86004. *pszEst = v; /* BLOB(k), VARCHAR(k), CHAR(k) -> r=(k/4+1) */
  86005. break;
  86006. }
  86007. zChar++;
  86008. }
  86009. }else{
  86010. *pszEst = 5; /* BLOB, TEXT, CLOB -> r=5 (approx 20 bytes)*/
  86011. }
  86012. }
  86013. }
  86014. return aff;
  86015. }
  86016. /*
  86017. ** This routine is called by the parser while in the middle of
  86018. ** parsing a CREATE TABLE statement. The pFirst token is the first
  86019. ** token in the sequence of tokens that describe the type of the
  86020. ** column currently under construction. pLast is the last token
  86021. ** in the sequence. Use this information to construct a string
  86022. ** that contains the typename of the column and store that string
  86023. ** in zType.
  86024. */
  86025. SQLITE_PRIVATE void sqlite3AddColumnType(Parse *pParse, Token *pType){
  86026. Table *p;
  86027. Column *pCol;
  86028. p = pParse->pNewTable;
  86029. if( p==0 || NEVER(p->nCol<1) ) return;
  86030. pCol = &p->aCol[p->nCol-1];
  86031. assert( pCol->zType==0 || CORRUPT_DB );
  86032. sqlite3DbFree(pParse->db, pCol->zType);
  86033. pCol->zType = sqlite3NameFromToken(pParse->db, pType);
  86034. pCol->affinity = sqlite3AffinityType(pCol->zType, &pCol->szEst);
  86035. }
  86036. /*
  86037. ** The expression is the default value for the most recently added column
  86038. ** of the table currently under construction.
  86039. **
  86040. ** Default value expressions must be constant. Raise an exception if this
  86041. ** is not the case.
  86042. **
  86043. ** This routine is called by the parser while in the middle of
  86044. ** parsing a CREATE TABLE statement.
  86045. */
  86046. SQLITE_PRIVATE void sqlite3AddDefaultValue(Parse *pParse, ExprSpan *pSpan){
  86047. Table *p;
  86048. Column *pCol;
  86049. sqlite3 *db = pParse->db;
  86050. p = pParse->pNewTable;
  86051. if( p!=0 ){
  86052. pCol = &(p->aCol[p->nCol-1]);
  86053. if( !sqlite3ExprIsConstantOrFunction(pSpan->pExpr, db->init.busy) ){
  86054. sqlite3ErrorMsg(pParse, "default value of column [%s] is not constant",
  86055. pCol->zName);
  86056. }else{
  86057. /* A copy of pExpr is used instead of the original, as pExpr contains
  86058. ** tokens that point to volatile memory. The 'span' of the expression
  86059. ** is required by pragma table_info.
  86060. */
  86061. sqlite3ExprDelete(db, pCol->pDflt);
  86062. pCol->pDflt = sqlite3ExprDup(db, pSpan->pExpr, EXPRDUP_REDUCE);
  86063. sqlite3DbFree(db, pCol->zDflt);
  86064. pCol->zDflt = sqlite3DbStrNDup(db, (char*)pSpan->zStart,
  86065. (int)(pSpan->zEnd - pSpan->zStart));
  86066. }
  86067. }
  86068. sqlite3ExprDelete(db, pSpan->pExpr);
  86069. }
  86070. /*
  86071. ** Designate the PRIMARY KEY for the table. pList is a list of names
  86072. ** of columns that form the primary key. If pList is NULL, then the
  86073. ** most recently added column of the table is the primary key.
  86074. **
  86075. ** A table can have at most one primary key. If the table already has
  86076. ** a primary key (and this is the second primary key) then create an
  86077. ** error.
  86078. **
  86079. ** If the PRIMARY KEY is on a single column whose datatype is INTEGER,
  86080. ** then we will try to use that column as the rowid. Set the Table.iPKey
  86081. ** field of the table under construction to be the index of the
  86082. ** INTEGER PRIMARY KEY column. Table.iPKey is set to -1 if there is
  86083. ** no INTEGER PRIMARY KEY.
  86084. **
  86085. ** If the key is not an INTEGER PRIMARY KEY, then create a unique
  86086. ** index for the key. No index is created for INTEGER PRIMARY KEYs.
  86087. */
  86088. SQLITE_PRIVATE void sqlite3AddPrimaryKey(
  86089. Parse *pParse, /* Parsing context */
  86090. ExprList *pList, /* List of field names to be indexed */
  86091. int onError, /* What to do with a uniqueness conflict */
  86092. int autoInc, /* True if the AUTOINCREMENT keyword is present */
  86093. int sortOrder /* SQLITE_SO_ASC or SQLITE_SO_DESC */
  86094. ){
  86095. Table *pTab = pParse->pNewTable;
  86096. char *zType = 0;
  86097. int iCol = -1, i;
  86098. int nTerm;
  86099. if( pTab==0 || IN_DECLARE_VTAB ) goto primary_key_exit;
  86100. if( pTab->tabFlags & TF_HasPrimaryKey ){
  86101. sqlite3ErrorMsg(pParse,
  86102. "table \"%s\" has more than one primary key", pTab->zName);
  86103. goto primary_key_exit;
  86104. }
  86105. pTab->tabFlags |= TF_HasPrimaryKey;
  86106. if( pList==0 ){
  86107. iCol = pTab->nCol - 1;
  86108. pTab->aCol[iCol].colFlags |= COLFLAG_PRIMKEY;
  86109. zType = pTab->aCol[iCol].zType;
  86110. nTerm = 1;
  86111. }else{
  86112. nTerm = pList->nExpr;
  86113. for(i=0; i<nTerm; i++){
  86114. for(iCol=0; iCol<pTab->nCol; iCol++){
  86115. if( sqlite3StrICmp(pList->a[i].zName, pTab->aCol[iCol].zName)==0 ){
  86116. pTab->aCol[iCol].colFlags |= COLFLAG_PRIMKEY;
  86117. zType = pTab->aCol[iCol].zType;
  86118. break;
  86119. }
  86120. }
  86121. }
  86122. }
  86123. if( nTerm==1
  86124. && zType && sqlite3StrICmp(zType, "INTEGER")==0
  86125. && sortOrder==SQLITE_SO_ASC
  86126. ){
  86127. pTab->iPKey = iCol;
  86128. pTab->keyConf = (u8)onError;
  86129. assert( autoInc==0 || autoInc==1 );
  86130. pTab->tabFlags |= autoInc*TF_Autoincrement;
  86131. if( pList ) pParse->iPkSortOrder = pList->a[0].sortOrder;
  86132. }else if( autoInc ){
  86133. #ifndef SQLITE_OMIT_AUTOINCREMENT
  86134. sqlite3ErrorMsg(pParse, "AUTOINCREMENT is only allowed on an "
  86135. "INTEGER PRIMARY KEY");
  86136. #endif
  86137. }else{
  86138. Vdbe *v = pParse->pVdbe;
  86139. Index *p;
  86140. if( v ) pParse->addrSkipPK = sqlite3VdbeAddOp0(v, OP_Noop);
  86141. p = sqlite3CreateIndex(pParse, 0, 0, 0, pList, onError, 0,
  86142. 0, sortOrder, 0);
  86143. if( p ){
  86144. p->idxType = SQLITE_IDXTYPE_PRIMARYKEY;
  86145. if( v ) sqlite3VdbeJumpHere(v, pParse->addrSkipPK);
  86146. }
  86147. pList = 0;
  86148. }
  86149. primary_key_exit:
  86150. sqlite3ExprListDelete(pParse->db, pList);
  86151. return;
  86152. }
  86153. /*
  86154. ** Add a new CHECK constraint to the table currently under construction.
  86155. */
  86156. SQLITE_PRIVATE void sqlite3AddCheckConstraint(
  86157. Parse *pParse, /* Parsing context */
  86158. Expr *pCheckExpr /* The check expression */
  86159. ){
  86160. #ifndef SQLITE_OMIT_CHECK
  86161. Table *pTab = pParse->pNewTable;
  86162. sqlite3 *db = pParse->db;
  86163. if( pTab && !IN_DECLARE_VTAB
  86164. && !sqlite3BtreeIsReadonly(db->aDb[db->init.iDb].pBt)
  86165. ){
  86166. pTab->pCheck = sqlite3ExprListAppend(pParse, pTab->pCheck, pCheckExpr);
  86167. if( pParse->constraintName.n ){
  86168. sqlite3ExprListSetName(pParse, pTab->pCheck, &pParse->constraintName, 1);
  86169. }
  86170. }else
  86171. #endif
  86172. {
  86173. sqlite3ExprDelete(pParse->db, pCheckExpr);
  86174. }
  86175. }
  86176. /*
  86177. ** Set the collation function of the most recently parsed table column
  86178. ** to the CollSeq given.
  86179. */
  86180. SQLITE_PRIVATE void sqlite3AddCollateType(Parse *pParse, Token *pToken){
  86181. Table *p;
  86182. int i;
  86183. char *zColl; /* Dequoted name of collation sequence */
  86184. sqlite3 *db;
  86185. if( (p = pParse->pNewTable)==0 ) return;
  86186. i = p->nCol-1;
  86187. db = pParse->db;
  86188. zColl = sqlite3NameFromToken(db, pToken);
  86189. if( !zColl ) return;
  86190. if( sqlite3LocateCollSeq(pParse, zColl) ){
  86191. Index *pIdx;
  86192. sqlite3DbFree(db, p->aCol[i].zColl);
  86193. p->aCol[i].zColl = zColl;
  86194. /* If the column is declared as "<name> PRIMARY KEY COLLATE <type>",
  86195. ** then an index may have been created on this column before the
  86196. ** collation type was added. Correct this if it is the case.
  86197. */
  86198. for(pIdx=p->pIndex; pIdx; pIdx=pIdx->pNext){
  86199. assert( pIdx->nKeyCol==1 );
  86200. if( pIdx->aiColumn[0]==i ){
  86201. pIdx->azColl[0] = p->aCol[i].zColl;
  86202. }
  86203. }
  86204. }else{
  86205. sqlite3DbFree(db, zColl);
  86206. }
  86207. }
  86208. /*
  86209. ** This function returns the collation sequence for database native text
  86210. ** encoding identified by the string zName, length nName.
  86211. **
  86212. ** If the requested collation sequence is not available, or not available
  86213. ** in the database native encoding, the collation factory is invoked to
  86214. ** request it. If the collation factory does not supply such a sequence,
  86215. ** and the sequence is available in another text encoding, then that is
  86216. ** returned instead.
  86217. **
  86218. ** If no versions of the requested collations sequence are available, or
  86219. ** another error occurs, NULL is returned and an error message written into
  86220. ** pParse.
  86221. **
  86222. ** This routine is a wrapper around sqlite3FindCollSeq(). This routine
  86223. ** invokes the collation factory if the named collation cannot be found
  86224. ** and generates an error message.
  86225. **
  86226. ** See also: sqlite3FindCollSeq(), sqlite3GetCollSeq()
  86227. */
  86228. SQLITE_PRIVATE CollSeq *sqlite3LocateCollSeq(Parse *pParse, const char *zName){
  86229. sqlite3 *db = pParse->db;
  86230. u8 enc = ENC(db);
  86231. u8 initbusy = db->init.busy;
  86232. CollSeq *pColl;
  86233. pColl = sqlite3FindCollSeq(db, enc, zName, initbusy);
  86234. if( !initbusy && (!pColl || !pColl->xCmp) ){
  86235. pColl = sqlite3GetCollSeq(pParse, enc, pColl, zName);
  86236. }
  86237. return pColl;
  86238. }
  86239. /*
  86240. ** Generate code that will increment the schema cookie.
  86241. **
  86242. ** The schema cookie is used to determine when the schema for the
  86243. ** database changes. After each schema change, the cookie value
  86244. ** changes. When a process first reads the schema it records the
  86245. ** cookie. Thereafter, whenever it goes to access the database,
  86246. ** it checks the cookie to make sure the schema has not changed
  86247. ** since it was last read.
  86248. **
  86249. ** This plan is not completely bullet-proof. It is possible for
  86250. ** the schema to change multiple times and for the cookie to be
  86251. ** set back to prior value. But schema changes are infrequent
  86252. ** and the probability of hitting the same cookie value is only
  86253. ** 1 chance in 2^32. So we're safe enough.
  86254. */
  86255. SQLITE_PRIVATE void sqlite3ChangeCookie(Parse *pParse, int iDb){
  86256. int r1 = sqlite3GetTempReg(pParse);
  86257. sqlite3 *db = pParse->db;
  86258. Vdbe *v = pParse->pVdbe;
  86259. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  86260. sqlite3VdbeAddOp2(v, OP_Integer, db->aDb[iDb].pSchema->schema_cookie+1, r1);
  86261. sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_SCHEMA_VERSION, r1);
  86262. sqlite3ReleaseTempReg(pParse, r1);
  86263. }
  86264. /*
  86265. ** Measure the number of characters needed to output the given
  86266. ** identifier. The number returned includes any quotes used
  86267. ** but does not include the null terminator.
  86268. **
  86269. ** The estimate is conservative. It might be larger that what is
  86270. ** really needed.
  86271. */
  86272. static int identLength(const char *z){
  86273. int n;
  86274. for(n=0; *z; n++, z++){
  86275. if( *z=='"' ){ n++; }
  86276. }
  86277. return n + 2;
  86278. }
  86279. /*
  86280. ** The first parameter is a pointer to an output buffer. The second
  86281. ** parameter is a pointer to an integer that contains the offset at
  86282. ** which to write into the output buffer. This function copies the
  86283. ** nul-terminated string pointed to by the third parameter, zSignedIdent,
  86284. ** to the specified offset in the buffer and updates *pIdx to refer
  86285. ** to the first byte after the last byte written before returning.
  86286. **
  86287. ** If the string zSignedIdent consists entirely of alpha-numeric
  86288. ** characters, does not begin with a digit and is not an SQL keyword,
  86289. ** then it is copied to the output buffer exactly as it is. Otherwise,
  86290. ** it is quoted using double-quotes.
  86291. */
  86292. static void identPut(char *z, int *pIdx, char *zSignedIdent){
  86293. unsigned char *zIdent = (unsigned char*)zSignedIdent;
  86294. int i, j, needQuote;
  86295. i = *pIdx;
  86296. for(j=0; zIdent[j]; j++){
  86297. if( !sqlite3Isalnum(zIdent[j]) && zIdent[j]!='_' ) break;
  86298. }
  86299. needQuote = sqlite3Isdigit(zIdent[0])
  86300. || sqlite3KeywordCode(zIdent, j)!=TK_ID
  86301. || zIdent[j]!=0
  86302. || j==0;
  86303. if( needQuote ) z[i++] = '"';
  86304. for(j=0; zIdent[j]; j++){
  86305. z[i++] = zIdent[j];
  86306. if( zIdent[j]=='"' ) z[i++] = '"';
  86307. }
  86308. if( needQuote ) z[i++] = '"';
  86309. z[i] = 0;
  86310. *pIdx = i;
  86311. }
  86312. /*
  86313. ** Generate a CREATE TABLE statement appropriate for the given
  86314. ** table. Memory to hold the text of the statement is obtained
  86315. ** from sqliteMalloc() and must be freed by the calling function.
  86316. */
  86317. static char *createTableStmt(sqlite3 *db, Table *p){
  86318. int i, k, n;
  86319. char *zStmt;
  86320. char *zSep, *zSep2, *zEnd;
  86321. Column *pCol;
  86322. n = 0;
  86323. for(pCol = p->aCol, i=0; i<p->nCol; i++, pCol++){
  86324. n += identLength(pCol->zName) + 5;
  86325. }
  86326. n += identLength(p->zName);
  86327. if( n<50 ){
  86328. zSep = "";
  86329. zSep2 = ",";
  86330. zEnd = ")";
  86331. }else{
  86332. zSep = "\n ";
  86333. zSep2 = ",\n ";
  86334. zEnd = "\n)";
  86335. }
  86336. n += 35 + 6*p->nCol;
  86337. zStmt = sqlite3DbMallocRaw(0, n);
  86338. if( zStmt==0 ){
  86339. db->mallocFailed = 1;
  86340. return 0;
  86341. }
  86342. sqlite3_snprintf(n, zStmt, "CREATE TABLE ");
  86343. k = sqlite3Strlen30(zStmt);
  86344. identPut(zStmt, &k, p->zName);
  86345. zStmt[k++] = '(';
  86346. for(pCol=p->aCol, i=0; i<p->nCol; i++, pCol++){
  86347. static const char * const azType[] = {
  86348. /* SQLITE_AFF_NONE */ "",
  86349. /* SQLITE_AFF_TEXT */ " TEXT",
  86350. /* SQLITE_AFF_NUMERIC */ " NUM",
  86351. /* SQLITE_AFF_INTEGER */ " INT",
  86352. /* SQLITE_AFF_REAL */ " REAL"
  86353. };
  86354. int len;
  86355. const char *zType;
  86356. sqlite3_snprintf(n-k, &zStmt[k], zSep);
  86357. k += sqlite3Strlen30(&zStmt[k]);
  86358. zSep = zSep2;
  86359. identPut(zStmt, &k, pCol->zName);
  86360. assert( pCol->affinity-SQLITE_AFF_NONE >= 0 );
  86361. assert( pCol->affinity-SQLITE_AFF_NONE < ArraySize(azType) );
  86362. testcase( pCol->affinity==SQLITE_AFF_NONE );
  86363. testcase( pCol->affinity==SQLITE_AFF_TEXT );
  86364. testcase( pCol->affinity==SQLITE_AFF_NUMERIC );
  86365. testcase( pCol->affinity==SQLITE_AFF_INTEGER );
  86366. testcase( pCol->affinity==SQLITE_AFF_REAL );
  86367. zType = azType[pCol->affinity - SQLITE_AFF_NONE];
  86368. len = sqlite3Strlen30(zType);
  86369. assert( pCol->affinity==SQLITE_AFF_NONE
  86370. || pCol->affinity==sqlite3AffinityType(zType, 0) );
  86371. memcpy(&zStmt[k], zType, len);
  86372. k += len;
  86373. assert( k<=n );
  86374. }
  86375. sqlite3_snprintf(n-k, &zStmt[k], "%s", zEnd);
  86376. return zStmt;
  86377. }
  86378. /*
  86379. ** Resize an Index object to hold N columns total. Return SQLITE_OK
  86380. ** on success and SQLITE_NOMEM on an OOM error.
  86381. */
  86382. static int resizeIndexObject(sqlite3 *db, Index *pIdx, int N){
  86383. char *zExtra;
  86384. int nByte;
  86385. if( pIdx->nColumn>=N ) return SQLITE_OK;
  86386. assert( pIdx->isResized==0 );
  86387. nByte = (sizeof(char*) + sizeof(i16) + 1)*N;
  86388. zExtra = sqlite3DbMallocZero(db, nByte);
  86389. if( zExtra==0 ) return SQLITE_NOMEM;
  86390. memcpy(zExtra, pIdx->azColl, sizeof(char*)*pIdx->nColumn);
  86391. pIdx->azColl = (char**)zExtra;
  86392. zExtra += sizeof(char*)*N;
  86393. memcpy(zExtra, pIdx->aiColumn, sizeof(i16)*pIdx->nColumn);
  86394. pIdx->aiColumn = (i16*)zExtra;
  86395. zExtra += sizeof(i16)*N;
  86396. memcpy(zExtra, pIdx->aSortOrder, pIdx->nColumn);
  86397. pIdx->aSortOrder = (u8*)zExtra;
  86398. pIdx->nColumn = N;
  86399. pIdx->isResized = 1;
  86400. return SQLITE_OK;
  86401. }
  86402. /*
  86403. ** Estimate the total row width for a table.
  86404. */
  86405. static void estimateTableWidth(Table *pTab){
  86406. unsigned wTable = 0;
  86407. const Column *pTabCol;
  86408. int i;
  86409. for(i=pTab->nCol, pTabCol=pTab->aCol; i>0; i--, pTabCol++){
  86410. wTable += pTabCol->szEst;
  86411. }
  86412. if( pTab->iPKey<0 ) wTable++;
  86413. pTab->szTabRow = sqlite3LogEst(wTable*4);
  86414. }
  86415. /*
  86416. ** Estimate the average size of a row for an index.
  86417. */
  86418. static void estimateIndexWidth(Index *pIdx){
  86419. unsigned wIndex = 0;
  86420. int i;
  86421. const Column *aCol = pIdx->pTable->aCol;
  86422. for(i=0; i<pIdx->nColumn; i++){
  86423. i16 x = pIdx->aiColumn[i];
  86424. assert( x<pIdx->pTable->nCol );
  86425. wIndex += x<0 ? 1 : aCol[pIdx->aiColumn[i]].szEst;
  86426. }
  86427. pIdx->szIdxRow = sqlite3LogEst(wIndex*4);
  86428. }
  86429. /* Return true if value x is found any of the first nCol entries of aiCol[]
  86430. */
  86431. static int hasColumn(const i16 *aiCol, int nCol, int x){
  86432. while( nCol-- > 0 ) if( x==*(aiCol++) ) return 1;
  86433. return 0;
  86434. }
  86435. /*
  86436. ** This routine runs at the end of parsing a CREATE TABLE statement that
  86437. ** has a WITHOUT ROWID clause. The job of this routine is to convert both
  86438. ** internal schema data structures and the generated VDBE code so that they
  86439. ** are appropriate for a WITHOUT ROWID table instead of a rowid table.
  86440. ** Changes include:
  86441. **
  86442. ** (1) Convert the OP_CreateTable into an OP_CreateIndex. There is
  86443. ** no rowid btree for a WITHOUT ROWID. Instead, the canonical
  86444. ** data storage is a covering index btree.
  86445. ** (2) Bypass the creation of the sqlite_master table entry
  86446. ** for the PRIMARY KEY as the primary key index is now
  86447. ** identified by the sqlite_master table entry of the table itself.
  86448. ** (3) Set the Index.tnum of the PRIMARY KEY Index object in the
  86449. ** schema to the rootpage from the main table.
  86450. ** (4) Set all columns of the PRIMARY KEY schema object to be NOT NULL.
  86451. ** (5) Add all table columns to the PRIMARY KEY Index object
  86452. ** so that the PRIMARY KEY is a covering index. The surplus
  86453. ** columns are part of KeyInfo.nXField and are not used for
  86454. ** sorting or lookup or uniqueness checks.
  86455. ** (6) Replace the rowid tail on all automatically generated UNIQUE
  86456. ** indices with the PRIMARY KEY columns.
  86457. */
  86458. static void convertToWithoutRowidTable(Parse *pParse, Table *pTab){
  86459. Index *pIdx;
  86460. Index *pPk;
  86461. int nPk;
  86462. int i, j;
  86463. sqlite3 *db = pParse->db;
  86464. Vdbe *v = pParse->pVdbe;
  86465. /* Convert the OP_CreateTable opcode that would normally create the
  86466. ** root-page for the table into an OP_CreateIndex opcode. The index
  86467. ** created will become the PRIMARY KEY index.
  86468. */
  86469. if( pParse->addrCrTab ){
  86470. assert( v );
  86471. sqlite3VdbeGetOp(v, pParse->addrCrTab)->opcode = OP_CreateIndex;
  86472. }
  86473. /* Bypass the creation of the PRIMARY KEY btree and the sqlite_master
  86474. ** table entry.
  86475. */
  86476. if( pParse->addrSkipPK ){
  86477. assert( v );
  86478. sqlite3VdbeGetOp(v, pParse->addrSkipPK)->opcode = OP_Goto;
  86479. }
  86480. /* Locate the PRIMARY KEY index. Or, if this table was originally
  86481. ** an INTEGER PRIMARY KEY table, create a new PRIMARY KEY index.
  86482. */
  86483. if( pTab->iPKey>=0 ){
  86484. ExprList *pList;
  86485. pList = sqlite3ExprListAppend(pParse, 0, 0);
  86486. if( pList==0 ) return;
  86487. pList->a[0].zName = sqlite3DbStrDup(pParse->db,
  86488. pTab->aCol[pTab->iPKey].zName);
  86489. pList->a[0].sortOrder = pParse->iPkSortOrder;
  86490. assert( pParse->pNewTable==pTab );
  86491. pPk = sqlite3CreateIndex(pParse, 0, 0, 0, pList, pTab->keyConf, 0, 0, 0, 0);
  86492. if( pPk==0 ) return;
  86493. pPk->idxType = SQLITE_IDXTYPE_PRIMARYKEY;
  86494. pTab->iPKey = -1;
  86495. }else{
  86496. pPk = sqlite3PrimaryKeyIndex(pTab);
  86497. /*
  86498. ** Remove all redundant columns from the PRIMARY KEY. For example, change
  86499. ** "PRIMARY KEY(a,b,a,b,c,b,c,d)" into just "PRIMARY KEY(a,b,c,d)". Later
  86500. ** code assumes the PRIMARY KEY contains no repeated columns.
  86501. */
  86502. for(i=j=1; i<pPk->nKeyCol; i++){
  86503. if( hasColumn(pPk->aiColumn, j, pPk->aiColumn[i]) ){
  86504. pPk->nColumn--;
  86505. }else{
  86506. pPk->aiColumn[j++] = pPk->aiColumn[i];
  86507. }
  86508. }
  86509. pPk->nKeyCol = j;
  86510. }
  86511. pPk->isCovering = 1;
  86512. assert( pPk!=0 );
  86513. nPk = pPk->nKeyCol;
  86514. /* Make sure every column of the PRIMARY KEY is NOT NULL. (Except,
  86515. ** do not enforce this for imposter tables.) */
  86516. if( !db->init.imposterTable ){
  86517. for(i=0; i<nPk; i++){
  86518. pTab->aCol[pPk->aiColumn[i]].notNull = 1;
  86519. }
  86520. pPk->uniqNotNull = 1;
  86521. }
  86522. /* The root page of the PRIMARY KEY is the table root page */
  86523. pPk->tnum = pTab->tnum;
  86524. /* Update the in-memory representation of all UNIQUE indices by converting
  86525. ** the final rowid column into one or more columns of the PRIMARY KEY.
  86526. */
  86527. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  86528. int n;
  86529. if( IsPrimaryKeyIndex(pIdx) ) continue;
  86530. for(i=n=0; i<nPk; i++){
  86531. if( !hasColumn(pIdx->aiColumn, pIdx->nKeyCol, pPk->aiColumn[i]) ) n++;
  86532. }
  86533. if( n==0 ){
  86534. /* This index is a superset of the primary key */
  86535. pIdx->nColumn = pIdx->nKeyCol;
  86536. continue;
  86537. }
  86538. if( resizeIndexObject(db, pIdx, pIdx->nKeyCol+n) ) return;
  86539. for(i=0, j=pIdx->nKeyCol; i<nPk; i++){
  86540. if( !hasColumn(pIdx->aiColumn, pIdx->nKeyCol, pPk->aiColumn[i]) ){
  86541. pIdx->aiColumn[j] = pPk->aiColumn[i];
  86542. pIdx->azColl[j] = pPk->azColl[i];
  86543. j++;
  86544. }
  86545. }
  86546. assert( pIdx->nColumn>=pIdx->nKeyCol+n );
  86547. assert( pIdx->nColumn>=j );
  86548. }
  86549. /* Add all table columns to the PRIMARY KEY index
  86550. */
  86551. if( nPk<pTab->nCol ){
  86552. if( resizeIndexObject(db, pPk, pTab->nCol) ) return;
  86553. for(i=0, j=nPk; i<pTab->nCol; i++){
  86554. if( !hasColumn(pPk->aiColumn, j, i) ){
  86555. assert( j<pPk->nColumn );
  86556. pPk->aiColumn[j] = i;
  86557. pPk->azColl[j] = "BINARY";
  86558. j++;
  86559. }
  86560. }
  86561. assert( pPk->nColumn==j );
  86562. assert( pTab->nCol==j );
  86563. }else{
  86564. pPk->nColumn = pTab->nCol;
  86565. }
  86566. }
  86567. /*
  86568. ** This routine is called to report the final ")" that terminates
  86569. ** a CREATE TABLE statement.
  86570. **
  86571. ** The table structure that other action routines have been building
  86572. ** is added to the internal hash tables, assuming no errors have
  86573. ** occurred.
  86574. **
  86575. ** An entry for the table is made in the master table on disk, unless
  86576. ** this is a temporary table or db->init.busy==1. When db->init.busy==1
  86577. ** it means we are reading the sqlite_master table because we just
  86578. ** connected to the database or because the sqlite_master table has
  86579. ** recently changed, so the entry for this table already exists in
  86580. ** the sqlite_master table. We do not want to create it again.
  86581. **
  86582. ** If the pSelect argument is not NULL, it means that this routine
  86583. ** was called to create a table generated from a
  86584. ** "CREATE TABLE ... AS SELECT ..." statement. The column names of
  86585. ** the new table will match the result set of the SELECT.
  86586. */
  86587. SQLITE_PRIVATE void sqlite3EndTable(
  86588. Parse *pParse, /* Parse context */
  86589. Token *pCons, /* The ',' token after the last column defn. */
  86590. Token *pEnd, /* The ')' before options in the CREATE TABLE */
  86591. u8 tabOpts, /* Extra table options. Usually 0. */
  86592. Select *pSelect /* Select from a "CREATE ... AS SELECT" */
  86593. ){
  86594. Table *p; /* The new table */
  86595. sqlite3 *db = pParse->db; /* The database connection */
  86596. int iDb; /* Database in which the table lives */
  86597. Index *pIdx; /* An implied index of the table */
  86598. if( (pEnd==0 && pSelect==0) || db->mallocFailed ){
  86599. return;
  86600. }
  86601. p = pParse->pNewTable;
  86602. if( p==0 ) return;
  86603. assert( !db->init.busy || !pSelect );
  86604. /* If the db->init.busy is 1 it means we are reading the SQL off the
  86605. ** "sqlite_master" or "sqlite_temp_master" table on the disk.
  86606. ** So do not write to the disk again. Extract the root page number
  86607. ** for the table from the db->init.newTnum field. (The page number
  86608. ** should have been put there by the sqliteOpenCb routine.)
  86609. */
  86610. if( db->init.busy ){
  86611. p->tnum = db->init.newTnum;
  86612. }
  86613. /* Special processing for WITHOUT ROWID Tables */
  86614. if( tabOpts & TF_WithoutRowid ){
  86615. if( (p->tabFlags & TF_Autoincrement) ){
  86616. sqlite3ErrorMsg(pParse,
  86617. "AUTOINCREMENT not allowed on WITHOUT ROWID tables");
  86618. return;
  86619. }
  86620. if( (p->tabFlags & TF_HasPrimaryKey)==0 ){
  86621. sqlite3ErrorMsg(pParse, "PRIMARY KEY missing on table %s", p->zName);
  86622. }else{
  86623. p->tabFlags |= TF_WithoutRowid;
  86624. convertToWithoutRowidTable(pParse, p);
  86625. }
  86626. }
  86627. iDb = sqlite3SchemaToIndex(db, p->pSchema);
  86628. #ifndef SQLITE_OMIT_CHECK
  86629. /* Resolve names in all CHECK constraint expressions.
  86630. */
  86631. if( p->pCheck ){
  86632. sqlite3ResolveSelfReference(pParse, p, NC_IsCheck, 0, p->pCheck);
  86633. }
  86634. #endif /* !defined(SQLITE_OMIT_CHECK) */
  86635. /* Estimate the average row size for the table and for all implied indices */
  86636. estimateTableWidth(p);
  86637. for(pIdx=p->pIndex; pIdx; pIdx=pIdx->pNext){
  86638. estimateIndexWidth(pIdx);
  86639. }
  86640. /* If not initializing, then create a record for the new table
  86641. ** in the SQLITE_MASTER table of the database.
  86642. **
  86643. ** If this is a TEMPORARY table, write the entry into the auxiliary
  86644. ** file instead of into the main database file.
  86645. */
  86646. if( !db->init.busy ){
  86647. int n;
  86648. Vdbe *v;
  86649. char *zType; /* "view" or "table" */
  86650. char *zType2; /* "VIEW" or "TABLE" */
  86651. char *zStmt; /* Text of the CREATE TABLE or CREATE VIEW statement */
  86652. v = sqlite3GetVdbe(pParse);
  86653. if( NEVER(v==0) ) return;
  86654. sqlite3VdbeAddOp1(v, OP_Close, 0);
  86655. /*
  86656. ** Initialize zType for the new view or table.
  86657. */
  86658. if( p->pSelect==0 ){
  86659. /* A regular table */
  86660. zType = "table";
  86661. zType2 = "TABLE";
  86662. #ifndef SQLITE_OMIT_VIEW
  86663. }else{
  86664. /* A view */
  86665. zType = "view";
  86666. zType2 = "VIEW";
  86667. #endif
  86668. }
  86669. /* If this is a CREATE TABLE xx AS SELECT ..., execute the SELECT
  86670. ** statement to populate the new table. The root-page number for the
  86671. ** new table is in register pParse->regRoot.
  86672. **
  86673. ** Once the SELECT has been coded by sqlite3Select(), it is in a
  86674. ** suitable state to query for the column names and types to be used
  86675. ** by the new table.
  86676. **
  86677. ** A shared-cache write-lock is not required to write to the new table,
  86678. ** as a schema-lock must have already been obtained to create it. Since
  86679. ** a schema-lock excludes all other database users, the write-lock would
  86680. ** be redundant.
  86681. */
  86682. if( pSelect ){
  86683. SelectDest dest;
  86684. Table *pSelTab;
  86685. assert(pParse->nTab==1);
  86686. sqlite3VdbeAddOp3(v, OP_OpenWrite, 1, pParse->regRoot, iDb);
  86687. sqlite3VdbeChangeP5(v, OPFLAG_P2ISREG);
  86688. pParse->nTab = 2;
  86689. sqlite3SelectDestInit(&dest, SRT_Table, 1);
  86690. sqlite3Select(pParse, pSelect, &dest);
  86691. sqlite3VdbeAddOp1(v, OP_Close, 1);
  86692. if( pParse->nErr==0 ){
  86693. pSelTab = sqlite3ResultSetOfSelect(pParse, pSelect);
  86694. if( pSelTab==0 ) return;
  86695. assert( p->aCol==0 );
  86696. p->nCol = pSelTab->nCol;
  86697. p->aCol = pSelTab->aCol;
  86698. pSelTab->nCol = 0;
  86699. pSelTab->aCol = 0;
  86700. sqlite3DeleteTable(db, pSelTab);
  86701. }
  86702. }
  86703. /* Compute the complete text of the CREATE statement */
  86704. if( pSelect ){
  86705. zStmt = createTableStmt(db, p);
  86706. }else{
  86707. Token *pEnd2 = tabOpts ? &pParse->sLastToken : pEnd;
  86708. n = (int)(pEnd2->z - pParse->sNameToken.z);
  86709. if( pEnd2->z[0]!=';' ) n += pEnd2->n;
  86710. zStmt = sqlite3MPrintf(db,
  86711. "CREATE %s %.*s", zType2, n, pParse->sNameToken.z
  86712. );
  86713. }
  86714. /* A slot for the record has already been allocated in the
  86715. ** SQLITE_MASTER table. We just need to update that slot with all
  86716. ** the information we've collected.
  86717. */
  86718. sqlite3NestedParse(pParse,
  86719. "UPDATE %Q.%s "
  86720. "SET type='%s', name=%Q, tbl_name=%Q, rootpage=#%d, sql=%Q "
  86721. "WHERE rowid=#%d",
  86722. db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
  86723. zType,
  86724. p->zName,
  86725. p->zName,
  86726. pParse->regRoot,
  86727. zStmt,
  86728. pParse->regRowid
  86729. );
  86730. sqlite3DbFree(db, zStmt);
  86731. sqlite3ChangeCookie(pParse, iDb);
  86732. #ifndef SQLITE_OMIT_AUTOINCREMENT
  86733. /* Check to see if we need to create an sqlite_sequence table for
  86734. ** keeping track of autoincrement keys.
  86735. */
  86736. if( p->tabFlags & TF_Autoincrement ){
  86737. Db *pDb = &db->aDb[iDb];
  86738. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  86739. if( pDb->pSchema->pSeqTab==0 ){
  86740. sqlite3NestedParse(pParse,
  86741. "CREATE TABLE %Q.sqlite_sequence(name,seq)",
  86742. pDb->zName
  86743. );
  86744. }
  86745. }
  86746. #endif
  86747. /* Reparse everything to update our internal data structures */
  86748. sqlite3VdbeAddParseSchemaOp(v, iDb,
  86749. sqlite3MPrintf(db, "tbl_name='%q' AND type!='trigger'", p->zName));
  86750. }
  86751. /* Add the table to the in-memory representation of the database.
  86752. */
  86753. if( db->init.busy ){
  86754. Table *pOld;
  86755. Schema *pSchema = p->pSchema;
  86756. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  86757. pOld = sqlite3HashInsert(&pSchema->tblHash, p->zName, p);
  86758. if( pOld ){
  86759. assert( p==pOld ); /* Malloc must have failed inside HashInsert() */
  86760. db->mallocFailed = 1;
  86761. return;
  86762. }
  86763. pParse->pNewTable = 0;
  86764. db->flags |= SQLITE_InternChanges;
  86765. #ifndef SQLITE_OMIT_ALTERTABLE
  86766. if( !p->pSelect ){
  86767. const char *zName = (const char *)pParse->sNameToken.z;
  86768. int nName;
  86769. assert( !pSelect && pCons && pEnd );
  86770. if( pCons->z==0 ){
  86771. pCons = pEnd;
  86772. }
  86773. nName = (int)((const char *)pCons->z - zName);
  86774. p->addColOffset = 13 + sqlite3Utf8CharLen(zName, nName);
  86775. }
  86776. #endif
  86777. }
  86778. }
  86779. #ifndef SQLITE_OMIT_VIEW
  86780. /*
  86781. ** The parser calls this routine in order to create a new VIEW
  86782. */
  86783. SQLITE_PRIVATE void sqlite3CreateView(
  86784. Parse *pParse, /* The parsing context */
  86785. Token *pBegin, /* The CREATE token that begins the statement */
  86786. Token *pName1, /* The token that holds the name of the view */
  86787. Token *pName2, /* The token that holds the name of the view */
  86788. Select *pSelect, /* A SELECT statement that will become the new view */
  86789. int isTemp, /* TRUE for a TEMPORARY view */
  86790. int noErr /* Suppress error messages if VIEW already exists */
  86791. ){
  86792. Table *p;
  86793. int n;
  86794. const char *z;
  86795. Token sEnd;
  86796. DbFixer sFix;
  86797. Token *pName = 0;
  86798. int iDb;
  86799. sqlite3 *db = pParse->db;
  86800. if( pParse->nVar>0 ){
  86801. sqlite3ErrorMsg(pParse, "parameters are not allowed in views");
  86802. sqlite3SelectDelete(db, pSelect);
  86803. return;
  86804. }
  86805. sqlite3StartTable(pParse, pName1, pName2, isTemp, 1, 0, noErr);
  86806. p = pParse->pNewTable;
  86807. if( p==0 || pParse->nErr ){
  86808. sqlite3SelectDelete(db, pSelect);
  86809. return;
  86810. }
  86811. sqlite3TwoPartName(pParse, pName1, pName2, &pName);
  86812. iDb = sqlite3SchemaToIndex(db, p->pSchema);
  86813. sqlite3FixInit(&sFix, pParse, iDb, "view", pName);
  86814. if( sqlite3FixSelect(&sFix, pSelect) ){
  86815. sqlite3SelectDelete(db, pSelect);
  86816. return;
  86817. }
  86818. /* Make a copy of the entire SELECT statement that defines the view.
  86819. ** This will force all the Expr.token.z values to be dynamically
  86820. ** allocated rather than point to the input string - which means that
  86821. ** they will persist after the current sqlite3_exec() call returns.
  86822. */
  86823. p->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
  86824. sqlite3SelectDelete(db, pSelect);
  86825. if( db->mallocFailed ){
  86826. return;
  86827. }
  86828. if( !db->init.busy ){
  86829. sqlite3ViewGetColumnNames(pParse, p);
  86830. }
  86831. /* Locate the end of the CREATE VIEW statement. Make sEnd point to
  86832. ** the end.
  86833. */
  86834. sEnd = pParse->sLastToken;
  86835. if( ALWAYS(sEnd.z[0]!=0) && sEnd.z[0]!=';' ){
  86836. sEnd.z += sEnd.n;
  86837. }
  86838. sEnd.n = 0;
  86839. n = (int)(sEnd.z - pBegin->z);
  86840. z = pBegin->z;
  86841. while( ALWAYS(n>0) && sqlite3Isspace(z[n-1]) ){ n--; }
  86842. sEnd.z = &z[n-1];
  86843. sEnd.n = 1;
  86844. /* Use sqlite3EndTable() to add the view to the SQLITE_MASTER table */
  86845. sqlite3EndTable(pParse, 0, &sEnd, 0, 0);
  86846. return;
  86847. }
  86848. #endif /* SQLITE_OMIT_VIEW */
  86849. #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
  86850. /*
  86851. ** The Table structure pTable is really a VIEW. Fill in the names of
  86852. ** the columns of the view in the pTable structure. Return the number
  86853. ** of errors. If an error is seen leave an error message in pParse->zErrMsg.
  86854. */
  86855. SQLITE_PRIVATE int sqlite3ViewGetColumnNames(Parse *pParse, Table *pTable){
  86856. Table *pSelTab; /* A fake table from which we get the result set */
  86857. Select *pSel; /* Copy of the SELECT that implements the view */
  86858. int nErr = 0; /* Number of errors encountered */
  86859. int n; /* Temporarily holds the number of cursors assigned */
  86860. sqlite3 *db = pParse->db; /* Database connection for malloc errors */
  86861. sqlite3_xauth xAuth; /* Saved xAuth pointer */
  86862. assert( pTable );
  86863. #ifndef SQLITE_OMIT_VIRTUALTABLE
  86864. if( sqlite3VtabCallConnect(pParse, pTable) ){
  86865. return SQLITE_ERROR;
  86866. }
  86867. if( IsVirtual(pTable) ) return 0;
  86868. #endif
  86869. #ifndef SQLITE_OMIT_VIEW
  86870. /* A positive nCol means the columns names for this view are
  86871. ** already known.
  86872. */
  86873. if( pTable->nCol>0 ) return 0;
  86874. /* A negative nCol is a special marker meaning that we are currently
  86875. ** trying to compute the column names. If we enter this routine with
  86876. ** a negative nCol, it means two or more views form a loop, like this:
  86877. **
  86878. ** CREATE VIEW one AS SELECT * FROM two;
  86879. ** CREATE VIEW two AS SELECT * FROM one;
  86880. **
  86881. ** Actually, the error above is now caught prior to reaching this point.
  86882. ** But the following test is still important as it does come up
  86883. ** in the following:
  86884. **
  86885. ** CREATE TABLE main.ex1(a);
  86886. ** CREATE TEMP VIEW ex1 AS SELECT a FROM ex1;
  86887. ** SELECT * FROM temp.ex1;
  86888. */
  86889. if( pTable->nCol<0 ){
  86890. sqlite3ErrorMsg(pParse, "view %s is circularly defined", pTable->zName);
  86891. return 1;
  86892. }
  86893. assert( pTable->nCol>=0 );
  86894. /* If we get this far, it means we need to compute the table names.
  86895. ** Note that the call to sqlite3ResultSetOfSelect() will expand any
  86896. ** "*" elements in the results set of the view and will assign cursors
  86897. ** to the elements of the FROM clause. But we do not want these changes
  86898. ** to be permanent. So the computation is done on a copy of the SELECT
  86899. ** statement that defines the view.
  86900. */
  86901. assert( pTable->pSelect );
  86902. pSel = sqlite3SelectDup(db, pTable->pSelect, 0);
  86903. if( pSel ){
  86904. u8 enableLookaside = db->lookaside.bEnabled;
  86905. n = pParse->nTab;
  86906. sqlite3SrcListAssignCursors(pParse, pSel->pSrc);
  86907. pTable->nCol = -1;
  86908. db->lookaside.bEnabled = 0;
  86909. #ifndef SQLITE_OMIT_AUTHORIZATION
  86910. xAuth = db->xAuth;
  86911. db->xAuth = 0;
  86912. pSelTab = sqlite3ResultSetOfSelect(pParse, pSel);
  86913. db->xAuth = xAuth;
  86914. #else
  86915. pSelTab = sqlite3ResultSetOfSelect(pParse, pSel);
  86916. #endif
  86917. db->lookaside.bEnabled = enableLookaside;
  86918. pParse->nTab = n;
  86919. if( pSelTab ){
  86920. assert( pTable->aCol==0 );
  86921. pTable->nCol = pSelTab->nCol;
  86922. pTable->aCol = pSelTab->aCol;
  86923. pSelTab->nCol = 0;
  86924. pSelTab->aCol = 0;
  86925. sqlite3DeleteTable(db, pSelTab);
  86926. assert( sqlite3SchemaMutexHeld(db, 0, pTable->pSchema) );
  86927. pTable->pSchema->schemaFlags |= DB_UnresetViews;
  86928. }else{
  86929. pTable->nCol = 0;
  86930. nErr++;
  86931. }
  86932. sqlite3SelectDelete(db, pSel);
  86933. } else {
  86934. nErr++;
  86935. }
  86936. #endif /* SQLITE_OMIT_VIEW */
  86937. return nErr;
  86938. }
  86939. #endif /* !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE) */
  86940. #ifndef SQLITE_OMIT_VIEW
  86941. /*
  86942. ** Clear the column names from every VIEW in database idx.
  86943. */
  86944. static void sqliteViewResetAll(sqlite3 *db, int idx){
  86945. HashElem *i;
  86946. assert( sqlite3SchemaMutexHeld(db, idx, 0) );
  86947. if( !DbHasProperty(db, idx, DB_UnresetViews) ) return;
  86948. for(i=sqliteHashFirst(&db->aDb[idx].pSchema->tblHash); i;i=sqliteHashNext(i)){
  86949. Table *pTab = sqliteHashData(i);
  86950. if( pTab->pSelect ){
  86951. sqliteDeleteColumnNames(db, pTab);
  86952. pTab->aCol = 0;
  86953. pTab->nCol = 0;
  86954. }
  86955. }
  86956. DbClearProperty(db, idx, DB_UnresetViews);
  86957. }
  86958. #else
  86959. # define sqliteViewResetAll(A,B)
  86960. #endif /* SQLITE_OMIT_VIEW */
  86961. /*
  86962. ** This function is called by the VDBE to adjust the internal schema
  86963. ** used by SQLite when the btree layer moves a table root page. The
  86964. ** root-page of a table or index in database iDb has changed from iFrom
  86965. ** to iTo.
  86966. **
  86967. ** Ticket #1728: The symbol table might still contain information
  86968. ** on tables and/or indices that are the process of being deleted.
  86969. ** If you are unlucky, one of those deleted indices or tables might
  86970. ** have the same rootpage number as the real table or index that is
  86971. ** being moved. So we cannot stop searching after the first match
  86972. ** because the first match might be for one of the deleted indices
  86973. ** or tables and not the table/index that is actually being moved.
  86974. ** We must continue looping until all tables and indices with
  86975. ** rootpage==iFrom have been converted to have a rootpage of iTo
  86976. ** in order to be certain that we got the right one.
  86977. */
  86978. #ifndef SQLITE_OMIT_AUTOVACUUM
  86979. SQLITE_PRIVATE void sqlite3RootPageMoved(sqlite3 *db, int iDb, int iFrom, int iTo){
  86980. HashElem *pElem;
  86981. Hash *pHash;
  86982. Db *pDb;
  86983. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  86984. pDb = &db->aDb[iDb];
  86985. pHash = &pDb->pSchema->tblHash;
  86986. for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){
  86987. Table *pTab = sqliteHashData(pElem);
  86988. if( pTab->tnum==iFrom ){
  86989. pTab->tnum = iTo;
  86990. }
  86991. }
  86992. pHash = &pDb->pSchema->idxHash;
  86993. for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){
  86994. Index *pIdx = sqliteHashData(pElem);
  86995. if( pIdx->tnum==iFrom ){
  86996. pIdx->tnum = iTo;
  86997. }
  86998. }
  86999. }
  87000. #endif
  87001. /*
  87002. ** Write code to erase the table with root-page iTable from database iDb.
  87003. ** Also write code to modify the sqlite_master table and internal schema
  87004. ** if a root-page of another table is moved by the btree-layer whilst
  87005. ** erasing iTable (this can happen with an auto-vacuum database).
  87006. */
  87007. static void destroyRootPage(Parse *pParse, int iTable, int iDb){
  87008. Vdbe *v = sqlite3GetVdbe(pParse);
  87009. int r1 = sqlite3GetTempReg(pParse);
  87010. sqlite3VdbeAddOp3(v, OP_Destroy, iTable, r1, iDb);
  87011. sqlite3MayAbort(pParse);
  87012. #ifndef SQLITE_OMIT_AUTOVACUUM
  87013. /* OP_Destroy stores an in integer r1. If this integer
  87014. ** is non-zero, then it is the root page number of a table moved to
  87015. ** location iTable. The following code modifies the sqlite_master table to
  87016. ** reflect this.
  87017. **
  87018. ** The "#NNN" in the SQL is a special constant that means whatever value
  87019. ** is in register NNN. See grammar rules associated with the TK_REGISTER
  87020. ** token for additional information.
  87021. */
  87022. sqlite3NestedParse(pParse,
  87023. "UPDATE %Q.%s SET rootpage=%d WHERE #%d AND rootpage=#%d",
  87024. pParse->db->aDb[iDb].zName, SCHEMA_TABLE(iDb), iTable, r1, r1);
  87025. #endif
  87026. sqlite3ReleaseTempReg(pParse, r1);
  87027. }
  87028. /*
  87029. ** Write VDBE code to erase table pTab and all associated indices on disk.
  87030. ** Code to update the sqlite_master tables and internal schema definitions
  87031. ** in case a root-page belonging to another table is moved by the btree layer
  87032. ** is also added (this can happen with an auto-vacuum database).
  87033. */
  87034. static void destroyTable(Parse *pParse, Table *pTab){
  87035. #ifdef SQLITE_OMIT_AUTOVACUUM
  87036. Index *pIdx;
  87037. int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
  87038. destroyRootPage(pParse, pTab->tnum, iDb);
  87039. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  87040. destroyRootPage(pParse, pIdx->tnum, iDb);
  87041. }
  87042. #else
  87043. /* If the database may be auto-vacuum capable (if SQLITE_OMIT_AUTOVACUUM
  87044. ** is not defined), then it is important to call OP_Destroy on the
  87045. ** table and index root-pages in order, starting with the numerically
  87046. ** largest root-page number. This guarantees that none of the root-pages
  87047. ** to be destroyed is relocated by an earlier OP_Destroy. i.e. if the
  87048. ** following were coded:
  87049. **
  87050. ** OP_Destroy 4 0
  87051. ** ...
  87052. ** OP_Destroy 5 0
  87053. **
  87054. ** and root page 5 happened to be the largest root-page number in the
  87055. ** database, then root page 5 would be moved to page 4 by the
  87056. ** "OP_Destroy 4 0" opcode. The subsequent "OP_Destroy 5 0" would hit
  87057. ** a free-list page.
  87058. */
  87059. int iTab = pTab->tnum;
  87060. int iDestroyed = 0;
  87061. while( 1 ){
  87062. Index *pIdx;
  87063. int iLargest = 0;
  87064. if( iDestroyed==0 || iTab<iDestroyed ){
  87065. iLargest = iTab;
  87066. }
  87067. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  87068. int iIdx = pIdx->tnum;
  87069. assert( pIdx->pSchema==pTab->pSchema );
  87070. if( (iDestroyed==0 || (iIdx<iDestroyed)) && iIdx>iLargest ){
  87071. iLargest = iIdx;
  87072. }
  87073. }
  87074. if( iLargest==0 ){
  87075. return;
  87076. }else{
  87077. int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
  87078. assert( iDb>=0 && iDb<pParse->db->nDb );
  87079. destroyRootPage(pParse, iLargest, iDb);
  87080. iDestroyed = iLargest;
  87081. }
  87082. }
  87083. #endif
  87084. }
  87085. /*
  87086. ** Remove entries from the sqlite_statN tables (for N in (1,2,3))
  87087. ** after a DROP INDEX or DROP TABLE command.
  87088. */
  87089. static void sqlite3ClearStatTables(
  87090. Parse *pParse, /* The parsing context */
  87091. int iDb, /* The database number */
  87092. const char *zType, /* "idx" or "tbl" */
  87093. const char *zName /* Name of index or table */
  87094. ){
  87095. int i;
  87096. const char *zDbName = pParse->db->aDb[iDb].zName;
  87097. for(i=1; i<=4; i++){
  87098. char zTab[24];
  87099. sqlite3_snprintf(sizeof(zTab),zTab,"sqlite_stat%d",i);
  87100. if( sqlite3FindTable(pParse->db, zTab, zDbName) ){
  87101. sqlite3NestedParse(pParse,
  87102. "DELETE FROM %Q.%s WHERE %s=%Q",
  87103. zDbName, zTab, zType, zName
  87104. );
  87105. }
  87106. }
  87107. }
  87108. /*
  87109. ** Generate code to drop a table.
  87110. */
  87111. SQLITE_PRIVATE void sqlite3CodeDropTable(Parse *pParse, Table *pTab, int iDb, int isView){
  87112. Vdbe *v;
  87113. sqlite3 *db = pParse->db;
  87114. Trigger *pTrigger;
  87115. Db *pDb = &db->aDb[iDb];
  87116. v = sqlite3GetVdbe(pParse);
  87117. assert( v!=0 );
  87118. sqlite3BeginWriteOperation(pParse, 1, iDb);
  87119. #ifndef SQLITE_OMIT_VIRTUALTABLE
  87120. if( IsVirtual(pTab) ){
  87121. sqlite3VdbeAddOp0(v, OP_VBegin);
  87122. }
  87123. #endif
  87124. /* Drop all triggers associated with the table being dropped. Code
  87125. ** is generated to remove entries from sqlite_master and/or
  87126. ** sqlite_temp_master if required.
  87127. */
  87128. pTrigger = sqlite3TriggerList(pParse, pTab);
  87129. while( pTrigger ){
  87130. assert( pTrigger->pSchema==pTab->pSchema ||
  87131. pTrigger->pSchema==db->aDb[1].pSchema );
  87132. sqlite3DropTriggerPtr(pParse, pTrigger);
  87133. pTrigger = pTrigger->pNext;
  87134. }
  87135. #ifndef SQLITE_OMIT_AUTOINCREMENT
  87136. /* Remove any entries of the sqlite_sequence table associated with
  87137. ** the table being dropped. This is done before the table is dropped
  87138. ** at the btree level, in case the sqlite_sequence table needs to
  87139. ** move as a result of the drop (can happen in auto-vacuum mode).
  87140. */
  87141. if( pTab->tabFlags & TF_Autoincrement ){
  87142. sqlite3NestedParse(pParse,
  87143. "DELETE FROM %Q.sqlite_sequence WHERE name=%Q",
  87144. pDb->zName, pTab->zName
  87145. );
  87146. }
  87147. #endif
  87148. /* Drop all SQLITE_MASTER table and index entries that refer to the
  87149. ** table. The program name loops through the master table and deletes
  87150. ** every row that refers to a table of the same name as the one being
  87151. ** dropped. Triggers are handled separately because a trigger can be
  87152. ** created in the temp database that refers to a table in another
  87153. ** database.
  87154. */
  87155. sqlite3NestedParse(pParse,
  87156. "DELETE FROM %Q.%s WHERE tbl_name=%Q and type!='trigger'",
  87157. pDb->zName, SCHEMA_TABLE(iDb), pTab->zName);
  87158. if( !isView && !IsVirtual(pTab) ){
  87159. destroyTable(pParse, pTab);
  87160. }
  87161. /* Remove the table entry from SQLite's internal schema and modify
  87162. ** the schema cookie.
  87163. */
  87164. if( IsVirtual(pTab) ){
  87165. sqlite3VdbeAddOp4(v, OP_VDestroy, iDb, 0, 0, pTab->zName, 0);
  87166. }
  87167. sqlite3VdbeAddOp4(v, OP_DropTable, iDb, 0, 0, pTab->zName, 0);
  87168. sqlite3ChangeCookie(pParse, iDb);
  87169. sqliteViewResetAll(db, iDb);
  87170. }
  87171. /*
  87172. ** This routine is called to do the work of a DROP TABLE statement.
  87173. ** pName is the name of the table to be dropped.
  87174. */
  87175. SQLITE_PRIVATE void sqlite3DropTable(Parse *pParse, SrcList *pName, int isView, int noErr){
  87176. Table *pTab;
  87177. Vdbe *v;
  87178. sqlite3 *db = pParse->db;
  87179. int iDb;
  87180. if( db->mallocFailed ){
  87181. goto exit_drop_table;
  87182. }
  87183. assert( pParse->nErr==0 );
  87184. assert( pName->nSrc==1 );
  87185. if( sqlite3ReadSchema(pParse) ) goto exit_drop_table;
  87186. if( noErr ) db->suppressErr++;
  87187. pTab = sqlite3LocateTableItem(pParse, isView, &pName->a[0]);
  87188. if( noErr ) db->suppressErr--;
  87189. if( pTab==0 ){
  87190. if( noErr ) sqlite3CodeVerifyNamedSchema(pParse, pName->a[0].zDatabase);
  87191. goto exit_drop_table;
  87192. }
  87193. iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  87194. assert( iDb>=0 && iDb<db->nDb );
  87195. /* If pTab is a virtual table, call ViewGetColumnNames() to ensure
  87196. ** it is initialized.
  87197. */
  87198. if( IsVirtual(pTab) && sqlite3ViewGetColumnNames(pParse, pTab) ){
  87199. goto exit_drop_table;
  87200. }
  87201. #ifndef SQLITE_OMIT_AUTHORIZATION
  87202. {
  87203. int code;
  87204. const char *zTab = SCHEMA_TABLE(iDb);
  87205. const char *zDb = db->aDb[iDb].zName;
  87206. const char *zArg2 = 0;
  87207. if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb)){
  87208. goto exit_drop_table;
  87209. }
  87210. if( isView ){
  87211. if( !OMIT_TEMPDB && iDb==1 ){
  87212. code = SQLITE_DROP_TEMP_VIEW;
  87213. }else{
  87214. code = SQLITE_DROP_VIEW;
  87215. }
  87216. #ifndef SQLITE_OMIT_VIRTUALTABLE
  87217. }else if( IsVirtual(pTab) ){
  87218. code = SQLITE_DROP_VTABLE;
  87219. zArg2 = sqlite3GetVTable(db, pTab)->pMod->zName;
  87220. #endif
  87221. }else{
  87222. if( !OMIT_TEMPDB && iDb==1 ){
  87223. code = SQLITE_DROP_TEMP_TABLE;
  87224. }else{
  87225. code = SQLITE_DROP_TABLE;
  87226. }
  87227. }
  87228. if( sqlite3AuthCheck(pParse, code, pTab->zName, zArg2, zDb) ){
  87229. goto exit_drop_table;
  87230. }
  87231. if( sqlite3AuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0, zDb) ){
  87232. goto exit_drop_table;
  87233. }
  87234. }
  87235. #endif
  87236. if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0
  87237. && sqlite3StrNICmp(pTab->zName, "sqlite_stat", 11)!=0 ){
  87238. sqlite3ErrorMsg(pParse, "table %s may not be dropped", pTab->zName);
  87239. goto exit_drop_table;
  87240. }
  87241. #ifndef SQLITE_OMIT_VIEW
  87242. /* Ensure DROP TABLE is not used on a view, and DROP VIEW is not used
  87243. ** on a table.
  87244. */
  87245. if( isView && pTab->pSelect==0 ){
  87246. sqlite3ErrorMsg(pParse, "use DROP TABLE to delete table %s", pTab->zName);
  87247. goto exit_drop_table;
  87248. }
  87249. if( !isView && pTab->pSelect ){
  87250. sqlite3ErrorMsg(pParse, "use DROP VIEW to delete view %s", pTab->zName);
  87251. goto exit_drop_table;
  87252. }
  87253. #endif
  87254. /* Generate code to remove the table from the master table
  87255. ** on disk.
  87256. */
  87257. v = sqlite3GetVdbe(pParse);
  87258. if( v ){
  87259. sqlite3BeginWriteOperation(pParse, 1, iDb);
  87260. sqlite3ClearStatTables(pParse, iDb, "tbl", pTab->zName);
  87261. sqlite3FkDropTable(pParse, pName, pTab);
  87262. sqlite3CodeDropTable(pParse, pTab, iDb, isView);
  87263. }
  87264. exit_drop_table:
  87265. sqlite3SrcListDelete(db, pName);
  87266. }
  87267. /*
  87268. ** This routine is called to create a new foreign key on the table
  87269. ** currently under construction. pFromCol determines which columns
  87270. ** in the current table point to the foreign key. If pFromCol==0 then
  87271. ** connect the key to the last column inserted. pTo is the name of
  87272. ** the table referred to (a.k.a the "parent" table). pToCol is a list
  87273. ** of tables in the parent pTo table. flags contains all
  87274. ** information about the conflict resolution algorithms specified
  87275. ** in the ON DELETE, ON UPDATE and ON INSERT clauses.
  87276. **
  87277. ** An FKey structure is created and added to the table currently
  87278. ** under construction in the pParse->pNewTable field.
  87279. **
  87280. ** The foreign key is set for IMMEDIATE processing. A subsequent call
  87281. ** to sqlite3DeferForeignKey() might change this to DEFERRED.
  87282. */
  87283. SQLITE_PRIVATE void sqlite3CreateForeignKey(
  87284. Parse *pParse, /* Parsing context */
  87285. ExprList *pFromCol, /* Columns in this table that point to other table */
  87286. Token *pTo, /* Name of the other table */
  87287. ExprList *pToCol, /* Columns in the other table */
  87288. int flags /* Conflict resolution algorithms. */
  87289. ){
  87290. sqlite3 *db = pParse->db;
  87291. #ifndef SQLITE_OMIT_FOREIGN_KEY
  87292. FKey *pFKey = 0;
  87293. FKey *pNextTo;
  87294. Table *p = pParse->pNewTable;
  87295. int nByte;
  87296. int i;
  87297. int nCol;
  87298. char *z;
  87299. assert( pTo!=0 );
  87300. if( p==0 || IN_DECLARE_VTAB ) goto fk_end;
  87301. if( pFromCol==0 ){
  87302. int iCol = p->nCol-1;
  87303. if( NEVER(iCol<0) ) goto fk_end;
  87304. if( pToCol && pToCol->nExpr!=1 ){
  87305. sqlite3ErrorMsg(pParse, "foreign key on %s"
  87306. " should reference only one column of table %T",
  87307. p->aCol[iCol].zName, pTo);
  87308. goto fk_end;
  87309. }
  87310. nCol = 1;
  87311. }else if( pToCol && pToCol->nExpr!=pFromCol->nExpr ){
  87312. sqlite3ErrorMsg(pParse,
  87313. "number of columns in foreign key does not match the number of "
  87314. "columns in the referenced table");
  87315. goto fk_end;
  87316. }else{
  87317. nCol = pFromCol->nExpr;
  87318. }
  87319. nByte = sizeof(*pFKey) + (nCol-1)*sizeof(pFKey->aCol[0]) + pTo->n + 1;
  87320. if( pToCol ){
  87321. for(i=0; i<pToCol->nExpr; i++){
  87322. nByte += sqlite3Strlen30(pToCol->a[i].zName) + 1;
  87323. }
  87324. }
  87325. pFKey = sqlite3DbMallocZero(db, nByte );
  87326. if( pFKey==0 ){
  87327. goto fk_end;
  87328. }
  87329. pFKey->pFrom = p;
  87330. pFKey->pNextFrom = p->pFKey;
  87331. z = (char*)&pFKey->aCol[nCol];
  87332. pFKey->zTo = z;
  87333. memcpy(z, pTo->z, pTo->n);
  87334. z[pTo->n] = 0;
  87335. sqlite3Dequote(z);
  87336. z += pTo->n+1;
  87337. pFKey->nCol = nCol;
  87338. if( pFromCol==0 ){
  87339. pFKey->aCol[0].iFrom = p->nCol-1;
  87340. }else{
  87341. for(i=0; i<nCol; i++){
  87342. int j;
  87343. for(j=0; j<p->nCol; j++){
  87344. if( sqlite3StrICmp(p->aCol[j].zName, pFromCol->a[i].zName)==0 ){
  87345. pFKey->aCol[i].iFrom = j;
  87346. break;
  87347. }
  87348. }
  87349. if( j>=p->nCol ){
  87350. sqlite3ErrorMsg(pParse,
  87351. "unknown column \"%s\" in foreign key definition",
  87352. pFromCol->a[i].zName);
  87353. goto fk_end;
  87354. }
  87355. }
  87356. }
  87357. if( pToCol ){
  87358. for(i=0; i<nCol; i++){
  87359. int n = sqlite3Strlen30(pToCol->a[i].zName);
  87360. pFKey->aCol[i].zCol = z;
  87361. memcpy(z, pToCol->a[i].zName, n);
  87362. z[n] = 0;
  87363. z += n+1;
  87364. }
  87365. }
  87366. pFKey->isDeferred = 0;
  87367. pFKey->aAction[0] = (u8)(flags & 0xff); /* ON DELETE action */
  87368. pFKey->aAction[1] = (u8)((flags >> 8 ) & 0xff); /* ON UPDATE action */
  87369. assert( sqlite3SchemaMutexHeld(db, 0, p->pSchema) );
  87370. pNextTo = (FKey *)sqlite3HashInsert(&p->pSchema->fkeyHash,
  87371. pFKey->zTo, (void *)pFKey
  87372. );
  87373. if( pNextTo==pFKey ){
  87374. db->mallocFailed = 1;
  87375. goto fk_end;
  87376. }
  87377. if( pNextTo ){
  87378. assert( pNextTo->pPrevTo==0 );
  87379. pFKey->pNextTo = pNextTo;
  87380. pNextTo->pPrevTo = pFKey;
  87381. }
  87382. /* Link the foreign key to the table as the last step.
  87383. */
  87384. p->pFKey = pFKey;
  87385. pFKey = 0;
  87386. fk_end:
  87387. sqlite3DbFree(db, pFKey);
  87388. #endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
  87389. sqlite3ExprListDelete(db, pFromCol);
  87390. sqlite3ExprListDelete(db, pToCol);
  87391. }
  87392. /*
  87393. ** This routine is called when an INITIALLY IMMEDIATE or INITIALLY DEFERRED
  87394. ** clause is seen as part of a foreign key definition. The isDeferred
  87395. ** parameter is 1 for INITIALLY DEFERRED and 0 for INITIALLY IMMEDIATE.
  87396. ** The behavior of the most recently created foreign key is adjusted
  87397. ** accordingly.
  87398. */
  87399. SQLITE_PRIVATE void sqlite3DeferForeignKey(Parse *pParse, int isDeferred){
  87400. #ifndef SQLITE_OMIT_FOREIGN_KEY
  87401. Table *pTab;
  87402. FKey *pFKey;
  87403. if( (pTab = pParse->pNewTable)==0 || (pFKey = pTab->pFKey)==0 ) return;
  87404. assert( isDeferred==0 || isDeferred==1 ); /* EV: R-30323-21917 */
  87405. pFKey->isDeferred = (u8)isDeferred;
  87406. #endif
  87407. }
  87408. /*
  87409. ** Generate code that will erase and refill index *pIdx. This is
  87410. ** used to initialize a newly created index or to recompute the
  87411. ** content of an index in response to a REINDEX command.
  87412. **
  87413. ** if memRootPage is not negative, it means that the index is newly
  87414. ** created. The register specified by memRootPage contains the
  87415. ** root page number of the index. If memRootPage is negative, then
  87416. ** the index already exists and must be cleared before being refilled and
  87417. ** the root page number of the index is taken from pIndex->tnum.
  87418. */
  87419. static void sqlite3RefillIndex(Parse *pParse, Index *pIndex, int memRootPage){
  87420. Table *pTab = pIndex->pTable; /* The table that is indexed */
  87421. int iTab = pParse->nTab++; /* Btree cursor used for pTab */
  87422. int iIdx = pParse->nTab++; /* Btree cursor used for pIndex */
  87423. int iSorter; /* Cursor opened by OpenSorter (if in use) */
  87424. int addr1; /* Address of top of loop */
  87425. int addr2; /* Address to jump to for next iteration */
  87426. int tnum; /* Root page of index */
  87427. int iPartIdxLabel; /* Jump to this label to skip a row */
  87428. Vdbe *v; /* Generate code into this virtual machine */
  87429. KeyInfo *pKey; /* KeyInfo for index */
  87430. int regRecord; /* Register holding assembled index record */
  87431. sqlite3 *db = pParse->db; /* The database connection */
  87432. int iDb = sqlite3SchemaToIndex(db, pIndex->pSchema);
  87433. #ifndef SQLITE_OMIT_AUTHORIZATION
  87434. if( sqlite3AuthCheck(pParse, SQLITE_REINDEX, pIndex->zName, 0,
  87435. db->aDb[iDb].zName ) ){
  87436. return;
  87437. }
  87438. #endif
  87439. /* Require a write-lock on the table to perform this operation */
  87440. sqlite3TableLock(pParse, iDb, pTab->tnum, 1, pTab->zName);
  87441. v = sqlite3GetVdbe(pParse);
  87442. if( v==0 ) return;
  87443. if( memRootPage>=0 ){
  87444. tnum = memRootPage;
  87445. }else{
  87446. tnum = pIndex->tnum;
  87447. }
  87448. pKey = sqlite3KeyInfoOfIndex(pParse, pIndex);
  87449. /* Open the sorter cursor if we are to use one. */
  87450. iSorter = pParse->nTab++;
  87451. sqlite3VdbeAddOp4(v, OP_SorterOpen, iSorter, 0, pIndex->nKeyCol, (char*)
  87452. sqlite3KeyInfoRef(pKey), P4_KEYINFO);
  87453. /* Open the table. Loop through all rows of the table, inserting index
  87454. ** records into the sorter. */
  87455. sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead);
  87456. addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iTab, 0); VdbeCoverage(v);
  87457. regRecord = sqlite3GetTempReg(pParse);
  87458. sqlite3GenerateIndexKey(pParse,pIndex,iTab,regRecord,0,&iPartIdxLabel,0,0);
  87459. sqlite3VdbeAddOp2(v, OP_SorterInsert, iSorter, regRecord);
  87460. sqlite3ResolvePartIdxLabel(pParse, iPartIdxLabel);
  87461. sqlite3VdbeAddOp2(v, OP_Next, iTab, addr1+1); VdbeCoverage(v);
  87462. sqlite3VdbeJumpHere(v, addr1);
  87463. if( memRootPage<0 ) sqlite3VdbeAddOp2(v, OP_Clear, tnum, iDb);
  87464. sqlite3VdbeAddOp4(v, OP_OpenWrite, iIdx, tnum, iDb,
  87465. (char *)pKey, P4_KEYINFO);
  87466. sqlite3VdbeChangeP5(v, OPFLAG_BULKCSR|((memRootPage>=0)?OPFLAG_P2ISREG:0));
  87467. addr1 = sqlite3VdbeAddOp2(v, OP_SorterSort, iSorter, 0); VdbeCoverage(v);
  87468. assert( pKey!=0 || db->mallocFailed || pParse->nErr );
  87469. if( IsUniqueIndex(pIndex) && pKey!=0 ){
  87470. int j2 = sqlite3VdbeCurrentAddr(v) + 3;
  87471. sqlite3VdbeAddOp2(v, OP_Goto, 0, j2);
  87472. addr2 = sqlite3VdbeCurrentAddr(v);
  87473. sqlite3VdbeAddOp4Int(v, OP_SorterCompare, iSorter, j2, regRecord,
  87474. pIndex->nKeyCol); VdbeCoverage(v);
  87475. sqlite3UniqueConstraint(pParse, OE_Abort, pIndex);
  87476. }else{
  87477. addr2 = sqlite3VdbeCurrentAddr(v);
  87478. }
  87479. sqlite3VdbeAddOp3(v, OP_SorterData, iSorter, regRecord, iIdx);
  87480. sqlite3VdbeAddOp3(v, OP_Last, iIdx, 0, -1);
  87481. sqlite3VdbeAddOp3(v, OP_IdxInsert, iIdx, regRecord, 0);
  87482. sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
  87483. sqlite3ReleaseTempReg(pParse, regRecord);
  87484. sqlite3VdbeAddOp2(v, OP_SorterNext, iSorter, addr2); VdbeCoverage(v);
  87485. sqlite3VdbeJumpHere(v, addr1);
  87486. sqlite3VdbeAddOp1(v, OP_Close, iTab);
  87487. sqlite3VdbeAddOp1(v, OP_Close, iIdx);
  87488. sqlite3VdbeAddOp1(v, OP_Close, iSorter);
  87489. }
  87490. /*
  87491. ** Allocate heap space to hold an Index object with nCol columns.
  87492. **
  87493. ** Increase the allocation size to provide an extra nExtra bytes
  87494. ** of 8-byte aligned space after the Index object and return a
  87495. ** pointer to this extra space in *ppExtra.
  87496. */
  87497. SQLITE_PRIVATE Index *sqlite3AllocateIndexObject(
  87498. sqlite3 *db, /* Database connection */
  87499. i16 nCol, /* Total number of columns in the index */
  87500. int nExtra, /* Number of bytes of extra space to alloc */
  87501. char **ppExtra /* Pointer to the "extra" space */
  87502. ){
  87503. Index *p; /* Allocated index object */
  87504. int nByte; /* Bytes of space for Index object + arrays */
  87505. nByte = ROUND8(sizeof(Index)) + /* Index structure */
  87506. ROUND8(sizeof(char*)*nCol) + /* Index.azColl */
  87507. ROUND8(sizeof(LogEst)*(nCol+1) + /* Index.aiRowLogEst */
  87508. sizeof(i16)*nCol + /* Index.aiColumn */
  87509. sizeof(u8)*nCol); /* Index.aSortOrder */
  87510. p = sqlite3DbMallocZero(db, nByte + nExtra);
  87511. if( p ){
  87512. char *pExtra = ((char*)p)+ROUND8(sizeof(Index));
  87513. p->azColl = (char**)pExtra; pExtra += ROUND8(sizeof(char*)*nCol);
  87514. p->aiRowLogEst = (LogEst*)pExtra; pExtra += sizeof(LogEst)*(nCol+1);
  87515. p->aiColumn = (i16*)pExtra; pExtra += sizeof(i16)*nCol;
  87516. p->aSortOrder = (u8*)pExtra;
  87517. p->nColumn = nCol;
  87518. p->nKeyCol = nCol - 1;
  87519. *ppExtra = ((char*)p) + nByte;
  87520. }
  87521. return p;
  87522. }
  87523. /*
  87524. ** Create a new index for an SQL table. pName1.pName2 is the name of the index
  87525. ** and pTblList is the name of the table that is to be indexed. Both will
  87526. ** be NULL for a primary key or an index that is created to satisfy a
  87527. ** UNIQUE constraint. If pTable and pIndex are NULL, use pParse->pNewTable
  87528. ** as the table to be indexed. pParse->pNewTable is a table that is
  87529. ** currently being constructed by a CREATE TABLE statement.
  87530. **
  87531. ** pList is a list of columns to be indexed. pList will be NULL if this
  87532. ** is a primary key or unique-constraint on the most recent column added
  87533. ** to the table currently under construction.
  87534. **
  87535. ** If the index is created successfully, return a pointer to the new Index
  87536. ** structure. This is used by sqlite3AddPrimaryKey() to mark the index
  87537. ** as the tables primary key (Index.idxType==SQLITE_IDXTYPE_PRIMARYKEY)
  87538. */
  87539. SQLITE_PRIVATE Index *sqlite3CreateIndex(
  87540. Parse *pParse, /* All information about this parse */
  87541. Token *pName1, /* First part of index name. May be NULL */
  87542. Token *pName2, /* Second part of index name. May be NULL */
  87543. SrcList *pTblName, /* Table to index. Use pParse->pNewTable if 0 */
  87544. ExprList *pList, /* A list of columns to be indexed */
  87545. int onError, /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */
  87546. Token *pStart, /* The CREATE token that begins this statement */
  87547. Expr *pPIWhere, /* WHERE clause for partial indices */
  87548. int sortOrder, /* Sort order of primary key when pList==NULL */
  87549. int ifNotExist /* Omit error if index already exists */
  87550. ){
  87551. Index *pRet = 0; /* Pointer to return */
  87552. Table *pTab = 0; /* Table to be indexed */
  87553. Index *pIndex = 0; /* The index to be created */
  87554. char *zName = 0; /* Name of the index */
  87555. int nName; /* Number of characters in zName */
  87556. int i, j;
  87557. DbFixer sFix; /* For assigning database names to pTable */
  87558. int sortOrderMask; /* 1 to honor DESC in index. 0 to ignore. */
  87559. sqlite3 *db = pParse->db;
  87560. Db *pDb; /* The specific table containing the indexed database */
  87561. int iDb; /* Index of the database that is being written */
  87562. Token *pName = 0; /* Unqualified name of the index to create */
  87563. struct ExprList_item *pListItem; /* For looping over pList */
  87564. const Column *pTabCol; /* A column in the table */
  87565. int nExtra = 0; /* Space allocated for zExtra[] */
  87566. int nExtraCol; /* Number of extra columns needed */
  87567. char *zExtra = 0; /* Extra space after the Index object */
  87568. Index *pPk = 0; /* PRIMARY KEY index for WITHOUT ROWID tables */
  87569. if( db->mallocFailed || IN_DECLARE_VTAB || pParse->nErr>0 ){
  87570. goto exit_create_index;
  87571. }
  87572. if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
  87573. goto exit_create_index;
  87574. }
  87575. /*
  87576. ** Find the table that is to be indexed. Return early if not found.
  87577. */
  87578. if( pTblName!=0 ){
  87579. /* Use the two-part index name to determine the database
  87580. ** to search for the table. 'Fix' the table name to this db
  87581. ** before looking up the table.
  87582. */
  87583. assert( pName1 && pName2 );
  87584. iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
  87585. if( iDb<0 ) goto exit_create_index;
  87586. assert( pName && pName->z );
  87587. #ifndef SQLITE_OMIT_TEMPDB
  87588. /* If the index name was unqualified, check if the table
  87589. ** is a temp table. If so, set the database to 1. Do not do this
  87590. ** if initialising a database schema.
  87591. */
  87592. if( !db->init.busy ){
  87593. pTab = sqlite3SrcListLookup(pParse, pTblName);
  87594. if( pName2->n==0 && pTab && pTab->pSchema==db->aDb[1].pSchema ){
  87595. iDb = 1;
  87596. }
  87597. }
  87598. #endif
  87599. sqlite3FixInit(&sFix, pParse, iDb, "index", pName);
  87600. if( sqlite3FixSrcList(&sFix, pTblName) ){
  87601. /* Because the parser constructs pTblName from a single identifier,
  87602. ** sqlite3FixSrcList can never fail. */
  87603. assert(0);
  87604. }
  87605. pTab = sqlite3LocateTableItem(pParse, 0, &pTblName->a[0]);
  87606. assert( db->mallocFailed==0 || pTab==0 );
  87607. if( pTab==0 ) goto exit_create_index;
  87608. if( iDb==1 && db->aDb[iDb].pSchema!=pTab->pSchema ){
  87609. sqlite3ErrorMsg(pParse,
  87610. "cannot create a TEMP index on non-TEMP table \"%s\"",
  87611. pTab->zName);
  87612. goto exit_create_index;
  87613. }
  87614. if( !HasRowid(pTab) ) pPk = sqlite3PrimaryKeyIndex(pTab);
  87615. }else{
  87616. assert( pName==0 );
  87617. assert( pStart==0 );
  87618. pTab = pParse->pNewTable;
  87619. if( !pTab ) goto exit_create_index;
  87620. iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  87621. }
  87622. pDb = &db->aDb[iDb];
  87623. assert( pTab!=0 );
  87624. assert( pParse->nErr==0 );
  87625. if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0
  87626. && db->init.busy==0
  87627. #if SQLITE_USER_AUTHENTICATION
  87628. && sqlite3UserAuthTable(pTab->zName)==0
  87629. #endif
  87630. && sqlite3StrNICmp(&pTab->zName[7],"altertab_",9)!=0 ){
  87631. sqlite3ErrorMsg(pParse, "table %s may not be indexed", pTab->zName);
  87632. goto exit_create_index;
  87633. }
  87634. #ifndef SQLITE_OMIT_VIEW
  87635. if( pTab->pSelect ){
  87636. sqlite3ErrorMsg(pParse, "views may not be indexed");
  87637. goto exit_create_index;
  87638. }
  87639. #endif
  87640. #ifndef SQLITE_OMIT_VIRTUALTABLE
  87641. if( IsVirtual(pTab) ){
  87642. sqlite3ErrorMsg(pParse, "virtual tables may not be indexed");
  87643. goto exit_create_index;
  87644. }
  87645. #endif
  87646. /*
  87647. ** Find the name of the index. Make sure there is not already another
  87648. ** index or table with the same name.
  87649. **
  87650. ** Exception: If we are reading the names of permanent indices from the
  87651. ** sqlite_master table (because some other process changed the schema) and
  87652. ** one of the index names collides with the name of a temporary table or
  87653. ** index, then we will continue to process this index.
  87654. **
  87655. ** If pName==0 it means that we are
  87656. ** dealing with a primary key or UNIQUE constraint. We have to invent our
  87657. ** own name.
  87658. */
  87659. if( pName ){
  87660. zName = sqlite3NameFromToken(db, pName);
  87661. if( zName==0 ) goto exit_create_index;
  87662. assert( pName->z!=0 );
  87663. if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
  87664. goto exit_create_index;
  87665. }
  87666. if( !db->init.busy ){
  87667. if( sqlite3FindTable(db, zName, 0)!=0 ){
  87668. sqlite3ErrorMsg(pParse, "there is already a table named %s", zName);
  87669. goto exit_create_index;
  87670. }
  87671. }
  87672. if( sqlite3FindIndex(db, zName, pDb->zName)!=0 ){
  87673. if( !ifNotExist ){
  87674. sqlite3ErrorMsg(pParse, "index %s already exists", zName);
  87675. }else{
  87676. assert( !db->init.busy );
  87677. sqlite3CodeVerifySchema(pParse, iDb);
  87678. }
  87679. goto exit_create_index;
  87680. }
  87681. }else{
  87682. int n;
  87683. Index *pLoop;
  87684. for(pLoop=pTab->pIndex, n=1; pLoop; pLoop=pLoop->pNext, n++){}
  87685. zName = sqlite3MPrintf(db, "sqlite_autoindex_%s_%d", pTab->zName, n);
  87686. if( zName==0 ){
  87687. goto exit_create_index;
  87688. }
  87689. }
  87690. /* Check for authorization to create an index.
  87691. */
  87692. #ifndef SQLITE_OMIT_AUTHORIZATION
  87693. {
  87694. const char *zDb = pDb->zName;
  87695. if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(iDb), 0, zDb) ){
  87696. goto exit_create_index;
  87697. }
  87698. i = SQLITE_CREATE_INDEX;
  87699. if( !OMIT_TEMPDB && iDb==1 ) i = SQLITE_CREATE_TEMP_INDEX;
  87700. if( sqlite3AuthCheck(pParse, i, zName, pTab->zName, zDb) ){
  87701. goto exit_create_index;
  87702. }
  87703. }
  87704. #endif
  87705. /* If pList==0, it means this routine was called to make a primary
  87706. ** key out of the last column added to the table under construction.
  87707. ** So create a fake list to simulate this.
  87708. */
  87709. if( pList==0 ){
  87710. pList = sqlite3ExprListAppend(pParse, 0, 0);
  87711. if( pList==0 ) goto exit_create_index;
  87712. pList->a[0].zName = sqlite3DbStrDup(pParse->db,
  87713. pTab->aCol[pTab->nCol-1].zName);
  87714. pList->a[0].sortOrder = (u8)sortOrder;
  87715. }
  87716. /* Figure out how many bytes of space are required to store explicitly
  87717. ** specified collation sequence names.
  87718. */
  87719. for(i=0; i<pList->nExpr; i++){
  87720. Expr *pExpr = pList->a[i].pExpr;
  87721. if( pExpr ){
  87722. assert( pExpr->op==TK_COLLATE );
  87723. nExtra += (1 + sqlite3Strlen30(pExpr->u.zToken));
  87724. }
  87725. }
  87726. /*
  87727. ** Allocate the index structure.
  87728. */
  87729. nName = sqlite3Strlen30(zName);
  87730. nExtraCol = pPk ? pPk->nKeyCol : 1;
  87731. pIndex = sqlite3AllocateIndexObject(db, pList->nExpr + nExtraCol,
  87732. nName + nExtra + 1, &zExtra);
  87733. if( db->mallocFailed ){
  87734. goto exit_create_index;
  87735. }
  87736. assert( EIGHT_BYTE_ALIGNMENT(pIndex->aiRowLogEst) );
  87737. assert( EIGHT_BYTE_ALIGNMENT(pIndex->azColl) );
  87738. pIndex->zName = zExtra;
  87739. zExtra += nName + 1;
  87740. memcpy(pIndex->zName, zName, nName+1);
  87741. pIndex->pTable = pTab;
  87742. pIndex->onError = (u8)onError;
  87743. pIndex->uniqNotNull = onError!=OE_None;
  87744. pIndex->idxType = pName ? SQLITE_IDXTYPE_APPDEF : SQLITE_IDXTYPE_UNIQUE;
  87745. pIndex->pSchema = db->aDb[iDb].pSchema;
  87746. pIndex->nKeyCol = pList->nExpr;
  87747. if( pPIWhere ){
  87748. sqlite3ResolveSelfReference(pParse, pTab, NC_PartIdx, pPIWhere, 0);
  87749. pIndex->pPartIdxWhere = pPIWhere;
  87750. pPIWhere = 0;
  87751. }
  87752. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  87753. /* Check to see if we should honor DESC requests on index columns
  87754. */
  87755. if( pDb->pSchema->file_format>=4 ){
  87756. sortOrderMask = -1; /* Honor DESC */
  87757. }else{
  87758. sortOrderMask = 0; /* Ignore DESC */
  87759. }
  87760. /* Scan the names of the columns of the table to be indexed and
  87761. ** load the column indices into the Index structure. Report an error
  87762. ** if any column is not found.
  87763. **
  87764. ** TODO: Add a test to make sure that the same column is not named
  87765. ** more than once within the same index. Only the first instance of
  87766. ** the column will ever be used by the optimizer. Note that using the
  87767. ** same column more than once cannot be an error because that would
  87768. ** break backwards compatibility - it needs to be a warning.
  87769. */
  87770. for(i=0, pListItem=pList->a; i<pList->nExpr; i++, pListItem++){
  87771. const char *zColName = pListItem->zName;
  87772. int requestedSortOrder;
  87773. char *zColl; /* Collation sequence name */
  87774. for(j=0, pTabCol=pTab->aCol; j<pTab->nCol; j++, pTabCol++){
  87775. if( sqlite3StrICmp(zColName, pTabCol->zName)==0 ) break;
  87776. }
  87777. if( j>=pTab->nCol ){
  87778. sqlite3ErrorMsg(pParse, "table %s has no column named %s",
  87779. pTab->zName, zColName);
  87780. pParse->checkSchema = 1;
  87781. goto exit_create_index;
  87782. }
  87783. assert( j<=0x7fff );
  87784. pIndex->aiColumn[i] = (i16)j;
  87785. if( pListItem->pExpr ){
  87786. int nColl;
  87787. assert( pListItem->pExpr->op==TK_COLLATE );
  87788. zColl = pListItem->pExpr->u.zToken;
  87789. nColl = sqlite3Strlen30(zColl) + 1;
  87790. assert( nExtra>=nColl );
  87791. memcpy(zExtra, zColl, nColl);
  87792. zColl = zExtra;
  87793. zExtra += nColl;
  87794. nExtra -= nColl;
  87795. }else{
  87796. zColl = pTab->aCol[j].zColl;
  87797. if( !zColl ) zColl = "BINARY";
  87798. }
  87799. if( !db->init.busy && !sqlite3LocateCollSeq(pParse, zColl) ){
  87800. goto exit_create_index;
  87801. }
  87802. pIndex->azColl[i] = zColl;
  87803. requestedSortOrder = pListItem->sortOrder & sortOrderMask;
  87804. pIndex->aSortOrder[i] = (u8)requestedSortOrder;
  87805. if( pTab->aCol[j].notNull==0 ) pIndex->uniqNotNull = 0;
  87806. }
  87807. if( pPk ){
  87808. for(j=0; j<pPk->nKeyCol; j++){
  87809. int x = pPk->aiColumn[j];
  87810. if( hasColumn(pIndex->aiColumn, pIndex->nKeyCol, x) ){
  87811. pIndex->nColumn--;
  87812. }else{
  87813. pIndex->aiColumn[i] = x;
  87814. pIndex->azColl[i] = pPk->azColl[j];
  87815. pIndex->aSortOrder[i] = pPk->aSortOrder[j];
  87816. i++;
  87817. }
  87818. }
  87819. assert( i==pIndex->nColumn );
  87820. }else{
  87821. pIndex->aiColumn[i] = -1;
  87822. pIndex->azColl[i] = "BINARY";
  87823. }
  87824. sqlite3DefaultRowEst(pIndex);
  87825. if( pParse->pNewTable==0 ) estimateIndexWidth(pIndex);
  87826. if( pTab==pParse->pNewTable ){
  87827. /* This routine has been called to create an automatic index as a
  87828. ** result of a PRIMARY KEY or UNIQUE clause on a column definition, or
  87829. ** a PRIMARY KEY or UNIQUE clause following the column definitions.
  87830. ** i.e. one of:
  87831. **
  87832. ** CREATE TABLE t(x PRIMARY KEY, y);
  87833. ** CREATE TABLE t(x, y, UNIQUE(x, y));
  87834. **
  87835. ** Either way, check to see if the table already has such an index. If
  87836. ** so, don't bother creating this one. This only applies to
  87837. ** automatically created indices. Users can do as they wish with
  87838. ** explicit indices.
  87839. **
  87840. ** Two UNIQUE or PRIMARY KEY constraints are considered equivalent
  87841. ** (and thus suppressing the second one) even if they have different
  87842. ** sort orders.
  87843. **
  87844. ** If there are different collating sequences or if the columns of
  87845. ** the constraint occur in different orders, then the constraints are
  87846. ** considered distinct and both result in separate indices.
  87847. */
  87848. Index *pIdx;
  87849. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  87850. int k;
  87851. assert( IsUniqueIndex(pIdx) );
  87852. assert( pIdx->idxType!=SQLITE_IDXTYPE_APPDEF );
  87853. assert( IsUniqueIndex(pIndex) );
  87854. if( pIdx->nKeyCol!=pIndex->nKeyCol ) continue;
  87855. for(k=0; k<pIdx->nKeyCol; k++){
  87856. const char *z1;
  87857. const char *z2;
  87858. if( pIdx->aiColumn[k]!=pIndex->aiColumn[k] ) break;
  87859. z1 = pIdx->azColl[k];
  87860. z2 = pIndex->azColl[k];
  87861. if( z1!=z2 && sqlite3StrICmp(z1, z2) ) break;
  87862. }
  87863. if( k==pIdx->nKeyCol ){
  87864. if( pIdx->onError!=pIndex->onError ){
  87865. /* This constraint creates the same index as a previous
  87866. ** constraint specified somewhere in the CREATE TABLE statement.
  87867. ** However the ON CONFLICT clauses are different. If both this
  87868. ** constraint and the previous equivalent constraint have explicit
  87869. ** ON CONFLICT clauses this is an error. Otherwise, use the
  87870. ** explicitly specified behavior for the index.
  87871. */
  87872. if( !(pIdx->onError==OE_Default || pIndex->onError==OE_Default) ){
  87873. sqlite3ErrorMsg(pParse,
  87874. "conflicting ON CONFLICT clauses specified", 0);
  87875. }
  87876. if( pIdx->onError==OE_Default ){
  87877. pIdx->onError = pIndex->onError;
  87878. }
  87879. }
  87880. pRet = pIdx;
  87881. goto exit_create_index;
  87882. }
  87883. }
  87884. }
  87885. /* Link the new Index structure to its table and to the other
  87886. ** in-memory database structures.
  87887. */
  87888. if( db->init.busy ){
  87889. Index *p;
  87890. assert( sqlite3SchemaMutexHeld(db, 0, pIndex->pSchema) );
  87891. p = sqlite3HashInsert(&pIndex->pSchema->idxHash,
  87892. pIndex->zName, pIndex);
  87893. if( p ){
  87894. assert( p==pIndex ); /* Malloc must have failed */
  87895. db->mallocFailed = 1;
  87896. goto exit_create_index;
  87897. }
  87898. db->flags |= SQLITE_InternChanges;
  87899. if( pTblName!=0 ){
  87900. pIndex->tnum = db->init.newTnum;
  87901. }
  87902. }
  87903. /* If this is the initial CREATE INDEX statement (or CREATE TABLE if the
  87904. ** index is an implied index for a UNIQUE or PRIMARY KEY constraint) then
  87905. ** emit code to allocate the index rootpage on disk and make an entry for
  87906. ** the index in the sqlite_master table and populate the index with
  87907. ** content. But, do not do this if we are simply reading the sqlite_master
  87908. ** table to parse the schema, or if this index is the PRIMARY KEY index
  87909. ** of a WITHOUT ROWID table.
  87910. **
  87911. ** If pTblName==0 it means this index is generated as an implied PRIMARY KEY
  87912. ** or UNIQUE index in a CREATE TABLE statement. Since the table
  87913. ** has just been created, it contains no data and the index initialization
  87914. ** step can be skipped.
  87915. */
  87916. else if( pParse->nErr==0 && (HasRowid(pTab) || pTblName!=0) ){
  87917. Vdbe *v;
  87918. char *zStmt;
  87919. int iMem = ++pParse->nMem;
  87920. v = sqlite3GetVdbe(pParse);
  87921. if( v==0 ) goto exit_create_index;
  87922. /* Create the rootpage for the index
  87923. */
  87924. sqlite3BeginWriteOperation(pParse, 1, iDb);
  87925. sqlite3VdbeAddOp2(v, OP_CreateIndex, iDb, iMem);
  87926. /* Gather the complete text of the CREATE INDEX statement into
  87927. ** the zStmt variable
  87928. */
  87929. if( pStart ){
  87930. int n = (int)(pParse->sLastToken.z - pName->z) + pParse->sLastToken.n;
  87931. if( pName->z[n-1]==';' ) n--;
  87932. /* A named index with an explicit CREATE INDEX statement */
  87933. zStmt = sqlite3MPrintf(db, "CREATE%s INDEX %.*s",
  87934. onError==OE_None ? "" : " UNIQUE", n, pName->z);
  87935. }else{
  87936. /* An automatic index created by a PRIMARY KEY or UNIQUE constraint */
  87937. /* zStmt = sqlite3MPrintf(""); */
  87938. zStmt = 0;
  87939. }
  87940. /* Add an entry in sqlite_master for this index
  87941. */
  87942. sqlite3NestedParse(pParse,
  87943. "INSERT INTO %Q.%s VALUES('index',%Q,%Q,#%d,%Q);",
  87944. db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
  87945. pIndex->zName,
  87946. pTab->zName,
  87947. iMem,
  87948. zStmt
  87949. );
  87950. sqlite3DbFree(db, zStmt);
  87951. /* Fill the index with data and reparse the schema. Code an OP_Expire
  87952. ** to invalidate all pre-compiled statements.
  87953. */
  87954. if( pTblName ){
  87955. sqlite3RefillIndex(pParse, pIndex, iMem);
  87956. sqlite3ChangeCookie(pParse, iDb);
  87957. sqlite3VdbeAddParseSchemaOp(v, iDb,
  87958. sqlite3MPrintf(db, "name='%q' AND type='index'", pIndex->zName));
  87959. sqlite3VdbeAddOp1(v, OP_Expire, 0);
  87960. }
  87961. }
  87962. /* When adding an index to the list of indices for a table, make
  87963. ** sure all indices labeled OE_Replace come after all those labeled
  87964. ** OE_Ignore. This is necessary for the correct constraint check
  87965. ** processing (in sqlite3GenerateConstraintChecks()) as part of
  87966. ** UPDATE and INSERT statements.
  87967. */
  87968. if( db->init.busy || pTblName==0 ){
  87969. if( onError!=OE_Replace || pTab->pIndex==0
  87970. || pTab->pIndex->onError==OE_Replace){
  87971. pIndex->pNext = pTab->pIndex;
  87972. pTab->pIndex = pIndex;
  87973. }else{
  87974. Index *pOther = pTab->pIndex;
  87975. while( pOther->pNext && pOther->pNext->onError!=OE_Replace ){
  87976. pOther = pOther->pNext;
  87977. }
  87978. pIndex->pNext = pOther->pNext;
  87979. pOther->pNext = pIndex;
  87980. }
  87981. pRet = pIndex;
  87982. pIndex = 0;
  87983. }
  87984. /* Clean up before exiting */
  87985. exit_create_index:
  87986. if( pIndex ) freeIndex(db, pIndex);
  87987. sqlite3ExprDelete(db, pPIWhere);
  87988. sqlite3ExprListDelete(db, pList);
  87989. sqlite3SrcListDelete(db, pTblName);
  87990. sqlite3DbFree(db, zName);
  87991. return pRet;
  87992. }
  87993. /*
  87994. ** Fill the Index.aiRowEst[] array with default information - information
  87995. ** to be used when we have not run the ANALYZE command.
  87996. **
  87997. ** aiRowEst[0] is supposed to contain the number of elements in the index.
  87998. ** Since we do not know, guess 1 million. aiRowEst[1] is an estimate of the
  87999. ** number of rows in the table that match any particular value of the
  88000. ** first column of the index. aiRowEst[2] is an estimate of the number
  88001. ** of rows that match any particular combination of the first 2 columns
  88002. ** of the index. And so forth. It must always be the case that
  88003. *
  88004. ** aiRowEst[N]<=aiRowEst[N-1]
  88005. ** aiRowEst[N]>=1
  88006. **
  88007. ** Apart from that, we have little to go on besides intuition as to
  88008. ** how aiRowEst[] should be initialized. The numbers generated here
  88009. ** are based on typical values found in actual indices.
  88010. */
  88011. SQLITE_PRIVATE void sqlite3DefaultRowEst(Index *pIdx){
  88012. /* 10, 9, 8, 7, 6 */
  88013. LogEst aVal[] = { 33, 32, 30, 28, 26 };
  88014. LogEst *a = pIdx->aiRowLogEst;
  88015. int nCopy = MIN(ArraySize(aVal), pIdx->nKeyCol);
  88016. int i;
  88017. /* Set the first entry (number of rows in the index) to the estimated
  88018. ** number of rows in the table. Or 10, if the estimated number of rows
  88019. ** in the table is less than that. */
  88020. a[0] = pIdx->pTable->nRowLogEst;
  88021. if( a[0]<33 ) a[0] = 33; assert( 33==sqlite3LogEst(10) );
  88022. /* Estimate that a[1] is 10, a[2] is 9, a[3] is 8, a[4] is 7, a[5] is
  88023. ** 6 and each subsequent value (if any) is 5. */
  88024. memcpy(&a[1], aVal, nCopy*sizeof(LogEst));
  88025. for(i=nCopy+1; i<=pIdx->nKeyCol; i++){
  88026. a[i] = 23; assert( 23==sqlite3LogEst(5) );
  88027. }
  88028. assert( 0==sqlite3LogEst(1) );
  88029. if( IsUniqueIndex(pIdx) ) a[pIdx->nKeyCol] = 0;
  88030. }
  88031. /*
  88032. ** This routine will drop an existing named index. This routine
  88033. ** implements the DROP INDEX statement.
  88034. */
  88035. SQLITE_PRIVATE void sqlite3DropIndex(Parse *pParse, SrcList *pName, int ifExists){
  88036. Index *pIndex;
  88037. Vdbe *v;
  88038. sqlite3 *db = pParse->db;
  88039. int iDb;
  88040. assert( pParse->nErr==0 ); /* Never called with prior errors */
  88041. if( db->mallocFailed ){
  88042. goto exit_drop_index;
  88043. }
  88044. assert( pName->nSrc==1 );
  88045. if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
  88046. goto exit_drop_index;
  88047. }
  88048. pIndex = sqlite3FindIndex(db, pName->a[0].zName, pName->a[0].zDatabase);
  88049. if( pIndex==0 ){
  88050. if( !ifExists ){
  88051. sqlite3ErrorMsg(pParse, "no such index: %S", pName, 0);
  88052. }else{
  88053. sqlite3CodeVerifyNamedSchema(pParse, pName->a[0].zDatabase);
  88054. }
  88055. pParse->checkSchema = 1;
  88056. goto exit_drop_index;
  88057. }
  88058. if( pIndex->idxType!=SQLITE_IDXTYPE_APPDEF ){
  88059. sqlite3ErrorMsg(pParse, "index associated with UNIQUE "
  88060. "or PRIMARY KEY constraint cannot be dropped", 0);
  88061. goto exit_drop_index;
  88062. }
  88063. iDb = sqlite3SchemaToIndex(db, pIndex->pSchema);
  88064. #ifndef SQLITE_OMIT_AUTHORIZATION
  88065. {
  88066. int code = SQLITE_DROP_INDEX;
  88067. Table *pTab = pIndex->pTable;
  88068. const char *zDb = db->aDb[iDb].zName;
  88069. const char *zTab = SCHEMA_TABLE(iDb);
  88070. if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb) ){
  88071. goto exit_drop_index;
  88072. }
  88073. if( !OMIT_TEMPDB && iDb ) code = SQLITE_DROP_TEMP_INDEX;
  88074. if( sqlite3AuthCheck(pParse, code, pIndex->zName, pTab->zName, zDb) ){
  88075. goto exit_drop_index;
  88076. }
  88077. }
  88078. #endif
  88079. /* Generate code to remove the index and from the master table */
  88080. v = sqlite3GetVdbe(pParse);
  88081. if( v ){
  88082. sqlite3BeginWriteOperation(pParse, 1, iDb);
  88083. sqlite3NestedParse(pParse,
  88084. "DELETE FROM %Q.%s WHERE name=%Q AND type='index'",
  88085. db->aDb[iDb].zName, SCHEMA_TABLE(iDb), pIndex->zName
  88086. );
  88087. sqlite3ClearStatTables(pParse, iDb, "idx", pIndex->zName);
  88088. sqlite3ChangeCookie(pParse, iDb);
  88089. destroyRootPage(pParse, pIndex->tnum, iDb);
  88090. sqlite3VdbeAddOp4(v, OP_DropIndex, iDb, 0, 0, pIndex->zName, 0);
  88091. }
  88092. exit_drop_index:
  88093. sqlite3SrcListDelete(db, pName);
  88094. }
  88095. /*
  88096. ** pArray is a pointer to an array of objects. Each object in the
  88097. ** array is szEntry bytes in size. This routine uses sqlite3DbRealloc()
  88098. ** to extend the array so that there is space for a new object at the end.
  88099. **
  88100. ** When this function is called, *pnEntry contains the current size of
  88101. ** the array (in entries - so the allocation is ((*pnEntry) * szEntry) bytes
  88102. ** in total).
  88103. **
  88104. ** If the realloc() is successful (i.e. if no OOM condition occurs), the
  88105. ** space allocated for the new object is zeroed, *pnEntry updated to
  88106. ** reflect the new size of the array and a pointer to the new allocation
  88107. ** returned. *pIdx is set to the index of the new array entry in this case.
  88108. **
  88109. ** Otherwise, if the realloc() fails, *pIdx is set to -1, *pnEntry remains
  88110. ** unchanged and a copy of pArray returned.
  88111. */
  88112. SQLITE_PRIVATE void *sqlite3ArrayAllocate(
  88113. sqlite3 *db, /* Connection to notify of malloc failures */
  88114. void *pArray, /* Array of objects. Might be reallocated */
  88115. int szEntry, /* Size of each object in the array */
  88116. int *pnEntry, /* Number of objects currently in use */
  88117. int *pIdx /* Write the index of a new slot here */
  88118. ){
  88119. char *z;
  88120. int n = *pnEntry;
  88121. if( (n & (n-1))==0 ){
  88122. int sz = (n==0) ? 1 : 2*n;
  88123. void *pNew = sqlite3DbRealloc(db, pArray, sz*szEntry);
  88124. if( pNew==0 ){
  88125. *pIdx = -1;
  88126. return pArray;
  88127. }
  88128. pArray = pNew;
  88129. }
  88130. z = (char*)pArray;
  88131. memset(&z[n * szEntry], 0, szEntry);
  88132. *pIdx = n;
  88133. ++*pnEntry;
  88134. return pArray;
  88135. }
  88136. /*
  88137. ** Append a new element to the given IdList. Create a new IdList if
  88138. ** need be.
  88139. **
  88140. ** A new IdList is returned, or NULL if malloc() fails.
  88141. */
  88142. SQLITE_PRIVATE IdList *sqlite3IdListAppend(sqlite3 *db, IdList *pList, Token *pToken){
  88143. int i;
  88144. if( pList==0 ){
  88145. pList = sqlite3DbMallocZero(db, sizeof(IdList) );
  88146. if( pList==0 ) return 0;
  88147. }
  88148. pList->a = sqlite3ArrayAllocate(
  88149. db,
  88150. pList->a,
  88151. sizeof(pList->a[0]),
  88152. &pList->nId,
  88153. &i
  88154. );
  88155. if( i<0 ){
  88156. sqlite3IdListDelete(db, pList);
  88157. return 0;
  88158. }
  88159. pList->a[i].zName = sqlite3NameFromToken(db, pToken);
  88160. return pList;
  88161. }
  88162. /*
  88163. ** Delete an IdList.
  88164. */
  88165. SQLITE_PRIVATE void sqlite3IdListDelete(sqlite3 *db, IdList *pList){
  88166. int i;
  88167. if( pList==0 ) return;
  88168. for(i=0; i<pList->nId; i++){
  88169. sqlite3DbFree(db, pList->a[i].zName);
  88170. }
  88171. sqlite3DbFree(db, pList->a);
  88172. sqlite3DbFree(db, pList);
  88173. }
  88174. /*
  88175. ** Return the index in pList of the identifier named zId. Return -1
  88176. ** if not found.
  88177. */
  88178. SQLITE_PRIVATE int sqlite3IdListIndex(IdList *pList, const char *zName){
  88179. int i;
  88180. if( pList==0 ) return -1;
  88181. for(i=0; i<pList->nId; i++){
  88182. if( sqlite3StrICmp(pList->a[i].zName, zName)==0 ) return i;
  88183. }
  88184. return -1;
  88185. }
  88186. /*
  88187. ** Expand the space allocated for the given SrcList object by
  88188. ** creating nExtra new slots beginning at iStart. iStart is zero based.
  88189. ** New slots are zeroed.
  88190. **
  88191. ** For example, suppose a SrcList initially contains two entries: A,B.
  88192. ** To append 3 new entries onto the end, do this:
  88193. **
  88194. ** sqlite3SrcListEnlarge(db, pSrclist, 3, 2);
  88195. **
  88196. ** After the call above it would contain: A, B, nil, nil, nil.
  88197. ** If the iStart argument had been 1 instead of 2, then the result
  88198. ** would have been: A, nil, nil, nil, B. To prepend the new slots,
  88199. ** the iStart value would be 0. The result then would
  88200. ** be: nil, nil, nil, A, B.
  88201. **
  88202. ** If a memory allocation fails the SrcList is unchanged. The
  88203. ** db->mallocFailed flag will be set to true.
  88204. */
  88205. SQLITE_PRIVATE SrcList *sqlite3SrcListEnlarge(
  88206. sqlite3 *db, /* Database connection to notify of OOM errors */
  88207. SrcList *pSrc, /* The SrcList to be enlarged */
  88208. int nExtra, /* Number of new slots to add to pSrc->a[] */
  88209. int iStart /* Index in pSrc->a[] of first new slot */
  88210. ){
  88211. int i;
  88212. /* Sanity checking on calling parameters */
  88213. assert( iStart>=0 );
  88214. assert( nExtra>=1 );
  88215. assert( pSrc!=0 );
  88216. assert( iStart<=pSrc->nSrc );
  88217. /* Allocate additional space if needed */
  88218. if( (u32)pSrc->nSrc+nExtra>pSrc->nAlloc ){
  88219. SrcList *pNew;
  88220. int nAlloc = pSrc->nSrc+nExtra;
  88221. int nGot;
  88222. pNew = sqlite3DbRealloc(db, pSrc,
  88223. sizeof(*pSrc) + (nAlloc-1)*sizeof(pSrc->a[0]) );
  88224. if( pNew==0 ){
  88225. assert( db->mallocFailed );
  88226. return pSrc;
  88227. }
  88228. pSrc = pNew;
  88229. nGot = (sqlite3DbMallocSize(db, pNew) - sizeof(*pSrc))/sizeof(pSrc->a[0])+1;
  88230. pSrc->nAlloc = nGot;
  88231. }
  88232. /* Move existing slots that come after the newly inserted slots
  88233. ** out of the way */
  88234. for(i=pSrc->nSrc-1; i>=iStart; i--){
  88235. pSrc->a[i+nExtra] = pSrc->a[i];
  88236. }
  88237. pSrc->nSrc += nExtra;
  88238. /* Zero the newly allocated slots */
  88239. memset(&pSrc->a[iStart], 0, sizeof(pSrc->a[0])*nExtra);
  88240. for(i=iStart; i<iStart+nExtra; i++){
  88241. pSrc->a[i].iCursor = -1;
  88242. }
  88243. /* Return a pointer to the enlarged SrcList */
  88244. return pSrc;
  88245. }
  88246. /*
  88247. ** Append a new table name to the given SrcList. Create a new SrcList if
  88248. ** need be. A new entry is created in the SrcList even if pTable is NULL.
  88249. **
  88250. ** A SrcList is returned, or NULL if there is an OOM error. The returned
  88251. ** SrcList might be the same as the SrcList that was input or it might be
  88252. ** a new one. If an OOM error does occurs, then the prior value of pList
  88253. ** that is input to this routine is automatically freed.
  88254. **
  88255. ** If pDatabase is not null, it means that the table has an optional
  88256. ** database name prefix. Like this: "database.table". The pDatabase
  88257. ** points to the table name and the pTable points to the database name.
  88258. ** The SrcList.a[].zName field is filled with the table name which might
  88259. ** come from pTable (if pDatabase is NULL) or from pDatabase.
  88260. ** SrcList.a[].zDatabase is filled with the database name from pTable,
  88261. ** or with NULL if no database is specified.
  88262. **
  88263. ** In other words, if call like this:
  88264. **
  88265. ** sqlite3SrcListAppend(D,A,B,0);
  88266. **
  88267. ** Then B is a table name and the database name is unspecified. If called
  88268. ** like this:
  88269. **
  88270. ** sqlite3SrcListAppend(D,A,B,C);
  88271. **
  88272. ** Then C is the table name and B is the database name. If C is defined
  88273. ** then so is B. In other words, we never have a case where:
  88274. **
  88275. ** sqlite3SrcListAppend(D,A,0,C);
  88276. **
  88277. ** Both pTable and pDatabase are assumed to be quoted. They are dequoted
  88278. ** before being added to the SrcList.
  88279. */
  88280. SQLITE_PRIVATE SrcList *sqlite3SrcListAppend(
  88281. sqlite3 *db, /* Connection to notify of malloc failures */
  88282. SrcList *pList, /* Append to this SrcList. NULL creates a new SrcList */
  88283. Token *pTable, /* Table to append */
  88284. Token *pDatabase /* Database of the table */
  88285. ){
  88286. struct SrcList_item *pItem;
  88287. assert( pDatabase==0 || pTable!=0 ); /* Cannot have C without B */
  88288. if( pList==0 ){
  88289. pList = sqlite3DbMallocZero(db, sizeof(SrcList) );
  88290. if( pList==0 ) return 0;
  88291. pList->nAlloc = 1;
  88292. }
  88293. pList = sqlite3SrcListEnlarge(db, pList, 1, pList->nSrc);
  88294. if( db->mallocFailed ){
  88295. sqlite3SrcListDelete(db, pList);
  88296. return 0;
  88297. }
  88298. pItem = &pList->a[pList->nSrc-1];
  88299. if( pDatabase && pDatabase->z==0 ){
  88300. pDatabase = 0;
  88301. }
  88302. if( pDatabase ){
  88303. Token *pTemp = pDatabase;
  88304. pDatabase = pTable;
  88305. pTable = pTemp;
  88306. }
  88307. pItem->zName = sqlite3NameFromToken(db, pTable);
  88308. pItem->zDatabase = sqlite3NameFromToken(db, pDatabase);
  88309. return pList;
  88310. }
  88311. /*
  88312. ** Assign VdbeCursor index numbers to all tables in a SrcList
  88313. */
  88314. SQLITE_PRIVATE void sqlite3SrcListAssignCursors(Parse *pParse, SrcList *pList){
  88315. int i;
  88316. struct SrcList_item *pItem;
  88317. assert(pList || pParse->db->mallocFailed );
  88318. if( pList ){
  88319. for(i=0, pItem=pList->a; i<pList->nSrc; i++, pItem++){
  88320. if( pItem->iCursor>=0 ) break;
  88321. pItem->iCursor = pParse->nTab++;
  88322. if( pItem->pSelect ){
  88323. sqlite3SrcListAssignCursors(pParse, pItem->pSelect->pSrc);
  88324. }
  88325. }
  88326. }
  88327. }
  88328. /*
  88329. ** Delete an entire SrcList including all its substructure.
  88330. */
  88331. SQLITE_PRIVATE void sqlite3SrcListDelete(sqlite3 *db, SrcList *pList){
  88332. int i;
  88333. struct SrcList_item *pItem;
  88334. if( pList==0 ) return;
  88335. for(pItem=pList->a, i=0; i<pList->nSrc; i++, pItem++){
  88336. sqlite3DbFree(db, pItem->zDatabase);
  88337. sqlite3DbFree(db, pItem->zName);
  88338. sqlite3DbFree(db, pItem->zAlias);
  88339. sqlite3DbFree(db, pItem->zIndex);
  88340. sqlite3DeleteTable(db, pItem->pTab);
  88341. sqlite3SelectDelete(db, pItem->pSelect);
  88342. sqlite3ExprDelete(db, pItem->pOn);
  88343. sqlite3IdListDelete(db, pItem->pUsing);
  88344. }
  88345. sqlite3DbFree(db, pList);
  88346. }
  88347. /*
  88348. ** This routine is called by the parser to add a new term to the
  88349. ** end of a growing FROM clause. The "p" parameter is the part of
  88350. ** the FROM clause that has already been constructed. "p" is NULL
  88351. ** if this is the first term of the FROM clause. pTable and pDatabase
  88352. ** are the name of the table and database named in the FROM clause term.
  88353. ** pDatabase is NULL if the database name qualifier is missing - the
  88354. ** usual case. If the term has an alias, then pAlias points to the
  88355. ** alias token. If the term is a subquery, then pSubquery is the
  88356. ** SELECT statement that the subquery encodes. The pTable and
  88357. ** pDatabase parameters are NULL for subqueries. The pOn and pUsing
  88358. ** parameters are the content of the ON and USING clauses.
  88359. **
  88360. ** Return a new SrcList which encodes is the FROM with the new
  88361. ** term added.
  88362. */
  88363. SQLITE_PRIVATE SrcList *sqlite3SrcListAppendFromTerm(
  88364. Parse *pParse, /* Parsing context */
  88365. SrcList *p, /* The left part of the FROM clause already seen */
  88366. Token *pTable, /* Name of the table to add to the FROM clause */
  88367. Token *pDatabase, /* Name of the database containing pTable */
  88368. Token *pAlias, /* The right-hand side of the AS subexpression */
  88369. Select *pSubquery, /* A subquery used in place of a table name */
  88370. Expr *pOn, /* The ON clause of a join */
  88371. IdList *pUsing /* The USING clause of a join */
  88372. ){
  88373. struct SrcList_item *pItem;
  88374. sqlite3 *db = pParse->db;
  88375. if( !p && (pOn || pUsing) ){
  88376. sqlite3ErrorMsg(pParse, "a JOIN clause is required before %s",
  88377. (pOn ? "ON" : "USING")
  88378. );
  88379. goto append_from_error;
  88380. }
  88381. p = sqlite3SrcListAppend(db, p, pTable, pDatabase);
  88382. if( p==0 || NEVER(p->nSrc==0) ){
  88383. goto append_from_error;
  88384. }
  88385. pItem = &p->a[p->nSrc-1];
  88386. assert( pAlias!=0 );
  88387. if( pAlias->n ){
  88388. pItem->zAlias = sqlite3NameFromToken(db, pAlias);
  88389. }
  88390. pItem->pSelect = pSubquery;
  88391. pItem->pOn = pOn;
  88392. pItem->pUsing = pUsing;
  88393. return p;
  88394. append_from_error:
  88395. assert( p==0 );
  88396. sqlite3ExprDelete(db, pOn);
  88397. sqlite3IdListDelete(db, pUsing);
  88398. sqlite3SelectDelete(db, pSubquery);
  88399. return 0;
  88400. }
  88401. /*
  88402. ** Add an INDEXED BY or NOT INDEXED clause to the most recently added
  88403. ** element of the source-list passed as the second argument.
  88404. */
  88405. SQLITE_PRIVATE void sqlite3SrcListIndexedBy(Parse *pParse, SrcList *p, Token *pIndexedBy){
  88406. assert( pIndexedBy!=0 );
  88407. if( p && ALWAYS(p->nSrc>0) ){
  88408. struct SrcList_item *pItem = &p->a[p->nSrc-1];
  88409. assert( pItem->notIndexed==0 && pItem->zIndex==0 );
  88410. if( pIndexedBy->n==1 && !pIndexedBy->z ){
  88411. /* A "NOT INDEXED" clause was supplied. See parse.y
  88412. ** construct "indexed_opt" for details. */
  88413. pItem->notIndexed = 1;
  88414. }else{
  88415. pItem->zIndex = sqlite3NameFromToken(pParse->db, pIndexedBy);
  88416. }
  88417. }
  88418. }
  88419. /*
  88420. ** When building up a FROM clause in the parser, the join operator
  88421. ** is initially attached to the left operand. But the code generator
  88422. ** expects the join operator to be on the right operand. This routine
  88423. ** Shifts all join operators from left to right for an entire FROM
  88424. ** clause.
  88425. **
  88426. ** Example: Suppose the join is like this:
  88427. **
  88428. ** A natural cross join B
  88429. **
  88430. ** The operator is "natural cross join". The A and B operands are stored
  88431. ** in p->a[0] and p->a[1], respectively. The parser initially stores the
  88432. ** operator with A. This routine shifts that operator over to B.
  88433. */
  88434. SQLITE_PRIVATE void sqlite3SrcListShiftJoinType(SrcList *p){
  88435. if( p ){
  88436. int i;
  88437. for(i=p->nSrc-1; i>0; i--){
  88438. p->a[i].jointype = p->a[i-1].jointype;
  88439. }
  88440. p->a[0].jointype = 0;
  88441. }
  88442. }
  88443. /*
  88444. ** Begin a transaction
  88445. */
  88446. SQLITE_PRIVATE void sqlite3BeginTransaction(Parse *pParse, int type){
  88447. sqlite3 *db;
  88448. Vdbe *v;
  88449. int i;
  88450. assert( pParse!=0 );
  88451. db = pParse->db;
  88452. assert( db!=0 );
  88453. /* if( db->aDb[0].pBt==0 ) return; */
  88454. if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "BEGIN", 0, 0) ){
  88455. return;
  88456. }
  88457. v = sqlite3GetVdbe(pParse);
  88458. if( !v ) return;
  88459. if( type!=TK_DEFERRED ){
  88460. for(i=0; i<db->nDb; i++){
  88461. sqlite3VdbeAddOp2(v, OP_Transaction, i, (type==TK_EXCLUSIVE)+1);
  88462. sqlite3VdbeUsesBtree(v, i);
  88463. }
  88464. }
  88465. sqlite3VdbeAddOp2(v, OP_AutoCommit, 0, 0);
  88466. }
  88467. /*
  88468. ** Commit a transaction
  88469. */
  88470. SQLITE_PRIVATE void sqlite3CommitTransaction(Parse *pParse){
  88471. Vdbe *v;
  88472. assert( pParse!=0 );
  88473. assert( pParse->db!=0 );
  88474. if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "COMMIT", 0, 0) ){
  88475. return;
  88476. }
  88477. v = sqlite3GetVdbe(pParse);
  88478. if( v ){
  88479. sqlite3VdbeAddOp2(v, OP_AutoCommit, 1, 0);
  88480. }
  88481. }
  88482. /*
  88483. ** Rollback a transaction
  88484. */
  88485. SQLITE_PRIVATE void sqlite3RollbackTransaction(Parse *pParse){
  88486. Vdbe *v;
  88487. assert( pParse!=0 );
  88488. assert( pParse->db!=0 );
  88489. if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "ROLLBACK", 0, 0) ){
  88490. return;
  88491. }
  88492. v = sqlite3GetVdbe(pParse);
  88493. if( v ){
  88494. sqlite3VdbeAddOp2(v, OP_AutoCommit, 1, 1);
  88495. }
  88496. }
  88497. /*
  88498. ** This function is called by the parser when it parses a command to create,
  88499. ** release or rollback an SQL savepoint.
  88500. */
  88501. SQLITE_PRIVATE void sqlite3Savepoint(Parse *pParse, int op, Token *pName){
  88502. char *zName = sqlite3NameFromToken(pParse->db, pName);
  88503. if( zName ){
  88504. Vdbe *v = sqlite3GetVdbe(pParse);
  88505. #ifndef SQLITE_OMIT_AUTHORIZATION
  88506. static const char * const az[] = { "BEGIN", "RELEASE", "ROLLBACK" };
  88507. assert( !SAVEPOINT_BEGIN && SAVEPOINT_RELEASE==1 && SAVEPOINT_ROLLBACK==2 );
  88508. #endif
  88509. if( !v || sqlite3AuthCheck(pParse, SQLITE_SAVEPOINT, az[op], zName, 0) ){
  88510. sqlite3DbFree(pParse->db, zName);
  88511. return;
  88512. }
  88513. sqlite3VdbeAddOp4(v, OP_Savepoint, op, 0, 0, zName, P4_DYNAMIC);
  88514. }
  88515. }
  88516. /*
  88517. ** Make sure the TEMP database is open and available for use. Return
  88518. ** the number of errors. Leave any error messages in the pParse structure.
  88519. */
  88520. SQLITE_PRIVATE int sqlite3OpenTempDatabase(Parse *pParse){
  88521. sqlite3 *db = pParse->db;
  88522. if( db->aDb[1].pBt==0 && !pParse->explain ){
  88523. int rc;
  88524. Btree *pBt;
  88525. static const int flags =
  88526. SQLITE_OPEN_READWRITE |
  88527. SQLITE_OPEN_CREATE |
  88528. SQLITE_OPEN_EXCLUSIVE |
  88529. SQLITE_OPEN_DELETEONCLOSE |
  88530. SQLITE_OPEN_TEMP_DB;
  88531. rc = sqlite3BtreeOpen(db->pVfs, 0, db, &pBt, 0, flags);
  88532. if( rc!=SQLITE_OK ){
  88533. sqlite3ErrorMsg(pParse, "unable to open a temporary database "
  88534. "file for storing temporary tables");
  88535. pParse->rc = rc;
  88536. return 1;
  88537. }
  88538. db->aDb[1].pBt = pBt;
  88539. assert( db->aDb[1].pSchema );
  88540. if( SQLITE_NOMEM==sqlite3BtreeSetPageSize(pBt, db->nextPagesize, -1, 0) ){
  88541. db->mallocFailed = 1;
  88542. return 1;
  88543. }
  88544. }
  88545. return 0;
  88546. }
  88547. /*
  88548. ** Record the fact that the schema cookie will need to be verified
  88549. ** for database iDb. The code to actually verify the schema cookie
  88550. ** will occur at the end of the top-level VDBE and will be generated
  88551. ** later, by sqlite3FinishCoding().
  88552. */
  88553. SQLITE_PRIVATE void sqlite3CodeVerifySchema(Parse *pParse, int iDb){
  88554. Parse *pToplevel = sqlite3ParseToplevel(pParse);
  88555. sqlite3 *db = pToplevel->db;
  88556. assert( iDb>=0 && iDb<db->nDb );
  88557. assert( db->aDb[iDb].pBt!=0 || iDb==1 );
  88558. assert( iDb<SQLITE_MAX_ATTACHED+2 );
  88559. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  88560. if( DbMaskTest(pToplevel->cookieMask, iDb)==0 ){
  88561. DbMaskSet(pToplevel->cookieMask, iDb);
  88562. pToplevel->cookieValue[iDb] = db->aDb[iDb].pSchema->schema_cookie;
  88563. if( !OMIT_TEMPDB && iDb==1 ){
  88564. sqlite3OpenTempDatabase(pToplevel);
  88565. }
  88566. }
  88567. }
  88568. /*
  88569. ** If argument zDb is NULL, then call sqlite3CodeVerifySchema() for each
  88570. ** attached database. Otherwise, invoke it for the database named zDb only.
  88571. */
  88572. SQLITE_PRIVATE void sqlite3CodeVerifyNamedSchema(Parse *pParse, const char *zDb){
  88573. sqlite3 *db = pParse->db;
  88574. int i;
  88575. for(i=0; i<db->nDb; i++){
  88576. Db *pDb = &db->aDb[i];
  88577. if( pDb->pBt && (!zDb || 0==sqlite3StrICmp(zDb, pDb->zName)) ){
  88578. sqlite3CodeVerifySchema(pParse, i);
  88579. }
  88580. }
  88581. }
  88582. /*
  88583. ** Generate VDBE code that prepares for doing an operation that
  88584. ** might change the database.
  88585. **
  88586. ** This routine starts a new transaction if we are not already within
  88587. ** a transaction. If we are already within a transaction, then a checkpoint
  88588. ** is set if the setStatement parameter is true. A checkpoint should
  88589. ** be set for operations that might fail (due to a constraint) part of
  88590. ** the way through and which will need to undo some writes without having to
  88591. ** rollback the whole transaction. For operations where all constraints
  88592. ** can be checked before any changes are made to the database, it is never
  88593. ** necessary to undo a write and the checkpoint should not be set.
  88594. */
  88595. SQLITE_PRIVATE void sqlite3BeginWriteOperation(Parse *pParse, int setStatement, int iDb){
  88596. Parse *pToplevel = sqlite3ParseToplevel(pParse);
  88597. sqlite3CodeVerifySchema(pParse, iDb);
  88598. DbMaskSet(pToplevel->writeMask, iDb);
  88599. pToplevel->isMultiWrite |= setStatement;
  88600. }
  88601. /*
  88602. ** Indicate that the statement currently under construction might write
  88603. ** more than one entry (example: deleting one row then inserting another,
  88604. ** inserting multiple rows in a table, or inserting a row and index entries.)
  88605. ** If an abort occurs after some of these writes have completed, then it will
  88606. ** be necessary to undo the completed writes.
  88607. */
  88608. SQLITE_PRIVATE void sqlite3MultiWrite(Parse *pParse){
  88609. Parse *pToplevel = sqlite3ParseToplevel(pParse);
  88610. pToplevel->isMultiWrite = 1;
  88611. }
  88612. /*
  88613. ** The code generator calls this routine if is discovers that it is
  88614. ** possible to abort a statement prior to completion. In order to
  88615. ** perform this abort without corrupting the database, we need to make
  88616. ** sure that the statement is protected by a statement transaction.
  88617. **
  88618. ** Technically, we only need to set the mayAbort flag if the
  88619. ** isMultiWrite flag was previously set. There is a time dependency
  88620. ** such that the abort must occur after the multiwrite. This makes
  88621. ** some statements involving the REPLACE conflict resolution algorithm
  88622. ** go a little faster. But taking advantage of this time dependency
  88623. ** makes it more difficult to prove that the code is correct (in
  88624. ** particular, it prevents us from writing an effective
  88625. ** implementation of sqlite3AssertMayAbort()) and so we have chosen
  88626. ** to take the safe route and skip the optimization.
  88627. */
  88628. SQLITE_PRIVATE void sqlite3MayAbort(Parse *pParse){
  88629. Parse *pToplevel = sqlite3ParseToplevel(pParse);
  88630. pToplevel->mayAbort = 1;
  88631. }
  88632. /*
  88633. ** Code an OP_Halt that causes the vdbe to return an SQLITE_CONSTRAINT
  88634. ** error. The onError parameter determines which (if any) of the statement
  88635. ** and/or current transaction is rolled back.
  88636. */
  88637. SQLITE_PRIVATE void sqlite3HaltConstraint(
  88638. Parse *pParse, /* Parsing context */
  88639. int errCode, /* extended error code */
  88640. int onError, /* Constraint type */
  88641. char *p4, /* Error message */
  88642. i8 p4type, /* P4_STATIC or P4_TRANSIENT */
  88643. u8 p5Errmsg /* P5_ErrMsg type */
  88644. ){
  88645. Vdbe *v = sqlite3GetVdbe(pParse);
  88646. assert( (errCode&0xff)==SQLITE_CONSTRAINT );
  88647. if( onError==OE_Abort ){
  88648. sqlite3MayAbort(pParse);
  88649. }
  88650. sqlite3VdbeAddOp4(v, OP_Halt, errCode, onError, 0, p4, p4type);
  88651. if( p5Errmsg ) sqlite3VdbeChangeP5(v, p5Errmsg);
  88652. }
  88653. /*
  88654. ** Code an OP_Halt due to UNIQUE or PRIMARY KEY constraint violation.
  88655. */
  88656. SQLITE_PRIVATE void sqlite3UniqueConstraint(
  88657. Parse *pParse, /* Parsing context */
  88658. int onError, /* Constraint type */
  88659. Index *pIdx /* The index that triggers the constraint */
  88660. ){
  88661. char *zErr;
  88662. int j;
  88663. StrAccum errMsg;
  88664. Table *pTab = pIdx->pTable;
  88665. sqlite3StrAccumInit(&errMsg, pParse->db, 0, 0, 200);
  88666. for(j=0; j<pIdx->nKeyCol; j++){
  88667. char *zCol = pTab->aCol[pIdx->aiColumn[j]].zName;
  88668. if( j ) sqlite3StrAccumAppend(&errMsg, ", ", 2);
  88669. sqlite3StrAccumAppendAll(&errMsg, pTab->zName);
  88670. sqlite3StrAccumAppend(&errMsg, ".", 1);
  88671. sqlite3StrAccumAppendAll(&errMsg, zCol);
  88672. }
  88673. zErr = sqlite3StrAccumFinish(&errMsg);
  88674. sqlite3HaltConstraint(pParse,
  88675. IsPrimaryKeyIndex(pIdx) ? SQLITE_CONSTRAINT_PRIMARYKEY
  88676. : SQLITE_CONSTRAINT_UNIQUE,
  88677. onError, zErr, P4_DYNAMIC, P5_ConstraintUnique);
  88678. }
  88679. /*
  88680. ** Code an OP_Halt due to non-unique rowid.
  88681. */
  88682. SQLITE_PRIVATE void sqlite3RowidConstraint(
  88683. Parse *pParse, /* Parsing context */
  88684. int onError, /* Conflict resolution algorithm */
  88685. Table *pTab /* The table with the non-unique rowid */
  88686. ){
  88687. char *zMsg;
  88688. int rc;
  88689. if( pTab->iPKey>=0 ){
  88690. zMsg = sqlite3MPrintf(pParse->db, "%s.%s", pTab->zName,
  88691. pTab->aCol[pTab->iPKey].zName);
  88692. rc = SQLITE_CONSTRAINT_PRIMARYKEY;
  88693. }else{
  88694. zMsg = sqlite3MPrintf(pParse->db, "%s.rowid", pTab->zName);
  88695. rc = SQLITE_CONSTRAINT_ROWID;
  88696. }
  88697. sqlite3HaltConstraint(pParse, rc, onError, zMsg, P4_DYNAMIC,
  88698. P5_ConstraintUnique);
  88699. }
  88700. /*
  88701. ** Check to see if pIndex uses the collating sequence pColl. Return
  88702. ** true if it does and false if it does not.
  88703. */
  88704. #ifndef SQLITE_OMIT_REINDEX
  88705. static int collationMatch(const char *zColl, Index *pIndex){
  88706. int i;
  88707. assert( zColl!=0 );
  88708. for(i=0; i<pIndex->nColumn; i++){
  88709. const char *z = pIndex->azColl[i];
  88710. assert( z!=0 || pIndex->aiColumn[i]<0 );
  88711. if( pIndex->aiColumn[i]>=0 && 0==sqlite3StrICmp(z, zColl) ){
  88712. return 1;
  88713. }
  88714. }
  88715. return 0;
  88716. }
  88717. #endif
  88718. /*
  88719. ** Recompute all indices of pTab that use the collating sequence pColl.
  88720. ** If pColl==0 then recompute all indices of pTab.
  88721. */
  88722. #ifndef SQLITE_OMIT_REINDEX
  88723. static void reindexTable(Parse *pParse, Table *pTab, char const *zColl){
  88724. Index *pIndex; /* An index associated with pTab */
  88725. for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){
  88726. if( zColl==0 || collationMatch(zColl, pIndex) ){
  88727. int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
  88728. sqlite3BeginWriteOperation(pParse, 0, iDb);
  88729. sqlite3RefillIndex(pParse, pIndex, -1);
  88730. }
  88731. }
  88732. }
  88733. #endif
  88734. /*
  88735. ** Recompute all indices of all tables in all databases where the
  88736. ** indices use the collating sequence pColl. If pColl==0 then recompute
  88737. ** all indices everywhere.
  88738. */
  88739. #ifndef SQLITE_OMIT_REINDEX
  88740. static void reindexDatabases(Parse *pParse, char const *zColl){
  88741. Db *pDb; /* A single database */
  88742. int iDb; /* The database index number */
  88743. sqlite3 *db = pParse->db; /* The database connection */
  88744. HashElem *k; /* For looping over tables in pDb */
  88745. Table *pTab; /* A table in the database */
  88746. assert( sqlite3BtreeHoldsAllMutexes(db) ); /* Needed for schema access */
  88747. for(iDb=0, pDb=db->aDb; iDb<db->nDb; iDb++, pDb++){
  88748. assert( pDb!=0 );
  88749. for(k=sqliteHashFirst(&pDb->pSchema->tblHash); k; k=sqliteHashNext(k)){
  88750. pTab = (Table*)sqliteHashData(k);
  88751. reindexTable(pParse, pTab, zColl);
  88752. }
  88753. }
  88754. }
  88755. #endif
  88756. /*
  88757. ** Generate code for the REINDEX command.
  88758. **
  88759. ** REINDEX -- 1
  88760. ** REINDEX <collation> -- 2
  88761. ** REINDEX ?<database>.?<tablename> -- 3
  88762. ** REINDEX ?<database>.?<indexname> -- 4
  88763. **
  88764. ** Form 1 causes all indices in all attached databases to be rebuilt.
  88765. ** Form 2 rebuilds all indices in all databases that use the named
  88766. ** collating function. Forms 3 and 4 rebuild the named index or all
  88767. ** indices associated with the named table.
  88768. */
  88769. #ifndef SQLITE_OMIT_REINDEX
  88770. SQLITE_PRIVATE void sqlite3Reindex(Parse *pParse, Token *pName1, Token *pName2){
  88771. CollSeq *pColl; /* Collating sequence to be reindexed, or NULL */
  88772. char *z; /* Name of a table or index */
  88773. const char *zDb; /* Name of the database */
  88774. Table *pTab; /* A table in the database */
  88775. Index *pIndex; /* An index associated with pTab */
  88776. int iDb; /* The database index number */
  88777. sqlite3 *db = pParse->db; /* The database connection */
  88778. Token *pObjName; /* Name of the table or index to be reindexed */
  88779. /* Read the database schema. If an error occurs, leave an error message
  88780. ** and code in pParse and return NULL. */
  88781. if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
  88782. return;
  88783. }
  88784. if( pName1==0 ){
  88785. reindexDatabases(pParse, 0);
  88786. return;
  88787. }else if( NEVER(pName2==0) || pName2->z==0 ){
  88788. char *zColl;
  88789. assert( pName1->z );
  88790. zColl = sqlite3NameFromToken(pParse->db, pName1);
  88791. if( !zColl ) return;
  88792. pColl = sqlite3FindCollSeq(db, ENC(db), zColl, 0);
  88793. if( pColl ){
  88794. reindexDatabases(pParse, zColl);
  88795. sqlite3DbFree(db, zColl);
  88796. return;
  88797. }
  88798. sqlite3DbFree(db, zColl);
  88799. }
  88800. iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pObjName);
  88801. if( iDb<0 ) return;
  88802. z = sqlite3NameFromToken(db, pObjName);
  88803. if( z==0 ) return;
  88804. zDb = db->aDb[iDb].zName;
  88805. pTab = sqlite3FindTable(db, z, zDb);
  88806. if( pTab ){
  88807. reindexTable(pParse, pTab, 0);
  88808. sqlite3DbFree(db, z);
  88809. return;
  88810. }
  88811. pIndex = sqlite3FindIndex(db, z, zDb);
  88812. sqlite3DbFree(db, z);
  88813. if( pIndex ){
  88814. sqlite3BeginWriteOperation(pParse, 0, iDb);
  88815. sqlite3RefillIndex(pParse, pIndex, -1);
  88816. return;
  88817. }
  88818. sqlite3ErrorMsg(pParse, "unable to identify the object to be reindexed");
  88819. }
  88820. #endif
  88821. /*
  88822. ** Return a KeyInfo structure that is appropriate for the given Index.
  88823. **
  88824. ** The KeyInfo structure for an index is cached in the Index object.
  88825. ** So there might be multiple references to the returned pointer. The
  88826. ** caller should not try to modify the KeyInfo object.
  88827. **
  88828. ** The caller should invoke sqlite3KeyInfoUnref() on the returned object
  88829. ** when it has finished using it.
  88830. */
  88831. SQLITE_PRIVATE KeyInfo *sqlite3KeyInfoOfIndex(Parse *pParse, Index *pIdx){
  88832. int i;
  88833. int nCol = pIdx->nColumn;
  88834. int nKey = pIdx->nKeyCol;
  88835. KeyInfo *pKey;
  88836. if( pParse->nErr ) return 0;
  88837. if( pIdx->uniqNotNull ){
  88838. pKey = sqlite3KeyInfoAlloc(pParse->db, nKey, nCol-nKey);
  88839. }else{
  88840. pKey = sqlite3KeyInfoAlloc(pParse->db, nCol, 0);
  88841. }
  88842. if( pKey ){
  88843. assert( sqlite3KeyInfoIsWriteable(pKey) );
  88844. for(i=0; i<nCol; i++){
  88845. char *zColl = pIdx->azColl[i];
  88846. assert( zColl!=0 );
  88847. pKey->aColl[i] = strcmp(zColl,"BINARY")==0 ? 0 :
  88848. sqlite3LocateCollSeq(pParse, zColl);
  88849. pKey->aSortOrder[i] = pIdx->aSortOrder[i];
  88850. }
  88851. if( pParse->nErr ){
  88852. sqlite3KeyInfoUnref(pKey);
  88853. pKey = 0;
  88854. }
  88855. }
  88856. return pKey;
  88857. }
  88858. #ifndef SQLITE_OMIT_CTE
  88859. /*
  88860. ** This routine is invoked once per CTE by the parser while parsing a
  88861. ** WITH clause.
  88862. */
  88863. SQLITE_PRIVATE With *sqlite3WithAdd(
  88864. Parse *pParse, /* Parsing context */
  88865. With *pWith, /* Existing WITH clause, or NULL */
  88866. Token *pName, /* Name of the common-table */
  88867. ExprList *pArglist, /* Optional column name list for the table */
  88868. Select *pQuery /* Query used to initialize the table */
  88869. ){
  88870. sqlite3 *db = pParse->db;
  88871. With *pNew;
  88872. char *zName;
  88873. /* Check that the CTE name is unique within this WITH clause. If
  88874. ** not, store an error in the Parse structure. */
  88875. zName = sqlite3NameFromToken(pParse->db, pName);
  88876. if( zName && pWith ){
  88877. int i;
  88878. for(i=0; i<pWith->nCte; i++){
  88879. if( sqlite3StrICmp(zName, pWith->a[i].zName)==0 ){
  88880. sqlite3ErrorMsg(pParse, "duplicate WITH table name: %s", zName);
  88881. }
  88882. }
  88883. }
  88884. if( pWith ){
  88885. int nByte = sizeof(*pWith) + (sizeof(pWith->a[1]) * pWith->nCte);
  88886. pNew = sqlite3DbRealloc(db, pWith, nByte);
  88887. }else{
  88888. pNew = sqlite3DbMallocZero(db, sizeof(*pWith));
  88889. }
  88890. assert( zName!=0 || pNew==0 );
  88891. assert( db->mallocFailed==0 || pNew==0 );
  88892. if( pNew==0 ){
  88893. sqlite3ExprListDelete(db, pArglist);
  88894. sqlite3SelectDelete(db, pQuery);
  88895. sqlite3DbFree(db, zName);
  88896. pNew = pWith;
  88897. }else{
  88898. pNew->a[pNew->nCte].pSelect = pQuery;
  88899. pNew->a[pNew->nCte].pCols = pArglist;
  88900. pNew->a[pNew->nCte].zName = zName;
  88901. pNew->a[pNew->nCte].zErr = 0;
  88902. pNew->nCte++;
  88903. }
  88904. return pNew;
  88905. }
  88906. /*
  88907. ** Free the contents of the With object passed as the second argument.
  88908. */
  88909. SQLITE_PRIVATE void sqlite3WithDelete(sqlite3 *db, With *pWith){
  88910. if( pWith ){
  88911. int i;
  88912. for(i=0; i<pWith->nCte; i++){
  88913. struct Cte *pCte = &pWith->a[i];
  88914. sqlite3ExprListDelete(db, pCte->pCols);
  88915. sqlite3SelectDelete(db, pCte->pSelect);
  88916. sqlite3DbFree(db, pCte->zName);
  88917. }
  88918. sqlite3DbFree(db, pWith);
  88919. }
  88920. }
  88921. #endif /* !defined(SQLITE_OMIT_CTE) */
  88922. /************** End of build.c ***********************************************/
  88923. /************** Begin file callback.c ****************************************/
  88924. /*
  88925. ** 2005 May 23
  88926. **
  88927. ** The author disclaims copyright to this source code. In place of
  88928. ** a legal notice, here is a blessing:
  88929. **
  88930. ** May you do good and not evil.
  88931. ** May you find forgiveness for yourself and forgive others.
  88932. ** May you share freely, never taking more than you give.
  88933. **
  88934. *************************************************************************
  88935. **
  88936. ** This file contains functions used to access the internal hash tables
  88937. ** of user defined functions and collation sequences.
  88938. */
  88939. /*
  88940. ** Invoke the 'collation needed' callback to request a collation sequence
  88941. ** in the encoding enc of name zName, length nName.
  88942. */
  88943. static void callCollNeeded(sqlite3 *db, int enc, const char *zName){
  88944. assert( !db->xCollNeeded || !db->xCollNeeded16 );
  88945. if( db->xCollNeeded ){
  88946. char *zExternal = sqlite3DbStrDup(db, zName);
  88947. if( !zExternal ) return;
  88948. db->xCollNeeded(db->pCollNeededArg, db, enc, zExternal);
  88949. sqlite3DbFree(db, zExternal);
  88950. }
  88951. #ifndef SQLITE_OMIT_UTF16
  88952. if( db->xCollNeeded16 ){
  88953. char const *zExternal;
  88954. sqlite3_value *pTmp = sqlite3ValueNew(db);
  88955. sqlite3ValueSetStr(pTmp, -1, zName, SQLITE_UTF8, SQLITE_STATIC);
  88956. zExternal = sqlite3ValueText(pTmp, SQLITE_UTF16NATIVE);
  88957. if( zExternal ){
  88958. db->xCollNeeded16(db->pCollNeededArg, db, (int)ENC(db), zExternal);
  88959. }
  88960. sqlite3ValueFree(pTmp);
  88961. }
  88962. #endif
  88963. }
  88964. /*
  88965. ** This routine is called if the collation factory fails to deliver a
  88966. ** collation function in the best encoding but there may be other versions
  88967. ** of this collation function (for other text encodings) available. Use one
  88968. ** of these instead if they exist. Avoid a UTF-8 <-> UTF-16 conversion if
  88969. ** possible.
  88970. */
  88971. static int synthCollSeq(sqlite3 *db, CollSeq *pColl){
  88972. CollSeq *pColl2;
  88973. char *z = pColl->zName;
  88974. int i;
  88975. static const u8 aEnc[] = { SQLITE_UTF16BE, SQLITE_UTF16LE, SQLITE_UTF8 };
  88976. for(i=0; i<3; i++){
  88977. pColl2 = sqlite3FindCollSeq(db, aEnc[i], z, 0);
  88978. if( pColl2->xCmp!=0 ){
  88979. memcpy(pColl, pColl2, sizeof(CollSeq));
  88980. pColl->xDel = 0; /* Do not copy the destructor */
  88981. return SQLITE_OK;
  88982. }
  88983. }
  88984. return SQLITE_ERROR;
  88985. }
  88986. /*
  88987. ** This function is responsible for invoking the collation factory callback
  88988. ** or substituting a collation sequence of a different encoding when the
  88989. ** requested collation sequence is not available in the desired encoding.
  88990. **
  88991. ** If it is not NULL, then pColl must point to the database native encoding
  88992. ** collation sequence with name zName, length nName.
  88993. **
  88994. ** The return value is either the collation sequence to be used in database
  88995. ** db for collation type name zName, length nName, or NULL, if no collation
  88996. ** sequence can be found. If no collation is found, leave an error message.
  88997. **
  88998. ** See also: sqlite3LocateCollSeq(), sqlite3FindCollSeq()
  88999. */
  89000. SQLITE_PRIVATE CollSeq *sqlite3GetCollSeq(
  89001. Parse *pParse, /* Parsing context */
  89002. u8 enc, /* The desired encoding for the collating sequence */
  89003. CollSeq *pColl, /* Collating sequence with native encoding, or NULL */
  89004. const char *zName /* Collating sequence name */
  89005. ){
  89006. CollSeq *p;
  89007. sqlite3 *db = pParse->db;
  89008. p = pColl;
  89009. if( !p ){
  89010. p = sqlite3FindCollSeq(db, enc, zName, 0);
  89011. }
  89012. if( !p || !p->xCmp ){
  89013. /* No collation sequence of this type for this encoding is registered.
  89014. ** Call the collation factory to see if it can supply us with one.
  89015. */
  89016. callCollNeeded(db, enc, zName);
  89017. p = sqlite3FindCollSeq(db, enc, zName, 0);
  89018. }
  89019. if( p && !p->xCmp && synthCollSeq(db, p) ){
  89020. p = 0;
  89021. }
  89022. assert( !p || p->xCmp );
  89023. if( p==0 ){
  89024. sqlite3ErrorMsg(pParse, "no such collation sequence: %s", zName);
  89025. }
  89026. return p;
  89027. }
  89028. /*
  89029. ** This routine is called on a collation sequence before it is used to
  89030. ** check that it is defined. An undefined collation sequence exists when
  89031. ** a database is loaded that contains references to collation sequences
  89032. ** that have not been defined by sqlite3_create_collation() etc.
  89033. **
  89034. ** If required, this routine calls the 'collation needed' callback to
  89035. ** request a definition of the collating sequence. If this doesn't work,
  89036. ** an equivalent collating sequence that uses a text encoding different
  89037. ** from the main database is substituted, if one is available.
  89038. */
  89039. SQLITE_PRIVATE int sqlite3CheckCollSeq(Parse *pParse, CollSeq *pColl){
  89040. if( pColl ){
  89041. const char *zName = pColl->zName;
  89042. sqlite3 *db = pParse->db;
  89043. CollSeq *p = sqlite3GetCollSeq(pParse, ENC(db), pColl, zName);
  89044. if( !p ){
  89045. return SQLITE_ERROR;
  89046. }
  89047. assert( p==pColl );
  89048. }
  89049. return SQLITE_OK;
  89050. }
  89051. /*
  89052. ** Locate and return an entry from the db.aCollSeq hash table. If the entry
  89053. ** specified by zName and nName is not found and parameter 'create' is
  89054. ** true, then create a new entry. Otherwise return NULL.
  89055. **
  89056. ** Each pointer stored in the sqlite3.aCollSeq hash table contains an
  89057. ** array of three CollSeq structures. The first is the collation sequence
  89058. ** preferred for UTF-8, the second UTF-16le, and the third UTF-16be.
  89059. **
  89060. ** Stored immediately after the three collation sequences is a copy of
  89061. ** the collation sequence name. A pointer to this string is stored in
  89062. ** each collation sequence structure.
  89063. */
  89064. static CollSeq *findCollSeqEntry(
  89065. sqlite3 *db, /* Database connection */
  89066. const char *zName, /* Name of the collating sequence */
  89067. int create /* Create a new entry if true */
  89068. ){
  89069. CollSeq *pColl;
  89070. pColl = sqlite3HashFind(&db->aCollSeq, zName);
  89071. if( 0==pColl && create ){
  89072. int nName = sqlite3Strlen30(zName);
  89073. pColl = sqlite3DbMallocZero(db, 3*sizeof(*pColl) + nName + 1);
  89074. if( pColl ){
  89075. CollSeq *pDel = 0;
  89076. pColl[0].zName = (char*)&pColl[3];
  89077. pColl[0].enc = SQLITE_UTF8;
  89078. pColl[1].zName = (char*)&pColl[3];
  89079. pColl[1].enc = SQLITE_UTF16LE;
  89080. pColl[2].zName = (char*)&pColl[3];
  89081. pColl[2].enc = SQLITE_UTF16BE;
  89082. memcpy(pColl[0].zName, zName, nName);
  89083. pColl[0].zName[nName] = 0;
  89084. pDel = sqlite3HashInsert(&db->aCollSeq, pColl[0].zName, pColl);
  89085. /* If a malloc() failure occurred in sqlite3HashInsert(), it will
  89086. ** return the pColl pointer to be deleted (because it wasn't added
  89087. ** to the hash table).
  89088. */
  89089. assert( pDel==0 || pDel==pColl );
  89090. if( pDel!=0 ){
  89091. db->mallocFailed = 1;
  89092. sqlite3DbFree(db, pDel);
  89093. pColl = 0;
  89094. }
  89095. }
  89096. }
  89097. return pColl;
  89098. }
  89099. /*
  89100. ** Parameter zName points to a UTF-8 encoded string nName bytes long.
  89101. ** Return the CollSeq* pointer for the collation sequence named zName
  89102. ** for the encoding 'enc' from the database 'db'.
  89103. **
  89104. ** If the entry specified is not found and 'create' is true, then create a
  89105. ** new entry. Otherwise return NULL.
  89106. **
  89107. ** A separate function sqlite3LocateCollSeq() is a wrapper around
  89108. ** this routine. sqlite3LocateCollSeq() invokes the collation factory
  89109. ** if necessary and generates an error message if the collating sequence
  89110. ** cannot be found.
  89111. **
  89112. ** See also: sqlite3LocateCollSeq(), sqlite3GetCollSeq()
  89113. */
  89114. SQLITE_PRIVATE CollSeq *sqlite3FindCollSeq(
  89115. sqlite3 *db,
  89116. u8 enc,
  89117. const char *zName,
  89118. int create
  89119. ){
  89120. CollSeq *pColl;
  89121. if( zName ){
  89122. pColl = findCollSeqEntry(db, zName, create);
  89123. }else{
  89124. pColl = db->pDfltColl;
  89125. }
  89126. assert( SQLITE_UTF8==1 && SQLITE_UTF16LE==2 && SQLITE_UTF16BE==3 );
  89127. assert( enc>=SQLITE_UTF8 && enc<=SQLITE_UTF16BE );
  89128. if( pColl ) pColl += enc-1;
  89129. return pColl;
  89130. }
  89131. /* During the search for the best function definition, this procedure
  89132. ** is called to test how well the function passed as the first argument
  89133. ** matches the request for a function with nArg arguments in a system
  89134. ** that uses encoding enc. The value returned indicates how well the
  89135. ** request is matched. A higher value indicates a better match.
  89136. **
  89137. ** If nArg is -1 that means to only return a match (non-zero) if p->nArg
  89138. ** is also -1. In other words, we are searching for a function that
  89139. ** takes a variable number of arguments.
  89140. **
  89141. ** If nArg is -2 that means that we are searching for any function
  89142. ** regardless of the number of arguments it uses, so return a positive
  89143. ** match score for any
  89144. **
  89145. ** The returned value is always between 0 and 6, as follows:
  89146. **
  89147. ** 0: Not a match.
  89148. ** 1: UTF8/16 conversion required and function takes any number of arguments.
  89149. ** 2: UTF16 byte order change required and function takes any number of args.
  89150. ** 3: encoding matches and function takes any number of arguments
  89151. ** 4: UTF8/16 conversion required - argument count matches exactly
  89152. ** 5: UTF16 byte order conversion required - argument count matches exactly
  89153. ** 6: Perfect match: encoding and argument count match exactly.
  89154. **
  89155. ** If nArg==(-2) then any function with a non-null xStep or xFunc is
  89156. ** a perfect match and any function with both xStep and xFunc NULL is
  89157. ** a non-match.
  89158. */
  89159. #define FUNC_PERFECT_MATCH 6 /* The score for a perfect match */
  89160. static int matchQuality(
  89161. FuncDef *p, /* The function we are evaluating for match quality */
  89162. int nArg, /* Desired number of arguments. (-1)==any */
  89163. u8 enc /* Desired text encoding */
  89164. ){
  89165. int match;
  89166. /* nArg of -2 is a special case */
  89167. if( nArg==(-2) ) return (p->xFunc==0 && p->xStep==0) ? 0 : FUNC_PERFECT_MATCH;
  89168. /* Wrong number of arguments means "no match" */
  89169. if( p->nArg!=nArg && p->nArg>=0 ) return 0;
  89170. /* Give a better score to a function with a specific number of arguments
  89171. ** than to function that accepts any number of arguments. */
  89172. if( p->nArg==nArg ){
  89173. match = 4;
  89174. }else{
  89175. match = 1;
  89176. }
  89177. /* Bonus points if the text encoding matches */
  89178. if( enc==(p->funcFlags & SQLITE_FUNC_ENCMASK) ){
  89179. match += 2; /* Exact encoding match */
  89180. }else if( (enc & p->funcFlags & 2)!=0 ){
  89181. match += 1; /* Both are UTF16, but with different byte orders */
  89182. }
  89183. return match;
  89184. }
  89185. /*
  89186. ** Search a FuncDefHash for a function with the given name. Return
  89187. ** a pointer to the matching FuncDef if found, or 0 if there is no match.
  89188. */
  89189. static FuncDef *functionSearch(
  89190. FuncDefHash *pHash, /* Hash table to search */
  89191. int h, /* Hash of the name */
  89192. const char *zFunc, /* Name of function */
  89193. int nFunc /* Number of bytes in zFunc */
  89194. ){
  89195. FuncDef *p;
  89196. for(p=pHash->a[h]; p; p=p->pHash){
  89197. if( sqlite3StrNICmp(p->zName, zFunc, nFunc)==0 && p->zName[nFunc]==0 ){
  89198. return p;
  89199. }
  89200. }
  89201. return 0;
  89202. }
  89203. /*
  89204. ** Insert a new FuncDef into a FuncDefHash hash table.
  89205. */
  89206. SQLITE_PRIVATE void sqlite3FuncDefInsert(
  89207. FuncDefHash *pHash, /* The hash table into which to insert */
  89208. FuncDef *pDef /* The function definition to insert */
  89209. ){
  89210. FuncDef *pOther;
  89211. int nName = sqlite3Strlen30(pDef->zName);
  89212. u8 c1 = (u8)pDef->zName[0];
  89213. int h = (sqlite3UpperToLower[c1] + nName) % ArraySize(pHash->a);
  89214. pOther = functionSearch(pHash, h, pDef->zName, nName);
  89215. if( pOther ){
  89216. assert( pOther!=pDef && pOther->pNext!=pDef );
  89217. pDef->pNext = pOther->pNext;
  89218. pOther->pNext = pDef;
  89219. }else{
  89220. pDef->pNext = 0;
  89221. pDef->pHash = pHash->a[h];
  89222. pHash->a[h] = pDef;
  89223. }
  89224. }
  89225. /*
  89226. ** Locate a user function given a name, a number of arguments and a flag
  89227. ** indicating whether the function prefers UTF-16 over UTF-8. Return a
  89228. ** pointer to the FuncDef structure that defines that function, or return
  89229. ** NULL if the function does not exist.
  89230. **
  89231. ** If the createFlag argument is true, then a new (blank) FuncDef
  89232. ** structure is created and liked into the "db" structure if a
  89233. ** no matching function previously existed.
  89234. **
  89235. ** If nArg is -2, then the first valid function found is returned. A
  89236. ** function is valid if either xFunc or xStep is non-zero. The nArg==(-2)
  89237. ** case is used to see if zName is a valid function name for some number
  89238. ** of arguments. If nArg is -2, then createFlag must be 0.
  89239. **
  89240. ** If createFlag is false, then a function with the required name and
  89241. ** number of arguments may be returned even if the eTextRep flag does not
  89242. ** match that requested.
  89243. */
  89244. SQLITE_PRIVATE FuncDef *sqlite3FindFunction(
  89245. sqlite3 *db, /* An open database */
  89246. const char *zName, /* Name of the function. Not null-terminated */
  89247. int nName, /* Number of characters in the name */
  89248. int nArg, /* Number of arguments. -1 means any number */
  89249. u8 enc, /* Preferred text encoding */
  89250. u8 createFlag /* Create new entry if true and does not otherwise exist */
  89251. ){
  89252. FuncDef *p; /* Iterator variable */
  89253. FuncDef *pBest = 0; /* Best match found so far */
  89254. int bestScore = 0; /* Score of best match */
  89255. int h; /* Hash value */
  89256. assert( nArg>=(-2) );
  89257. assert( nArg>=(-1) || createFlag==0 );
  89258. h = (sqlite3UpperToLower[(u8)zName[0]] + nName) % ArraySize(db->aFunc.a);
  89259. /* First search for a match amongst the application-defined functions.
  89260. */
  89261. p = functionSearch(&db->aFunc, h, zName, nName);
  89262. while( p ){
  89263. int score = matchQuality(p, nArg, enc);
  89264. if( score>bestScore ){
  89265. pBest = p;
  89266. bestScore = score;
  89267. }
  89268. p = p->pNext;
  89269. }
  89270. /* If no match is found, search the built-in functions.
  89271. **
  89272. ** If the SQLITE_PreferBuiltin flag is set, then search the built-in
  89273. ** functions even if a prior app-defined function was found. And give
  89274. ** priority to built-in functions.
  89275. **
  89276. ** Except, if createFlag is true, that means that we are trying to
  89277. ** install a new function. Whatever FuncDef structure is returned it will
  89278. ** have fields overwritten with new information appropriate for the
  89279. ** new function. But the FuncDefs for built-in functions are read-only.
  89280. ** So we must not search for built-ins when creating a new function.
  89281. */
  89282. if( !createFlag && (pBest==0 || (db->flags & SQLITE_PreferBuiltin)!=0) ){
  89283. FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
  89284. bestScore = 0;
  89285. p = functionSearch(pHash, h, zName, nName);
  89286. while( p ){
  89287. int score = matchQuality(p, nArg, enc);
  89288. if( score>bestScore ){
  89289. pBest = p;
  89290. bestScore = score;
  89291. }
  89292. p = p->pNext;
  89293. }
  89294. }
  89295. /* If the createFlag parameter is true and the search did not reveal an
  89296. ** exact match for the name, number of arguments and encoding, then add a
  89297. ** new entry to the hash table and return it.
  89298. */
  89299. if( createFlag && bestScore<FUNC_PERFECT_MATCH &&
  89300. (pBest = sqlite3DbMallocZero(db, sizeof(*pBest)+nName+1))!=0 ){
  89301. pBest->zName = (char *)&pBest[1];
  89302. pBest->nArg = (u16)nArg;
  89303. pBest->funcFlags = enc;
  89304. memcpy(pBest->zName, zName, nName);
  89305. pBest->zName[nName] = 0;
  89306. sqlite3FuncDefInsert(&db->aFunc, pBest);
  89307. }
  89308. if( pBest && (pBest->xStep || pBest->xFunc || createFlag) ){
  89309. return pBest;
  89310. }
  89311. return 0;
  89312. }
  89313. /*
  89314. ** Free all resources held by the schema structure. The void* argument points
  89315. ** at a Schema struct. This function does not call sqlite3DbFree(db, ) on the
  89316. ** pointer itself, it just cleans up subsidiary resources (i.e. the contents
  89317. ** of the schema hash tables).
  89318. **
  89319. ** The Schema.cache_size variable is not cleared.
  89320. */
  89321. SQLITE_PRIVATE void sqlite3SchemaClear(void *p){
  89322. Hash temp1;
  89323. Hash temp2;
  89324. HashElem *pElem;
  89325. Schema *pSchema = (Schema *)p;
  89326. temp1 = pSchema->tblHash;
  89327. temp2 = pSchema->trigHash;
  89328. sqlite3HashInit(&pSchema->trigHash);
  89329. sqlite3HashClear(&pSchema->idxHash);
  89330. for(pElem=sqliteHashFirst(&temp2); pElem; pElem=sqliteHashNext(pElem)){
  89331. sqlite3DeleteTrigger(0, (Trigger*)sqliteHashData(pElem));
  89332. }
  89333. sqlite3HashClear(&temp2);
  89334. sqlite3HashInit(&pSchema->tblHash);
  89335. for(pElem=sqliteHashFirst(&temp1); pElem; pElem=sqliteHashNext(pElem)){
  89336. Table *pTab = sqliteHashData(pElem);
  89337. sqlite3DeleteTable(0, pTab);
  89338. }
  89339. sqlite3HashClear(&temp1);
  89340. sqlite3HashClear(&pSchema->fkeyHash);
  89341. pSchema->pSeqTab = 0;
  89342. if( pSchema->schemaFlags & DB_SchemaLoaded ){
  89343. pSchema->iGeneration++;
  89344. pSchema->schemaFlags &= ~DB_SchemaLoaded;
  89345. }
  89346. }
  89347. /*
  89348. ** Find and return the schema associated with a BTree. Create
  89349. ** a new one if necessary.
  89350. */
  89351. SQLITE_PRIVATE Schema *sqlite3SchemaGet(sqlite3 *db, Btree *pBt){
  89352. Schema * p;
  89353. if( pBt ){
  89354. p = (Schema *)sqlite3BtreeSchema(pBt, sizeof(Schema), sqlite3SchemaClear);
  89355. }else{
  89356. p = (Schema *)sqlite3DbMallocZero(0, sizeof(Schema));
  89357. }
  89358. if( !p ){
  89359. db->mallocFailed = 1;
  89360. }else if ( 0==p->file_format ){
  89361. sqlite3HashInit(&p->tblHash);
  89362. sqlite3HashInit(&p->idxHash);
  89363. sqlite3HashInit(&p->trigHash);
  89364. sqlite3HashInit(&p->fkeyHash);
  89365. p->enc = SQLITE_UTF8;
  89366. }
  89367. return p;
  89368. }
  89369. /************** End of callback.c ********************************************/
  89370. /************** Begin file delete.c ******************************************/
  89371. /*
  89372. ** 2001 September 15
  89373. **
  89374. ** The author disclaims copyright to this source code. In place of
  89375. ** a legal notice, here is a blessing:
  89376. **
  89377. ** May you do good and not evil.
  89378. ** May you find forgiveness for yourself and forgive others.
  89379. ** May you share freely, never taking more than you give.
  89380. **
  89381. *************************************************************************
  89382. ** This file contains C code routines that are called by the parser
  89383. ** in order to generate code for DELETE FROM statements.
  89384. */
  89385. /*
  89386. ** While a SrcList can in general represent multiple tables and subqueries
  89387. ** (as in the FROM clause of a SELECT statement) in this case it contains
  89388. ** the name of a single table, as one might find in an INSERT, DELETE,
  89389. ** or UPDATE statement. Look up that table in the symbol table and
  89390. ** return a pointer. Set an error message and return NULL if the table
  89391. ** name is not found or if any other error occurs.
  89392. **
  89393. ** The following fields are initialized appropriate in pSrc:
  89394. **
  89395. ** pSrc->a[0].pTab Pointer to the Table object
  89396. ** pSrc->a[0].pIndex Pointer to the INDEXED BY index, if there is one
  89397. **
  89398. */
  89399. SQLITE_PRIVATE Table *sqlite3SrcListLookup(Parse *pParse, SrcList *pSrc){
  89400. struct SrcList_item *pItem = pSrc->a;
  89401. Table *pTab;
  89402. assert( pItem && pSrc->nSrc==1 );
  89403. pTab = sqlite3LocateTableItem(pParse, 0, pItem);
  89404. sqlite3DeleteTable(pParse->db, pItem->pTab);
  89405. pItem->pTab = pTab;
  89406. if( pTab ){
  89407. pTab->nRef++;
  89408. }
  89409. if( sqlite3IndexedByLookup(pParse, pItem) ){
  89410. pTab = 0;
  89411. }
  89412. return pTab;
  89413. }
  89414. /*
  89415. ** Check to make sure the given table is writable. If it is not
  89416. ** writable, generate an error message and return 1. If it is
  89417. ** writable return 0;
  89418. */
  89419. SQLITE_PRIVATE int sqlite3IsReadOnly(Parse *pParse, Table *pTab, int viewOk){
  89420. /* A table is not writable under the following circumstances:
  89421. **
  89422. ** 1) It is a virtual table and no implementation of the xUpdate method
  89423. ** has been provided, or
  89424. ** 2) It is a system table (i.e. sqlite_master), this call is not
  89425. ** part of a nested parse and writable_schema pragma has not
  89426. ** been specified.
  89427. **
  89428. ** In either case leave an error message in pParse and return non-zero.
  89429. */
  89430. if( ( IsVirtual(pTab)
  89431. && sqlite3GetVTable(pParse->db, pTab)->pMod->pModule->xUpdate==0 )
  89432. || ( (pTab->tabFlags & TF_Readonly)!=0
  89433. && (pParse->db->flags & SQLITE_WriteSchema)==0
  89434. && pParse->nested==0 )
  89435. ){
  89436. sqlite3ErrorMsg(pParse, "table %s may not be modified", pTab->zName);
  89437. return 1;
  89438. }
  89439. #ifndef SQLITE_OMIT_VIEW
  89440. if( !viewOk && pTab->pSelect ){
  89441. sqlite3ErrorMsg(pParse,"cannot modify %s because it is a view",pTab->zName);
  89442. return 1;
  89443. }
  89444. #endif
  89445. return 0;
  89446. }
  89447. #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
  89448. /*
  89449. ** Evaluate a view and store its result in an ephemeral table. The
  89450. ** pWhere argument is an optional WHERE clause that restricts the
  89451. ** set of rows in the view that are to be added to the ephemeral table.
  89452. */
  89453. SQLITE_PRIVATE void sqlite3MaterializeView(
  89454. Parse *pParse, /* Parsing context */
  89455. Table *pView, /* View definition */
  89456. Expr *pWhere, /* Optional WHERE clause to be added */
  89457. int iCur /* Cursor number for ephemeral table */
  89458. ){
  89459. SelectDest dest;
  89460. Select *pSel;
  89461. SrcList *pFrom;
  89462. sqlite3 *db = pParse->db;
  89463. int iDb = sqlite3SchemaToIndex(db, pView->pSchema);
  89464. pWhere = sqlite3ExprDup(db, pWhere, 0);
  89465. pFrom = sqlite3SrcListAppend(db, 0, 0, 0);
  89466. if( pFrom ){
  89467. assert( pFrom->nSrc==1 );
  89468. pFrom->a[0].zName = sqlite3DbStrDup(db, pView->zName);
  89469. pFrom->a[0].zDatabase = sqlite3DbStrDup(db, db->aDb[iDb].zName);
  89470. assert( pFrom->a[0].pOn==0 );
  89471. assert( pFrom->a[0].pUsing==0 );
  89472. }
  89473. pSel = sqlite3SelectNew(pParse, 0, pFrom, pWhere, 0, 0, 0, 0, 0, 0);
  89474. sqlite3SelectDestInit(&dest, SRT_EphemTab, iCur);
  89475. sqlite3Select(pParse, pSel, &dest);
  89476. sqlite3SelectDelete(db, pSel);
  89477. }
  89478. #endif /* !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER) */
  89479. #if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)
  89480. /*
  89481. ** Generate an expression tree to implement the WHERE, ORDER BY,
  89482. ** and LIMIT/OFFSET portion of DELETE and UPDATE statements.
  89483. **
  89484. ** DELETE FROM table_wxyz WHERE a<5 ORDER BY a LIMIT 1;
  89485. ** \__________________________/
  89486. ** pLimitWhere (pInClause)
  89487. */
  89488. SQLITE_PRIVATE Expr *sqlite3LimitWhere(
  89489. Parse *pParse, /* The parser context */
  89490. SrcList *pSrc, /* the FROM clause -- which tables to scan */
  89491. Expr *pWhere, /* The WHERE clause. May be null */
  89492. ExprList *pOrderBy, /* The ORDER BY clause. May be null */
  89493. Expr *pLimit, /* The LIMIT clause. May be null */
  89494. Expr *pOffset, /* The OFFSET clause. May be null */
  89495. char *zStmtType /* Either DELETE or UPDATE. For err msgs. */
  89496. ){
  89497. Expr *pWhereRowid = NULL; /* WHERE rowid .. */
  89498. Expr *pInClause = NULL; /* WHERE rowid IN ( select ) */
  89499. Expr *pSelectRowid = NULL; /* SELECT rowid ... */
  89500. ExprList *pEList = NULL; /* Expression list contaning only pSelectRowid */
  89501. SrcList *pSelectSrc = NULL; /* SELECT rowid FROM x ... (dup of pSrc) */
  89502. Select *pSelect = NULL; /* Complete SELECT tree */
  89503. /* Check that there isn't an ORDER BY without a LIMIT clause.
  89504. */
  89505. if( pOrderBy && (pLimit == 0) ) {
  89506. sqlite3ErrorMsg(pParse, "ORDER BY without LIMIT on %s", zStmtType);
  89507. goto limit_where_cleanup_2;
  89508. }
  89509. /* We only need to generate a select expression if there
  89510. ** is a limit/offset term to enforce.
  89511. */
  89512. if( pLimit == 0 ) {
  89513. /* if pLimit is null, pOffset will always be null as well. */
  89514. assert( pOffset == 0 );
  89515. return pWhere;
  89516. }
  89517. /* Generate a select expression tree to enforce the limit/offset
  89518. ** term for the DELETE or UPDATE statement. For example:
  89519. ** DELETE FROM table_a WHERE col1=1 ORDER BY col2 LIMIT 1 OFFSET 1
  89520. ** becomes:
  89521. ** DELETE FROM table_a WHERE rowid IN (
  89522. ** SELECT rowid FROM table_a WHERE col1=1 ORDER BY col2 LIMIT 1 OFFSET 1
  89523. ** );
  89524. */
  89525. pSelectRowid = sqlite3PExpr(pParse, TK_ROW, 0, 0, 0);
  89526. if( pSelectRowid == 0 ) goto limit_where_cleanup_2;
  89527. pEList = sqlite3ExprListAppend(pParse, 0, pSelectRowid);
  89528. if( pEList == 0 ) goto limit_where_cleanup_2;
  89529. /* duplicate the FROM clause as it is needed by both the DELETE/UPDATE tree
  89530. ** and the SELECT subtree. */
  89531. pSelectSrc = sqlite3SrcListDup(pParse->db, pSrc, 0);
  89532. if( pSelectSrc == 0 ) {
  89533. sqlite3ExprListDelete(pParse->db, pEList);
  89534. goto limit_where_cleanup_2;
  89535. }
  89536. /* generate the SELECT expression tree. */
  89537. pSelect = sqlite3SelectNew(pParse,pEList,pSelectSrc,pWhere,0,0,
  89538. pOrderBy,0,pLimit,pOffset);
  89539. if( pSelect == 0 ) return 0;
  89540. /* now generate the new WHERE rowid IN clause for the DELETE/UDPATE */
  89541. pWhereRowid = sqlite3PExpr(pParse, TK_ROW, 0, 0, 0);
  89542. if( pWhereRowid == 0 ) goto limit_where_cleanup_1;
  89543. pInClause = sqlite3PExpr(pParse, TK_IN, pWhereRowid, 0, 0);
  89544. if( pInClause == 0 ) goto limit_where_cleanup_1;
  89545. pInClause->x.pSelect = pSelect;
  89546. pInClause->flags |= EP_xIsSelect;
  89547. sqlite3ExprSetHeightAndFlags(pParse, pInClause);
  89548. return pInClause;
  89549. /* something went wrong. clean up anything allocated. */
  89550. limit_where_cleanup_1:
  89551. sqlite3SelectDelete(pParse->db, pSelect);
  89552. return 0;
  89553. limit_where_cleanup_2:
  89554. sqlite3ExprDelete(pParse->db, pWhere);
  89555. sqlite3ExprListDelete(pParse->db, pOrderBy);
  89556. sqlite3ExprDelete(pParse->db, pLimit);
  89557. sqlite3ExprDelete(pParse->db, pOffset);
  89558. return 0;
  89559. }
  89560. #endif /* defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) */
  89561. /* && !defined(SQLITE_OMIT_SUBQUERY) */
  89562. /*
  89563. ** Generate code for a DELETE FROM statement.
  89564. **
  89565. ** DELETE FROM table_wxyz WHERE a<5 AND b NOT NULL;
  89566. ** \________/ \________________/
  89567. ** pTabList pWhere
  89568. */
  89569. SQLITE_PRIVATE void sqlite3DeleteFrom(
  89570. Parse *pParse, /* The parser context */
  89571. SrcList *pTabList, /* The table from which we should delete things */
  89572. Expr *pWhere /* The WHERE clause. May be null */
  89573. ){
  89574. Vdbe *v; /* The virtual database engine */
  89575. Table *pTab; /* The table from which records will be deleted */
  89576. const char *zDb; /* Name of database holding pTab */
  89577. int i; /* Loop counter */
  89578. WhereInfo *pWInfo; /* Information about the WHERE clause */
  89579. Index *pIdx; /* For looping over indices of the table */
  89580. int iTabCur; /* Cursor number for the table */
  89581. int iDataCur = 0; /* VDBE cursor for the canonical data source */
  89582. int iIdxCur = 0; /* Cursor number of the first index */
  89583. int nIdx; /* Number of indices */
  89584. sqlite3 *db; /* Main database structure */
  89585. AuthContext sContext; /* Authorization context */
  89586. NameContext sNC; /* Name context to resolve expressions in */
  89587. int iDb; /* Database number */
  89588. int memCnt = -1; /* Memory cell used for change counting */
  89589. int rcauth; /* Value returned by authorization callback */
  89590. int okOnePass; /* True for one-pass algorithm without the FIFO */
  89591. int aiCurOnePass[2]; /* The write cursors opened by WHERE_ONEPASS */
  89592. u8 *aToOpen = 0; /* Open cursor iTabCur+j if aToOpen[j] is true */
  89593. Index *pPk; /* The PRIMARY KEY index on the table */
  89594. int iPk = 0; /* First of nPk registers holding PRIMARY KEY value */
  89595. i16 nPk = 1; /* Number of columns in the PRIMARY KEY */
  89596. int iKey; /* Memory cell holding key of row to be deleted */
  89597. i16 nKey; /* Number of memory cells in the row key */
  89598. int iEphCur = 0; /* Ephemeral table holding all primary key values */
  89599. int iRowSet = 0; /* Register for rowset of rows to delete */
  89600. int addrBypass = 0; /* Address of jump over the delete logic */
  89601. int addrLoop = 0; /* Top of the delete loop */
  89602. int addrDelete = 0; /* Jump directly to the delete logic */
  89603. int addrEphOpen = 0; /* Instruction to open the Ephemeral table */
  89604. #ifndef SQLITE_OMIT_TRIGGER
  89605. int isView; /* True if attempting to delete from a view */
  89606. Trigger *pTrigger; /* List of table triggers, if required */
  89607. #endif
  89608. memset(&sContext, 0, sizeof(sContext));
  89609. db = pParse->db;
  89610. if( pParse->nErr || db->mallocFailed ){
  89611. goto delete_from_cleanup;
  89612. }
  89613. assert( pTabList->nSrc==1 );
  89614. /* Locate the table which we want to delete. This table has to be
  89615. ** put in an SrcList structure because some of the subroutines we
  89616. ** will be calling are designed to work with multiple tables and expect
  89617. ** an SrcList* parameter instead of just a Table* parameter.
  89618. */
  89619. pTab = sqlite3SrcListLookup(pParse, pTabList);
  89620. if( pTab==0 ) goto delete_from_cleanup;
  89621. /* Figure out if we have any triggers and if the table being
  89622. ** deleted from is a view
  89623. */
  89624. #ifndef SQLITE_OMIT_TRIGGER
  89625. pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
  89626. isView = pTab->pSelect!=0;
  89627. #else
  89628. # define pTrigger 0
  89629. # define isView 0
  89630. #endif
  89631. #ifdef SQLITE_OMIT_VIEW
  89632. # undef isView
  89633. # define isView 0
  89634. #endif
  89635. /* If pTab is really a view, make sure it has been initialized.
  89636. */
  89637. if( sqlite3ViewGetColumnNames(pParse, pTab) ){
  89638. goto delete_from_cleanup;
  89639. }
  89640. if( sqlite3IsReadOnly(pParse, pTab, (pTrigger?1:0)) ){
  89641. goto delete_from_cleanup;
  89642. }
  89643. iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  89644. assert( iDb<db->nDb );
  89645. zDb = db->aDb[iDb].zName;
  89646. rcauth = sqlite3AuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0, zDb);
  89647. assert( rcauth==SQLITE_OK || rcauth==SQLITE_DENY || rcauth==SQLITE_IGNORE );
  89648. if( rcauth==SQLITE_DENY ){
  89649. goto delete_from_cleanup;
  89650. }
  89651. assert(!isView || pTrigger);
  89652. /* Assign cursor numbers to the table and all its indices.
  89653. */
  89654. assert( pTabList->nSrc==1 );
  89655. iTabCur = pTabList->a[0].iCursor = pParse->nTab++;
  89656. for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){
  89657. pParse->nTab++;
  89658. }
  89659. /* Start the view context
  89660. */
  89661. if( isView ){
  89662. sqlite3AuthContextPush(pParse, &sContext, pTab->zName);
  89663. }
  89664. /* Begin generating code.
  89665. */
  89666. v = sqlite3GetVdbe(pParse);
  89667. if( v==0 ){
  89668. goto delete_from_cleanup;
  89669. }
  89670. if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
  89671. sqlite3BeginWriteOperation(pParse, 1, iDb);
  89672. /* If we are trying to delete from a view, realize that view into
  89673. ** an ephemeral table.
  89674. */
  89675. #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
  89676. if( isView ){
  89677. sqlite3MaterializeView(pParse, pTab, pWhere, iTabCur);
  89678. iDataCur = iIdxCur = iTabCur;
  89679. }
  89680. #endif
  89681. /* Resolve the column names in the WHERE clause.
  89682. */
  89683. memset(&sNC, 0, sizeof(sNC));
  89684. sNC.pParse = pParse;
  89685. sNC.pSrcList = pTabList;
  89686. if( sqlite3ResolveExprNames(&sNC, pWhere) ){
  89687. goto delete_from_cleanup;
  89688. }
  89689. /* Initialize the counter of the number of rows deleted, if
  89690. ** we are counting rows.
  89691. */
  89692. if( db->flags & SQLITE_CountRows ){
  89693. memCnt = ++pParse->nMem;
  89694. sqlite3VdbeAddOp2(v, OP_Integer, 0, memCnt);
  89695. }
  89696. #ifndef SQLITE_OMIT_TRUNCATE_OPTIMIZATION
  89697. /* Special case: A DELETE without a WHERE clause deletes everything.
  89698. ** It is easier just to erase the whole table. Prior to version 3.6.5,
  89699. ** this optimization caused the row change count (the value returned by
  89700. ** API function sqlite3_count_changes) to be set incorrectly. */
  89701. if( rcauth==SQLITE_OK && pWhere==0 && !pTrigger && !IsVirtual(pTab)
  89702. && 0==sqlite3FkRequired(pParse, pTab, 0, 0)
  89703. ){
  89704. assert( !isView );
  89705. sqlite3TableLock(pParse, iDb, pTab->tnum, 1, pTab->zName);
  89706. if( HasRowid(pTab) ){
  89707. sqlite3VdbeAddOp4(v, OP_Clear, pTab->tnum, iDb, memCnt,
  89708. pTab->zName, P4_STATIC);
  89709. }
  89710. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  89711. assert( pIdx->pSchema==pTab->pSchema );
  89712. sqlite3VdbeAddOp2(v, OP_Clear, pIdx->tnum, iDb);
  89713. }
  89714. }else
  89715. #endif /* SQLITE_OMIT_TRUNCATE_OPTIMIZATION */
  89716. {
  89717. if( HasRowid(pTab) ){
  89718. /* For a rowid table, initialize the RowSet to an empty set */
  89719. pPk = 0;
  89720. nPk = 1;
  89721. iRowSet = ++pParse->nMem;
  89722. sqlite3VdbeAddOp2(v, OP_Null, 0, iRowSet);
  89723. }else{
  89724. /* For a WITHOUT ROWID table, create an ephemeral table used to
  89725. ** hold all primary keys for rows to be deleted. */
  89726. pPk = sqlite3PrimaryKeyIndex(pTab);
  89727. assert( pPk!=0 );
  89728. nPk = pPk->nKeyCol;
  89729. iPk = pParse->nMem+1;
  89730. pParse->nMem += nPk;
  89731. iEphCur = pParse->nTab++;
  89732. addrEphOpen = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, iEphCur, nPk);
  89733. sqlite3VdbeSetP4KeyInfo(pParse, pPk);
  89734. }
  89735. /* Construct a query to find the rowid or primary key for every row
  89736. ** to be deleted, based on the WHERE clause.
  89737. */
  89738. pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, 0, 0,
  89739. WHERE_ONEPASS_DESIRED|WHERE_DUPLICATES_OK,
  89740. iTabCur+1);
  89741. if( pWInfo==0 ) goto delete_from_cleanup;
  89742. okOnePass = sqlite3WhereOkOnePass(pWInfo, aiCurOnePass);
  89743. /* Keep track of the number of rows to be deleted */
  89744. if( db->flags & SQLITE_CountRows ){
  89745. sqlite3VdbeAddOp2(v, OP_AddImm, memCnt, 1);
  89746. }
  89747. /* Extract the rowid or primary key for the current row */
  89748. if( pPk ){
  89749. for(i=0; i<nPk; i++){
  89750. sqlite3ExprCodeGetColumnOfTable(v, pTab, iTabCur,
  89751. pPk->aiColumn[i], iPk+i);
  89752. }
  89753. iKey = iPk;
  89754. }else{
  89755. iKey = pParse->nMem + 1;
  89756. iKey = sqlite3ExprCodeGetColumn(pParse, pTab, -1, iTabCur, iKey, 0);
  89757. if( iKey>pParse->nMem ) pParse->nMem = iKey;
  89758. }
  89759. if( okOnePass ){
  89760. /* For ONEPASS, no need to store the rowid/primary-key. There is only
  89761. ** one, so just keep it in its register(s) and fall through to the
  89762. ** delete code.
  89763. */
  89764. nKey = nPk; /* OP_Found will use an unpacked key */
  89765. aToOpen = sqlite3DbMallocRaw(db, nIdx+2);
  89766. if( aToOpen==0 ){
  89767. sqlite3WhereEnd(pWInfo);
  89768. goto delete_from_cleanup;
  89769. }
  89770. memset(aToOpen, 1, nIdx+1);
  89771. aToOpen[nIdx+1] = 0;
  89772. if( aiCurOnePass[0]>=0 ) aToOpen[aiCurOnePass[0]-iTabCur] = 0;
  89773. if( aiCurOnePass[1]>=0 ) aToOpen[aiCurOnePass[1]-iTabCur] = 0;
  89774. if( addrEphOpen ) sqlite3VdbeChangeToNoop(v, addrEphOpen);
  89775. addrDelete = sqlite3VdbeAddOp0(v, OP_Goto); /* Jump to DELETE logic */
  89776. }else if( pPk ){
  89777. /* Construct a composite key for the row to be deleted and remember it */
  89778. iKey = ++pParse->nMem;
  89779. nKey = 0; /* Zero tells OP_Found to use a composite key */
  89780. sqlite3VdbeAddOp4(v, OP_MakeRecord, iPk, nPk, iKey,
  89781. sqlite3IndexAffinityStr(v, pPk), nPk);
  89782. sqlite3VdbeAddOp2(v, OP_IdxInsert, iEphCur, iKey);
  89783. }else{
  89784. /* Get the rowid of the row to be deleted and remember it in the RowSet */
  89785. nKey = 1; /* OP_Seek always uses a single rowid */
  89786. sqlite3VdbeAddOp2(v, OP_RowSetAdd, iRowSet, iKey);
  89787. }
  89788. /* End of the WHERE loop */
  89789. sqlite3WhereEnd(pWInfo);
  89790. if( okOnePass ){
  89791. /* Bypass the delete logic below if the WHERE loop found zero rows */
  89792. addrBypass = sqlite3VdbeMakeLabel(v);
  89793. sqlite3VdbeAddOp2(v, OP_Goto, 0, addrBypass);
  89794. sqlite3VdbeJumpHere(v, addrDelete);
  89795. }
  89796. /* Unless this is a view, open cursors for the table we are
  89797. ** deleting from and all its indices. If this is a view, then the
  89798. ** only effect this statement has is to fire the INSTEAD OF
  89799. ** triggers.
  89800. */
  89801. if( !isView ){
  89802. testcase( IsVirtual(pTab) );
  89803. sqlite3OpenTableAndIndices(pParse, pTab, OP_OpenWrite, iTabCur, aToOpen,
  89804. &iDataCur, &iIdxCur);
  89805. assert( pPk || IsVirtual(pTab) || iDataCur==iTabCur );
  89806. assert( pPk || IsVirtual(pTab) || iIdxCur==iDataCur+1 );
  89807. }
  89808. /* Set up a loop over the rowids/primary-keys that were found in the
  89809. ** where-clause loop above.
  89810. */
  89811. if( okOnePass ){
  89812. /* Just one row. Hence the top-of-loop is a no-op */
  89813. assert( nKey==nPk ); /* OP_Found will use an unpacked key */
  89814. assert( !IsVirtual(pTab) );
  89815. if( aToOpen[iDataCur-iTabCur] ){
  89816. assert( pPk!=0 || pTab->pSelect!=0 );
  89817. sqlite3VdbeAddOp4Int(v, OP_NotFound, iDataCur, addrBypass, iKey, nKey);
  89818. VdbeCoverage(v);
  89819. }
  89820. }else if( pPk ){
  89821. addrLoop = sqlite3VdbeAddOp1(v, OP_Rewind, iEphCur); VdbeCoverage(v);
  89822. sqlite3VdbeAddOp2(v, OP_RowKey, iEphCur, iKey);
  89823. assert( nKey==0 ); /* OP_Found will use a composite key */
  89824. }else{
  89825. addrLoop = sqlite3VdbeAddOp3(v, OP_RowSetRead, iRowSet, 0, iKey);
  89826. VdbeCoverage(v);
  89827. assert( nKey==1 );
  89828. }
  89829. /* Delete the row */
  89830. #ifndef SQLITE_OMIT_VIRTUALTABLE
  89831. if( IsVirtual(pTab) ){
  89832. const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
  89833. sqlite3VtabMakeWritable(pParse, pTab);
  89834. sqlite3VdbeAddOp4(v, OP_VUpdate, 0, 1, iKey, pVTab, P4_VTAB);
  89835. sqlite3VdbeChangeP5(v, OE_Abort);
  89836. sqlite3MayAbort(pParse);
  89837. }else
  89838. #endif
  89839. {
  89840. int count = (pParse->nested==0); /* True to count changes */
  89841. sqlite3GenerateRowDelete(pParse, pTab, pTrigger, iDataCur, iIdxCur,
  89842. iKey, nKey, count, OE_Default, okOnePass);
  89843. }
  89844. /* End of the loop over all rowids/primary-keys. */
  89845. if( okOnePass ){
  89846. sqlite3VdbeResolveLabel(v, addrBypass);
  89847. }else if( pPk ){
  89848. sqlite3VdbeAddOp2(v, OP_Next, iEphCur, addrLoop+1); VdbeCoverage(v);
  89849. sqlite3VdbeJumpHere(v, addrLoop);
  89850. }else{
  89851. sqlite3VdbeAddOp2(v, OP_Goto, 0, addrLoop);
  89852. sqlite3VdbeJumpHere(v, addrLoop);
  89853. }
  89854. /* Close the cursors open on the table and its indexes. */
  89855. if( !isView && !IsVirtual(pTab) ){
  89856. if( !pPk ) sqlite3VdbeAddOp1(v, OP_Close, iDataCur);
  89857. for(i=0, pIdx=pTab->pIndex; pIdx; i++, pIdx=pIdx->pNext){
  89858. sqlite3VdbeAddOp1(v, OP_Close, iIdxCur + i);
  89859. }
  89860. }
  89861. } /* End non-truncate path */
  89862. /* Update the sqlite_sequence table by storing the content of the
  89863. ** maximum rowid counter values recorded while inserting into
  89864. ** autoincrement tables.
  89865. */
  89866. if( pParse->nested==0 && pParse->pTriggerTab==0 ){
  89867. sqlite3AutoincrementEnd(pParse);
  89868. }
  89869. /* Return the number of rows that were deleted. If this routine is
  89870. ** generating code because of a call to sqlite3NestedParse(), do not
  89871. ** invoke the callback function.
  89872. */
  89873. if( (db->flags&SQLITE_CountRows) && !pParse->nested && !pParse->pTriggerTab ){
  89874. sqlite3VdbeAddOp2(v, OP_ResultRow, memCnt, 1);
  89875. sqlite3VdbeSetNumCols(v, 1);
  89876. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows deleted", SQLITE_STATIC);
  89877. }
  89878. delete_from_cleanup:
  89879. sqlite3AuthContextPop(&sContext);
  89880. sqlite3SrcListDelete(db, pTabList);
  89881. sqlite3ExprDelete(db, pWhere);
  89882. sqlite3DbFree(db, aToOpen);
  89883. return;
  89884. }
  89885. /* Make sure "isView" and other macros defined above are undefined. Otherwise
  89886. ** they may interfere with compilation of other functions in this file
  89887. ** (or in another file, if this file becomes part of the amalgamation). */
  89888. #ifdef isView
  89889. #undef isView
  89890. #endif
  89891. #ifdef pTrigger
  89892. #undef pTrigger
  89893. #endif
  89894. /*
  89895. ** This routine generates VDBE code that causes a single row of a
  89896. ** single table to be deleted. Both the original table entry and
  89897. ** all indices are removed.
  89898. **
  89899. ** Preconditions:
  89900. **
  89901. ** 1. iDataCur is an open cursor on the btree that is the canonical data
  89902. ** store for the table. (This will be either the table itself,
  89903. ** in the case of a rowid table, or the PRIMARY KEY index in the case
  89904. ** of a WITHOUT ROWID table.)
  89905. **
  89906. ** 2. Read/write cursors for all indices of pTab must be open as
  89907. ** cursor number iIdxCur+i for the i-th index.
  89908. **
  89909. ** 3. The primary key for the row to be deleted must be stored in a
  89910. ** sequence of nPk memory cells starting at iPk. If nPk==0 that means
  89911. ** that a search record formed from OP_MakeRecord is contained in the
  89912. ** single memory location iPk.
  89913. */
  89914. SQLITE_PRIVATE void sqlite3GenerateRowDelete(
  89915. Parse *pParse, /* Parsing context */
  89916. Table *pTab, /* Table containing the row to be deleted */
  89917. Trigger *pTrigger, /* List of triggers to (potentially) fire */
  89918. int iDataCur, /* Cursor from which column data is extracted */
  89919. int iIdxCur, /* First index cursor */
  89920. int iPk, /* First memory cell containing the PRIMARY KEY */
  89921. i16 nPk, /* Number of PRIMARY KEY memory cells */
  89922. u8 count, /* If non-zero, increment the row change counter */
  89923. u8 onconf, /* Default ON CONFLICT policy for triggers */
  89924. u8 bNoSeek /* iDataCur is already pointing to the row to delete */
  89925. ){
  89926. Vdbe *v = pParse->pVdbe; /* Vdbe */
  89927. int iOld = 0; /* First register in OLD.* array */
  89928. int iLabel; /* Label resolved to end of generated code */
  89929. u8 opSeek; /* Seek opcode */
  89930. /* Vdbe is guaranteed to have been allocated by this stage. */
  89931. assert( v );
  89932. VdbeModuleComment((v, "BEGIN: GenRowDel(%d,%d,%d,%d)",
  89933. iDataCur, iIdxCur, iPk, (int)nPk));
  89934. /* Seek cursor iCur to the row to delete. If this row no longer exists
  89935. ** (this can happen if a trigger program has already deleted it), do
  89936. ** not attempt to delete it or fire any DELETE triggers. */
  89937. iLabel = sqlite3VdbeMakeLabel(v);
  89938. opSeek = HasRowid(pTab) ? OP_NotExists : OP_NotFound;
  89939. if( !bNoSeek ){
  89940. sqlite3VdbeAddOp4Int(v, opSeek, iDataCur, iLabel, iPk, nPk);
  89941. VdbeCoverageIf(v, opSeek==OP_NotExists);
  89942. VdbeCoverageIf(v, opSeek==OP_NotFound);
  89943. }
  89944. /* If there are any triggers to fire, allocate a range of registers to
  89945. ** use for the old.* references in the triggers. */
  89946. if( sqlite3FkRequired(pParse, pTab, 0, 0) || pTrigger ){
  89947. u32 mask; /* Mask of OLD.* columns in use */
  89948. int iCol; /* Iterator used while populating OLD.* */
  89949. int addrStart; /* Start of BEFORE trigger programs */
  89950. /* TODO: Could use temporary registers here. Also could attempt to
  89951. ** avoid copying the contents of the rowid register. */
  89952. mask = sqlite3TriggerColmask(
  89953. pParse, pTrigger, 0, 0, TRIGGER_BEFORE|TRIGGER_AFTER, pTab, onconf
  89954. );
  89955. mask |= sqlite3FkOldmask(pParse, pTab);
  89956. iOld = pParse->nMem+1;
  89957. pParse->nMem += (1 + pTab->nCol);
  89958. /* Populate the OLD.* pseudo-table register array. These values will be
  89959. ** used by any BEFORE and AFTER triggers that exist. */
  89960. sqlite3VdbeAddOp2(v, OP_Copy, iPk, iOld);
  89961. for(iCol=0; iCol<pTab->nCol; iCol++){
  89962. testcase( mask!=0xffffffff && iCol==31 );
  89963. testcase( mask!=0xffffffff && iCol==32 );
  89964. if( mask==0xffffffff || (iCol<=31 && (mask & MASKBIT32(iCol))!=0) ){
  89965. sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur, iCol, iOld+iCol+1);
  89966. }
  89967. }
  89968. /* Invoke BEFORE DELETE trigger programs. */
  89969. addrStart = sqlite3VdbeCurrentAddr(v);
  89970. sqlite3CodeRowTrigger(pParse, pTrigger,
  89971. TK_DELETE, 0, TRIGGER_BEFORE, pTab, iOld, onconf, iLabel
  89972. );
  89973. /* If any BEFORE triggers were coded, then seek the cursor to the
  89974. ** row to be deleted again. It may be that the BEFORE triggers moved
  89975. ** the cursor or of already deleted the row that the cursor was
  89976. ** pointing to.
  89977. */
  89978. if( addrStart<sqlite3VdbeCurrentAddr(v) ){
  89979. sqlite3VdbeAddOp4Int(v, opSeek, iDataCur, iLabel, iPk, nPk);
  89980. VdbeCoverageIf(v, opSeek==OP_NotExists);
  89981. VdbeCoverageIf(v, opSeek==OP_NotFound);
  89982. }
  89983. /* Do FK processing. This call checks that any FK constraints that
  89984. ** refer to this table (i.e. constraints attached to other tables)
  89985. ** are not violated by deleting this row. */
  89986. sqlite3FkCheck(pParse, pTab, iOld, 0, 0, 0);
  89987. }
  89988. /* Delete the index and table entries. Skip this step if pTab is really
  89989. ** a view (in which case the only effect of the DELETE statement is to
  89990. ** fire the INSTEAD OF triggers). */
  89991. if( pTab->pSelect==0 ){
  89992. sqlite3GenerateRowIndexDelete(pParse, pTab, iDataCur, iIdxCur, 0);
  89993. sqlite3VdbeAddOp2(v, OP_Delete, iDataCur, (count?OPFLAG_NCHANGE:0));
  89994. if( count ){
  89995. sqlite3VdbeChangeP4(v, -1, pTab->zName, P4_TRANSIENT);
  89996. }
  89997. }
  89998. /* Do any ON CASCADE, SET NULL or SET DEFAULT operations required to
  89999. ** handle rows (possibly in other tables) that refer via a foreign key
  90000. ** to the row just deleted. */
  90001. sqlite3FkActions(pParse, pTab, 0, iOld, 0, 0);
  90002. /* Invoke AFTER DELETE trigger programs. */
  90003. sqlite3CodeRowTrigger(pParse, pTrigger,
  90004. TK_DELETE, 0, TRIGGER_AFTER, pTab, iOld, onconf, iLabel
  90005. );
  90006. /* Jump here if the row had already been deleted before any BEFORE
  90007. ** trigger programs were invoked. Or if a trigger program throws a
  90008. ** RAISE(IGNORE) exception. */
  90009. sqlite3VdbeResolveLabel(v, iLabel);
  90010. VdbeModuleComment((v, "END: GenRowDel()"));
  90011. }
  90012. /*
  90013. ** This routine generates VDBE code that causes the deletion of all
  90014. ** index entries associated with a single row of a single table, pTab
  90015. **
  90016. ** Preconditions:
  90017. **
  90018. ** 1. A read/write cursor "iDataCur" must be open on the canonical storage
  90019. ** btree for the table pTab. (This will be either the table itself
  90020. ** for rowid tables or to the primary key index for WITHOUT ROWID
  90021. ** tables.)
  90022. **
  90023. ** 2. Read/write cursors for all indices of pTab must be open as
  90024. ** cursor number iIdxCur+i for the i-th index. (The pTab->pIndex
  90025. ** index is the 0-th index.)
  90026. **
  90027. ** 3. The "iDataCur" cursor must be already be positioned on the row
  90028. ** that is to be deleted.
  90029. */
  90030. SQLITE_PRIVATE void sqlite3GenerateRowIndexDelete(
  90031. Parse *pParse, /* Parsing and code generating context */
  90032. Table *pTab, /* Table containing the row to be deleted */
  90033. int iDataCur, /* Cursor of table holding data. */
  90034. int iIdxCur, /* First index cursor */
  90035. int *aRegIdx /* Only delete if aRegIdx!=0 && aRegIdx[i]>0 */
  90036. ){
  90037. int i; /* Index loop counter */
  90038. int r1 = -1; /* Register holding an index key */
  90039. int iPartIdxLabel; /* Jump destination for skipping partial index entries */
  90040. Index *pIdx; /* Current index */
  90041. Index *pPrior = 0; /* Prior index */
  90042. Vdbe *v; /* The prepared statement under construction */
  90043. Index *pPk; /* PRIMARY KEY index, or NULL for rowid tables */
  90044. v = pParse->pVdbe;
  90045. pPk = HasRowid(pTab) ? 0 : sqlite3PrimaryKeyIndex(pTab);
  90046. for(i=0, pIdx=pTab->pIndex; pIdx; i++, pIdx=pIdx->pNext){
  90047. assert( iIdxCur+i!=iDataCur || pPk==pIdx );
  90048. if( aRegIdx!=0 && aRegIdx[i]==0 ) continue;
  90049. if( pIdx==pPk ) continue;
  90050. VdbeModuleComment((v, "GenRowIdxDel for %s", pIdx->zName));
  90051. r1 = sqlite3GenerateIndexKey(pParse, pIdx, iDataCur, 0, 1,
  90052. &iPartIdxLabel, pPrior, r1);
  90053. sqlite3VdbeAddOp3(v, OP_IdxDelete, iIdxCur+i, r1,
  90054. pIdx->uniqNotNull ? pIdx->nKeyCol : pIdx->nColumn);
  90055. sqlite3ResolvePartIdxLabel(pParse, iPartIdxLabel);
  90056. pPrior = pIdx;
  90057. }
  90058. }
  90059. /*
  90060. ** Generate code that will assemble an index key and stores it in register
  90061. ** regOut. The key with be for index pIdx which is an index on pTab.
  90062. ** iCur is the index of a cursor open on the pTab table and pointing to
  90063. ** the entry that needs indexing. If pTab is a WITHOUT ROWID table, then
  90064. ** iCur must be the cursor of the PRIMARY KEY index.
  90065. **
  90066. ** Return a register number which is the first in a block of
  90067. ** registers that holds the elements of the index key. The
  90068. ** block of registers has already been deallocated by the time
  90069. ** this routine returns.
  90070. **
  90071. ** If *piPartIdxLabel is not NULL, fill it in with a label and jump
  90072. ** to that label if pIdx is a partial index that should be skipped.
  90073. ** The label should be resolved using sqlite3ResolvePartIdxLabel().
  90074. ** A partial index should be skipped if its WHERE clause evaluates
  90075. ** to false or null. If pIdx is not a partial index, *piPartIdxLabel
  90076. ** will be set to zero which is an empty label that is ignored by
  90077. ** sqlite3ResolvePartIdxLabel().
  90078. **
  90079. ** The pPrior and regPrior parameters are used to implement a cache to
  90080. ** avoid unnecessary register loads. If pPrior is not NULL, then it is
  90081. ** a pointer to a different index for which an index key has just been
  90082. ** computed into register regPrior. If the current pIdx index is generating
  90083. ** its key into the same sequence of registers and if pPrior and pIdx share
  90084. ** a column in common, then the register corresponding to that column already
  90085. ** holds the correct value and the loading of that register is skipped.
  90086. ** This optimization is helpful when doing a DELETE or an INTEGRITY_CHECK
  90087. ** on a table with multiple indices, and especially with the ROWID or
  90088. ** PRIMARY KEY columns of the index.
  90089. */
  90090. SQLITE_PRIVATE int sqlite3GenerateIndexKey(
  90091. Parse *pParse, /* Parsing context */
  90092. Index *pIdx, /* The index for which to generate a key */
  90093. int iDataCur, /* Cursor number from which to take column data */
  90094. int regOut, /* Put the new key into this register if not 0 */
  90095. int prefixOnly, /* Compute only a unique prefix of the key */
  90096. int *piPartIdxLabel, /* OUT: Jump to this label to skip partial index */
  90097. Index *pPrior, /* Previously generated index key */
  90098. int regPrior /* Register holding previous generated key */
  90099. ){
  90100. Vdbe *v = pParse->pVdbe;
  90101. int j;
  90102. Table *pTab = pIdx->pTable;
  90103. int regBase;
  90104. int nCol;
  90105. if( piPartIdxLabel ){
  90106. if( pIdx->pPartIdxWhere ){
  90107. *piPartIdxLabel = sqlite3VdbeMakeLabel(v);
  90108. pParse->iPartIdxTab = iDataCur;
  90109. sqlite3ExprCachePush(pParse);
  90110. sqlite3ExprIfFalse(pParse, pIdx->pPartIdxWhere, *piPartIdxLabel,
  90111. SQLITE_JUMPIFNULL);
  90112. }else{
  90113. *piPartIdxLabel = 0;
  90114. }
  90115. }
  90116. nCol = (prefixOnly && pIdx->uniqNotNull) ? pIdx->nKeyCol : pIdx->nColumn;
  90117. regBase = sqlite3GetTempRange(pParse, nCol);
  90118. if( pPrior && (regBase!=regPrior || pPrior->pPartIdxWhere) ) pPrior = 0;
  90119. for(j=0; j<nCol; j++){
  90120. if( pPrior && pPrior->aiColumn[j]==pIdx->aiColumn[j] ) continue;
  90121. sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur, pIdx->aiColumn[j],
  90122. regBase+j);
  90123. /* If the column affinity is REAL but the number is an integer, then it
  90124. ** might be stored in the table as an integer (using a compact
  90125. ** representation) then converted to REAL by an OP_RealAffinity opcode.
  90126. ** But we are getting ready to store this value back into an index, where
  90127. ** it should be converted by to INTEGER again. So omit the OP_RealAffinity
  90128. ** opcode if it is present */
  90129. sqlite3VdbeDeletePriorOpcode(v, OP_RealAffinity);
  90130. }
  90131. if( regOut ){
  90132. sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nCol, regOut);
  90133. }
  90134. sqlite3ReleaseTempRange(pParse, regBase, nCol);
  90135. return regBase;
  90136. }
  90137. /*
  90138. ** If a prior call to sqlite3GenerateIndexKey() generated a jump-over label
  90139. ** because it was a partial index, then this routine should be called to
  90140. ** resolve that label.
  90141. */
  90142. SQLITE_PRIVATE void sqlite3ResolvePartIdxLabel(Parse *pParse, int iLabel){
  90143. if( iLabel ){
  90144. sqlite3VdbeResolveLabel(pParse->pVdbe, iLabel);
  90145. sqlite3ExprCachePop(pParse);
  90146. }
  90147. }
  90148. /************** End of delete.c **********************************************/
  90149. /************** Begin file func.c ********************************************/
  90150. /*
  90151. ** 2002 February 23
  90152. **
  90153. ** The author disclaims copyright to this source code. In place of
  90154. ** a legal notice, here is a blessing:
  90155. **
  90156. ** May you do good and not evil.
  90157. ** May you find forgiveness for yourself and forgive others.
  90158. ** May you share freely, never taking more than you give.
  90159. **
  90160. *************************************************************************
  90161. ** This file contains the C-language implementations for many of the SQL
  90162. ** functions of SQLite. (Some function, and in particular the date and
  90163. ** time functions, are implemented separately.)
  90164. */
  90165. /* #include <stdlib.h> */
  90166. /* #include <assert.h> */
  90167. /*
  90168. ** Return the collating function associated with a function.
  90169. */
  90170. static CollSeq *sqlite3GetFuncCollSeq(sqlite3_context *context){
  90171. VdbeOp *pOp;
  90172. assert( context->pVdbe!=0 );
  90173. pOp = &context->pVdbe->aOp[context->iOp-1];
  90174. assert( pOp->opcode==OP_CollSeq );
  90175. assert( pOp->p4type==P4_COLLSEQ );
  90176. return pOp->p4.pColl;
  90177. }
  90178. /*
  90179. ** Indicate that the accumulator load should be skipped on this
  90180. ** iteration of the aggregate loop.
  90181. */
  90182. static void sqlite3SkipAccumulatorLoad(sqlite3_context *context){
  90183. context->skipFlag = 1;
  90184. }
  90185. /*
  90186. ** Implementation of the non-aggregate min() and max() functions
  90187. */
  90188. static void minmaxFunc(
  90189. sqlite3_context *context,
  90190. int argc,
  90191. sqlite3_value **argv
  90192. ){
  90193. int i;
  90194. int mask; /* 0 for min() or 0xffffffff for max() */
  90195. int iBest;
  90196. CollSeq *pColl;
  90197. assert( argc>1 );
  90198. mask = sqlite3_user_data(context)==0 ? 0 : -1;
  90199. pColl = sqlite3GetFuncCollSeq(context);
  90200. assert( pColl );
  90201. assert( mask==-1 || mask==0 );
  90202. iBest = 0;
  90203. if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
  90204. for(i=1; i<argc; i++){
  90205. if( sqlite3_value_type(argv[i])==SQLITE_NULL ) return;
  90206. if( (sqlite3MemCompare(argv[iBest], argv[i], pColl)^mask)>=0 ){
  90207. testcase( mask==0 );
  90208. iBest = i;
  90209. }
  90210. }
  90211. sqlite3_result_value(context, argv[iBest]);
  90212. }
  90213. /*
  90214. ** Return the type of the argument.
  90215. */
  90216. static void typeofFunc(
  90217. sqlite3_context *context,
  90218. int NotUsed,
  90219. sqlite3_value **argv
  90220. ){
  90221. const char *z = 0;
  90222. UNUSED_PARAMETER(NotUsed);
  90223. switch( sqlite3_value_type(argv[0]) ){
  90224. case SQLITE_INTEGER: z = "integer"; break;
  90225. case SQLITE_TEXT: z = "text"; break;
  90226. case SQLITE_FLOAT: z = "real"; break;
  90227. case SQLITE_BLOB: z = "blob"; break;
  90228. default: z = "null"; break;
  90229. }
  90230. sqlite3_result_text(context, z, -1, SQLITE_STATIC);
  90231. }
  90232. /*
  90233. ** Implementation of the length() function
  90234. */
  90235. static void lengthFunc(
  90236. sqlite3_context *context,
  90237. int argc,
  90238. sqlite3_value **argv
  90239. ){
  90240. int len;
  90241. assert( argc==1 );
  90242. UNUSED_PARAMETER(argc);
  90243. switch( sqlite3_value_type(argv[0]) ){
  90244. case SQLITE_BLOB:
  90245. case SQLITE_INTEGER:
  90246. case SQLITE_FLOAT: {
  90247. sqlite3_result_int(context, sqlite3_value_bytes(argv[0]));
  90248. break;
  90249. }
  90250. case SQLITE_TEXT: {
  90251. const unsigned char *z = sqlite3_value_text(argv[0]);
  90252. if( z==0 ) return;
  90253. len = 0;
  90254. while( *z ){
  90255. len++;
  90256. SQLITE_SKIP_UTF8(z);
  90257. }
  90258. sqlite3_result_int(context, len);
  90259. break;
  90260. }
  90261. default: {
  90262. sqlite3_result_null(context);
  90263. break;
  90264. }
  90265. }
  90266. }
  90267. /*
  90268. ** Implementation of the abs() function.
  90269. **
  90270. ** IMP: R-23979-26855 The abs(X) function returns the absolute value of
  90271. ** the numeric argument X.
  90272. */
  90273. static void absFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
  90274. assert( argc==1 );
  90275. UNUSED_PARAMETER(argc);
  90276. switch( sqlite3_value_type(argv[0]) ){
  90277. case SQLITE_INTEGER: {
  90278. i64 iVal = sqlite3_value_int64(argv[0]);
  90279. if( iVal<0 ){
  90280. if( iVal==SMALLEST_INT64 ){
  90281. /* IMP: R-31676-45509 If X is the integer -9223372036854775808
  90282. ** then abs(X) throws an integer overflow error since there is no
  90283. ** equivalent positive 64-bit two complement value. */
  90284. sqlite3_result_error(context, "integer overflow", -1);
  90285. return;
  90286. }
  90287. iVal = -iVal;
  90288. }
  90289. sqlite3_result_int64(context, iVal);
  90290. break;
  90291. }
  90292. case SQLITE_NULL: {
  90293. /* IMP: R-37434-19929 Abs(X) returns NULL if X is NULL. */
  90294. sqlite3_result_null(context);
  90295. break;
  90296. }
  90297. default: {
  90298. /* Because sqlite3_value_double() returns 0.0 if the argument is not
  90299. ** something that can be converted into a number, we have:
  90300. ** IMP: R-01992-00519 Abs(X) returns 0.0 if X is a string or blob
  90301. ** that cannot be converted to a numeric value.
  90302. */
  90303. double rVal = sqlite3_value_double(argv[0]);
  90304. if( rVal<0 ) rVal = -rVal;
  90305. sqlite3_result_double(context, rVal);
  90306. break;
  90307. }
  90308. }
  90309. }
  90310. /*
  90311. ** Implementation of the instr() function.
  90312. **
  90313. ** instr(haystack,needle) finds the first occurrence of needle
  90314. ** in haystack and returns the number of previous characters plus 1,
  90315. ** or 0 if needle does not occur within haystack.
  90316. **
  90317. ** If both haystack and needle are BLOBs, then the result is one more than
  90318. ** the number of bytes in haystack prior to the first occurrence of needle,
  90319. ** or 0 if needle never occurs in haystack.
  90320. */
  90321. static void instrFunc(
  90322. sqlite3_context *context,
  90323. int argc,
  90324. sqlite3_value **argv
  90325. ){
  90326. const unsigned char *zHaystack;
  90327. const unsigned char *zNeedle;
  90328. int nHaystack;
  90329. int nNeedle;
  90330. int typeHaystack, typeNeedle;
  90331. int N = 1;
  90332. int isText;
  90333. UNUSED_PARAMETER(argc);
  90334. typeHaystack = sqlite3_value_type(argv[0]);
  90335. typeNeedle = sqlite3_value_type(argv[1]);
  90336. if( typeHaystack==SQLITE_NULL || typeNeedle==SQLITE_NULL ) return;
  90337. nHaystack = sqlite3_value_bytes(argv[0]);
  90338. nNeedle = sqlite3_value_bytes(argv[1]);
  90339. if( typeHaystack==SQLITE_BLOB && typeNeedle==SQLITE_BLOB ){
  90340. zHaystack = sqlite3_value_blob(argv[0]);
  90341. zNeedle = sqlite3_value_blob(argv[1]);
  90342. isText = 0;
  90343. }else{
  90344. zHaystack = sqlite3_value_text(argv[0]);
  90345. zNeedle = sqlite3_value_text(argv[1]);
  90346. isText = 1;
  90347. }
  90348. while( nNeedle<=nHaystack && memcmp(zHaystack, zNeedle, nNeedle)!=0 ){
  90349. N++;
  90350. do{
  90351. nHaystack--;
  90352. zHaystack++;
  90353. }while( isText && (zHaystack[0]&0xc0)==0x80 );
  90354. }
  90355. if( nNeedle>nHaystack ) N = 0;
  90356. sqlite3_result_int(context, N);
  90357. }
  90358. /*
  90359. ** Implementation of the printf() function.
  90360. */
  90361. static void printfFunc(
  90362. sqlite3_context *context,
  90363. int argc,
  90364. sqlite3_value **argv
  90365. ){
  90366. PrintfArguments x;
  90367. StrAccum str;
  90368. const char *zFormat;
  90369. int n;
  90370. sqlite3 *db = sqlite3_context_db_handle(context);
  90371. if( argc>=1 && (zFormat = (const char*)sqlite3_value_text(argv[0]))!=0 ){
  90372. x.nArg = argc-1;
  90373. x.nUsed = 0;
  90374. x.apArg = argv+1;
  90375. sqlite3StrAccumInit(&str, db, 0, 0, db->aLimit[SQLITE_LIMIT_LENGTH]);
  90376. sqlite3XPrintf(&str, SQLITE_PRINTF_SQLFUNC, zFormat, &x);
  90377. n = str.nChar;
  90378. sqlite3_result_text(context, sqlite3StrAccumFinish(&str), n,
  90379. SQLITE_DYNAMIC);
  90380. }
  90381. }
  90382. /*
  90383. ** Implementation of the substr() function.
  90384. **
  90385. ** substr(x,p1,p2) returns p2 characters of x[] beginning with p1.
  90386. ** p1 is 1-indexed. So substr(x,1,1) returns the first character
  90387. ** of x. If x is text, then we actually count UTF-8 characters.
  90388. ** If x is a blob, then we count bytes.
  90389. **
  90390. ** If p1 is negative, then we begin abs(p1) from the end of x[].
  90391. **
  90392. ** If p2 is negative, return the p2 characters preceding p1.
  90393. */
  90394. static void substrFunc(
  90395. sqlite3_context *context,
  90396. int argc,
  90397. sqlite3_value **argv
  90398. ){
  90399. const unsigned char *z;
  90400. const unsigned char *z2;
  90401. int len;
  90402. int p0type;
  90403. i64 p1, p2;
  90404. int negP2 = 0;
  90405. assert( argc==3 || argc==2 );
  90406. if( sqlite3_value_type(argv[1])==SQLITE_NULL
  90407. || (argc==3 && sqlite3_value_type(argv[2])==SQLITE_NULL)
  90408. ){
  90409. return;
  90410. }
  90411. p0type = sqlite3_value_type(argv[0]);
  90412. p1 = sqlite3_value_int(argv[1]);
  90413. if( p0type==SQLITE_BLOB ){
  90414. len = sqlite3_value_bytes(argv[0]);
  90415. z = sqlite3_value_blob(argv[0]);
  90416. if( z==0 ) return;
  90417. assert( len==sqlite3_value_bytes(argv[0]) );
  90418. }else{
  90419. z = sqlite3_value_text(argv[0]);
  90420. if( z==0 ) return;
  90421. len = 0;
  90422. if( p1<0 ){
  90423. for(z2=z; *z2; len++){
  90424. SQLITE_SKIP_UTF8(z2);
  90425. }
  90426. }
  90427. }
  90428. #ifdef SQLITE_SUBSTR_COMPATIBILITY
  90429. /* If SUBSTR_COMPATIBILITY is defined then substr(X,0,N) work the same as
  90430. ** as substr(X,1,N) - it returns the first N characters of X. This
  90431. ** is essentially a back-out of the bug-fix in check-in [5fc125d362df4b8]
  90432. ** from 2009-02-02 for compatibility of applications that exploited the
  90433. ** old buggy behavior. */
  90434. if( p1==0 ) p1 = 1; /* <rdar://problem/6778339> */
  90435. #endif
  90436. if( argc==3 ){
  90437. p2 = sqlite3_value_int(argv[2]);
  90438. if( p2<0 ){
  90439. p2 = -p2;
  90440. negP2 = 1;
  90441. }
  90442. }else{
  90443. p2 = sqlite3_context_db_handle(context)->aLimit[SQLITE_LIMIT_LENGTH];
  90444. }
  90445. if( p1<0 ){
  90446. p1 += len;
  90447. if( p1<0 ){
  90448. p2 += p1;
  90449. if( p2<0 ) p2 = 0;
  90450. p1 = 0;
  90451. }
  90452. }else if( p1>0 ){
  90453. p1--;
  90454. }else if( p2>0 ){
  90455. p2--;
  90456. }
  90457. if( negP2 ){
  90458. p1 -= p2;
  90459. if( p1<0 ){
  90460. p2 += p1;
  90461. p1 = 0;
  90462. }
  90463. }
  90464. assert( p1>=0 && p2>=0 );
  90465. if( p0type!=SQLITE_BLOB ){
  90466. while( *z && p1 ){
  90467. SQLITE_SKIP_UTF8(z);
  90468. p1--;
  90469. }
  90470. for(z2=z; *z2 && p2; p2--){
  90471. SQLITE_SKIP_UTF8(z2);
  90472. }
  90473. sqlite3_result_text64(context, (char*)z, z2-z, SQLITE_TRANSIENT,
  90474. SQLITE_UTF8);
  90475. }else{
  90476. if( p1+p2>len ){
  90477. p2 = len-p1;
  90478. if( p2<0 ) p2 = 0;
  90479. }
  90480. sqlite3_result_blob64(context, (char*)&z[p1], (u64)p2, SQLITE_TRANSIENT);
  90481. }
  90482. }
  90483. /*
  90484. ** Implementation of the round() function
  90485. */
  90486. #ifndef SQLITE_OMIT_FLOATING_POINT
  90487. static void roundFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
  90488. int n = 0;
  90489. double r;
  90490. char *zBuf;
  90491. assert( argc==1 || argc==2 );
  90492. if( argc==2 ){
  90493. if( SQLITE_NULL==sqlite3_value_type(argv[1]) ) return;
  90494. n = sqlite3_value_int(argv[1]);
  90495. if( n>30 ) n = 30;
  90496. if( n<0 ) n = 0;
  90497. }
  90498. if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
  90499. r = sqlite3_value_double(argv[0]);
  90500. /* If Y==0 and X will fit in a 64-bit int,
  90501. ** handle the rounding directly,
  90502. ** otherwise use printf.
  90503. */
  90504. if( n==0 && r>=0 && r<LARGEST_INT64-1 ){
  90505. r = (double)((sqlite_int64)(r+0.5));
  90506. }else if( n==0 && r<0 && (-r)<LARGEST_INT64-1 ){
  90507. r = -(double)((sqlite_int64)((-r)+0.5));
  90508. }else{
  90509. zBuf = sqlite3_mprintf("%.*f",n,r);
  90510. if( zBuf==0 ){
  90511. sqlite3_result_error_nomem(context);
  90512. return;
  90513. }
  90514. sqlite3AtoF(zBuf, &r, sqlite3Strlen30(zBuf), SQLITE_UTF8);
  90515. sqlite3_free(zBuf);
  90516. }
  90517. sqlite3_result_double(context, r);
  90518. }
  90519. #endif
  90520. /*
  90521. ** Allocate nByte bytes of space using sqlite3Malloc(). If the
  90522. ** allocation fails, call sqlite3_result_error_nomem() to notify
  90523. ** the database handle that malloc() has failed and return NULL.
  90524. ** If nByte is larger than the maximum string or blob length, then
  90525. ** raise an SQLITE_TOOBIG exception and return NULL.
  90526. */
  90527. static void *contextMalloc(sqlite3_context *context, i64 nByte){
  90528. char *z;
  90529. sqlite3 *db = sqlite3_context_db_handle(context);
  90530. assert( nByte>0 );
  90531. testcase( nByte==db->aLimit[SQLITE_LIMIT_LENGTH] );
  90532. testcase( nByte==db->aLimit[SQLITE_LIMIT_LENGTH]+1 );
  90533. if( nByte>db->aLimit[SQLITE_LIMIT_LENGTH] ){
  90534. sqlite3_result_error_toobig(context);
  90535. z = 0;
  90536. }else{
  90537. z = sqlite3Malloc(nByte);
  90538. if( !z ){
  90539. sqlite3_result_error_nomem(context);
  90540. }
  90541. }
  90542. return z;
  90543. }
  90544. /*
  90545. ** Implementation of the upper() and lower() SQL functions.
  90546. */
  90547. static void upperFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
  90548. char *z1;
  90549. const char *z2;
  90550. int i, n;
  90551. UNUSED_PARAMETER(argc);
  90552. z2 = (char*)sqlite3_value_text(argv[0]);
  90553. n = sqlite3_value_bytes(argv[0]);
  90554. /* Verify that the call to _bytes() does not invalidate the _text() pointer */
  90555. assert( z2==(char*)sqlite3_value_text(argv[0]) );
  90556. if( z2 ){
  90557. z1 = contextMalloc(context, ((i64)n)+1);
  90558. if( z1 ){
  90559. for(i=0; i<n; i++){
  90560. z1[i] = (char)sqlite3Toupper(z2[i]);
  90561. }
  90562. sqlite3_result_text(context, z1, n, sqlite3_free);
  90563. }
  90564. }
  90565. }
  90566. static void lowerFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
  90567. char *z1;
  90568. const char *z2;
  90569. int i, n;
  90570. UNUSED_PARAMETER(argc);
  90571. z2 = (char*)sqlite3_value_text(argv[0]);
  90572. n = sqlite3_value_bytes(argv[0]);
  90573. /* Verify that the call to _bytes() does not invalidate the _text() pointer */
  90574. assert( z2==(char*)sqlite3_value_text(argv[0]) );
  90575. if( z2 ){
  90576. z1 = contextMalloc(context, ((i64)n)+1);
  90577. if( z1 ){
  90578. for(i=0; i<n; i++){
  90579. z1[i] = sqlite3Tolower(z2[i]);
  90580. }
  90581. sqlite3_result_text(context, z1, n, sqlite3_free);
  90582. }
  90583. }
  90584. }
  90585. /*
  90586. ** Some functions like COALESCE() and IFNULL() and UNLIKELY() are implemented
  90587. ** as VDBE code so that unused argument values do not have to be computed.
  90588. ** However, we still need some kind of function implementation for this
  90589. ** routines in the function table. The noopFunc macro provides this.
  90590. ** noopFunc will never be called so it doesn't matter what the implementation
  90591. ** is. We might as well use the "version()" function as a substitute.
  90592. */
  90593. #define noopFunc versionFunc /* Substitute function - never called */
  90594. /*
  90595. ** Implementation of random(). Return a random integer.
  90596. */
  90597. static void randomFunc(
  90598. sqlite3_context *context,
  90599. int NotUsed,
  90600. sqlite3_value **NotUsed2
  90601. ){
  90602. sqlite_int64 r;
  90603. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  90604. sqlite3_randomness(sizeof(r), &r);
  90605. if( r<0 ){
  90606. /* We need to prevent a random number of 0x8000000000000000
  90607. ** (or -9223372036854775808) since when you do abs() of that
  90608. ** number of you get the same value back again. To do this
  90609. ** in a way that is testable, mask the sign bit off of negative
  90610. ** values, resulting in a positive value. Then take the
  90611. ** 2s complement of that positive value. The end result can
  90612. ** therefore be no less than -9223372036854775807.
  90613. */
  90614. r = -(r & LARGEST_INT64);
  90615. }
  90616. sqlite3_result_int64(context, r);
  90617. }
  90618. /*
  90619. ** Implementation of randomblob(N). Return a random blob
  90620. ** that is N bytes long.
  90621. */
  90622. static void randomBlob(
  90623. sqlite3_context *context,
  90624. int argc,
  90625. sqlite3_value **argv
  90626. ){
  90627. int n;
  90628. unsigned char *p;
  90629. assert( argc==1 );
  90630. UNUSED_PARAMETER(argc);
  90631. n = sqlite3_value_int(argv[0]);
  90632. if( n<1 ){
  90633. n = 1;
  90634. }
  90635. p = contextMalloc(context, n);
  90636. if( p ){
  90637. sqlite3_randomness(n, p);
  90638. sqlite3_result_blob(context, (char*)p, n, sqlite3_free);
  90639. }
  90640. }
  90641. /*
  90642. ** Implementation of the last_insert_rowid() SQL function. The return
  90643. ** value is the same as the sqlite3_last_insert_rowid() API function.
  90644. */
  90645. static void last_insert_rowid(
  90646. sqlite3_context *context,
  90647. int NotUsed,
  90648. sqlite3_value **NotUsed2
  90649. ){
  90650. sqlite3 *db = sqlite3_context_db_handle(context);
  90651. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  90652. /* IMP: R-51513-12026 The last_insert_rowid() SQL function is a
  90653. ** wrapper around the sqlite3_last_insert_rowid() C/C++ interface
  90654. ** function. */
  90655. sqlite3_result_int64(context, sqlite3_last_insert_rowid(db));
  90656. }
  90657. /*
  90658. ** Implementation of the changes() SQL function.
  90659. **
  90660. ** IMP: R-62073-11209 The changes() SQL function is a wrapper
  90661. ** around the sqlite3_changes() C/C++ function and hence follows the same
  90662. ** rules for counting changes.
  90663. */
  90664. static void changes(
  90665. sqlite3_context *context,
  90666. int NotUsed,
  90667. sqlite3_value **NotUsed2
  90668. ){
  90669. sqlite3 *db = sqlite3_context_db_handle(context);
  90670. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  90671. sqlite3_result_int(context, sqlite3_changes(db));
  90672. }
  90673. /*
  90674. ** Implementation of the total_changes() SQL function. The return value is
  90675. ** the same as the sqlite3_total_changes() API function.
  90676. */
  90677. static void total_changes(
  90678. sqlite3_context *context,
  90679. int NotUsed,
  90680. sqlite3_value **NotUsed2
  90681. ){
  90682. sqlite3 *db = sqlite3_context_db_handle(context);
  90683. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  90684. /* IMP: R-52756-41993 This function is a wrapper around the
  90685. ** sqlite3_total_changes() C/C++ interface. */
  90686. sqlite3_result_int(context, sqlite3_total_changes(db));
  90687. }
  90688. /*
  90689. ** A structure defining how to do GLOB-style comparisons.
  90690. */
  90691. struct compareInfo {
  90692. u8 matchAll;
  90693. u8 matchOne;
  90694. u8 matchSet;
  90695. u8 noCase;
  90696. };
  90697. /*
  90698. ** For LIKE and GLOB matching on EBCDIC machines, assume that every
  90699. ** character is exactly one byte in size. Also, all characters are
  90700. ** able to participate in upper-case-to-lower-case mappings in EBCDIC
  90701. ** whereas only characters less than 0x80 do in ASCII.
  90702. */
  90703. #if defined(SQLITE_EBCDIC)
  90704. # define sqlite3Utf8Read(A) (*((*A)++))
  90705. # define GlobUpperToLower(A) A = sqlite3UpperToLower[A]
  90706. # define GlobUpperToLowerAscii(A) A = sqlite3UpperToLower[A]
  90707. #else
  90708. # define GlobUpperToLower(A) if( A<=0x7f ){ A = sqlite3UpperToLower[A]; }
  90709. # define GlobUpperToLowerAscii(A) A = sqlite3UpperToLower[A]
  90710. #endif
  90711. static const struct compareInfo globInfo = { '*', '?', '[', 0 };
  90712. /* The correct SQL-92 behavior is for the LIKE operator to ignore
  90713. ** case. Thus 'a' LIKE 'A' would be true. */
  90714. static const struct compareInfo likeInfoNorm = { '%', '_', 0, 1 };
  90715. /* If SQLITE_CASE_SENSITIVE_LIKE is defined, then the LIKE operator
  90716. ** is case sensitive causing 'a' LIKE 'A' to be false */
  90717. static const struct compareInfo likeInfoAlt = { '%', '_', 0, 0 };
  90718. /*
  90719. ** Compare two UTF-8 strings for equality where the first string can
  90720. ** potentially be a "glob" or "like" expression. Return true (1) if they
  90721. ** are the same and false (0) if they are different.
  90722. **
  90723. ** Globbing rules:
  90724. **
  90725. ** '*' Matches any sequence of zero or more characters.
  90726. **
  90727. ** '?' Matches exactly one character.
  90728. **
  90729. ** [...] Matches one character from the enclosed list of
  90730. ** characters.
  90731. **
  90732. ** [^...] Matches one character not in the enclosed list.
  90733. **
  90734. ** With the [...] and [^...] matching, a ']' character can be included
  90735. ** in the list by making it the first character after '[' or '^'. A
  90736. ** range of characters can be specified using '-'. Example:
  90737. ** "[a-z]" matches any single lower-case letter. To match a '-', make
  90738. ** it the last character in the list.
  90739. **
  90740. ** Like matching rules:
  90741. **
  90742. ** '%' Matches any sequence of zero or more characters
  90743. **
  90744. *** '_' Matches any one character
  90745. **
  90746. ** Ec Where E is the "esc" character and c is any other
  90747. ** character, including '%', '_', and esc, match exactly c.
  90748. **
  90749. ** The comments through this routine usually assume glob matching.
  90750. **
  90751. ** This routine is usually quick, but can be N**2 in the worst case.
  90752. */
  90753. static int patternCompare(
  90754. const u8 *zPattern, /* The glob pattern */
  90755. const u8 *zString, /* The string to compare against the glob */
  90756. const struct compareInfo *pInfo, /* Information about how to do the compare */
  90757. u32 esc /* The escape character */
  90758. ){
  90759. u32 c, c2; /* Next pattern and input string chars */
  90760. u32 matchOne = pInfo->matchOne; /* "?" or "_" */
  90761. u32 matchAll = pInfo->matchAll; /* "*" or "%" */
  90762. u32 matchOther; /* "[" or the escape character */
  90763. u8 noCase = pInfo->noCase; /* True if uppercase==lowercase */
  90764. const u8 *zEscaped = 0; /* One past the last escaped input char */
  90765. /* The GLOB operator does not have an ESCAPE clause. And LIKE does not
  90766. ** have the matchSet operator. So we either have to look for one or
  90767. ** the other, never both. Hence the single variable matchOther is used
  90768. ** to store the one we have to look for.
  90769. */
  90770. matchOther = esc ? esc : pInfo->matchSet;
  90771. while( (c = sqlite3Utf8Read(&zPattern))!=0 ){
  90772. if( c==matchAll ){ /* Match "*" */
  90773. /* Skip over multiple "*" characters in the pattern. If there
  90774. ** are also "?" characters, skip those as well, but consume a
  90775. ** single character of the input string for each "?" skipped */
  90776. while( (c=sqlite3Utf8Read(&zPattern)) == matchAll
  90777. || c == matchOne ){
  90778. if( c==matchOne && sqlite3Utf8Read(&zString)==0 ){
  90779. return 0;
  90780. }
  90781. }
  90782. if( c==0 ){
  90783. return 1; /* "*" at the end of the pattern matches */
  90784. }else if( c==matchOther ){
  90785. if( esc ){
  90786. c = sqlite3Utf8Read(&zPattern);
  90787. if( c==0 ) return 0;
  90788. }else{
  90789. /* "[...]" immediately follows the "*". We have to do a slow
  90790. ** recursive search in this case, but it is an unusual case. */
  90791. assert( matchOther<0x80 ); /* '[' is a single-byte character */
  90792. while( *zString
  90793. && patternCompare(&zPattern[-1],zString,pInfo,esc)==0 ){
  90794. SQLITE_SKIP_UTF8(zString);
  90795. }
  90796. return *zString!=0;
  90797. }
  90798. }
  90799. /* At this point variable c contains the first character of the
  90800. ** pattern string past the "*". Search in the input string for the
  90801. ** first matching character and recursively contine the match from
  90802. ** that point.
  90803. **
  90804. ** For a case-insensitive search, set variable cx to be the same as
  90805. ** c but in the other case and search the input string for either
  90806. ** c or cx.
  90807. */
  90808. if( c<=0x80 ){
  90809. u32 cx;
  90810. if( noCase ){
  90811. cx = sqlite3Toupper(c);
  90812. c = sqlite3Tolower(c);
  90813. }else{
  90814. cx = c;
  90815. }
  90816. while( (c2 = *(zString++))!=0 ){
  90817. if( c2!=c && c2!=cx ) continue;
  90818. if( patternCompare(zPattern,zString,pInfo,esc) ) return 1;
  90819. }
  90820. }else{
  90821. while( (c2 = sqlite3Utf8Read(&zString))!=0 ){
  90822. if( c2!=c ) continue;
  90823. if( patternCompare(zPattern,zString,pInfo,esc) ) return 1;
  90824. }
  90825. }
  90826. return 0;
  90827. }
  90828. if( c==matchOther ){
  90829. if( esc ){
  90830. c = sqlite3Utf8Read(&zPattern);
  90831. if( c==0 ) return 0;
  90832. zEscaped = zPattern;
  90833. }else{
  90834. u32 prior_c = 0;
  90835. int seen = 0;
  90836. int invert = 0;
  90837. c = sqlite3Utf8Read(&zString);
  90838. if( c==0 ) return 0;
  90839. c2 = sqlite3Utf8Read(&zPattern);
  90840. if( c2=='^' ){
  90841. invert = 1;
  90842. c2 = sqlite3Utf8Read(&zPattern);
  90843. }
  90844. if( c2==']' ){
  90845. if( c==']' ) seen = 1;
  90846. c2 = sqlite3Utf8Read(&zPattern);
  90847. }
  90848. while( c2 && c2!=']' ){
  90849. if( c2=='-' && zPattern[0]!=']' && zPattern[0]!=0 && prior_c>0 ){
  90850. c2 = sqlite3Utf8Read(&zPattern);
  90851. if( c>=prior_c && c<=c2 ) seen = 1;
  90852. prior_c = 0;
  90853. }else{
  90854. if( c==c2 ){
  90855. seen = 1;
  90856. }
  90857. prior_c = c2;
  90858. }
  90859. c2 = sqlite3Utf8Read(&zPattern);
  90860. }
  90861. if( c2==0 || (seen ^ invert)==0 ){
  90862. return 0;
  90863. }
  90864. continue;
  90865. }
  90866. }
  90867. c2 = sqlite3Utf8Read(&zString);
  90868. if( c==c2 ) continue;
  90869. if( noCase && c<0x80 && c2<0x80 && sqlite3Tolower(c)==sqlite3Tolower(c2) ){
  90870. continue;
  90871. }
  90872. if( c==matchOne && zPattern!=zEscaped && c2!=0 ) continue;
  90873. return 0;
  90874. }
  90875. return *zString==0;
  90876. }
  90877. /*
  90878. ** The sqlite3_strglob() interface.
  90879. */
  90880. SQLITE_API int SQLITE_STDCALL sqlite3_strglob(const char *zGlobPattern, const char *zString){
  90881. return patternCompare((u8*)zGlobPattern, (u8*)zString, &globInfo, 0)==0;
  90882. }
  90883. /*
  90884. ** Count the number of times that the LIKE operator (or GLOB which is
  90885. ** just a variation of LIKE) gets called. This is used for testing
  90886. ** only.
  90887. */
  90888. #ifdef SQLITE_TEST
  90889. SQLITE_API int sqlite3_like_count = 0;
  90890. #endif
  90891. /*
  90892. ** Implementation of the like() SQL function. This function implements
  90893. ** the build-in LIKE operator. The first argument to the function is the
  90894. ** pattern and the second argument is the string. So, the SQL statements:
  90895. **
  90896. ** A LIKE B
  90897. **
  90898. ** is implemented as like(B,A).
  90899. **
  90900. ** This same function (with a different compareInfo structure) computes
  90901. ** the GLOB operator.
  90902. */
  90903. static void likeFunc(
  90904. sqlite3_context *context,
  90905. int argc,
  90906. sqlite3_value **argv
  90907. ){
  90908. const unsigned char *zA, *zB;
  90909. u32 escape = 0;
  90910. int nPat;
  90911. sqlite3 *db = sqlite3_context_db_handle(context);
  90912. zB = sqlite3_value_text(argv[0]);
  90913. zA = sqlite3_value_text(argv[1]);
  90914. /* Limit the length of the LIKE or GLOB pattern to avoid problems
  90915. ** of deep recursion and N*N behavior in patternCompare().
  90916. */
  90917. nPat = sqlite3_value_bytes(argv[0]);
  90918. testcase( nPat==db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH] );
  90919. testcase( nPat==db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH]+1 );
  90920. if( nPat > db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH] ){
  90921. sqlite3_result_error(context, "LIKE or GLOB pattern too complex", -1);
  90922. return;
  90923. }
  90924. assert( zB==sqlite3_value_text(argv[0]) ); /* Encoding did not change */
  90925. if( argc==3 ){
  90926. /* The escape character string must consist of a single UTF-8 character.
  90927. ** Otherwise, return an error.
  90928. */
  90929. const unsigned char *zEsc = sqlite3_value_text(argv[2]);
  90930. if( zEsc==0 ) return;
  90931. if( sqlite3Utf8CharLen((char*)zEsc, -1)!=1 ){
  90932. sqlite3_result_error(context,
  90933. "ESCAPE expression must be a single character", -1);
  90934. return;
  90935. }
  90936. escape = sqlite3Utf8Read(&zEsc);
  90937. }
  90938. if( zA && zB ){
  90939. struct compareInfo *pInfo = sqlite3_user_data(context);
  90940. #ifdef SQLITE_TEST
  90941. sqlite3_like_count++;
  90942. #endif
  90943. sqlite3_result_int(context, patternCompare(zB, zA, pInfo, escape));
  90944. }
  90945. }
  90946. /*
  90947. ** Implementation of the NULLIF(x,y) function. The result is the first
  90948. ** argument if the arguments are different. The result is NULL if the
  90949. ** arguments are equal to each other.
  90950. */
  90951. static void nullifFunc(
  90952. sqlite3_context *context,
  90953. int NotUsed,
  90954. sqlite3_value **argv
  90955. ){
  90956. CollSeq *pColl = sqlite3GetFuncCollSeq(context);
  90957. UNUSED_PARAMETER(NotUsed);
  90958. if( sqlite3MemCompare(argv[0], argv[1], pColl)!=0 ){
  90959. sqlite3_result_value(context, argv[0]);
  90960. }
  90961. }
  90962. /*
  90963. ** Implementation of the sqlite_version() function. The result is the version
  90964. ** of the SQLite library that is running.
  90965. */
  90966. static void versionFunc(
  90967. sqlite3_context *context,
  90968. int NotUsed,
  90969. sqlite3_value **NotUsed2
  90970. ){
  90971. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  90972. /* IMP: R-48699-48617 This function is an SQL wrapper around the
  90973. ** sqlite3_libversion() C-interface. */
  90974. sqlite3_result_text(context, sqlite3_libversion(), -1, SQLITE_STATIC);
  90975. }
  90976. /*
  90977. ** Implementation of the sqlite_source_id() function. The result is a string
  90978. ** that identifies the particular version of the source code used to build
  90979. ** SQLite.
  90980. */
  90981. static void sourceidFunc(
  90982. sqlite3_context *context,
  90983. int NotUsed,
  90984. sqlite3_value **NotUsed2
  90985. ){
  90986. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  90987. /* IMP: R-24470-31136 This function is an SQL wrapper around the
  90988. ** sqlite3_sourceid() C interface. */
  90989. sqlite3_result_text(context, sqlite3_sourceid(), -1, SQLITE_STATIC);
  90990. }
  90991. /*
  90992. ** Implementation of the sqlite_log() function. This is a wrapper around
  90993. ** sqlite3_log(). The return value is NULL. The function exists purely for
  90994. ** its side-effects.
  90995. */
  90996. static void errlogFunc(
  90997. sqlite3_context *context,
  90998. int argc,
  90999. sqlite3_value **argv
  91000. ){
  91001. UNUSED_PARAMETER(argc);
  91002. UNUSED_PARAMETER(context);
  91003. sqlite3_log(sqlite3_value_int(argv[0]), "%s", sqlite3_value_text(argv[1]));
  91004. }
  91005. /*
  91006. ** Implementation of the sqlite_compileoption_used() function.
  91007. ** The result is an integer that identifies if the compiler option
  91008. ** was used to build SQLite.
  91009. */
  91010. #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
  91011. static void compileoptionusedFunc(
  91012. sqlite3_context *context,
  91013. int argc,
  91014. sqlite3_value **argv
  91015. ){
  91016. const char *zOptName;
  91017. assert( argc==1 );
  91018. UNUSED_PARAMETER(argc);
  91019. /* IMP: R-39564-36305 The sqlite_compileoption_used() SQL
  91020. ** function is a wrapper around the sqlite3_compileoption_used() C/C++
  91021. ** function.
  91022. */
  91023. if( (zOptName = (const char*)sqlite3_value_text(argv[0]))!=0 ){
  91024. sqlite3_result_int(context, sqlite3_compileoption_used(zOptName));
  91025. }
  91026. }
  91027. #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
  91028. /*
  91029. ** Implementation of the sqlite_compileoption_get() function.
  91030. ** The result is a string that identifies the compiler options
  91031. ** used to build SQLite.
  91032. */
  91033. #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
  91034. static void compileoptiongetFunc(
  91035. sqlite3_context *context,
  91036. int argc,
  91037. sqlite3_value **argv
  91038. ){
  91039. int n;
  91040. assert( argc==1 );
  91041. UNUSED_PARAMETER(argc);
  91042. /* IMP: R-04922-24076 The sqlite_compileoption_get() SQL function
  91043. ** is a wrapper around the sqlite3_compileoption_get() C/C++ function.
  91044. */
  91045. n = sqlite3_value_int(argv[0]);
  91046. sqlite3_result_text(context, sqlite3_compileoption_get(n), -1, SQLITE_STATIC);
  91047. }
  91048. #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
  91049. /* Array for converting from half-bytes (nybbles) into ASCII hex
  91050. ** digits. */
  91051. static const char hexdigits[] = {
  91052. '0', '1', '2', '3', '4', '5', '6', '7',
  91053. '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'
  91054. };
  91055. /*
  91056. ** Implementation of the QUOTE() function. This function takes a single
  91057. ** argument. If the argument is numeric, the return value is the same as
  91058. ** the argument. If the argument is NULL, the return value is the string
  91059. ** "NULL". Otherwise, the argument is enclosed in single quotes with
  91060. ** single-quote escapes.
  91061. */
  91062. static void quoteFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
  91063. assert( argc==1 );
  91064. UNUSED_PARAMETER(argc);
  91065. switch( sqlite3_value_type(argv[0]) ){
  91066. case SQLITE_FLOAT: {
  91067. double r1, r2;
  91068. char zBuf[50];
  91069. r1 = sqlite3_value_double(argv[0]);
  91070. sqlite3_snprintf(sizeof(zBuf), zBuf, "%!.15g", r1);
  91071. sqlite3AtoF(zBuf, &r2, 20, SQLITE_UTF8);
  91072. if( r1!=r2 ){
  91073. sqlite3_snprintf(sizeof(zBuf), zBuf, "%!.20e", r1);
  91074. }
  91075. sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
  91076. break;
  91077. }
  91078. case SQLITE_INTEGER: {
  91079. sqlite3_result_value(context, argv[0]);
  91080. break;
  91081. }
  91082. case SQLITE_BLOB: {
  91083. char *zText = 0;
  91084. char const *zBlob = sqlite3_value_blob(argv[0]);
  91085. int nBlob = sqlite3_value_bytes(argv[0]);
  91086. assert( zBlob==sqlite3_value_blob(argv[0]) ); /* No encoding change */
  91087. zText = (char *)contextMalloc(context, (2*(i64)nBlob)+4);
  91088. if( zText ){
  91089. int i;
  91090. for(i=0; i<nBlob; i++){
  91091. zText[(i*2)+2] = hexdigits[(zBlob[i]>>4)&0x0F];
  91092. zText[(i*2)+3] = hexdigits[(zBlob[i])&0x0F];
  91093. }
  91094. zText[(nBlob*2)+2] = '\'';
  91095. zText[(nBlob*2)+3] = '\0';
  91096. zText[0] = 'X';
  91097. zText[1] = '\'';
  91098. sqlite3_result_text(context, zText, -1, SQLITE_TRANSIENT);
  91099. sqlite3_free(zText);
  91100. }
  91101. break;
  91102. }
  91103. case SQLITE_TEXT: {
  91104. int i,j;
  91105. u64 n;
  91106. const unsigned char *zArg = sqlite3_value_text(argv[0]);
  91107. char *z;
  91108. if( zArg==0 ) return;
  91109. for(i=0, n=0; zArg[i]; i++){ if( zArg[i]=='\'' ) n++; }
  91110. z = contextMalloc(context, ((i64)i)+((i64)n)+3);
  91111. if( z ){
  91112. z[0] = '\'';
  91113. for(i=0, j=1; zArg[i]; i++){
  91114. z[j++] = zArg[i];
  91115. if( zArg[i]=='\'' ){
  91116. z[j++] = '\'';
  91117. }
  91118. }
  91119. z[j++] = '\'';
  91120. z[j] = 0;
  91121. sqlite3_result_text(context, z, j, sqlite3_free);
  91122. }
  91123. break;
  91124. }
  91125. default: {
  91126. assert( sqlite3_value_type(argv[0])==SQLITE_NULL );
  91127. sqlite3_result_text(context, "NULL", 4, SQLITE_STATIC);
  91128. break;
  91129. }
  91130. }
  91131. }
  91132. /*
  91133. ** The unicode() function. Return the integer unicode code-point value
  91134. ** for the first character of the input string.
  91135. */
  91136. static void unicodeFunc(
  91137. sqlite3_context *context,
  91138. int argc,
  91139. sqlite3_value **argv
  91140. ){
  91141. const unsigned char *z = sqlite3_value_text(argv[0]);
  91142. (void)argc;
  91143. if( z && z[0] ) sqlite3_result_int(context, sqlite3Utf8Read(&z));
  91144. }
  91145. /*
  91146. ** The char() function takes zero or more arguments, each of which is
  91147. ** an integer. It constructs a string where each character of the string
  91148. ** is the unicode character for the corresponding integer argument.
  91149. */
  91150. static void charFunc(
  91151. sqlite3_context *context,
  91152. int argc,
  91153. sqlite3_value **argv
  91154. ){
  91155. unsigned char *z, *zOut;
  91156. int i;
  91157. zOut = z = sqlite3_malloc64( argc*4+1 );
  91158. if( z==0 ){
  91159. sqlite3_result_error_nomem(context);
  91160. return;
  91161. }
  91162. for(i=0; i<argc; i++){
  91163. sqlite3_int64 x;
  91164. unsigned c;
  91165. x = sqlite3_value_int64(argv[i]);
  91166. if( x<0 || x>0x10ffff ) x = 0xfffd;
  91167. c = (unsigned)(x & 0x1fffff);
  91168. if( c<0x00080 ){
  91169. *zOut++ = (u8)(c&0xFF);
  91170. }else if( c<0x00800 ){
  91171. *zOut++ = 0xC0 + (u8)((c>>6)&0x1F);
  91172. *zOut++ = 0x80 + (u8)(c & 0x3F);
  91173. }else if( c<0x10000 ){
  91174. *zOut++ = 0xE0 + (u8)((c>>12)&0x0F);
  91175. *zOut++ = 0x80 + (u8)((c>>6) & 0x3F);
  91176. *zOut++ = 0x80 + (u8)(c & 0x3F);
  91177. }else{
  91178. *zOut++ = 0xF0 + (u8)((c>>18) & 0x07);
  91179. *zOut++ = 0x80 + (u8)((c>>12) & 0x3F);
  91180. *zOut++ = 0x80 + (u8)((c>>6) & 0x3F);
  91181. *zOut++ = 0x80 + (u8)(c & 0x3F);
  91182. } \
  91183. }
  91184. sqlite3_result_text64(context, (char*)z, zOut-z, sqlite3_free, SQLITE_UTF8);
  91185. }
  91186. /*
  91187. ** The hex() function. Interpret the argument as a blob. Return
  91188. ** a hexadecimal rendering as text.
  91189. */
  91190. static void hexFunc(
  91191. sqlite3_context *context,
  91192. int argc,
  91193. sqlite3_value **argv
  91194. ){
  91195. int i, n;
  91196. const unsigned char *pBlob;
  91197. char *zHex, *z;
  91198. assert( argc==1 );
  91199. UNUSED_PARAMETER(argc);
  91200. pBlob = sqlite3_value_blob(argv[0]);
  91201. n = sqlite3_value_bytes(argv[0]);
  91202. assert( pBlob==sqlite3_value_blob(argv[0]) ); /* No encoding change */
  91203. z = zHex = contextMalloc(context, ((i64)n)*2 + 1);
  91204. if( zHex ){
  91205. for(i=0; i<n; i++, pBlob++){
  91206. unsigned char c = *pBlob;
  91207. *(z++) = hexdigits[(c>>4)&0xf];
  91208. *(z++) = hexdigits[c&0xf];
  91209. }
  91210. *z = 0;
  91211. sqlite3_result_text(context, zHex, n*2, sqlite3_free);
  91212. }
  91213. }
  91214. /*
  91215. ** The zeroblob(N) function returns a zero-filled blob of size N bytes.
  91216. */
  91217. static void zeroblobFunc(
  91218. sqlite3_context *context,
  91219. int argc,
  91220. sqlite3_value **argv
  91221. ){
  91222. i64 n;
  91223. sqlite3 *db = sqlite3_context_db_handle(context);
  91224. assert( argc==1 );
  91225. UNUSED_PARAMETER(argc);
  91226. n = sqlite3_value_int64(argv[0]);
  91227. testcase( n==db->aLimit[SQLITE_LIMIT_LENGTH] );
  91228. testcase( n==db->aLimit[SQLITE_LIMIT_LENGTH]+1 );
  91229. if( n>db->aLimit[SQLITE_LIMIT_LENGTH] ){
  91230. sqlite3_result_error_toobig(context);
  91231. }else{
  91232. sqlite3_result_zeroblob(context, (int)n); /* IMP: R-00293-64994 */
  91233. }
  91234. }
  91235. /*
  91236. ** The replace() function. Three arguments are all strings: call
  91237. ** them A, B, and C. The result is also a string which is derived
  91238. ** from A by replacing every occurrence of B with C. The match
  91239. ** must be exact. Collating sequences are not used.
  91240. */
  91241. static void replaceFunc(
  91242. sqlite3_context *context,
  91243. int argc,
  91244. sqlite3_value **argv
  91245. ){
  91246. const unsigned char *zStr; /* The input string A */
  91247. const unsigned char *zPattern; /* The pattern string B */
  91248. const unsigned char *zRep; /* The replacement string C */
  91249. unsigned char *zOut; /* The output */
  91250. int nStr; /* Size of zStr */
  91251. int nPattern; /* Size of zPattern */
  91252. int nRep; /* Size of zRep */
  91253. i64 nOut; /* Maximum size of zOut */
  91254. int loopLimit; /* Last zStr[] that might match zPattern[] */
  91255. int i, j; /* Loop counters */
  91256. assert( argc==3 );
  91257. UNUSED_PARAMETER(argc);
  91258. zStr = sqlite3_value_text(argv[0]);
  91259. if( zStr==0 ) return;
  91260. nStr = sqlite3_value_bytes(argv[0]);
  91261. assert( zStr==sqlite3_value_text(argv[0]) ); /* No encoding change */
  91262. zPattern = sqlite3_value_text(argv[1]);
  91263. if( zPattern==0 ){
  91264. assert( sqlite3_value_type(argv[1])==SQLITE_NULL
  91265. || sqlite3_context_db_handle(context)->mallocFailed );
  91266. return;
  91267. }
  91268. if( zPattern[0]==0 ){
  91269. assert( sqlite3_value_type(argv[1])!=SQLITE_NULL );
  91270. sqlite3_result_value(context, argv[0]);
  91271. return;
  91272. }
  91273. nPattern = sqlite3_value_bytes(argv[1]);
  91274. assert( zPattern==sqlite3_value_text(argv[1]) ); /* No encoding change */
  91275. zRep = sqlite3_value_text(argv[2]);
  91276. if( zRep==0 ) return;
  91277. nRep = sqlite3_value_bytes(argv[2]);
  91278. assert( zRep==sqlite3_value_text(argv[2]) );
  91279. nOut = nStr + 1;
  91280. assert( nOut<SQLITE_MAX_LENGTH );
  91281. zOut = contextMalloc(context, (i64)nOut);
  91282. if( zOut==0 ){
  91283. return;
  91284. }
  91285. loopLimit = nStr - nPattern;
  91286. for(i=j=0; i<=loopLimit; i++){
  91287. if( zStr[i]!=zPattern[0] || memcmp(&zStr[i], zPattern, nPattern) ){
  91288. zOut[j++] = zStr[i];
  91289. }else{
  91290. u8 *zOld;
  91291. sqlite3 *db = sqlite3_context_db_handle(context);
  91292. nOut += nRep - nPattern;
  91293. testcase( nOut-1==db->aLimit[SQLITE_LIMIT_LENGTH] );
  91294. testcase( nOut-2==db->aLimit[SQLITE_LIMIT_LENGTH] );
  91295. if( nOut-1>db->aLimit[SQLITE_LIMIT_LENGTH] ){
  91296. sqlite3_result_error_toobig(context);
  91297. sqlite3_free(zOut);
  91298. return;
  91299. }
  91300. zOld = zOut;
  91301. zOut = sqlite3_realloc64(zOut, (int)nOut);
  91302. if( zOut==0 ){
  91303. sqlite3_result_error_nomem(context);
  91304. sqlite3_free(zOld);
  91305. return;
  91306. }
  91307. memcpy(&zOut[j], zRep, nRep);
  91308. j += nRep;
  91309. i += nPattern-1;
  91310. }
  91311. }
  91312. assert( j+nStr-i+1==nOut );
  91313. memcpy(&zOut[j], &zStr[i], nStr-i);
  91314. j += nStr - i;
  91315. assert( j<=nOut );
  91316. zOut[j] = 0;
  91317. sqlite3_result_text(context, (char*)zOut, j, sqlite3_free);
  91318. }
  91319. /*
  91320. ** Implementation of the TRIM(), LTRIM(), and RTRIM() functions.
  91321. ** The userdata is 0x1 for left trim, 0x2 for right trim, 0x3 for both.
  91322. */
  91323. static void trimFunc(
  91324. sqlite3_context *context,
  91325. int argc,
  91326. sqlite3_value **argv
  91327. ){
  91328. const unsigned char *zIn; /* Input string */
  91329. const unsigned char *zCharSet; /* Set of characters to trim */
  91330. int nIn; /* Number of bytes in input */
  91331. int flags; /* 1: trimleft 2: trimright 3: trim */
  91332. int i; /* Loop counter */
  91333. unsigned char *aLen = 0; /* Length of each character in zCharSet */
  91334. unsigned char **azChar = 0; /* Individual characters in zCharSet */
  91335. int nChar; /* Number of characters in zCharSet */
  91336. if( sqlite3_value_type(argv[0])==SQLITE_NULL ){
  91337. return;
  91338. }
  91339. zIn = sqlite3_value_text(argv[0]);
  91340. if( zIn==0 ) return;
  91341. nIn = sqlite3_value_bytes(argv[0]);
  91342. assert( zIn==sqlite3_value_text(argv[0]) );
  91343. if( argc==1 ){
  91344. static const unsigned char lenOne[] = { 1 };
  91345. static unsigned char * const azOne[] = { (u8*)" " };
  91346. nChar = 1;
  91347. aLen = (u8*)lenOne;
  91348. azChar = (unsigned char **)azOne;
  91349. zCharSet = 0;
  91350. }else if( (zCharSet = sqlite3_value_text(argv[1]))==0 ){
  91351. return;
  91352. }else{
  91353. const unsigned char *z;
  91354. for(z=zCharSet, nChar=0; *z; nChar++){
  91355. SQLITE_SKIP_UTF8(z);
  91356. }
  91357. if( nChar>0 ){
  91358. azChar = contextMalloc(context, ((i64)nChar)*(sizeof(char*)+1));
  91359. if( azChar==0 ){
  91360. return;
  91361. }
  91362. aLen = (unsigned char*)&azChar[nChar];
  91363. for(z=zCharSet, nChar=0; *z; nChar++){
  91364. azChar[nChar] = (unsigned char *)z;
  91365. SQLITE_SKIP_UTF8(z);
  91366. aLen[nChar] = (u8)(z - azChar[nChar]);
  91367. }
  91368. }
  91369. }
  91370. if( nChar>0 ){
  91371. flags = SQLITE_PTR_TO_INT(sqlite3_user_data(context));
  91372. if( flags & 1 ){
  91373. while( nIn>0 ){
  91374. int len = 0;
  91375. for(i=0; i<nChar; i++){
  91376. len = aLen[i];
  91377. if( len<=nIn && memcmp(zIn, azChar[i], len)==0 ) break;
  91378. }
  91379. if( i>=nChar ) break;
  91380. zIn += len;
  91381. nIn -= len;
  91382. }
  91383. }
  91384. if( flags & 2 ){
  91385. while( nIn>0 ){
  91386. int len = 0;
  91387. for(i=0; i<nChar; i++){
  91388. len = aLen[i];
  91389. if( len<=nIn && memcmp(&zIn[nIn-len],azChar[i],len)==0 ) break;
  91390. }
  91391. if( i>=nChar ) break;
  91392. nIn -= len;
  91393. }
  91394. }
  91395. if( zCharSet ){
  91396. sqlite3_free(azChar);
  91397. }
  91398. }
  91399. sqlite3_result_text(context, (char*)zIn, nIn, SQLITE_TRANSIENT);
  91400. }
  91401. /* IMP: R-25361-16150 This function is omitted from SQLite by default. It
  91402. ** is only available if the SQLITE_SOUNDEX compile-time option is used
  91403. ** when SQLite is built.
  91404. */
  91405. #ifdef SQLITE_SOUNDEX
  91406. /*
  91407. ** Compute the soundex encoding of a word.
  91408. **
  91409. ** IMP: R-59782-00072 The soundex(X) function returns a string that is the
  91410. ** soundex encoding of the string X.
  91411. */
  91412. static void soundexFunc(
  91413. sqlite3_context *context,
  91414. int argc,
  91415. sqlite3_value **argv
  91416. ){
  91417. char zResult[8];
  91418. const u8 *zIn;
  91419. int i, j;
  91420. static const unsigned char iCode[] = {
  91421. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  91422. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  91423. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  91424. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  91425. 0, 0, 1, 2, 3, 0, 1, 2, 0, 0, 2, 2, 4, 5, 5, 0,
  91426. 1, 2, 6, 2, 3, 0, 1, 0, 2, 0, 2, 0, 0, 0, 0, 0,
  91427. 0, 0, 1, 2, 3, 0, 1, 2, 0, 0, 2, 2, 4, 5, 5, 0,
  91428. 1, 2, 6, 2, 3, 0, 1, 0, 2, 0, 2, 0, 0, 0, 0, 0,
  91429. };
  91430. assert( argc==1 );
  91431. zIn = (u8*)sqlite3_value_text(argv[0]);
  91432. if( zIn==0 ) zIn = (u8*)"";
  91433. for(i=0; zIn[i] && !sqlite3Isalpha(zIn[i]); i++){}
  91434. if( zIn[i] ){
  91435. u8 prevcode = iCode[zIn[i]&0x7f];
  91436. zResult[0] = sqlite3Toupper(zIn[i]);
  91437. for(j=1; j<4 && zIn[i]; i++){
  91438. int code = iCode[zIn[i]&0x7f];
  91439. if( code>0 ){
  91440. if( code!=prevcode ){
  91441. prevcode = code;
  91442. zResult[j++] = code + '0';
  91443. }
  91444. }else{
  91445. prevcode = 0;
  91446. }
  91447. }
  91448. while( j<4 ){
  91449. zResult[j++] = '0';
  91450. }
  91451. zResult[j] = 0;
  91452. sqlite3_result_text(context, zResult, 4, SQLITE_TRANSIENT);
  91453. }else{
  91454. /* IMP: R-64894-50321 The string "?000" is returned if the argument
  91455. ** is NULL or contains no ASCII alphabetic characters. */
  91456. sqlite3_result_text(context, "?000", 4, SQLITE_STATIC);
  91457. }
  91458. }
  91459. #endif /* SQLITE_SOUNDEX */
  91460. #ifndef SQLITE_OMIT_LOAD_EXTENSION
  91461. /*
  91462. ** A function that loads a shared-library extension then returns NULL.
  91463. */
  91464. static void loadExt(sqlite3_context *context, int argc, sqlite3_value **argv){
  91465. const char *zFile = (const char *)sqlite3_value_text(argv[0]);
  91466. const char *zProc;
  91467. sqlite3 *db = sqlite3_context_db_handle(context);
  91468. char *zErrMsg = 0;
  91469. if( argc==2 ){
  91470. zProc = (const char *)sqlite3_value_text(argv[1]);
  91471. }else{
  91472. zProc = 0;
  91473. }
  91474. if( zFile && sqlite3_load_extension(db, zFile, zProc, &zErrMsg) ){
  91475. sqlite3_result_error(context, zErrMsg, -1);
  91476. sqlite3_free(zErrMsg);
  91477. }
  91478. }
  91479. #endif
  91480. /*
  91481. ** An instance of the following structure holds the context of a
  91482. ** sum() or avg() aggregate computation.
  91483. */
  91484. typedef struct SumCtx SumCtx;
  91485. struct SumCtx {
  91486. double rSum; /* Floating point sum */
  91487. i64 iSum; /* Integer sum */
  91488. i64 cnt; /* Number of elements summed */
  91489. u8 overflow; /* True if integer overflow seen */
  91490. u8 approx; /* True if non-integer value was input to the sum */
  91491. };
  91492. /*
  91493. ** Routines used to compute the sum, average, and total.
  91494. **
  91495. ** The SUM() function follows the (broken) SQL standard which means
  91496. ** that it returns NULL if it sums over no inputs. TOTAL returns
  91497. ** 0.0 in that case. In addition, TOTAL always returns a float where
  91498. ** SUM might return an integer if it never encounters a floating point
  91499. ** value. TOTAL never fails, but SUM might through an exception if
  91500. ** it overflows an integer.
  91501. */
  91502. static void sumStep(sqlite3_context *context, int argc, sqlite3_value **argv){
  91503. SumCtx *p;
  91504. int type;
  91505. assert( argc==1 );
  91506. UNUSED_PARAMETER(argc);
  91507. p = sqlite3_aggregate_context(context, sizeof(*p));
  91508. type = sqlite3_value_numeric_type(argv[0]);
  91509. if( p && type!=SQLITE_NULL ){
  91510. p->cnt++;
  91511. if( type==SQLITE_INTEGER ){
  91512. i64 v = sqlite3_value_int64(argv[0]);
  91513. p->rSum += v;
  91514. if( (p->approx|p->overflow)==0 && sqlite3AddInt64(&p->iSum, v) ){
  91515. p->overflow = 1;
  91516. }
  91517. }else{
  91518. p->rSum += sqlite3_value_double(argv[0]);
  91519. p->approx = 1;
  91520. }
  91521. }
  91522. }
  91523. static void sumFinalize(sqlite3_context *context){
  91524. SumCtx *p;
  91525. p = sqlite3_aggregate_context(context, 0);
  91526. if( p && p->cnt>0 ){
  91527. if( p->overflow ){
  91528. sqlite3_result_error(context,"integer overflow",-1);
  91529. }else if( p->approx ){
  91530. sqlite3_result_double(context, p->rSum);
  91531. }else{
  91532. sqlite3_result_int64(context, p->iSum);
  91533. }
  91534. }
  91535. }
  91536. static void avgFinalize(sqlite3_context *context){
  91537. SumCtx *p;
  91538. p = sqlite3_aggregate_context(context, 0);
  91539. if( p && p->cnt>0 ){
  91540. sqlite3_result_double(context, p->rSum/(double)p->cnt);
  91541. }
  91542. }
  91543. static void totalFinalize(sqlite3_context *context){
  91544. SumCtx *p;
  91545. p = sqlite3_aggregate_context(context, 0);
  91546. /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
  91547. sqlite3_result_double(context, p ? p->rSum : (double)0);
  91548. }
  91549. /*
  91550. ** The following structure keeps track of state information for the
  91551. ** count() aggregate function.
  91552. */
  91553. typedef struct CountCtx CountCtx;
  91554. struct CountCtx {
  91555. i64 n;
  91556. };
  91557. /*
  91558. ** Routines to implement the count() aggregate function.
  91559. */
  91560. static void countStep(sqlite3_context *context, int argc, sqlite3_value **argv){
  91561. CountCtx *p;
  91562. p = sqlite3_aggregate_context(context, sizeof(*p));
  91563. if( (argc==0 || SQLITE_NULL!=sqlite3_value_type(argv[0])) && p ){
  91564. p->n++;
  91565. }
  91566. #ifndef SQLITE_OMIT_DEPRECATED
  91567. /* The sqlite3_aggregate_count() function is deprecated. But just to make
  91568. ** sure it still operates correctly, verify that its count agrees with our
  91569. ** internal count when using count(*) and when the total count can be
  91570. ** expressed as a 32-bit integer. */
  91571. assert( argc==1 || p==0 || p->n>0x7fffffff
  91572. || p->n==sqlite3_aggregate_count(context) );
  91573. #endif
  91574. }
  91575. static void countFinalize(sqlite3_context *context){
  91576. CountCtx *p;
  91577. p = sqlite3_aggregate_context(context, 0);
  91578. sqlite3_result_int64(context, p ? p->n : 0);
  91579. }
  91580. /*
  91581. ** Routines to implement min() and max() aggregate functions.
  91582. */
  91583. static void minmaxStep(
  91584. sqlite3_context *context,
  91585. int NotUsed,
  91586. sqlite3_value **argv
  91587. ){
  91588. Mem *pArg = (Mem *)argv[0];
  91589. Mem *pBest;
  91590. UNUSED_PARAMETER(NotUsed);
  91591. pBest = (Mem *)sqlite3_aggregate_context(context, sizeof(*pBest));
  91592. if( !pBest ) return;
  91593. if( sqlite3_value_type(argv[0])==SQLITE_NULL ){
  91594. if( pBest->flags ) sqlite3SkipAccumulatorLoad(context);
  91595. }else if( pBest->flags ){
  91596. int max;
  91597. int cmp;
  91598. CollSeq *pColl = sqlite3GetFuncCollSeq(context);
  91599. /* This step function is used for both the min() and max() aggregates,
  91600. ** the only difference between the two being that the sense of the
  91601. ** comparison is inverted. For the max() aggregate, the
  91602. ** sqlite3_user_data() function returns (void *)-1. For min() it
  91603. ** returns (void *)db, where db is the sqlite3* database pointer.
  91604. ** Therefore the next statement sets variable 'max' to 1 for the max()
  91605. ** aggregate, or 0 for min().
  91606. */
  91607. max = sqlite3_user_data(context)!=0;
  91608. cmp = sqlite3MemCompare(pBest, pArg, pColl);
  91609. if( (max && cmp<0) || (!max && cmp>0) ){
  91610. sqlite3VdbeMemCopy(pBest, pArg);
  91611. }else{
  91612. sqlite3SkipAccumulatorLoad(context);
  91613. }
  91614. }else{
  91615. pBest->db = sqlite3_context_db_handle(context);
  91616. sqlite3VdbeMemCopy(pBest, pArg);
  91617. }
  91618. }
  91619. static void minMaxFinalize(sqlite3_context *context){
  91620. sqlite3_value *pRes;
  91621. pRes = (sqlite3_value *)sqlite3_aggregate_context(context, 0);
  91622. if( pRes ){
  91623. if( pRes->flags ){
  91624. sqlite3_result_value(context, pRes);
  91625. }
  91626. sqlite3VdbeMemRelease(pRes);
  91627. }
  91628. }
  91629. /*
  91630. ** group_concat(EXPR, ?SEPARATOR?)
  91631. */
  91632. static void groupConcatStep(
  91633. sqlite3_context *context,
  91634. int argc,
  91635. sqlite3_value **argv
  91636. ){
  91637. const char *zVal;
  91638. StrAccum *pAccum;
  91639. const char *zSep;
  91640. int nVal, nSep;
  91641. assert( argc==1 || argc==2 );
  91642. if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
  91643. pAccum = (StrAccum*)sqlite3_aggregate_context(context, sizeof(*pAccum));
  91644. if( pAccum ){
  91645. sqlite3 *db = sqlite3_context_db_handle(context);
  91646. int firstTerm = pAccum->mxAlloc==0;
  91647. pAccum->mxAlloc = db->aLimit[SQLITE_LIMIT_LENGTH];
  91648. if( !firstTerm ){
  91649. if( argc==2 ){
  91650. zSep = (char*)sqlite3_value_text(argv[1]);
  91651. nSep = sqlite3_value_bytes(argv[1]);
  91652. }else{
  91653. zSep = ",";
  91654. nSep = 1;
  91655. }
  91656. if( nSep ) sqlite3StrAccumAppend(pAccum, zSep, nSep);
  91657. }
  91658. zVal = (char*)sqlite3_value_text(argv[0]);
  91659. nVal = sqlite3_value_bytes(argv[0]);
  91660. if( zVal ) sqlite3StrAccumAppend(pAccum, zVal, nVal);
  91661. }
  91662. }
  91663. static void groupConcatFinalize(sqlite3_context *context){
  91664. StrAccum *pAccum;
  91665. pAccum = sqlite3_aggregate_context(context, 0);
  91666. if( pAccum ){
  91667. if( pAccum->accError==STRACCUM_TOOBIG ){
  91668. sqlite3_result_error_toobig(context);
  91669. }else if( pAccum->accError==STRACCUM_NOMEM ){
  91670. sqlite3_result_error_nomem(context);
  91671. }else{
  91672. sqlite3_result_text(context, sqlite3StrAccumFinish(pAccum), -1,
  91673. sqlite3_free);
  91674. }
  91675. }
  91676. }
  91677. /*
  91678. ** This routine does per-connection function registration. Most
  91679. ** of the built-in functions above are part of the global function set.
  91680. ** This routine only deals with those that are not global.
  91681. */
  91682. SQLITE_PRIVATE void sqlite3RegisterBuiltinFunctions(sqlite3 *db){
  91683. int rc = sqlite3_overload_function(db, "MATCH", 2);
  91684. assert( rc==SQLITE_NOMEM || rc==SQLITE_OK );
  91685. if( rc==SQLITE_NOMEM ){
  91686. db->mallocFailed = 1;
  91687. }
  91688. }
  91689. /*
  91690. ** Set the LIKEOPT flag on the 2-argument function with the given name.
  91691. */
  91692. static void setLikeOptFlag(sqlite3 *db, const char *zName, u8 flagVal){
  91693. FuncDef *pDef;
  91694. pDef = sqlite3FindFunction(db, zName, sqlite3Strlen30(zName),
  91695. 2, SQLITE_UTF8, 0);
  91696. if( ALWAYS(pDef) ){
  91697. pDef->funcFlags |= flagVal;
  91698. }
  91699. }
  91700. /*
  91701. ** Register the built-in LIKE and GLOB functions. The caseSensitive
  91702. ** parameter determines whether or not the LIKE operator is case
  91703. ** sensitive. GLOB is always case sensitive.
  91704. */
  91705. SQLITE_PRIVATE void sqlite3RegisterLikeFunctions(sqlite3 *db, int caseSensitive){
  91706. struct compareInfo *pInfo;
  91707. if( caseSensitive ){
  91708. pInfo = (struct compareInfo*)&likeInfoAlt;
  91709. }else{
  91710. pInfo = (struct compareInfo*)&likeInfoNorm;
  91711. }
  91712. sqlite3CreateFunc(db, "like", 2, SQLITE_UTF8, pInfo, likeFunc, 0, 0, 0);
  91713. sqlite3CreateFunc(db, "like", 3, SQLITE_UTF8, pInfo, likeFunc, 0, 0, 0);
  91714. sqlite3CreateFunc(db, "glob", 2, SQLITE_UTF8,
  91715. (struct compareInfo*)&globInfo, likeFunc, 0, 0, 0);
  91716. setLikeOptFlag(db, "glob", SQLITE_FUNC_LIKE | SQLITE_FUNC_CASE);
  91717. setLikeOptFlag(db, "like",
  91718. caseSensitive ? (SQLITE_FUNC_LIKE | SQLITE_FUNC_CASE) : SQLITE_FUNC_LIKE);
  91719. }
  91720. /*
  91721. ** pExpr points to an expression which implements a function. If
  91722. ** it is appropriate to apply the LIKE optimization to that function
  91723. ** then set aWc[0] through aWc[2] to the wildcard characters and
  91724. ** return TRUE. If the function is not a LIKE-style function then
  91725. ** return FALSE.
  91726. **
  91727. ** *pIsNocase is set to true if uppercase and lowercase are equivalent for
  91728. ** the function (default for LIKE). If the function makes the distinction
  91729. ** between uppercase and lowercase (as does GLOB) then *pIsNocase is set to
  91730. ** false.
  91731. */
  91732. SQLITE_PRIVATE int sqlite3IsLikeFunction(sqlite3 *db, Expr *pExpr, int *pIsNocase, char *aWc){
  91733. FuncDef *pDef;
  91734. if( pExpr->op!=TK_FUNCTION
  91735. || !pExpr->x.pList
  91736. || pExpr->x.pList->nExpr!=2
  91737. ){
  91738. return 0;
  91739. }
  91740. assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
  91741. pDef = sqlite3FindFunction(db, pExpr->u.zToken,
  91742. sqlite3Strlen30(pExpr->u.zToken),
  91743. 2, SQLITE_UTF8, 0);
  91744. if( NEVER(pDef==0) || (pDef->funcFlags & SQLITE_FUNC_LIKE)==0 ){
  91745. return 0;
  91746. }
  91747. /* The memcpy() statement assumes that the wildcard characters are
  91748. ** the first three statements in the compareInfo structure. The
  91749. ** asserts() that follow verify that assumption
  91750. */
  91751. memcpy(aWc, pDef->pUserData, 3);
  91752. assert( (char*)&likeInfoAlt == (char*)&likeInfoAlt.matchAll );
  91753. assert( &((char*)&likeInfoAlt)[1] == (char*)&likeInfoAlt.matchOne );
  91754. assert( &((char*)&likeInfoAlt)[2] == (char*)&likeInfoAlt.matchSet );
  91755. *pIsNocase = (pDef->funcFlags & SQLITE_FUNC_CASE)==0;
  91756. return 1;
  91757. }
  91758. /*
  91759. ** All of the FuncDef structures in the aBuiltinFunc[] array above
  91760. ** to the global function hash table. This occurs at start-time (as
  91761. ** a consequence of calling sqlite3_initialize()).
  91762. **
  91763. ** After this routine runs
  91764. */
  91765. SQLITE_PRIVATE void sqlite3RegisterGlobalFunctions(void){
  91766. /*
  91767. ** The following array holds FuncDef structures for all of the functions
  91768. ** defined in this file.
  91769. **
  91770. ** The array cannot be constant since changes are made to the
  91771. ** FuncDef.pHash elements at start-time. The elements of this array
  91772. ** are read-only after initialization is complete.
  91773. */
  91774. static SQLITE_WSD FuncDef aBuiltinFunc[] = {
  91775. FUNCTION(ltrim, 1, 1, 0, trimFunc ),
  91776. FUNCTION(ltrim, 2, 1, 0, trimFunc ),
  91777. FUNCTION(rtrim, 1, 2, 0, trimFunc ),
  91778. FUNCTION(rtrim, 2, 2, 0, trimFunc ),
  91779. FUNCTION(trim, 1, 3, 0, trimFunc ),
  91780. FUNCTION(trim, 2, 3, 0, trimFunc ),
  91781. FUNCTION(min, -1, 0, 1, minmaxFunc ),
  91782. FUNCTION(min, 0, 0, 1, 0 ),
  91783. AGGREGATE2(min, 1, 0, 1, minmaxStep, minMaxFinalize,
  91784. SQLITE_FUNC_MINMAX ),
  91785. FUNCTION(max, -1, 1, 1, minmaxFunc ),
  91786. FUNCTION(max, 0, 1, 1, 0 ),
  91787. AGGREGATE2(max, 1, 1, 1, minmaxStep, minMaxFinalize,
  91788. SQLITE_FUNC_MINMAX ),
  91789. FUNCTION2(typeof, 1, 0, 0, typeofFunc, SQLITE_FUNC_TYPEOF),
  91790. FUNCTION2(length, 1, 0, 0, lengthFunc, SQLITE_FUNC_LENGTH),
  91791. FUNCTION(instr, 2, 0, 0, instrFunc ),
  91792. FUNCTION(substr, 2, 0, 0, substrFunc ),
  91793. FUNCTION(substr, 3, 0, 0, substrFunc ),
  91794. FUNCTION(printf, -1, 0, 0, printfFunc ),
  91795. FUNCTION(unicode, 1, 0, 0, unicodeFunc ),
  91796. FUNCTION(char, -1, 0, 0, charFunc ),
  91797. FUNCTION(abs, 1, 0, 0, absFunc ),
  91798. #ifndef SQLITE_OMIT_FLOATING_POINT
  91799. FUNCTION(round, 1, 0, 0, roundFunc ),
  91800. FUNCTION(round, 2, 0, 0, roundFunc ),
  91801. #endif
  91802. FUNCTION(upper, 1, 0, 0, upperFunc ),
  91803. FUNCTION(lower, 1, 0, 0, lowerFunc ),
  91804. FUNCTION(coalesce, 1, 0, 0, 0 ),
  91805. FUNCTION(coalesce, 0, 0, 0, 0 ),
  91806. FUNCTION2(coalesce, -1, 0, 0, noopFunc, SQLITE_FUNC_COALESCE),
  91807. FUNCTION(hex, 1, 0, 0, hexFunc ),
  91808. FUNCTION2(ifnull, 2, 0, 0, noopFunc, SQLITE_FUNC_COALESCE),
  91809. FUNCTION2(unlikely, 1, 0, 0, noopFunc, SQLITE_FUNC_UNLIKELY),
  91810. FUNCTION2(likelihood, 2, 0, 0, noopFunc, SQLITE_FUNC_UNLIKELY),
  91811. FUNCTION2(likely, 1, 0, 0, noopFunc, SQLITE_FUNC_UNLIKELY),
  91812. VFUNCTION(random, 0, 0, 0, randomFunc ),
  91813. VFUNCTION(randomblob, 1, 0, 0, randomBlob ),
  91814. FUNCTION(nullif, 2, 0, 1, nullifFunc ),
  91815. FUNCTION(sqlite_version, 0, 0, 0, versionFunc ),
  91816. FUNCTION(sqlite_source_id, 0, 0, 0, sourceidFunc ),
  91817. FUNCTION(sqlite_log, 2, 0, 0, errlogFunc ),
  91818. #if SQLITE_USER_AUTHENTICATION
  91819. FUNCTION(sqlite_crypt, 2, 0, 0, sqlite3CryptFunc ),
  91820. #endif
  91821. #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
  91822. FUNCTION(sqlite_compileoption_used,1, 0, 0, compileoptionusedFunc ),
  91823. FUNCTION(sqlite_compileoption_get, 1, 0, 0, compileoptiongetFunc ),
  91824. #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
  91825. FUNCTION(quote, 1, 0, 0, quoteFunc ),
  91826. VFUNCTION(last_insert_rowid, 0, 0, 0, last_insert_rowid),
  91827. VFUNCTION(changes, 0, 0, 0, changes ),
  91828. VFUNCTION(total_changes, 0, 0, 0, total_changes ),
  91829. FUNCTION(replace, 3, 0, 0, replaceFunc ),
  91830. FUNCTION(zeroblob, 1, 0, 0, zeroblobFunc ),
  91831. #ifdef SQLITE_SOUNDEX
  91832. FUNCTION(soundex, 1, 0, 0, soundexFunc ),
  91833. #endif
  91834. #ifndef SQLITE_OMIT_LOAD_EXTENSION
  91835. FUNCTION(load_extension, 1, 0, 0, loadExt ),
  91836. FUNCTION(load_extension, 2, 0, 0, loadExt ),
  91837. #endif
  91838. AGGREGATE(sum, 1, 0, 0, sumStep, sumFinalize ),
  91839. AGGREGATE(total, 1, 0, 0, sumStep, totalFinalize ),
  91840. AGGREGATE(avg, 1, 0, 0, sumStep, avgFinalize ),
  91841. AGGREGATE2(count, 0, 0, 0, countStep, countFinalize,
  91842. SQLITE_FUNC_COUNT ),
  91843. AGGREGATE(count, 1, 0, 0, countStep, countFinalize ),
  91844. AGGREGATE(group_concat, 1, 0, 0, groupConcatStep, groupConcatFinalize),
  91845. AGGREGATE(group_concat, 2, 0, 0, groupConcatStep, groupConcatFinalize),
  91846. LIKEFUNC(glob, 2, &globInfo, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE),
  91847. #ifdef SQLITE_CASE_SENSITIVE_LIKE
  91848. LIKEFUNC(like, 2, &likeInfoAlt, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE),
  91849. LIKEFUNC(like, 3, &likeInfoAlt, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE),
  91850. #else
  91851. LIKEFUNC(like, 2, &likeInfoNorm, SQLITE_FUNC_LIKE),
  91852. LIKEFUNC(like, 3, &likeInfoNorm, SQLITE_FUNC_LIKE),
  91853. #endif
  91854. };
  91855. int i;
  91856. FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
  91857. FuncDef *aFunc = (FuncDef*)&GLOBAL(FuncDef, aBuiltinFunc);
  91858. for(i=0; i<ArraySize(aBuiltinFunc); i++){
  91859. sqlite3FuncDefInsert(pHash, &aFunc[i]);
  91860. }
  91861. sqlite3RegisterDateTimeFunctions();
  91862. #ifndef SQLITE_OMIT_ALTERTABLE
  91863. sqlite3AlterFunctions();
  91864. #endif
  91865. #if defined(SQLITE_ENABLE_STAT3) || defined(SQLITE_ENABLE_STAT4)
  91866. sqlite3AnalyzeFunctions();
  91867. #endif
  91868. }
  91869. /************** End of func.c ************************************************/
  91870. /************** Begin file fkey.c ********************************************/
  91871. /*
  91872. **
  91873. ** The author disclaims copyright to this source code. In place of
  91874. ** a legal notice, here is a blessing:
  91875. **
  91876. ** May you do good and not evil.
  91877. ** May you find forgiveness for yourself and forgive others.
  91878. ** May you share freely, never taking more than you give.
  91879. **
  91880. *************************************************************************
  91881. ** This file contains code used by the compiler to add foreign key
  91882. ** support to compiled SQL statements.
  91883. */
  91884. #ifndef SQLITE_OMIT_FOREIGN_KEY
  91885. #ifndef SQLITE_OMIT_TRIGGER
  91886. /*
  91887. ** Deferred and Immediate FKs
  91888. ** --------------------------
  91889. **
  91890. ** Foreign keys in SQLite come in two flavours: deferred and immediate.
  91891. ** If an immediate foreign key constraint is violated,
  91892. ** SQLITE_CONSTRAINT_FOREIGNKEY is returned and the current
  91893. ** statement transaction rolled back. If a
  91894. ** deferred foreign key constraint is violated, no action is taken
  91895. ** immediately. However if the application attempts to commit the
  91896. ** transaction before fixing the constraint violation, the attempt fails.
  91897. **
  91898. ** Deferred constraints are implemented using a simple counter associated
  91899. ** with the database handle. The counter is set to zero each time a
  91900. ** database transaction is opened. Each time a statement is executed
  91901. ** that causes a foreign key violation, the counter is incremented. Each
  91902. ** time a statement is executed that removes an existing violation from
  91903. ** the database, the counter is decremented. When the transaction is
  91904. ** committed, the commit fails if the current value of the counter is
  91905. ** greater than zero. This scheme has two big drawbacks:
  91906. **
  91907. ** * When a commit fails due to a deferred foreign key constraint,
  91908. ** there is no way to tell which foreign constraint is not satisfied,
  91909. ** or which row it is not satisfied for.
  91910. **
  91911. ** * If the database contains foreign key violations when the
  91912. ** transaction is opened, this may cause the mechanism to malfunction.
  91913. **
  91914. ** Despite these problems, this approach is adopted as it seems simpler
  91915. ** than the alternatives.
  91916. **
  91917. ** INSERT operations:
  91918. **
  91919. ** I.1) For each FK for which the table is the child table, search
  91920. ** the parent table for a match. If none is found increment the
  91921. ** constraint counter.
  91922. **
  91923. ** I.2) For each FK for which the table is the parent table,
  91924. ** search the child table for rows that correspond to the new
  91925. ** row in the parent table. Decrement the counter for each row
  91926. ** found (as the constraint is now satisfied).
  91927. **
  91928. ** DELETE operations:
  91929. **
  91930. ** D.1) For each FK for which the table is the child table,
  91931. ** search the parent table for a row that corresponds to the
  91932. ** deleted row in the child table. If such a row is not found,
  91933. ** decrement the counter.
  91934. **
  91935. ** D.2) For each FK for which the table is the parent table, search
  91936. ** the child table for rows that correspond to the deleted row
  91937. ** in the parent table. For each found increment the counter.
  91938. **
  91939. ** UPDATE operations:
  91940. **
  91941. ** An UPDATE command requires that all 4 steps above are taken, but only
  91942. ** for FK constraints for which the affected columns are actually
  91943. ** modified (values must be compared at runtime).
  91944. **
  91945. ** Note that I.1 and D.1 are very similar operations, as are I.2 and D.2.
  91946. ** This simplifies the implementation a bit.
  91947. **
  91948. ** For the purposes of immediate FK constraints, the OR REPLACE conflict
  91949. ** resolution is considered to delete rows before the new row is inserted.
  91950. ** If a delete caused by OR REPLACE violates an FK constraint, an exception
  91951. ** is thrown, even if the FK constraint would be satisfied after the new
  91952. ** row is inserted.
  91953. **
  91954. ** Immediate constraints are usually handled similarly. The only difference
  91955. ** is that the counter used is stored as part of each individual statement
  91956. ** object (struct Vdbe). If, after the statement has run, its immediate
  91957. ** constraint counter is greater than zero,
  91958. ** it returns SQLITE_CONSTRAINT_FOREIGNKEY
  91959. ** and the statement transaction is rolled back. An exception is an INSERT
  91960. ** statement that inserts a single row only (no triggers). In this case,
  91961. ** instead of using a counter, an exception is thrown immediately if the
  91962. ** INSERT violates a foreign key constraint. This is necessary as such
  91963. ** an INSERT does not open a statement transaction.
  91964. **
  91965. ** TODO: How should dropping a table be handled? How should renaming a
  91966. ** table be handled?
  91967. **
  91968. **
  91969. ** Query API Notes
  91970. ** ---------------
  91971. **
  91972. ** Before coding an UPDATE or DELETE row operation, the code-generator
  91973. ** for those two operations needs to know whether or not the operation
  91974. ** requires any FK processing and, if so, which columns of the original
  91975. ** row are required by the FK processing VDBE code (i.e. if FKs were
  91976. ** implemented using triggers, which of the old.* columns would be
  91977. ** accessed). No information is required by the code-generator before
  91978. ** coding an INSERT operation. The functions used by the UPDATE/DELETE
  91979. ** generation code to query for this information are:
  91980. **
  91981. ** sqlite3FkRequired() - Test to see if FK processing is required.
  91982. ** sqlite3FkOldmask() - Query for the set of required old.* columns.
  91983. **
  91984. **
  91985. ** Externally accessible module functions
  91986. ** --------------------------------------
  91987. **
  91988. ** sqlite3FkCheck() - Check for foreign key violations.
  91989. ** sqlite3FkActions() - Code triggers for ON UPDATE/ON DELETE actions.
  91990. ** sqlite3FkDelete() - Delete an FKey structure.
  91991. */
  91992. /*
  91993. ** VDBE Calling Convention
  91994. ** -----------------------
  91995. **
  91996. ** Example:
  91997. **
  91998. ** For the following INSERT statement:
  91999. **
  92000. ** CREATE TABLE t1(a, b INTEGER PRIMARY KEY, c);
  92001. ** INSERT INTO t1 VALUES(1, 2, 3.1);
  92002. **
  92003. ** Register (x): 2 (type integer)
  92004. ** Register (x+1): 1 (type integer)
  92005. ** Register (x+2): NULL (type NULL)
  92006. ** Register (x+3): 3.1 (type real)
  92007. */
  92008. /*
  92009. ** A foreign key constraint requires that the key columns in the parent
  92010. ** table are collectively subject to a UNIQUE or PRIMARY KEY constraint.
  92011. ** Given that pParent is the parent table for foreign key constraint pFKey,
  92012. ** search the schema for a unique index on the parent key columns.
  92013. **
  92014. ** If successful, zero is returned. If the parent key is an INTEGER PRIMARY
  92015. ** KEY column, then output variable *ppIdx is set to NULL. Otherwise, *ppIdx
  92016. ** is set to point to the unique index.
  92017. **
  92018. ** If the parent key consists of a single column (the foreign key constraint
  92019. ** is not a composite foreign key), output variable *paiCol is set to NULL.
  92020. ** Otherwise, it is set to point to an allocated array of size N, where
  92021. ** N is the number of columns in the parent key. The first element of the
  92022. ** array is the index of the child table column that is mapped by the FK
  92023. ** constraint to the parent table column stored in the left-most column
  92024. ** of index *ppIdx. The second element of the array is the index of the
  92025. ** child table column that corresponds to the second left-most column of
  92026. ** *ppIdx, and so on.
  92027. **
  92028. ** If the required index cannot be found, either because:
  92029. **
  92030. ** 1) The named parent key columns do not exist, or
  92031. **
  92032. ** 2) The named parent key columns do exist, but are not subject to a
  92033. ** UNIQUE or PRIMARY KEY constraint, or
  92034. **
  92035. ** 3) No parent key columns were provided explicitly as part of the
  92036. ** foreign key definition, and the parent table does not have a
  92037. ** PRIMARY KEY, or
  92038. **
  92039. ** 4) No parent key columns were provided explicitly as part of the
  92040. ** foreign key definition, and the PRIMARY KEY of the parent table
  92041. ** consists of a different number of columns to the child key in
  92042. ** the child table.
  92043. **
  92044. ** then non-zero is returned, and a "foreign key mismatch" error loaded
  92045. ** into pParse. If an OOM error occurs, non-zero is returned and the
  92046. ** pParse->db->mallocFailed flag is set.
  92047. */
  92048. SQLITE_PRIVATE int sqlite3FkLocateIndex(
  92049. Parse *pParse, /* Parse context to store any error in */
  92050. Table *pParent, /* Parent table of FK constraint pFKey */
  92051. FKey *pFKey, /* Foreign key to find index for */
  92052. Index **ppIdx, /* OUT: Unique index on parent table */
  92053. int **paiCol /* OUT: Map of index columns in pFKey */
  92054. ){
  92055. Index *pIdx = 0; /* Value to return via *ppIdx */
  92056. int *aiCol = 0; /* Value to return via *paiCol */
  92057. int nCol = pFKey->nCol; /* Number of columns in parent key */
  92058. char *zKey = pFKey->aCol[0].zCol; /* Name of left-most parent key column */
  92059. /* The caller is responsible for zeroing output parameters. */
  92060. assert( ppIdx && *ppIdx==0 );
  92061. assert( !paiCol || *paiCol==0 );
  92062. assert( pParse );
  92063. /* If this is a non-composite (single column) foreign key, check if it
  92064. ** maps to the INTEGER PRIMARY KEY of table pParent. If so, leave *ppIdx
  92065. ** and *paiCol set to zero and return early.
  92066. **
  92067. ** Otherwise, for a composite foreign key (more than one column), allocate
  92068. ** space for the aiCol array (returned via output parameter *paiCol).
  92069. ** Non-composite foreign keys do not require the aiCol array.
  92070. */
  92071. if( nCol==1 ){
  92072. /* The FK maps to the IPK if any of the following are true:
  92073. **
  92074. ** 1) There is an INTEGER PRIMARY KEY column and the FK is implicitly
  92075. ** mapped to the primary key of table pParent, or
  92076. ** 2) The FK is explicitly mapped to a column declared as INTEGER
  92077. ** PRIMARY KEY.
  92078. */
  92079. if( pParent->iPKey>=0 ){
  92080. if( !zKey ) return 0;
  92081. if( !sqlite3StrICmp(pParent->aCol[pParent->iPKey].zName, zKey) ) return 0;
  92082. }
  92083. }else if( paiCol ){
  92084. assert( nCol>1 );
  92085. aiCol = (int *)sqlite3DbMallocRaw(pParse->db, nCol*sizeof(int));
  92086. if( !aiCol ) return 1;
  92087. *paiCol = aiCol;
  92088. }
  92089. for(pIdx=pParent->pIndex; pIdx; pIdx=pIdx->pNext){
  92090. if( pIdx->nKeyCol==nCol && IsUniqueIndex(pIdx) ){
  92091. /* pIdx is a UNIQUE index (or a PRIMARY KEY) and has the right number
  92092. ** of columns. If each indexed column corresponds to a foreign key
  92093. ** column of pFKey, then this index is a winner. */
  92094. if( zKey==0 ){
  92095. /* If zKey is NULL, then this foreign key is implicitly mapped to
  92096. ** the PRIMARY KEY of table pParent. The PRIMARY KEY index may be
  92097. ** identified by the test. */
  92098. if( IsPrimaryKeyIndex(pIdx) ){
  92099. if( aiCol ){
  92100. int i;
  92101. for(i=0; i<nCol; i++) aiCol[i] = pFKey->aCol[i].iFrom;
  92102. }
  92103. break;
  92104. }
  92105. }else{
  92106. /* If zKey is non-NULL, then this foreign key was declared to
  92107. ** map to an explicit list of columns in table pParent. Check if this
  92108. ** index matches those columns. Also, check that the index uses
  92109. ** the default collation sequences for each column. */
  92110. int i, j;
  92111. for(i=0; i<nCol; i++){
  92112. i16 iCol = pIdx->aiColumn[i]; /* Index of column in parent tbl */
  92113. char *zDfltColl; /* Def. collation for column */
  92114. char *zIdxCol; /* Name of indexed column */
  92115. /* If the index uses a collation sequence that is different from
  92116. ** the default collation sequence for the column, this index is
  92117. ** unusable. Bail out early in this case. */
  92118. zDfltColl = pParent->aCol[iCol].zColl;
  92119. if( !zDfltColl ){
  92120. zDfltColl = "BINARY";
  92121. }
  92122. if( sqlite3StrICmp(pIdx->azColl[i], zDfltColl) ) break;
  92123. zIdxCol = pParent->aCol[iCol].zName;
  92124. for(j=0; j<nCol; j++){
  92125. if( sqlite3StrICmp(pFKey->aCol[j].zCol, zIdxCol)==0 ){
  92126. if( aiCol ) aiCol[i] = pFKey->aCol[j].iFrom;
  92127. break;
  92128. }
  92129. }
  92130. if( j==nCol ) break;
  92131. }
  92132. if( i==nCol ) break; /* pIdx is usable */
  92133. }
  92134. }
  92135. }
  92136. if( !pIdx ){
  92137. if( !pParse->disableTriggers ){
  92138. sqlite3ErrorMsg(pParse,
  92139. "foreign key mismatch - \"%w\" referencing \"%w\"",
  92140. pFKey->pFrom->zName, pFKey->zTo);
  92141. }
  92142. sqlite3DbFree(pParse->db, aiCol);
  92143. return 1;
  92144. }
  92145. *ppIdx = pIdx;
  92146. return 0;
  92147. }
  92148. /*
  92149. ** This function is called when a row is inserted into or deleted from the
  92150. ** child table of foreign key constraint pFKey. If an SQL UPDATE is executed
  92151. ** on the child table of pFKey, this function is invoked twice for each row
  92152. ** affected - once to "delete" the old row, and then again to "insert" the
  92153. ** new row.
  92154. **
  92155. ** Each time it is called, this function generates VDBE code to locate the
  92156. ** row in the parent table that corresponds to the row being inserted into
  92157. ** or deleted from the child table. If the parent row can be found, no
  92158. ** special action is taken. Otherwise, if the parent row can *not* be
  92159. ** found in the parent table:
  92160. **
  92161. ** Operation | FK type | Action taken
  92162. ** --------------------------------------------------------------------------
  92163. ** INSERT immediate Increment the "immediate constraint counter".
  92164. **
  92165. ** DELETE immediate Decrement the "immediate constraint counter".
  92166. **
  92167. ** INSERT deferred Increment the "deferred constraint counter".
  92168. **
  92169. ** DELETE deferred Decrement the "deferred constraint counter".
  92170. **
  92171. ** These operations are identified in the comment at the top of this file
  92172. ** (fkey.c) as "I.1" and "D.1".
  92173. */
  92174. static void fkLookupParent(
  92175. Parse *pParse, /* Parse context */
  92176. int iDb, /* Index of database housing pTab */
  92177. Table *pTab, /* Parent table of FK pFKey */
  92178. Index *pIdx, /* Unique index on parent key columns in pTab */
  92179. FKey *pFKey, /* Foreign key constraint */
  92180. int *aiCol, /* Map from parent key columns to child table columns */
  92181. int regData, /* Address of array containing child table row */
  92182. int nIncr, /* Increment constraint counter by this */
  92183. int isIgnore /* If true, pretend pTab contains all NULL values */
  92184. ){
  92185. int i; /* Iterator variable */
  92186. Vdbe *v = sqlite3GetVdbe(pParse); /* Vdbe to add code to */
  92187. int iCur = pParse->nTab - 1; /* Cursor number to use */
  92188. int iOk = sqlite3VdbeMakeLabel(v); /* jump here if parent key found */
  92189. /* If nIncr is less than zero, then check at runtime if there are any
  92190. ** outstanding constraints to resolve. If there are not, there is no need
  92191. ** to check if deleting this row resolves any outstanding violations.
  92192. **
  92193. ** Check if any of the key columns in the child table row are NULL. If
  92194. ** any are, then the constraint is considered satisfied. No need to
  92195. ** search for a matching row in the parent table. */
  92196. if( nIncr<0 ){
  92197. sqlite3VdbeAddOp2(v, OP_FkIfZero, pFKey->isDeferred, iOk);
  92198. VdbeCoverage(v);
  92199. }
  92200. for(i=0; i<pFKey->nCol; i++){
  92201. int iReg = aiCol[i] + regData + 1;
  92202. sqlite3VdbeAddOp2(v, OP_IsNull, iReg, iOk); VdbeCoverage(v);
  92203. }
  92204. if( isIgnore==0 ){
  92205. if( pIdx==0 ){
  92206. /* If pIdx is NULL, then the parent key is the INTEGER PRIMARY KEY
  92207. ** column of the parent table (table pTab). */
  92208. int iMustBeInt; /* Address of MustBeInt instruction */
  92209. int regTemp = sqlite3GetTempReg(pParse);
  92210. /* Invoke MustBeInt to coerce the child key value to an integer (i.e.
  92211. ** apply the affinity of the parent key). If this fails, then there
  92212. ** is no matching parent key. Before using MustBeInt, make a copy of
  92213. ** the value. Otherwise, the value inserted into the child key column
  92214. ** will have INTEGER affinity applied to it, which may not be correct. */
  92215. sqlite3VdbeAddOp2(v, OP_SCopy, aiCol[0]+1+regData, regTemp);
  92216. iMustBeInt = sqlite3VdbeAddOp2(v, OP_MustBeInt, regTemp, 0);
  92217. VdbeCoverage(v);
  92218. /* If the parent table is the same as the child table, and we are about
  92219. ** to increment the constraint-counter (i.e. this is an INSERT operation),
  92220. ** then check if the row being inserted matches itself. If so, do not
  92221. ** increment the constraint-counter. */
  92222. if( pTab==pFKey->pFrom && nIncr==1 ){
  92223. sqlite3VdbeAddOp3(v, OP_Eq, regData, iOk, regTemp); VdbeCoverage(v);
  92224. sqlite3VdbeChangeP5(v, SQLITE_NOTNULL);
  92225. }
  92226. sqlite3OpenTable(pParse, iCur, iDb, pTab, OP_OpenRead);
  92227. sqlite3VdbeAddOp3(v, OP_NotExists, iCur, 0, regTemp); VdbeCoverage(v);
  92228. sqlite3VdbeAddOp2(v, OP_Goto, 0, iOk);
  92229. sqlite3VdbeJumpHere(v, sqlite3VdbeCurrentAddr(v)-2);
  92230. sqlite3VdbeJumpHere(v, iMustBeInt);
  92231. sqlite3ReleaseTempReg(pParse, regTemp);
  92232. }else{
  92233. int nCol = pFKey->nCol;
  92234. int regTemp = sqlite3GetTempRange(pParse, nCol);
  92235. int regRec = sqlite3GetTempReg(pParse);
  92236. sqlite3VdbeAddOp3(v, OP_OpenRead, iCur, pIdx->tnum, iDb);
  92237. sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
  92238. for(i=0; i<nCol; i++){
  92239. sqlite3VdbeAddOp2(v, OP_Copy, aiCol[i]+1+regData, regTemp+i);
  92240. }
  92241. /* If the parent table is the same as the child table, and we are about
  92242. ** to increment the constraint-counter (i.e. this is an INSERT operation),
  92243. ** then check if the row being inserted matches itself. If so, do not
  92244. ** increment the constraint-counter.
  92245. **
  92246. ** If any of the parent-key values are NULL, then the row cannot match
  92247. ** itself. So set JUMPIFNULL to make sure we do the OP_Found if any
  92248. ** of the parent-key values are NULL (at this point it is known that
  92249. ** none of the child key values are).
  92250. */
  92251. if( pTab==pFKey->pFrom && nIncr==1 ){
  92252. int iJump = sqlite3VdbeCurrentAddr(v) + nCol + 1;
  92253. for(i=0; i<nCol; i++){
  92254. int iChild = aiCol[i]+1+regData;
  92255. int iParent = pIdx->aiColumn[i]+1+regData;
  92256. assert( aiCol[i]!=pTab->iPKey );
  92257. if( pIdx->aiColumn[i]==pTab->iPKey ){
  92258. /* The parent key is a composite key that includes the IPK column */
  92259. iParent = regData;
  92260. }
  92261. sqlite3VdbeAddOp3(v, OP_Ne, iChild, iJump, iParent); VdbeCoverage(v);
  92262. sqlite3VdbeChangeP5(v, SQLITE_JUMPIFNULL);
  92263. }
  92264. sqlite3VdbeAddOp2(v, OP_Goto, 0, iOk);
  92265. }
  92266. sqlite3VdbeAddOp4(v, OP_MakeRecord, regTemp, nCol, regRec,
  92267. sqlite3IndexAffinityStr(v,pIdx), nCol);
  92268. sqlite3VdbeAddOp4Int(v, OP_Found, iCur, iOk, regRec, 0); VdbeCoverage(v);
  92269. sqlite3ReleaseTempReg(pParse, regRec);
  92270. sqlite3ReleaseTempRange(pParse, regTemp, nCol);
  92271. }
  92272. }
  92273. if( !pFKey->isDeferred && !(pParse->db->flags & SQLITE_DeferFKs)
  92274. && !pParse->pToplevel
  92275. && !pParse->isMultiWrite
  92276. ){
  92277. /* Special case: If this is an INSERT statement that will insert exactly
  92278. ** one row into the table, raise a constraint immediately instead of
  92279. ** incrementing a counter. This is necessary as the VM code is being
  92280. ** generated for will not open a statement transaction. */
  92281. assert( nIncr==1 );
  92282. sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_FOREIGNKEY,
  92283. OE_Abort, 0, P4_STATIC, P5_ConstraintFK);
  92284. }else{
  92285. if( nIncr>0 && pFKey->isDeferred==0 ){
  92286. sqlite3MayAbort(pParse);
  92287. }
  92288. sqlite3VdbeAddOp2(v, OP_FkCounter, pFKey->isDeferred, nIncr);
  92289. }
  92290. sqlite3VdbeResolveLabel(v, iOk);
  92291. sqlite3VdbeAddOp1(v, OP_Close, iCur);
  92292. }
  92293. /*
  92294. ** Return an Expr object that refers to a memory register corresponding
  92295. ** to column iCol of table pTab.
  92296. **
  92297. ** regBase is the first of an array of register that contains the data
  92298. ** for pTab. regBase itself holds the rowid. regBase+1 holds the first
  92299. ** column. regBase+2 holds the second column, and so forth.
  92300. */
  92301. static Expr *exprTableRegister(
  92302. Parse *pParse, /* Parsing and code generating context */
  92303. Table *pTab, /* The table whose content is at r[regBase]... */
  92304. int regBase, /* Contents of table pTab */
  92305. i16 iCol /* Which column of pTab is desired */
  92306. ){
  92307. Expr *pExpr;
  92308. Column *pCol;
  92309. const char *zColl;
  92310. sqlite3 *db = pParse->db;
  92311. pExpr = sqlite3Expr(db, TK_REGISTER, 0);
  92312. if( pExpr ){
  92313. if( iCol>=0 && iCol!=pTab->iPKey ){
  92314. pCol = &pTab->aCol[iCol];
  92315. pExpr->iTable = regBase + iCol + 1;
  92316. pExpr->affinity = pCol->affinity;
  92317. zColl = pCol->zColl;
  92318. if( zColl==0 ) zColl = db->pDfltColl->zName;
  92319. pExpr = sqlite3ExprAddCollateString(pParse, pExpr, zColl);
  92320. }else{
  92321. pExpr->iTable = regBase;
  92322. pExpr->affinity = SQLITE_AFF_INTEGER;
  92323. }
  92324. }
  92325. return pExpr;
  92326. }
  92327. /*
  92328. ** Return an Expr object that refers to column iCol of table pTab which
  92329. ** has cursor iCur.
  92330. */
  92331. static Expr *exprTableColumn(
  92332. sqlite3 *db, /* The database connection */
  92333. Table *pTab, /* The table whose column is desired */
  92334. int iCursor, /* The open cursor on the table */
  92335. i16 iCol /* The column that is wanted */
  92336. ){
  92337. Expr *pExpr = sqlite3Expr(db, TK_COLUMN, 0);
  92338. if( pExpr ){
  92339. pExpr->pTab = pTab;
  92340. pExpr->iTable = iCursor;
  92341. pExpr->iColumn = iCol;
  92342. }
  92343. return pExpr;
  92344. }
  92345. /*
  92346. ** This function is called to generate code executed when a row is deleted
  92347. ** from the parent table of foreign key constraint pFKey and, if pFKey is
  92348. ** deferred, when a row is inserted into the same table. When generating
  92349. ** code for an SQL UPDATE operation, this function may be called twice -
  92350. ** once to "delete" the old row and once to "insert" the new row.
  92351. **
  92352. ** Parameter nIncr is passed -1 when inserting a row (as this may decrease
  92353. ** the number of FK violations in the db) or +1 when deleting one (as this
  92354. ** may increase the number of FK constraint problems).
  92355. **
  92356. ** The code generated by this function scans through the rows in the child
  92357. ** table that correspond to the parent table row being deleted or inserted.
  92358. ** For each child row found, one of the following actions is taken:
  92359. **
  92360. ** Operation | FK type | Action taken
  92361. ** --------------------------------------------------------------------------
  92362. ** DELETE immediate Increment the "immediate constraint counter".
  92363. ** Or, if the ON (UPDATE|DELETE) action is RESTRICT,
  92364. ** throw a "FOREIGN KEY constraint failed" exception.
  92365. **
  92366. ** INSERT immediate Decrement the "immediate constraint counter".
  92367. **
  92368. ** DELETE deferred Increment the "deferred constraint counter".
  92369. ** Or, if the ON (UPDATE|DELETE) action is RESTRICT,
  92370. ** throw a "FOREIGN KEY constraint failed" exception.
  92371. **
  92372. ** INSERT deferred Decrement the "deferred constraint counter".
  92373. **
  92374. ** These operations are identified in the comment at the top of this file
  92375. ** (fkey.c) as "I.2" and "D.2".
  92376. */
  92377. static void fkScanChildren(
  92378. Parse *pParse, /* Parse context */
  92379. SrcList *pSrc, /* The child table to be scanned */
  92380. Table *pTab, /* The parent table */
  92381. Index *pIdx, /* Index on parent covering the foreign key */
  92382. FKey *pFKey, /* The foreign key linking pSrc to pTab */
  92383. int *aiCol, /* Map from pIdx cols to child table cols */
  92384. int regData, /* Parent row data starts here */
  92385. int nIncr /* Amount to increment deferred counter by */
  92386. ){
  92387. sqlite3 *db = pParse->db; /* Database handle */
  92388. int i; /* Iterator variable */
  92389. Expr *pWhere = 0; /* WHERE clause to scan with */
  92390. NameContext sNameContext; /* Context used to resolve WHERE clause */
  92391. WhereInfo *pWInfo; /* Context used by sqlite3WhereXXX() */
  92392. int iFkIfZero = 0; /* Address of OP_FkIfZero */
  92393. Vdbe *v = sqlite3GetVdbe(pParse);
  92394. assert( pIdx==0 || pIdx->pTable==pTab );
  92395. assert( pIdx==0 || pIdx->nKeyCol==pFKey->nCol );
  92396. assert( pIdx!=0 || pFKey->nCol==1 );
  92397. assert( pIdx!=0 || HasRowid(pTab) );
  92398. if( nIncr<0 ){
  92399. iFkIfZero = sqlite3VdbeAddOp2(v, OP_FkIfZero, pFKey->isDeferred, 0);
  92400. VdbeCoverage(v);
  92401. }
  92402. /* Create an Expr object representing an SQL expression like:
  92403. **
  92404. ** <parent-key1> = <child-key1> AND <parent-key2> = <child-key2> ...
  92405. **
  92406. ** The collation sequence used for the comparison should be that of
  92407. ** the parent key columns. The affinity of the parent key column should
  92408. ** be applied to each child key value before the comparison takes place.
  92409. */
  92410. for(i=0; i<pFKey->nCol; i++){
  92411. Expr *pLeft; /* Value from parent table row */
  92412. Expr *pRight; /* Column ref to child table */
  92413. Expr *pEq; /* Expression (pLeft = pRight) */
  92414. i16 iCol; /* Index of column in child table */
  92415. const char *zCol; /* Name of column in child table */
  92416. iCol = pIdx ? pIdx->aiColumn[i] : -1;
  92417. pLeft = exprTableRegister(pParse, pTab, regData, iCol);
  92418. iCol = aiCol ? aiCol[i] : pFKey->aCol[0].iFrom;
  92419. assert( iCol>=0 );
  92420. zCol = pFKey->pFrom->aCol[iCol].zName;
  92421. pRight = sqlite3Expr(db, TK_ID, zCol);
  92422. pEq = sqlite3PExpr(pParse, TK_EQ, pLeft, pRight, 0);
  92423. pWhere = sqlite3ExprAnd(db, pWhere, pEq);
  92424. }
  92425. /* If the child table is the same as the parent table, then add terms
  92426. ** to the WHERE clause that prevent this entry from being scanned.
  92427. ** The added WHERE clause terms are like this:
  92428. **
  92429. ** $current_rowid!=rowid
  92430. ** NOT( $current_a==a AND $current_b==b AND ... )
  92431. **
  92432. ** The first form is used for rowid tables. The second form is used
  92433. ** for WITHOUT ROWID tables. In the second form, the primary key is
  92434. ** (a,b,...)
  92435. */
  92436. if( pTab==pFKey->pFrom && nIncr>0 ){
  92437. Expr *pNe; /* Expression (pLeft != pRight) */
  92438. Expr *pLeft; /* Value from parent table row */
  92439. Expr *pRight; /* Column ref to child table */
  92440. if( HasRowid(pTab) ){
  92441. pLeft = exprTableRegister(pParse, pTab, regData, -1);
  92442. pRight = exprTableColumn(db, pTab, pSrc->a[0].iCursor, -1);
  92443. pNe = sqlite3PExpr(pParse, TK_NE, pLeft, pRight, 0);
  92444. }else{
  92445. Expr *pEq, *pAll = 0;
  92446. Index *pPk = sqlite3PrimaryKeyIndex(pTab);
  92447. assert( pIdx!=0 );
  92448. for(i=0; i<pPk->nKeyCol; i++){
  92449. i16 iCol = pIdx->aiColumn[i];
  92450. pLeft = exprTableRegister(pParse, pTab, regData, iCol);
  92451. pRight = exprTableColumn(db, pTab, pSrc->a[0].iCursor, iCol);
  92452. pEq = sqlite3PExpr(pParse, TK_EQ, pLeft, pRight, 0);
  92453. pAll = sqlite3ExprAnd(db, pAll, pEq);
  92454. }
  92455. pNe = sqlite3PExpr(pParse, TK_NOT, pAll, 0, 0);
  92456. }
  92457. pWhere = sqlite3ExprAnd(db, pWhere, pNe);
  92458. }
  92459. /* Resolve the references in the WHERE clause. */
  92460. memset(&sNameContext, 0, sizeof(NameContext));
  92461. sNameContext.pSrcList = pSrc;
  92462. sNameContext.pParse = pParse;
  92463. sqlite3ResolveExprNames(&sNameContext, pWhere);
  92464. /* Create VDBE to loop through the entries in pSrc that match the WHERE
  92465. ** clause. For each row found, increment either the deferred or immediate
  92466. ** foreign key constraint counter. */
  92467. pWInfo = sqlite3WhereBegin(pParse, pSrc, pWhere, 0, 0, 0, 0);
  92468. sqlite3VdbeAddOp2(v, OP_FkCounter, pFKey->isDeferred, nIncr);
  92469. if( pWInfo ){
  92470. sqlite3WhereEnd(pWInfo);
  92471. }
  92472. /* Clean up the WHERE clause constructed above. */
  92473. sqlite3ExprDelete(db, pWhere);
  92474. if( iFkIfZero ){
  92475. sqlite3VdbeJumpHere(v, iFkIfZero);
  92476. }
  92477. }
  92478. /*
  92479. ** This function returns a linked list of FKey objects (connected by
  92480. ** FKey.pNextTo) holding all children of table pTab. For example,
  92481. ** given the following schema:
  92482. **
  92483. ** CREATE TABLE t1(a PRIMARY KEY);
  92484. ** CREATE TABLE t2(b REFERENCES t1(a);
  92485. **
  92486. ** Calling this function with table "t1" as an argument returns a pointer
  92487. ** to the FKey structure representing the foreign key constraint on table
  92488. ** "t2". Calling this function with "t2" as the argument would return a
  92489. ** NULL pointer (as there are no FK constraints for which t2 is the parent
  92490. ** table).
  92491. */
  92492. SQLITE_PRIVATE FKey *sqlite3FkReferences(Table *pTab){
  92493. return (FKey *)sqlite3HashFind(&pTab->pSchema->fkeyHash, pTab->zName);
  92494. }
  92495. /*
  92496. ** The second argument is a Trigger structure allocated by the
  92497. ** fkActionTrigger() routine. This function deletes the Trigger structure
  92498. ** and all of its sub-components.
  92499. **
  92500. ** The Trigger structure or any of its sub-components may be allocated from
  92501. ** the lookaside buffer belonging to database handle dbMem.
  92502. */
  92503. static void fkTriggerDelete(sqlite3 *dbMem, Trigger *p){
  92504. if( p ){
  92505. TriggerStep *pStep = p->step_list;
  92506. sqlite3ExprDelete(dbMem, pStep->pWhere);
  92507. sqlite3ExprListDelete(dbMem, pStep->pExprList);
  92508. sqlite3SelectDelete(dbMem, pStep->pSelect);
  92509. sqlite3ExprDelete(dbMem, p->pWhen);
  92510. sqlite3DbFree(dbMem, p);
  92511. }
  92512. }
  92513. /*
  92514. ** This function is called to generate code that runs when table pTab is
  92515. ** being dropped from the database. The SrcList passed as the second argument
  92516. ** to this function contains a single entry guaranteed to resolve to
  92517. ** table pTab.
  92518. **
  92519. ** Normally, no code is required. However, if either
  92520. **
  92521. ** (a) The table is the parent table of a FK constraint, or
  92522. ** (b) The table is the child table of a deferred FK constraint and it is
  92523. ** determined at runtime that there are outstanding deferred FK
  92524. ** constraint violations in the database,
  92525. **
  92526. ** then the equivalent of "DELETE FROM <tbl>" is executed before dropping
  92527. ** the table from the database. Triggers are disabled while running this
  92528. ** DELETE, but foreign key actions are not.
  92529. */
  92530. SQLITE_PRIVATE void sqlite3FkDropTable(Parse *pParse, SrcList *pName, Table *pTab){
  92531. sqlite3 *db = pParse->db;
  92532. if( (db->flags&SQLITE_ForeignKeys) && !IsVirtual(pTab) && !pTab->pSelect ){
  92533. int iSkip = 0;
  92534. Vdbe *v = sqlite3GetVdbe(pParse);
  92535. assert( v ); /* VDBE has already been allocated */
  92536. if( sqlite3FkReferences(pTab)==0 ){
  92537. /* Search for a deferred foreign key constraint for which this table
  92538. ** is the child table. If one cannot be found, return without
  92539. ** generating any VDBE code. If one can be found, then jump over
  92540. ** the entire DELETE if there are no outstanding deferred constraints
  92541. ** when this statement is run. */
  92542. FKey *p;
  92543. for(p=pTab->pFKey; p; p=p->pNextFrom){
  92544. if( p->isDeferred || (db->flags & SQLITE_DeferFKs) ) break;
  92545. }
  92546. if( !p ) return;
  92547. iSkip = sqlite3VdbeMakeLabel(v);
  92548. sqlite3VdbeAddOp2(v, OP_FkIfZero, 1, iSkip); VdbeCoverage(v);
  92549. }
  92550. pParse->disableTriggers = 1;
  92551. sqlite3DeleteFrom(pParse, sqlite3SrcListDup(db, pName, 0), 0);
  92552. pParse->disableTriggers = 0;
  92553. /* If the DELETE has generated immediate foreign key constraint
  92554. ** violations, halt the VDBE and return an error at this point, before
  92555. ** any modifications to the schema are made. This is because statement
  92556. ** transactions are not able to rollback schema changes.
  92557. **
  92558. ** If the SQLITE_DeferFKs flag is set, then this is not required, as
  92559. ** the statement transaction will not be rolled back even if FK
  92560. ** constraints are violated.
  92561. */
  92562. if( (db->flags & SQLITE_DeferFKs)==0 ){
  92563. sqlite3VdbeAddOp2(v, OP_FkIfZero, 0, sqlite3VdbeCurrentAddr(v)+2);
  92564. VdbeCoverage(v);
  92565. sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_FOREIGNKEY,
  92566. OE_Abort, 0, P4_STATIC, P5_ConstraintFK);
  92567. }
  92568. if( iSkip ){
  92569. sqlite3VdbeResolveLabel(v, iSkip);
  92570. }
  92571. }
  92572. }
  92573. /*
  92574. ** The second argument points to an FKey object representing a foreign key
  92575. ** for which pTab is the child table. An UPDATE statement against pTab
  92576. ** is currently being processed. For each column of the table that is
  92577. ** actually updated, the corresponding element in the aChange[] array
  92578. ** is zero or greater (if a column is unmodified the corresponding element
  92579. ** is set to -1). If the rowid column is modified by the UPDATE statement
  92580. ** the bChngRowid argument is non-zero.
  92581. **
  92582. ** This function returns true if any of the columns that are part of the
  92583. ** child key for FK constraint *p are modified.
  92584. */
  92585. static int fkChildIsModified(
  92586. Table *pTab, /* Table being updated */
  92587. FKey *p, /* Foreign key for which pTab is the child */
  92588. int *aChange, /* Array indicating modified columns */
  92589. int bChngRowid /* True if rowid is modified by this update */
  92590. ){
  92591. int i;
  92592. for(i=0; i<p->nCol; i++){
  92593. int iChildKey = p->aCol[i].iFrom;
  92594. if( aChange[iChildKey]>=0 ) return 1;
  92595. if( iChildKey==pTab->iPKey && bChngRowid ) return 1;
  92596. }
  92597. return 0;
  92598. }
  92599. /*
  92600. ** The second argument points to an FKey object representing a foreign key
  92601. ** for which pTab is the parent table. An UPDATE statement against pTab
  92602. ** is currently being processed. For each column of the table that is
  92603. ** actually updated, the corresponding element in the aChange[] array
  92604. ** is zero or greater (if a column is unmodified the corresponding element
  92605. ** is set to -1). If the rowid column is modified by the UPDATE statement
  92606. ** the bChngRowid argument is non-zero.
  92607. **
  92608. ** This function returns true if any of the columns that are part of the
  92609. ** parent key for FK constraint *p are modified.
  92610. */
  92611. static int fkParentIsModified(
  92612. Table *pTab,
  92613. FKey *p,
  92614. int *aChange,
  92615. int bChngRowid
  92616. ){
  92617. int i;
  92618. for(i=0; i<p->nCol; i++){
  92619. char *zKey = p->aCol[i].zCol;
  92620. int iKey;
  92621. for(iKey=0; iKey<pTab->nCol; iKey++){
  92622. if( aChange[iKey]>=0 || (iKey==pTab->iPKey && bChngRowid) ){
  92623. Column *pCol = &pTab->aCol[iKey];
  92624. if( zKey ){
  92625. if( 0==sqlite3StrICmp(pCol->zName, zKey) ) return 1;
  92626. }else if( pCol->colFlags & COLFLAG_PRIMKEY ){
  92627. return 1;
  92628. }
  92629. }
  92630. }
  92631. }
  92632. return 0;
  92633. }
  92634. /*
  92635. ** Return true if the parser passed as the first argument is being
  92636. ** used to code a trigger that is really a "SET NULL" action belonging
  92637. ** to trigger pFKey.
  92638. */
  92639. static int isSetNullAction(Parse *pParse, FKey *pFKey){
  92640. Parse *pTop = sqlite3ParseToplevel(pParse);
  92641. if( pTop->pTriggerPrg ){
  92642. Trigger *p = pTop->pTriggerPrg->pTrigger;
  92643. if( (p==pFKey->apTrigger[0] && pFKey->aAction[0]==OE_SetNull)
  92644. || (p==pFKey->apTrigger[1] && pFKey->aAction[1]==OE_SetNull)
  92645. ){
  92646. return 1;
  92647. }
  92648. }
  92649. return 0;
  92650. }
  92651. /*
  92652. ** This function is called when inserting, deleting or updating a row of
  92653. ** table pTab to generate VDBE code to perform foreign key constraint
  92654. ** processing for the operation.
  92655. **
  92656. ** For a DELETE operation, parameter regOld is passed the index of the
  92657. ** first register in an array of (pTab->nCol+1) registers containing the
  92658. ** rowid of the row being deleted, followed by each of the column values
  92659. ** of the row being deleted, from left to right. Parameter regNew is passed
  92660. ** zero in this case.
  92661. **
  92662. ** For an INSERT operation, regOld is passed zero and regNew is passed the
  92663. ** first register of an array of (pTab->nCol+1) registers containing the new
  92664. ** row data.
  92665. **
  92666. ** For an UPDATE operation, this function is called twice. Once before
  92667. ** the original record is deleted from the table using the calling convention
  92668. ** described for DELETE. Then again after the original record is deleted
  92669. ** but before the new record is inserted using the INSERT convention.
  92670. */
  92671. SQLITE_PRIVATE void sqlite3FkCheck(
  92672. Parse *pParse, /* Parse context */
  92673. Table *pTab, /* Row is being deleted from this table */
  92674. int regOld, /* Previous row data is stored here */
  92675. int regNew, /* New row data is stored here */
  92676. int *aChange, /* Array indicating UPDATEd columns (or 0) */
  92677. int bChngRowid /* True if rowid is UPDATEd */
  92678. ){
  92679. sqlite3 *db = pParse->db; /* Database handle */
  92680. FKey *pFKey; /* Used to iterate through FKs */
  92681. int iDb; /* Index of database containing pTab */
  92682. const char *zDb; /* Name of database containing pTab */
  92683. int isIgnoreErrors = pParse->disableTriggers;
  92684. /* Exactly one of regOld and regNew should be non-zero. */
  92685. assert( (regOld==0)!=(regNew==0) );
  92686. /* If foreign-keys are disabled, this function is a no-op. */
  92687. if( (db->flags&SQLITE_ForeignKeys)==0 ) return;
  92688. iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  92689. zDb = db->aDb[iDb].zName;
  92690. /* Loop through all the foreign key constraints for which pTab is the
  92691. ** child table (the table that the foreign key definition is part of). */
  92692. for(pFKey=pTab->pFKey; pFKey; pFKey=pFKey->pNextFrom){
  92693. Table *pTo; /* Parent table of foreign key pFKey */
  92694. Index *pIdx = 0; /* Index on key columns in pTo */
  92695. int *aiFree = 0;
  92696. int *aiCol;
  92697. int iCol;
  92698. int i;
  92699. int bIgnore = 0;
  92700. if( aChange
  92701. && sqlite3_stricmp(pTab->zName, pFKey->zTo)!=0
  92702. && fkChildIsModified(pTab, pFKey, aChange, bChngRowid)==0
  92703. ){
  92704. continue;
  92705. }
  92706. /* Find the parent table of this foreign key. Also find a unique index
  92707. ** on the parent key columns in the parent table. If either of these
  92708. ** schema items cannot be located, set an error in pParse and return
  92709. ** early. */
  92710. if( pParse->disableTriggers ){
  92711. pTo = sqlite3FindTable(db, pFKey->zTo, zDb);
  92712. }else{
  92713. pTo = sqlite3LocateTable(pParse, 0, pFKey->zTo, zDb);
  92714. }
  92715. if( !pTo || sqlite3FkLocateIndex(pParse, pTo, pFKey, &pIdx, &aiFree) ){
  92716. assert( isIgnoreErrors==0 || (regOld!=0 && regNew==0) );
  92717. if( !isIgnoreErrors || db->mallocFailed ) return;
  92718. if( pTo==0 ){
  92719. /* If isIgnoreErrors is true, then a table is being dropped. In this
  92720. ** case SQLite runs a "DELETE FROM xxx" on the table being dropped
  92721. ** before actually dropping it in order to check FK constraints.
  92722. ** If the parent table of an FK constraint on the current table is
  92723. ** missing, behave as if it is empty. i.e. decrement the relevant
  92724. ** FK counter for each row of the current table with non-NULL keys.
  92725. */
  92726. Vdbe *v = sqlite3GetVdbe(pParse);
  92727. int iJump = sqlite3VdbeCurrentAddr(v) + pFKey->nCol + 1;
  92728. for(i=0; i<pFKey->nCol; i++){
  92729. int iReg = pFKey->aCol[i].iFrom + regOld + 1;
  92730. sqlite3VdbeAddOp2(v, OP_IsNull, iReg, iJump); VdbeCoverage(v);
  92731. }
  92732. sqlite3VdbeAddOp2(v, OP_FkCounter, pFKey->isDeferred, -1);
  92733. }
  92734. continue;
  92735. }
  92736. assert( pFKey->nCol==1 || (aiFree && pIdx) );
  92737. if( aiFree ){
  92738. aiCol = aiFree;
  92739. }else{
  92740. iCol = pFKey->aCol[0].iFrom;
  92741. aiCol = &iCol;
  92742. }
  92743. for(i=0; i<pFKey->nCol; i++){
  92744. if( aiCol[i]==pTab->iPKey ){
  92745. aiCol[i] = -1;
  92746. }
  92747. #ifndef SQLITE_OMIT_AUTHORIZATION
  92748. /* Request permission to read the parent key columns. If the
  92749. ** authorization callback returns SQLITE_IGNORE, behave as if any
  92750. ** values read from the parent table are NULL. */
  92751. if( db->xAuth ){
  92752. int rcauth;
  92753. char *zCol = pTo->aCol[pIdx ? pIdx->aiColumn[i] : pTo->iPKey].zName;
  92754. rcauth = sqlite3AuthReadCol(pParse, pTo->zName, zCol, iDb);
  92755. bIgnore = (rcauth==SQLITE_IGNORE);
  92756. }
  92757. #endif
  92758. }
  92759. /* Take a shared-cache advisory read-lock on the parent table. Allocate
  92760. ** a cursor to use to search the unique index on the parent key columns
  92761. ** in the parent table. */
  92762. sqlite3TableLock(pParse, iDb, pTo->tnum, 0, pTo->zName);
  92763. pParse->nTab++;
  92764. if( regOld!=0 ){
  92765. /* A row is being removed from the child table. Search for the parent.
  92766. ** If the parent does not exist, removing the child row resolves an
  92767. ** outstanding foreign key constraint violation. */
  92768. fkLookupParent(pParse, iDb, pTo, pIdx, pFKey, aiCol, regOld, -1, bIgnore);
  92769. }
  92770. if( regNew!=0 && !isSetNullAction(pParse, pFKey) ){
  92771. /* A row is being added to the child table. If a parent row cannot
  92772. ** be found, adding the child row has violated the FK constraint.
  92773. **
  92774. ** If this operation is being performed as part of a trigger program
  92775. ** that is actually a "SET NULL" action belonging to this very
  92776. ** foreign key, then omit this scan altogether. As all child key
  92777. ** values are guaranteed to be NULL, it is not possible for adding
  92778. ** this row to cause an FK violation. */
  92779. fkLookupParent(pParse, iDb, pTo, pIdx, pFKey, aiCol, regNew, +1, bIgnore);
  92780. }
  92781. sqlite3DbFree(db, aiFree);
  92782. }
  92783. /* Loop through all the foreign key constraints that refer to this table.
  92784. ** (the "child" constraints) */
  92785. for(pFKey = sqlite3FkReferences(pTab); pFKey; pFKey=pFKey->pNextTo){
  92786. Index *pIdx = 0; /* Foreign key index for pFKey */
  92787. SrcList *pSrc;
  92788. int *aiCol = 0;
  92789. if( aChange && fkParentIsModified(pTab, pFKey, aChange, bChngRowid)==0 ){
  92790. continue;
  92791. }
  92792. if( !pFKey->isDeferred && !(db->flags & SQLITE_DeferFKs)
  92793. && !pParse->pToplevel && !pParse->isMultiWrite
  92794. ){
  92795. assert( regOld==0 && regNew!=0 );
  92796. /* Inserting a single row into a parent table cannot cause (or fix)
  92797. ** an immediate foreign key violation. So do nothing in this case. */
  92798. continue;
  92799. }
  92800. if( sqlite3FkLocateIndex(pParse, pTab, pFKey, &pIdx, &aiCol) ){
  92801. if( !isIgnoreErrors || db->mallocFailed ) return;
  92802. continue;
  92803. }
  92804. assert( aiCol || pFKey->nCol==1 );
  92805. /* Create a SrcList structure containing the child table. We need the
  92806. ** child table as a SrcList for sqlite3WhereBegin() */
  92807. pSrc = sqlite3SrcListAppend(db, 0, 0, 0);
  92808. if( pSrc ){
  92809. struct SrcList_item *pItem = pSrc->a;
  92810. pItem->pTab = pFKey->pFrom;
  92811. pItem->zName = pFKey->pFrom->zName;
  92812. pItem->pTab->nRef++;
  92813. pItem->iCursor = pParse->nTab++;
  92814. if( regNew!=0 ){
  92815. fkScanChildren(pParse, pSrc, pTab, pIdx, pFKey, aiCol, regNew, -1);
  92816. }
  92817. if( regOld!=0 ){
  92818. int eAction = pFKey->aAction[aChange!=0];
  92819. fkScanChildren(pParse, pSrc, pTab, pIdx, pFKey, aiCol, regOld, 1);
  92820. /* If this is a deferred FK constraint, or a CASCADE or SET NULL
  92821. ** action applies, then any foreign key violations caused by
  92822. ** removing the parent key will be rectified by the action trigger.
  92823. ** So do not set the "may-abort" flag in this case.
  92824. **
  92825. ** Note 1: If the FK is declared "ON UPDATE CASCADE", then the
  92826. ** may-abort flag will eventually be set on this statement anyway
  92827. ** (when this function is called as part of processing the UPDATE
  92828. ** within the action trigger).
  92829. **
  92830. ** Note 2: At first glance it may seem like SQLite could simply omit
  92831. ** all OP_FkCounter related scans when either CASCADE or SET NULL
  92832. ** applies. The trouble starts if the CASCADE or SET NULL action
  92833. ** trigger causes other triggers or action rules attached to the
  92834. ** child table to fire. In these cases the fk constraint counters
  92835. ** might be set incorrectly if any OP_FkCounter related scans are
  92836. ** omitted. */
  92837. if( !pFKey->isDeferred && eAction!=OE_Cascade && eAction!=OE_SetNull ){
  92838. sqlite3MayAbort(pParse);
  92839. }
  92840. }
  92841. pItem->zName = 0;
  92842. sqlite3SrcListDelete(db, pSrc);
  92843. }
  92844. sqlite3DbFree(db, aiCol);
  92845. }
  92846. }
  92847. #define COLUMN_MASK(x) (((x)>31) ? 0xffffffff : ((u32)1<<(x)))
  92848. /*
  92849. ** This function is called before generating code to update or delete a
  92850. ** row contained in table pTab.
  92851. */
  92852. SQLITE_PRIVATE u32 sqlite3FkOldmask(
  92853. Parse *pParse, /* Parse context */
  92854. Table *pTab /* Table being modified */
  92855. ){
  92856. u32 mask = 0;
  92857. if( pParse->db->flags&SQLITE_ForeignKeys ){
  92858. FKey *p;
  92859. int i;
  92860. for(p=pTab->pFKey; p; p=p->pNextFrom){
  92861. for(i=0; i<p->nCol; i++) mask |= COLUMN_MASK(p->aCol[i].iFrom);
  92862. }
  92863. for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
  92864. Index *pIdx = 0;
  92865. sqlite3FkLocateIndex(pParse, pTab, p, &pIdx, 0);
  92866. if( pIdx ){
  92867. for(i=0; i<pIdx->nKeyCol; i++) mask |= COLUMN_MASK(pIdx->aiColumn[i]);
  92868. }
  92869. }
  92870. }
  92871. return mask;
  92872. }
  92873. /*
  92874. ** This function is called before generating code to update or delete a
  92875. ** row contained in table pTab. If the operation is a DELETE, then
  92876. ** parameter aChange is passed a NULL value. For an UPDATE, aChange points
  92877. ** to an array of size N, where N is the number of columns in table pTab.
  92878. ** If the i'th column is not modified by the UPDATE, then the corresponding
  92879. ** entry in the aChange[] array is set to -1. If the column is modified,
  92880. ** the value is 0 or greater. Parameter chngRowid is set to true if the
  92881. ** UPDATE statement modifies the rowid fields of the table.
  92882. **
  92883. ** If any foreign key processing will be required, this function returns
  92884. ** true. If there is no foreign key related processing, this function
  92885. ** returns false.
  92886. */
  92887. SQLITE_PRIVATE int sqlite3FkRequired(
  92888. Parse *pParse, /* Parse context */
  92889. Table *pTab, /* Table being modified */
  92890. int *aChange, /* Non-NULL for UPDATE operations */
  92891. int chngRowid /* True for UPDATE that affects rowid */
  92892. ){
  92893. if( pParse->db->flags&SQLITE_ForeignKeys ){
  92894. if( !aChange ){
  92895. /* A DELETE operation. Foreign key processing is required if the
  92896. ** table in question is either the child or parent table for any
  92897. ** foreign key constraint. */
  92898. return (sqlite3FkReferences(pTab) || pTab->pFKey);
  92899. }else{
  92900. /* This is an UPDATE. Foreign key processing is only required if the
  92901. ** operation modifies one or more child or parent key columns. */
  92902. FKey *p;
  92903. /* Check if any child key columns are being modified. */
  92904. for(p=pTab->pFKey; p; p=p->pNextFrom){
  92905. if( fkChildIsModified(pTab, p, aChange, chngRowid) ) return 1;
  92906. }
  92907. /* Check if any parent key columns are being modified. */
  92908. for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
  92909. if( fkParentIsModified(pTab, p, aChange, chngRowid) ) return 1;
  92910. }
  92911. }
  92912. }
  92913. return 0;
  92914. }
  92915. /*
  92916. ** This function is called when an UPDATE or DELETE operation is being
  92917. ** compiled on table pTab, which is the parent table of foreign-key pFKey.
  92918. ** If the current operation is an UPDATE, then the pChanges parameter is
  92919. ** passed a pointer to the list of columns being modified. If it is a
  92920. ** DELETE, pChanges is passed a NULL pointer.
  92921. **
  92922. ** It returns a pointer to a Trigger structure containing a trigger
  92923. ** equivalent to the ON UPDATE or ON DELETE action specified by pFKey.
  92924. ** If the action is "NO ACTION" or "RESTRICT", then a NULL pointer is
  92925. ** returned (these actions require no special handling by the triggers
  92926. ** sub-system, code for them is created by fkScanChildren()).
  92927. **
  92928. ** For example, if pFKey is the foreign key and pTab is table "p" in
  92929. ** the following schema:
  92930. **
  92931. ** CREATE TABLE p(pk PRIMARY KEY);
  92932. ** CREATE TABLE c(ck REFERENCES p ON DELETE CASCADE);
  92933. **
  92934. ** then the returned trigger structure is equivalent to:
  92935. **
  92936. ** CREATE TRIGGER ... DELETE ON p BEGIN
  92937. ** DELETE FROM c WHERE ck = old.pk;
  92938. ** END;
  92939. **
  92940. ** The returned pointer is cached as part of the foreign key object. It
  92941. ** is eventually freed along with the rest of the foreign key object by
  92942. ** sqlite3FkDelete().
  92943. */
  92944. static Trigger *fkActionTrigger(
  92945. Parse *pParse, /* Parse context */
  92946. Table *pTab, /* Table being updated or deleted from */
  92947. FKey *pFKey, /* Foreign key to get action for */
  92948. ExprList *pChanges /* Change-list for UPDATE, NULL for DELETE */
  92949. ){
  92950. sqlite3 *db = pParse->db; /* Database handle */
  92951. int action; /* One of OE_None, OE_Cascade etc. */
  92952. Trigger *pTrigger; /* Trigger definition to return */
  92953. int iAction = (pChanges!=0); /* 1 for UPDATE, 0 for DELETE */
  92954. action = pFKey->aAction[iAction];
  92955. pTrigger = pFKey->apTrigger[iAction];
  92956. if( action!=OE_None && !pTrigger ){
  92957. u8 enableLookaside; /* Copy of db->lookaside.bEnabled */
  92958. char const *zFrom; /* Name of child table */
  92959. int nFrom; /* Length in bytes of zFrom */
  92960. Index *pIdx = 0; /* Parent key index for this FK */
  92961. int *aiCol = 0; /* child table cols -> parent key cols */
  92962. TriggerStep *pStep = 0; /* First (only) step of trigger program */
  92963. Expr *pWhere = 0; /* WHERE clause of trigger step */
  92964. ExprList *pList = 0; /* Changes list if ON UPDATE CASCADE */
  92965. Select *pSelect = 0; /* If RESTRICT, "SELECT RAISE(...)" */
  92966. int i; /* Iterator variable */
  92967. Expr *pWhen = 0; /* WHEN clause for the trigger */
  92968. if( sqlite3FkLocateIndex(pParse, pTab, pFKey, &pIdx, &aiCol) ) return 0;
  92969. assert( aiCol || pFKey->nCol==1 );
  92970. for(i=0; i<pFKey->nCol; i++){
  92971. Token tOld = { "old", 3 }; /* Literal "old" token */
  92972. Token tNew = { "new", 3 }; /* Literal "new" token */
  92973. Token tFromCol; /* Name of column in child table */
  92974. Token tToCol; /* Name of column in parent table */
  92975. int iFromCol; /* Idx of column in child table */
  92976. Expr *pEq; /* tFromCol = OLD.tToCol */
  92977. iFromCol = aiCol ? aiCol[i] : pFKey->aCol[0].iFrom;
  92978. assert( iFromCol>=0 );
  92979. assert( pIdx!=0 || (pTab->iPKey>=0 && pTab->iPKey<pTab->nCol) );
  92980. tToCol.z = pTab->aCol[pIdx ? pIdx->aiColumn[i] : pTab->iPKey].zName;
  92981. tFromCol.z = pFKey->pFrom->aCol[iFromCol].zName;
  92982. tToCol.n = sqlite3Strlen30(tToCol.z);
  92983. tFromCol.n = sqlite3Strlen30(tFromCol.z);
  92984. /* Create the expression "OLD.zToCol = zFromCol". It is important
  92985. ** that the "OLD.zToCol" term is on the LHS of the = operator, so
  92986. ** that the affinity and collation sequence associated with the
  92987. ** parent table are used for the comparison. */
  92988. pEq = sqlite3PExpr(pParse, TK_EQ,
  92989. sqlite3PExpr(pParse, TK_DOT,
  92990. sqlite3ExprAlloc(db, TK_ID, &tOld, 0),
  92991. sqlite3ExprAlloc(db, TK_ID, &tToCol, 0)
  92992. , 0),
  92993. sqlite3ExprAlloc(db, TK_ID, &tFromCol, 0)
  92994. , 0);
  92995. pWhere = sqlite3ExprAnd(db, pWhere, pEq);
  92996. /* For ON UPDATE, construct the next term of the WHEN clause.
  92997. ** The final WHEN clause will be like this:
  92998. **
  92999. ** WHEN NOT(old.col1 IS new.col1 AND ... AND old.colN IS new.colN)
  93000. */
  93001. if( pChanges ){
  93002. pEq = sqlite3PExpr(pParse, TK_IS,
  93003. sqlite3PExpr(pParse, TK_DOT,
  93004. sqlite3ExprAlloc(db, TK_ID, &tOld, 0),
  93005. sqlite3ExprAlloc(db, TK_ID, &tToCol, 0),
  93006. 0),
  93007. sqlite3PExpr(pParse, TK_DOT,
  93008. sqlite3ExprAlloc(db, TK_ID, &tNew, 0),
  93009. sqlite3ExprAlloc(db, TK_ID, &tToCol, 0),
  93010. 0),
  93011. 0);
  93012. pWhen = sqlite3ExprAnd(db, pWhen, pEq);
  93013. }
  93014. if( action!=OE_Restrict && (action!=OE_Cascade || pChanges) ){
  93015. Expr *pNew;
  93016. if( action==OE_Cascade ){
  93017. pNew = sqlite3PExpr(pParse, TK_DOT,
  93018. sqlite3ExprAlloc(db, TK_ID, &tNew, 0),
  93019. sqlite3ExprAlloc(db, TK_ID, &tToCol, 0)
  93020. , 0);
  93021. }else if( action==OE_SetDflt ){
  93022. Expr *pDflt = pFKey->pFrom->aCol[iFromCol].pDflt;
  93023. if( pDflt ){
  93024. pNew = sqlite3ExprDup(db, pDflt, 0);
  93025. }else{
  93026. pNew = sqlite3PExpr(pParse, TK_NULL, 0, 0, 0);
  93027. }
  93028. }else{
  93029. pNew = sqlite3PExpr(pParse, TK_NULL, 0, 0, 0);
  93030. }
  93031. pList = sqlite3ExprListAppend(pParse, pList, pNew);
  93032. sqlite3ExprListSetName(pParse, pList, &tFromCol, 0);
  93033. }
  93034. }
  93035. sqlite3DbFree(db, aiCol);
  93036. zFrom = pFKey->pFrom->zName;
  93037. nFrom = sqlite3Strlen30(zFrom);
  93038. if( action==OE_Restrict ){
  93039. Token tFrom;
  93040. Expr *pRaise;
  93041. tFrom.z = zFrom;
  93042. tFrom.n = nFrom;
  93043. pRaise = sqlite3Expr(db, TK_RAISE, "FOREIGN KEY constraint failed");
  93044. if( pRaise ){
  93045. pRaise->affinity = OE_Abort;
  93046. }
  93047. pSelect = sqlite3SelectNew(pParse,
  93048. sqlite3ExprListAppend(pParse, 0, pRaise),
  93049. sqlite3SrcListAppend(db, 0, &tFrom, 0),
  93050. pWhere,
  93051. 0, 0, 0, 0, 0, 0
  93052. );
  93053. pWhere = 0;
  93054. }
  93055. /* Disable lookaside memory allocation */
  93056. enableLookaside = db->lookaside.bEnabled;
  93057. db->lookaside.bEnabled = 0;
  93058. pTrigger = (Trigger *)sqlite3DbMallocZero(db,
  93059. sizeof(Trigger) + /* struct Trigger */
  93060. sizeof(TriggerStep) + /* Single step in trigger program */
  93061. nFrom + 1 /* Space for pStep->zTarget */
  93062. );
  93063. if( pTrigger ){
  93064. pStep = pTrigger->step_list = (TriggerStep *)&pTrigger[1];
  93065. pStep->zTarget = (char *)&pStep[1];
  93066. memcpy((char *)pStep->zTarget, zFrom, nFrom);
  93067. pStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE);
  93068. pStep->pExprList = sqlite3ExprListDup(db, pList, EXPRDUP_REDUCE);
  93069. pStep->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
  93070. if( pWhen ){
  93071. pWhen = sqlite3PExpr(pParse, TK_NOT, pWhen, 0, 0);
  93072. pTrigger->pWhen = sqlite3ExprDup(db, pWhen, EXPRDUP_REDUCE);
  93073. }
  93074. }
  93075. /* Re-enable the lookaside buffer, if it was disabled earlier. */
  93076. db->lookaside.bEnabled = enableLookaside;
  93077. sqlite3ExprDelete(db, pWhere);
  93078. sqlite3ExprDelete(db, pWhen);
  93079. sqlite3ExprListDelete(db, pList);
  93080. sqlite3SelectDelete(db, pSelect);
  93081. if( db->mallocFailed==1 ){
  93082. fkTriggerDelete(db, pTrigger);
  93083. return 0;
  93084. }
  93085. assert( pStep!=0 );
  93086. switch( action ){
  93087. case OE_Restrict:
  93088. pStep->op = TK_SELECT;
  93089. break;
  93090. case OE_Cascade:
  93091. if( !pChanges ){
  93092. pStep->op = TK_DELETE;
  93093. break;
  93094. }
  93095. default:
  93096. pStep->op = TK_UPDATE;
  93097. }
  93098. pStep->pTrig = pTrigger;
  93099. pTrigger->pSchema = pTab->pSchema;
  93100. pTrigger->pTabSchema = pTab->pSchema;
  93101. pFKey->apTrigger[iAction] = pTrigger;
  93102. pTrigger->op = (pChanges ? TK_UPDATE : TK_DELETE);
  93103. }
  93104. return pTrigger;
  93105. }
  93106. /*
  93107. ** This function is called when deleting or updating a row to implement
  93108. ** any required CASCADE, SET NULL or SET DEFAULT actions.
  93109. */
  93110. SQLITE_PRIVATE void sqlite3FkActions(
  93111. Parse *pParse, /* Parse context */
  93112. Table *pTab, /* Table being updated or deleted from */
  93113. ExprList *pChanges, /* Change-list for UPDATE, NULL for DELETE */
  93114. int regOld, /* Address of array containing old row */
  93115. int *aChange, /* Array indicating UPDATEd columns (or 0) */
  93116. int bChngRowid /* True if rowid is UPDATEd */
  93117. ){
  93118. /* If foreign-key support is enabled, iterate through all FKs that
  93119. ** refer to table pTab. If there is an action associated with the FK
  93120. ** for this operation (either update or delete), invoke the associated
  93121. ** trigger sub-program. */
  93122. if( pParse->db->flags&SQLITE_ForeignKeys ){
  93123. FKey *pFKey; /* Iterator variable */
  93124. for(pFKey = sqlite3FkReferences(pTab); pFKey; pFKey=pFKey->pNextTo){
  93125. if( aChange==0 || fkParentIsModified(pTab, pFKey, aChange, bChngRowid) ){
  93126. Trigger *pAct = fkActionTrigger(pParse, pTab, pFKey, pChanges);
  93127. if( pAct ){
  93128. sqlite3CodeRowTriggerDirect(pParse, pAct, pTab, regOld, OE_Abort, 0);
  93129. }
  93130. }
  93131. }
  93132. }
  93133. }
  93134. #endif /* ifndef SQLITE_OMIT_TRIGGER */
  93135. /*
  93136. ** Free all memory associated with foreign key definitions attached to
  93137. ** table pTab. Remove the deleted foreign keys from the Schema.fkeyHash
  93138. ** hash table.
  93139. */
  93140. SQLITE_PRIVATE void sqlite3FkDelete(sqlite3 *db, Table *pTab){
  93141. FKey *pFKey; /* Iterator variable */
  93142. FKey *pNext; /* Copy of pFKey->pNextFrom */
  93143. assert( db==0 || sqlite3SchemaMutexHeld(db, 0, pTab->pSchema) );
  93144. for(pFKey=pTab->pFKey; pFKey; pFKey=pNext){
  93145. /* Remove the FK from the fkeyHash hash table. */
  93146. if( !db || db->pnBytesFreed==0 ){
  93147. if( pFKey->pPrevTo ){
  93148. pFKey->pPrevTo->pNextTo = pFKey->pNextTo;
  93149. }else{
  93150. void *p = (void *)pFKey->pNextTo;
  93151. const char *z = (p ? pFKey->pNextTo->zTo : pFKey->zTo);
  93152. sqlite3HashInsert(&pTab->pSchema->fkeyHash, z, p);
  93153. }
  93154. if( pFKey->pNextTo ){
  93155. pFKey->pNextTo->pPrevTo = pFKey->pPrevTo;
  93156. }
  93157. }
  93158. /* EV: R-30323-21917 Each foreign key constraint in SQLite is
  93159. ** classified as either immediate or deferred.
  93160. */
  93161. assert( pFKey->isDeferred==0 || pFKey->isDeferred==1 );
  93162. /* Delete any triggers created to implement actions for this FK. */
  93163. #ifndef SQLITE_OMIT_TRIGGER
  93164. fkTriggerDelete(db, pFKey->apTrigger[0]);
  93165. fkTriggerDelete(db, pFKey->apTrigger[1]);
  93166. #endif
  93167. pNext = pFKey->pNextFrom;
  93168. sqlite3DbFree(db, pFKey);
  93169. }
  93170. }
  93171. #endif /* ifndef SQLITE_OMIT_FOREIGN_KEY */
  93172. /************** End of fkey.c ************************************************/
  93173. /************** Begin file insert.c ******************************************/
  93174. /*
  93175. ** 2001 September 15
  93176. **
  93177. ** The author disclaims copyright to this source code. In place of
  93178. ** a legal notice, here is a blessing:
  93179. **
  93180. ** May you do good and not evil.
  93181. ** May you find forgiveness for yourself and forgive others.
  93182. ** May you share freely, never taking more than you give.
  93183. **
  93184. *************************************************************************
  93185. ** This file contains C code routines that are called by the parser
  93186. ** to handle INSERT statements in SQLite.
  93187. */
  93188. /*
  93189. ** Generate code that will
  93190. **
  93191. ** (1) acquire a lock for table pTab then
  93192. ** (2) open pTab as cursor iCur.
  93193. **
  93194. ** If pTab is a WITHOUT ROWID table, then it is the PRIMARY KEY index
  93195. ** for that table that is actually opened.
  93196. */
  93197. SQLITE_PRIVATE void sqlite3OpenTable(
  93198. Parse *pParse, /* Generate code into this VDBE */
  93199. int iCur, /* The cursor number of the table */
  93200. int iDb, /* The database index in sqlite3.aDb[] */
  93201. Table *pTab, /* The table to be opened */
  93202. int opcode /* OP_OpenRead or OP_OpenWrite */
  93203. ){
  93204. Vdbe *v;
  93205. assert( !IsVirtual(pTab) );
  93206. v = sqlite3GetVdbe(pParse);
  93207. assert( opcode==OP_OpenWrite || opcode==OP_OpenRead );
  93208. sqlite3TableLock(pParse, iDb, pTab->tnum,
  93209. (opcode==OP_OpenWrite)?1:0, pTab->zName);
  93210. if( HasRowid(pTab) ){
  93211. sqlite3VdbeAddOp4Int(v, opcode, iCur, pTab->tnum, iDb, pTab->nCol);
  93212. VdbeComment((v, "%s", pTab->zName));
  93213. }else{
  93214. Index *pPk = sqlite3PrimaryKeyIndex(pTab);
  93215. assert( pPk!=0 );
  93216. assert( pPk->tnum=pTab->tnum );
  93217. sqlite3VdbeAddOp3(v, opcode, iCur, pPk->tnum, iDb);
  93218. sqlite3VdbeSetP4KeyInfo(pParse, pPk);
  93219. VdbeComment((v, "%s", pTab->zName));
  93220. }
  93221. }
  93222. /*
  93223. ** Return a pointer to the column affinity string associated with index
  93224. ** pIdx. A column affinity string has one character for each column in
  93225. ** the table, according to the affinity of the column:
  93226. **
  93227. ** Character Column affinity
  93228. ** ------------------------------
  93229. ** 'A' NONE
  93230. ** 'B' TEXT
  93231. ** 'C' NUMERIC
  93232. ** 'D' INTEGER
  93233. ** 'F' REAL
  93234. **
  93235. ** An extra 'D' is appended to the end of the string to cover the
  93236. ** rowid that appears as the last column in every index.
  93237. **
  93238. ** Memory for the buffer containing the column index affinity string
  93239. ** is managed along with the rest of the Index structure. It will be
  93240. ** released when sqlite3DeleteIndex() is called.
  93241. */
  93242. SQLITE_PRIVATE const char *sqlite3IndexAffinityStr(Vdbe *v, Index *pIdx){
  93243. if( !pIdx->zColAff ){
  93244. /* The first time a column affinity string for a particular index is
  93245. ** required, it is allocated and populated here. It is then stored as
  93246. ** a member of the Index structure for subsequent use.
  93247. **
  93248. ** The column affinity string will eventually be deleted by
  93249. ** sqliteDeleteIndex() when the Index structure itself is cleaned
  93250. ** up.
  93251. */
  93252. int n;
  93253. Table *pTab = pIdx->pTable;
  93254. sqlite3 *db = sqlite3VdbeDb(v);
  93255. pIdx->zColAff = (char *)sqlite3DbMallocRaw(0, pIdx->nColumn+1);
  93256. if( !pIdx->zColAff ){
  93257. db->mallocFailed = 1;
  93258. return 0;
  93259. }
  93260. for(n=0; n<pIdx->nColumn; n++){
  93261. i16 x = pIdx->aiColumn[n];
  93262. pIdx->zColAff[n] = x<0 ? SQLITE_AFF_INTEGER : pTab->aCol[x].affinity;
  93263. }
  93264. pIdx->zColAff[n] = 0;
  93265. }
  93266. return pIdx->zColAff;
  93267. }
  93268. /*
  93269. ** Compute the affinity string for table pTab, if it has not already been
  93270. ** computed. As an optimization, omit trailing SQLITE_AFF_NONE affinities.
  93271. **
  93272. ** If the affinity exists (if it is no entirely SQLITE_AFF_NONE values) and
  93273. ** if iReg>0 then code an OP_Affinity opcode that will set the affinities
  93274. ** for register iReg and following. Or if affinities exists and iReg==0,
  93275. ** then just set the P4 operand of the previous opcode (which should be
  93276. ** an OP_MakeRecord) to the affinity string.
  93277. **
  93278. ** A column affinity string has one character per column:
  93279. **
  93280. ** Character Column affinity
  93281. ** ------------------------------
  93282. ** 'A' NONE
  93283. ** 'B' TEXT
  93284. ** 'C' NUMERIC
  93285. ** 'D' INTEGER
  93286. ** 'E' REAL
  93287. */
  93288. SQLITE_PRIVATE void sqlite3TableAffinity(Vdbe *v, Table *pTab, int iReg){
  93289. int i;
  93290. char *zColAff = pTab->zColAff;
  93291. if( zColAff==0 ){
  93292. sqlite3 *db = sqlite3VdbeDb(v);
  93293. zColAff = (char *)sqlite3DbMallocRaw(0, pTab->nCol+1);
  93294. if( !zColAff ){
  93295. db->mallocFailed = 1;
  93296. return;
  93297. }
  93298. for(i=0; i<pTab->nCol; i++){
  93299. zColAff[i] = pTab->aCol[i].affinity;
  93300. }
  93301. do{
  93302. zColAff[i--] = 0;
  93303. }while( i>=0 && zColAff[i]==SQLITE_AFF_NONE );
  93304. pTab->zColAff = zColAff;
  93305. }
  93306. i = sqlite3Strlen30(zColAff);
  93307. if( i ){
  93308. if( iReg ){
  93309. sqlite3VdbeAddOp4(v, OP_Affinity, iReg, i, 0, zColAff, i);
  93310. }else{
  93311. sqlite3VdbeChangeP4(v, -1, zColAff, i);
  93312. }
  93313. }
  93314. }
  93315. /*
  93316. ** Return non-zero if the table pTab in database iDb or any of its indices
  93317. ** have been opened at any point in the VDBE program. This is used to see if
  93318. ** a statement of the form "INSERT INTO <iDb, pTab> SELECT ..." can
  93319. ** run without using a temporary table for the results of the SELECT.
  93320. */
  93321. static int readsTable(Parse *p, int iDb, Table *pTab){
  93322. Vdbe *v = sqlite3GetVdbe(p);
  93323. int i;
  93324. int iEnd = sqlite3VdbeCurrentAddr(v);
  93325. #ifndef SQLITE_OMIT_VIRTUALTABLE
  93326. VTable *pVTab = IsVirtual(pTab) ? sqlite3GetVTable(p->db, pTab) : 0;
  93327. #endif
  93328. for(i=1; i<iEnd; i++){
  93329. VdbeOp *pOp = sqlite3VdbeGetOp(v, i);
  93330. assert( pOp!=0 );
  93331. if( pOp->opcode==OP_OpenRead && pOp->p3==iDb ){
  93332. Index *pIndex;
  93333. int tnum = pOp->p2;
  93334. if( tnum==pTab->tnum ){
  93335. return 1;
  93336. }
  93337. for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){
  93338. if( tnum==pIndex->tnum ){
  93339. return 1;
  93340. }
  93341. }
  93342. }
  93343. #ifndef SQLITE_OMIT_VIRTUALTABLE
  93344. if( pOp->opcode==OP_VOpen && pOp->p4.pVtab==pVTab ){
  93345. assert( pOp->p4.pVtab!=0 );
  93346. assert( pOp->p4type==P4_VTAB );
  93347. return 1;
  93348. }
  93349. #endif
  93350. }
  93351. return 0;
  93352. }
  93353. #ifndef SQLITE_OMIT_AUTOINCREMENT
  93354. /*
  93355. ** Locate or create an AutoincInfo structure associated with table pTab
  93356. ** which is in database iDb. Return the register number for the register
  93357. ** that holds the maximum rowid.
  93358. **
  93359. ** There is at most one AutoincInfo structure per table even if the
  93360. ** same table is autoincremented multiple times due to inserts within
  93361. ** triggers. A new AutoincInfo structure is created if this is the
  93362. ** first use of table pTab. On 2nd and subsequent uses, the original
  93363. ** AutoincInfo structure is used.
  93364. **
  93365. ** Three memory locations are allocated:
  93366. **
  93367. ** (1) Register to hold the name of the pTab table.
  93368. ** (2) Register to hold the maximum ROWID of pTab.
  93369. ** (3) Register to hold the rowid in sqlite_sequence of pTab
  93370. **
  93371. ** The 2nd register is the one that is returned. That is all the
  93372. ** insert routine needs to know about.
  93373. */
  93374. static int autoIncBegin(
  93375. Parse *pParse, /* Parsing context */
  93376. int iDb, /* Index of the database holding pTab */
  93377. Table *pTab /* The table we are writing to */
  93378. ){
  93379. int memId = 0; /* Register holding maximum rowid */
  93380. if( pTab->tabFlags & TF_Autoincrement ){
  93381. Parse *pToplevel = sqlite3ParseToplevel(pParse);
  93382. AutoincInfo *pInfo;
  93383. pInfo = pToplevel->pAinc;
  93384. while( pInfo && pInfo->pTab!=pTab ){ pInfo = pInfo->pNext; }
  93385. if( pInfo==0 ){
  93386. pInfo = sqlite3DbMallocRaw(pParse->db, sizeof(*pInfo));
  93387. if( pInfo==0 ) return 0;
  93388. pInfo->pNext = pToplevel->pAinc;
  93389. pToplevel->pAinc = pInfo;
  93390. pInfo->pTab = pTab;
  93391. pInfo->iDb = iDb;
  93392. pToplevel->nMem++; /* Register to hold name of table */
  93393. pInfo->regCtr = ++pToplevel->nMem; /* Max rowid register */
  93394. pToplevel->nMem++; /* Rowid in sqlite_sequence */
  93395. }
  93396. memId = pInfo->regCtr;
  93397. }
  93398. return memId;
  93399. }
  93400. /*
  93401. ** This routine generates code that will initialize all of the
  93402. ** register used by the autoincrement tracker.
  93403. */
  93404. SQLITE_PRIVATE void sqlite3AutoincrementBegin(Parse *pParse){
  93405. AutoincInfo *p; /* Information about an AUTOINCREMENT */
  93406. sqlite3 *db = pParse->db; /* The database connection */
  93407. Db *pDb; /* Database only autoinc table */
  93408. int memId; /* Register holding max rowid */
  93409. int addr; /* A VDBE address */
  93410. Vdbe *v = pParse->pVdbe; /* VDBE under construction */
  93411. /* This routine is never called during trigger-generation. It is
  93412. ** only called from the top-level */
  93413. assert( pParse->pTriggerTab==0 );
  93414. assert( pParse==sqlite3ParseToplevel(pParse) );
  93415. assert( v ); /* We failed long ago if this is not so */
  93416. for(p = pParse->pAinc; p; p = p->pNext){
  93417. pDb = &db->aDb[p->iDb];
  93418. memId = p->regCtr;
  93419. assert( sqlite3SchemaMutexHeld(db, 0, pDb->pSchema) );
  93420. sqlite3OpenTable(pParse, 0, p->iDb, pDb->pSchema->pSeqTab, OP_OpenRead);
  93421. sqlite3VdbeAddOp3(v, OP_Null, 0, memId, memId+1);
  93422. addr = sqlite3VdbeCurrentAddr(v);
  93423. sqlite3VdbeAddOp4(v, OP_String8, 0, memId-1, 0, p->pTab->zName, 0);
  93424. sqlite3VdbeAddOp2(v, OP_Rewind, 0, addr+9); VdbeCoverage(v);
  93425. sqlite3VdbeAddOp3(v, OP_Column, 0, 0, memId);
  93426. sqlite3VdbeAddOp3(v, OP_Ne, memId-1, addr+7, memId); VdbeCoverage(v);
  93427. sqlite3VdbeChangeP5(v, SQLITE_JUMPIFNULL);
  93428. sqlite3VdbeAddOp2(v, OP_Rowid, 0, memId+1);
  93429. sqlite3VdbeAddOp3(v, OP_Column, 0, 1, memId);
  93430. sqlite3VdbeAddOp2(v, OP_Goto, 0, addr+9);
  93431. sqlite3VdbeAddOp2(v, OP_Next, 0, addr+2); VdbeCoverage(v);
  93432. sqlite3VdbeAddOp2(v, OP_Integer, 0, memId);
  93433. sqlite3VdbeAddOp0(v, OP_Close);
  93434. }
  93435. }
  93436. /*
  93437. ** Update the maximum rowid for an autoincrement calculation.
  93438. **
  93439. ** This routine should be called when the top of the stack holds a
  93440. ** new rowid that is about to be inserted. If that new rowid is
  93441. ** larger than the maximum rowid in the memId memory cell, then the
  93442. ** memory cell is updated. The stack is unchanged.
  93443. */
  93444. static void autoIncStep(Parse *pParse, int memId, int regRowid){
  93445. if( memId>0 ){
  93446. sqlite3VdbeAddOp2(pParse->pVdbe, OP_MemMax, memId, regRowid);
  93447. }
  93448. }
  93449. /*
  93450. ** This routine generates the code needed to write autoincrement
  93451. ** maximum rowid values back into the sqlite_sequence register.
  93452. ** Every statement that might do an INSERT into an autoincrement
  93453. ** table (either directly or through triggers) needs to call this
  93454. ** routine just before the "exit" code.
  93455. */
  93456. SQLITE_PRIVATE void sqlite3AutoincrementEnd(Parse *pParse){
  93457. AutoincInfo *p;
  93458. Vdbe *v = pParse->pVdbe;
  93459. sqlite3 *db = pParse->db;
  93460. assert( v );
  93461. for(p = pParse->pAinc; p; p = p->pNext){
  93462. Db *pDb = &db->aDb[p->iDb];
  93463. int j1;
  93464. int iRec;
  93465. int memId = p->regCtr;
  93466. iRec = sqlite3GetTempReg(pParse);
  93467. assert( sqlite3SchemaMutexHeld(db, 0, pDb->pSchema) );
  93468. sqlite3OpenTable(pParse, 0, p->iDb, pDb->pSchema->pSeqTab, OP_OpenWrite);
  93469. j1 = sqlite3VdbeAddOp1(v, OP_NotNull, memId+1); VdbeCoverage(v);
  93470. sqlite3VdbeAddOp2(v, OP_NewRowid, 0, memId+1);
  93471. sqlite3VdbeJumpHere(v, j1);
  93472. sqlite3VdbeAddOp3(v, OP_MakeRecord, memId-1, 2, iRec);
  93473. sqlite3VdbeAddOp3(v, OP_Insert, 0, iRec, memId+1);
  93474. sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
  93475. sqlite3VdbeAddOp0(v, OP_Close);
  93476. sqlite3ReleaseTempReg(pParse, iRec);
  93477. }
  93478. }
  93479. #else
  93480. /*
  93481. ** If SQLITE_OMIT_AUTOINCREMENT is defined, then the three routines
  93482. ** above are all no-ops
  93483. */
  93484. # define autoIncBegin(A,B,C) (0)
  93485. # define autoIncStep(A,B,C)
  93486. #endif /* SQLITE_OMIT_AUTOINCREMENT */
  93487. /* Forward declaration */
  93488. static int xferOptimization(
  93489. Parse *pParse, /* Parser context */
  93490. Table *pDest, /* The table we are inserting into */
  93491. Select *pSelect, /* A SELECT statement to use as the data source */
  93492. int onError, /* How to handle constraint errors */
  93493. int iDbDest /* The database of pDest */
  93494. );
  93495. /*
  93496. ** This routine is called to handle SQL of the following forms:
  93497. **
  93498. ** insert into TABLE (IDLIST) values(EXPRLIST),(EXPRLIST),...
  93499. ** insert into TABLE (IDLIST) select
  93500. ** insert into TABLE (IDLIST) default values
  93501. **
  93502. ** The IDLIST following the table name is always optional. If omitted,
  93503. ** then a list of all (non-hidden) columns for the table is substituted.
  93504. ** The IDLIST appears in the pColumn parameter. pColumn is NULL if IDLIST
  93505. ** is omitted.
  93506. **
  93507. ** For the pSelect parameter holds the values to be inserted for the
  93508. ** first two forms shown above. A VALUES clause is really just short-hand
  93509. ** for a SELECT statement that omits the FROM clause and everything else
  93510. ** that follows. If the pSelect parameter is NULL, that means that the
  93511. ** DEFAULT VALUES form of the INSERT statement is intended.
  93512. **
  93513. ** The code generated follows one of four templates. For a simple
  93514. ** insert with data coming from a single-row VALUES clause, the code executes
  93515. ** once straight down through. Pseudo-code follows (we call this
  93516. ** the "1st template"):
  93517. **
  93518. ** open write cursor to <table> and its indices
  93519. ** put VALUES clause expressions into registers
  93520. ** write the resulting record into <table>
  93521. ** cleanup
  93522. **
  93523. ** The three remaining templates assume the statement is of the form
  93524. **
  93525. ** INSERT INTO <table> SELECT ...
  93526. **
  93527. ** If the SELECT clause is of the restricted form "SELECT * FROM <table2>" -
  93528. ** in other words if the SELECT pulls all columns from a single table
  93529. ** and there is no WHERE or LIMIT or GROUP BY or ORDER BY clauses, and
  93530. ** if <table2> and <table1> are distinct tables but have identical
  93531. ** schemas, including all the same indices, then a special optimization
  93532. ** is invoked that copies raw records from <table2> over to <table1>.
  93533. ** See the xferOptimization() function for the implementation of this
  93534. ** template. This is the 2nd template.
  93535. **
  93536. ** open a write cursor to <table>
  93537. ** open read cursor on <table2>
  93538. ** transfer all records in <table2> over to <table>
  93539. ** close cursors
  93540. ** foreach index on <table>
  93541. ** open a write cursor on the <table> index
  93542. ** open a read cursor on the corresponding <table2> index
  93543. ** transfer all records from the read to the write cursors
  93544. ** close cursors
  93545. ** end foreach
  93546. **
  93547. ** The 3rd template is for when the second template does not apply
  93548. ** and the SELECT clause does not read from <table> at any time.
  93549. ** The generated code follows this template:
  93550. **
  93551. ** X <- A
  93552. ** goto B
  93553. ** A: setup for the SELECT
  93554. ** loop over the rows in the SELECT
  93555. ** load values into registers R..R+n
  93556. ** yield X
  93557. ** end loop
  93558. ** cleanup after the SELECT
  93559. ** end-coroutine X
  93560. ** B: open write cursor to <table> and its indices
  93561. ** C: yield X, at EOF goto D
  93562. ** insert the select result into <table> from R..R+n
  93563. ** goto C
  93564. ** D: cleanup
  93565. **
  93566. ** The 4th template is used if the insert statement takes its
  93567. ** values from a SELECT but the data is being inserted into a table
  93568. ** that is also read as part of the SELECT. In the third form,
  93569. ** we have to use an intermediate table to store the results of
  93570. ** the select. The template is like this:
  93571. **
  93572. ** X <- A
  93573. ** goto B
  93574. ** A: setup for the SELECT
  93575. ** loop over the tables in the SELECT
  93576. ** load value into register R..R+n
  93577. ** yield X
  93578. ** end loop
  93579. ** cleanup after the SELECT
  93580. ** end co-routine R
  93581. ** B: open temp table
  93582. ** L: yield X, at EOF goto M
  93583. ** insert row from R..R+n into temp table
  93584. ** goto L
  93585. ** M: open write cursor to <table> and its indices
  93586. ** rewind temp table
  93587. ** C: loop over rows of intermediate table
  93588. ** transfer values form intermediate table into <table>
  93589. ** end loop
  93590. ** D: cleanup
  93591. */
  93592. SQLITE_PRIVATE void sqlite3Insert(
  93593. Parse *pParse, /* Parser context */
  93594. SrcList *pTabList, /* Name of table into which we are inserting */
  93595. Select *pSelect, /* A SELECT statement to use as the data source */
  93596. IdList *pColumn, /* Column names corresponding to IDLIST. */
  93597. int onError /* How to handle constraint errors */
  93598. ){
  93599. sqlite3 *db; /* The main database structure */
  93600. Table *pTab; /* The table to insert into. aka TABLE */
  93601. char *zTab; /* Name of the table into which we are inserting */
  93602. const char *zDb; /* Name of the database holding this table */
  93603. int i, j, idx; /* Loop counters */
  93604. Vdbe *v; /* Generate code into this virtual machine */
  93605. Index *pIdx; /* For looping over indices of the table */
  93606. int nColumn; /* Number of columns in the data */
  93607. int nHidden = 0; /* Number of hidden columns if TABLE is virtual */
  93608. int iDataCur = 0; /* VDBE cursor that is the main data repository */
  93609. int iIdxCur = 0; /* First index cursor */
  93610. int ipkColumn = -1; /* Column that is the INTEGER PRIMARY KEY */
  93611. int endOfLoop; /* Label for the end of the insertion loop */
  93612. int srcTab = 0; /* Data comes from this temporary cursor if >=0 */
  93613. int addrInsTop = 0; /* Jump to label "D" */
  93614. int addrCont = 0; /* Top of insert loop. Label "C" in templates 3 and 4 */
  93615. SelectDest dest; /* Destination for SELECT on rhs of INSERT */
  93616. int iDb; /* Index of database holding TABLE */
  93617. Db *pDb; /* The database containing table being inserted into */
  93618. u8 useTempTable = 0; /* Store SELECT results in intermediate table */
  93619. u8 appendFlag = 0; /* True if the insert is likely to be an append */
  93620. u8 withoutRowid; /* 0 for normal table. 1 for WITHOUT ROWID table */
  93621. u8 bIdListInOrder; /* True if IDLIST is in table order */
  93622. ExprList *pList = 0; /* List of VALUES() to be inserted */
  93623. /* Register allocations */
  93624. int regFromSelect = 0;/* Base register for data coming from SELECT */
  93625. int regAutoinc = 0; /* Register holding the AUTOINCREMENT counter */
  93626. int regRowCount = 0; /* Memory cell used for the row counter */
  93627. int regIns; /* Block of regs holding rowid+data being inserted */
  93628. int regRowid; /* registers holding insert rowid */
  93629. int regData; /* register holding first column to insert */
  93630. int *aRegIdx = 0; /* One register allocated to each index */
  93631. #ifndef SQLITE_OMIT_TRIGGER
  93632. int isView; /* True if attempting to insert into a view */
  93633. Trigger *pTrigger; /* List of triggers on pTab, if required */
  93634. int tmask; /* Mask of trigger times */
  93635. #endif
  93636. db = pParse->db;
  93637. memset(&dest, 0, sizeof(dest));
  93638. if( pParse->nErr || db->mallocFailed ){
  93639. goto insert_cleanup;
  93640. }
  93641. /* If the Select object is really just a simple VALUES() list with a
  93642. ** single row (the common case) then keep that one row of values
  93643. ** and discard the other (unused) parts of the pSelect object
  93644. */
  93645. if( pSelect && (pSelect->selFlags & SF_Values)!=0 && pSelect->pPrior==0 ){
  93646. pList = pSelect->pEList;
  93647. pSelect->pEList = 0;
  93648. sqlite3SelectDelete(db, pSelect);
  93649. pSelect = 0;
  93650. }
  93651. /* Locate the table into which we will be inserting new information.
  93652. */
  93653. assert( pTabList->nSrc==1 );
  93654. zTab = pTabList->a[0].zName;
  93655. if( NEVER(zTab==0) ) goto insert_cleanup;
  93656. pTab = sqlite3SrcListLookup(pParse, pTabList);
  93657. if( pTab==0 ){
  93658. goto insert_cleanup;
  93659. }
  93660. iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  93661. assert( iDb<db->nDb );
  93662. pDb = &db->aDb[iDb];
  93663. zDb = pDb->zName;
  93664. if( sqlite3AuthCheck(pParse, SQLITE_INSERT, pTab->zName, 0, zDb) ){
  93665. goto insert_cleanup;
  93666. }
  93667. withoutRowid = !HasRowid(pTab);
  93668. /* Figure out if we have any triggers and if the table being
  93669. ** inserted into is a view
  93670. */
  93671. #ifndef SQLITE_OMIT_TRIGGER
  93672. pTrigger = sqlite3TriggersExist(pParse, pTab, TK_INSERT, 0, &tmask);
  93673. isView = pTab->pSelect!=0;
  93674. #else
  93675. # define pTrigger 0
  93676. # define tmask 0
  93677. # define isView 0
  93678. #endif
  93679. #ifdef SQLITE_OMIT_VIEW
  93680. # undef isView
  93681. # define isView 0
  93682. #endif
  93683. assert( (pTrigger && tmask) || (pTrigger==0 && tmask==0) );
  93684. /* If pTab is really a view, make sure it has been initialized.
  93685. ** ViewGetColumnNames() is a no-op if pTab is not a view.
  93686. */
  93687. if( sqlite3ViewGetColumnNames(pParse, pTab) ){
  93688. goto insert_cleanup;
  93689. }
  93690. /* Cannot insert into a read-only table.
  93691. */
  93692. if( sqlite3IsReadOnly(pParse, pTab, tmask) ){
  93693. goto insert_cleanup;
  93694. }
  93695. /* Allocate a VDBE
  93696. */
  93697. v = sqlite3GetVdbe(pParse);
  93698. if( v==0 ) goto insert_cleanup;
  93699. if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
  93700. sqlite3BeginWriteOperation(pParse, pSelect || pTrigger, iDb);
  93701. #ifndef SQLITE_OMIT_XFER_OPT
  93702. /* If the statement is of the form
  93703. **
  93704. ** INSERT INTO <table1> SELECT * FROM <table2>;
  93705. **
  93706. ** Then special optimizations can be applied that make the transfer
  93707. ** very fast and which reduce fragmentation of indices.
  93708. **
  93709. ** This is the 2nd template.
  93710. */
  93711. if( pColumn==0 && xferOptimization(pParse, pTab, pSelect, onError, iDb) ){
  93712. assert( !pTrigger );
  93713. assert( pList==0 );
  93714. goto insert_end;
  93715. }
  93716. #endif /* SQLITE_OMIT_XFER_OPT */
  93717. /* If this is an AUTOINCREMENT table, look up the sequence number in the
  93718. ** sqlite_sequence table and store it in memory cell regAutoinc.
  93719. */
  93720. regAutoinc = autoIncBegin(pParse, iDb, pTab);
  93721. /* Allocate registers for holding the rowid of the new row,
  93722. ** the content of the new row, and the assembled row record.
  93723. */
  93724. regRowid = regIns = pParse->nMem+1;
  93725. pParse->nMem += pTab->nCol + 1;
  93726. if( IsVirtual(pTab) ){
  93727. regRowid++;
  93728. pParse->nMem++;
  93729. }
  93730. regData = regRowid+1;
  93731. /* If the INSERT statement included an IDLIST term, then make sure
  93732. ** all elements of the IDLIST really are columns of the table and
  93733. ** remember the column indices.
  93734. **
  93735. ** If the table has an INTEGER PRIMARY KEY column and that column
  93736. ** is named in the IDLIST, then record in the ipkColumn variable
  93737. ** the index into IDLIST of the primary key column. ipkColumn is
  93738. ** the index of the primary key as it appears in IDLIST, not as
  93739. ** is appears in the original table. (The index of the INTEGER
  93740. ** PRIMARY KEY in the original table is pTab->iPKey.)
  93741. */
  93742. bIdListInOrder = (pTab->tabFlags & TF_OOOHidden)==0;
  93743. if( pColumn ){
  93744. for(i=0; i<pColumn->nId; i++){
  93745. pColumn->a[i].idx = -1;
  93746. }
  93747. for(i=0; i<pColumn->nId; i++){
  93748. for(j=0; j<pTab->nCol; j++){
  93749. if( sqlite3StrICmp(pColumn->a[i].zName, pTab->aCol[j].zName)==0 ){
  93750. pColumn->a[i].idx = j;
  93751. if( i!=j ) bIdListInOrder = 0;
  93752. if( j==pTab->iPKey ){
  93753. ipkColumn = i; assert( !withoutRowid );
  93754. }
  93755. break;
  93756. }
  93757. }
  93758. if( j>=pTab->nCol ){
  93759. if( sqlite3IsRowid(pColumn->a[i].zName) && !withoutRowid ){
  93760. ipkColumn = i;
  93761. bIdListInOrder = 0;
  93762. }else{
  93763. sqlite3ErrorMsg(pParse, "table %S has no column named %s",
  93764. pTabList, 0, pColumn->a[i].zName);
  93765. pParse->checkSchema = 1;
  93766. goto insert_cleanup;
  93767. }
  93768. }
  93769. }
  93770. }
  93771. /* Figure out how many columns of data are supplied. If the data
  93772. ** is coming from a SELECT statement, then generate a co-routine that
  93773. ** produces a single row of the SELECT on each invocation. The
  93774. ** co-routine is the common header to the 3rd and 4th templates.
  93775. */
  93776. if( pSelect ){
  93777. /* Data is coming from a SELECT or from a multi-row VALUES clause.
  93778. ** Generate a co-routine to run the SELECT. */
  93779. int regYield; /* Register holding co-routine entry-point */
  93780. int addrTop; /* Top of the co-routine */
  93781. int rc; /* Result code */
  93782. regYield = ++pParse->nMem;
  93783. addrTop = sqlite3VdbeCurrentAddr(v) + 1;
  93784. sqlite3VdbeAddOp3(v, OP_InitCoroutine, regYield, 0, addrTop);
  93785. sqlite3SelectDestInit(&dest, SRT_Coroutine, regYield);
  93786. dest.iSdst = bIdListInOrder ? regData : 0;
  93787. dest.nSdst = pTab->nCol;
  93788. rc = sqlite3Select(pParse, pSelect, &dest);
  93789. regFromSelect = dest.iSdst;
  93790. if( rc || db->mallocFailed || pParse->nErr ) goto insert_cleanup;
  93791. sqlite3VdbeAddOp1(v, OP_EndCoroutine, regYield);
  93792. sqlite3VdbeJumpHere(v, addrTop - 1); /* label B: */
  93793. assert( pSelect->pEList );
  93794. nColumn = pSelect->pEList->nExpr;
  93795. /* Set useTempTable to TRUE if the result of the SELECT statement
  93796. ** should be written into a temporary table (template 4). Set to
  93797. ** FALSE if each output row of the SELECT can be written directly into
  93798. ** the destination table (template 3).
  93799. **
  93800. ** A temp table must be used if the table being updated is also one
  93801. ** of the tables being read by the SELECT statement. Also use a
  93802. ** temp table in the case of row triggers.
  93803. */
  93804. if( pTrigger || readsTable(pParse, iDb, pTab) ){
  93805. useTempTable = 1;
  93806. }
  93807. if( useTempTable ){
  93808. /* Invoke the coroutine to extract information from the SELECT
  93809. ** and add it to a transient table srcTab. The code generated
  93810. ** here is from the 4th template:
  93811. **
  93812. ** B: open temp table
  93813. ** L: yield X, goto M at EOF
  93814. ** insert row from R..R+n into temp table
  93815. ** goto L
  93816. ** M: ...
  93817. */
  93818. int regRec; /* Register to hold packed record */
  93819. int regTempRowid; /* Register to hold temp table ROWID */
  93820. int addrL; /* Label "L" */
  93821. srcTab = pParse->nTab++;
  93822. regRec = sqlite3GetTempReg(pParse);
  93823. regTempRowid = sqlite3GetTempReg(pParse);
  93824. sqlite3VdbeAddOp2(v, OP_OpenEphemeral, srcTab, nColumn);
  93825. addrL = sqlite3VdbeAddOp1(v, OP_Yield, dest.iSDParm); VdbeCoverage(v);
  93826. sqlite3VdbeAddOp3(v, OP_MakeRecord, regFromSelect, nColumn, regRec);
  93827. sqlite3VdbeAddOp2(v, OP_NewRowid, srcTab, regTempRowid);
  93828. sqlite3VdbeAddOp3(v, OP_Insert, srcTab, regRec, regTempRowid);
  93829. sqlite3VdbeAddOp2(v, OP_Goto, 0, addrL);
  93830. sqlite3VdbeJumpHere(v, addrL);
  93831. sqlite3ReleaseTempReg(pParse, regRec);
  93832. sqlite3ReleaseTempReg(pParse, regTempRowid);
  93833. }
  93834. }else{
  93835. /* This is the case if the data for the INSERT is coming from a
  93836. ** single-row VALUES clause
  93837. */
  93838. NameContext sNC;
  93839. memset(&sNC, 0, sizeof(sNC));
  93840. sNC.pParse = pParse;
  93841. srcTab = -1;
  93842. assert( useTempTable==0 );
  93843. nColumn = pList ? pList->nExpr : 0;
  93844. for(i=0; i<nColumn; i++){
  93845. if( sqlite3ResolveExprNames(&sNC, pList->a[i].pExpr) ){
  93846. goto insert_cleanup;
  93847. }
  93848. }
  93849. }
  93850. /* If there is no IDLIST term but the table has an integer primary
  93851. ** key, the set the ipkColumn variable to the integer primary key
  93852. ** column index in the original table definition.
  93853. */
  93854. if( pColumn==0 && nColumn>0 ){
  93855. ipkColumn = pTab->iPKey;
  93856. }
  93857. /* Make sure the number of columns in the source data matches the number
  93858. ** of columns to be inserted into the table.
  93859. */
  93860. if( IsVirtual(pTab) ){
  93861. for(i=0; i<pTab->nCol; i++){
  93862. nHidden += (IsHiddenColumn(&pTab->aCol[i]) ? 1 : 0);
  93863. }
  93864. }
  93865. if( pColumn==0 && nColumn && nColumn!=(pTab->nCol-nHidden) ){
  93866. sqlite3ErrorMsg(pParse,
  93867. "table %S has %d columns but %d values were supplied",
  93868. pTabList, 0, pTab->nCol-nHidden, nColumn);
  93869. goto insert_cleanup;
  93870. }
  93871. if( pColumn!=0 && nColumn!=pColumn->nId ){
  93872. sqlite3ErrorMsg(pParse, "%d values for %d columns", nColumn, pColumn->nId);
  93873. goto insert_cleanup;
  93874. }
  93875. /* Initialize the count of rows to be inserted
  93876. */
  93877. if( db->flags & SQLITE_CountRows ){
  93878. regRowCount = ++pParse->nMem;
  93879. sqlite3VdbeAddOp2(v, OP_Integer, 0, regRowCount);
  93880. }
  93881. /* If this is not a view, open the table and and all indices */
  93882. if( !isView ){
  93883. int nIdx;
  93884. nIdx = sqlite3OpenTableAndIndices(pParse, pTab, OP_OpenWrite, -1, 0,
  93885. &iDataCur, &iIdxCur);
  93886. aRegIdx = sqlite3DbMallocRaw(db, sizeof(int)*(nIdx+1));
  93887. if( aRegIdx==0 ){
  93888. goto insert_cleanup;
  93889. }
  93890. for(i=0; i<nIdx; i++){
  93891. aRegIdx[i] = ++pParse->nMem;
  93892. }
  93893. }
  93894. /* This is the top of the main insertion loop */
  93895. if( useTempTable ){
  93896. /* This block codes the top of loop only. The complete loop is the
  93897. ** following pseudocode (template 4):
  93898. **
  93899. ** rewind temp table, if empty goto D
  93900. ** C: loop over rows of intermediate table
  93901. ** transfer values form intermediate table into <table>
  93902. ** end loop
  93903. ** D: ...
  93904. */
  93905. addrInsTop = sqlite3VdbeAddOp1(v, OP_Rewind, srcTab); VdbeCoverage(v);
  93906. addrCont = sqlite3VdbeCurrentAddr(v);
  93907. }else if( pSelect ){
  93908. /* This block codes the top of loop only. The complete loop is the
  93909. ** following pseudocode (template 3):
  93910. **
  93911. ** C: yield X, at EOF goto D
  93912. ** insert the select result into <table> from R..R+n
  93913. ** goto C
  93914. ** D: ...
  93915. */
  93916. addrInsTop = addrCont = sqlite3VdbeAddOp1(v, OP_Yield, dest.iSDParm);
  93917. VdbeCoverage(v);
  93918. }
  93919. /* Run the BEFORE and INSTEAD OF triggers, if there are any
  93920. */
  93921. endOfLoop = sqlite3VdbeMakeLabel(v);
  93922. if( tmask & TRIGGER_BEFORE ){
  93923. int regCols = sqlite3GetTempRange(pParse, pTab->nCol+1);
  93924. /* build the NEW.* reference row. Note that if there is an INTEGER
  93925. ** PRIMARY KEY into which a NULL is being inserted, that NULL will be
  93926. ** translated into a unique ID for the row. But on a BEFORE trigger,
  93927. ** we do not know what the unique ID will be (because the insert has
  93928. ** not happened yet) so we substitute a rowid of -1
  93929. */
  93930. if( ipkColumn<0 ){
  93931. sqlite3VdbeAddOp2(v, OP_Integer, -1, regCols);
  93932. }else{
  93933. int j1;
  93934. assert( !withoutRowid );
  93935. if( useTempTable ){
  93936. sqlite3VdbeAddOp3(v, OP_Column, srcTab, ipkColumn, regCols);
  93937. }else{
  93938. assert( pSelect==0 ); /* Otherwise useTempTable is true */
  93939. sqlite3ExprCode(pParse, pList->a[ipkColumn].pExpr, regCols);
  93940. }
  93941. j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regCols); VdbeCoverage(v);
  93942. sqlite3VdbeAddOp2(v, OP_Integer, -1, regCols);
  93943. sqlite3VdbeJumpHere(v, j1);
  93944. sqlite3VdbeAddOp1(v, OP_MustBeInt, regCols); VdbeCoverage(v);
  93945. }
  93946. /* Cannot have triggers on a virtual table. If it were possible,
  93947. ** this block would have to account for hidden column.
  93948. */
  93949. assert( !IsVirtual(pTab) );
  93950. /* Create the new column data
  93951. */
  93952. for(i=0; i<pTab->nCol; i++){
  93953. if( pColumn==0 ){
  93954. j = i;
  93955. }else{
  93956. for(j=0; j<pColumn->nId; j++){
  93957. if( pColumn->a[j].idx==i ) break;
  93958. }
  93959. }
  93960. if( (!useTempTable && !pList) || (pColumn && j>=pColumn->nId) ){
  93961. sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, regCols+i+1);
  93962. }else if( useTempTable ){
  93963. sqlite3VdbeAddOp3(v, OP_Column, srcTab, j, regCols+i+1);
  93964. }else{
  93965. assert( pSelect==0 ); /* Otherwise useTempTable is true */
  93966. sqlite3ExprCodeAndCache(pParse, pList->a[j].pExpr, regCols+i+1);
  93967. }
  93968. }
  93969. /* If this is an INSERT on a view with an INSTEAD OF INSERT trigger,
  93970. ** do not attempt any conversions before assembling the record.
  93971. ** If this is a real table, attempt conversions as required by the
  93972. ** table column affinities.
  93973. */
  93974. if( !isView ){
  93975. sqlite3TableAffinity(v, pTab, regCols+1);
  93976. }
  93977. /* Fire BEFORE or INSTEAD OF triggers */
  93978. sqlite3CodeRowTrigger(pParse, pTrigger, TK_INSERT, 0, TRIGGER_BEFORE,
  93979. pTab, regCols-pTab->nCol-1, onError, endOfLoop);
  93980. sqlite3ReleaseTempRange(pParse, regCols, pTab->nCol+1);
  93981. }
  93982. /* Compute the content of the next row to insert into a range of
  93983. ** registers beginning at regIns.
  93984. */
  93985. if( !isView ){
  93986. if( IsVirtual(pTab) ){
  93987. /* The row that the VUpdate opcode will delete: none */
  93988. sqlite3VdbeAddOp2(v, OP_Null, 0, regIns);
  93989. }
  93990. if( ipkColumn>=0 ){
  93991. if( useTempTable ){
  93992. sqlite3VdbeAddOp3(v, OP_Column, srcTab, ipkColumn, regRowid);
  93993. }else if( pSelect ){
  93994. sqlite3VdbeAddOp2(v, OP_Copy, regFromSelect+ipkColumn, regRowid);
  93995. }else{
  93996. VdbeOp *pOp;
  93997. sqlite3ExprCode(pParse, pList->a[ipkColumn].pExpr, regRowid);
  93998. pOp = sqlite3VdbeGetOp(v, -1);
  93999. if( ALWAYS(pOp) && pOp->opcode==OP_Null && !IsVirtual(pTab) ){
  94000. appendFlag = 1;
  94001. pOp->opcode = OP_NewRowid;
  94002. pOp->p1 = iDataCur;
  94003. pOp->p2 = regRowid;
  94004. pOp->p3 = regAutoinc;
  94005. }
  94006. }
  94007. /* If the PRIMARY KEY expression is NULL, then use OP_NewRowid
  94008. ** to generate a unique primary key value.
  94009. */
  94010. if( !appendFlag ){
  94011. int j1;
  94012. if( !IsVirtual(pTab) ){
  94013. j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regRowid); VdbeCoverage(v);
  94014. sqlite3VdbeAddOp3(v, OP_NewRowid, iDataCur, regRowid, regAutoinc);
  94015. sqlite3VdbeJumpHere(v, j1);
  94016. }else{
  94017. j1 = sqlite3VdbeCurrentAddr(v);
  94018. sqlite3VdbeAddOp2(v, OP_IsNull, regRowid, j1+2); VdbeCoverage(v);
  94019. }
  94020. sqlite3VdbeAddOp1(v, OP_MustBeInt, regRowid); VdbeCoverage(v);
  94021. }
  94022. }else if( IsVirtual(pTab) || withoutRowid ){
  94023. sqlite3VdbeAddOp2(v, OP_Null, 0, regRowid);
  94024. }else{
  94025. sqlite3VdbeAddOp3(v, OP_NewRowid, iDataCur, regRowid, regAutoinc);
  94026. appendFlag = 1;
  94027. }
  94028. autoIncStep(pParse, regAutoinc, regRowid);
  94029. /* Compute data for all columns of the new entry, beginning
  94030. ** with the first column.
  94031. */
  94032. nHidden = 0;
  94033. for(i=0; i<pTab->nCol; i++){
  94034. int iRegStore = regRowid+1+i;
  94035. if( i==pTab->iPKey ){
  94036. /* The value of the INTEGER PRIMARY KEY column is always a NULL.
  94037. ** Whenever this column is read, the rowid will be substituted
  94038. ** in its place. Hence, fill this column with a NULL to avoid
  94039. ** taking up data space with information that will never be used.
  94040. ** As there may be shallow copies of this value, make it a soft-NULL */
  94041. sqlite3VdbeAddOp1(v, OP_SoftNull, iRegStore);
  94042. continue;
  94043. }
  94044. if( pColumn==0 ){
  94045. if( IsHiddenColumn(&pTab->aCol[i]) ){
  94046. assert( IsVirtual(pTab) );
  94047. j = -1;
  94048. nHidden++;
  94049. }else{
  94050. j = i - nHidden;
  94051. }
  94052. }else{
  94053. for(j=0; j<pColumn->nId; j++){
  94054. if( pColumn->a[j].idx==i ) break;
  94055. }
  94056. }
  94057. if( j<0 || nColumn==0 || (pColumn && j>=pColumn->nId) ){
  94058. sqlite3ExprCodeFactorable(pParse, pTab->aCol[i].pDflt, iRegStore);
  94059. }else if( useTempTable ){
  94060. sqlite3VdbeAddOp3(v, OP_Column, srcTab, j, iRegStore);
  94061. }else if( pSelect ){
  94062. if( regFromSelect!=regData ){
  94063. sqlite3VdbeAddOp2(v, OP_SCopy, regFromSelect+j, iRegStore);
  94064. }
  94065. }else{
  94066. sqlite3ExprCode(pParse, pList->a[j].pExpr, iRegStore);
  94067. }
  94068. }
  94069. /* Generate code to check constraints and generate index keys and
  94070. ** do the insertion.
  94071. */
  94072. #ifndef SQLITE_OMIT_VIRTUALTABLE
  94073. if( IsVirtual(pTab) ){
  94074. const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
  94075. sqlite3VtabMakeWritable(pParse, pTab);
  94076. sqlite3VdbeAddOp4(v, OP_VUpdate, 1, pTab->nCol+2, regIns, pVTab, P4_VTAB);
  94077. sqlite3VdbeChangeP5(v, onError==OE_Default ? OE_Abort : onError);
  94078. sqlite3MayAbort(pParse);
  94079. }else
  94080. #endif
  94081. {
  94082. int isReplace; /* Set to true if constraints may cause a replace */
  94083. sqlite3GenerateConstraintChecks(pParse, pTab, aRegIdx, iDataCur, iIdxCur,
  94084. regIns, 0, ipkColumn>=0, onError, endOfLoop, &isReplace
  94085. );
  94086. sqlite3FkCheck(pParse, pTab, 0, regIns, 0, 0);
  94087. sqlite3CompleteInsertion(pParse, pTab, iDataCur, iIdxCur,
  94088. regIns, aRegIdx, 0, appendFlag, isReplace==0);
  94089. }
  94090. }
  94091. /* Update the count of rows that are inserted
  94092. */
  94093. if( (db->flags & SQLITE_CountRows)!=0 ){
  94094. sqlite3VdbeAddOp2(v, OP_AddImm, regRowCount, 1);
  94095. }
  94096. if( pTrigger ){
  94097. /* Code AFTER triggers */
  94098. sqlite3CodeRowTrigger(pParse, pTrigger, TK_INSERT, 0, TRIGGER_AFTER,
  94099. pTab, regData-2-pTab->nCol, onError, endOfLoop);
  94100. }
  94101. /* The bottom of the main insertion loop, if the data source
  94102. ** is a SELECT statement.
  94103. */
  94104. sqlite3VdbeResolveLabel(v, endOfLoop);
  94105. if( useTempTable ){
  94106. sqlite3VdbeAddOp2(v, OP_Next, srcTab, addrCont); VdbeCoverage(v);
  94107. sqlite3VdbeJumpHere(v, addrInsTop);
  94108. sqlite3VdbeAddOp1(v, OP_Close, srcTab);
  94109. }else if( pSelect ){
  94110. sqlite3VdbeAddOp2(v, OP_Goto, 0, addrCont);
  94111. sqlite3VdbeJumpHere(v, addrInsTop);
  94112. }
  94113. if( !IsVirtual(pTab) && !isView ){
  94114. /* Close all tables opened */
  94115. if( iDataCur<iIdxCur ) sqlite3VdbeAddOp1(v, OP_Close, iDataCur);
  94116. for(idx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, idx++){
  94117. sqlite3VdbeAddOp1(v, OP_Close, idx+iIdxCur);
  94118. }
  94119. }
  94120. insert_end:
  94121. /* Update the sqlite_sequence table by storing the content of the
  94122. ** maximum rowid counter values recorded while inserting into
  94123. ** autoincrement tables.
  94124. */
  94125. if( pParse->nested==0 && pParse->pTriggerTab==0 ){
  94126. sqlite3AutoincrementEnd(pParse);
  94127. }
  94128. /*
  94129. ** Return the number of rows inserted. If this routine is
  94130. ** generating code because of a call to sqlite3NestedParse(), do not
  94131. ** invoke the callback function.
  94132. */
  94133. if( (db->flags&SQLITE_CountRows) && !pParse->nested && !pParse->pTriggerTab ){
  94134. sqlite3VdbeAddOp2(v, OP_ResultRow, regRowCount, 1);
  94135. sqlite3VdbeSetNumCols(v, 1);
  94136. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows inserted", SQLITE_STATIC);
  94137. }
  94138. insert_cleanup:
  94139. sqlite3SrcListDelete(db, pTabList);
  94140. sqlite3ExprListDelete(db, pList);
  94141. sqlite3SelectDelete(db, pSelect);
  94142. sqlite3IdListDelete(db, pColumn);
  94143. sqlite3DbFree(db, aRegIdx);
  94144. }
  94145. /* Make sure "isView" and other macros defined above are undefined. Otherwise
  94146. ** they may interfere with compilation of other functions in this file
  94147. ** (or in another file, if this file becomes part of the amalgamation). */
  94148. #ifdef isView
  94149. #undef isView
  94150. #endif
  94151. #ifdef pTrigger
  94152. #undef pTrigger
  94153. #endif
  94154. #ifdef tmask
  94155. #undef tmask
  94156. #endif
  94157. /*
  94158. ** Generate code to do constraint checks prior to an INSERT or an UPDATE
  94159. ** on table pTab.
  94160. **
  94161. ** The regNewData parameter is the first register in a range that contains
  94162. ** the data to be inserted or the data after the update. There will be
  94163. ** pTab->nCol+1 registers in this range. The first register (the one
  94164. ** that regNewData points to) will contain the new rowid, or NULL in the
  94165. ** case of a WITHOUT ROWID table. The second register in the range will
  94166. ** contain the content of the first table column. The third register will
  94167. ** contain the content of the second table column. And so forth.
  94168. **
  94169. ** The regOldData parameter is similar to regNewData except that it contains
  94170. ** the data prior to an UPDATE rather than afterwards. regOldData is zero
  94171. ** for an INSERT. This routine can distinguish between UPDATE and INSERT by
  94172. ** checking regOldData for zero.
  94173. **
  94174. ** For an UPDATE, the pkChng boolean is true if the true primary key (the
  94175. ** rowid for a normal table or the PRIMARY KEY for a WITHOUT ROWID table)
  94176. ** might be modified by the UPDATE. If pkChng is false, then the key of
  94177. ** the iDataCur content table is guaranteed to be unchanged by the UPDATE.
  94178. **
  94179. ** For an INSERT, the pkChng boolean indicates whether or not the rowid
  94180. ** was explicitly specified as part of the INSERT statement. If pkChng
  94181. ** is zero, it means that the either rowid is computed automatically or
  94182. ** that the table is a WITHOUT ROWID table and has no rowid. On an INSERT,
  94183. ** pkChng will only be true if the INSERT statement provides an integer
  94184. ** value for either the rowid column or its INTEGER PRIMARY KEY alias.
  94185. **
  94186. ** The code generated by this routine will store new index entries into
  94187. ** registers identified by aRegIdx[]. No index entry is created for
  94188. ** indices where aRegIdx[i]==0. The order of indices in aRegIdx[] is
  94189. ** the same as the order of indices on the linked list of indices
  94190. ** at pTab->pIndex.
  94191. **
  94192. ** The caller must have already opened writeable cursors on the main
  94193. ** table and all applicable indices (that is to say, all indices for which
  94194. ** aRegIdx[] is not zero). iDataCur is the cursor for the main table when
  94195. ** inserting or updating a rowid table, or the cursor for the PRIMARY KEY
  94196. ** index when operating on a WITHOUT ROWID table. iIdxCur is the cursor
  94197. ** for the first index in the pTab->pIndex list. Cursors for other indices
  94198. ** are at iIdxCur+N for the N-th element of the pTab->pIndex list.
  94199. **
  94200. ** This routine also generates code to check constraints. NOT NULL,
  94201. ** CHECK, and UNIQUE constraints are all checked. If a constraint fails,
  94202. ** then the appropriate action is performed. There are five possible
  94203. ** actions: ROLLBACK, ABORT, FAIL, REPLACE, and IGNORE.
  94204. **
  94205. ** Constraint type Action What Happens
  94206. ** --------------- ---------- ----------------------------------------
  94207. ** any ROLLBACK The current transaction is rolled back and
  94208. ** sqlite3_step() returns immediately with a
  94209. ** return code of SQLITE_CONSTRAINT.
  94210. **
  94211. ** any ABORT Back out changes from the current command
  94212. ** only (do not do a complete rollback) then
  94213. ** cause sqlite3_step() to return immediately
  94214. ** with SQLITE_CONSTRAINT.
  94215. **
  94216. ** any FAIL Sqlite3_step() returns immediately with a
  94217. ** return code of SQLITE_CONSTRAINT. The
  94218. ** transaction is not rolled back and any
  94219. ** changes to prior rows are retained.
  94220. **
  94221. ** any IGNORE The attempt in insert or update the current
  94222. ** row is skipped, without throwing an error.
  94223. ** Processing continues with the next row.
  94224. ** (There is an immediate jump to ignoreDest.)
  94225. **
  94226. ** NOT NULL REPLACE The NULL value is replace by the default
  94227. ** value for that column. If the default value
  94228. ** is NULL, the action is the same as ABORT.
  94229. **
  94230. ** UNIQUE REPLACE The other row that conflicts with the row
  94231. ** being inserted is removed.
  94232. **
  94233. ** CHECK REPLACE Illegal. The results in an exception.
  94234. **
  94235. ** Which action to take is determined by the overrideError parameter.
  94236. ** Or if overrideError==OE_Default, then the pParse->onError parameter
  94237. ** is used. Or if pParse->onError==OE_Default then the onError value
  94238. ** for the constraint is used.
  94239. */
  94240. SQLITE_PRIVATE void sqlite3GenerateConstraintChecks(
  94241. Parse *pParse, /* The parser context */
  94242. Table *pTab, /* The table being inserted or updated */
  94243. int *aRegIdx, /* Use register aRegIdx[i] for index i. 0 for unused */
  94244. int iDataCur, /* Canonical data cursor (main table or PK index) */
  94245. int iIdxCur, /* First index cursor */
  94246. int regNewData, /* First register in a range holding values to insert */
  94247. int regOldData, /* Previous content. 0 for INSERTs */
  94248. u8 pkChng, /* Non-zero if the rowid or PRIMARY KEY changed */
  94249. u8 overrideError, /* Override onError to this if not OE_Default */
  94250. int ignoreDest, /* Jump to this label on an OE_Ignore resolution */
  94251. int *pbMayReplace /* OUT: Set to true if constraint may cause a replace */
  94252. ){
  94253. Vdbe *v; /* VDBE under constrution */
  94254. Index *pIdx; /* Pointer to one of the indices */
  94255. Index *pPk = 0; /* The PRIMARY KEY index */
  94256. sqlite3 *db; /* Database connection */
  94257. int i; /* loop counter */
  94258. int ix; /* Index loop counter */
  94259. int nCol; /* Number of columns */
  94260. int onError; /* Conflict resolution strategy */
  94261. int j1; /* Address of jump instruction */
  94262. int seenReplace = 0; /* True if REPLACE is used to resolve INT PK conflict */
  94263. int nPkField; /* Number of fields in PRIMARY KEY. 1 for ROWID tables */
  94264. int ipkTop = 0; /* Top of the rowid change constraint check */
  94265. int ipkBottom = 0; /* Bottom of the rowid change constraint check */
  94266. u8 isUpdate; /* True if this is an UPDATE operation */
  94267. u8 bAffinityDone = 0; /* True if the OP_Affinity operation has been run */
  94268. int regRowid = -1; /* Register holding ROWID value */
  94269. isUpdate = regOldData!=0;
  94270. db = pParse->db;
  94271. v = sqlite3GetVdbe(pParse);
  94272. assert( v!=0 );
  94273. assert( pTab->pSelect==0 ); /* This table is not a VIEW */
  94274. nCol = pTab->nCol;
  94275. /* pPk is the PRIMARY KEY index for WITHOUT ROWID tables and NULL for
  94276. ** normal rowid tables. nPkField is the number of key fields in the
  94277. ** pPk index or 1 for a rowid table. In other words, nPkField is the
  94278. ** number of fields in the true primary key of the table. */
  94279. if( HasRowid(pTab) ){
  94280. pPk = 0;
  94281. nPkField = 1;
  94282. }else{
  94283. pPk = sqlite3PrimaryKeyIndex(pTab);
  94284. nPkField = pPk->nKeyCol;
  94285. }
  94286. /* Record that this module has started */
  94287. VdbeModuleComment((v, "BEGIN: GenCnstCks(%d,%d,%d,%d,%d)",
  94288. iDataCur, iIdxCur, regNewData, regOldData, pkChng));
  94289. /* Test all NOT NULL constraints.
  94290. */
  94291. for(i=0; i<nCol; i++){
  94292. if( i==pTab->iPKey ){
  94293. continue;
  94294. }
  94295. onError = pTab->aCol[i].notNull;
  94296. if( onError==OE_None ) continue;
  94297. if( overrideError!=OE_Default ){
  94298. onError = overrideError;
  94299. }else if( onError==OE_Default ){
  94300. onError = OE_Abort;
  94301. }
  94302. if( onError==OE_Replace && pTab->aCol[i].pDflt==0 ){
  94303. onError = OE_Abort;
  94304. }
  94305. assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
  94306. || onError==OE_Ignore || onError==OE_Replace );
  94307. switch( onError ){
  94308. case OE_Abort:
  94309. sqlite3MayAbort(pParse);
  94310. /* Fall through */
  94311. case OE_Rollback:
  94312. case OE_Fail: {
  94313. char *zMsg = sqlite3MPrintf(db, "%s.%s", pTab->zName,
  94314. pTab->aCol[i].zName);
  94315. sqlite3VdbeAddOp4(v, OP_HaltIfNull, SQLITE_CONSTRAINT_NOTNULL, onError,
  94316. regNewData+1+i, zMsg, P4_DYNAMIC);
  94317. sqlite3VdbeChangeP5(v, P5_ConstraintNotNull);
  94318. VdbeCoverage(v);
  94319. break;
  94320. }
  94321. case OE_Ignore: {
  94322. sqlite3VdbeAddOp2(v, OP_IsNull, regNewData+1+i, ignoreDest);
  94323. VdbeCoverage(v);
  94324. break;
  94325. }
  94326. default: {
  94327. assert( onError==OE_Replace );
  94328. j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regNewData+1+i); VdbeCoverage(v);
  94329. sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, regNewData+1+i);
  94330. sqlite3VdbeJumpHere(v, j1);
  94331. break;
  94332. }
  94333. }
  94334. }
  94335. /* Test all CHECK constraints
  94336. */
  94337. #ifndef SQLITE_OMIT_CHECK
  94338. if( pTab->pCheck && (db->flags & SQLITE_IgnoreChecks)==0 ){
  94339. ExprList *pCheck = pTab->pCheck;
  94340. pParse->ckBase = regNewData+1;
  94341. onError = overrideError!=OE_Default ? overrideError : OE_Abort;
  94342. for(i=0; i<pCheck->nExpr; i++){
  94343. int allOk = sqlite3VdbeMakeLabel(v);
  94344. sqlite3ExprIfTrue(pParse, pCheck->a[i].pExpr, allOk, SQLITE_JUMPIFNULL);
  94345. if( onError==OE_Ignore ){
  94346. sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);
  94347. }else{
  94348. char *zName = pCheck->a[i].zName;
  94349. if( zName==0 ) zName = pTab->zName;
  94350. if( onError==OE_Replace ) onError = OE_Abort; /* IMP: R-15569-63625 */
  94351. sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_CHECK,
  94352. onError, zName, P4_TRANSIENT,
  94353. P5_ConstraintCheck);
  94354. }
  94355. sqlite3VdbeResolveLabel(v, allOk);
  94356. }
  94357. }
  94358. #endif /* !defined(SQLITE_OMIT_CHECK) */
  94359. /* If rowid is changing, make sure the new rowid does not previously
  94360. ** exist in the table.
  94361. */
  94362. if( pkChng && pPk==0 ){
  94363. int addrRowidOk = sqlite3VdbeMakeLabel(v);
  94364. /* Figure out what action to take in case of a rowid collision */
  94365. onError = pTab->keyConf;
  94366. if( overrideError!=OE_Default ){
  94367. onError = overrideError;
  94368. }else if( onError==OE_Default ){
  94369. onError = OE_Abort;
  94370. }
  94371. if( isUpdate ){
  94372. /* pkChng!=0 does not mean that the rowid has change, only that
  94373. ** it might have changed. Skip the conflict logic below if the rowid
  94374. ** is unchanged. */
  94375. sqlite3VdbeAddOp3(v, OP_Eq, regNewData, addrRowidOk, regOldData);
  94376. sqlite3VdbeChangeP5(v, SQLITE_NOTNULL);
  94377. VdbeCoverage(v);
  94378. }
  94379. /* If the response to a rowid conflict is REPLACE but the response
  94380. ** to some other UNIQUE constraint is FAIL or IGNORE, then we need
  94381. ** to defer the running of the rowid conflict checking until after
  94382. ** the UNIQUE constraints have run.
  94383. */
  94384. if( onError==OE_Replace && overrideError!=OE_Replace ){
  94385. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  94386. if( pIdx->onError==OE_Ignore || pIdx->onError==OE_Fail ){
  94387. ipkTop = sqlite3VdbeAddOp0(v, OP_Goto);
  94388. break;
  94389. }
  94390. }
  94391. }
  94392. /* Check to see if the new rowid already exists in the table. Skip
  94393. ** the following conflict logic if it does not. */
  94394. sqlite3VdbeAddOp3(v, OP_NotExists, iDataCur, addrRowidOk, regNewData);
  94395. VdbeCoverage(v);
  94396. /* Generate code that deals with a rowid collision */
  94397. switch( onError ){
  94398. default: {
  94399. onError = OE_Abort;
  94400. /* Fall thru into the next case */
  94401. }
  94402. case OE_Rollback:
  94403. case OE_Abort:
  94404. case OE_Fail: {
  94405. sqlite3RowidConstraint(pParse, onError, pTab);
  94406. break;
  94407. }
  94408. case OE_Replace: {
  94409. /* If there are DELETE triggers on this table and the
  94410. ** recursive-triggers flag is set, call GenerateRowDelete() to
  94411. ** remove the conflicting row from the table. This will fire
  94412. ** the triggers and remove both the table and index b-tree entries.
  94413. **
  94414. ** Otherwise, if there are no triggers or the recursive-triggers
  94415. ** flag is not set, but the table has one or more indexes, call
  94416. ** GenerateRowIndexDelete(). This removes the index b-tree entries
  94417. ** only. The table b-tree entry will be replaced by the new entry
  94418. ** when it is inserted.
  94419. **
  94420. ** If either GenerateRowDelete() or GenerateRowIndexDelete() is called,
  94421. ** also invoke MultiWrite() to indicate that this VDBE may require
  94422. ** statement rollback (if the statement is aborted after the delete
  94423. ** takes place). Earlier versions called sqlite3MultiWrite() regardless,
  94424. ** but being more selective here allows statements like:
  94425. **
  94426. ** REPLACE INTO t(rowid) VALUES($newrowid)
  94427. **
  94428. ** to run without a statement journal if there are no indexes on the
  94429. ** table.
  94430. */
  94431. Trigger *pTrigger = 0;
  94432. if( db->flags&SQLITE_RecTriggers ){
  94433. pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
  94434. }
  94435. if( pTrigger || sqlite3FkRequired(pParse, pTab, 0, 0) ){
  94436. sqlite3MultiWrite(pParse);
  94437. sqlite3GenerateRowDelete(pParse, pTab, pTrigger, iDataCur, iIdxCur,
  94438. regNewData, 1, 0, OE_Replace, 1);
  94439. }else if( pTab->pIndex ){
  94440. sqlite3MultiWrite(pParse);
  94441. sqlite3GenerateRowIndexDelete(pParse, pTab, iDataCur, iIdxCur, 0);
  94442. }
  94443. seenReplace = 1;
  94444. break;
  94445. }
  94446. case OE_Ignore: {
  94447. /*assert( seenReplace==0 );*/
  94448. sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);
  94449. break;
  94450. }
  94451. }
  94452. sqlite3VdbeResolveLabel(v, addrRowidOk);
  94453. if( ipkTop ){
  94454. ipkBottom = sqlite3VdbeAddOp0(v, OP_Goto);
  94455. sqlite3VdbeJumpHere(v, ipkTop);
  94456. }
  94457. }
  94458. /* Test all UNIQUE constraints by creating entries for each UNIQUE
  94459. ** index and making sure that duplicate entries do not already exist.
  94460. ** Compute the revised record entries for indices as we go.
  94461. **
  94462. ** This loop also handles the case of the PRIMARY KEY index for a
  94463. ** WITHOUT ROWID table.
  94464. */
  94465. for(ix=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, ix++){
  94466. int regIdx; /* Range of registers hold conent for pIdx */
  94467. int regR; /* Range of registers holding conflicting PK */
  94468. int iThisCur; /* Cursor for this UNIQUE index */
  94469. int addrUniqueOk; /* Jump here if the UNIQUE constraint is satisfied */
  94470. if( aRegIdx[ix]==0 ) continue; /* Skip indices that do not change */
  94471. if( bAffinityDone==0 ){
  94472. sqlite3TableAffinity(v, pTab, regNewData+1);
  94473. bAffinityDone = 1;
  94474. }
  94475. iThisCur = iIdxCur+ix;
  94476. addrUniqueOk = sqlite3VdbeMakeLabel(v);
  94477. /* Skip partial indices for which the WHERE clause is not true */
  94478. if( pIdx->pPartIdxWhere ){
  94479. sqlite3VdbeAddOp2(v, OP_Null, 0, aRegIdx[ix]);
  94480. pParse->ckBase = regNewData+1;
  94481. sqlite3ExprIfFalse(pParse, pIdx->pPartIdxWhere, addrUniqueOk,
  94482. SQLITE_JUMPIFNULL);
  94483. pParse->ckBase = 0;
  94484. }
  94485. /* Create a record for this index entry as it should appear after
  94486. ** the insert or update. Store that record in the aRegIdx[ix] register
  94487. */
  94488. regIdx = sqlite3GetTempRange(pParse, pIdx->nColumn);
  94489. for(i=0; i<pIdx->nColumn; i++){
  94490. int iField = pIdx->aiColumn[i];
  94491. int x;
  94492. if( iField<0 || iField==pTab->iPKey ){
  94493. if( regRowid==regIdx+i ) continue; /* ROWID already in regIdx+i */
  94494. x = regNewData;
  94495. regRowid = pIdx->pPartIdxWhere ? -1 : regIdx+i;
  94496. }else{
  94497. x = iField + regNewData + 1;
  94498. }
  94499. sqlite3VdbeAddOp2(v, OP_SCopy, x, regIdx+i);
  94500. VdbeComment((v, "%s", iField<0 ? "rowid" : pTab->aCol[iField].zName));
  94501. }
  94502. sqlite3VdbeAddOp3(v, OP_MakeRecord, regIdx, pIdx->nColumn, aRegIdx[ix]);
  94503. VdbeComment((v, "for %s", pIdx->zName));
  94504. sqlite3ExprCacheAffinityChange(pParse, regIdx, pIdx->nColumn);
  94505. /* In an UPDATE operation, if this index is the PRIMARY KEY index
  94506. ** of a WITHOUT ROWID table and there has been no change the
  94507. ** primary key, then no collision is possible. The collision detection
  94508. ** logic below can all be skipped. */
  94509. if( isUpdate && pPk==pIdx && pkChng==0 ){
  94510. sqlite3VdbeResolveLabel(v, addrUniqueOk);
  94511. continue;
  94512. }
  94513. /* Find out what action to take in case there is a uniqueness conflict */
  94514. onError = pIdx->onError;
  94515. if( onError==OE_None ){
  94516. sqlite3ReleaseTempRange(pParse, regIdx, pIdx->nColumn);
  94517. sqlite3VdbeResolveLabel(v, addrUniqueOk);
  94518. continue; /* pIdx is not a UNIQUE index */
  94519. }
  94520. if( overrideError!=OE_Default ){
  94521. onError = overrideError;
  94522. }else if( onError==OE_Default ){
  94523. onError = OE_Abort;
  94524. }
  94525. /* Check to see if the new index entry will be unique */
  94526. sqlite3VdbeAddOp4Int(v, OP_NoConflict, iThisCur, addrUniqueOk,
  94527. regIdx, pIdx->nKeyCol); VdbeCoverage(v);
  94528. /* Generate code to handle collisions */
  94529. regR = (pIdx==pPk) ? regIdx : sqlite3GetTempRange(pParse, nPkField);
  94530. if( isUpdate || onError==OE_Replace ){
  94531. if( HasRowid(pTab) ){
  94532. sqlite3VdbeAddOp2(v, OP_IdxRowid, iThisCur, regR);
  94533. /* Conflict only if the rowid of the existing index entry
  94534. ** is different from old-rowid */
  94535. if( isUpdate ){
  94536. sqlite3VdbeAddOp3(v, OP_Eq, regR, addrUniqueOk, regOldData);
  94537. sqlite3VdbeChangeP5(v, SQLITE_NOTNULL);
  94538. VdbeCoverage(v);
  94539. }
  94540. }else{
  94541. int x;
  94542. /* Extract the PRIMARY KEY from the end of the index entry and
  94543. ** store it in registers regR..regR+nPk-1 */
  94544. if( pIdx!=pPk ){
  94545. for(i=0; i<pPk->nKeyCol; i++){
  94546. x = sqlite3ColumnOfIndex(pIdx, pPk->aiColumn[i]);
  94547. sqlite3VdbeAddOp3(v, OP_Column, iThisCur, x, regR+i);
  94548. VdbeComment((v, "%s.%s", pTab->zName,
  94549. pTab->aCol[pPk->aiColumn[i]].zName));
  94550. }
  94551. }
  94552. if( isUpdate ){
  94553. /* If currently processing the PRIMARY KEY of a WITHOUT ROWID
  94554. ** table, only conflict if the new PRIMARY KEY values are actually
  94555. ** different from the old.
  94556. **
  94557. ** For a UNIQUE index, only conflict if the PRIMARY KEY values
  94558. ** of the matched index row are different from the original PRIMARY
  94559. ** KEY values of this row before the update. */
  94560. int addrJump = sqlite3VdbeCurrentAddr(v)+pPk->nKeyCol;
  94561. int op = OP_Ne;
  94562. int regCmp = (IsPrimaryKeyIndex(pIdx) ? regIdx : regR);
  94563. for(i=0; i<pPk->nKeyCol; i++){
  94564. char *p4 = (char*)sqlite3LocateCollSeq(pParse, pPk->azColl[i]);
  94565. x = pPk->aiColumn[i];
  94566. if( i==(pPk->nKeyCol-1) ){
  94567. addrJump = addrUniqueOk;
  94568. op = OP_Eq;
  94569. }
  94570. sqlite3VdbeAddOp4(v, op,
  94571. regOldData+1+x, addrJump, regCmp+i, p4, P4_COLLSEQ
  94572. );
  94573. sqlite3VdbeChangeP5(v, SQLITE_NOTNULL);
  94574. VdbeCoverageIf(v, op==OP_Eq);
  94575. VdbeCoverageIf(v, op==OP_Ne);
  94576. }
  94577. }
  94578. }
  94579. }
  94580. /* Generate code that executes if the new index entry is not unique */
  94581. assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
  94582. || onError==OE_Ignore || onError==OE_Replace );
  94583. switch( onError ){
  94584. case OE_Rollback:
  94585. case OE_Abort:
  94586. case OE_Fail: {
  94587. sqlite3UniqueConstraint(pParse, onError, pIdx);
  94588. break;
  94589. }
  94590. case OE_Ignore: {
  94591. sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);
  94592. break;
  94593. }
  94594. default: {
  94595. Trigger *pTrigger = 0;
  94596. assert( onError==OE_Replace );
  94597. sqlite3MultiWrite(pParse);
  94598. if( db->flags&SQLITE_RecTriggers ){
  94599. pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
  94600. }
  94601. sqlite3GenerateRowDelete(pParse, pTab, pTrigger, iDataCur, iIdxCur,
  94602. regR, nPkField, 0, OE_Replace, pIdx==pPk);
  94603. seenReplace = 1;
  94604. break;
  94605. }
  94606. }
  94607. sqlite3VdbeResolveLabel(v, addrUniqueOk);
  94608. sqlite3ReleaseTempRange(pParse, regIdx, pIdx->nColumn);
  94609. if( regR!=regIdx ) sqlite3ReleaseTempRange(pParse, regR, nPkField);
  94610. }
  94611. if( ipkTop ){
  94612. sqlite3VdbeAddOp2(v, OP_Goto, 0, ipkTop+1);
  94613. sqlite3VdbeJumpHere(v, ipkBottom);
  94614. }
  94615. *pbMayReplace = seenReplace;
  94616. VdbeModuleComment((v, "END: GenCnstCks(%d)", seenReplace));
  94617. }
  94618. /*
  94619. ** This routine generates code to finish the INSERT or UPDATE operation
  94620. ** that was started by a prior call to sqlite3GenerateConstraintChecks.
  94621. ** A consecutive range of registers starting at regNewData contains the
  94622. ** rowid and the content to be inserted.
  94623. **
  94624. ** The arguments to this routine should be the same as the first six
  94625. ** arguments to sqlite3GenerateConstraintChecks.
  94626. */
  94627. SQLITE_PRIVATE void sqlite3CompleteInsertion(
  94628. Parse *pParse, /* The parser context */
  94629. Table *pTab, /* the table into which we are inserting */
  94630. int iDataCur, /* Cursor of the canonical data source */
  94631. int iIdxCur, /* First index cursor */
  94632. int regNewData, /* Range of content */
  94633. int *aRegIdx, /* Register used by each index. 0 for unused indices */
  94634. int isUpdate, /* True for UPDATE, False for INSERT */
  94635. int appendBias, /* True if this is likely to be an append */
  94636. int useSeekResult /* True to set the USESEEKRESULT flag on OP_[Idx]Insert */
  94637. ){
  94638. Vdbe *v; /* Prepared statements under construction */
  94639. Index *pIdx; /* An index being inserted or updated */
  94640. u8 pik_flags; /* flag values passed to the btree insert */
  94641. int regData; /* Content registers (after the rowid) */
  94642. int regRec; /* Register holding assembled record for the table */
  94643. int i; /* Loop counter */
  94644. u8 bAffinityDone = 0; /* True if OP_Affinity has been run already */
  94645. v = sqlite3GetVdbe(pParse);
  94646. assert( v!=0 );
  94647. assert( pTab->pSelect==0 ); /* This table is not a VIEW */
  94648. for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
  94649. if( aRegIdx[i]==0 ) continue;
  94650. bAffinityDone = 1;
  94651. if( pIdx->pPartIdxWhere ){
  94652. sqlite3VdbeAddOp2(v, OP_IsNull, aRegIdx[i], sqlite3VdbeCurrentAddr(v)+2);
  94653. VdbeCoverage(v);
  94654. }
  94655. sqlite3VdbeAddOp2(v, OP_IdxInsert, iIdxCur+i, aRegIdx[i]);
  94656. pik_flags = 0;
  94657. if( useSeekResult ) pik_flags = OPFLAG_USESEEKRESULT;
  94658. if( IsPrimaryKeyIndex(pIdx) && !HasRowid(pTab) ){
  94659. assert( pParse->nested==0 );
  94660. pik_flags |= OPFLAG_NCHANGE;
  94661. }
  94662. if( pik_flags ) sqlite3VdbeChangeP5(v, pik_flags);
  94663. }
  94664. if( !HasRowid(pTab) ) return;
  94665. regData = regNewData + 1;
  94666. regRec = sqlite3GetTempReg(pParse);
  94667. sqlite3VdbeAddOp3(v, OP_MakeRecord, regData, pTab->nCol, regRec);
  94668. if( !bAffinityDone ) sqlite3TableAffinity(v, pTab, 0);
  94669. sqlite3ExprCacheAffinityChange(pParse, regData, pTab->nCol);
  94670. if( pParse->nested ){
  94671. pik_flags = 0;
  94672. }else{
  94673. pik_flags = OPFLAG_NCHANGE;
  94674. pik_flags |= (isUpdate?OPFLAG_ISUPDATE:OPFLAG_LASTROWID);
  94675. }
  94676. if( appendBias ){
  94677. pik_flags |= OPFLAG_APPEND;
  94678. }
  94679. if( useSeekResult ){
  94680. pik_flags |= OPFLAG_USESEEKRESULT;
  94681. }
  94682. sqlite3VdbeAddOp3(v, OP_Insert, iDataCur, regRec, regNewData);
  94683. if( !pParse->nested ){
  94684. sqlite3VdbeChangeP4(v, -1, pTab->zName, P4_TRANSIENT);
  94685. }
  94686. sqlite3VdbeChangeP5(v, pik_flags);
  94687. }
  94688. /*
  94689. ** Allocate cursors for the pTab table and all its indices and generate
  94690. ** code to open and initialized those cursors.
  94691. **
  94692. ** The cursor for the object that contains the complete data (normally
  94693. ** the table itself, but the PRIMARY KEY index in the case of a WITHOUT
  94694. ** ROWID table) is returned in *piDataCur. The first index cursor is
  94695. ** returned in *piIdxCur. The number of indices is returned.
  94696. **
  94697. ** Use iBase as the first cursor (either the *piDataCur for rowid tables
  94698. ** or the first index for WITHOUT ROWID tables) if it is non-negative.
  94699. ** If iBase is negative, then allocate the next available cursor.
  94700. **
  94701. ** For a rowid table, *piDataCur will be exactly one less than *piIdxCur.
  94702. ** For a WITHOUT ROWID table, *piDataCur will be somewhere in the range
  94703. ** of *piIdxCurs, depending on where the PRIMARY KEY index appears on the
  94704. ** pTab->pIndex list.
  94705. **
  94706. ** If pTab is a virtual table, then this routine is a no-op and the
  94707. ** *piDataCur and *piIdxCur values are left uninitialized.
  94708. */
  94709. SQLITE_PRIVATE int sqlite3OpenTableAndIndices(
  94710. Parse *pParse, /* Parsing context */
  94711. Table *pTab, /* Table to be opened */
  94712. int op, /* OP_OpenRead or OP_OpenWrite */
  94713. int iBase, /* Use this for the table cursor, if there is one */
  94714. u8 *aToOpen, /* If not NULL: boolean for each table and index */
  94715. int *piDataCur, /* Write the database source cursor number here */
  94716. int *piIdxCur /* Write the first index cursor number here */
  94717. ){
  94718. int i;
  94719. int iDb;
  94720. int iDataCur;
  94721. Index *pIdx;
  94722. Vdbe *v;
  94723. assert( op==OP_OpenRead || op==OP_OpenWrite );
  94724. if( IsVirtual(pTab) ){
  94725. /* This routine is a no-op for virtual tables. Leave the output
  94726. ** variables *piDataCur and *piIdxCur uninitialized so that valgrind
  94727. ** can detect if they are used by mistake in the caller. */
  94728. return 0;
  94729. }
  94730. iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
  94731. v = sqlite3GetVdbe(pParse);
  94732. assert( v!=0 );
  94733. if( iBase<0 ) iBase = pParse->nTab;
  94734. iDataCur = iBase++;
  94735. if( piDataCur ) *piDataCur = iDataCur;
  94736. if( HasRowid(pTab) && (aToOpen==0 || aToOpen[0]) ){
  94737. sqlite3OpenTable(pParse, iDataCur, iDb, pTab, op);
  94738. }else{
  94739. sqlite3TableLock(pParse, iDb, pTab->tnum, op==OP_OpenWrite, pTab->zName);
  94740. }
  94741. if( piIdxCur ) *piIdxCur = iBase;
  94742. for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
  94743. int iIdxCur = iBase++;
  94744. assert( pIdx->pSchema==pTab->pSchema );
  94745. if( IsPrimaryKeyIndex(pIdx) && !HasRowid(pTab) && piDataCur ){
  94746. *piDataCur = iIdxCur;
  94747. }
  94748. if( aToOpen==0 || aToOpen[i+1] ){
  94749. sqlite3VdbeAddOp3(v, op, iIdxCur, pIdx->tnum, iDb);
  94750. sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
  94751. VdbeComment((v, "%s", pIdx->zName));
  94752. }
  94753. }
  94754. if( iBase>pParse->nTab ) pParse->nTab = iBase;
  94755. return i;
  94756. }
  94757. #ifdef SQLITE_TEST
  94758. /*
  94759. ** The following global variable is incremented whenever the
  94760. ** transfer optimization is used. This is used for testing
  94761. ** purposes only - to make sure the transfer optimization really
  94762. ** is happening when it is supposed to.
  94763. */
  94764. SQLITE_API int sqlite3_xferopt_count;
  94765. #endif /* SQLITE_TEST */
  94766. #ifndef SQLITE_OMIT_XFER_OPT
  94767. /*
  94768. ** Check to collation names to see if they are compatible.
  94769. */
  94770. static int xferCompatibleCollation(const char *z1, const char *z2){
  94771. if( z1==0 ){
  94772. return z2==0;
  94773. }
  94774. if( z2==0 ){
  94775. return 0;
  94776. }
  94777. return sqlite3StrICmp(z1, z2)==0;
  94778. }
  94779. /*
  94780. ** Check to see if index pSrc is compatible as a source of data
  94781. ** for index pDest in an insert transfer optimization. The rules
  94782. ** for a compatible index:
  94783. **
  94784. ** * The index is over the same set of columns
  94785. ** * The same DESC and ASC markings occurs on all columns
  94786. ** * The same onError processing (OE_Abort, OE_Ignore, etc)
  94787. ** * The same collating sequence on each column
  94788. ** * The index has the exact same WHERE clause
  94789. */
  94790. static int xferCompatibleIndex(Index *pDest, Index *pSrc){
  94791. int i;
  94792. assert( pDest && pSrc );
  94793. assert( pDest->pTable!=pSrc->pTable );
  94794. if( pDest->nKeyCol!=pSrc->nKeyCol ){
  94795. return 0; /* Different number of columns */
  94796. }
  94797. if( pDest->onError!=pSrc->onError ){
  94798. return 0; /* Different conflict resolution strategies */
  94799. }
  94800. for(i=0; i<pSrc->nKeyCol; i++){
  94801. if( pSrc->aiColumn[i]!=pDest->aiColumn[i] ){
  94802. return 0; /* Different columns indexed */
  94803. }
  94804. if( pSrc->aSortOrder[i]!=pDest->aSortOrder[i] ){
  94805. return 0; /* Different sort orders */
  94806. }
  94807. if( !xferCompatibleCollation(pSrc->azColl[i],pDest->azColl[i]) ){
  94808. return 0; /* Different collating sequences */
  94809. }
  94810. }
  94811. if( sqlite3ExprCompare(pSrc->pPartIdxWhere, pDest->pPartIdxWhere, -1) ){
  94812. return 0; /* Different WHERE clauses */
  94813. }
  94814. /* If no test above fails then the indices must be compatible */
  94815. return 1;
  94816. }
  94817. /*
  94818. ** Attempt the transfer optimization on INSERTs of the form
  94819. **
  94820. ** INSERT INTO tab1 SELECT * FROM tab2;
  94821. **
  94822. ** The xfer optimization transfers raw records from tab2 over to tab1.
  94823. ** Columns are not decoded and reassembled, which greatly improves
  94824. ** performance. Raw index records are transferred in the same way.
  94825. **
  94826. ** The xfer optimization is only attempted if tab1 and tab2 are compatible.
  94827. ** There are lots of rules for determining compatibility - see comments
  94828. ** embedded in the code for details.
  94829. **
  94830. ** This routine returns TRUE if the optimization is guaranteed to be used.
  94831. ** Sometimes the xfer optimization will only work if the destination table
  94832. ** is empty - a factor that can only be determined at run-time. In that
  94833. ** case, this routine generates code for the xfer optimization but also
  94834. ** does a test to see if the destination table is empty and jumps over the
  94835. ** xfer optimization code if the test fails. In that case, this routine
  94836. ** returns FALSE so that the caller will know to go ahead and generate
  94837. ** an unoptimized transfer. This routine also returns FALSE if there
  94838. ** is no chance that the xfer optimization can be applied.
  94839. **
  94840. ** This optimization is particularly useful at making VACUUM run faster.
  94841. */
  94842. static int xferOptimization(
  94843. Parse *pParse, /* Parser context */
  94844. Table *pDest, /* The table we are inserting into */
  94845. Select *pSelect, /* A SELECT statement to use as the data source */
  94846. int onError, /* How to handle constraint errors */
  94847. int iDbDest /* The database of pDest */
  94848. ){
  94849. sqlite3 *db = pParse->db;
  94850. ExprList *pEList; /* The result set of the SELECT */
  94851. Table *pSrc; /* The table in the FROM clause of SELECT */
  94852. Index *pSrcIdx, *pDestIdx; /* Source and destination indices */
  94853. struct SrcList_item *pItem; /* An element of pSelect->pSrc */
  94854. int i; /* Loop counter */
  94855. int iDbSrc; /* The database of pSrc */
  94856. int iSrc, iDest; /* Cursors from source and destination */
  94857. int addr1, addr2; /* Loop addresses */
  94858. int emptyDestTest = 0; /* Address of test for empty pDest */
  94859. int emptySrcTest = 0; /* Address of test for empty pSrc */
  94860. Vdbe *v; /* The VDBE we are building */
  94861. int regAutoinc; /* Memory register used by AUTOINC */
  94862. int destHasUniqueIdx = 0; /* True if pDest has a UNIQUE index */
  94863. int regData, regRowid; /* Registers holding data and rowid */
  94864. if( pSelect==0 ){
  94865. return 0; /* Must be of the form INSERT INTO ... SELECT ... */
  94866. }
  94867. if( pParse->pWith || pSelect->pWith ){
  94868. /* Do not attempt to process this query if there are an WITH clauses
  94869. ** attached to it. Proceeding may generate a false "no such table: xxx"
  94870. ** error if pSelect reads from a CTE named "xxx". */
  94871. return 0;
  94872. }
  94873. if( sqlite3TriggerList(pParse, pDest) ){
  94874. return 0; /* tab1 must not have triggers */
  94875. }
  94876. #ifndef SQLITE_OMIT_VIRTUALTABLE
  94877. if( pDest->tabFlags & TF_Virtual ){
  94878. return 0; /* tab1 must not be a virtual table */
  94879. }
  94880. #endif
  94881. if( onError==OE_Default ){
  94882. if( pDest->iPKey>=0 ) onError = pDest->keyConf;
  94883. if( onError==OE_Default ) onError = OE_Abort;
  94884. }
  94885. assert(pSelect->pSrc); /* allocated even if there is no FROM clause */
  94886. if( pSelect->pSrc->nSrc!=1 ){
  94887. return 0; /* FROM clause must have exactly one term */
  94888. }
  94889. if( pSelect->pSrc->a[0].pSelect ){
  94890. return 0; /* FROM clause cannot contain a subquery */
  94891. }
  94892. if( pSelect->pWhere ){
  94893. return 0; /* SELECT may not have a WHERE clause */
  94894. }
  94895. if( pSelect->pOrderBy ){
  94896. return 0; /* SELECT may not have an ORDER BY clause */
  94897. }
  94898. /* Do not need to test for a HAVING clause. If HAVING is present but
  94899. ** there is no ORDER BY, we will get an error. */
  94900. if( pSelect->pGroupBy ){
  94901. return 0; /* SELECT may not have a GROUP BY clause */
  94902. }
  94903. if( pSelect->pLimit ){
  94904. return 0; /* SELECT may not have a LIMIT clause */
  94905. }
  94906. assert( pSelect->pOffset==0 ); /* Must be so if pLimit==0 */
  94907. if( pSelect->pPrior ){
  94908. return 0; /* SELECT may not be a compound query */
  94909. }
  94910. if( pSelect->selFlags & SF_Distinct ){
  94911. return 0; /* SELECT may not be DISTINCT */
  94912. }
  94913. pEList = pSelect->pEList;
  94914. assert( pEList!=0 );
  94915. if( pEList->nExpr!=1 ){
  94916. return 0; /* The result set must have exactly one column */
  94917. }
  94918. assert( pEList->a[0].pExpr );
  94919. if( pEList->a[0].pExpr->op!=TK_ALL ){
  94920. return 0; /* The result set must be the special operator "*" */
  94921. }
  94922. /* At this point we have established that the statement is of the
  94923. ** correct syntactic form to participate in this optimization. Now
  94924. ** we have to check the semantics.
  94925. */
  94926. pItem = pSelect->pSrc->a;
  94927. pSrc = sqlite3LocateTableItem(pParse, 0, pItem);
  94928. if( pSrc==0 ){
  94929. return 0; /* FROM clause does not contain a real table */
  94930. }
  94931. if( pSrc==pDest ){
  94932. return 0; /* tab1 and tab2 may not be the same table */
  94933. }
  94934. if( HasRowid(pDest)!=HasRowid(pSrc) ){
  94935. return 0; /* source and destination must both be WITHOUT ROWID or not */
  94936. }
  94937. #ifndef SQLITE_OMIT_VIRTUALTABLE
  94938. if( pSrc->tabFlags & TF_Virtual ){
  94939. return 0; /* tab2 must not be a virtual table */
  94940. }
  94941. #endif
  94942. if( pSrc->pSelect ){
  94943. return 0; /* tab2 may not be a view */
  94944. }
  94945. if( pDest->nCol!=pSrc->nCol ){
  94946. return 0; /* Number of columns must be the same in tab1 and tab2 */
  94947. }
  94948. if( pDest->iPKey!=pSrc->iPKey ){
  94949. return 0; /* Both tables must have the same INTEGER PRIMARY KEY */
  94950. }
  94951. for(i=0; i<pDest->nCol; i++){
  94952. Column *pDestCol = &pDest->aCol[i];
  94953. Column *pSrcCol = &pSrc->aCol[i];
  94954. if( pDestCol->affinity!=pSrcCol->affinity ){
  94955. return 0; /* Affinity must be the same on all columns */
  94956. }
  94957. if( !xferCompatibleCollation(pDestCol->zColl, pSrcCol->zColl) ){
  94958. return 0; /* Collating sequence must be the same on all columns */
  94959. }
  94960. if( pDestCol->notNull && !pSrcCol->notNull ){
  94961. return 0; /* tab2 must be NOT NULL if tab1 is */
  94962. }
  94963. /* Default values for second and subsequent columns need to match. */
  94964. if( i>0
  94965. && ((pDestCol->zDflt==0)!=(pSrcCol->zDflt==0)
  94966. || (pDestCol->zDflt && strcmp(pDestCol->zDflt, pSrcCol->zDflt)!=0))
  94967. ){
  94968. return 0; /* Default values must be the same for all columns */
  94969. }
  94970. }
  94971. for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
  94972. if( IsUniqueIndex(pDestIdx) ){
  94973. destHasUniqueIdx = 1;
  94974. }
  94975. for(pSrcIdx=pSrc->pIndex; pSrcIdx; pSrcIdx=pSrcIdx->pNext){
  94976. if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
  94977. }
  94978. if( pSrcIdx==0 ){
  94979. return 0; /* pDestIdx has no corresponding index in pSrc */
  94980. }
  94981. }
  94982. #ifndef SQLITE_OMIT_CHECK
  94983. if( pDest->pCheck && sqlite3ExprListCompare(pSrc->pCheck,pDest->pCheck,-1) ){
  94984. return 0; /* Tables have different CHECK constraints. Ticket #2252 */
  94985. }
  94986. #endif
  94987. #ifndef SQLITE_OMIT_FOREIGN_KEY
  94988. /* Disallow the transfer optimization if the destination table constains
  94989. ** any foreign key constraints. This is more restrictive than necessary.
  94990. ** But the main beneficiary of the transfer optimization is the VACUUM
  94991. ** command, and the VACUUM command disables foreign key constraints. So
  94992. ** the extra complication to make this rule less restrictive is probably
  94993. ** not worth the effort. Ticket [6284df89debdfa61db8073e062908af0c9b6118e]
  94994. */
  94995. if( (db->flags & SQLITE_ForeignKeys)!=0 && pDest->pFKey!=0 ){
  94996. return 0;
  94997. }
  94998. #endif
  94999. if( (db->flags & SQLITE_CountRows)!=0 ){
  95000. return 0; /* xfer opt does not play well with PRAGMA count_changes */
  95001. }
  95002. /* If we get this far, it means that the xfer optimization is at
  95003. ** least a possibility, though it might only work if the destination
  95004. ** table (tab1) is initially empty.
  95005. */
  95006. #ifdef SQLITE_TEST
  95007. sqlite3_xferopt_count++;
  95008. #endif
  95009. iDbSrc = sqlite3SchemaToIndex(db, pSrc->pSchema);
  95010. v = sqlite3GetVdbe(pParse);
  95011. sqlite3CodeVerifySchema(pParse, iDbSrc);
  95012. iSrc = pParse->nTab++;
  95013. iDest = pParse->nTab++;
  95014. regAutoinc = autoIncBegin(pParse, iDbDest, pDest);
  95015. regData = sqlite3GetTempReg(pParse);
  95016. regRowid = sqlite3GetTempReg(pParse);
  95017. sqlite3OpenTable(pParse, iDest, iDbDest, pDest, OP_OpenWrite);
  95018. assert( HasRowid(pDest) || destHasUniqueIdx );
  95019. if( (db->flags & SQLITE_Vacuum)==0 && (
  95020. (pDest->iPKey<0 && pDest->pIndex!=0) /* (1) */
  95021. || destHasUniqueIdx /* (2) */
  95022. || (onError!=OE_Abort && onError!=OE_Rollback) /* (3) */
  95023. )){
  95024. /* In some circumstances, we are able to run the xfer optimization
  95025. ** only if the destination table is initially empty. Unless the
  95026. ** SQLITE_Vacuum flag is set, this block generates code to make
  95027. ** that determination. If SQLITE_Vacuum is set, then the destination
  95028. ** table is always empty.
  95029. **
  95030. ** Conditions under which the destination must be empty:
  95031. **
  95032. ** (1) There is no INTEGER PRIMARY KEY but there are indices.
  95033. ** (If the destination is not initially empty, the rowid fields
  95034. ** of index entries might need to change.)
  95035. **
  95036. ** (2) The destination has a unique index. (The xfer optimization
  95037. ** is unable to test uniqueness.)
  95038. **
  95039. ** (3) onError is something other than OE_Abort and OE_Rollback.
  95040. */
  95041. addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iDest, 0); VdbeCoverage(v);
  95042. emptyDestTest = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0);
  95043. sqlite3VdbeJumpHere(v, addr1);
  95044. }
  95045. if( HasRowid(pSrc) ){
  95046. sqlite3OpenTable(pParse, iSrc, iDbSrc, pSrc, OP_OpenRead);
  95047. emptySrcTest = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0); VdbeCoverage(v);
  95048. if( pDest->iPKey>=0 ){
  95049. addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid);
  95050. addr2 = sqlite3VdbeAddOp3(v, OP_NotExists, iDest, 0, regRowid);
  95051. VdbeCoverage(v);
  95052. sqlite3RowidConstraint(pParse, onError, pDest);
  95053. sqlite3VdbeJumpHere(v, addr2);
  95054. autoIncStep(pParse, regAutoinc, regRowid);
  95055. }else if( pDest->pIndex==0 ){
  95056. addr1 = sqlite3VdbeAddOp2(v, OP_NewRowid, iDest, regRowid);
  95057. }else{
  95058. addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid);
  95059. assert( (pDest->tabFlags & TF_Autoincrement)==0 );
  95060. }
  95061. sqlite3VdbeAddOp2(v, OP_RowData, iSrc, regData);
  95062. sqlite3VdbeAddOp3(v, OP_Insert, iDest, regData, regRowid);
  95063. sqlite3VdbeChangeP5(v, OPFLAG_NCHANGE|OPFLAG_LASTROWID|OPFLAG_APPEND);
  95064. sqlite3VdbeChangeP4(v, -1, pDest->zName, 0);
  95065. sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1); VdbeCoverage(v);
  95066. sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0);
  95067. sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
  95068. }else{
  95069. sqlite3TableLock(pParse, iDbDest, pDest->tnum, 1, pDest->zName);
  95070. sqlite3TableLock(pParse, iDbSrc, pSrc->tnum, 0, pSrc->zName);
  95071. }
  95072. for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
  95073. u8 useSeekResult = 0;
  95074. for(pSrcIdx=pSrc->pIndex; ALWAYS(pSrcIdx); pSrcIdx=pSrcIdx->pNext){
  95075. if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
  95076. }
  95077. assert( pSrcIdx );
  95078. sqlite3VdbeAddOp3(v, OP_OpenRead, iSrc, pSrcIdx->tnum, iDbSrc);
  95079. sqlite3VdbeSetP4KeyInfo(pParse, pSrcIdx);
  95080. VdbeComment((v, "%s", pSrcIdx->zName));
  95081. sqlite3VdbeAddOp3(v, OP_OpenWrite, iDest, pDestIdx->tnum, iDbDest);
  95082. sqlite3VdbeSetP4KeyInfo(pParse, pDestIdx);
  95083. sqlite3VdbeChangeP5(v, OPFLAG_BULKCSR);
  95084. VdbeComment((v, "%s", pDestIdx->zName));
  95085. addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0); VdbeCoverage(v);
  95086. sqlite3VdbeAddOp2(v, OP_RowKey, iSrc, regData);
  95087. if( db->flags & SQLITE_Vacuum ){
  95088. /* This INSERT command is part of a VACUUM operation, which guarantees
  95089. ** that the destination table is empty. If all indexed columns use
  95090. ** collation sequence BINARY, then it can also be assumed that the
  95091. ** index will be populated by inserting keys in strictly sorted
  95092. ** order. In this case, instead of seeking within the b-tree as part
  95093. ** of every OP_IdxInsert opcode, an OP_Last is added before the
  95094. ** OP_IdxInsert to seek to the point within the b-tree where each key
  95095. ** should be inserted. This is faster.
  95096. **
  95097. ** If any of the indexed columns use a collation sequence other than
  95098. ** BINARY, this optimization is disabled. This is because the user
  95099. ** might change the definition of a collation sequence and then run
  95100. ** a VACUUM command. In that case keys may not be written in strictly
  95101. ** sorted order. */
  95102. for(i=0; i<pSrcIdx->nColumn; i++){
  95103. char *zColl = pSrcIdx->azColl[i];
  95104. assert( zColl!=0 );
  95105. if( sqlite3_stricmp("BINARY", zColl) ) break;
  95106. }
  95107. if( i==pSrcIdx->nColumn ){
  95108. useSeekResult = OPFLAG_USESEEKRESULT;
  95109. sqlite3VdbeAddOp3(v, OP_Last, iDest, 0, -1);
  95110. }
  95111. }
  95112. sqlite3VdbeAddOp3(v, OP_IdxInsert, iDest, regData, 1);
  95113. sqlite3VdbeChangeP5(v, useSeekResult);
  95114. sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1+1); VdbeCoverage(v);
  95115. sqlite3VdbeJumpHere(v, addr1);
  95116. sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0);
  95117. sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
  95118. }
  95119. if( emptySrcTest ) sqlite3VdbeJumpHere(v, emptySrcTest);
  95120. sqlite3ReleaseTempReg(pParse, regRowid);
  95121. sqlite3ReleaseTempReg(pParse, regData);
  95122. if( emptyDestTest ){
  95123. sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_OK, 0);
  95124. sqlite3VdbeJumpHere(v, emptyDestTest);
  95125. sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
  95126. return 0;
  95127. }else{
  95128. return 1;
  95129. }
  95130. }
  95131. #endif /* SQLITE_OMIT_XFER_OPT */
  95132. /************** End of insert.c **********************************************/
  95133. /************** Begin file legacy.c ******************************************/
  95134. /*
  95135. ** 2001 September 15
  95136. **
  95137. ** The author disclaims copyright to this source code. In place of
  95138. ** a legal notice, here is a blessing:
  95139. **
  95140. ** May you do good and not evil.
  95141. ** May you find forgiveness for yourself and forgive others.
  95142. ** May you share freely, never taking more than you give.
  95143. **
  95144. *************************************************************************
  95145. ** Main file for the SQLite library. The routines in this file
  95146. ** implement the programmer interface to the library. Routines in
  95147. ** other files are for internal use by SQLite and should not be
  95148. ** accessed by users of the library.
  95149. */
  95150. /*
  95151. ** Execute SQL code. Return one of the SQLITE_ success/failure
  95152. ** codes. Also write an error message into memory obtained from
  95153. ** malloc() and make *pzErrMsg point to that message.
  95154. **
  95155. ** If the SQL is a query, then for each row in the query result
  95156. ** the xCallback() function is called. pArg becomes the first
  95157. ** argument to xCallback(). If xCallback=NULL then no callback
  95158. ** is invoked, even for queries.
  95159. */
  95160. SQLITE_API int SQLITE_STDCALL sqlite3_exec(
  95161. sqlite3 *db, /* The database on which the SQL executes */
  95162. const char *zSql, /* The SQL to be executed */
  95163. sqlite3_callback xCallback, /* Invoke this callback routine */
  95164. void *pArg, /* First argument to xCallback() */
  95165. char **pzErrMsg /* Write error messages here */
  95166. ){
  95167. int rc = SQLITE_OK; /* Return code */
  95168. const char *zLeftover; /* Tail of unprocessed SQL */
  95169. sqlite3_stmt *pStmt = 0; /* The current SQL statement */
  95170. char **azCols = 0; /* Names of result columns */
  95171. int callbackIsInit; /* True if callback data is initialized */
  95172. if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
  95173. if( zSql==0 ) zSql = "";
  95174. sqlite3_mutex_enter(db->mutex);
  95175. sqlite3Error(db, SQLITE_OK);
  95176. while( rc==SQLITE_OK && zSql[0] ){
  95177. int nCol;
  95178. char **azVals = 0;
  95179. pStmt = 0;
  95180. rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, &zLeftover);
  95181. assert( rc==SQLITE_OK || pStmt==0 );
  95182. if( rc!=SQLITE_OK ){
  95183. continue;
  95184. }
  95185. if( !pStmt ){
  95186. /* this happens for a comment or white-space */
  95187. zSql = zLeftover;
  95188. continue;
  95189. }
  95190. callbackIsInit = 0;
  95191. nCol = sqlite3_column_count(pStmt);
  95192. while( 1 ){
  95193. int i;
  95194. rc = sqlite3_step(pStmt);
  95195. /* Invoke the callback function if required */
  95196. if( xCallback && (SQLITE_ROW==rc ||
  95197. (SQLITE_DONE==rc && !callbackIsInit
  95198. && db->flags&SQLITE_NullCallback)) ){
  95199. if( !callbackIsInit ){
  95200. azCols = sqlite3DbMallocZero(db, 2*nCol*sizeof(const char*) + 1);
  95201. if( azCols==0 ){
  95202. goto exec_out;
  95203. }
  95204. for(i=0; i<nCol; i++){
  95205. azCols[i] = (char *)sqlite3_column_name(pStmt, i);
  95206. /* sqlite3VdbeSetColName() installs column names as UTF8
  95207. ** strings so there is no way for sqlite3_column_name() to fail. */
  95208. assert( azCols[i]!=0 );
  95209. }
  95210. callbackIsInit = 1;
  95211. }
  95212. if( rc==SQLITE_ROW ){
  95213. azVals = &azCols[nCol];
  95214. for(i=0; i<nCol; i++){
  95215. azVals[i] = (char *)sqlite3_column_text(pStmt, i);
  95216. if( !azVals[i] && sqlite3_column_type(pStmt, i)!=SQLITE_NULL ){
  95217. db->mallocFailed = 1;
  95218. goto exec_out;
  95219. }
  95220. }
  95221. }
  95222. if( xCallback(pArg, nCol, azVals, azCols) ){
  95223. /* EVIDENCE-OF: R-38229-40159 If the callback function to
  95224. ** sqlite3_exec() returns non-zero, then sqlite3_exec() will
  95225. ** return SQLITE_ABORT. */
  95226. rc = SQLITE_ABORT;
  95227. sqlite3VdbeFinalize((Vdbe *)pStmt);
  95228. pStmt = 0;
  95229. sqlite3Error(db, SQLITE_ABORT);
  95230. goto exec_out;
  95231. }
  95232. }
  95233. if( rc!=SQLITE_ROW ){
  95234. rc = sqlite3VdbeFinalize((Vdbe *)pStmt);
  95235. pStmt = 0;
  95236. zSql = zLeftover;
  95237. while( sqlite3Isspace(zSql[0]) ) zSql++;
  95238. break;
  95239. }
  95240. }
  95241. sqlite3DbFree(db, azCols);
  95242. azCols = 0;
  95243. }
  95244. exec_out:
  95245. if( pStmt ) sqlite3VdbeFinalize((Vdbe *)pStmt);
  95246. sqlite3DbFree(db, azCols);
  95247. rc = sqlite3ApiExit(db, rc);
  95248. if( rc!=SQLITE_OK && pzErrMsg ){
  95249. int nErrMsg = 1 + sqlite3Strlen30(sqlite3_errmsg(db));
  95250. *pzErrMsg = sqlite3Malloc(nErrMsg);
  95251. if( *pzErrMsg ){
  95252. memcpy(*pzErrMsg, sqlite3_errmsg(db), nErrMsg);
  95253. }else{
  95254. rc = SQLITE_NOMEM;
  95255. sqlite3Error(db, SQLITE_NOMEM);
  95256. }
  95257. }else if( pzErrMsg ){
  95258. *pzErrMsg = 0;
  95259. }
  95260. assert( (rc&db->errMask)==rc );
  95261. sqlite3_mutex_leave(db->mutex);
  95262. return rc;
  95263. }
  95264. /************** End of legacy.c **********************************************/
  95265. /************** Begin file loadext.c *****************************************/
  95266. /*
  95267. ** 2006 June 7
  95268. **
  95269. ** The author disclaims copyright to this source code. In place of
  95270. ** a legal notice, here is a blessing:
  95271. **
  95272. ** May you do good and not evil.
  95273. ** May you find forgiveness for yourself and forgive others.
  95274. ** May you share freely, never taking more than you give.
  95275. **
  95276. *************************************************************************
  95277. ** This file contains code used to dynamically load extensions into
  95278. ** the SQLite library.
  95279. */
  95280. #ifndef SQLITE_CORE
  95281. #define SQLITE_CORE 1 /* Disable the API redefinition in sqlite3ext.h */
  95282. #endif
  95283. /************** Include sqlite3ext.h in the middle of loadext.c **************/
  95284. /************** Begin file sqlite3ext.h **************************************/
  95285. /*
  95286. ** 2006 June 7
  95287. **
  95288. ** The author disclaims copyright to this source code. In place of
  95289. ** a legal notice, here is a blessing:
  95290. **
  95291. ** May you do good and not evil.
  95292. ** May you find forgiveness for yourself and forgive others.
  95293. ** May you share freely, never taking more than you give.
  95294. **
  95295. *************************************************************************
  95296. ** This header file defines the SQLite interface for use by
  95297. ** shared libraries that want to be imported as extensions into
  95298. ** an SQLite instance. Shared libraries that intend to be loaded
  95299. ** as extensions by SQLite should #include this file instead of
  95300. ** sqlite3.h.
  95301. */
  95302. #ifndef _SQLITE3EXT_H_
  95303. #define _SQLITE3EXT_H_
  95304. typedef struct sqlite3_api_routines sqlite3_api_routines;
  95305. /*
  95306. ** The following structure holds pointers to all of the SQLite API
  95307. ** routines.
  95308. **
  95309. ** WARNING: In order to maintain backwards compatibility, add new
  95310. ** interfaces to the end of this structure only. If you insert new
  95311. ** interfaces in the middle of this structure, then older different
  95312. ** versions of SQLite will not be able to load each other's shared
  95313. ** libraries!
  95314. */
  95315. struct sqlite3_api_routines {
  95316. void * (*aggregate_context)(sqlite3_context*,int nBytes);
  95317. int (*aggregate_count)(sqlite3_context*);
  95318. int (*bind_blob)(sqlite3_stmt*,int,const void*,int n,void(*)(void*));
  95319. int (*bind_double)(sqlite3_stmt*,int,double);
  95320. int (*bind_int)(sqlite3_stmt*,int,int);
  95321. int (*bind_int64)(sqlite3_stmt*,int,sqlite_int64);
  95322. int (*bind_null)(sqlite3_stmt*,int);
  95323. int (*bind_parameter_count)(sqlite3_stmt*);
  95324. int (*bind_parameter_index)(sqlite3_stmt*,const char*zName);
  95325. const char * (*bind_parameter_name)(sqlite3_stmt*,int);
  95326. int (*bind_text)(sqlite3_stmt*,int,const char*,int n,void(*)(void*));
  95327. int (*bind_text16)(sqlite3_stmt*,int,const void*,int,void(*)(void*));
  95328. int (*bind_value)(sqlite3_stmt*,int,const sqlite3_value*);
  95329. int (*busy_handler)(sqlite3*,int(*)(void*,int),void*);
  95330. int (*busy_timeout)(sqlite3*,int ms);
  95331. int (*changes)(sqlite3*);
  95332. int (*close)(sqlite3*);
  95333. int (*collation_needed)(sqlite3*,void*,void(*)(void*,sqlite3*,
  95334. int eTextRep,const char*));
  95335. int (*collation_needed16)(sqlite3*,void*,void(*)(void*,sqlite3*,
  95336. int eTextRep,const void*));
  95337. const void * (*column_blob)(sqlite3_stmt*,int iCol);
  95338. int (*column_bytes)(sqlite3_stmt*,int iCol);
  95339. int (*column_bytes16)(sqlite3_stmt*,int iCol);
  95340. int (*column_count)(sqlite3_stmt*pStmt);
  95341. const char * (*column_database_name)(sqlite3_stmt*,int);
  95342. const void * (*column_database_name16)(sqlite3_stmt*,int);
  95343. const char * (*column_decltype)(sqlite3_stmt*,int i);
  95344. const void * (*column_decltype16)(sqlite3_stmt*,int);
  95345. double (*column_double)(sqlite3_stmt*,int iCol);
  95346. int (*column_int)(sqlite3_stmt*,int iCol);
  95347. sqlite_int64 (*column_int64)(sqlite3_stmt*,int iCol);
  95348. const char * (*column_name)(sqlite3_stmt*,int);
  95349. const void * (*column_name16)(sqlite3_stmt*,int);
  95350. const char * (*column_origin_name)(sqlite3_stmt*,int);
  95351. const void * (*column_origin_name16)(sqlite3_stmt*,int);
  95352. const char * (*column_table_name)(sqlite3_stmt*,int);
  95353. const void * (*column_table_name16)(sqlite3_stmt*,int);
  95354. const unsigned char * (*column_text)(sqlite3_stmt*,int iCol);
  95355. const void * (*column_text16)(sqlite3_stmt*,int iCol);
  95356. int (*column_type)(sqlite3_stmt*,int iCol);
  95357. sqlite3_value* (*column_value)(sqlite3_stmt*,int iCol);
  95358. void * (*commit_hook)(sqlite3*,int(*)(void*),void*);
  95359. int (*complete)(const char*sql);
  95360. int (*complete16)(const void*sql);
  95361. int (*create_collation)(sqlite3*,const char*,int,void*,
  95362. int(*)(void*,int,const void*,int,const void*));
  95363. int (*create_collation16)(sqlite3*,const void*,int,void*,
  95364. int(*)(void*,int,const void*,int,const void*));
  95365. int (*create_function)(sqlite3*,const char*,int,int,void*,
  95366. void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
  95367. void (*xStep)(sqlite3_context*,int,sqlite3_value**),
  95368. void (*xFinal)(sqlite3_context*));
  95369. int (*create_function16)(sqlite3*,const void*,int,int,void*,
  95370. void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
  95371. void (*xStep)(sqlite3_context*,int,sqlite3_value**),
  95372. void (*xFinal)(sqlite3_context*));
  95373. int (*create_module)(sqlite3*,const char*,const sqlite3_module*,void*);
  95374. int (*data_count)(sqlite3_stmt*pStmt);
  95375. sqlite3 * (*db_handle)(sqlite3_stmt*);
  95376. int (*declare_vtab)(sqlite3*,const char*);
  95377. int (*enable_shared_cache)(int);
  95378. int (*errcode)(sqlite3*db);
  95379. const char * (*errmsg)(sqlite3*);
  95380. const void * (*errmsg16)(sqlite3*);
  95381. int (*exec)(sqlite3*,const char*,sqlite3_callback,void*,char**);
  95382. int (*expired)(sqlite3_stmt*);
  95383. int (*finalize)(sqlite3_stmt*pStmt);
  95384. void (*free)(void*);
  95385. void (*free_table)(char**result);
  95386. int (*get_autocommit)(sqlite3*);
  95387. void * (*get_auxdata)(sqlite3_context*,int);
  95388. int (*get_table)(sqlite3*,const char*,char***,int*,int*,char**);
  95389. int (*global_recover)(void);
  95390. void (*interruptx)(sqlite3*);
  95391. sqlite_int64 (*last_insert_rowid)(sqlite3*);
  95392. const char * (*libversion)(void);
  95393. int (*libversion_number)(void);
  95394. void *(*malloc)(int);
  95395. char * (*mprintf)(const char*,...);
  95396. int (*open)(const char*,sqlite3**);
  95397. int (*open16)(const void*,sqlite3**);
  95398. int (*prepare)(sqlite3*,const char*,int,sqlite3_stmt**,const char**);
  95399. int (*prepare16)(sqlite3*,const void*,int,sqlite3_stmt**,const void**);
  95400. void * (*profile)(sqlite3*,void(*)(void*,const char*,sqlite_uint64),void*);
  95401. void (*progress_handler)(sqlite3*,int,int(*)(void*),void*);
  95402. void *(*realloc)(void*,int);
  95403. int (*reset)(sqlite3_stmt*pStmt);
  95404. void (*result_blob)(sqlite3_context*,const void*,int,void(*)(void*));
  95405. void (*result_double)(sqlite3_context*,double);
  95406. void (*result_error)(sqlite3_context*,const char*,int);
  95407. void (*result_error16)(sqlite3_context*,const void*,int);
  95408. void (*result_int)(sqlite3_context*,int);
  95409. void (*result_int64)(sqlite3_context*,sqlite_int64);
  95410. void (*result_null)(sqlite3_context*);
  95411. void (*result_text)(sqlite3_context*,const char*,int,void(*)(void*));
  95412. void (*result_text16)(sqlite3_context*,const void*,int,void(*)(void*));
  95413. void (*result_text16be)(sqlite3_context*,const void*,int,void(*)(void*));
  95414. void (*result_text16le)(sqlite3_context*,const void*,int,void(*)(void*));
  95415. void (*result_value)(sqlite3_context*,sqlite3_value*);
  95416. void * (*rollback_hook)(sqlite3*,void(*)(void*),void*);
  95417. int (*set_authorizer)(sqlite3*,int(*)(void*,int,const char*,const char*,
  95418. const char*,const char*),void*);
  95419. void (*set_auxdata)(sqlite3_context*,int,void*,void (*)(void*));
  95420. char * (*snprintf)(int,char*,const char*,...);
  95421. int (*step)(sqlite3_stmt*);
  95422. int (*table_column_metadata)(sqlite3*,const char*,const char*,const char*,
  95423. char const**,char const**,int*,int*,int*);
  95424. void (*thread_cleanup)(void);
  95425. int (*total_changes)(sqlite3*);
  95426. void * (*trace)(sqlite3*,void(*xTrace)(void*,const char*),void*);
  95427. int (*transfer_bindings)(sqlite3_stmt*,sqlite3_stmt*);
  95428. void * (*update_hook)(sqlite3*,void(*)(void*,int ,char const*,char const*,
  95429. sqlite_int64),void*);
  95430. void * (*user_data)(sqlite3_context*);
  95431. const void * (*value_blob)(sqlite3_value*);
  95432. int (*value_bytes)(sqlite3_value*);
  95433. int (*value_bytes16)(sqlite3_value*);
  95434. double (*value_double)(sqlite3_value*);
  95435. int (*value_int)(sqlite3_value*);
  95436. sqlite_int64 (*value_int64)(sqlite3_value*);
  95437. int (*value_numeric_type)(sqlite3_value*);
  95438. const unsigned char * (*value_text)(sqlite3_value*);
  95439. const void * (*value_text16)(sqlite3_value*);
  95440. const void * (*value_text16be)(sqlite3_value*);
  95441. const void * (*value_text16le)(sqlite3_value*);
  95442. int (*value_type)(sqlite3_value*);
  95443. char *(*vmprintf)(const char*,va_list);
  95444. /* Added ??? */
  95445. int (*overload_function)(sqlite3*, const char *zFuncName, int nArg);
  95446. /* Added by 3.3.13 */
  95447. int (*prepare_v2)(sqlite3*,const char*,int,sqlite3_stmt**,const char**);
  95448. int (*prepare16_v2)(sqlite3*,const void*,int,sqlite3_stmt**,const void**);
  95449. int (*clear_bindings)(sqlite3_stmt*);
  95450. /* Added by 3.4.1 */
  95451. int (*create_module_v2)(sqlite3*,const char*,const sqlite3_module*,void*,
  95452. void (*xDestroy)(void *));
  95453. /* Added by 3.5.0 */
  95454. int (*bind_zeroblob)(sqlite3_stmt*,int,int);
  95455. int (*blob_bytes)(sqlite3_blob*);
  95456. int (*blob_close)(sqlite3_blob*);
  95457. int (*blob_open)(sqlite3*,const char*,const char*,const char*,sqlite3_int64,
  95458. int,sqlite3_blob**);
  95459. int (*blob_read)(sqlite3_blob*,void*,int,int);
  95460. int (*blob_write)(sqlite3_blob*,const void*,int,int);
  95461. int (*create_collation_v2)(sqlite3*,const char*,int,void*,
  95462. int(*)(void*,int,const void*,int,const void*),
  95463. void(*)(void*));
  95464. int (*file_control)(sqlite3*,const char*,int,void*);
  95465. sqlite3_int64 (*memory_highwater)(int);
  95466. sqlite3_int64 (*memory_used)(void);
  95467. sqlite3_mutex *(*mutex_alloc)(int);
  95468. void (*mutex_enter)(sqlite3_mutex*);
  95469. void (*mutex_free)(sqlite3_mutex*);
  95470. void (*mutex_leave)(sqlite3_mutex*);
  95471. int (*mutex_try)(sqlite3_mutex*);
  95472. int (*open_v2)(const char*,sqlite3**,int,const char*);
  95473. int (*release_memory)(int);
  95474. void (*result_error_nomem)(sqlite3_context*);
  95475. void (*result_error_toobig)(sqlite3_context*);
  95476. int (*sleep)(int);
  95477. void (*soft_heap_limit)(int);
  95478. sqlite3_vfs *(*vfs_find)(const char*);
  95479. int (*vfs_register)(sqlite3_vfs*,int);
  95480. int (*vfs_unregister)(sqlite3_vfs*);
  95481. int (*xthreadsafe)(void);
  95482. void (*result_zeroblob)(sqlite3_context*,int);
  95483. void (*result_error_code)(sqlite3_context*,int);
  95484. int (*test_control)(int, ...);
  95485. void (*randomness)(int,void*);
  95486. sqlite3 *(*context_db_handle)(sqlite3_context*);
  95487. int (*extended_result_codes)(sqlite3*,int);
  95488. int (*limit)(sqlite3*,int,int);
  95489. sqlite3_stmt *(*next_stmt)(sqlite3*,sqlite3_stmt*);
  95490. const char *(*sql)(sqlite3_stmt*);
  95491. int (*status)(int,int*,int*,int);
  95492. int (*backup_finish)(sqlite3_backup*);
  95493. sqlite3_backup *(*backup_init)(sqlite3*,const char*,sqlite3*,const char*);
  95494. int (*backup_pagecount)(sqlite3_backup*);
  95495. int (*backup_remaining)(sqlite3_backup*);
  95496. int (*backup_step)(sqlite3_backup*,int);
  95497. const char *(*compileoption_get)(int);
  95498. int (*compileoption_used)(const char*);
  95499. int (*create_function_v2)(sqlite3*,const char*,int,int,void*,
  95500. void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
  95501. void (*xStep)(sqlite3_context*,int,sqlite3_value**),
  95502. void (*xFinal)(sqlite3_context*),
  95503. void(*xDestroy)(void*));
  95504. int (*db_config)(sqlite3*,int,...);
  95505. sqlite3_mutex *(*db_mutex)(sqlite3*);
  95506. int (*db_status)(sqlite3*,int,int*,int*,int);
  95507. int (*extended_errcode)(sqlite3*);
  95508. void (*log)(int,const char*,...);
  95509. sqlite3_int64 (*soft_heap_limit64)(sqlite3_int64);
  95510. const char *(*sourceid)(void);
  95511. int (*stmt_status)(sqlite3_stmt*,int,int);
  95512. int (*strnicmp)(const char*,const char*,int);
  95513. int (*unlock_notify)(sqlite3*,void(*)(void**,int),void*);
  95514. int (*wal_autocheckpoint)(sqlite3*,int);
  95515. int (*wal_checkpoint)(sqlite3*,const char*);
  95516. void *(*wal_hook)(sqlite3*,int(*)(void*,sqlite3*,const char*,int),void*);
  95517. int (*blob_reopen)(sqlite3_blob*,sqlite3_int64);
  95518. int (*vtab_config)(sqlite3*,int op,...);
  95519. int (*vtab_on_conflict)(sqlite3*);
  95520. /* Version 3.7.16 and later */
  95521. int (*close_v2)(sqlite3*);
  95522. const char *(*db_filename)(sqlite3*,const char*);
  95523. int (*db_readonly)(sqlite3*,const char*);
  95524. int (*db_release_memory)(sqlite3*);
  95525. const char *(*errstr)(int);
  95526. int (*stmt_busy)(sqlite3_stmt*);
  95527. int (*stmt_readonly)(sqlite3_stmt*);
  95528. int (*stricmp)(const char*,const char*);
  95529. int (*uri_boolean)(const char*,const char*,int);
  95530. sqlite3_int64 (*uri_int64)(const char*,const char*,sqlite3_int64);
  95531. const char *(*uri_parameter)(const char*,const char*);
  95532. char *(*vsnprintf)(int,char*,const char*,va_list);
  95533. int (*wal_checkpoint_v2)(sqlite3*,const char*,int,int*,int*);
  95534. /* Version 3.8.7 and later */
  95535. int (*auto_extension)(void(*)(void));
  95536. int (*bind_blob64)(sqlite3_stmt*,int,const void*,sqlite3_uint64,
  95537. void(*)(void*));
  95538. int (*bind_text64)(sqlite3_stmt*,int,const char*,sqlite3_uint64,
  95539. void(*)(void*),unsigned char);
  95540. int (*cancel_auto_extension)(void(*)(void));
  95541. int (*load_extension)(sqlite3*,const char*,const char*,char**);
  95542. void *(*malloc64)(sqlite3_uint64);
  95543. sqlite3_uint64 (*msize)(void*);
  95544. void *(*realloc64)(void*,sqlite3_uint64);
  95545. void (*reset_auto_extension)(void);
  95546. void (*result_blob64)(sqlite3_context*,const void*,sqlite3_uint64,
  95547. void(*)(void*));
  95548. void (*result_text64)(sqlite3_context*,const char*,sqlite3_uint64,
  95549. void(*)(void*), unsigned char);
  95550. int (*strglob)(const char*,const char*);
  95551. };
  95552. /*
  95553. ** The following macros redefine the API routines so that they are
  95554. ** redirected through the global sqlite3_api structure.
  95555. **
  95556. ** This header file is also used by the loadext.c source file
  95557. ** (part of the main SQLite library - not an extension) so that
  95558. ** it can get access to the sqlite3_api_routines structure
  95559. ** definition. But the main library does not want to redefine
  95560. ** the API. So the redefinition macros are only valid if the
  95561. ** SQLITE_CORE macros is undefined.
  95562. */
  95563. #ifndef SQLITE_CORE
  95564. #define sqlite3_aggregate_context sqlite3_api->aggregate_context
  95565. #ifndef SQLITE_OMIT_DEPRECATED
  95566. #define sqlite3_aggregate_count sqlite3_api->aggregate_count
  95567. #endif
  95568. #define sqlite3_bind_blob sqlite3_api->bind_blob
  95569. #define sqlite3_bind_double sqlite3_api->bind_double
  95570. #define sqlite3_bind_int sqlite3_api->bind_int
  95571. #define sqlite3_bind_int64 sqlite3_api->bind_int64
  95572. #define sqlite3_bind_null sqlite3_api->bind_null
  95573. #define sqlite3_bind_parameter_count sqlite3_api->bind_parameter_count
  95574. #define sqlite3_bind_parameter_index sqlite3_api->bind_parameter_index
  95575. #define sqlite3_bind_parameter_name sqlite3_api->bind_parameter_name
  95576. #define sqlite3_bind_text sqlite3_api->bind_text
  95577. #define sqlite3_bind_text16 sqlite3_api->bind_text16
  95578. #define sqlite3_bind_value sqlite3_api->bind_value
  95579. #define sqlite3_busy_handler sqlite3_api->busy_handler
  95580. #define sqlite3_busy_timeout sqlite3_api->busy_timeout
  95581. #define sqlite3_changes sqlite3_api->changes
  95582. #define sqlite3_close sqlite3_api->close
  95583. #define sqlite3_collation_needed sqlite3_api->collation_needed
  95584. #define sqlite3_collation_needed16 sqlite3_api->collation_needed16
  95585. #define sqlite3_column_blob sqlite3_api->column_blob
  95586. #define sqlite3_column_bytes sqlite3_api->column_bytes
  95587. #define sqlite3_column_bytes16 sqlite3_api->column_bytes16
  95588. #define sqlite3_column_count sqlite3_api->column_count
  95589. #define sqlite3_column_database_name sqlite3_api->column_database_name
  95590. #define sqlite3_column_database_name16 sqlite3_api->column_database_name16
  95591. #define sqlite3_column_decltype sqlite3_api->column_decltype
  95592. #define sqlite3_column_decltype16 sqlite3_api->column_decltype16
  95593. #define sqlite3_column_double sqlite3_api->column_double
  95594. #define sqlite3_column_int sqlite3_api->column_int
  95595. #define sqlite3_column_int64 sqlite3_api->column_int64
  95596. #define sqlite3_column_name sqlite3_api->column_name
  95597. #define sqlite3_column_name16 sqlite3_api->column_name16
  95598. #define sqlite3_column_origin_name sqlite3_api->column_origin_name
  95599. #define sqlite3_column_origin_name16 sqlite3_api->column_origin_name16
  95600. #define sqlite3_column_table_name sqlite3_api->column_table_name
  95601. #define sqlite3_column_table_name16 sqlite3_api->column_table_name16
  95602. #define sqlite3_column_text sqlite3_api->column_text
  95603. #define sqlite3_column_text16 sqlite3_api->column_text16
  95604. #define sqlite3_column_type sqlite3_api->column_type
  95605. #define sqlite3_column_value sqlite3_api->column_value
  95606. #define sqlite3_commit_hook sqlite3_api->commit_hook
  95607. #define sqlite3_complete sqlite3_api->complete
  95608. #define sqlite3_complete16 sqlite3_api->complete16
  95609. #define sqlite3_create_collation sqlite3_api->create_collation
  95610. #define sqlite3_create_collation16 sqlite3_api->create_collation16
  95611. #define sqlite3_create_function sqlite3_api->create_function
  95612. #define sqlite3_create_function16 sqlite3_api->create_function16
  95613. #define sqlite3_create_module sqlite3_api->create_module
  95614. #define sqlite3_create_module_v2 sqlite3_api->create_module_v2
  95615. #define sqlite3_data_count sqlite3_api->data_count
  95616. #define sqlite3_db_handle sqlite3_api->db_handle
  95617. #define sqlite3_declare_vtab sqlite3_api->declare_vtab
  95618. #define sqlite3_enable_shared_cache sqlite3_api->enable_shared_cache
  95619. #define sqlite3_errcode sqlite3_api->errcode
  95620. #define sqlite3_errmsg sqlite3_api->errmsg
  95621. #define sqlite3_errmsg16 sqlite3_api->errmsg16
  95622. #define sqlite3_exec sqlite3_api->exec
  95623. #ifndef SQLITE_OMIT_DEPRECATED
  95624. #define sqlite3_expired sqlite3_api->expired
  95625. #endif
  95626. #define sqlite3_finalize sqlite3_api->finalize
  95627. #define sqlite3_free sqlite3_api->free
  95628. #define sqlite3_free_table sqlite3_api->free_table
  95629. #define sqlite3_get_autocommit sqlite3_api->get_autocommit
  95630. #define sqlite3_get_auxdata sqlite3_api->get_auxdata
  95631. #define sqlite3_get_table sqlite3_api->get_table
  95632. #ifndef SQLITE_OMIT_DEPRECATED
  95633. #define sqlite3_global_recover sqlite3_api->global_recover
  95634. #endif
  95635. #define sqlite3_interrupt sqlite3_api->interruptx
  95636. #define sqlite3_last_insert_rowid sqlite3_api->last_insert_rowid
  95637. #define sqlite3_libversion sqlite3_api->libversion
  95638. #define sqlite3_libversion_number sqlite3_api->libversion_number
  95639. #define sqlite3_malloc sqlite3_api->malloc
  95640. #define sqlite3_mprintf sqlite3_api->mprintf
  95641. #define sqlite3_open sqlite3_api->open
  95642. #define sqlite3_open16 sqlite3_api->open16
  95643. #define sqlite3_prepare sqlite3_api->prepare
  95644. #define sqlite3_prepare16 sqlite3_api->prepare16
  95645. #define sqlite3_prepare_v2 sqlite3_api->prepare_v2
  95646. #define sqlite3_prepare16_v2 sqlite3_api->prepare16_v2
  95647. #define sqlite3_profile sqlite3_api->profile
  95648. #define sqlite3_progress_handler sqlite3_api->progress_handler
  95649. #define sqlite3_realloc sqlite3_api->realloc
  95650. #define sqlite3_reset sqlite3_api->reset
  95651. #define sqlite3_result_blob sqlite3_api->result_blob
  95652. #define sqlite3_result_double sqlite3_api->result_double
  95653. #define sqlite3_result_error sqlite3_api->result_error
  95654. #define sqlite3_result_error16 sqlite3_api->result_error16
  95655. #define sqlite3_result_int sqlite3_api->result_int
  95656. #define sqlite3_result_int64 sqlite3_api->result_int64
  95657. #define sqlite3_result_null sqlite3_api->result_null
  95658. #define sqlite3_result_text sqlite3_api->result_text
  95659. #define sqlite3_result_text16 sqlite3_api->result_text16
  95660. #define sqlite3_result_text16be sqlite3_api->result_text16be
  95661. #define sqlite3_result_text16le sqlite3_api->result_text16le
  95662. #define sqlite3_result_value sqlite3_api->result_value
  95663. #define sqlite3_rollback_hook sqlite3_api->rollback_hook
  95664. #define sqlite3_set_authorizer sqlite3_api->set_authorizer
  95665. #define sqlite3_set_auxdata sqlite3_api->set_auxdata
  95666. #define sqlite3_snprintf sqlite3_api->snprintf
  95667. #define sqlite3_step sqlite3_api->step
  95668. #define sqlite3_table_column_metadata sqlite3_api->table_column_metadata
  95669. #define sqlite3_thread_cleanup sqlite3_api->thread_cleanup
  95670. #define sqlite3_total_changes sqlite3_api->total_changes
  95671. #define sqlite3_trace sqlite3_api->trace
  95672. #ifndef SQLITE_OMIT_DEPRECATED
  95673. #define sqlite3_transfer_bindings sqlite3_api->transfer_bindings
  95674. #endif
  95675. #define sqlite3_update_hook sqlite3_api->update_hook
  95676. #define sqlite3_user_data sqlite3_api->user_data
  95677. #define sqlite3_value_blob sqlite3_api->value_blob
  95678. #define sqlite3_value_bytes sqlite3_api->value_bytes
  95679. #define sqlite3_value_bytes16 sqlite3_api->value_bytes16
  95680. #define sqlite3_value_double sqlite3_api->value_double
  95681. #define sqlite3_value_int sqlite3_api->value_int
  95682. #define sqlite3_value_int64 sqlite3_api->value_int64
  95683. #define sqlite3_value_numeric_type sqlite3_api->value_numeric_type
  95684. #define sqlite3_value_text sqlite3_api->value_text
  95685. #define sqlite3_value_text16 sqlite3_api->value_text16
  95686. #define sqlite3_value_text16be sqlite3_api->value_text16be
  95687. #define sqlite3_value_text16le sqlite3_api->value_text16le
  95688. #define sqlite3_value_type sqlite3_api->value_type
  95689. #define sqlite3_vmprintf sqlite3_api->vmprintf
  95690. #define sqlite3_overload_function sqlite3_api->overload_function
  95691. #define sqlite3_prepare_v2 sqlite3_api->prepare_v2
  95692. #define sqlite3_prepare16_v2 sqlite3_api->prepare16_v2
  95693. #define sqlite3_clear_bindings sqlite3_api->clear_bindings
  95694. #define sqlite3_bind_zeroblob sqlite3_api->bind_zeroblob
  95695. #define sqlite3_blob_bytes sqlite3_api->blob_bytes
  95696. #define sqlite3_blob_close sqlite3_api->blob_close
  95697. #define sqlite3_blob_open sqlite3_api->blob_open
  95698. #define sqlite3_blob_read sqlite3_api->blob_read
  95699. #define sqlite3_blob_write sqlite3_api->blob_write
  95700. #define sqlite3_create_collation_v2 sqlite3_api->create_collation_v2
  95701. #define sqlite3_file_control sqlite3_api->file_control
  95702. #define sqlite3_memory_highwater sqlite3_api->memory_highwater
  95703. #define sqlite3_memory_used sqlite3_api->memory_used
  95704. #define sqlite3_mutex_alloc sqlite3_api->mutex_alloc
  95705. #define sqlite3_mutex_enter sqlite3_api->mutex_enter
  95706. #define sqlite3_mutex_free sqlite3_api->mutex_free
  95707. #define sqlite3_mutex_leave sqlite3_api->mutex_leave
  95708. #define sqlite3_mutex_try sqlite3_api->mutex_try
  95709. #define sqlite3_open_v2 sqlite3_api->open_v2
  95710. #define sqlite3_release_memory sqlite3_api->release_memory
  95711. #define sqlite3_result_error_nomem sqlite3_api->result_error_nomem
  95712. #define sqlite3_result_error_toobig sqlite3_api->result_error_toobig
  95713. #define sqlite3_sleep sqlite3_api->sleep
  95714. #define sqlite3_soft_heap_limit sqlite3_api->soft_heap_limit
  95715. #define sqlite3_vfs_find sqlite3_api->vfs_find
  95716. #define sqlite3_vfs_register sqlite3_api->vfs_register
  95717. #define sqlite3_vfs_unregister sqlite3_api->vfs_unregister
  95718. #define sqlite3_threadsafe sqlite3_api->xthreadsafe
  95719. #define sqlite3_result_zeroblob sqlite3_api->result_zeroblob
  95720. #define sqlite3_result_error_code sqlite3_api->result_error_code
  95721. #define sqlite3_test_control sqlite3_api->test_control
  95722. #define sqlite3_randomness sqlite3_api->randomness
  95723. #define sqlite3_context_db_handle sqlite3_api->context_db_handle
  95724. #define sqlite3_extended_result_codes sqlite3_api->extended_result_codes
  95725. #define sqlite3_limit sqlite3_api->limit
  95726. #define sqlite3_next_stmt sqlite3_api->next_stmt
  95727. #define sqlite3_sql sqlite3_api->sql
  95728. #define sqlite3_status sqlite3_api->status
  95729. #define sqlite3_backup_finish sqlite3_api->backup_finish
  95730. #define sqlite3_backup_init sqlite3_api->backup_init
  95731. #define sqlite3_backup_pagecount sqlite3_api->backup_pagecount
  95732. #define sqlite3_backup_remaining sqlite3_api->backup_remaining
  95733. #define sqlite3_backup_step sqlite3_api->backup_step
  95734. #define sqlite3_compileoption_get sqlite3_api->compileoption_get
  95735. #define sqlite3_compileoption_used sqlite3_api->compileoption_used
  95736. #define sqlite3_create_function_v2 sqlite3_api->create_function_v2
  95737. #define sqlite3_db_config sqlite3_api->db_config
  95738. #define sqlite3_db_mutex sqlite3_api->db_mutex
  95739. #define sqlite3_db_status sqlite3_api->db_status
  95740. #define sqlite3_extended_errcode sqlite3_api->extended_errcode
  95741. #define sqlite3_log sqlite3_api->log
  95742. #define sqlite3_soft_heap_limit64 sqlite3_api->soft_heap_limit64
  95743. #define sqlite3_sourceid sqlite3_api->sourceid
  95744. #define sqlite3_stmt_status sqlite3_api->stmt_status
  95745. #define sqlite3_strnicmp sqlite3_api->strnicmp
  95746. #define sqlite3_unlock_notify sqlite3_api->unlock_notify
  95747. #define sqlite3_wal_autocheckpoint sqlite3_api->wal_autocheckpoint
  95748. #define sqlite3_wal_checkpoint sqlite3_api->wal_checkpoint
  95749. #define sqlite3_wal_hook sqlite3_api->wal_hook
  95750. #define sqlite3_blob_reopen sqlite3_api->blob_reopen
  95751. #define sqlite3_vtab_config sqlite3_api->vtab_config
  95752. #define sqlite3_vtab_on_conflict sqlite3_api->vtab_on_conflict
  95753. /* Version 3.7.16 and later */
  95754. #define sqlite3_close_v2 sqlite3_api->close_v2
  95755. #define sqlite3_db_filename sqlite3_api->db_filename
  95756. #define sqlite3_db_readonly sqlite3_api->db_readonly
  95757. #define sqlite3_db_release_memory sqlite3_api->db_release_memory
  95758. #define sqlite3_errstr sqlite3_api->errstr
  95759. #define sqlite3_stmt_busy sqlite3_api->stmt_busy
  95760. #define sqlite3_stmt_readonly sqlite3_api->stmt_readonly
  95761. #define sqlite3_stricmp sqlite3_api->stricmp
  95762. #define sqlite3_uri_boolean sqlite3_api->uri_boolean
  95763. #define sqlite3_uri_int64 sqlite3_api->uri_int64
  95764. #define sqlite3_uri_parameter sqlite3_api->uri_parameter
  95765. #define sqlite3_uri_vsnprintf sqlite3_api->vsnprintf
  95766. #define sqlite3_wal_checkpoint_v2 sqlite3_api->wal_checkpoint_v2
  95767. /* Version 3.8.7 and later */
  95768. #define sqlite3_auto_extension sqlite3_api->auto_extension
  95769. #define sqlite3_bind_blob64 sqlite3_api->bind_blob64
  95770. #define sqlite3_bind_text64 sqlite3_api->bind_text64
  95771. #define sqlite3_cancel_auto_extension sqlite3_api->cancel_auto_extension
  95772. #define sqlite3_load_extension sqlite3_api->load_extension
  95773. #define sqlite3_malloc64 sqlite3_api->malloc64
  95774. #define sqlite3_msize sqlite3_api->msize
  95775. #define sqlite3_realloc64 sqlite3_api->realloc64
  95776. #define sqlite3_reset_auto_extension sqlite3_api->reset_auto_extension
  95777. #define sqlite3_result_blob64 sqlite3_api->result_blob64
  95778. #define sqlite3_result_text64 sqlite3_api->result_text64
  95779. #define sqlite3_strglob sqlite3_api->strglob
  95780. #endif /* SQLITE_CORE */
  95781. #ifndef SQLITE_CORE
  95782. /* This case when the file really is being compiled as a loadable
  95783. ** extension */
  95784. # define SQLITE_EXTENSION_INIT1 const sqlite3_api_routines *sqlite3_api=0;
  95785. # define SQLITE_EXTENSION_INIT2(v) sqlite3_api=v;
  95786. # define SQLITE_EXTENSION_INIT3 \
  95787. extern const sqlite3_api_routines *sqlite3_api;
  95788. #else
  95789. /* This case when the file is being statically linked into the
  95790. ** application */
  95791. # define SQLITE_EXTENSION_INIT1 /*no-op*/
  95792. # define SQLITE_EXTENSION_INIT2(v) (void)v; /* unused parameter */
  95793. # define SQLITE_EXTENSION_INIT3 /*no-op*/
  95794. #endif
  95795. #endif /* _SQLITE3EXT_H_ */
  95796. /************** End of sqlite3ext.h ******************************************/
  95797. /************** Continuing where we left off in loadext.c ********************/
  95798. /* #include <string.h> */
  95799. #ifndef SQLITE_OMIT_LOAD_EXTENSION
  95800. /*
  95801. ** Some API routines are omitted when various features are
  95802. ** excluded from a build of SQLite. Substitute a NULL pointer
  95803. ** for any missing APIs.
  95804. */
  95805. #ifndef SQLITE_ENABLE_COLUMN_METADATA
  95806. # define sqlite3_column_database_name 0
  95807. # define sqlite3_column_database_name16 0
  95808. # define sqlite3_column_table_name 0
  95809. # define sqlite3_column_table_name16 0
  95810. # define sqlite3_column_origin_name 0
  95811. # define sqlite3_column_origin_name16 0
  95812. #endif
  95813. #ifdef SQLITE_OMIT_AUTHORIZATION
  95814. # define sqlite3_set_authorizer 0
  95815. #endif
  95816. #ifdef SQLITE_OMIT_UTF16
  95817. # define sqlite3_bind_text16 0
  95818. # define sqlite3_collation_needed16 0
  95819. # define sqlite3_column_decltype16 0
  95820. # define sqlite3_column_name16 0
  95821. # define sqlite3_column_text16 0
  95822. # define sqlite3_complete16 0
  95823. # define sqlite3_create_collation16 0
  95824. # define sqlite3_create_function16 0
  95825. # define sqlite3_errmsg16 0
  95826. # define sqlite3_open16 0
  95827. # define sqlite3_prepare16 0
  95828. # define sqlite3_prepare16_v2 0
  95829. # define sqlite3_result_error16 0
  95830. # define sqlite3_result_text16 0
  95831. # define sqlite3_result_text16be 0
  95832. # define sqlite3_result_text16le 0
  95833. # define sqlite3_value_text16 0
  95834. # define sqlite3_value_text16be 0
  95835. # define sqlite3_value_text16le 0
  95836. # define sqlite3_column_database_name16 0
  95837. # define sqlite3_column_table_name16 0
  95838. # define sqlite3_column_origin_name16 0
  95839. #endif
  95840. #ifdef SQLITE_OMIT_COMPLETE
  95841. # define sqlite3_complete 0
  95842. # define sqlite3_complete16 0
  95843. #endif
  95844. #ifdef SQLITE_OMIT_DECLTYPE
  95845. # define sqlite3_column_decltype16 0
  95846. # define sqlite3_column_decltype 0
  95847. #endif
  95848. #ifdef SQLITE_OMIT_PROGRESS_CALLBACK
  95849. # define sqlite3_progress_handler 0
  95850. #endif
  95851. #ifdef SQLITE_OMIT_VIRTUALTABLE
  95852. # define sqlite3_create_module 0
  95853. # define sqlite3_create_module_v2 0
  95854. # define sqlite3_declare_vtab 0
  95855. # define sqlite3_vtab_config 0
  95856. # define sqlite3_vtab_on_conflict 0
  95857. #endif
  95858. #ifdef SQLITE_OMIT_SHARED_CACHE
  95859. # define sqlite3_enable_shared_cache 0
  95860. #endif
  95861. #ifdef SQLITE_OMIT_TRACE
  95862. # define sqlite3_profile 0
  95863. # define sqlite3_trace 0
  95864. #endif
  95865. #ifdef SQLITE_OMIT_GET_TABLE
  95866. # define sqlite3_free_table 0
  95867. # define sqlite3_get_table 0
  95868. #endif
  95869. #ifdef SQLITE_OMIT_INCRBLOB
  95870. #define sqlite3_bind_zeroblob 0
  95871. #define sqlite3_blob_bytes 0
  95872. #define sqlite3_blob_close 0
  95873. #define sqlite3_blob_open 0
  95874. #define sqlite3_blob_read 0
  95875. #define sqlite3_blob_write 0
  95876. #define sqlite3_blob_reopen 0
  95877. #endif
  95878. /*
  95879. ** The following structure contains pointers to all SQLite API routines.
  95880. ** A pointer to this structure is passed into extensions when they are
  95881. ** loaded so that the extension can make calls back into the SQLite
  95882. ** library.
  95883. **
  95884. ** When adding new APIs, add them to the bottom of this structure
  95885. ** in order to preserve backwards compatibility.
  95886. **
  95887. ** Extensions that use newer APIs should first call the
  95888. ** sqlite3_libversion_number() to make sure that the API they
  95889. ** intend to use is supported by the library. Extensions should
  95890. ** also check to make sure that the pointer to the function is
  95891. ** not NULL before calling it.
  95892. */
  95893. static const sqlite3_api_routines sqlite3Apis = {
  95894. sqlite3_aggregate_context,
  95895. #ifndef SQLITE_OMIT_DEPRECATED
  95896. sqlite3_aggregate_count,
  95897. #else
  95898. 0,
  95899. #endif
  95900. sqlite3_bind_blob,
  95901. sqlite3_bind_double,
  95902. sqlite3_bind_int,
  95903. sqlite3_bind_int64,
  95904. sqlite3_bind_null,
  95905. sqlite3_bind_parameter_count,
  95906. sqlite3_bind_parameter_index,
  95907. sqlite3_bind_parameter_name,
  95908. sqlite3_bind_text,
  95909. sqlite3_bind_text16,
  95910. sqlite3_bind_value,
  95911. sqlite3_busy_handler,
  95912. sqlite3_busy_timeout,
  95913. sqlite3_changes,
  95914. sqlite3_close,
  95915. sqlite3_collation_needed,
  95916. sqlite3_collation_needed16,
  95917. sqlite3_column_blob,
  95918. sqlite3_column_bytes,
  95919. sqlite3_column_bytes16,
  95920. sqlite3_column_count,
  95921. sqlite3_column_database_name,
  95922. sqlite3_column_database_name16,
  95923. sqlite3_column_decltype,
  95924. sqlite3_column_decltype16,
  95925. sqlite3_column_double,
  95926. sqlite3_column_int,
  95927. sqlite3_column_int64,
  95928. sqlite3_column_name,
  95929. sqlite3_column_name16,
  95930. sqlite3_column_origin_name,
  95931. sqlite3_column_origin_name16,
  95932. sqlite3_column_table_name,
  95933. sqlite3_column_table_name16,
  95934. sqlite3_column_text,
  95935. sqlite3_column_text16,
  95936. sqlite3_column_type,
  95937. sqlite3_column_value,
  95938. sqlite3_commit_hook,
  95939. sqlite3_complete,
  95940. sqlite3_complete16,
  95941. sqlite3_create_collation,
  95942. sqlite3_create_collation16,
  95943. sqlite3_create_function,
  95944. sqlite3_create_function16,
  95945. sqlite3_create_module,
  95946. sqlite3_data_count,
  95947. sqlite3_db_handle,
  95948. sqlite3_declare_vtab,
  95949. sqlite3_enable_shared_cache,
  95950. sqlite3_errcode,
  95951. sqlite3_errmsg,
  95952. sqlite3_errmsg16,
  95953. sqlite3_exec,
  95954. #ifndef SQLITE_OMIT_DEPRECATED
  95955. sqlite3_expired,
  95956. #else
  95957. 0,
  95958. #endif
  95959. sqlite3_finalize,
  95960. sqlite3_free,
  95961. sqlite3_free_table,
  95962. sqlite3_get_autocommit,
  95963. sqlite3_get_auxdata,
  95964. sqlite3_get_table,
  95965. 0, /* Was sqlite3_global_recover(), but that function is deprecated */
  95966. sqlite3_interrupt,
  95967. sqlite3_last_insert_rowid,
  95968. sqlite3_libversion,
  95969. sqlite3_libversion_number,
  95970. sqlite3_malloc,
  95971. sqlite3_mprintf,
  95972. sqlite3_open,
  95973. sqlite3_open16,
  95974. sqlite3_prepare,
  95975. sqlite3_prepare16,
  95976. sqlite3_profile,
  95977. sqlite3_progress_handler,
  95978. sqlite3_realloc,
  95979. sqlite3_reset,
  95980. sqlite3_result_blob,
  95981. sqlite3_result_double,
  95982. sqlite3_result_error,
  95983. sqlite3_result_error16,
  95984. sqlite3_result_int,
  95985. sqlite3_result_int64,
  95986. sqlite3_result_null,
  95987. sqlite3_result_text,
  95988. sqlite3_result_text16,
  95989. sqlite3_result_text16be,
  95990. sqlite3_result_text16le,
  95991. sqlite3_result_value,
  95992. sqlite3_rollback_hook,
  95993. sqlite3_set_authorizer,
  95994. sqlite3_set_auxdata,
  95995. sqlite3_snprintf,
  95996. sqlite3_step,
  95997. sqlite3_table_column_metadata,
  95998. #ifndef SQLITE_OMIT_DEPRECATED
  95999. sqlite3_thread_cleanup,
  96000. #else
  96001. 0,
  96002. #endif
  96003. sqlite3_total_changes,
  96004. sqlite3_trace,
  96005. #ifndef SQLITE_OMIT_DEPRECATED
  96006. sqlite3_transfer_bindings,
  96007. #else
  96008. 0,
  96009. #endif
  96010. sqlite3_update_hook,
  96011. sqlite3_user_data,
  96012. sqlite3_value_blob,
  96013. sqlite3_value_bytes,
  96014. sqlite3_value_bytes16,
  96015. sqlite3_value_double,
  96016. sqlite3_value_int,
  96017. sqlite3_value_int64,
  96018. sqlite3_value_numeric_type,
  96019. sqlite3_value_text,
  96020. sqlite3_value_text16,
  96021. sqlite3_value_text16be,
  96022. sqlite3_value_text16le,
  96023. sqlite3_value_type,
  96024. sqlite3_vmprintf,
  96025. /*
  96026. ** The original API set ends here. All extensions can call any
  96027. ** of the APIs above provided that the pointer is not NULL. But
  96028. ** before calling APIs that follow, extension should check the
  96029. ** sqlite3_libversion_number() to make sure they are dealing with
  96030. ** a library that is new enough to support that API.
  96031. *************************************************************************
  96032. */
  96033. sqlite3_overload_function,
  96034. /*
  96035. ** Added after 3.3.13
  96036. */
  96037. sqlite3_prepare_v2,
  96038. sqlite3_prepare16_v2,
  96039. sqlite3_clear_bindings,
  96040. /*
  96041. ** Added for 3.4.1
  96042. */
  96043. sqlite3_create_module_v2,
  96044. /*
  96045. ** Added for 3.5.0
  96046. */
  96047. sqlite3_bind_zeroblob,
  96048. sqlite3_blob_bytes,
  96049. sqlite3_blob_close,
  96050. sqlite3_blob_open,
  96051. sqlite3_blob_read,
  96052. sqlite3_blob_write,
  96053. sqlite3_create_collation_v2,
  96054. sqlite3_file_control,
  96055. sqlite3_memory_highwater,
  96056. sqlite3_memory_used,
  96057. #ifdef SQLITE_MUTEX_OMIT
  96058. 0,
  96059. 0,
  96060. 0,
  96061. 0,
  96062. 0,
  96063. #else
  96064. sqlite3_mutex_alloc,
  96065. sqlite3_mutex_enter,
  96066. sqlite3_mutex_free,
  96067. sqlite3_mutex_leave,
  96068. sqlite3_mutex_try,
  96069. #endif
  96070. sqlite3_open_v2,
  96071. sqlite3_release_memory,
  96072. sqlite3_result_error_nomem,
  96073. sqlite3_result_error_toobig,
  96074. sqlite3_sleep,
  96075. sqlite3_soft_heap_limit,
  96076. sqlite3_vfs_find,
  96077. sqlite3_vfs_register,
  96078. sqlite3_vfs_unregister,
  96079. /*
  96080. ** Added for 3.5.8
  96081. */
  96082. sqlite3_threadsafe,
  96083. sqlite3_result_zeroblob,
  96084. sqlite3_result_error_code,
  96085. sqlite3_test_control,
  96086. sqlite3_randomness,
  96087. sqlite3_context_db_handle,
  96088. /*
  96089. ** Added for 3.6.0
  96090. */
  96091. sqlite3_extended_result_codes,
  96092. sqlite3_limit,
  96093. sqlite3_next_stmt,
  96094. sqlite3_sql,
  96095. sqlite3_status,
  96096. /*
  96097. ** Added for 3.7.4
  96098. */
  96099. sqlite3_backup_finish,
  96100. sqlite3_backup_init,
  96101. sqlite3_backup_pagecount,
  96102. sqlite3_backup_remaining,
  96103. sqlite3_backup_step,
  96104. #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
  96105. sqlite3_compileoption_get,
  96106. sqlite3_compileoption_used,
  96107. #else
  96108. 0,
  96109. 0,
  96110. #endif
  96111. sqlite3_create_function_v2,
  96112. sqlite3_db_config,
  96113. sqlite3_db_mutex,
  96114. sqlite3_db_status,
  96115. sqlite3_extended_errcode,
  96116. sqlite3_log,
  96117. sqlite3_soft_heap_limit64,
  96118. sqlite3_sourceid,
  96119. sqlite3_stmt_status,
  96120. sqlite3_strnicmp,
  96121. #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
  96122. sqlite3_unlock_notify,
  96123. #else
  96124. 0,
  96125. #endif
  96126. #ifndef SQLITE_OMIT_WAL
  96127. sqlite3_wal_autocheckpoint,
  96128. sqlite3_wal_checkpoint,
  96129. sqlite3_wal_hook,
  96130. #else
  96131. 0,
  96132. 0,
  96133. 0,
  96134. #endif
  96135. sqlite3_blob_reopen,
  96136. sqlite3_vtab_config,
  96137. sqlite3_vtab_on_conflict,
  96138. sqlite3_close_v2,
  96139. sqlite3_db_filename,
  96140. sqlite3_db_readonly,
  96141. sqlite3_db_release_memory,
  96142. sqlite3_errstr,
  96143. sqlite3_stmt_busy,
  96144. sqlite3_stmt_readonly,
  96145. sqlite3_stricmp,
  96146. sqlite3_uri_boolean,
  96147. sqlite3_uri_int64,
  96148. sqlite3_uri_parameter,
  96149. sqlite3_vsnprintf,
  96150. sqlite3_wal_checkpoint_v2,
  96151. /* Version 3.8.7 and later */
  96152. sqlite3_auto_extension,
  96153. sqlite3_bind_blob64,
  96154. sqlite3_bind_text64,
  96155. sqlite3_cancel_auto_extension,
  96156. sqlite3_load_extension,
  96157. sqlite3_malloc64,
  96158. sqlite3_msize,
  96159. sqlite3_realloc64,
  96160. sqlite3_reset_auto_extension,
  96161. sqlite3_result_blob64,
  96162. sqlite3_result_text64,
  96163. sqlite3_strglob
  96164. };
  96165. /*
  96166. ** Attempt to load an SQLite extension library contained in the file
  96167. ** zFile. The entry point is zProc. zProc may be 0 in which case a
  96168. ** default entry point name (sqlite3_extension_init) is used. Use
  96169. ** of the default name is recommended.
  96170. **
  96171. ** Return SQLITE_OK on success and SQLITE_ERROR if something goes wrong.
  96172. **
  96173. ** If an error occurs and pzErrMsg is not 0, then fill *pzErrMsg with
  96174. ** error message text. The calling function should free this memory
  96175. ** by calling sqlite3DbFree(db, ).
  96176. */
  96177. static int sqlite3LoadExtension(
  96178. sqlite3 *db, /* Load the extension into this database connection */
  96179. const char *zFile, /* Name of the shared library containing extension */
  96180. const char *zProc, /* Entry point. Use "sqlite3_extension_init" if 0 */
  96181. char **pzErrMsg /* Put error message here if not 0 */
  96182. ){
  96183. sqlite3_vfs *pVfs = db->pVfs;
  96184. void *handle;
  96185. int (*xInit)(sqlite3*,char**,const sqlite3_api_routines*);
  96186. char *zErrmsg = 0;
  96187. const char *zEntry;
  96188. char *zAltEntry = 0;
  96189. void **aHandle;
  96190. u64 nMsg = 300 + sqlite3Strlen30(zFile);
  96191. int ii;
  96192. /* Shared library endings to try if zFile cannot be loaded as written */
  96193. static const char *azEndings[] = {
  96194. #if SQLITE_OS_WIN
  96195. "dll"
  96196. #elif defined(__APPLE__)
  96197. "dylib"
  96198. #else
  96199. "so"
  96200. #endif
  96201. };
  96202. if( pzErrMsg ) *pzErrMsg = 0;
  96203. /* Ticket #1863. To avoid a creating security problems for older
  96204. ** applications that relink against newer versions of SQLite, the
  96205. ** ability to run load_extension is turned off by default. One
  96206. ** must call sqlite3_enable_load_extension() to turn on extension
  96207. ** loading. Otherwise you get the following error.
  96208. */
  96209. if( (db->flags & SQLITE_LoadExtension)==0 ){
  96210. if( pzErrMsg ){
  96211. *pzErrMsg = sqlite3_mprintf("not authorized");
  96212. }
  96213. return SQLITE_ERROR;
  96214. }
  96215. zEntry = zProc ? zProc : "sqlite3_extension_init";
  96216. handle = sqlite3OsDlOpen(pVfs, zFile);
  96217. #if SQLITE_OS_UNIX || SQLITE_OS_WIN
  96218. for(ii=0; ii<ArraySize(azEndings) && handle==0; ii++){
  96219. char *zAltFile = sqlite3_mprintf("%s.%s", zFile, azEndings[ii]);
  96220. if( zAltFile==0 ) return SQLITE_NOMEM;
  96221. handle = sqlite3OsDlOpen(pVfs, zAltFile);
  96222. sqlite3_free(zAltFile);
  96223. }
  96224. #endif
  96225. if( handle==0 ){
  96226. if( pzErrMsg ){
  96227. *pzErrMsg = zErrmsg = sqlite3_malloc64(nMsg);
  96228. if( zErrmsg ){
  96229. sqlite3_snprintf(nMsg, zErrmsg,
  96230. "unable to open shared library [%s]", zFile);
  96231. sqlite3OsDlError(pVfs, nMsg-1, zErrmsg);
  96232. }
  96233. }
  96234. return SQLITE_ERROR;
  96235. }
  96236. xInit = (int(*)(sqlite3*,char**,const sqlite3_api_routines*))
  96237. sqlite3OsDlSym(pVfs, handle, zEntry);
  96238. /* If no entry point was specified and the default legacy
  96239. ** entry point name "sqlite3_extension_init" was not found, then
  96240. ** construct an entry point name "sqlite3_X_init" where the X is
  96241. ** replaced by the lowercase value of every ASCII alphabetic
  96242. ** character in the filename after the last "/" upto the first ".",
  96243. ** and eliding the first three characters if they are "lib".
  96244. ** Examples:
  96245. **
  96246. ** /usr/local/lib/libExample5.4.3.so ==> sqlite3_example_init
  96247. ** C:/lib/mathfuncs.dll ==> sqlite3_mathfuncs_init
  96248. */
  96249. if( xInit==0 && zProc==0 ){
  96250. int iFile, iEntry, c;
  96251. int ncFile = sqlite3Strlen30(zFile);
  96252. zAltEntry = sqlite3_malloc64(ncFile+30);
  96253. if( zAltEntry==0 ){
  96254. sqlite3OsDlClose(pVfs, handle);
  96255. return SQLITE_NOMEM;
  96256. }
  96257. memcpy(zAltEntry, "sqlite3_", 8);
  96258. for(iFile=ncFile-1; iFile>=0 && zFile[iFile]!='/'; iFile--){}
  96259. iFile++;
  96260. if( sqlite3_strnicmp(zFile+iFile, "lib", 3)==0 ) iFile += 3;
  96261. for(iEntry=8; (c = zFile[iFile])!=0 && c!='.'; iFile++){
  96262. if( sqlite3Isalpha(c) ){
  96263. zAltEntry[iEntry++] = (char)sqlite3UpperToLower[(unsigned)c];
  96264. }
  96265. }
  96266. memcpy(zAltEntry+iEntry, "_init", 6);
  96267. zEntry = zAltEntry;
  96268. xInit = (int(*)(sqlite3*,char**,const sqlite3_api_routines*))
  96269. sqlite3OsDlSym(pVfs, handle, zEntry);
  96270. }
  96271. if( xInit==0 ){
  96272. if( pzErrMsg ){
  96273. nMsg += sqlite3Strlen30(zEntry);
  96274. *pzErrMsg = zErrmsg = sqlite3_malloc64(nMsg);
  96275. if( zErrmsg ){
  96276. sqlite3_snprintf(nMsg, zErrmsg,
  96277. "no entry point [%s] in shared library [%s]", zEntry, zFile);
  96278. sqlite3OsDlError(pVfs, nMsg-1, zErrmsg);
  96279. }
  96280. }
  96281. sqlite3OsDlClose(pVfs, handle);
  96282. sqlite3_free(zAltEntry);
  96283. return SQLITE_ERROR;
  96284. }
  96285. sqlite3_free(zAltEntry);
  96286. if( xInit(db, &zErrmsg, &sqlite3Apis) ){
  96287. if( pzErrMsg ){
  96288. *pzErrMsg = sqlite3_mprintf("error during initialization: %s", zErrmsg);
  96289. }
  96290. sqlite3_free(zErrmsg);
  96291. sqlite3OsDlClose(pVfs, handle);
  96292. return SQLITE_ERROR;
  96293. }
  96294. /* Append the new shared library handle to the db->aExtension array. */
  96295. aHandle = sqlite3DbMallocZero(db, sizeof(handle)*(db->nExtension+1));
  96296. if( aHandle==0 ){
  96297. return SQLITE_NOMEM;
  96298. }
  96299. if( db->nExtension>0 ){
  96300. memcpy(aHandle, db->aExtension, sizeof(handle)*db->nExtension);
  96301. }
  96302. sqlite3DbFree(db, db->aExtension);
  96303. db->aExtension = aHandle;
  96304. db->aExtension[db->nExtension++] = handle;
  96305. return SQLITE_OK;
  96306. }
  96307. SQLITE_API int SQLITE_STDCALL sqlite3_load_extension(
  96308. sqlite3 *db, /* Load the extension into this database connection */
  96309. const char *zFile, /* Name of the shared library containing extension */
  96310. const char *zProc, /* Entry point. Use "sqlite3_extension_init" if 0 */
  96311. char **pzErrMsg /* Put error message here if not 0 */
  96312. ){
  96313. int rc;
  96314. sqlite3_mutex_enter(db->mutex);
  96315. rc = sqlite3LoadExtension(db, zFile, zProc, pzErrMsg);
  96316. rc = sqlite3ApiExit(db, rc);
  96317. sqlite3_mutex_leave(db->mutex);
  96318. return rc;
  96319. }
  96320. /*
  96321. ** Call this routine when the database connection is closing in order
  96322. ** to clean up loaded extensions
  96323. */
  96324. SQLITE_PRIVATE void sqlite3CloseExtensions(sqlite3 *db){
  96325. int i;
  96326. assert( sqlite3_mutex_held(db->mutex) );
  96327. for(i=0; i<db->nExtension; i++){
  96328. sqlite3OsDlClose(db->pVfs, db->aExtension[i]);
  96329. }
  96330. sqlite3DbFree(db, db->aExtension);
  96331. }
  96332. /*
  96333. ** Enable or disable extension loading. Extension loading is disabled by
  96334. ** default so as not to open security holes in older applications.
  96335. */
  96336. SQLITE_API int SQLITE_STDCALL sqlite3_enable_load_extension(sqlite3 *db, int onoff){
  96337. sqlite3_mutex_enter(db->mutex);
  96338. if( onoff ){
  96339. db->flags |= SQLITE_LoadExtension;
  96340. }else{
  96341. db->flags &= ~SQLITE_LoadExtension;
  96342. }
  96343. sqlite3_mutex_leave(db->mutex);
  96344. return SQLITE_OK;
  96345. }
  96346. #endif /* SQLITE_OMIT_LOAD_EXTENSION */
  96347. /*
  96348. ** The auto-extension code added regardless of whether or not extension
  96349. ** loading is supported. We need a dummy sqlite3Apis pointer for that
  96350. ** code if regular extension loading is not available. This is that
  96351. ** dummy pointer.
  96352. */
  96353. #ifdef SQLITE_OMIT_LOAD_EXTENSION
  96354. static const sqlite3_api_routines sqlite3Apis = { 0 };
  96355. #endif
  96356. /*
  96357. ** The following object holds the list of automatically loaded
  96358. ** extensions.
  96359. **
  96360. ** This list is shared across threads. The SQLITE_MUTEX_STATIC_MASTER
  96361. ** mutex must be held while accessing this list.
  96362. */
  96363. typedef struct sqlite3AutoExtList sqlite3AutoExtList;
  96364. static SQLITE_WSD struct sqlite3AutoExtList {
  96365. u32 nExt; /* Number of entries in aExt[] */
  96366. void (**aExt)(void); /* Pointers to the extension init functions */
  96367. } sqlite3Autoext = { 0, 0 };
  96368. /* The "wsdAutoext" macro will resolve to the autoextension
  96369. ** state vector. If writable static data is unsupported on the target,
  96370. ** we have to locate the state vector at run-time. In the more common
  96371. ** case where writable static data is supported, wsdStat can refer directly
  96372. ** to the "sqlite3Autoext" state vector declared above.
  96373. */
  96374. #ifdef SQLITE_OMIT_WSD
  96375. # define wsdAutoextInit \
  96376. sqlite3AutoExtList *x = &GLOBAL(sqlite3AutoExtList,sqlite3Autoext)
  96377. # define wsdAutoext x[0]
  96378. #else
  96379. # define wsdAutoextInit
  96380. # define wsdAutoext sqlite3Autoext
  96381. #endif
  96382. /*
  96383. ** Register a statically linked extension that is automatically
  96384. ** loaded by every new database connection.
  96385. */
  96386. SQLITE_API int SQLITE_STDCALL sqlite3_auto_extension(void (*xInit)(void)){
  96387. int rc = SQLITE_OK;
  96388. #ifndef SQLITE_OMIT_AUTOINIT
  96389. rc = sqlite3_initialize();
  96390. if( rc ){
  96391. return rc;
  96392. }else
  96393. #endif
  96394. {
  96395. u32 i;
  96396. #if SQLITE_THREADSAFE
  96397. sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
  96398. #endif
  96399. wsdAutoextInit;
  96400. sqlite3_mutex_enter(mutex);
  96401. for(i=0; i<wsdAutoext.nExt; i++){
  96402. if( wsdAutoext.aExt[i]==xInit ) break;
  96403. }
  96404. if( i==wsdAutoext.nExt ){
  96405. u64 nByte = (wsdAutoext.nExt+1)*sizeof(wsdAutoext.aExt[0]);
  96406. void (**aNew)(void);
  96407. aNew = sqlite3_realloc64(wsdAutoext.aExt, nByte);
  96408. if( aNew==0 ){
  96409. rc = SQLITE_NOMEM;
  96410. }else{
  96411. wsdAutoext.aExt = aNew;
  96412. wsdAutoext.aExt[wsdAutoext.nExt] = xInit;
  96413. wsdAutoext.nExt++;
  96414. }
  96415. }
  96416. sqlite3_mutex_leave(mutex);
  96417. assert( (rc&0xff)==rc );
  96418. return rc;
  96419. }
  96420. }
  96421. /*
  96422. ** Cancel a prior call to sqlite3_auto_extension. Remove xInit from the
  96423. ** set of routines that is invoked for each new database connection, if it
  96424. ** is currently on the list. If xInit is not on the list, then this
  96425. ** routine is a no-op.
  96426. **
  96427. ** Return 1 if xInit was found on the list and removed. Return 0 if xInit
  96428. ** was not on the list.
  96429. */
  96430. SQLITE_API int SQLITE_STDCALL sqlite3_cancel_auto_extension(void (*xInit)(void)){
  96431. #if SQLITE_THREADSAFE
  96432. sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
  96433. #endif
  96434. int i;
  96435. int n = 0;
  96436. wsdAutoextInit;
  96437. sqlite3_mutex_enter(mutex);
  96438. for(i=(int)wsdAutoext.nExt-1; i>=0; i--){
  96439. if( wsdAutoext.aExt[i]==xInit ){
  96440. wsdAutoext.nExt--;
  96441. wsdAutoext.aExt[i] = wsdAutoext.aExt[wsdAutoext.nExt];
  96442. n++;
  96443. break;
  96444. }
  96445. }
  96446. sqlite3_mutex_leave(mutex);
  96447. return n;
  96448. }
  96449. /*
  96450. ** Reset the automatic extension loading mechanism.
  96451. */
  96452. SQLITE_API void SQLITE_STDCALL sqlite3_reset_auto_extension(void){
  96453. #ifndef SQLITE_OMIT_AUTOINIT
  96454. if( sqlite3_initialize()==SQLITE_OK )
  96455. #endif
  96456. {
  96457. #if SQLITE_THREADSAFE
  96458. sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
  96459. #endif
  96460. wsdAutoextInit;
  96461. sqlite3_mutex_enter(mutex);
  96462. sqlite3_free(wsdAutoext.aExt);
  96463. wsdAutoext.aExt = 0;
  96464. wsdAutoext.nExt = 0;
  96465. sqlite3_mutex_leave(mutex);
  96466. }
  96467. }
  96468. /*
  96469. ** Load all automatic extensions.
  96470. **
  96471. ** If anything goes wrong, set an error in the database connection.
  96472. */
  96473. SQLITE_PRIVATE void sqlite3AutoLoadExtensions(sqlite3 *db){
  96474. u32 i;
  96475. int go = 1;
  96476. int rc;
  96477. int (*xInit)(sqlite3*,char**,const sqlite3_api_routines*);
  96478. wsdAutoextInit;
  96479. if( wsdAutoext.nExt==0 ){
  96480. /* Common case: early out without every having to acquire a mutex */
  96481. return;
  96482. }
  96483. for(i=0; go; i++){
  96484. char *zErrmsg;
  96485. #if SQLITE_THREADSAFE
  96486. sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
  96487. #endif
  96488. sqlite3_mutex_enter(mutex);
  96489. if( i>=wsdAutoext.nExt ){
  96490. xInit = 0;
  96491. go = 0;
  96492. }else{
  96493. xInit = (int(*)(sqlite3*,char**,const sqlite3_api_routines*))
  96494. wsdAutoext.aExt[i];
  96495. }
  96496. sqlite3_mutex_leave(mutex);
  96497. zErrmsg = 0;
  96498. if( xInit && (rc = xInit(db, &zErrmsg, &sqlite3Apis))!=0 ){
  96499. sqlite3ErrorWithMsg(db, rc,
  96500. "automatic extension loading failed: %s", zErrmsg);
  96501. go = 0;
  96502. }
  96503. sqlite3_free(zErrmsg);
  96504. }
  96505. }
  96506. /************** End of loadext.c *********************************************/
  96507. /************** Begin file pragma.c ******************************************/
  96508. /*
  96509. ** 2003 April 6
  96510. **
  96511. ** The author disclaims copyright to this source code. In place of
  96512. ** a legal notice, here is a blessing:
  96513. **
  96514. ** May you do good and not evil.
  96515. ** May you find forgiveness for yourself and forgive others.
  96516. ** May you share freely, never taking more than you give.
  96517. **
  96518. *************************************************************************
  96519. ** This file contains code used to implement the PRAGMA command.
  96520. */
  96521. #if !defined(SQLITE_ENABLE_LOCKING_STYLE)
  96522. # if defined(__APPLE__)
  96523. # define SQLITE_ENABLE_LOCKING_STYLE 1
  96524. # else
  96525. # define SQLITE_ENABLE_LOCKING_STYLE 0
  96526. # endif
  96527. #endif
  96528. /***************************************************************************
  96529. ** The "pragma.h" include file is an automatically generated file that
  96530. ** that includes the PragType_XXXX macro definitions and the aPragmaName[]
  96531. ** object. This ensures that the aPragmaName[] table is arranged in
  96532. ** lexicographical order to facility a binary search of the pragma name.
  96533. ** Do not edit pragma.h directly. Edit and rerun the script in at
  96534. ** ../tool/mkpragmatab.tcl. */
  96535. /************** Include pragma.h in the middle of pragma.c *******************/
  96536. /************** Begin file pragma.h ******************************************/
  96537. /* DO NOT EDIT!
  96538. ** This file is automatically generated by the script at
  96539. ** ../tool/mkpragmatab.tcl. To update the set of pragmas, edit
  96540. ** that script and rerun it.
  96541. */
  96542. #define PragTyp_HEADER_VALUE 0
  96543. #define PragTyp_AUTO_VACUUM 1
  96544. #define PragTyp_FLAG 2
  96545. #define PragTyp_BUSY_TIMEOUT 3
  96546. #define PragTyp_CACHE_SIZE 4
  96547. #define PragTyp_CASE_SENSITIVE_LIKE 5
  96548. #define PragTyp_COLLATION_LIST 6
  96549. #define PragTyp_COMPILE_OPTIONS 7
  96550. #define PragTyp_DATA_STORE_DIRECTORY 8
  96551. #define PragTyp_DATABASE_LIST 9
  96552. #define PragTyp_DEFAULT_CACHE_SIZE 10
  96553. #define PragTyp_ENCODING 11
  96554. #define PragTyp_FOREIGN_KEY_CHECK 12
  96555. #define PragTyp_FOREIGN_KEY_LIST 13
  96556. #define PragTyp_INCREMENTAL_VACUUM 14
  96557. #define PragTyp_INDEX_INFO 15
  96558. #define PragTyp_INDEX_LIST 16
  96559. #define PragTyp_INTEGRITY_CHECK 17
  96560. #define PragTyp_JOURNAL_MODE 18
  96561. #define PragTyp_JOURNAL_SIZE_LIMIT 19
  96562. #define PragTyp_LOCK_PROXY_FILE 20
  96563. #define PragTyp_LOCKING_MODE 21
  96564. #define PragTyp_PAGE_COUNT 22
  96565. #define PragTyp_MMAP_SIZE 23
  96566. #define PragTyp_PAGE_SIZE 24
  96567. #define PragTyp_SECURE_DELETE 25
  96568. #define PragTyp_SHRINK_MEMORY 26
  96569. #define PragTyp_SOFT_HEAP_LIMIT 27
  96570. #define PragTyp_STATS 28
  96571. #define PragTyp_SYNCHRONOUS 29
  96572. #define PragTyp_TABLE_INFO 30
  96573. #define PragTyp_TEMP_STORE 31
  96574. #define PragTyp_TEMP_STORE_DIRECTORY 32
  96575. #define PragTyp_THREADS 33
  96576. #define PragTyp_WAL_AUTOCHECKPOINT 34
  96577. #define PragTyp_WAL_CHECKPOINT 35
  96578. #define PragTyp_ACTIVATE_EXTENSIONS 36
  96579. #define PragTyp_HEXKEY 37
  96580. #define PragTyp_KEY 38
  96581. #define PragTyp_REKEY 39
  96582. #define PragTyp_LOCK_STATUS 40
  96583. #define PragTyp_PARSER_TRACE 41
  96584. #define PragFlag_NeedSchema 0x01
  96585. #define PragFlag_ReadOnly 0x02
  96586. static const struct sPragmaNames {
  96587. const char *const zName; /* Name of pragma */
  96588. u8 ePragTyp; /* PragTyp_XXX value */
  96589. u8 mPragFlag; /* Zero or more PragFlag_XXX values */
  96590. u32 iArg; /* Extra argument */
  96591. } aPragmaNames[] = {
  96592. #if defined(SQLITE_HAS_CODEC) || defined(SQLITE_ENABLE_CEROD)
  96593. { /* zName: */ "activate_extensions",
  96594. /* ePragTyp: */ PragTyp_ACTIVATE_EXTENSIONS,
  96595. /* ePragFlag: */ 0,
  96596. /* iArg: */ 0 },
  96597. #endif
  96598. #if !defined(SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS)
  96599. { /* zName: */ "application_id",
  96600. /* ePragTyp: */ PragTyp_HEADER_VALUE,
  96601. /* ePragFlag: */ 0,
  96602. /* iArg: */ BTREE_APPLICATION_ID },
  96603. #endif
  96604. #if !defined(SQLITE_OMIT_AUTOVACUUM)
  96605. { /* zName: */ "auto_vacuum",
  96606. /* ePragTyp: */ PragTyp_AUTO_VACUUM,
  96607. /* ePragFlag: */ PragFlag_NeedSchema,
  96608. /* iArg: */ 0 },
  96609. #endif
  96610. #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
  96611. #if !defined(SQLITE_OMIT_AUTOMATIC_INDEX)
  96612. { /* zName: */ "automatic_index",
  96613. /* ePragTyp: */ PragTyp_FLAG,
  96614. /* ePragFlag: */ 0,
  96615. /* iArg: */ SQLITE_AutoIndex },
  96616. #endif
  96617. #endif
  96618. { /* zName: */ "busy_timeout",
  96619. /* ePragTyp: */ PragTyp_BUSY_TIMEOUT,
  96620. /* ePragFlag: */ 0,
  96621. /* iArg: */ 0 },
  96622. #if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
  96623. { /* zName: */ "cache_size",
  96624. /* ePragTyp: */ PragTyp_CACHE_SIZE,
  96625. /* ePragFlag: */ PragFlag_NeedSchema,
  96626. /* iArg: */ 0 },
  96627. #endif
  96628. #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
  96629. { /* zName: */ "cache_spill",
  96630. /* ePragTyp: */ PragTyp_FLAG,
  96631. /* ePragFlag: */ 0,
  96632. /* iArg: */ SQLITE_CacheSpill },
  96633. #endif
  96634. { /* zName: */ "case_sensitive_like",
  96635. /* ePragTyp: */ PragTyp_CASE_SENSITIVE_LIKE,
  96636. /* ePragFlag: */ 0,
  96637. /* iArg: */ 0 },
  96638. #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
  96639. { /* zName: */ "checkpoint_fullfsync",
  96640. /* ePragTyp: */ PragTyp_FLAG,
  96641. /* ePragFlag: */ 0,
  96642. /* iArg: */ SQLITE_CkptFullFSync },
  96643. #endif
  96644. #if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS)
  96645. { /* zName: */ "collation_list",
  96646. /* ePragTyp: */ PragTyp_COLLATION_LIST,
  96647. /* ePragFlag: */ 0,
  96648. /* iArg: */ 0 },
  96649. #endif
  96650. #if !defined(SQLITE_OMIT_COMPILEOPTION_DIAGS)
  96651. { /* zName: */ "compile_options",
  96652. /* ePragTyp: */ PragTyp_COMPILE_OPTIONS,
  96653. /* ePragFlag: */ 0,
  96654. /* iArg: */ 0 },
  96655. #endif
  96656. #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
  96657. { /* zName: */ "count_changes",
  96658. /* ePragTyp: */ PragTyp_FLAG,
  96659. /* ePragFlag: */ 0,
  96660. /* iArg: */ SQLITE_CountRows },
  96661. #endif
  96662. #if !defined(SQLITE_OMIT_PAGER_PRAGMAS) && SQLITE_OS_WIN
  96663. { /* zName: */ "data_store_directory",
  96664. /* ePragTyp: */ PragTyp_DATA_STORE_DIRECTORY,
  96665. /* ePragFlag: */ 0,
  96666. /* iArg: */ 0 },
  96667. #endif
  96668. #if !defined(SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS)
  96669. { /* zName: */ "data_version",
  96670. /* ePragTyp: */ PragTyp_HEADER_VALUE,
  96671. /* ePragFlag: */ PragFlag_ReadOnly,
  96672. /* iArg: */ BTREE_DATA_VERSION },
  96673. #endif
  96674. #if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS)
  96675. { /* zName: */ "database_list",
  96676. /* ePragTyp: */ PragTyp_DATABASE_LIST,
  96677. /* ePragFlag: */ PragFlag_NeedSchema,
  96678. /* iArg: */ 0 },
  96679. #endif
  96680. #if !defined(SQLITE_OMIT_PAGER_PRAGMAS) && !defined(SQLITE_OMIT_DEPRECATED)
  96681. { /* zName: */ "default_cache_size",
  96682. /* ePragTyp: */ PragTyp_DEFAULT_CACHE_SIZE,
  96683. /* ePragFlag: */ PragFlag_NeedSchema,
  96684. /* iArg: */ 0 },
  96685. #endif
  96686. #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
  96687. #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
  96688. { /* zName: */ "defer_foreign_keys",
  96689. /* ePragTyp: */ PragTyp_FLAG,
  96690. /* ePragFlag: */ 0,
  96691. /* iArg: */ SQLITE_DeferFKs },
  96692. #endif
  96693. #endif
  96694. #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
  96695. { /* zName: */ "empty_result_callbacks",
  96696. /* ePragTyp: */ PragTyp_FLAG,
  96697. /* ePragFlag: */ 0,
  96698. /* iArg: */ SQLITE_NullCallback },
  96699. #endif
  96700. #if !defined(SQLITE_OMIT_UTF16)
  96701. { /* zName: */ "encoding",
  96702. /* ePragTyp: */ PragTyp_ENCODING,
  96703. /* ePragFlag: */ 0,
  96704. /* iArg: */ 0 },
  96705. #endif
  96706. #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
  96707. { /* zName: */ "foreign_key_check",
  96708. /* ePragTyp: */ PragTyp_FOREIGN_KEY_CHECK,
  96709. /* ePragFlag: */ PragFlag_NeedSchema,
  96710. /* iArg: */ 0 },
  96711. #endif
  96712. #if !defined(SQLITE_OMIT_FOREIGN_KEY)
  96713. { /* zName: */ "foreign_key_list",
  96714. /* ePragTyp: */ PragTyp_FOREIGN_KEY_LIST,
  96715. /* ePragFlag: */ PragFlag_NeedSchema,
  96716. /* iArg: */ 0 },
  96717. #endif
  96718. #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
  96719. #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
  96720. { /* zName: */ "foreign_keys",
  96721. /* ePragTyp: */ PragTyp_FLAG,
  96722. /* ePragFlag: */ 0,
  96723. /* iArg: */ SQLITE_ForeignKeys },
  96724. #endif
  96725. #endif
  96726. #if !defined(SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS)
  96727. { /* zName: */ "freelist_count",
  96728. /* ePragTyp: */ PragTyp_HEADER_VALUE,
  96729. /* ePragFlag: */ PragFlag_ReadOnly,
  96730. /* iArg: */ BTREE_FREE_PAGE_COUNT },
  96731. #endif
  96732. #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
  96733. { /* zName: */ "full_column_names",
  96734. /* ePragTyp: */ PragTyp_FLAG,
  96735. /* ePragFlag: */ 0,
  96736. /* iArg: */ SQLITE_FullColNames },
  96737. { /* zName: */ "fullfsync",
  96738. /* ePragTyp: */ PragTyp_FLAG,
  96739. /* ePragFlag: */ 0,
  96740. /* iArg: */ SQLITE_FullFSync },
  96741. #endif
  96742. #if defined(SQLITE_HAS_CODEC)
  96743. { /* zName: */ "hexkey",
  96744. /* ePragTyp: */ PragTyp_HEXKEY,
  96745. /* ePragFlag: */ 0,
  96746. /* iArg: */ 0 },
  96747. { /* zName: */ "hexrekey",
  96748. /* ePragTyp: */ PragTyp_HEXKEY,
  96749. /* ePragFlag: */ 0,
  96750. /* iArg: */ 0 },
  96751. #endif
  96752. #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
  96753. #if !defined(SQLITE_OMIT_CHECK)
  96754. { /* zName: */ "ignore_check_constraints",
  96755. /* ePragTyp: */ PragTyp_FLAG,
  96756. /* ePragFlag: */ 0,
  96757. /* iArg: */ SQLITE_IgnoreChecks },
  96758. #endif
  96759. #endif
  96760. #if !defined(SQLITE_OMIT_AUTOVACUUM)
  96761. { /* zName: */ "incremental_vacuum",
  96762. /* ePragTyp: */ PragTyp_INCREMENTAL_VACUUM,
  96763. /* ePragFlag: */ PragFlag_NeedSchema,
  96764. /* iArg: */ 0 },
  96765. #endif
  96766. #if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS)
  96767. { /* zName: */ "index_info",
  96768. /* ePragTyp: */ PragTyp_INDEX_INFO,
  96769. /* ePragFlag: */ PragFlag_NeedSchema,
  96770. /* iArg: */ 0 },
  96771. { /* zName: */ "index_list",
  96772. /* ePragTyp: */ PragTyp_INDEX_LIST,
  96773. /* ePragFlag: */ PragFlag_NeedSchema,
  96774. /* iArg: */ 0 },
  96775. { /* zName: */ "index_xinfo",
  96776. /* ePragTyp: */ PragTyp_INDEX_INFO,
  96777. /* ePragFlag: */ PragFlag_NeedSchema,
  96778. /* iArg: */ 1 },
  96779. #endif
  96780. #if !defined(SQLITE_OMIT_INTEGRITY_CHECK)
  96781. { /* zName: */ "integrity_check",
  96782. /* ePragTyp: */ PragTyp_INTEGRITY_CHECK,
  96783. /* ePragFlag: */ PragFlag_NeedSchema,
  96784. /* iArg: */ 0 },
  96785. #endif
  96786. #if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
  96787. { /* zName: */ "journal_mode",
  96788. /* ePragTyp: */ PragTyp_JOURNAL_MODE,
  96789. /* ePragFlag: */ PragFlag_NeedSchema,
  96790. /* iArg: */ 0 },
  96791. { /* zName: */ "journal_size_limit",
  96792. /* ePragTyp: */ PragTyp_JOURNAL_SIZE_LIMIT,
  96793. /* ePragFlag: */ 0,
  96794. /* iArg: */ 0 },
  96795. #endif
  96796. #if defined(SQLITE_HAS_CODEC)
  96797. { /* zName: */ "key",
  96798. /* ePragTyp: */ PragTyp_KEY,
  96799. /* ePragFlag: */ 0,
  96800. /* iArg: */ 0 },
  96801. #endif
  96802. #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
  96803. { /* zName: */ "legacy_file_format",
  96804. /* ePragTyp: */ PragTyp_FLAG,
  96805. /* ePragFlag: */ 0,
  96806. /* iArg: */ SQLITE_LegacyFileFmt },
  96807. #endif
  96808. #if !defined(SQLITE_OMIT_PAGER_PRAGMAS) && SQLITE_ENABLE_LOCKING_STYLE
  96809. { /* zName: */ "lock_proxy_file",
  96810. /* ePragTyp: */ PragTyp_LOCK_PROXY_FILE,
  96811. /* ePragFlag: */ 0,
  96812. /* iArg: */ 0 },
  96813. #endif
  96814. #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
  96815. { /* zName: */ "lock_status",
  96816. /* ePragTyp: */ PragTyp_LOCK_STATUS,
  96817. /* ePragFlag: */ 0,
  96818. /* iArg: */ 0 },
  96819. #endif
  96820. #if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
  96821. { /* zName: */ "locking_mode",
  96822. /* ePragTyp: */ PragTyp_LOCKING_MODE,
  96823. /* ePragFlag: */ 0,
  96824. /* iArg: */ 0 },
  96825. { /* zName: */ "max_page_count",
  96826. /* ePragTyp: */ PragTyp_PAGE_COUNT,
  96827. /* ePragFlag: */ PragFlag_NeedSchema,
  96828. /* iArg: */ 0 },
  96829. { /* zName: */ "mmap_size",
  96830. /* ePragTyp: */ PragTyp_MMAP_SIZE,
  96831. /* ePragFlag: */ 0,
  96832. /* iArg: */ 0 },
  96833. { /* zName: */ "page_count",
  96834. /* ePragTyp: */ PragTyp_PAGE_COUNT,
  96835. /* ePragFlag: */ PragFlag_NeedSchema,
  96836. /* iArg: */ 0 },
  96837. { /* zName: */ "page_size",
  96838. /* ePragTyp: */ PragTyp_PAGE_SIZE,
  96839. /* ePragFlag: */ 0,
  96840. /* iArg: */ 0 },
  96841. #endif
  96842. #if defined(SQLITE_DEBUG)
  96843. { /* zName: */ "parser_trace",
  96844. /* ePragTyp: */ PragTyp_PARSER_TRACE,
  96845. /* ePragFlag: */ 0,
  96846. /* iArg: */ 0 },
  96847. #endif
  96848. #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
  96849. { /* zName: */ "query_only",
  96850. /* ePragTyp: */ PragTyp_FLAG,
  96851. /* ePragFlag: */ 0,
  96852. /* iArg: */ SQLITE_QueryOnly },
  96853. #endif
  96854. #if !defined(SQLITE_OMIT_INTEGRITY_CHECK)
  96855. { /* zName: */ "quick_check",
  96856. /* ePragTyp: */ PragTyp_INTEGRITY_CHECK,
  96857. /* ePragFlag: */ PragFlag_NeedSchema,
  96858. /* iArg: */ 0 },
  96859. #endif
  96860. #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
  96861. { /* zName: */ "read_uncommitted",
  96862. /* ePragTyp: */ PragTyp_FLAG,
  96863. /* ePragFlag: */ 0,
  96864. /* iArg: */ SQLITE_ReadUncommitted },
  96865. { /* zName: */ "recursive_triggers",
  96866. /* ePragTyp: */ PragTyp_FLAG,
  96867. /* ePragFlag: */ 0,
  96868. /* iArg: */ SQLITE_RecTriggers },
  96869. #endif
  96870. #if defined(SQLITE_HAS_CODEC)
  96871. { /* zName: */ "rekey",
  96872. /* ePragTyp: */ PragTyp_REKEY,
  96873. /* ePragFlag: */ 0,
  96874. /* iArg: */ 0 },
  96875. #endif
  96876. #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
  96877. { /* zName: */ "reverse_unordered_selects",
  96878. /* ePragTyp: */ PragTyp_FLAG,
  96879. /* ePragFlag: */ 0,
  96880. /* iArg: */ SQLITE_ReverseOrder },
  96881. #endif
  96882. #if !defined(SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS)
  96883. { /* zName: */ "schema_version",
  96884. /* ePragTyp: */ PragTyp_HEADER_VALUE,
  96885. /* ePragFlag: */ 0,
  96886. /* iArg: */ BTREE_SCHEMA_VERSION },
  96887. #endif
  96888. #if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
  96889. { /* zName: */ "secure_delete",
  96890. /* ePragTyp: */ PragTyp_SECURE_DELETE,
  96891. /* ePragFlag: */ 0,
  96892. /* iArg: */ 0 },
  96893. #endif
  96894. #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
  96895. { /* zName: */ "short_column_names",
  96896. /* ePragTyp: */ PragTyp_FLAG,
  96897. /* ePragFlag: */ 0,
  96898. /* iArg: */ SQLITE_ShortColNames },
  96899. #endif
  96900. { /* zName: */ "shrink_memory",
  96901. /* ePragTyp: */ PragTyp_SHRINK_MEMORY,
  96902. /* ePragFlag: */ 0,
  96903. /* iArg: */ 0 },
  96904. { /* zName: */ "soft_heap_limit",
  96905. /* ePragTyp: */ PragTyp_SOFT_HEAP_LIMIT,
  96906. /* ePragFlag: */ 0,
  96907. /* iArg: */ 0 },
  96908. #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
  96909. #if defined(SQLITE_DEBUG)
  96910. { /* zName: */ "sql_trace",
  96911. /* ePragTyp: */ PragTyp_FLAG,
  96912. /* ePragFlag: */ 0,
  96913. /* iArg: */ SQLITE_SqlTrace },
  96914. #endif
  96915. #endif
  96916. #if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS)
  96917. { /* zName: */ "stats",
  96918. /* ePragTyp: */ PragTyp_STATS,
  96919. /* ePragFlag: */ PragFlag_NeedSchema,
  96920. /* iArg: */ 0 },
  96921. #endif
  96922. #if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
  96923. { /* zName: */ "synchronous",
  96924. /* ePragTyp: */ PragTyp_SYNCHRONOUS,
  96925. /* ePragFlag: */ PragFlag_NeedSchema,
  96926. /* iArg: */ 0 },
  96927. #endif
  96928. #if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS)
  96929. { /* zName: */ "table_info",
  96930. /* ePragTyp: */ PragTyp_TABLE_INFO,
  96931. /* ePragFlag: */ PragFlag_NeedSchema,
  96932. /* iArg: */ 0 },
  96933. #endif
  96934. #if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
  96935. { /* zName: */ "temp_store",
  96936. /* ePragTyp: */ PragTyp_TEMP_STORE,
  96937. /* ePragFlag: */ 0,
  96938. /* iArg: */ 0 },
  96939. { /* zName: */ "temp_store_directory",
  96940. /* ePragTyp: */ PragTyp_TEMP_STORE_DIRECTORY,
  96941. /* ePragFlag: */ 0,
  96942. /* iArg: */ 0 },
  96943. #endif
  96944. { /* zName: */ "threads",
  96945. /* ePragTyp: */ PragTyp_THREADS,
  96946. /* ePragFlag: */ 0,
  96947. /* iArg: */ 0 },
  96948. #if !defined(SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS)
  96949. { /* zName: */ "user_version",
  96950. /* ePragTyp: */ PragTyp_HEADER_VALUE,
  96951. /* ePragFlag: */ 0,
  96952. /* iArg: */ BTREE_USER_VERSION },
  96953. #endif
  96954. #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
  96955. #if defined(SQLITE_DEBUG)
  96956. { /* zName: */ "vdbe_addoptrace",
  96957. /* ePragTyp: */ PragTyp_FLAG,
  96958. /* ePragFlag: */ 0,
  96959. /* iArg: */ SQLITE_VdbeAddopTrace },
  96960. { /* zName: */ "vdbe_debug",
  96961. /* ePragTyp: */ PragTyp_FLAG,
  96962. /* ePragFlag: */ 0,
  96963. /* iArg: */ SQLITE_SqlTrace|SQLITE_VdbeListing|SQLITE_VdbeTrace },
  96964. { /* zName: */ "vdbe_eqp",
  96965. /* ePragTyp: */ PragTyp_FLAG,
  96966. /* ePragFlag: */ 0,
  96967. /* iArg: */ SQLITE_VdbeEQP },
  96968. { /* zName: */ "vdbe_listing",
  96969. /* ePragTyp: */ PragTyp_FLAG,
  96970. /* ePragFlag: */ 0,
  96971. /* iArg: */ SQLITE_VdbeListing },
  96972. { /* zName: */ "vdbe_trace",
  96973. /* ePragTyp: */ PragTyp_FLAG,
  96974. /* ePragFlag: */ 0,
  96975. /* iArg: */ SQLITE_VdbeTrace },
  96976. #endif
  96977. #endif
  96978. #if !defined(SQLITE_OMIT_WAL)
  96979. { /* zName: */ "wal_autocheckpoint",
  96980. /* ePragTyp: */ PragTyp_WAL_AUTOCHECKPOINT,
  96981. /* ePragFlag: */ 0,
  96982. /* iArg: */ 0 },
  96983. { /* zName: */ "wal_checkpoint",
  96984. /* ePragTyp: */ PragTyp_WAL_CHECKPOINT,
  96985. /* ePragFlag: */ PragFlag_NeedSchema,
  96986. /* iArg: */ 0 },
  96987. #endif
  96988. #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
  96989. { /* zName: */ "writable_schema",
  96990. /* ePragTyp: */ PragTyp_FLAG,
  96991. /* ePragFlag: */ 0,
  96992. /* iArg: */ SQLITE_WriteSchema|SQLITE_RecoveryMode },
  96993. #endif
  96994. };
  96995. /* Number of pragmas: 59 on by default, 72 total. */
  96996. /************** End of pragma.h **********************************************/
  96997. /************** Continuing where we left off in pragma.c *********************/
  96998. /*
  96999. ** Interpret the given string as a safety level. Return 0 for OFF,
  97000. ** 1 for ON or NORMAL and 2 for FULL. Return 1 for an empty or
  97001. ** unrecognized string argument. The FULL option is disallowed
  97002. ** if the omitFull parameter it 1.
  97003. **
  97004. ** Note that the values returned are one less that the values that
  97005. ** should be passed into sqlite3BtreeSetSafetyLevel(). The is done
  97006. ** to support legacy SQL code. The safety level used to be boolean
  97007. ** and older scripts may have used numbers 0 for OFF and 1 for ON.
  97008. */
  97009. static u8 getSafetyLevel(const char *z, int omitFull, u8 dflt){
  97010. /* 123456789 123456789 */
  97011. static const char zText[] = "onoffalseyestruefull";
  97012. static const u8 iOffset[] = {0, 1, 2, 4, 9, 12, 16};
  97013. static const u8 iLength[] = {2, 2, 3, 5, 3, 4, 4};
  97014. static const u8 iValue[] = {1, 0, 0, 0, 1, 1, 2};
  97015. int i, n;
  97016. if( sqlite3Isdigit(*z) ){
  97017. return (u8)sqlite3Atoi(z);
  97018. }
  97019. n = sqlite3Strlen30(z);
  97020. for(i=0; i<ArraySize(iLength)-omitFull; i++){
  97021. if( iLength[i]==n && sqlite3StrNICmp(&zText[iOffset[i]],z,n)==0 ){
  97022. return iValue[i];
  97023. }
  97024. }
  97025. return dflt;
  97026. }
  97027. /*
  97028. ** Interpret the given string as a boolean value.
  97029. */
  97030. SQLITE_PRIVATE u8 sqlite3GetBoolean(const char *z, u8 dflt){
  97031. return getSafetyLevel(z,1,dflt)!=0;
  97032. }
  97033. /* The sqlite3GetBoolean() function is used by other modules but the
  97034. ** remainder of this file is specific to PRAGMA processing. So omit
  97035. ** the rest of the file if PRAGMAs are omitted from the build.
  97036. */
  97037. #if !defined(SQLITE_OMIT_PRAGMA)
  97038. /*
  97039. ** Interpret the given string as a locking mode value.
  97040. */
  97041. static int getLockingMode(const char *z){
  97042. if( z ){
  97043. if( 0==sqlite3StrICmp(z, "exclusive") ) return PAGER_LOCKINGMODE_EXCLUSIVE;
  97044. if( 0==sqlite3StrICmp(z, "normal") ) return PAGER_LOCKINGMODE_NORMAL;
  97045. }
  97046. return PAGER_LOCKINGMODE_QUERY;
  97047. }
  97048. #ifndef SQLITE_OMIT_AUTOVACUUM
  97049. /*
  97050. ** Interpret the given string as an auto-vacuum mode value.
  97051. **
  97052. ** The following strings, "none", "full" and "incremental" are
  97053. ** acceptable, as are their numeric equivalents: 0, 1 and 2 respectively.
  97054. */
  97055. static int getAutoVacuum(const char *z){
  97056. int i;
  97057. if( 0==sqlite3StrICmp(z, "none") ) return BTREE_AUTOVACUUM_NONE;
  97058. if( 0==sqlite3StrICmp(z, "full") ) return BTREE_AUTOVACUUM_FULL;
  97059. if( 0==sqlite3StrICmp(z, "incremental") ) return BTREE_AUTOVACUUM_INCR;
  97060. i = sqlite3Atoi(z);
  97061. return (u8)((i>=0&&i<=2)?i:0);
  97062. }
  97063. #endif /* ifndef SQLITE_OMIT_AUTOVACUUM */
  97064. #ifndef SQLITE_OMIT_PAGER_PRAGMAS
  97065. /*
  97066. ** Interpret the given string as a temp db location. Return 1 for file
  97067. ** backed temporary databases, 2 for the Red-Black tree in memory database
  97068. ** and 0 to use the compile-time default.
  97069. */
  97070. static int getTempStore(const char *z){
  97071. if( z[0]>='0' && z[0]<='2' ){
  97072. return z[0] - '0';
  97073. }else if( sqlite3StrICmp(z, "file")==0 ){
  97074. return 1;
  97075. }else if( sqlite3StrICmp(z, "memory")==0 ){
  97076. return 2;
  97077. }else{
  97078. return 0;
  97079. }
  97080. }
  97081. #endif /* SQLITE_PAGER_PRAGMAS */
  97082. #ifndef SQLITE_OMIT_PAGER_PRAGMAS
  97083. /*
  97084. ** Invalidate temp storage, either when the temp storage is changed
  97085. ** from default, or when 'file' and the temp_store_directory has changed
  97086. */
  97087. static int invalidateTempStorage(Parse *pParse){
  97088. sqlite3 *db = pParse->db;
  97089. if( db->aDb[1].pBt!=0 ){
  97090. if( !db->autoCommit || sqlite3BtreeIsInReadTrans(db->aDb[1].pBt) ){
  97091. sqlite3ErrorMsg(pParse, "temporary storage cannot be changed "
  97092. "from within a transaction");
  97093. return SQLITE_ERROR;
  97094. }
  97095. sqlite3BtreeClose(db->aDb[1].pBt);
  97096. db->aDb[1].pBt = 0;
  97097. sqlite3ResetAllSchemasOfConnection(db);
  97098. }
  97099. return SQLITE_OK;
  97100. }
  97101. #endif /* SQLITE_PAGER_PRAGMAS */
  97102. #ifndef SQLITE_OMIT_PAGER_PRAGMAS
  97103. /*
  97104. ** If the TEMP database is open, close it and mark the database schema
  97105. ** as needing reloading. This must be done when using the SQLITE_TEMP_STORE
  97106. ** or DEFAULT_TEMP_STORE pragmas.
  97107. */
  97108. static int changeTempStorage(Parse *pParse, const char *zStorageType){
  97109. int ts = getTempStore(zStorageType);
  97110. sqlite3 *db = pParse->db;
  97111. if( db->temp_store==ts ) return SQLITE_OK;
  97112. if( invalidateTempStorage( pParse ) != SQLITE_OK ){
  97113. return SQLITE_ERROR;
  97114. }
  97115. db->temp_store = (u8)ts;
  97116. return SQLITE_OK;
  97117. }
  97118. #endif /* SQLITE_PAGER_PRAGMAS */
  97119. /*
  97120. ** Generate code to return a single integer value.
  97121. */
  97122. static void returnSingleInt(Parse *pParse, const char *zLabel, i64 value){
  97123. Vdbe *v = sqlite3GetVdbe(pParse);
  97124. int nMem = ++pParse->nMem;
  97125. i64 *pI64 = sqlite3DbMallocRaw(pParse->db, sizeof(value));
  97126. if( pI64 ){
  97127. memcpy(pI64, &value, sizeof(value));
  97128. }
  97129. sqlite3VdbeAddOp4(v, OP_Int64, 0, nMem, 0, (char*)pI64, P4_INT64);
  97130. sqlite3VdbeSetNumCols(v, 1);
  97131. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, zLabel, SQLITE_STATIC);
  97132. sqlite3VdbeAddOp2(v, OP_ResultRow, nMem, 1);
  97133. }
  97134. /*
  97135. ** Set the safety_level and pager flags for pager iDb. Or if iDb<0
  97136. ** set these values for all pagers.
  97137. */
  97138. #ifndef SQLITE_OMIT_PAGER_PRAGMAS
  97139. static void setAllPagerFlags(sqlite3 *db){
  97140. if( db->autoCommit ){
  97141. Db *pDb = db->aDb;
  97142. int n = db->nDb;
  97143. assert( SQLITE_FullFSync==PAGER_FULLFSYNC );
  97144. assert( SQLITE_CkptFullFSync==PAGER_CKPT_FULLFSYNC );
  97145. assert( SQLITE_CacheSpill==PAGER_CACHESPILL );
  97146. assert( (PAGER_FULLFSYNC | PAGER_CKPT_FULLFSYNC | PAGER_CACHESPILL)
  97147. == PAGER_FLAGS_MASK );
  97148. assert( (pDb->safety_level & PAGER_SYNCHRONOUS_MASK)==pDb->safety_level );
  97149. while( (n--) > 0 ){
  97150. if( pDb->pBt ){
  97151. sqlite3BtreeSetPagerFlags(pDb->pBt,
  97152. pDb->safety_level | (db->flags & PAGER_FLAGS_MASK) );
  97153. }
  97154. pDb++;
  97155. }
  97156. }
  97157. }
  97158. #else
  97159. # define setAllPagerFlags(X) /* no-op */
  97160. #endif
  97161. /*
  97162. ** Return a human-readable name for a constraint resolution action.
  97163. */
  97164. #ifndef SQLITE_OMIT_FOREIGN_KEY
  97165. static const char *actionName(u8 action){
  97166. const char *zName;
  97167. switch( action ){
  97168. case OE_SetNull: zName = "SET NULL"; break;
  97169. case OE_SetDflt: zName = "SET DEFAULT"; break;
  97170. case OE_Cascade: zName = "CASCADE"; break;
  97171. case OE_Restrict: zName = "RESTRICT"; break;
  97172. default: zName = "NO ACTION";
  97173. assert( action==OE_None ); break;
  97174. }
  97175. return zName;
  97176. }
  97177. #endif
  97178. /*
  97179. ** Parameter eMode must be one of the PAGER_JOURNALMODE_XXX constants
  97180. ** defined in pager.h. This function returns the associated lowercase
  97181. ** journal-mode name.
  97182. */
  97183. SQLITE_PRIVATE const char *sqlite3JournalModename(int eMode){
  97184. static char * const azModeName[] = {
  97185. "delete", "persist", "off", "truncate", "memory"
  97186. #ifndef SQLITE_OMIT_WAL
  97187. , "wal"
  97188. #endif
  97189. };
  97190. assert( PAGER_JOURNALMODE_DELETE==0 );
  97191. assert( PAGER_JOURNALMODE_PERSIST==1 );
  97192. assert( PAGER_JOURNALMODE_OFF==2 );
  97193. assert( PAGER_JOURNALMODE_TRUNCATE==3 );
  97194. assert( PAGER_JOURNALMODE_MEMORY==4 );
  97195. assert( PAGER_JOURNALMODE_WAL==5 );
  97196. assert( eMode>=0 && eMode<=ArraySize(azModeName) );
  97197. if( eMode==ArraySize(azModeName) ) return 0;
  97198. return azModeName[eMode];
  97199. }
  97200. /*
  97201. ** Process a pragma statement.
  97202. **
  97203. ** Pragmas are of this form:
  97204. **
  97205. ** PRAGMA [database.]id [= value]
  97206. **
  97207. ** The identifier might also be a string. The value is a string, and
  97208. ** identifier, or a number. If minusFlag is true, then the value is
  97209. ** a number that was preceded by a minus sign.
  97210. **
  97211. ** If the left side is "database.id" then pId1 is the database name
  97212. ** and pId2 is the id. If the left side is just "id" then pId1 is the
  97213. ** id and pId2 is any empty string.
  97214. */
  97215. SQLITE_PRIVATE void sqlite3Pragma(
  97216. Parse *pParse,
  97217. Token *pId1, /* First part of [database.]id field */
  97218. Token *pId2, /* Second part of [database.]id field, or NULL */
  97219. Token *pValue, /* Token for <value>, or NULL */
  97220. int minusFlag /* True if a '-' sign preceded <value> */
  97221. ){
  97222. char *zLeft = 0; /* Nul-terminated UTF-8 string <id> */
  97223. char *zRight = 0; /* Nul-terminated UTF-8 string <value>, or NULL */
  97224. const char *zDb = 0; /* The database name */
  97225. Token *pId; /* Pointer to <id> token */
  97226. char *aFcntl[4]; /* Argument to SQLITE_FCNTL_PRAGMA */
  97227. int iDb; /* Database index for <database> */
  97228. int lwr, upr, mid = 0; /* Binary search bounds */
  97229. int rc; /* return value form SQLITE_FCNTL_PRAGMA */
  97230. sqlite3 *db = pParse->db; /* The database connection */
  97231. Db *pDb; /* The specific database being pragmaed */
  97232. Vdbe *v = sqlite3GetVdbe(pParse); /* Prepared statement */
  97233. const struct sPragmaNames *pPragma;
  97234. if( v==0 ) return;
  97235. sqlite3VdbeRunOnlyOnce(v);
  97236. pParse->nMem = 2;
  97237. /* Interpret the [database.] part of the pragma statement. iDb is the
  97238. ** index of the database this pragma is being applied to in db.aDb[]. */
  97239. iDb = sqlite3TwoPartName(pParse, pId1, pId2, &pId);
  97240. if( iDb<0 ) return;
  97241. pDb = &db->aDb[iDb];
  97242. /* If the temp database has been explicitly named as part of the
  97243. ** pragma, make sure it is open.
  97244. */
  97245. if( iDb==1 && sqlite3OpenTempDatabase(pParse) ){
  97246. return;
  97247. }
  97248. zLeft = sqlite3NameFromToken(db, pId);
  97249. if( !zLeft ) return;
  97250. if( minusFlag ){
  97251. zRight = sqlite3MPrintf(db, "-%T", pValue);
  97252. }else{
  97253. zRight = sqlite3NameFromToken(db, pValue);
  97254. }
  97255. assert( pId2 );
  97256. zDb = pId2->n>0 ? pDb->zName : 0;
  97257. if( sqlite3AuthCheck(pParse, SQLITE_PRAGMA, zLeft, zRight, zDb) ){
  97258. goto pragma_out;
  97259. }
  97260. /* Send an SQLITE_FCNTL_PRAGMA file-control to the underlying VFS
  97261. ** connection. If it returns SQLITE_OK, then assume that the VFS
  97262. ** handled the pragma and generate a no-op prepared statement.
  97263. **
  97264. ** IMPLEMENTATION-OF: R-12238-55120 Whenever a PRAGMA statement is parsed,
  97265. ** an SQLITE_FCNTL_PRAGMA file control is sent to the open sqlite3_file
  97266. ** object corresponding to the database file to which the pragma
  97267. ** statement refers.
  97268. **
  97269. ** IMPLEMENTATION-OF: R-29875-31678 The argument to the SQLITE_FCNTL_PRAGMA
  97270. ** file control is an array of pointers to strings (char**) in which the
  97271. ** second element of the array is the name of the pragma and the third
  97272. ** element is the argument to the pragma or NULL if the pragma has no
  97273. ** argument.
  97274. */
  97275. aFcntl[0] = 0;
  97276. aFcntl[1] = zLeft;
  97277. aFcntl[2] = zRight;
  97278. aFcntl[3] = 0;
  97279. db->busyHandler.nBusy = 0;
  97280. rc = sqlite3_file_control(db, zDb, SQLITE_FCNTL_PRAGMA, (void*)aFcntl);
  97281. if( rc==SQLITE_OK ){
  97282. if( aFcntl[0] ){
  97283. int nMem = ++pParse->nMem;
  97284. sqlite3VdbeAddOp4(v, OP_String8, 0, nMem, 0, aFcntl[0], 0);
  97285. sqlite3VdbeSetNumCols(v, 1);
  97286. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "result", SQLITE_STATIC);
  97287. sqlite3VdbeAddOp2(v, OP_ResultRow, nMem, 1);
  97288. sqlite3_free(aFcntl[0]);
  97289. }
  97290. goto pragma_out;
  97291. }
  97292. if( rc!=SQLITE_NOTFOUND ){
  97293. if( aFcntl[0] ){
  97294. sqlite3ErrorMsg(pParse, "%s", aFcntl[0]);
  97295. sqlite3_free(aFcntl[0]);
  97296. }
  97297. pParse->nErr++;
  97298. pParse->rc = rc;
  97299. goto pragma_out;
  97300. }
  97301. /* Locate the pragma in the lookup table */
  97302. lwr = 0;
  97303. upr = ArraySize(aPragmaNames)-1;
  97304. while( lwr<=upr ){
  97305. mid = (lwr+upr)/2;
  97306. rc = sqlite3_stricmp(zLeft, aPragmaNames[mid].zName);
  97307. if( rc==0 ) break;
  97308. if( rc<0 ){
  97309. upr = mid - 1;
  97310. }else{
  97311. lwr = mid + 1;
  97312. }
  97313. }
  97314. if( lwr>upr ) goto pragma_out;
  97315. pPragma = &aPragmaNames[mid];
  97316. /* Make sure the database schema is loaded if the pragma requires that */
  97317. if( (pPragma->mPragFlag & PragFlag_NeedSchema)!=0 ){
  97318. if( sqlite3ReadSchema(pParse) ) goto pragma_out;
  97319. }
  97320. /* Jump to the appropriate pragma handler */
  97321. switch( pPragma->ePragTyp ){
  97322. #if !defined(SQLITE_OMIT_PAGER_PRAGMAS) && !defined(SQLITE_OMIT_DEPRECATED)
  97323. /*
  97324. ** PRAGMA [database.]default_cache_size
  97325. ** PRAGMA [database.]default_cache_size=N
  97326. **
  97327. ** The first form reports the current persistent setting for the
  97328. ** page cache size. The value returned is the maximum number of
  97329. ** pages in the page cache. The second form sets both the current
  97330. ** page cache size value and the persistent page cache size value
  97331. ** stored in the database file.
  97332. **
  97333. ** Older versions of SQLite would set the default cache size to a
  97334. ** negative number to indicate synchronous=OFF. These days, synchronous
  97335. ** is always on by default regardless of the sign of the default cache
  97336. ** size. But continue to take the absolute value of the default cache
  97337. ** size of historical compatibility.
  97338. */
  97339. case PragTyp_DEFAULT_CACHE_SIZE: {
  97340. static const int iLn = VDBE_OFFSET_LINENO(2);
  97341. static const VdbeOpList getCacheSize[] = {
  97342. { OP_Transaction, 0, 0, 0}, /* 0 */
  97343. { OP_ReadCookie, 0, 1, BTREE_DEFAULT_CACHE_SIZE}, /* 1 */
  97344. { OP_IfPos, 1, 8, 0},
  97345. { OP_Integer, 0, 2, 0},
  97346. { OP_Subtract, 1, 2, 1},
  97347. { OP_IfPos, 1, 8, 0},
  97348. { OP_Integer, 0, 1, 0}, /* 6 */
  97349. { OP_Noop, 0, 0, 0},
  97350. { OP_ResultRow, 1, 1, 0},
  97351. };
  97352. int addr;
  97353. sqlite3VdbeUsesBtree(v, iDb);
  97354. if( !zRight ){
  97355. sqlite3VdbeSetNumCols(v, 1);
  97356. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "cache_size", SQLITE_STATIC);
  97357. pParse->nMem += 2;
  97358. addr = sqlite3VdbeAddOpList(v, ArraySize(getCacheSize), getCacheSize,iLn);
  97359. sqlite3VdbeChangeP1(v, addr, iDb);
  97360. sqlite3VdbeChangeP1(v, addr+1, iDb);
  97361. sqlite3VdbeChangeP1(v, addr+6, SQLITE_DEFAULT_CACHE_SIZE);
  97362. }else{
  97363. int size = sqlite3AbsInt32(sqlite3Atoi(zRight));
  97364. sqlite3BeginWriteOperation(pParse, 0, iDb);
  97365. sqlite3VdbeAddOp2(v, OP_Integer, size, 1);
  97366. sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_DEFAULT_CACHE_SIZE, 1);
  97367. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  97368. pDb->pSchema->cache_size = size;
  97369. sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
  97370. }
  97371. break;
  97372. }
  97373. #endif /* !SQLITE_OMIT_PAGER_PRAGMAS && !SQLITE_OMIT_DEPRECATED */
  97374. #if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
  97375. /*
  97376. ** PRAGMA [database.]page_size
  97377. ** PRAGMA [database.]page_size=N
  97378. **
  97379. ** The first form reports the current setting for the
  97380. ** database page size in bytes. The second form sets the
  97381. ** database page size value. The value can only be set if
  97382. ** the database has not yet been created.
  97383. */
  97384. case PragTyp_PAGE_SIZE: {
  97385. Btree *pBt = pDb->pBt;
  97386. assert( pBt!=0 );
  97387. if( !zRight ){
  97388. int size = ALWAYS(pBt) ? sqlite3BtreeGetPageSize(pBt) : 0;
  97389. returnSingleInt(pParse, "page_size", size);
  97390. }else{
  97391. /* Malloc may fail when setting the page-size, as there is an internal
  97392. ** buffer that the pager module resizes using sqlite3_realloc().
  97393. */
  97394. db->nextPagesize = sqlite3Atoi(zRight);
  97395. if( SQLITE_NOMEM==sqlite3BtreeSetPageSize(pBt, db->nextPagesize,-1,0) ){
  97396. db->mallocFailed = 1;
  97397. }
  97398. }
  97399. break;
  97400. }
  97401. /*
  97402. ** PRAGMA [database.]secure_delete
  97403. ** PRAGMA [database.]secure_delete=ON/OFF
  97404. **
  97405. ** The first form reports the current setting for the
  97406. ** secure_delete flag. The second form changes the secure_delete
  97407. ** flag setting and reports thenew value.
  97408. */
  97409. case PragTyp_SECURE_DELETE: {
  97410. Btree *pBt = pDb->pBt;
  97411. int b = -1;
  97412. assert( pBt!=0 );
  97413. if( zRight ){
  97414. b = sqlite3GetBoolean(zRight, 0);
  97415. }
  97416. if( pId2->n==0 && b>=0 ){
  97417. int ii;
  97418. for(ii=0; ii<db->nDb; ii++){
  97419. sqlite3BtreeSecureDelete(db->aDb[ii].pBt, b);
  97420. }
  97421. }
  97422. b = sqlite3BtreeSecureDelete(pBt, b);
  97423. returnSingleInt(pParse, "secure_delete", b);
  97424. break;
  97425. }
  97426. /*
  97427. ** PRAGMA [database.]max_page_count
  97428. ** PRAGMA [database.]max_page_count=N
  97429. **
  97430. ** The first form reports the current setting for the
  97431. ** maximum number of pages in the database file. The
  97432. ** second form attempts to change this setting. Both
  97433. ** forms return the current setting.
  97434. **
  97435. ** The absolute value of N is used. This is undocumented and might
  97436. ** change. The only purpose is to provide an easy way to test
  97437. ** the sqlite3AbsInt32() function.
  97438. **
  97439. ** PRAGMA [database.]page_count
  97440. **
  97441. ** Return the number of pages in the specified database.
  97442. */
  97443. case PragTyp_PAGE_COUNT: {
  97444. int iReg;
  97445. sqlite3CodeVerifySchema(pParse, iDb);
  97446. iReg = ++pParse->nMem;
  97447. if( sqlite3Tolower(zLeft[0])=='p' ){
  97448. sqlite3VdbeAddOp2(v, OP_Pagecount, iDb, iReg);
  97449. }else{
  97450. sqlite3VdbeAddOp3(v, OP_MaxPgcnt, iDb, iReg,
  97451. sqlite3AbsInt32(sqlite3Atoi(zRight)));
  97452. }
  97453. sqlite3VdbeAddOp2(v, OP_ResultRow, iReg, 1);
  97454. sqlite3VdbeSetNumCols(v, 1);
  97455. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, zLeft, SQLITE_TRANSIENT);
  97456. break;
  97457. }
  97458. /*
  97459. ** PRAGMA [database.]locking_mode
  97460. ** PRAGMA [database.]locking_mode = (normal|exclusive)
  97461. */
  97462. case PragTyp_LOCKING_MODE: {
  97463. const char *zRet = "normal";
  97464. int eMode = getLockingMode(zRight);
  97465. if( pId2->n==0 && eMode==PAGER_LOCKINGMODE_QUERY ){
  97466. /* Simple "PRAGMA locking_mode;" statement. This is a query for
  97467. ** the current default locking mode (which may be different to
  97468. ** the locking-mode of the main database).
  97469. */
  97470. eMode = db->dfltLockMode;
  97471. }else{
  97472. Pager *pPager;
  97473. if( pId2->n==0 ){
  97474. /* This indicates that no database name was specified as part
  97475. ** of the PRAGMA command. In this case the locking-mode must be
  97476. ** set on all attached databases, as well as the main db file.
  97477. **
  97478. ** Also, the sqlite3.dfltLockMode variable is set so that
  97479. ** any subsequently attached databases also use the specified
  97480. ** locking mode.
  97481. */
  97482. int ii;
  97483. assert(pDb==&db->aDb[0]);
  97484. for(ii=2; ii<db->nDb; ii++){
  97485. pPager = sqlite3BtreePager(db->aDb[ii].pBt);
  97486. sqlite3PagerLockingMode(pPager, eMode);
  97487. }
  97488. db->dfltLockMode = (u8)eMode;
  97489. }
  97490. pPager = sqlite3BtreePager(pDb->pBt);
  97491. eMode = sqlite3PagerLockingMode(pPager, eMode);
  97492. }
  97493. assert( eMode==PAGER_LOCKINGMODE_NORMAL
  97494. || eMode==PAGER_LOCKINGMODE_EXCLUSIVE );
  97495. if( eMode==PAGER_LOCKINGMODE_EXCLUSIVE ){
  97496. zRet = "exclusive";
  97497. }
  97498. sqlite3VdbeSetNumCols(v, 1);
  97499. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "locking_mode", SQLITE_STATIC);
  97500. sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, zRet, 0);
  97501. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
  97502. break;
  97503. }
  97504. /*
  97505. ** PRAGMA [database.]journal_mode
  97506. ** PRAGMA [database.]journal_mode =
  97507. ** (delete|persist|off|truncate|memory|wal|off)
  97508. */
  97509. case PragTyp_JOURNAL_MODE: {
  97510. int eMode; /* One of the PAGER_JOURNALMODE_XXX symbols */
  97511. int ii; /* Loop counter */
  97512. sqlite3VdbeSetNumCols(v, 1);
  97513. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "journal_mode", SQLITE_STATIC);
  97514. if( zRight==0 ){
  97515. /* If there is no "=MODE" part of the pragma, do a query for the
  97516. ** current mode */
  97517. eMode = PAGER_JOURNALMODE_QUERY;
  97518. }else{
  97519. const char *zMode;
  97520. int n = sqlite3Strlen30(zRight);
  97521. for(eMode=0; (zMode = sqlite3JournalModename(eMode))!=0; eMode++){
  97522. if( sqlite3StrNICmp(zRight, zMode, n)==0 ) break;
  97523. }
  97524. if( !zMode ){
  97525. /* If the "=MODE" part does not match any known journal mode,
  97526. ** then do a query */
  97527. eMode = PAGER_JOURNALMODE_QUERY;
  97528. }
  97529. }
  97530. if( eMode==PAGER_JOURNALMODE_QUERY && pId2->n==0 ){
  97531. /* Convert "PRAGMA journal_mode" into "PRAGMA main.journal_mode" */
  97532. iDb = 0;
  97533. pId2->n = 1;
  97534. }
  97535. for(ii=db->nDb-1; ii>=0; ii--){
  97536. if( db->aDb[ii].pBt && (ii==iDb || pId2->n==0) ){
  97537. sqlite3VdbeUsesBtree(v, ii);
  97538. sqlite3VdbeAddOp3(v, OP_JournalMode, ii, 1, eMode);
  97539. }
  97540. }
  97541. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
  97542. break;
  97543. }
  97544. /*
  97545. ** PRAGMA [database.]journal_size_limit
  97546. ** PRAGMA [database.]journal_size_limit=N
  97547. **
  97548. ** Get or set the size limit on rollback journal files.
  97549. */
  97550. case PragTyp_JOURNAL_SIZE_LIMIT: {
  97551. Pager *pPager = sqlite3BtreePager(pDb->pBt);
  97552. i64 iLimit = -2;
  97553. if( zRight ){
  97554. sqlite3DecOrHexToI64(zRight, &iLimit);
  97555. if( iLimit<-1 ) iLimit = -1;
  97556. }
  97557. iLimit = sqlite3PagerJournalSizeLimit(pPager, iLimit);
  97558. returnSingleInt(pParse, "journal_size_limit", iLimit);
  97559. break;
  97560. }
  97561. #endif /* SQLITE_OMIT_PAGER_PRAGMAS */
  97562. /*
  97563. ** PRAGMA [database.]auto_vacuum
  97564. ** PRAGMA [database.]auto_vacuum=N
  97565. **
  97566. ** Get or set the value of the database 'auto-vacuum' parameter.
  97567. ** The value is one of: 0 NONE 1 FULL 2 INCREMENTAL
  97568. */
  97569. #ifndef SQLITE_OMIT_AUTOVACUUM
  97570. case PragTyp_AUTO_VACUUM: {
  97571. Btree *pBt = pDb->pBt;
  97572. assert( pBt!=0 );
  97573. if( !zRight ){
  97574. returnSingleInt(pParse, "auto_vacuum", sqlite3BtreeGetAutoVacuum(pBt));
  97575. }else{
  97576. int eAuto = getAutoVacuum(zRight);
  97577. assert( eAuto>=0 && eAuto<=2 );
  97578. db->nextAutovac = (u8)eAuto;
  97579. /* Call SetAutoVacuum() to set initialize the internal auto and
  97580. ** incr-vacuum flags. This is required in case this connection
  97581. ** creates the database file. It is important that it is created
  97582. ** as an auto-vacuum capable db.
  97583. */
  97584. rc = sqlite3BtreeSetAutoVacuum(pBt, eAuto);
  97585. if( rc==SQLITE_OK && (eAuto==1 || eAuto==2) ){
  97586. /* When setting the auto_vacuum mode to either "full" or
  97587. ** "incremental", write the value of meta[6] in the database
  97588. ** file. Before writing to meta[6], check that meta[3] indicates
  97589. ** that this really is an auto-vacuum capable database.
  97590. */
  97591. static const int iLn = VDBE_OFFSET_LINENO(2);
  97592. static const VdbeOpList setMeta6[] = {
  97593. { OP_Transaction, 0, 1, 0}, /* 0 */
  97594. { OP_ReadCookie, 0, 1, BTREE_LARGEST_ROOT_PAGE},
  97595. { OP_If, 1, 0, 0}, /* 2 */
  97596. { OP_Halt, SQLITE_OK, OE_Abort, 0}, /* 3 */
  97597. { OP_Integer, 0, 1, 0}, /* 4 */
  97598. { OP_SetCookie, 0, BTREE_INCR_VACUUM, 1}, /* 5 */
  97599. };
  97600. int iAddr;
  97601. iAddr = sqlite3VdbeAddOpList(v, ArraySize(setMeta6), setMeta6, iLn);
  97602. sqlite3VdbeChangeP1(v, iAddr, iDb);
  97603. sqlite3VdbeChangeP1(v, iAddr+1, iDb);
  97604. sqlite3VdbeChangeP2(v, iAddr+2, iAddr+4);
  97605. sqlite3VdbeChangeP1(v, iAddr+4, eAuto-1);
  97606. sqlite3VdbeChangeP1(v, iAddr+5, iDb);
  97607. sqlite3VdbeUsesBtree(v, iDb);
  97608. }
  97609. }
  97610. break;
  97611. }
  97612. #endif
  97613. /*
  97614. ** PRAGMA [database.]incremental_vacuum(N)
  97615. **
  97616. ** Do N steps of incremental vacuuming on a database.
  97617. */
  97618. #ifndef SQLITE_OMIT_AUTOVACUUM
  97619. case PragTyp_INCREMENTAL_VACUUM: {
  97620. int iLimit, addr;
  97621. if( zRight==0 || !sqlite3GetInt32(zRight, &iLimit) || iLimit<=0 ){
  97622. iLimit = 0x7fffffff;
  97623. }
  97624. sqlite3BeginWriteOperation(pParse, 0, iDb);
  97625. sqlite3VdbeAddOp2(v, OP_Integer, iLimit, 1);
  97626. addr = sqlite3VdbeAddOp1(v, OP_IncrVacuum, iDb); VdbeCoverage(v);
  97627. sqlite3VdbeAddOp1(v, OP_ResultRow, 1);
  97628. sqlite3VdbeAddOp2(v, OP_AddImm, 1, -1);
  97629. sqlite3VdbeAddOp2(v, OP_IfPos, 1, addr); VdbeCoverage(v);
  97630. sqlite3VdbeJumpHere(v, addr);
  97631. break;
  97632. }
  97633. #endif
  97634. #ifndef SQLITE_OMIT_PAGER_PRAGMAS
  97635. /*
  97636. ** PRAGMA [database.]cache_size
  97637. ** PRAGMA [database.]cache_size=N
  97638. **
  97639. ** The first form reports the current local setting for the
  97640. ** page cache size. The second form sets the local
  97641. ** page cache size value. If N is positive then that is the
  97642. ** number of pages in the cache. If N is negative, then the
  97643. ** number of pages is adjusted so that the cache uses -N kibibytes
  97644. ** of memory.
  97645. */
  97646. case PragTyp_CACHE_SIZE: {
  97647. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  97648. if( !zRight ){
  97649. returnSingleInt(pParse, "cache_size", pDb->pSchema->cache_size);
  97650. }else{
  97651. int size = sqlite3Atoi(zRight);
  97652. pDb->pSchema->cache_size = size;
  97653. sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
  97654. }
  97655. break;
  97656. }
  97657. /*
  97658. ** PRAGMA [database.]mmap_size(N)
  97659. **
  97660. ** Used to set mapping size limit. The mapping size limit is
  97661. ** used to limit the aggregate size of all memory mapped regions of the
  97662. ** database file. If this parameter is set to zero, then memory mapping
  97663. ** is not used at all. If N is negative, then the default memory map
  97664. ** limit determined by sqlite3_config(SQLITE_CONFIG_MMAP_SIZE) is set.
  97665. ** The parameter N is measured in bytes.
  97666. **
  97667. ** This value is advisory. The underlying VFS is free to memory map
  97668. ** as little or as much as it wants. Except, if N is set to 0 then the
  97669. ** upper layers will never invoke the xFetch interfaces to the VFS.
  97670. */
  97671. case PragTyp_MMAP_SIZE: {
  97672. sqlite3_int64 sz;
  97673. #if SQLITE_MAX_MMAP_SIZE>0
  97674. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  97675. if( zRight ){
  97676. int ii;
  97677. sqlite3DecOrHexToI64(zRight, &sz);
  97678. if( sz<0 ) sz = sqlite3GlobalConfig.szMmap;
  97679. if( pId2->n==0 ) db->szMmap = sz;
  97680. for(ii=db->nDb-1; ii>=0; ii--){
  97681. if( db->aDb[ii].pBt && (ii==iDb || pId2->n==0) ){
  97682. sqlite3BtreeSetMmapLimit(db->aDb[ii].pBt, sz);
  97683. }
  97684. }
  97685. }
  97686. sz = -1;
  97687. rc = sqlite3_file_control(db, zDb, SQLITE_FCNTL_MMAP_SIZE, &sz);
  97688. #else
  97689. sz = 0;
  97690. rc = SQLITE_OK;
  97691. #endif
  97692. if( rc==SQLITE_OK ){
  97693. returnSingleInt(pParse, "mmap_size", sz);
  97694. }else if( rc!=SQLITE_NOTFOUND ){
  97695. pParse->nErr++;
  97696. pParse->rc = rc;
  97697. }
  97698. break;
  97699. }
  97700. /*
  97701. ** PRAGMA temp_store
  97702. ** PRAGMA temp_store = "default"|"memory"|"file"
  97703. **
  97704. ** Return or set the local value of the temp_store flag. Changing
  97705. ** the local value does not make changes to the disk file and the default
  97706. ** value will be restored the next time the database is opened.
  97707. **
  97708. ** Note that it is possible for the library compile-time options to
  97709. ** override this setting
  97710. */
  97711. case PragTyp_TEMP_STORE: {
  97712. if( !zRight ){
  97713. returnSingleInt(pParse, "temp_store", db->temp_store);
  97714. }else{
  97715. changeTempStorage(pParse, zRight);
  97716. }
  97717. break;
  97718. }
  97719. /*
  97720. ** PRAGMA temp_store_directory
  97721. ** PRAGMA temp_store_directory = ""|"directory_name"
  97722. **
  97723. ** Return or set the local value of the temp_store_directory flag. Changing
  97724. ** the value sets a specific directory to be used for temporary files.
  97725. ** Setting to a null string reverts to the default temporary directory search.
  97726. ** If temporary directory is changed, then invalidateTempStorage.
  97727. **
  97728. */
  97729. case PragTyp_TEMP_STORE_DIRECTORY: {
  97730. if( !zRight ){
  97731. if( sqlite3_temp_directory ){
  97732. sqlite3VdbeSetNumCols(v, 1);
  97733. sqlite3VdbeSetColName(v, 0, COLNAME_NAME,
  97734. "temp_store_directory", SQLITE_STATIC);
  97735. sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, sqlite3_temp_directory, 0);
  97736. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
  97737. }
  97738. }else{
  97739. #ifndef SQLITE_OMIT_WSD
  97740. if( zRight[0] ){
  97741. int res;
  97742. rc = sqlite3OsAccess(db->pVfs, zRight, SQLITE_ACCESS_READWRITE, &res);
  97743. if( rc!=SQLITE_OK || res==0 ){
  97744. sqlite3ErrorMsg(pParse, "not a writable directory");
  97745. goto pragma_out;
  97746. }
  97747. }
  97748. if( SQLITE_TEMP_STORE==0
  97749. || (SQLITE_TEMP_STORE==1 && db->temp_store<=1)
  97750. || (SQLITE_TEMP_STORE==2 && db->temp_store==1)
  97751. ){
  97752. invalidateTempStorage(pParse);
  97753. }
  97754. sqlite3_free(sqlite3_temp_directory);
  97755. if( zRight[0] ){
  97756. sqlite3_temp_directory = sqlite3_mprintf("%s", zRight);
  97757. }else{
  97758. sqlite3_temp_directory = 0;
  97759. }
  97760. #endif /* SQLITE_OMIT_WSD */
  97761. }
  97762. break;
  97763. }
  97764. #if SQLITE_OS_WIN
  97765. /*
  97766. ** PRAGMA data_store_directory
  97767. ** PRAGMA data_store_directory = ""|"directory_name"
  97768. **
  97769. ** Return or set the local value of the data_store_directory flag. Changing
  97770. ** the value sets a specific directory to be used for database files that
  97771. ** were specified with a relative pathname. Setting to a null string reverts
  97772. ** to the default database directory, which for database files specified with
  97773. ** a relative path will probably be based on the current directory for the
  97774. ** process. Database file specified with an absolute path are not impacted
  97775. ** by this setting, regardless of its value.
  97776. **
  97777. */
  97778. case PragTyp_DATA_STORE_DIRECTORY: {
  97779. if( !zRight ){
  97780. if( sqlite3_data_directory ){
  97781. sqlite3VdbeSetNumCols(v, 1);
  97782. sqlite3VdbeSetColName(v, 0, COLNAME_NAME,
  97783. "data_store_directory", SQLITE_STATIC);
  97784. sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, sqlite3_data_directory, 0);
  97785. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
  97786. }
  97787. }else{
  97788. #ifndef SQLITE_OMIT_WSD
  97789. if( zRight[0] ){
  97790. int res;
  97791. rc = sqlite3OsAccess(db->pVfs, zRight, SQLITE_ACCESS_READWRITE, &res);
  97792. if( rc!=SQLITE_OK || res==0 ){
  97793. sqlite3ErrorMsg(pParse, "not a writable directory");
  97794. goto pragma_out;
  97795. }
  97796. }
  97797. sqlite3_free(sqlite3_data_directory);
  97798. if( zRight[0] ){
  97799. sqlite3_data_directory = sqlite3_mprintf("%s", zRight);
  97800. }else{
  97801. sqlite3_data_directory = 0;
  97802. }
  97803. #endif /* SQLITE_OMIT_WSD */
  97804. }
  97805. break;
  97806. }
  97807. #endif
  97808. #if SQLITE_ENABLE_LOCKING_STYLE
  97809. /*
  97810. ** PRAGMA [database.]lock_proxy_file
  97811. ** PRAGMA [database.]lock_proxy_file = ":auto:"|"lock_file_path"
  97812. **
  97813. ** Return or set the value of the lock_proxy_file flag. Changing
  97814. ** the value sets a specific file to be used for database access locks.
  97815. **
  97816. */
  97817. case PragTyp_LOCK_PROXY_FILE: {
  97818. if( !zRight ){
  97819. Pager *pPager = sqlite3BtreePager(pDb->pBt);
  97820. char *proxy_file_path = NULL;
  97821. sqlite3_file *pFile = sqlite3PagerFile(pPager);
  97822. sqlite3OsFileControlHint(pFile, SQLITE_GET_LOCKPROXYFILE,
  97823. &proxy_file_path);
  97824. if( proxy_file_path ){
  97825. sqlite3VdbeSetNumCols(v, 1);
  97826. sqlite3VdbeSetColName(v, 0, COLNAME_NAME,
  97827. "lock_proxy_file", SQLITE_STATIC);
  97828. sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, proxy_file_path, 0);
  97829. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
  97830. }
  97831. }else{
  97832. Pager *pPager = sqlite3BtreePager(pDb->pBt);
  97833. sqlite3_file *pFile = sqlite3PagerFile(pPager);
  97834. int res;
  97835. if( zRight[0] ){
  97836. res=sqlite3OsFileControl(pFile, SQLITE_SET_LOCKPROXYFILE,
  97837. zRight);
  97838. } else {
  97839. res=sqlite3OsFileControl(pFile, SQLITE_SET_LOCKPROXYFILE,
  97840. NULL);
  97841. }
  97842. if( res!=SQLITE_OK ){
  97843. sqlite3ErrorMsg(pParse, "failed to set lock proxy file");
  97844. goto pragma_out;
  97845. }
  97846. }
  97847. break;
  97848. }
  97849. #endif /* SQLITE_ENABLE_LOCKING_STYLE */
  97850. /*
  97851. ** PRAGMA [database.]synchronous
  97852. ** PRAGMA [database.]synchronous=OFF|ON|NORMAL|FULL
  97853. **
  97854. ** Return or set the local value of the synchronous flag. Changing
  97855. ** the local value does not make changes to the disk file and the
  97856. ** default value will be restored the next time the database is
  97857. ** opened.
  97858. */
  97859. case PragTyp_SYNCHRONOUS: {
  97860. if( !zRight ){
  97861. returnSingleInt(pParse, "synchronous", pDb->safety_level-1);
  97862. }else{
  97863. if( !db->autoCommit ){
  97864. sqlite3ErrorMsg(pParse,
  97865. "Safety level may not be changed inside a transaction");
  97866. }else{
  97867. int iLevel = (getSafetyLevel(zRight,0,1)+1) & PAGER_SYNCHRONOUS_MASK;
  97868. if( iLevel==0 ) iLevel = 1;
  97869. pDb->safety_level = iLevel;
  97870. setAllPagerFlags(db);
  97871. }
  97872. }
  97873. break;
  97874. }
  97875. #endif /* SQLITE_OMIT_PAGER_PRAGMAS */
  97876. #ifndef SQLITE_OMIT_FLAG_PRAGMAS
  97877. case PragTyp_FLAG: {
  97878. if( zRight==0 ){
  97879. returnSingleInt(pParse, pPragma->zName, (db->flags & pPragma->iArg)!=0 );
  97880. }else{
  97881. int mask = pPragma->iArg; /* Mask of bits to set or clear. */
  97882. if( db->autoCommit==0 ){
  97883. /* Foreign key support may not be enabled or disabled while not
  97884. ** in auto-commit mode. */
  97885. mask &= ~(SQLITE_ForeignKeys);
  97886. }
  97887. #if SQLITE_USER_AUTHENTICATION
  97888. if( db->auth.authLevel==UAUTH_User ){
  97889. /* Do not allow non-admin users to modify the schema arbitrarily */
  97890. mask &= ~(SQLITE_WriteSchema);
  97891. }
  97892. #endif
  97893. if( sqlite3GetBoolean(zRight, 0) ){
  97894. db->flags |= mask;
  97895. }else{
  97896. db->flags &= ~mask;
  97897. if( mask==SQLITE_DeferFKs ) db->nDeferredImmCons = 0;
  97898. }
  97899. /* Many of the flag-pragmas modify the code generated by the SQL
  97900. ** compiler (eg. count_changes). So add an opcode to expire all
  97901. ** compiled SQL statements after modifying a pragma value.
  97902. */
  97903. sqlite3VdbeAddOp2(v, OP_Expire, 0, 0);
  97904. setAllPagerFlags(db);
  97905. }
  97906. break;
  97907. }
  97908. #endif /* SQLITE_OMIT_FLAG_PRAGMAS */
  97909. #ifndef SQLITE_OMIT_SCHEMA_PRAGMAS
  97910. /*
  97911. ** PRAGMA table_info(<table>)
  97912. **
  97913. ** Return a single row for each column of the named table. The columns of
  97914. ** the returned data set are:
  97915. **
  97916. ** cid: Column id (numbered from left to right, starting at 0)
  97917. ** name: Column name
  97918. ** type: Column declaration type.
  97919. ** notnull: True if 'NOT NULL' is part of column declaration
  97920. ** dflt_value: The default value for the column, if any.
  97921. */
  97922. case PragTyp_TABLE_INFO: if( zRight ){
  97923. Table *pTab;
  97924. pTab = sqlite3FindTable(db, zRight, zDb);
  97925. if( pTab ){
  97926. int i, k;
  97927. int nHidden = 0;
  97928. Column *pCol;
  97929. Index *pPk = sqlite3PrimaryKeyIndex(pTab);
  97930. sqlite3VdbeSetNumCols(v, 6);
  97931. pParse->nMem = 6;
  97932. sqlite3CodeVerifySchema(pParse, iDb);
  97933. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "cid", SQLITE_STATIC);
  97934. sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "name", SQLITE_STATIC);
  97935. sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "type", SQLITE_STATIC);
  97936. sqlite3VdbeSetColName(v, 3, COLNAME_NAME, "notnull", SQLITE_STATIC);
  97937. sqlite3VdbeSetColName(v, 4, COLNAME_NAME, "dflt_value", SQLITE_STATIC);
  97938. sqlite3VdbeSetColName(v, 5, COLNAME_NAME, "pk", SQLITE_STATIC);
  97939. sqlite3ViewGetColumnNames(pParse, pTab);
  97940. for(i=0, pCol=pTab->aCol; i<pTab->nCol; i++, pCol++){
  97941. if( IsHiddenColumn(pCol) ){
  97942. nHidden++;
  97943. continue;
  97944. }
  97945. sqlite3VdbeAddOp2(v, OP_Integer, i-nHidden, 1);
  97946. sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, pCol->zName, 0);
  97947. sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0,
  97948. pCol->zType ? pCol->zType : "", 0);
  97949. sqlite3VdbeAddOp2(v, OP_Integer, (pCol->notNull ? 1 : 0), 4);
  97950. if( pCol->zDflt ){
  97951. sqlite3VdbeAddOp4(v, OP_String8, 0, 5, 0, (char*)pCol->zDflt, 0);
  97952. }else{
  97953. sqlite3VdbeAddOp2(v, OP_Null, 0, 5);
  97954. }
  97955. if( (pCol->colFlags & COLFLAG_PRIMKEY)==0 ){
  97956. k = 0;
  97957. }else if( pPk==0 ){
  97958. k = 1;
  97959. }else{
  97960. for(k=1; k<=pTab->nCol && pPk->aiColumn[k-1]!=i; k++){}
  97961. }
  97962. sqlite3VdbeAddOp2(v, OP_Integer, k, 6);
  97963. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 6);
  97964. }
  97965. }
  97966. }
  97967. break;
  97968. case PragTyp_STATS: {
  97969. Index *pIdx;
  97970. HashElem *i;
  97971. v = sqlite3GetVdbe(pParse);
  97972. sqlite3VdbeSetNumCols(v, 4);
  97973. pParse->nMem = 4;
  97974. sqlite3CodeVerifySchema(pParse, iDb);
  97975. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "table", SQLITE_STATIC);
  97976. sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "index", SQLITE_STATIC);
  97977. sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "width", SQLITE_STATIC);
  97978. sqlite3VdbeSetColName(v, 3, COLNAME_NAME, "height", SQLITE_STATIC);
  97979. for(i=sqliteHashFirst(&pDb->pSchema->tblHash); i; i=sqliteHashNext(i)){
  97980. Table *pTab = sqliteHashData(i);
  97981. sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, pTab->zName, 0);
  97982. sqlite3VdbeAddOp2(v, OP_Null, 0, 2);
  97983. sqlite3VdbeAddOp2(v, OP_Integer,
  97984. (int)sqlite3LogEstToInt(pTab->szTabRow), 3);
  97985. sqlite3VdbeAddOp2(v, OP_Integer,
  97986. (int)sqlite3LogEstToInt(pTab->nRowLogEst), 4);
  97987. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 4);
  97988. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  97989. sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, pIdx->zName, 0);
  97990. sqlite3VdbeAddOp2(v, OP_Integer,
  97991. (int)sqlite3LogEstToInt(pIdx->szIdxRow), 3);
  97992. sqlite3VdbeAddOp2(v, OP_Integer,
  97993. (int)sqlite3LogEstToInt(pIdx->aiRowLogEst[0]), 4);
  97994. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 4);
  97995. }
  97996. }
  97997. }
  97998. break;
  97999. case PragTyp_INDEX_INFO: if( zRight ){
  98000. Index *pIdx;
  98001. Table *pTab;
  98002. pIdx = sqlite3FindIndex(db, zRight, zDb);
  98003. if( pIdx ){
  98004. int i;
  98005. int mx;
  98006. if( pPragma->iArg ){
  98007. /* PRAGMA index_xinfo (newer version with more rows and columns) */
  98008. mx = pIdx->nColumn;
  98009. pParse->nMem = 6;
  98010. }else{
  98011. /* PRAGMA index_info (legacy version) */
  98012. mx = pIdx->nKeyCol;
  98013. pParse->nMem = 3;
  98014. }
  98015. pTab = pIdx->pTable;
  98016. sqlite3VdbeSetNumCols(v, pParse->nMem);
  98017. sqlite3CodeVerifySchema(pParse, iDb);
  98018. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "seqno", SQLITE_STATIC);
  98019. sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "cid", SQLITE_STATIC);
  98020. sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "name", SQLITE_STATIC);
  98021. if( pPragma->iArg ){
  98022. sqlite3VdbeSetColName(v, 3, COLNAME_NAME, "desc", SQLITE_STATIC);
  98023. sqlite3VdbeSetColName(v, 4, COLNAME_NAME, "coll", SQLITE_STATIC);
  98024. sqlite3VdbeSetColName(v, 5, COLNAME_NAME, "key", SQLITE_STATIC);
  98025. }
  98026. for(i=0; i<mx; i++){
  98027. i16 cnum = pIdx->aiColumn[i];
  98028. sqlite3VdbeAddOp2(v, OP_Integer, i, 1);
  98029. sqlite3VdbeAddOp2(v, OP_Integer, cnum, 2);
  98030. if( cnum<0 ){
  98031. sqlite3VdbeAddOp2(v, OP_Null, 0, 3);
  98032. }else{
  98033. sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, pTab->aCol[cnum].zName, 0);
  98034. }
  98035. if( pPragma->iArg ){
  98036. sqlite3VdbeAddOp2(v, OP_Integer, pIdx->aSortOrder[i], 4);
  98037. sqlite3VdbeAddOp4(v, OP_String8, 0, 5, 0, pIdx->azColl[i], 0);
  98038. sqlite3VdbeAddOp2(v, OP_Integer, i<pIdx->nKeyCol, 6);
  98039. }
  98040. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, pParse->nMem);
  98041. }
  98042. }
  98043. }
  98044. break;
  98045. case PragTyp_INDEX_LIST: if( zRight ){
  98046. Index *pIdx;
  98047. Table *pTab;
  98048. int i;
  98049. pTab = sqlite3FindTable(db, zRight, zDb);
  98050. if( pTab ){
  98051. v = sqlite3GetVdbe(pParse);
  98052. sqlite3VdbeSetNumCols(v, 5);
  98053. pParse->nMem = 5;
  98054. sqlite3CodeVerifySchema(pParse, iDb);
  98055. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "seq", SQLITE_STATIC);
  98056. sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "name", SQLITE_STATIC);
  98057. sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "unique", SQLITE_STATIC);
  98058. sqlite3VdbeSetColName(v, 3, COLNAME_NAME, "origin", SQLITE_STATIC);
  98059. sqlite3VdbeSetColName(v, 4, COLNAME_NAME, "partial", SQLITE_STATIC);
  98060. for(pIdx=pTab->pIndex, i=0; pIdx; pIdx=pIdx->pNext, i++){
  98061. const char *azOrigin[] = { "c", "u", "pk" };
  98062. sqlite3VdbeAddOp2(v, OP_Integer, i, 1);
  98063. sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, pIdx->zName, 0);
  98064. sqlite3VdbeAddOp2(v, OP_Integer, IsUniqueIndex(pIdx), 3);
  98065. sqlite3VdbeAddOp4(v, OP_String8, 0, 4, 0, azOrigin[pIdx->idxType], 0);
  98066. sqlite3VdbeAddOp2(v, OP_Integer, pIdx->pPartIdxWhere!=0, 5);
  98067. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 5);
  98068. }
  98069. }
  98070. }
  98071. break;
  98072. case PragTyp_DATABASE_LIST: {
  98073. int i;
  98074. sqlite3VdbeSetNumCols(v, 3);
  98075. pParse->nMem = 3;
  98076. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "seq", SQLITE_STATIC);
  98077. sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "name", SQLITE_STATIC);
  98078. sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "file", SQLITE_STATIC);
  98079. for(i=0; i<db->nDb; i++){
  98080. if( db->aDb[i].pBt==0 ) continue;
  98081. assert( db->aDb[i].zName!=0 );
  98082. sqlite3VdbeAddOp2(v, OP_Integer, i, 1);
  98083. sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, db->aDb[i].zName, 0);
  98084. sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0,
  98085. sqlite3BtreeGetFilename(db->aDb[i].pBt), 0);
  98086. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3);
  98087. }
  98088. }
  98089. break;
  98090. case PragTyp_COLLATION_LIST: {
  98091. int i = 0;
  98092. HashElem *p;
  98093. sqlite3VdbeSetNumCols(v, 2);
  98094. pParse->nMem = 2;
  98095. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "seq", SQLITE_STATIC);
  98096. sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "name", SQLITE_STATIC);
  98097. for(p=sqliteHashFirst(&db->aCollSeq); p; p=sqliteHashNext(p)){
  98098. CollSeq *pColl = (CollSeq *)sqliteHashData(p);
  98099. sqlite3VdbeAddOp2(v, OP_Integer, i++, 1);
  98100. sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, pColl->zName, 0);
  98101. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 2);
  98102. }
  98103. }
  98104. break;
  98105. #endif /* SQLITE_OMIT_SCHEMA_PRAGMAS */
  98106. #ifndef SQLITE_OMIT_FOREIGN_KEY
  98107. case PragTyp_FOREIGN_KEY_LIST: if( zRight ){
  98108. FKey *pFK;
  98109. Table *pTab;
  98110. pTab = sqlite3FindTable(db, zRight, zDb);
  98111. if( pTab ){
  98112. v = sqlite3GetVdbe(pParse);
  98113. pFK = pTab->pFKey;
  98114. if( pFK ){
  98115. int i = 0;
  98116. sqlite3VdbeSetNumCols(v, 8);
  98117. pParse->nMem = 8;
  98118. sqlite3CodeVerifySchema(pParse, iDb);
  98119. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "id", SQLITE_STATIC);
  98120. sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "seq", SQLITE_STATIC);
  98121. sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "table", SQLITE_STATIC);
  98122. sqlite3VdbeSetColName(v, 3, COLNAME_NAME, "from", SQLITE_STATIC);
  98123. sqlite3VdbeSetColName(v, 4, COLNAME_NAME, "to", SQLITE_STATIC);
  98124. sqlite3VdbeSetColName(v, 5, COLNAME_NAME, "on_update", SQLITE_STATIC);
  98125. sqlite3VdbeSetColName(v, 6, COLNAME_NAME, "on_delete", SQLITE_STATIC);
  98126. sqlite3VdbeSetColName(v, 7, COLNAME_NAME, "match", SQLITE_STATIC);
  98127. while(pFK){
  98128. int j;
  98129. for(j=0; j<pFK->nCol; j++){
  98130. char *zCol = pFK->aCol[j].zCol;
  98131. char *zOnDelete = (char *)actionName(pFK->aAction[0]);
  98132. char *zOnUpdate = (char *)actionName(pFK->aAction[1]);
  98133. sqlite3VdbeAddOp2(v, OP_Integer, i, 1);
  98134. sqlite3VdbeAddOp2(v, OP_Integer, j, 2);
  98135. sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, pFK->zTo, 0);
  98136. sqlite3VdbeAddOp4(v, OP_String8, 0, 4, 0,
  98137. pTab->aCol[pFK->aCol[j].iFrom].zName, 0);
  98138. sqlite3VdbeAddOp4(v, zCol ? OP_String8 : OP_Null, 0, 5, 0, zCol, 0);
  98139. sqlite3VdbeAddOp4(v, OP_String8, 0, 6, 0, zOnUpdate, 0);
  98140. sqlite3VdbeAddOp4(v, OP_String8, 0, 7, 0, zOnDelete, 0);
  98141. sqlite3VdbeAddOp4(v, OP_String8, 0, 8, 0, "NONE", 0);
  98142. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 8);
  98143. }
  98144. ++i;
  98145. pFK = pFK->pNextFrom;
  98146. }
  98147. }
  98148. }
  98149. }
  98150. break;
  98151. #endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
  98152. #ifndef SQLITE_OMIT_FOREIGN_KEY
  98153. #ifndef SQLITE_OMIT_TRIGGER
  98154. case PragTyp_FOREIGN_KEY_CHECK: {
  98155. FKey *pFK; /* A foreign key constraint */
  98156. Table *pTab; /* Child table contain "REFERENCES" keyword */
  98157. Table *pParent; /* Parent table that child points to */
  98158. Index *pIdx; /* Index in the parent table */
  98159. int i; /* Loop counter: Foreign key number for pTab */
  98160. int j; /* Loop counter: Field of the foreign key */
  98161. HashElem *k; /* Loop counter: Next table in schema */
  98162. int x; /* result variable */
  98163. int regResult; /* 3 registers to hold a result row */
  98164. int regKey; /* Register to hold key for checking the FK */
  98165. int regRow; /* Registers to hold a row from pTab */
  98166. int addrTop; /* Top of a loop checking foreign keys */
  98167. int addrOk; /* Jump here if the key is OK */
  98168. int *aiCols; /* child to parent column mapping */
  98169. regResult = pParse->nMem+1;
  98170. pParse->nMem += 4;
  98171. regKey = ++pParse->nMem;
  98172. regRow = ++pParse->nMem;
  98173. v = sqlite3GetVdbe(pParse);
  98174. sqlite3VdbeSetNumCols(v, 4);
  98175. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "table", SQLITE_STATIC);
  98176. sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "rowid", SQLITE_STATIC);
  98177. sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "parent", SQLITE_STATIC);
  98178. sqlite3VdbeSetColName(v, 3, COLNAME_NAME, "fkid", SQLITE_STATIC);
  98179. sqlite3CodeVerifySchema(pParse, iDb);
  98180. k = sqliteHashFirst(&db->aDb[iDb].pSchema->tblHash);
  98181. while( k ){
  98182. if( zRight ){
  98183. pTab = sqlite3LocateTable(pParse, 0, zRight, zDb);
  98184. k = 0;
  98185. }else{
  98186. pTab = (Table*)sqliteHashData(k);
  98187. k = sqliteHashNext(k);
  98188. }
  98189. if( pTab==0 || pTab->pFKey==0 ) continue;
  98190. sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
  98191. if( pTab->nCol+regRow>pParse->nMem ) pParse->nMem = pTab->nCol + regRow;
  98192. sqlite3OpenTable(pParse, 0, iDb, pTab, OP_OpenRead);
  98193. sqlite3VdbeAddOp4(v, OP_String8, 0, regResult, 0, pTab->zName,
  98194. P4_TRANSIENT);
  98195. for(i=1, pFK=pTab->pFKey; pFK; i++, pFK=pFK->pNextFrom){
  98196. pParent = sqlite3FindTable(db, pFK->zTo, zDb);
  98197. if( pParent==0 ) continue;
  98198. pIdx = 0;
  98199. sqlite3TableLock(pParse, iDb, pParent->tnum, 0, pParent->zName);
  98200. x = sqlite3FkLocateIndex(pParse, pParent, pFK, &pIdx, 0);
  98201. if( x==0 ){
  98202. if( pIdx==0 ){
  98203. sqlite3OpenTable(pParse, i, iDb, pParent, OP_OpenRead);
  98204. }else{
  98205. sqlite3VdbeAddOp3(v, OP_OpenRead, i, pIdx->tnum, iDb);
  98206. sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
  98207. }
  98208. }else{
  98209. k = 0;
  98210. break;
  98211. }
  98212. }
  98213. assert( pParse->nErr>0 || pFK==0 );
  98214. if( pFK ) break;
  98215. if( pParse->nTab<i ) pParse->nTab = i;
  98216. addrTop = sqlite3VdbeAddOp1(v, OP_Rewind, 0); VdbeCoverage(v);
  98217. for(i=1, pFK=pTab->pFKey; pFK; i++, pFK=pFK->pNextFrom){
  98218. pParent = sqlite3FindTable(db, pFK->zTo, zDb);
  98219. pIdx = 0;
  98220. aiCols = 0;
  98221. if( pParent ){
  98222. x = sqlite3FkLocateIndex(pParse, pParent, pFK, &pIdx, &aiCols);
  98223. assert( x==0 );
  98224. }
  98225. addrOk = sqlite3VdbeMakeLabel(v);
  98226. if( pParent && pIdx==0 ){
  98227. int iKey = pFK->aCol[0].iFrom;
  98228. assert( iKey>=0 && iKey<pTab->nCol );
  98229. if( iKey!=pTab->iPKey ){
  98230. sqlite3VdbeAddOp3(v, OP_Column, 0, iKey, regRow);
  98231. sqlite3ColumnDefault(v, pTab, iKey, regRow);
  98232. sqlite3VdbeAddOp2(v, OP_IsNull, regRow, addrOk); VdbeCoverage(v);
  98233. sqlite3VdbeAddOp2(v, OP_MustBeInt, regRow,
  98234. sqlite3VdbeCurrentAddr(v)+3); VdbeCoverage(v);
  98235. }else{
  98236. sqlite3VdbeAddOp2(v, OP_Rowid, 0, regRow);
  98237. }
  98238. sqlite3VdbeAddOp3(v, OP_NotExists, i, 0, regRow); VdbeCoverage(v);
  98239. sqlite3VdbeAddOp2(v, OP_Goto, 0, addrOk);
  98240. sqlite3VdbeJumpHere(v, sqlite3VdbeCurrentAddr(v)-2);
  98241. }else{
  98242. for(j=0; j<pFK->nCol; j++){
  98243. sqlite3ExprCodeGetColumnOfTable(v, pTab, 0,
  98244. aiCols ? aiCols[j] : pFK->aCol[j].iFrom, regRow+j);
  98245. sqlite3VdbeAddOp2(v, OP_IsNull, regRow+j, addrOk); VdbeCoverage(v);
  98246. }
  98247. if( pParent ){
  98248. sqlite3VdbeAddOp4(v, OP_MakeRecord, regRow, pFK->nCol, regKey,
  98249. sqlite3IndexAffinityStr(v,pIdx), pFK->nCol);
  98250. sqlite3VdbeAddOp4Int(v, OP_Found, i, addrOk, regKey, 0);
  98251. VdbeCoverage(v);
  98252. }
  98253. }
  98254. sqlite3VdbeAddOp2(v, OP_Rowid, 0, regResult+1);
  98255. sqlite3VdbeAddOp4(v, OP_String8, 0, regResult+2, 0,
  98256. pFK->zTo, P4_TRANSIENT);
  98257. sqlite3VdbeAddOp2(v, OP_Integer, i-1, regResult+3);
  98258. sqlite3VdbeAddOp2(v, OP_ResultRow, regResult, 4);
  98259. sqlite3VdbeResolveLabel(v, addrOk);
  98260. sqlite3DbFree(db, aiCols);
  98261. }
  98262. sqlite3VdbeAddOp2(v, OP_Next, 0, addrTop+1); VdbeCoverage(v);
  98263. sqlite3VdbeJumpHere(v, addrTop);
  98264. }
  98265. }
  98266. break;
  98267. #endif /* !defined(SQLITE_OMIT_TRIGGER) */
  98268. #endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
  98269. #ifndef NDEBUG
  98270. case PragTyp_PARSER_TRACE: {
  98271. if( zRight ){
  98272. if( sqlite3GetBoolean(zRight, 0) ){
  98273. sqlite3ParserTrace(stderr, "parser: ");
  98274. }else{
  98275. sqlite3ParserTrace(0, 0);
  98276. }
  98277. }
  98278. }
  98279. break;
  98280. #endif
  98281. /* Reinstall the LIKE and GLOB functions. The variant of LIKE
  98282. ** used will be case sensitive or not depending on the RHS.
  98283. */
  98284. case PragTyp_CASE_SENSITIVE_LIKE: {
  98285. if( zRight ){
  98286. sqlite3RegisterLikeFunctions(db, sqlite3GetBoolean(zRight, 0));
  98287. }
  98288. }
  98289. break;
  98290. #ifndef SQLITE_INTEGRITY_CHECK_ERROR_MAX
  98291. # define SQLITE_INTEGRITY_CHECK_ERROR_MAX 100
  98292. #endif
  98293. #ifndef SQLITE_OMIT_INTEGRITY_CHECK
  98294. /* Pragma "quick_check" is reduced version of
  98295. ** integrity_check designed to detect most database corruption
  98296. ** without most of the overhead of a full integrity-check.
  98297. */
  98298. case PragTyp_INTEGRITY_CHECK: {
  98299. int i, j, addr, mxErr;
  98300. /* Code that appears at the end of the integrity check. If no error
  98301. ** messages have been generated, output OK. Otherwise output the
  98302. ** error message
  98303. */
  98304. static const int iLn = VDBE_OFFSET_LINENO(2);
  98305. static const VdbeOpList endCode[] = {
  98306. { OP_IfNeg, 1, 0, 0}, /* 0 */
  98307. { OP_String8, 0, 3, 0}, /* 1 */
  98308. { OP_ResultRow, 3, 1, 0},
  98309. };
  98310. int isQuick = (sqlite3Tolower(zLeft[0])=='q');
  98311. /* If the PRAGMA command was of the form "PRAGMA <db>.integrity_check",
  98312. ** then iDb is set to the index of the database identified by <db>.
  98313. ** In this case, the integrity of database iDb only is verified by
  98314. ** the VDBE created below.
  98315. **
  98316. ** Otherwise, if the command was simply "PRAGMA integrity_check" (or
  98317. ** "PRAGMA quick_check"), then iDb is set to 0. In this case, set iDb
  98318. ** to -1 here, to indicate that the VDBE should verify the integrity
  98319. ** of all attached databases. */
  98320. assert( iDb>=0 );
  98321. assert( iDb==0 || pId2->z );
  98322. if( pId2->z==0 ) iDb = -1;
  98323. /* Initialize the VDBE program */
  98324. pParse->nMem = 6;
  98325. sqlite3VdbeSetNumCols(v, 1);
  98326. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "integrity_check", SQLITE_STATIC);
  98327. /* Set the maximum error count */
  98328. mxErr = SQLITE_INTEGRITY_CHECK_ERROR_MAX;
  98329. if( zRight ){
  98330. sqlite3GetInt32(zRight, &mxErr);
  98331. if( mxErr<=0 ){
  98332. mxErr = SQLITE_INTEGRITY_CHECK_ERROR_MAX;
  98333. }
  98334. }
  98335. sqlite3VdbeAddOp2(v, OP_Integer, mxErr, 1); /* reg[1] holds errors left */
  98336. /* Do an integrity check on each database file */
  98337. for(i=0; i<db->nDb; i++){
  98338. HashElem *x;
  98339. Hash *pTbls;
  98340. int cnt = 0;
  98341. if( OMIT_TEMPDB && i==1 ) continue;
  98342. if( iDb>=0 && i!=iDb ) continue;
  98343. sqlite3CodeVerifySchema(pParse, i);
  98344. addr = sqlite3VdbeAddOp1(v, OP_IfPos, 1); /* Halt if out of errors */
  98345. VdbeCoverage(v);
  98346. sqlite3VdbeAddOp2(v, OP_Halt, 0, 0);
  98347. sqlite3VdbeJumpHere(v, addr);
  98348. /* Do an integrity check of the B-Tree
  98349. **
  98350. ** Begin by filling registers 2, 3, ... with the root pages numbers
  98351. ** for all tables and indices in the database.
  98352. */
  98353. assert( sqlite3SchemaMutexHeld(db, i, 0) );
  98354. pTbls = &db->aDb[i].pSchema->tblHash;
  98355. for(x=sqliteHashFirst(pTbls); x; x=sqliteHashNext(x)){
  98356. Table *pTab = sqliteHashData(x);
  98357. Index *pIdx;
  98358. if( HasRowid(pTab) ){
  98359. sqlite3VdbeAddOp2(v, OP_Integer, pTab->tnum, 2+cnt);
  98360. VdbeComment((v, "%s", pTab->zName));
  98361. cnt++;
  98362. }
  98363. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  98364. sqlite3VdbeAddOp2(v, OP_Integer, pIdx->tnum, 2+cnt);
  98365. VdbeComment((v, "%s", pIdx->zName));
  98366. cnt++;
  98367. }
  98368. }
  98369. /* Make sure sufficient number of registers have been allocated */
  98370. pParse->nMem = MAX( pParse->nMem, cnt+8 );
  98371. /* Do the b-tree integrity checks */
  98372. sqlite3VdbeAddOp3(v, OP_IntegrityCk, 2, cnt, 1);
  98373. sqlite3VdbeChangeP5(v, (u8)i);
  98374. addr = sqlite3VdbeAddOp1(v, OP_IsNull, 2); VdbeCoverage(v);
  98375. sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0,
  98376. sqlite3MPrintf(db, "*** in database %s ***\n", db->aDb[i].zName),
  98377. P4_DYNAMIC);
  98378. sqlite3VdbeAddOp3(v, OP_Move, 2, 4, 1);
  98379. sqlite3VdbeAddOp3(v, OP_Concat, 4, 3, 2);
  98380. sqlite3VdbeAddOp2(v, OP_ResultRow, 2, 1);
  98381. sqlite3VdbeJumpHere(v, addr);
  98382. /* Make sure all the indices are constructed correctly.
  98383. */
  98384. for(x=sqliteHashFirst(pTbls); x && !isQuick; x=sqliteHashNext(x)){
  98385. Table *pTab = sqliteHashData(x);
  98386. Index *pIdx, *pPk;
  98387. Index *pPrior = 0;
  98388. int loopTop;
  98389. int iDataCur, iIdxCur;
  98390. int r1 = -1;
  98391. if( pTab->pIndex==0 ) continue;
  98392. pPk = HasRowid(pTab) ? 0 : sqlite3PrimaryKeyIndex(pTab);
  98393. addr = sqlite3VdbeAddOp1(v, OP_IfPos, 1); /* Stop if out of errors */
  98394. VdbeCoverage(v);
  98395. sqlite3VdbeAddOp2(v, OP_Halt, 0, 0);
  98396. sqlite3VdbeJumpHere(v, addr);
  98397. sqlite3ExprCacheClear(pParse);
  98398. sqlite3OpenTableAndIndices(pParse, pTab, OP_OpenRead,
  98399. 1, 0, &iDataCur, &iIdxCur);
  98400. sqlite3VdbeAddOp2(v, OP_Integer, 0, 7);
  98401. for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
  98402. sqlite3VdbeAddOp2(v, OP_Integer, 0, 8+j); /* index entries counter */
  98403. }
  98404. pParse->nMem = MAX(pParse->nMem, 8+j);
  98405. sqlite3VdbeAddOp2(v, OP_Rewind, iDataCur, 0); VdbeCoverage(v);
  98406. loopTop = sqlite3VdbeAddOp2(v, OP_AddImm, 7, 1);
  98407. /* Verify that all NOT NULL columns really are NOT NULL */
  98408. for(j=0; j<pTab->nCol; j++){
  98409. char *zErr;
  98410. int jmp2, jmp3;
  98411. if( j==pTab->iPKey ) continue;
  98412. if( pTab->aCol[j].notNull==0 ) continue;
  98413. sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur, j, 3);
  98414. sqlite3VdbeChangeP5(v, OPFLAG_TYPEOFARG);
  98415. jmp2 = sqlite3VdbeAddOp1(v, OP_NotNull, 3); VdbeCoverage(v);
  98416. sqlite3VdbeAddOp2(v, OP_AddImm, 1, -1); /* Decrement error limit */
  98417. zErr = sqlite3MPrintf(db, "NULL value in %s.%s", pTab->zName,
  98418. pTab->aCol[j].zName);
  98419. sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, zErr, P4_DYNAMIC);
  98420. sqlite3VdbeAddOp2(v, OP_ResultRow, 3, 1);
  98421. jmp3 = sqlite3VdbeAddOp1(v, OP_IfPos, 1); VdbeCoverage(v);
  98422. sqlite3VdbeAddOp0(v, OP_Halt);
  98423. sqlite3VdbeJumpHere(v, jmp2);
  98424. sqlite3VdbeJumpHere(v, jmp3);
  98425. }
  98426. /* Validate index entries for the current row */
  98427. for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
  98428. int jmp2, jmp3, jmp4, jmp5;
  98429. int ckUniq = sqlite3VdbeMakeLabel(v);
  98430. if( pPk==pIdx ) continue;
  98431. r1 = sqlite3GenerateIndexKey(pParse, pIdx, iDataCur, 0, 0, &jmp3,
  98432. pPrior, r1);
  98433. pPrior = pIdx;
  98434. sqlite3VdbeAddOp2(v, OP_AddImm, 8+j, 1); /* increment entry count */
  98435. /* Verify that an index entry exists for the current table row */
  98436. jmp2 = sqlite3VdbeAddOp4Int(v, OP_Found, iIdxCur+j, ckUniq, r1,
  98437. pIdx->nColumn); VdbeCoverage(v);
  98438. sqlite3VdbeAddOp2(v, OP_AddImm, 1, -1); /* Decrement error limit */
  98439. sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, "row ", P4_STATIC);
  98440. sqlite3VdbeAddOp3(v, OP_Concat, 7, 3, 3);
  98441. sqlite3VdbeAddOp4(v, OP_String8, 0, 4, 0,
  98442. " missing from index ", P4_STATIC);
  98443. sqlite3VdbeAddOp3(v, OP_Concat, 4, 3, 3);
  98444. jmp5 = sqlite3VdbeAddOp4(v, OP_String8, 0, 4, 0,
  98445. pIdx->zName, P4_TRANSIENT);
  98446. sqlite3VdbeAddOp3(v, OP_Concat, 4, 3, 3);
  98447. sqlite3VdbeAddOp2(v, OP_ResultRow, 3, 1);
  98448. jmp4 = sqlite3VdbeAddOp1(v, OP_IfPos, 1); VdbeCoverage(v);
  98449. sqlite3VdbeAddOp0(v, OP_Halt);
  98450. sqlite3VdbeJumpHere(v, jmp2);
  98451. /* For UNIQUE indexes, verify that only one entry exists with the
  98452. ** current key. The entry is unique if (1) any column is NULL
  98453. ** or (2) the next entry has a different key */
  98454. if( IsUniqueIndex(pIdx) ){
  98455. int uniqOk = sqlite3VdbeMakeLabel(v);
  98456. int jmp6;
  98457. int kk;
  98458. for(kk=0; kk<pIdx->nKeyCol; kk++){
  98459. int iCol = pIdx->aiColumn[kk];
  98460. assert( iCol>=0 && iCol<pTab->nCol );
  98461. if( pTab->aCol[iCol].notNull ) continue;
  98462. sqlite3VdbeAddOp2(v, OP_IsNull, r1+kk, uniqOk);
  98463. VdbeCoverage(v);
  98464. }
  98465. jmp6 = sqlite3VdbeAddOp1(v, OP_Next, iIdxCur+j); VdbeCoverage(v);
  98466. sqlite3VdbeAddOp2(v, OP_Goto, 0, uniqOk);
  98467. sqlite3VdbeJumpHere(v, jmp6);
  98468. sqlite3VdbeAddOp4Int(v, OP_IdxGT, iIdxCur+j, uniqOk, r1,
  98469. pIdx->nKeyCol); VdbeCoverage(v);
  98470. sqlite3VdbeAddOp2(v, OP_AddImm, 1, -1); /* Decrement error limit */
  98471. sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0,
  98472. "non-unique entry in index ", P4_STATIC);
  98473. sqlite3VdbeAddOp2(v, OP_Goto, 0, jmp5);
  98474. sqlite3VdbeResolveLabel(v, uniqOk);
  98475. }
  98476. sqlite3VdbeJumpHere(v, jmp4);
  98477. sqlite3ResolvePartIdxLabel(pParse, jmp3);
  98478. }
  98479. sqlite3VdbeAddOp2(v, OP_Next, iDataCur, loopTop); VdbeCoverage(v);
  98480. sqlite3VdbeJumpHere(v, loopTop-1);
  98481. #ifndef SQLITE_OMIT_BTREECOUNT
  98482. sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0,
  98483. "wrong # of entries in index ", P4_STATIC);
  98484. for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
  98485. if( pPk==pIdx ) continue;
  98486. addr = sqlite3VdbeCurrentAddr(v);
  98487. sqlite3VdbeAddOp2(v, OP_IfPos, 1, addr+2); VdbeCoverage(v);
  98488. sqlite3VdbeAddOp2(v, OP_Halt, 0, 0);
  98489. sqlite3VdbeAddOp2(v, OP_Count, iIdxCur+j, 3);
  98490. sqlite3VdbeAddOp3(v, OP_Eq, 8+j, addr+8, 3); VdbeCoverage(v);
  98491. sqlite3VdbeChangeP5(v, SQLITE_NOTNULL);
  98492. sqlite3VdbeAddOp2(v, OP_AddImm, 1, -1);
  98493. sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, pIdx->zName, P4_TRANSIENT);
  98494. sqlite3VdbeAddOp3(v, OP_Concat, 3, 2, 7);
  98495. sqlite3VdbeAddOp2(v, OP_ResultRow, 7, 1);
  98496. }
  98497. #endif /* SQLITE_OMIT_BTREECOUNT */
  98498. }
  98499. }
  98500. addr = sqlite3VdbeAddOpList(v, ArraySize(endCode), endCode, iLn);
  98501. sqlite3VdbeChangeP3(v, addr, -mxErr);
  98502. sqlite3VdbeJumpHere(v, addr);
  98503. sqlite3VdbeChangeP4(v, addr+1, "ok", P4_STATIC);
  98504. }
  98505. break;
  98506. #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
  98507. #ifndef SQLITE_OMIT_UTF16
  98508. /*
  98509. ** PRAGMA encoding
  98510. ** PRAGMA encoding = "utf-8"|"utf-16"|"utf-16le"|"utf-16be"
  98511. **
  98512. ** In its first form, this pragma returns the encoding of the main
  98513. ** database. If the database is not initialized, it is initialized now.
  98514. **
  98515. ** The second form of this pragma is a no-op if the main database file
  98516. ** has not already been initialized. In this case it sets the default
  98517. ** encoding that will be used for the main database file if a new file
  98518. ** is created. If an existing main database file is opened, then the
  98519. ** default text encoding for the existing database is used.
  98520. **
  98521. ** In all cases new databases created using the ATTACH command are
  98522. ** created to use the same default text encoding as the main database. If
  98523. ** the main database has not been initialized and/or created when ATTACH
  98524. ** is executed, this is done before the ATTACH operation.
  98525. **
  98526. ** In the second form this pragma sets the text encoding to be used in
  98527. ** new database files created using this database handle. It is only
  98528. ** useful if invoked immediately after the main database i
  98529. */
  98530. case PragTyp_ENCODING: {
  98531. static const struct EncName {
  98532. char *zName;
  98533. u8 enc;
  98534. } encnames[] = {
  98535. { "UTF8", SQLITE_UTF8 },
  98536. { "UTF-8", SQLITE_UTF8 }, /* Must be element [1] */
  98537. { "UTF-16le", SQLITE_UTF16LE }, /* Must be element [2] */
  98538. { "UTF-16be", SQLITE_UTF16BE }, /* Must be element [3] */
  98539. { "UTF16le", SQLITE_UTF16LE },
  98540. { "UTF16be", SQLITE_UTF16BE },
  98541. { "UTF-16", 0 }, /* SQLITE_UTF16NATIVE */
  98542. { "UTF16", 0 }, /* SQLITE_UTF16NATIVE */
  98543. { 0, 0 }
  98544. };
  98545. const struct EncName *pEnc;
  98546. if( !zRight ){ /* "PRAGMA encoding" */
  98547. if( sqlite3ReadSchema(pParse) ) goto pragma_out;
  98548. sqlite3VdbeSetNumCols(v, 1);
  98549. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "encoding", SQLITE_STATIC);
  98550. sqlite3VdbeAddOp2(v, OP_String8, 0, 1);
  98551. assert( encnames[SQLITE_UTF8].enc==SQLITE_UTF8 );
  98552. assert( encnames[SQLITE_UTF16LE].enc==SQLITE_UTF16LE );
  98553. assert( encnames[SQLITE_UTF16BE].enc==SQLITE_UTF16BE );
  98554. sqlite3VdbeChangeP4(v, -1, encnames[ENC(pParse->db)].zName, P4_STATIC);
  98555. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
  98556. }else{ /* "PRAGMA encoding = XXX" */
  98557. /* Only change the value of sqlite.enc if the database handle is not
  98558. ** initialized. If the main database exists, the new sqlite.enc value
  98559. ** will be overwritten when the schema is next loaded. If it does not
  98560. ** already exists, it will be created to use the new encoding value.
  98561. */
  98562. if(
  98563. !(DbHasProperty(db, 0, DB_SchemaLoaded)) ||
  98564. DbHasProperty(db, 0, DB_Empty)
  98565. ){
  98566. for(pEnc=&encnames[0]; pEnc->zName; pEnc++){
  98567. if( 0==sqlite3StrICmp(zRight, pEnc->zName) ){
  98568. SCHEMA_ENC(db) = ENC(db) =
  98569. pEnc->enc ? pEnc->enc : SQLITE_UTF16NATIVE;
  98570. break;
  98571. }
  98572. }
  98573. if( !pEnc->zName ){
  98574. sqlite3ErrorMsg(pParse, "unsupported encoding: %s", zRight);
  98575. }
  98576. }
  98577. }
  98578. }
  98579. break;
  98580. #endif /* SQLITE_OMIT_UTF16 */
  98581. #ifndef SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS
  98582. /*
  98583. ** PRAGMA [database.]schema_version
  98584. ** PRAGMA [database.]schema_version = <integer>
  98585. **
  98586. ** PRAGMA [database.]user_version
  98587. ** PRAGMA [database.]user_version = <integer>
  98588. **
  98589. ** PRAGMA [database.]freelist_count = <integer>
  98590. **
  98591. ** PRAGMA [database.]application_id
  98592. ** PRAGMA [database.]application_id = <integer>
  98593. **
  98594. ** The pragma's schema_version and user_version are used to set or get
  98595. ** the value of the schema-version and user-version, respectively. Both
  98596. ** the schema-version and the user-version are 32-bit signed integers
  98597. ** stored in the database header.
  98598. **
  98599. ** The schema-cookie is usually only manipulated internally by SQLite. It
  98600. ** is incremented by SQLite whenever the database schema is modified (by
  98601. ** creating or dropping a table or index). The schema version is used by
  98602. ** SQLite each time a query is executed to ensure that the internal cache
  98603. ** of the schema used when compiling the SQL query matches the schema of
  98604. ** the database against which the compiled query is actually executed.
  98605. ** Subverting this mechanism by using "PRAGMA schema_version" to modify
  98606. ** the schema-version is potentially dangerous and may lead to program
  98607. ** crashes or database corruption. Use with caution!
  98608. **
  98609. ** The user-version is not used internally by SQLite. It may be used by
  98610. ** applications for any purpose.
  98611. */
  98612. case PragTyp_HEADER_VALUE: {
  98613. int iCookie = pPragma->iArg; /* Which cookie to read or write */
  98614. sqlite3VdbeUsesBtree(v, iDb);
  98615. if( zRight && (pPragma->mPragFlag & PragFlag_ReadOnly)==0 ){
  98616. /* Write the specified cookie value */
  98617. static const VdbeOpList setCookie[] = {
  98618. { OP_Transaction, 0, 1, 0}, /* 0 */
  98619. { OP_Integer, 0, 1, 0}, /* 1 */
  98620. { OP_SetCookie, 0, 0, 1}, /* 2 */
  98621. };
  98622. int addr = sqlite3VdbeAddOpList(v, ArraySize(setCookie), setCookie, 0);
  98623. sqlite3VdbeChangeP1(v, addr, iDb);
  98624. sqlite3VdbeChangeP1(v, addr+1, sqlite3Atoi(zRight));
  98625. sqlite3VdbeChangeP1(v, addr+2, iDb);
  98626. sqlite3VdbeChangeP2(v, addr+2, iCookie);
  98627. }else{
  98628. /* Read the specified cookie value */
  98629. static const VdbeOpList readCookie[] = {
  98630. { OP_Transaction, 0, 0, 0}, /* 0 */
  98631. { OP_ReadCookie, 0, 1, 0}, /* 1 */
  98632. { OP_ResultRow, 1, 1, 0}
  98633. };
  98634. int addr = sqlite3VdbeAddOpList(v, ArraySize(readCookie), readCookie, 0);
  98635. sqlite3VdbeChangeP1(v, addr, iDb);
  98636. sqlite3VdbeChangeP1(v, addr+1, iDb);
  98637. sqlite3VdbeChangeP3(v, addr+1, iCookie);
  98638. sqlite3VdbeSetNumCols(v, 1);
  98639. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, zLeft, SQLITE_TRANSIENT);
  98640. }
  98641. }
  98642. break;
  98643. #endif /* SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS */
  98644. #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
  98645. /*
  98646. ** PRAGMA compile_options
  98647. **
  98648. ** Return the names of all compile-time options used in this build,
  98649. ** one option per row.
  98650. */
  98651. case PragTyp_COMPILE_OPTIONS: {
  98652. int i = 0;
  98653. const char *zOpt;
  98654. sqlite3VdbeSetNumCols(v, 1);
  98655. pParse->nMem = 1;
  98656. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "compile_option", SQLITE_STATIC);
  98657. while( (zOpt = sqlite3_compileoption_get(i++))!=0 ){
  98658. sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, zOpt, 0);
  98659. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
  98660. }
  98661. }
  98662. break;
  98663. #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
  98664. #ifndef SQLITE_OMIT_WAL
  98665. /*
  98666. ** PRAGMA [database.]wal_checkpoint = passive|full|restart|truncate
  98667. **
  98668. ** Checkpoint the database.
  98669. */
  98670. case PragTyp_WAL_CHECKPOINT: {
  98671. int iBt = (pId2->z?iDb:SQLITE_MAX_ATTACHED);
  98672. int eMode = SQLITE_CHECKPOINT_PASSIVE;
  98673. if( zRight ){
  98674. if( sqlite3StrICmp(zRight, "full")==0 ){
  98675. eMode = SQLITE_CHECKPOINT_FULL;
  98676. }else if( sqlite3StrICmp(zRight, "restart")==0 ){
  98677. eMode = SQLITE_CHECKPOINT_RESTART;
  98678. }else if( sqlite3StrICmp(zRight, "truncate")==0 ){
  98679. eMode = SQLITE_CHECKPOINT_TRUNCATE;
  98680. }
  98681. }
  98682. sqlite3VdbeSetNumCols(v, 3);
  98683. pParse->nMem = 3;
  98684. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "busy", SQLITE_STATIC);
  98685. sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "log", SQLITE_STATIC);
  98686. sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "checkpointed", SQLITE_STATIC);
  98687. sqlite3VdbeAddOp3(v, OP_Checkpoint, iBt, eMode, 1);
  98688. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3);
  98689. }
  98690. break;
  98691. /*
  98692. ** PRAGMA wal_autocheckpoint
  98693. ** PRAGMA wal_autocheckpoint = N
  98694. **
  98695. ** Configure a database connection to automatically checkpoint a database
  98696. ** after accumulating N frames in the log. Or query for the current value
  98697. ** of N.
  98698. */
  98699. case PragTyp_WAL_AUTOCHECKPOINT: {
  98700. if( zRight ){
  98701. sqlite3_wal_autocheckpoint(db, sqlite3Atoi(zRight));
  98702. }
  98703. returnSingleInt(pParse, "wal_autocheckpoint",
  98704. db->xWalCallback==sqlite3WalDefaultHook ?
  98705. SQLITE_PTR_TO_INT(db->pWalArg) : 0);
  98706. }
  98707. break;
  98708. #endif
  98709. /*
  98710. ** PRAGMA shrink_memory
  98711. **
  98712. ** IMPLEMENTATION-OF: R-23445-46109 This pragma causes the database
  98713. ** connection on which it is invoked to free up as much memory as it
  98714. ** can, by calling sqlite3_db_release_memory().
  98715. */
  98716. case PragTyp_SHRINK_MEMORY: {
  98717. sqlite3_db_release_memory(db);
  98718. break;
  98719. }
  98720. /*
  98721. ** PRAGMA busy_timeout
  98722. ** PRAGMA busy_timeout = N
  98723. **
  98724. ** Call sqlite3_busy_timeout(db, N). Return the current timeout value
  98725. ** if one is set. If no busy handler or a different busy handler is set
  98726. ** then 0 is returned. Setting the busy_timeout to 0 or negative
  98727. ** disables the timeout.
  98728. */
  98729. /*case PragTyp_BUSY_TIMEOUT*/ default: {
  98730. assert( pPragma->ePragTyp==PragTyp_BUSY_TIMEOUT );
  98731. if( zRight ){
  98732. sqlite3_busy_timeout(db, sqlite3Atoi(zRight));
  98733. }
  98734. returnSingleInt(pParse, "timeout", db->busyTimeout);
  98735. break;
  98736. }
  98737. /*
  98738. ** PRAGMA soft_heap_limit
  98739. ** PRAGMA soft_heap_limit = N
  98740. **
  98741. ** IMPLEMENTATION-OF: R-26343-45930 This pragma invokes the
  98742. ** sqlite3_soft_heap_limit64() interface with the argument N, if N is
  98743. ** specified and is a non-negative integer.
  98744. ** IMPLEMENTATION-OF: R-64451-07163 The soft_heap_limit pragma always
  98745. ** returns the same integer that would be returned by the
  98746. ** sqlite3_soft_heap_limit64(-1) C-language function.
  98747. */
  98748. case PragTyp_SOFT_HEAP_LIMIT: {
  98749. sqlite3_int64 N;
  98750. if( zRight && sqlite3DecOrHexToI64(zRight, &N)==SQLITE_OK ){
  98751. sqlite3_soft_heap_limit64(N);
  98752. }
  98753. returnSingleInt(pParse, "soft_heap_limit", sqlite3_soft_heap_limit64(-1));
  98754. break;
  98755. }
  98756. /*
  98757. ** PRAGMA threads
  98758. ** PRAGMA threads = N
  98759. **
  98760. ** Configure the maximum number of worker threads. Return the new
  98761. ** maximum, which might be less than requested.
  98762. */
  98763. case PragTyp_THREADS: {
  98764. sqlite3_int64 N;
  98765. if( zRight
  98766. && sqlite3DecOrHexToI64(zRight, &N)==SQLITE_OK
  98767. && N>=0
  98768. ){
  98769. sqlite3_limit(db, SQLITE_LIMIT_WORKER_THREADS, (int)(N&0x7fffffff));
  98770. }
  98771. returnSingleInt(pParse, "threads",
  98772. sqlite3_limit(db, SQLITE_LIMIT_WORKER_THREADS, -1));
  98773. break;
  98774. }
  98775. #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
  98776. /*
  98777. ** Report the current state of file logs for all databases
  98778. */
  98779. case PragTyp_LOCK_STATUS: {
  98780. static const char *const azLockName[] = {
  98781. "unlocked", "shared", "reserved", "pending", "exclusive"
  98782. };
  98783. int i;
  98784. sqlite3VdbeSetNumCols(v, 2);
  98785. pParse->nMem = 2;
  98786. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "database", SQLITE_STATIC);
  98787. sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "status", SQLITE_STATIC);
  98788. for(i=0; i<db->nDb; i++){
  98789. Btree *pBt;
  98790. const char *zState = "unknown";
  98791. int j;
  98792. if( db->aDb[i].zName==0 ) continue;
  98793. sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, db->aDb[i].zName, P4_STATIC);
  98794. pBt = db->aDb[i].pBt;
  98795. if( pBt==0 || sqlite3BtreePager(pBt)==0 ){
  98796. zState = "closed";
  98797. }else if( sqlite3_file_control(db, i ? db->aDb[i].zName : 0,
  98798. SQLITE_FCNTL_LOCKSTATE, &j)==SQLITE_OK ){
  98799. zState = azLockName[j];
  98800. }
  98801. sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, zState, P4_STATIC);
  98802. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 2);
  98803. }
  98804. break;
  98805. }
  98806. #endif
  98807. #ifdef SQLITE_HAS_CODEC
  98808. case PragTyp_KEY: {
  98809. if( zRight ) sqlite3_key_v2(db, zDb, zRight, sqlite3Strlen30(zRight));
  98810. break;
  98811. }
  98812. case PragTyp_REKEY: {
  98813. if( zRight ) sqlite3_rekey_v2(db, zDb, zRight, sqlite3Strlen30(zRight));
  98814. break;
  98815. }
  98816. case PragTyp_HEXKEY: {
  98817. if( zRight ){
  98818. u8 iByte;
  98819. int i;
  98820. char zKey[40];
  98821. for(i=0, iByte=0; i<sizeof(zKey)*2 && sqlite3Isxdigit(zRight[i]); i++){
  98822. iByte = (iByte<<4) + sqlite3HexToInt(zRight[i]);
  98823. if( (i&1)!=0 ) zKey[i/2] = iByte;
  98824. }
  98825. if( (zLeft[3] & 0xf)==0xb ){
  98826. sqlite3_key_v2(db, zDb, zKey, i/2);
  98827. }else{
  98828. sqlite3_rekey_v2(db, zDb, zKey, i/2);
  98829. }
  98830. }
  98831. break;
  98832. }
  98833. #endif
  98834. #if defined(SQLITE_HAS_CODEC) || defined(SQLITE_ENABLE_CEROD)
  98835. case PragTyp_ACTIVATE_EXTENSIONS: if( zRight ){
  98836. #ifdef SQLITE_HAS_CODEC
  98837. if( sqlite3StrNICmp(zRight, "see-", 4)==0 ){
  98838. sqlite3_activate_see(&zRight[4]);
  98839. }
  98840. #endif
  98841. #ifdef SQLITE_ENABLE_CEROD
  98842. if( sqlite3StrNICmp(zRight, "cerod-", 6)==0 ){
  98843. sqlite3_activate_cerod(&zRight[6]);
  98844. }
  98845. #endif
  98846. }
  98847. break;
  98848. #endif
  98849. } /* End of the PRAGMA switch */
  98850. pragma_out:
  98851. sqlite3DbFree(db, zLeft);
  98852. sqlite3DbFree(db, zRight);
  98853. }
  98854. #endif /* SQLITE_OMIT_PRAGMA */
  98855. /************** End of pragma.c **********************************************/
  98856. /************** Begin file prepare.c *****************************************/
  98857. /*
  98858. ** 2005 May 25
  98859. **
  98860. ** The author disclaims copyright to this source code. In place of
  98861. ** a legal notice, here is a blessing:
  98862. **
  98863. ** May you do good and not evil.
  98864. ** May you find forgiveness for yourself and forgive others.
  98865. ** May you share freely, never taking more than you give.
  98866. **
  98867. *************************************************************************
  98868. ** This file contains the implementation of the sqlite3_prepare()
  98869. ** interface, and routines that contribute to loading the database schema
  98870. ** from disk.
  98871. */
  98872. /*
  98873. ** Fill the InitData structure with an error message that indicates
  98874. ** that the database is corrupt.
  98875. */
  98876. static void corruptSchema(
  98877. InitData *pData, /* Initialization context */
  98878. const char *zObj, /* Object being parsed at the point of error */
  98879. const char *zExtra /* Error information */
  98880. ){
  98881. sqlite3 *db = pData->db;
  98882. if( !db->mallocFailed && (db->flags & SQLITE_RecoveryMode)==0 ){
  98883. if( zObj==0 ) zObj = "?";
  98884. sqlite3SetString(pData->pzErrMsg, db,
  98885. "malformed database schema (%s)", zObj);
  98886. if( zExtra ){
  98887. *pData->pzErrMsg = sqlite3MAppendf(db, *pData->pzErrMsg,
  98888. "%s - %s", *pData->pzErrMsg, zExtra);
  98889. }
  98890. }
  98891. pData->rc = db->mallocFailed ? SQLITE_NOMEM : SQLITE_CORRUPT_BKPT;
  98892. }
  98893. /*
  98894. ** This is the callback routine for the code that initializes the
  98895. ** database. See sqlite3Init() below for additional information.
  98896. ** This routine is also called from the OP_ParseSchema opcode of the VDBE.
  98897. **
  98898. ** Each callback contains the following information:
  98899. **
  98900. ** argv[0] = name of thing being created
  98901. ** argv[1] = root page number for table or index. 0 for trigger or view.
  98902. ** argv[2] = SQL text for the CREATE statement.
  98903. **
  98904. */
  98905. SQLITE_PRIVATE int sqlite3InitCallback(void *pInit, int argc, char **argv, char **NotUsed){
  98906. InitData *pData = (InitData*)pInit;
  98907. sqlite3 *db = pData->db;
  98908. int iDb = pData->iDb;
  98909. assert( argc==3 );
  98910. UNUSED_PARAMETER2(NotUsed, argc);
  98911. assert( sqlite3_mutex_held(db->mutex) );
  98912. DbClearProperty(db, iDb, DB_Empty);
  98913. if( db->mallocFailed ){
  98914. corruptSchema(pData, argv[0], 0);
  98915. return 1;
  98916. }
  98917. assert( iDb>=0 && iDb<db->nDb );
  98918. if( argv==0 ) return 0; /* Might happen if EMPTY_RESULT_CALLBACKS are on */
  98919. if( argv[1]==0 ){
  98920. corruptSchema(pData, argv[0], 0);
  98921. }else if( sqlite3_strnicmp(argv[2],"create ",7)==0 ){
  98922. /* Call the parser to process a CREATE TABLE, INDEX or VIEW.
  98923. ** But because db->init.busy is set to 1, no VDBE code is generated
  98924. ** or executed. All the parser does is build the internal data
  98925. ** structures that describe the table, index, or view.
  98926. */
  98927. int rc;
  98928. sqlite3_stmt *pStmt;
  98929. TESTONLY(int rcp); /* Return code from sqlite3_prepare() */
  98930. assert( db->init.busy );
  98931. db->init.iDb = iDb;
  98932. db->init.newTnum = sqlite3Atoi(argv[1]);
  98933. db->init.orphanTrigger = 0;
  98934. TESTONLY(rcp = ) sqlite3_prepare(db, argv[2], -1, &pStmt, 0);
  98935. rc = db->errCode;
  98936. assert( (rc&0xFF)==(rcp&0xFF) );
  98937. db->init.iDb = 0;
  98938. if( SQLITE_OK!=rc ){
  98939. if( db->init.orphanTrigger ){
  98940. assert( iDb==1 );
  98941. }else{
  98942. pData->rc = rc;
  98943. if( rc==SQLITE_NOMEM ){
  98944. db->mallocFailed = 1;
  98945. }else if( rc!=SQLITE_INTERRUPT && (rc&0xFF)!=SQLITE_LOCKED ){
  98946. corruptSchema(pData, argv[0], sqlite3_errmsg(db));
  98947. }
  98948. }
  98949. }
  98950. sqlite3_finalize(pStmt);
  98951. }else if( argv[0]==0 || (argv[2]!=0 && argv[2][0]!=0) ){
  98952. corruptSchema(pData, argv[0], 0);
  98953. }else{
  98954. /* If the SQL column is blank it means this is an index that
  98955. ** was created to be the PRIMARY KEY or to fulfill a UNIQUE
  98956. ** constraint for a CREATE TABLE. The index should have already
  98957. ** been created when we processed the CREATE TABLE. All we have
  98958. ** to do here is record the root page number for that index.
  98959. */
  98960. Index *pIndex;
  98961. pIndex = sqlite3FindIndex(db, argv[0], db->aDb[iDb].zName);
  98962. if( pIndex==0 ){
  98963. /* This can occur if there exists an index on a TEMP table which
  98964. ** has the same name as another index on a permanent index. Since
  98965. ** the permanent table is hidden by the TEMP table, we can also
  98966. ** safely ignore the index on the permanent table.
  98967. */
  98968. /* Do Nothing */;
  98969. }else if( sqlite3GetInt32(argv[1], &pIndex->tnum)==0 ){
  98970. corruptSchema(pData, argv[0], "invalid rootpage");
  98971. }
  98972. }
  98973. return 0;
  98974. }
  98975. /*
  98976. ** Attempt to read the database schema and initialize internal
  98977. ** data structures for a single database file. The index of the
  98978. ** database file is given by iDb. iDb==0 is used for the main
  98979. ** database. iDb==1 should never be used. iDb>=2 is used for
  98980. ** auxiliary databases. Return one of the SQLITE_ error codes to
  98981. ** indicate success or failure.
  98982. */
  98983. static int sqlite3InitOne(sqlite3 *db, int iDb, char **pzErrMsg){
  98984. int rc;
  98985. int i;
  98986. #ifndef SQLITE_OMIT_DEPRECATED
  98987. int size;
  98988. #endif
  98989. Table *pTab;
  98990. Db *pDb;
  98991. char const *azArg[4];
  98992. int meta[5];
  98993. InitData initData;
  98994. char const *zMasterSchema;
  98995. char const *zMasterName;
  98996. int openedTransaction = 0;
  98997. /*
  98998. ** The master database table has a structure like this
  98999. */
  99000. static const char master_schema[] =
  99001. "CREATE TABLE sqlite_master(\n"
  99002. " type text,\n"
  99003. " name text,\n"
  99004. " tbl_name text,\n"
  99005. " rootpage integer,\n"
  99006. " sql text\n"
  99007. ")"
  99008. ;
  99009. #ifndef SQLITE_OMIT_TEMPDB
  99010. static const char temp_master_schema[] =
  99011. "CREATE TEMP TABLE sqlite_temp_master(\n"
  99012. " type text,\n"
  99013. " name text,\n"
  99014. " tbl_name text,\n"
  99015. " rootpage integer,\n"
  99016. " sql text\n"
  99017. ")"
  99018. ;
  99019. #else
  99020. #define temp_master_schema 0
  99021. #endif
  99022. assert( iDb>=0 && iDb<db->nDb );
  99023. assert( db->aDb[iDb].pSchema );
  99024. assert( sqlite3_mutex_held(db->mutex) );
  99025. assert( iDb==1 || sqlite3BtreeHoldsMutex(db->aDb[iDb].pBt) );
  99026. /* zMasterSchema and zInitScript are set to point at the master schema
  99027. ** and initialisation script appropriate for the database being
  99028. ** initialized. zMasterName is the name of the master table.
  99029. */
  99030. if( !OMIT_TEMPDB && iDb==1 ){
  99031. zMasterSchema = temp_master_schema;
  99032. }else{
  99033. zMasterSchema = master_schema;
  99034. }
  99035. zMasterName = SCHEMA_TABLE(iDb);
  99036. /* Construct the schema tables. */
  99037. azArg[0] = zMasterName;
  99038. azArg[1] = "1";
  99039. azArg[2] = zMasterSchema;
  99040. azArg[3] = 0;
  99041. initData.db = db;
  99042. initData.iDb = iDb;
  99043. initData.rc = SQLITE_OK;
  99044. initData.pzErrMsg = pzErrMsg;
  99045. sqlite3InitCallback(&initData, 3, (char **)azArg, 0);
  99046. if( initData.rc ){
  99047. rc = initData.rc;
  99048. goto error_out;
  99049. }
  99050. pTab = sqlite3FindTable(db, zMasterName, db->aDb[iDb].zName);
  99051. if( ALWAYS(pTab) ){
  99052. pTab->tabFlags |= TF_Readonly;
  99053. }
  99054. /* Create a cursor to hold the database open
  99055. */
  99056. pDb = &db->aDb[iDb];
  99057. if( pDb->pBt==0 ){
  99058. if( !OMIT_TEMPDB && ALWAYS(iDb==1) ){
  99059. DbSetProperty(db, 1, DB_SchemaLoaded);
  99060. }
  99061. return SQLITE_OK;
  99062. }
  99063. /* If there is not already a read-only (or read-write) transaction opened
  99064. ** on the b-tree database, open one now. If a transaction is opened, it
  99065. ** will be closed before this function returns. */
  99066. sqlite3BtreeEnter(pDb->pBt);
  99067. if( !sqlite3BtreeIsInReadTrans(pDb->pBt) ){
  99068. rc = sqlite3BtreeBeginTrans(pDb->pBt, 0);
  99069. if( rc!=SQLITE_OK ){
  99070. sqlite3SetString(pzErrMsg, db, "%s", sqlite3ErrStr(rc));
  99071. goto initone_error_out;
  99072. }
  99073. openedTransaction = 1;
  99074. }
  99075. /* Get the database meta information.
  99076. **
  99077. ** Meta values are as follows:
  99078. ** meta[0] Schema cookie. Changes with each schema change.
  99079. ** meta[1] File format of schema layer.
  99080. ** meta[2] Size of the page cache.
  99081. ** meta[3] Largest rootpage (auto/incr_vacuum mode)
  99082. ** meta[4] Db text encoding. 1:UTF-8 2:UTF-16LE 3:UTF-16BE
  99083. ** meta[5] User version
  99084. ** meta[6] Incremental vacuum mode
  99085. ** meta[7] unused
  99086. ** meta[8] unused
  99087. ** meta[9] unused
  99088. **
  99089. ** Note: The #defined SQLITE_UTF* symbols in sqliteInt.h correspond to
  99090. ** the possible values of meta[4].
  99091. */
  99092. for(i=0; i<ArraySize(meta); i++){
  99093. sqlite3BtreeGetMeta(pDb->pBt, i+1, (u32 *)&meta[i]);
  99094. }
  99095. pDb->pSchema->schema_cookie = meta[BTREE_SCHEMA_VERSION-1];
  99096. /* If opening a non-empty database, check the text encoding. For the
  99097. ** main database, set sqlite3.enc to the encoding of the main database.
  99098. ** For an attached db, it is an error if the encoding is not the same
  99099. ** as sqlite3.enc.
  99100. */
  99101. if( meta[BTREE_TEXT_ENCODING-1] ){ /* text encoding */
  99102. if( iDb==0 ){
  99103. #ifndef SQLITE_OMIT_UTF16
  99104. u8 encoding;
  99105. /* If opening the main database, set ENC(db). */
  99106. encoding = (u8)meta[BTREE_TEXT_ENCODING-1] & 3;
  99107. if( encoding==0 ) encoding = SQLITE_UTF8;
  99108. ENC(db) = encoding;
  99109. #else
  99110. ENC(db) = SQLITE_UTF8;
  99111. #endif
  99112. }else{
  99113. /* If opening an attached database, the encoding much match ENC(db) */
  99114. if( meta[BTREE_TEXT_ENCODING-1]!=ENC(db) ){
  99115. sqlite3SetString(pzErrMsg, db, "attached databases must use the same"
  99116. " text encoding as main database");
  99117. rc = SQLITE_ERROR;
  99118. goto initone_error_out;
  99119. }
  99120. }
  99121. }else{
  99122. DbSetProperty(db, iDb, DB_Empty);
  99123. }
  99124. pDb->pSchema->enc = ENC(db);
  99125. if( pDb->pSchema->cache_size==0 ){
  99126. #ifndef SQLITE_OMIT_DEPRECATED
  99127. size = sqlite3AbsInt32(meta[BTREE_DEFAULT_CACHE_SIZE-1]);
  99128. if( size==0 ){ size = SQLITE_DEFAULT_CACHE_SIZE; }
  99129. pDb->pSchema->cache_size = size;
  99130. #else
  99131. pDb->pSchema->cache_size = SQLITE_DEFAULT_CACHE_SIZE;
  99132. #endif
  99133. sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
  99134. }
  99135. /*
  99136. ** file_format==1 Version 3.0.0.
  99137. ** file_format==2 Version 3.1.3. // ALTER TABLE ADD COLUMN
  99138. ** file_format==3 Version 3.1.4. // ditto but with non-NULL defaults
  99139. ** file_format==4 Version 3.3.0. // DESC indices. Boolean constants
  99140. */
  99141. pDb->pSchema->file_format = (u8)meta[BTREE_FILE_FORMAT-1];
  99142. if( pDb->pSchema->file_format==0 ){
  99143. pDb->pSchema->file_format = 1;
  99144. }
  99145. if( pDb->pSchema->file_format>SQLITE_MAX_FILE_FORMAT ){
  99146. sqlite3SetString(pzErrMsg, db, "unsupported file format");
  99147. rc = SQLITE_ERROR;
  99148. goto initone_error_out;
  99149. }
  99150. /* Ticket #2804: When we open a database in the newer file format,
  99151. ** clear the legacy_file_format pragma flag so that a VACUUM will
  99152. ** not downgrade the database and thus invalidate any descending
  99153. ** indices that the user might have created.
  99154. */
  99155. if( iDb==0 && meta[BTREE_FILE_FORMAT-1]>=4 ){
  99156. db->flags &= ~SQLITE_LegacyFileFmt;
  99157. }
  99158. /* Read the schema information out of the schema tables
  99159. */
  99160. assert( db->init.busy );
  99161. {
  99162. char *zSql;
  99163. zSql = sqlite3MPrintf(db,
  99164. "SELECT name, rootpage, sql FROM '%q'.%s ORDER BY rowid",
  99165. db->aDb[iDb].zName, zMasterName);
  99166. #ifndef SQLITE_OMIT_AUTHORIZATION
  99167. {
  99168. sqlite3_xauth xAuth;
  99169. xAuth = db->xAuth;
  99170. db->xAuth = 0;
  99171. #endif
  99172. rc = sqlite3_exec(db, zSql, sqlite3InitCallback, &initData, 0);
  99173. #ifndef SQLITE_OMIT_AUTHORIZATION
  99174. db->xAuth = xAuth;
  99175. }
  99176. #endif
  99177. if( rc==SQLITE_OK ) rc = initData.rc;
  99178. sqlite3DbFree(db, zSql);
  99179. #ifndef SQLITE_OMIT_ANALYZE
  99180. if( rc==SQLITE_OK ){
  99181. sqlite3AnalysisLoad(db, iDb);
  99182. }
  99183. #endif
  99184. }
  99185. if( db->mallocFailed ){
  99186. rc = SQLITE_NOMEM;
  99187. sqlite3ResetAllSchemasOfConnection(db);
  99188. }
  99189. if( rc==SQLITE_OK || (db->flags&SQLITE_RecoveryMode)){
  99190. /* Black magic: If the SQLITE_RecoveryMode flag is set, then consider
  99191. ** the schema loaded, even if errors occurred. In this situation the
  99192. ** current sqlite3_prepare() operation will fail, but the following one
  99193. ** will attempt to compile the supplied statement against whatever subset
  99194. ** of the schema was loaded before the error occurred. The primary
  99195. ** purpose of this is to allow access to the sqlite_master table
  99196. ** even when its contents have been corrupted.
  99197. */
  99198. DbSetProperty(db, iDb, DB_SchemaLoaded);
  99199. rc = SQLITE_OK;
  99200. }
  99201. /* Jump here for an error that occurs after successfully allocating
  99202. ** curMain and calling sqlite3BtreeEnter(). For an error that occurs
  99203. ** before that point, jump to error_out.
  99204. */
  99205. initone_error_out:
  99206. if( openedTransaction ){
  99207. sqlite3BtreeCommit(pDb->pBt);
  99208. }
  99209. sqlite3BtreeLeave(pDb->pBt);
  99210. error_out:
  99211. if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){
  99212. db->mallocFailed = 1;
  99213. }
  99214. return rc;
  99215. }
  99216. /*
  99217. ** Initialize all database files - the main database file, the file
  99218. ** used to store temporary tables, and any additional database files
  99219. ** created using ATTACH statements. Return a success code. If an
  99220. ** error occurs, write an error message into *pzErrMsg.
  99221. **
  99222. ** After a database is initialized, the DB_SchemaLoaded bit is set
  99223. ** bit is set in the flags field of the Db structure. If the database
  99224. ** file was of zero-length, then the DB_Empty flag is also set.
  99225. */
  99226. SQLITE_PRIVATE int sqlite3Init(sqlite3 *db, char **pzErrMsg){
  99227. int i, rc;
  99228. int commit_internal = !(db->flags&SQLITE_InternChanges);
  99229. assert( sqlite3_mutex_held(db->mutex) );
  99230. assert( sqlite3BtreeHoldsMutex(db->aDb[0].pBt) );
  99231. assert( db->init.busy==0 );
  99232. rc = SQLITE_OK;
  99233. db->init.busy = 1;
  99234. ENC(db) = SCHEMA_ENC(db);
  99235. for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
  99236. if( DbHasProperty(db, i, DB_SchemaLoaded) || i==1 ) continue;
  99237. rc = sqlite3InitOne(db, i, pzErrMsg);
  99238. if( rc ){
  99239. sqlite3ResetOneSchema(db, i);
  99240. }
  99241. }
  99242. /* Once all the other databases have been initialized, load the schema
  99243. ** for the TEMP database. This is loaded last, as the TEMP database
  99244. ** schema may contain references to objects in other databases.
  99245. */
  99246. #ifndef SQLITE_OMIT_TEMPDB
  99247. assert( db->nDb>1 );
  99248. if( rc==SQLITE_OK && !DbHasProperty(db, 1, DB_SchemaLoaded) ){
  99249. rc = sqlite3InitOne(db, 1, pzErrMsg);
  99250. if( rc ){
  99251. sqlite3ResetOneSchema(db, 1);
  99252. }
  99253. }
  99254. #endif
  99255. db->init.busy = 0;
  99256. if( rc==SQLITE_OK && commit_internal ){
  99257. sqlite3CommitInternalChanges(db);
  99258. }
  99259. return rc;
  99260. }
  99261. /*
  99262. ** This routine is a no-op if the database schema is already initialized.
  99263. ** Otherwise, the schema is loaded. An error code is returned.
  99264. */
  99265. SQLITE_PRIVATE int sqlite3ReadSchema(Parse *pParse){
  99266. int rc = SQLITE_OK;
  99267. sqlite3 *db = pParse->db;
  99268. assert( sqlite3_mutex_held(db->mutex) );
  99269. if( !db->init.busy ){
  99270. rc = sqlite3Init(db, &pParse->zErrMsg);
  99271. }
  99272. if( rc!=SQLITE_OK ){
  99273. pParse->rc = rc;
  99274. pParse->nErr++;
  99275. }
  99276. return rc;
  99277. }
  99278. /*
  99279. ** Check schema cookies in all databases. If any cookie is out
  99280. ** of date set pParse->rc to SQLITE_SCHEMA. If all schema cookies
  99281. ** make no changes to pParse->rc.
  99282. */
  99283. static void schemaIsValid(Parse *pParse){
  99284. sqlite3 *db = pParse->db;
  99285. int iDb;
  99286. int rc;
  99287. int cookie;
  99288. assert( pParse->checkSchema );
  99289. assert( sqlite3_mutex_held(db->mutex) );
  99290. for(iDb=0; iDb<db->nDb; iDb++){
  99291. int openedTransaction = 0; /* True if a transaction is opened */
  99292. Btree *pBt = db->aDb[iDb].pBt; /* Btree database to read cookie from */
  99293. if( pBt==0 ) continue;
  99294. /* If there is not already a read-only (or read-write) transaction opened
  99295. ** on the b-tree database, open one now. If a transaction is opened, it
  99296. ** will be closed immediately after reading the meta-value. */
  99297. if( !sqlite3BtreeIsInReadTrans(pBt) ){
  99298. rc = sqlite3BtreeBeginTrans(pBt, 0);
  99299. if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){
  99300. db->mallocFailed = 1;
  99301. }
  99302. if( rc!=SQLITE_OK ) return;
  99303. openedTransaction = 1;
  99304. }
  99305. /* Read the schema cookie from the database. If it does not match the
  99306. ** value stored as part of the in-memory schema representation,
  99307. ** set Parse.rc to SQLITE_SCHEMA. */
  99308. sqlite3BtreeGetMeta(pBt, BTREE_SCHEMA_VERSION, (u32 *)&cookie);
  99309. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  99310. if( cookie!=db->aDb[iDb].pSchema->schema_cookie ){
  99311. sqlite3ResetOneSchema(db, iDb);
  99312. pParse->rc = SQLITE_SCHEMA;
  99313. }
  99314. /* Close the transaction, if one was opened. */
  99315. if( openedTransaction ){
  99316. sqlite3BtreeCommit(pBt);
  99317. }
  99318. }
  99319. }
  99320. /*
  99321. ** Convert a schema pointer into the iDb index that indicates
  99322. ** which database file in db->aDb[] the schema refers to.
  99323. **
  99324. ** If the same database is attached more than once, the first
  99325. ** attached database is returned.
  99326. */
  99327. SQLITE_PRIVATE int sqlite3SchemaToIndex(sqlite3 *db, Schema *pSchema){
  99328. int i = -1000000;
  99329. /* If pSchema is NULL, then return -1000000. This happens when code in
  99330. ** expr.c is trying to resolve a reference to a transient table (i.e. one
  99331. ** created by a sub-select). In this case the return value of this
  99332. ** function should never be used.
  99333. **
  99334. ** We return -1000000 instead of the more usual -1 simply because using
  99335. ** -1000000 as the incorrect index into db->aDb[] is much
  99336. ** more likely to cause a segfault than -1 (of course there are assert()
  99337. ** statements too, but it never hurts to play the odds).
  99338. */
  99339. assert( sqlite3_mutex_held(db->mutex) );
  99340. if( pSchema ){
  99341. for(i=0; ALWAYS(i<db->nDb); i++){
  99342. if( db->aDb[i].pSchema==pSchema ){
  99343. break;
  99344. }
  99345. }
  99346. assert( i>=0 && i<db->nDb );
  99347. }
  99348. return i;
  99349. }
  99350. /*
  99351. ** Free all memory allocations in the pParse object
  99352. */
  99353. SQLITE_PRIVATE void sqlite3ParserReset(Parse *pParse){
  99354. if( pParse ){
  99355. sqlite3 *db = pParse->db;
  99356. sqlite3DbFree(db, pParse->aLabel);
  99357. sqlite3ExprListDelete(db, pParse->pConstExpr);
  99358. }
  99359. }
  99360. /*
  99361. ** Compile the UTF-8 encoded SQL statement zSql into a statement handle.
  99362. */
  99363. static int sqlite3Prepare(
  99364. sqlite3 *db, /* Database handle. */
  99365. const char *zSql, /* UTF-8 encoded SQL statement. */
  99366. int nBytes, /* Length of zSql in bytes. */
  99367. int saveSqlFlag, /* True to copy SQL text into the sqlite3_stmt */
  99368. Vdbe *pReprepare, /* VM being reprepared */
  99369. sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
  99370. const char **pzTail /* OUT: End of parsed string */
  99371. ){
  99372. Parse *pParse; /* Parsing context */
  99373. char *zErrMsg = 0; /* Error message */
  99374. int rc = SQLITE_OK; /* Result code */
  99375. int i; /* Loop counter */
  99376. /* Allocate the parsing context */
  99377. pParse = sqlite3StackAllocZero(db, sizeof(*pParse));
  99378. if( pParse==0 ){
  99379. rc = SQLITE_NOMEM;
  99380. goto end_prepare;
  99381. }
  99382. pParse->pReprepare = pReprepare;
  99383. assert( ppStmt && *ppStmt==0 );
  99384. assert( !db->mallocFailed );
  99385. assert( sqlite3_mutex_held(db->mutex) );
  99386. /* Check to verify that it is possible to get a read lock on all
  99387. ** database schemas. The inability to get a read lock indicates that
  99388. ** some other database connection is holding a write-lock, which in
  99389. ** turn means that the other connection has made uncommitted changes
  99390. ** to the schema.
  99391. **
  99392. ** Were we to proceed and prepare the statement against the uncommitted
  99393. ** schema changes and if those schema changes are subsequently rolled
  99394. ** back and different changes are made in their place, then when this
  99395. ** prepared statement goes to run the schema cookie would fail to detect
  99396. ** the schema change. Disaster would follow.
  99397. **
  99398. ** This thread is currently holding mutexes on all Btrees (because
  99399. ** of the sqlite3BtreeEnterAll() in sqlite3LockAndPrepare()) so it
  99400. ** is not possible for another thread to start a new schema change
  99401. ** while this routine is running. Hence, we do not need to hold
  99402. ** locks on the schema, we just need to make sure nobody else is
  99403. ** holding them.
  99404. **
  99405. ** Note that setting READ_UNCOMMITTED overrides most lock detection,
  99406. ** but it does *not* override schema lock detection, so this all still
  99407. ** works even if READ_UNCOMMITTED is set.
  99408. */
  99409. for(i=0; i<db->nDb; i++) {
  99410. Btree *pBt = db->aDb[i].pBt;
  99411. if( pBt ){
  99412. assert( sqlite3BtreeHoldsMutex(pBt) );
  99413. rc = sqlite3BtreeSchemaLocked(pBt);
  99414. if( rc ){
  99415. const char *zDb = db->aDb[i].zName;
  99416. sqlite3ErrorWithMsg(db, rc, "database schema is locked: %s", zDb);
  99417. testcase( db->flags & SQLITE_ReadUncommitted );
  99418. goto end_prepare;
  99419. }
  99420. }
  99421. }
  99422. sqlite3VtabUnlockList(db);
  99423. pParse->db = db;
  99424. pParse->nQueryLoop = 0; /* Logarithmic, so 0 really means 1 */
  99425. if( nBytes>=0 && (nBytes==0 || zSql[nBytes-1]!=0) ){
  99426. char *zSqlCopy;
  99427. int mxLen = db->aLimit[SQLITE_LIMIT_SQL_LENGTH];
  99428. testcase( nBytes==mxLen );
  99429. testcase( nBytes==mxLen+1 );
  99430. if( nBytes>mxLen ){
  99431. sqlite3ErrorWithMsg(db, SQLITE_TOOBIG, "statement too long");
  99432. rc = sqlite3ApiExit(db, SQLITE_TOOBIG);
  99433. goto end_prepare;
  99434. }
  99435. zSqlCopy = sqlite3DbStrNDup(db, zSql, nBytes);
  99436. if( zSqlCopy ){
  99437. sqlite3RunParser(pParse, zSqlCopy, &zErrMsg);
  99438. sqlite3DbFree(db, zSqlCopy);
  99439. pParse->zTail = &zSql[pParse->zTail-zSqlCopy];
  99440. }else{
  99441. pParse->zTail = &zSql[nBytes];
  99442. }
  99443. }else{
  99444. sqlite3RunParser(pParse, zSql, &zErrMsg);
  99445. }
  99446. assert( 0==pParse->nQueryLoop );
  99447. if( db->mallocFailed ){
  99448. pParse->rc = SQLITE_NOMEM;
  99449. }
  99450. if( pParse->rc==SQLITE_DONE ) pParse->rc = SQLITE_OK;
  99451. if( pParse->checkSchema ){
  99452. schemaIsValid(pParse);
  99453. }
  99454. if( db->mallocFailed ){
  99455. pParse->rc = SQLITE_NOMEM;
  99456. }
  99457. if( pzTail ){
  99458. *pzTail = pParse->zTail;
  99459. }
  99460. rc = pParse->rc;
  99461. #ifndef SQLITE_OMIT_EXPLAIN
  99462. if( rc==SQLITE_OK && pParse->pVdbe && pParse->explain ){
  99463. static const char * const azColName[] = {
  99464. "addr", "opcode", "p1", "p2", "p3", "p4", "p5", "comment",
  99465. "selectid", "order", "from", "detail"
  99466. };
  99467. int iFirst, mx;
  99468. if( pParse->explain==2 ){
  99469. sqlite3VdbeSetNumCols(pParse->pVdbe, 4);
  99470. iFirst = 8;
  99471. mx = 12;
  99472. }else{
  99473. sqlite3VdbeSetNumCols(pParse->pVdbe, 8);
  99474. iFirst = 0;
  99475. mx = 8;
  99476. }
  99477. for(i=iFirst; i<mx; i++){
  99478. sqlite3VdbeSetColName(pParse->pVdbe, i-iFirst, COLNAME_NAME,
  99479. azColName[i], SQLITE_STATIC);
  99480. }
  99481. }
  99482. #endif
  99483. if( db->init.busy==0 ){
  99484. Vdbe *pVdbe = pParse->pVdbe;
  99485. sqlite3VdbeSetSql(pVdbe, zSql, (int)(pParse->zTail-zSql), saveSqlFlag);
  99486. }
  99487. if( pParse->pVdbe && (rc!=SQLITE_OK || db->mallocFailed) ){
  99488. sqlite3VdbeFinalize(pParse->pVdbe);
  99489. assert(!(*ppStmt));
  99490. }else{
  99491. *ppStmt = (sqlite3_stmt*)pParse->pVdbe;
  99492. }
  99493. if( zErrMsg ){
  99494. sqlite3ErrorWithMsg(db, rc, "%s", zErrMsg);
  99495. sqlite3DbFree(db, zErrMsg);
  99496. }else{
  99497. sqlite3Error(db, rc);
  99498. }
  99499. /* Delete any TriggerPrg structures allocated while parsing this statement. */
  99500. while( pParse->pTriggerPrg ){
  99501. TriggerPrg *pT = pParse->pTriggerPrg;
  99502. pParse->pTriggerPrg = pT->pNext;
  99503. sqlite3DbFree(db, pT);
  99504. }
  99505. end_prepare:
  99506. sqlite3ParserReset(pParse);
  99507. sqlite3StackFree(db, pParse);
  99508. rc = sqlite3ApiExit(db, rc);
  99509. assert( (rc&db->errMask)==rc );
  99510. return rc;
  99511. }
  99512. static int sqlite3LockAndPrepare(
  99513. sqlite3 *db, /* Database handle. */
  99514. const char *zSql, /* UTF-8 encoded SQL statement. */
  99515. int nBytes, /* Length of zSql in bytes. */
  99516. int saveSqlFlag, /* True to copy SQL text into the sqlite3_stmt */
  99517. Vdbe *pOld, /* VM being reprepared */
  99518. sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
  99519. const char **pzTail /* OUT: End of parsed string */
  99520. ){
  99521. int rc;
  99522. #ifdef SQLITE_ENABLE_API_ARMOR
  99523. if( ppStmt==0 ) return SQLITE_MISUSE_BKPT;
  99524. #endif
  99525. *ppStmt = 0;
  99526. if( !sqlite3SafetyCheckOk(db)||zSql==0 ){
  99527. return SQLITE_MISUSE_BKPT;
  99528. }
  99529. sqlite3_mutex_enter(db->mutex);
  99530. sqlite3BtreeEnterAll(db);
  99531. rc = sqlite3Prepare(db, zSql, nBytes, saveSqlFlag, pOld, ppStmt, pzTail);
  99532. if( rc==SQLITE_SCHEMA ){
  99533. sqlite3_finalize(*ppStmt);
  99534. rc = sqlite3Prepare(db, zSql, nBytes, saveSqlFlag, pOld, ppStmt, pzTail);
  99535. }
  99536. sqlite3BtreeLeaveAll(db);
  99537. sqlite3_mutex_leave(db->mutex);
  99538. assert( rc==SQLITE_OK || *ppStmt==0 );
  99539. return rc;
  99540. }
  99541. /*
  99542. ** Rerun the compilation of a statement after a schema change.
  99543. **
  99544. ** If the statement is successfully recompiled, return SQLITE_OK. Otherwise,
  99545. ** if the statement cannot be recompiled because another connection has
  99546. ** locked the sqlite3_master table, return SQLITE_LOCKED. If any other error
  99547. ** occurs, return SQLITE_SCHEMA.
  99548. */
  99549. SQLITE_PRIVATE int sqlite3Reprepare(Vdbe *p){
  99550. int rc;
  99551. sqlite3_stmt *pNew;
  99552. const char *zSql;
  99553. sqlite3 *db;
  99554. assert( sqlite3_mutex_held(sqlite3VdbeDb(p)->mutex) );
  99555. zSql = sqlite3_sql((sqlite3_stmt *)p);
  99556. assert( zSql!=0 ); /* Reprepare only called for prepare_v2() statements */
  99557. db = sqlite3VdbeDb(p);
  99558. assert( sqlite3_mutex_held(db->mutex) );
  99559. rc = sqlite3LockAndPrepare(db, zSql, -1, 0, p, &pNew, 0);
  99560. if( rc ){
  99561. if( rc==SQLITE_NOMEM ){
  99562. db->mallocFailed = 1;
  99563. }
  99564. assert( pNew==0 );
  99565. return rc;
  99566. }else{
  99567. assert( pNew!=0 );
  99568. }
  99569. sqlite3VdbeSwap((Vdbe*)pNew, p);
  99570. sqlite3TransferBindings(pNew, (sqlite3_stmt*)p);
  99571. sqlite3VdbeResetStepResult((Vdbe*)pNew);
  99572. sqlite3VdbeFinalize((Vdbe*)pNew);
  99573. return SQLITE_OK;
  99574. }
  99575. /*
  99576. ** Two versions of the official API. Legacy and new use. In the legacy
  99577. ** version, the original SQL text is not saved in the prepared statement
  99578. ** and so if a schema change occurs, SQLITE_SCHEMA is returned by
  99579. ** sqlite3_step(). In the new version, the original SQL text is retained
  99580. ** and the statement is automatically recompiled if an schema change
  99581. ** occurs.
  99582. */
  99583. SQLITE_API int SQLITE_STDCALL sqlite3_prepare(
  99584. sqlite3 *db, /* Database handle. */
  99585. const char *zSql, /* UTF-8 encoded SQL statement. */
  99586. int nBytes, /* Length of zSql in bytes. */
  99587. sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
  99588. const char **pzTail /* OUT: End of parsed string */
  99589. ){
  99590. int rc;
  99591. rc = sqlite3LockAndPrepare(db,zSql,nBytes,0,0,ppStmt,pzTail);
  99592. assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 ); /* VERIFY: F13021 */
  99593. return rc;
  99594. }
  99595. SQLITE_API int SQLITE_STDCALL sqlite3_prepare_v2(
  99596. sqlite3 *db, /* Database handle. */
  99597. const char *zSql, /* UTF-8 encoded SQL statement. */
  99598. int nBytes, /* Length of zSql in bytes. */
  99599. sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
  99600. const char **pzTail /* OUT: End of parsed string */
  99601. ){
  99602. int rc;
  99603. rc = sqlite3LockAndPrepare(db,zSql,nBytes,1,0,ppStmt,pzTail);
  99604. assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 ); /* VERIFY: F13021 */
  99605. return rc;
  99606. }
  99607. #ifndef SQLITE_OMIT_UTF16
  99608. /*
  99609. ** Compile the UTF-16 encoded SQL statement zSql into a statement handle.
  99610. */
  99611. static int sqlite3Prepare16(
  99612. sqlite3 *db, /* Database handle. */
  99613. const void *zSql, /* UTF-16 encoded SQL statement. */
  99614. int nBytes, /* Length of zSql in bytes. */
  99615. int saveSqlFlag, /* True to save SQL text into the sqlite3_stmt */
  99616. sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
  99617. const void **pzTail /* OUT: End of parsed string */
  99618. ){
  99619. /* This function currently works by first transforming the UTF-16
  99620. ** encoded string to UTF-8, then invoking sqlite3_prepare(). The
  99621. ** tricky bit is figuring out the pointer to return in *pzTail.
  99622. */
  99623. char *zSql8;
  99624. const char *zTail8 = 0;
  99625. int rc = SQLITE_OK;
  99626. #ifdef SQLITE_ENABLE_API_ARMOR
  99627. if( ppStmt==0 ) return SQLITE_MISUSE_BKPT;
  99628. #endif
  99629. *ppStmt = 0;
  99630. if( !sqlite3SafetyCheckOk(db)||zSql==0 ){
  99631. return SQLITE_MISUSE_BKPT;
  99632. }
  99633. if( nBytes>=0 ){
  99634. int sz;
  99635. const char *z = (const char*)zSql;
  99636. for(sz=0; sz<nBytes && (z[sz]!=0 || z[sz+1]!=0); sz += 2){}
  99637. nBytes = sz;
  99638. }
  99639. sqlite3_mutex_enter(db->mutex);
  99640. zSql8 = sqlite3Utf16to8(db, zSql, nBytes, SQLITE_UTF16NATIVE);
  99641. if( zSql8 ){
  99642. rc = sqlite3LockAndPrepare(db, zSql8, -1, saveSqlFlag, 0, ppStmt, &zTail8);
  99643. }
  99644. if( zTail8 && pzTail ){
  99645. /* If sqlite3_prepare returns a tail pointer, we calculate the
  99646. ** equivalent pointer into the UTF-16 string by counting the unicode
  99647. ** characters between zSql8 and zTail8, and then returning a pointer
  99648. ** the same number of characters into the UTF-16 string.
  99649. */
  99650. int chars_parsed = sqlite3Utf8CharLen(zSql8, (int)(zTail8-zSql8));
  99651. *pzTail = (u8 *)zSql + sqlite3Utf16ByteLen(zSql, chars_parsed);
  99652. }
  99653. sqlite3DbFree(db, zSql8);
  99654. rc = sqlite3ApiExit(db, rc);
  99655. sqlite3_mutex_leave(db->mutex);
  99656. return rc;
  99657. }
  99658. /*
  99659. ** Two versions of the official API. Legacy and new use. In the legacy
  99660. ** version, the original SQL text is not saved in the prepared statement
  99661. ** and so if a schema change occurs, SQLITE_SCHEMA is returned by
  99662. ** sqlite3_step(). In the new version, the original SQL text is retained
  99663. ** and the statement is automatically recompiled if an schema change
  99664. ** occurs.
  99665. */
  99666. SQLITE_API int SQLITE_STDCALL sqlite3_prepare16(
  99667. sqlite3 *db, /* Database handle. */
  99668. const void *zSql, /* UTF-16 encoded SQL statement. */
  99669. int nBytes, /* Length of zSql in bytes. */
  99670. sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
  99671. const void **pzTail /* OUT: End of parsed string */
  99672. ){
  99673. int rc;
  99674. rc = sqlite3Prepare16(db,zSql,nBytes,0,ppStmt,pzTail);
  99675. assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 ); /* VERIFY: F13021 */
  99676. return rc;
  99677. }
  99678. SQLITE_API int SQLITE_STDCALL sqlite3_prepare16_v2(
  99679. sqlite3 *db, /* Database handle. */
  99680. const void *zSql, /* UTF-16 encoded SQL statement. */
  99681. int nBytes, /* Length of zSql in bytes. */
  99682. sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
  99683. const void **pzTail /* OUT: End of parsed string */
  99684. ){
  99685. int rc;
  99686. rc = sqlite3Prepare16(db,zSql,nBytes,1,ppStmt,pzTail);
  99687. assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 ); /* VERIFY: F13021 */
  99688. return rc;
  99689. }
  99690. #endif /* SQLITE_OMIT_UTF16 */
  99691. /************** End of prepare.c *********************************************/
  99692. /************** Begin file select.c ******************************************/
  99693. /*
  99694. ** 2001 September 15
  99695. **
  99696. ** The author disclaims copyright to this source code. In place of
  99697. ** a legal notice, here is a blessing:
  99698. **
  99699. ** May you do good and not evil.
  99700. ** May you find forgiveness for yourself and forgive others.
  99701. ** May you share freely, never taking more than you give.
  99702. **
  99703. *************************************************************************
  99704. ** This file contains C code routines that are called by the parser
  99705. ** to handle SELECT statements in SQLite.
  99706. */
  99707. /*
  99708. ** Trace output macros
  99709. */
  99710. #if SELECTTRACE_ENABLED
  99711. /***/ int sqlite3SelectTrace = 0;
  99712. # define SELECTTRACE(K,P,S,X) \
  99713. if(sqlite3SelectTrace&(K)) \
  99714. sqlite3DebugPrintf("%*s%s.%p: ",(P)->nSelectIndent*2-2,"",(S)->zSelName,(S)),\
  99715. sqlite3DebugPrintf X
  99716. #else
  99717. # define SELECTTRACE(K,P,S,X)
  99718. #endif
  99719. /*
  99720. ** An instance of the following object is used to record information about
  99721. ** how to process the DISTINCT keyword, to simplify passing that information
  99722. ** into the selectInnerLoop() routine.
  99723. */
  99724. typedef struct DistinctCtx DistinctCtx;
  99725. struct DistinctCtx {
  99726. u8 isTnct; /* True if the DISTINCT keyword is present */
  99727. u8 eTnctType; /* One of the WHERE_DISTINCT_* operators */
  99728. int tabTnct; /* Ephemeral table used for DISTINCT processing */
  99729. int addrTnct; /* Address of OP_OpenEphemeral opcode for tabTnct */
  99730. };
  99731. /*
  99732. ** An instance of the following object is used to record information about
  99733. ** the ORDER BY (or GROUP BY) clause of query is being coded.
  99734. */
  99735. typedef struct SortCtx SortCtx;
  99736. struct SortCtx {
  99737. ExprList *pOrderBy; /* The ORDER BY (or GROUP BY clause) */
  99738. int nOBSat; /* Number of ORDER BY terms satisfied by indices */
  99739. int iECursor; /* Cursor number for the sorter */
  99740. int regReturn; /* Register holding block-output return address */
  99741. int labelBkOut; /* Start label for the block-output subroutine */
  99742. int addrSortIndex; /* Address of the OP_SorterOpen or OP_OpenEphemeral */
  99743. u8 sortFlags; /* Zero or more SORTFLAG_* bits */
  99744. };
  99745. #define SORTFLAG_UseSorter 0x01 /* Use SorterOpen instead of OpenEphemeral */
  99746. /*
  99747. ** Delete all the content of a Select structure. Deallocate the structure
  99748. ** itself only if bFree is true.
  99749. */
  99750. static void clearSelect(sqlite3 *db, Select *p, int bFree){
  99751. while( p ){
  99752. Select *pPrior = p->pPrior;
  99753. sqlite3ExprListDelete(db, p->pEList);
  99754. sqlite3SrcListDelete(db, p->pSrc);
  99755. sqlite3ExprDelete(db, p->pWhere);
  99756. sqlite3ExprListDelete(db, p->pGroupBy);
  99757. sqlite3ExprDelete(db, p->pHaving);
  99758. sqlite3ExprListDelete(db, p->pOrderBy);
  99759. sqlite3ExprDelete(db, p->pLimit);
  99760. sqlite3ExprDelete(db, p->pOffset);
  99761. sqlite3WithDelete(db, p->pWith);
  99762. if( bFree ) sqlite3DbFree(db, p);
  99763. p = pPrior;
  99764. bFree = 1;
  99765. }
  99766. }
  99767. /*
  99768. ** Initialize a SelectDest structure.
  99769. */
  99770. SQLITE_PRIVATE void sqlite3SelectDestInit(SelectDest *pDest, int eDest, int iParm){
  99771. pDest->eDest = (u8)eDest;
  99772. pDest->iSDParm = iParm;
  99773. pDest->affSdst = 0;
  99774. pDest->iSdst = 0;
  99775. pDest->nSdst = 0;
  99776. }
  99777. /*
  99778. ** Allocate a new Select structure and return a pointer to that
  99779. ** structure.
  99780. */
  99781. SQLITE_PRIVATE Select *sqlite3SelectNew(
  99782. Parse *pParse, /* Parsing context */
  99783. ExprList *pEList, /* which columns to include in the result */
  99784. SrcList *pSrc, /* the FROM clause -- which tables to scan */
  99785. Expr *pWhere, /* the WHERE clause */
  99786. ExprList *pGroupBy, /* the GROUP BY clause */
  99787. Expr *pHaving, /* the HAVING clause */
  99788. ExprList *pOrderBy, /* the ORDER BY clause */
  99789. u16 selFlags, /* Flag parameters, such as SF_Distinct */
  99790. Expr *pLimit, /* LIMIT value. NULL means not used */
  99791. Expr *pOffset /* OFFSET value. NULL means no offset */
  99792. ){
  99793. Select *pNew;
  99794. Select standin;
  99795. sqlite3 *db = pParse->db;
  99796. pNew = sqlite3DbMallocZero(db, sizeof(*pNew) );
  99797. if( pNew==0 ){
  99798. assert( db->mallocFailed );
  99799. pNew = &standin;
  99800. memset(pNew, 0, sizeof(*pNew));
  99801. }
  99802. if( pEList==0 ){
  99803. pEList = sqlite3ExprListAppend(pParse, 0, sqlite3Expr(db,TK_ALL,0));
  99804. }
  99805. pNew->pEList = pEList;
  99806. if( pSrc==0 ) pSrc = sqlite3DbMallocZero(db, sizeof(*pSrc));
  99807. pNew->pSrc = pSrc;
  99808. pNew->pWhere = pWhere;
  99809. pNew->pGroupBy = pGroupBy;
  99810. pNew->pHaving = pHaving;
  99811. pNew->pOrderBy = pOrderBy;
  99812. pNew->selFlags = selFlags;
  99813. pNew->op = TK_SELECT;
  99814. pNew->pLimit = pLimit;
  99815. pNew->pOffset = pOffset;
  99816. assert( pOffset==0 || pLimit!=0 || pParse->nErr>0 || db->mallocFailed!=0 );
  99817. pNew->addrOpenEphm[0] = -1;
  99818. pNew->addrOpenEphm[1] = -1;
  99819. if( db->mallocFailed ) {
  99820. clearSelect(db, pNew, pNew!=&standin);
  99821. pNew = 0;
  99822. }else{
  99823. assert( pNew->pSrc!=0 || pParse->nErr>0 );
  99824. }
  99825. assert( pNew!=&standin );
  99826. return pNew;
  99827. }
  99828. #if SELECTTRACE_ENABLED
  99829. /*
  99830. ** Set the name of a Select object
  99831. */
  99832. SQLITE_PRIVATE void sqlite3SelectSetName(Select *p, const char *zName){
  99833. if( p && zName ){
  99834. sqlite3_snprintf(sizeof(p->zSelName), p->zSelName, "%s", zName);
  99835. }
  99836. }
  99837. #endif
  99838. /*
  99839. ** Delete the given Select structure and all of its substructures.
  99840. */
  99841. SQLITE_PRIVATE void sqlite3SelectDelete(sqlite3 *db, Select *p){
  99842. clearSelect(db, p, 1);
  99843. }
  99844. /*
  99845. ** Return a pointer to the right-most SELECT statement in a compound.
  99846. */
  99847. static Select *findRightmost(Select *p){
  99848. while( p->pNext ) p = p->pNext;
  99849. return p;
  99850. }
  99851. /*
  99852. ** Given 1 to 3 identifiers preceding the JOIN keyword, determine the
  99853. ** type of join. Return an integer constant that expresses that type
  99854. ** in terms of the following bit values:
  99855. **
  99856. ** JT_INNER
  99857. ** JT_CROSS
  99858. ** JT_OUTER
  99859. ** JT_NATURAL
  99860. ** JT_LEFT
  99861. ** JT_RIGHT
  99862. **
  99863. ** A full outer join is the combination of JT_LEFT and JT_RIGHT.
  99864. **
  99865. ** If an illegal or unsupported join type is seen, then still return
  99866. ** a join type, but put an error in the pParse structure.
  99867. */
  99868. SQLITE_PRIVATE int sqlite3JoinType(Parse *pParse, Token *pA, Token *pB, Token *pC){
  99869. int jointype = 0;
  99870. Token *apAll[3];
  99871. Token *p;
  99872. /* 0123456789 123456789 123456789 123 */
  99873. static const char zKeyText[] = "naturaleftouterightfullinnercross";
  99874. static const struct {
  99875. u8 i; /* Beginning of keyword text in zKeyText[] */
  99876. u8 nChar; /* Length of the keyword in characters */
  99877. u8 code; /* Join type mask */
  99878. } aKeyword[] = {
  99879. /* natural */ { 0, 7, JT_NATURAL },
  99880. /* left */ { 6, 4, JT_LEFT|JT_OUTER },
  99881. /* outer */ { 10, 5, JT_OUTER },
  99882. /* right */ { 14, 5, JT_RIGHT|JT_OUTER },
  99883. /* full */ { 19, 4, JT_LEFT|JT_RIGHT|JT_OUTER },
  99884. /* inner */ { 23, 5, JT_INNER },
  99885. /* cross */ { 28, 5, JT_INNER|JT_CROSS },
  99886. };
  99887. int i, j;
  99888. apAll[0] = pA;
  99889. apAll[1] = pB;
  99890. apAll[2] = pC;
  99891. for(i=0; i<3 && apAll[i]; i++){
  99892. p = apAll[i];
  99893. for(j=0; j<ArraySize(aKeyword); j++){
  99894. if( p->n==aKeyword[j].nChar
  99895. && sqlite3StrNICmp((char*)p->z, &zKeyText[aKeyword[j].i], p->n)==0 ){
  99896. jointype |= aKeyword[j].code;
  99897. break;
  99898. }
  99899. }
  99900. testcase( j==0 || j==1 || j==2 || j==3 || j==4 || j==5 || j==6 );
  99901. if( j>=ArraySize(aKeyword) ){
  99902. jointype |= JT_ERROR;
  99903. break;
  99904. }
  99905. }
  99906. if(
  99907. (jointype & (JT_INNER|JT_OUTER))==(JT_INNER|JT_OUTER) ||
  99908. (jointype & JT_ERROR)!=0
  99909. ){
  99910. const char *zSp = " ";
  99911. assert( pB!=0 );
  99912. if( pC==0 ){ zSp++; }
  99913. sqlite3ErrorMsg(pParse, "unknown or unsupported join type: "
  99914. "%T %T%s%T", pA, pB, zSp, pC);
  99915. jointype = JT_INNER;
  99916. }else if( (jointype & JT_OUTER)!=0
  99917. && (jointype & (JT_LEFT|JT_RIGHT))!=JT_LEFT ){
  99918. sqlite3ErrorMsg(pParse,
  99919. "RIGHT and FULL OUTER JOINs are not currently supported");
  99920. jointype = JT_INNER;
  99921. }
  99922. return jointype;
  99923. }
  99924. /*
  99925. ** Return the index of a column in a table. Return -1 if the column
  99926. ** is not contained in the table.
  99927. */
  99928. static int columnIndex(Table *pTab, const char *zCol){
  99929. int i;
  99930. for(i=0; i<pTab->nCol; i++){
  99931. if( sqlite3StrICmp(pTab->aCol[i].zName, zCol)==0 ) return i;
  99932. }
  99933. return -1;
  99934. }
  99935. /*
  99936. ** Search the first N tables in pSrc, from left to right, looking for a
  99937. ** table that has a column named zCol.
  99938. **
  99939. ** When found, set *piTab and *piCol to the table index and column index
  99940. ** of the matching column and return TRUE.
  99941. **
  99942. ** If not found, return FALSE.
  99943. */
  99944. static int tableAndColumnIndex(
  99945. SrcList *pSrc, /* Array of tables to search */
  99946. int N, /* Number of tables in pSrc->a[] to search */
  99947. const char *zCol, /* Name of the column we are looking for */
  99948. int *piTab, /* Write index of pSrc->a[] here */
  99949. int *piCol /* Write index of pSrc->a[*piTab].pTab->aCol[] here */
  99950. ){
  99951. int i; /* For looping over tables in pSrc */
  99952. int iCol; /* Index of column matching zCol */
  99953. assert( (piTab==0)==(piCol==0) ); /* Both or neither are NULL */
  99954. for(i=0; i<N; i++){
  99955. iCol = columnIndex(pSrc->a[i].pTab, zCol);
  99956. if( iCol>=0 ){
  99957. if( piTab ){
  99958. *piTab = i;
  99959. *piCol = iCol;
  99960. }
  99961. return 1;
  99962. }
  99963. }
  99964. return 0;
  99965. }
  99966. /*
  99967. ** This function is used to add terms implied by JOIN syntax to the
  99968. ** WHERE clause expression of a SELECT statement. The new term, which
  99969. ** is ANDed with the existing WHERE clause, is of the form:
  99970. **
  99971. ** (tab1.col1 = tab2.col2)
  99972. **
  99973. ** where tab1 is the iSrc'th table in SrcList pSrc and tab2 is the
  99974. ** (iSrc+1)'th. Column col1 is column iColLeft of tab1, and col2 is
  99975. ** column iColRight of tab2.
  99976. */
  99977. static void addWhereTerm(
  99978. Parse *pParse, /* Parsing context */
  99979. SrcList *pSrc, /* List of tables in FROM clause */
  99980. int iLeft, /* Index of first table to join in pSrc */
  99981. int iColLeft, /* Index of column in first table */
  99982. int iRight, /* Index of second table in pSrc */
  99983. int iColRight, /* Index of column in second table */
  99984. int isOuterJoin, /* True if this is an OUTER join */
  99985. Expr **ppWhere /* IN/OUT: The WHERE clause to add to */
  99986. ){
  99987. sqlite3 *db = pParse->db;
  99988. Expr *pE1;
  99989. Expr *pE2;
  99990. Expr *pEq;
  99991. assert( iLeft<iRight );
  99992. assert( pSrc->nSrc>iRight );
  99993. assert( pSrc->a[iLeft].pTab );
  99994. assert( pSrc->a[iRight].pTab );
  99995. pE1 = sqlite3CreateColumnExpr(db, pSrc, iLeft, iColLeft);
  99996. pE2 = sqlite3CreateColumnExpr(db, pSrc, iRight, iColRight);
  99997. pEq = sqlite3PExpr(pParse, TK_EQ, pE1, pE2, 0);
  99998. if( pEq && isOuterJoin ){
  99999. ExprSetProperty(pEq, EP_FromJoin);
  100000. assert( !ExprHasProperty(pEq, EP_TokenOnly|EP_Reduced) );
  100001. ExprSetVVAProperty(pEq, EP_NoReduce);
  100002. pEq->iRightJoinTable = (i16)pE2->iTable;
  100003. }
  100004. *ppWhere = sqlite3ExprAnd(db, *ppWhere, pEq);
  100005. }
  100006. /*
  100007. ** Set the EP_FromJoin property on all terms of the given expression.
  100008. ** And set the Expr.iRightJoinTable to iTable for every term in the
  100009. ** expression.
  100010. **
  100011. ** The EP_FromJoin property is used on terms of an expression to tell
  100012. ** the LEFT OUTER JOIN processing logic that this term is part of the
  100013. ** join restriction specified in the ON or USING clause and not a part
  100014. ** of the more general WHERE clause. These terms are moved over to the
  100015. ** WHERE clause during join processing but we need to remember that they
  100016. ** originated in the ON or USING clause.
  100017. **
  100018. ** The Expr.iRightJoinTable tells the WHERE clause processing that the
  100019. ** expression depends on table iRightJoinTable even if that table is not
  100020. ** explicitly mentioned in the expression. That information is needed
  100021. ** for cases like this:
  100022. **
  100023. ** SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.b AND t1.x=5
  100024. **
  100025. ** The where clause needs to defer the handling of the t1.x=5
  100026. ** term until after the t2 loop of the join. In that way, a
  100027. ** NULL t2 row will be inserted whenever t1.x!=5. If we do not
  100028. ** defer the handling of t1.x=5, it will be processed immediately
  100029. ** after the t1 loop and rows with t1.x!=5 will never appear in
  100030. ** the output, which is incorrect.
  100031. */
  100032. static void setJoinExpr(Expr *p, int iTable){
  100033. while( p ){
  100034. ExprSetProperty(p, EP_FromJoin);
  100035. assert( !ExprHasProperty(p, EP_TokenOnly|EP_Reduced) );
  100036. ExprSetVVAProperty(p, EP_NoReduce);
  100037. p->iRightJoinTable = (i16)iTable;
  100038. setJoinExpr(p->pLeft, iTable);
  100039. p = p->pRight;
  100040. }
  100041. }
  100042. /*
  100043. ** This routine processes the join information for a SELECT statement.
  100044. ** ON and USING clauses are converted into extra terms of the WHERE clause.
  100045. ** NATURAL joins also create extra WHERE clause terms.
  100046. **
  100047. ** The terms of a FROM clause are contained in the Select.pSrc structure.
  100048. ** The left most table is the first entry in Select.pSrc. The right-most
  100049. ** table is the last entry. The join operator is held in the entry to
  100050. ** the left. Thus entry 0 contains the join operator for the join between
  100051. ** entries 0 and 1. Any ON or USING clauses associated with the join are
  100052. ** also attached to the left entry.
  100053. **
  100054. ** This routine returns the number of errors encountered.
  100055. */
  100056. static int sqliteProcessJoin(Parse *pParse, Select *p){
  100057. SrcList *pSrc; /* All tables in the FROM clause */
  100058. int i, j; /* Loop counters */
  100059. struct SrcList_item *pLeft; /* Left table being joined */
  100060. struct SrcList_item *pRight; /* Right table being joined */
  100061. pSrc = p->pSrc;
  100062. pLeft = &pSrc->a[0];
  100063. pRight = &pLeft[1];
  100064. for(i=0; i<pSrc->nSrc-1; i++, pRight++, pLeft++){
  100065. Table *pLeftTab = pLeft->pTab;
  100066. Table *pRightTab = pRight->pTab;
  100067. int isOuter;
  100068. if( NEVER(pLeftTab==0 || pRightTab==0) ) continue;
  100069. isOuter = (pRight->jointype & JT_OUTER)!=0;
  100070. /* When the NATURAL keyword is present, add WHERE clause terms for
  100071. ** every column that the two tables have in common.
  100072. */
  100073. if( pRight->jointype & JT_NATURAL ){
  100074. if( pRight->pOn || pRight->pUsing ){
  100075. sqlite3ErrorMsg(pParse, "a NATURAL join may not have "
  100076. "an ON or USING clause", 0);
  100077. return 1;
  100078. }
  100079. for(j=0; j<pRightTab->nCol; j++){
  100080. char *zName; /* Name of column in the right table */
  100081. int iLeft; /* Matching left table */
  100082. int iLeftCol; /* Matching column in the left table */
  100083. zName = pRightTab->aCol[j].zName;
  100084. if( tableAndColumnIndex(pSrc, i+1, zName, &iLeft, &iLeftCol) ){
  100085. addWhereTerm(pParse, pSrc, iLeft, iLeftCol, i+1, j,
  100086. isOuter, &p->pWhere);
  100087. }
  100088. }
  100089. }
  100090. /* Disallow both ON and USING clauses in the same join
  100091. */
  100092. if( pRight->pOn && pRight->pUsing ){
  100093. sqlite3ErrorMsg(pParse, "cannot have both ON and USING "
  100094. "clauses in the same join");
  100095. return 1;
  100096. }
  100097. /* Add the ON clause to the end of the WHERE clause, connected by
  100098. ** an AND operator.
  100099. */
  100100. if( pRight->pOn ){
  100101. if( isOuter ) setJoinExpr(pRight->pOn, pRight->iCursor);
  100102. p->pWhere = sqlite3ExprAnd(pParse->db, p->pWhere, pRight->pOn);
  100103. pRight->pOn = 0;
  100104. }
  100105. /* Create extra terms on the WHERE clause for each column named
  100106. ** in the USING clause. Example: If the two tables to be joined are
  100107. ** A and B and the USING clause names X, Y, and Z, then add this
  100108. ** to the WHERE clause: A.X=B.X AND A.Y=B.Y AND A.Z=B.Z
  100109. ** Report an error if any column mentioned in the USING clause is
  100110. ** not contained in both tables to be joined.
  100111. */
  100112. if( pRight->pUsing ){
  100113. IdList *pList = pRight->pUsing;
  100114. for(j=0; j<pList->nId; j++){
  100115. char *zName; /* Name of the term in the USING clause */
  100116. int iLeft; /* Table on the left with matching column name */
  100117. int iLeftCol; /* Column number of matching column on the left */
  100118. int iRightCol; /* Column number of matching column on the right */
  100119. zName = pList->a[j].zName;
  100120. iRightCol = columnIndex(pRightTab, zName);
  100121. if( iRightCol<0
  100122. || !tableAndColumnIndex(pSrc, i+1, zName, &iLeft, &iLeftCol)
  100123. ){
  100124. sqlite3ErrorMsg(pParse, "cannot join using column %s - column "
  100125. "not present in both tables", zName);
  100126. return 1;
  100127. }
  100128. addWhereTerm(pParse, pSrc, iLeft, iLeftCol, i+1, iRightCol,
  100129. isOuter, &p->pWhere);
  100130. }
  100131. }
  100132. }
  100133. return 0;
  100134. }
  100135. /* Forward reference */
  100136. static KeyInfo *keyInfoFromExprList(
  100137. Parse *pParse, /* Parsing context */
  100138. ExprList *pList, /* Form the KeyInfo object from this ExprList */
  100139. int iStart, /* Begin with this column of pList */
  100140. int nExtra /* Add this many extra columns to the end */
  100141. );
  100142. /*
  100143. ** Generate code that will push the record in registers regData
  100144. ** through regData+nData-1 onto the sorter.
  100145. */
  100146. static void pushOntoSorter(
  100147. Parse *pParse, /* Parser context */
  100148. SortCtx *pSort, /* Information about the ORDER BY clause */
  100149. Select *pSelect, /* The whole SELECT statement */
  100150. int regData, /* First register holding data to be sorted */
  100151. int nData, /* Number of elements in the data array */
  100152. int nPrefixReg /* No. of reg prior to regData available for use */
  100153. ){
  100154. Vdbe *v = pParse->pVdbe; /* Stmt under construction */
  100155. int bSeq = ((pSort->sortFlags & SORTFLAG_UseSorter)==0);
  100156. int nExpr = pSort->pOrderBy->nExpr; /* No. of ORDER BY terms */
  100157. int nBase = nExpr + bSeq + nData; /* Fields in sorter record */
  100158. int regBase; /* Regs for sorter record */
  100159. int regRecord = ++pParse->nMem; /* Assembled sorter record */
  100160. int nOBSat = pSort->nOBSat; /* ORDER BY terms to skip */
  100161. int op; /* Opcode to add sorter record to sorter */
  100162. assert( bSeq==0 || bSeq==1 );
  100163. if( nPrefixReg ){
  100164. assert( nPrefixReg==nExpr+bSeq );
  100165. regBase = regData - nExpr - bSeq;
  100166. }else{
  100167. regBase = pParse->nMem + 1;
  100168. pParse->nMem += nBase;
  100169. }
  100170. sqlite3ExprCodeExprList(pParse, pSort->pOrderBy, regBase, SQLITE_ECEL_DUP);
  100171. if( bSeq ){
  100172. sqlite3VdbeAddOp2(v, OP_Sequence, pSort->iECursor, regBase+nExpr);
  100173. }
  100174. if( nPrefixReg==0 ){
  100175. sqlite3ExprCodeMove(pParse, regData, regBase+nExpr+bSeq, nData);
  100176. }
  100177. sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase+nOBSat, nBase-nOBSat, regRecord);
  100178. if( nOBSat>0 ){
  100179. int regPrevKey; /* The first nOBSat columns of the previous row */
  100180. int addrFirst; /* Address of the OP_IfNot opcode */
  100181. int addrJmp; /* Address of the OP_Jump opcode */
  100182. VdbeOp *pOp; /* Opcode that opens the sorter */
  100183. int nKey; /* Number of sorting key columns, including OP_Sequence */
  100184. KeyInfo *pKI; /* Original KeyInfo on the sorter table */
  100185. regPrevKey = pParse->nMem+1;
  100186. pParse->nMem += pSort->nOBSat;
  100187. nKey = nExpr - pSort->nOBSat + bSeq;
  100188. if( bSeq ){
  100189. addrFirst = sqlite3VdbeAddOp1(v, OP_IfNot, regBase+nExpr);
  100190. }else{
  100191. addrFirst = sqlite3VdbeAddOp1(v, OP_SequenceTest, pSort->iECursor);
  100192. }
  100193. VdbeCoverage(v);
  100194. sqlite3VdbeAddOp3(v, OP_Compare, regPrevKey, regBase, pSort->nOBSat);
  100195. pOp = sqlite3VdbeGetOp(v, pSort->addrSortIndex);
  100196. if( pParse->db->mallocFailed ) return;
  100197. pOp->p2 = nKey + nData;
  100198. pKI = pOp->p4.pKeyInfo;
  100199. memset(pKI->aSortOrder, 0, pKI->nField); /* Makes OP_Jump below testable */
  100200. sqlite3VdbeChangeP4(v, -1, (char*)pKI, P4_KEYINFO);
  100201. testcase( pKI->nXField>2 );
  100202. pOp->p4.pKeyInfo = keyInfoFromExprList(pParse, pSort->pOrderBy, nOBSat,
  100203. pKI->nXField-1);
  100204. addrJmp = sqlite3VdbeCurrentAddr(v);
  100205. sqlite3VdbeAddOp3(v, OP_Jump, addrJmp+1, 0, addrJmp+1); VdbeCoverage(v);
  100206. pSort->labelBkOut = sqlite3VdbeMakeLabel(v);
  100207. pSort->regReturn = ++pParse->nMem;
  100208. sqlite3VdbeAddOp2(v, OP_Gosub, pSort->regReturn, pSort->labelBkOut);
  100209. sqlite3VdbeAddOp1(v, OP_ResetSorter, pSort->iECursor);
  100210. sqlite3VdbeJumpHere(v, addrFirst);
  100211. sqlite3ExprCodeMove(pParse, regBase, regPrevKey, pSort->nOBSat);
  100212. sqlite3VdbeJumpHere(v, addrJmp);
  100213. }
  100214. if( pSort->sortFlags & SORTFLAG_UseSorter ){
  100215. op = OP_SorterInsert;
  100216. }else{
  100217. op = OP_IdxInsert;
  100218. }
  100219. sqlite3VdbeAddOp2(v, op, pSort->iECursor, regRecord);
  100220. if( pSelect->iLimit ){
  100221. int addr;
  100222. int iLimit;
  100223. if( pSelect->iOffset ){
  100224. iLimit = pSelect->iOffset+1;
  100225. }else{
  100226. iLimit = pSelect->iLimit;
  100227. }
  100228. addr = sqlite3VdbeAddOp3(v, OP_IfNotZero, iLimit, 0, -1); VdbeCoverage(v);
  100229. sqlite3VdbeAddOp1(v, OP_Last, pSort->iECursor);
  100230. sqlite3VdbeAddOp1(v, OP_Delete, pSort->iECursor);
  100231. sqlite3VdbeJumpHere(v, addr);
  100232. }
  100233. }
  100234. /*
  100235. ** Add code to implement the OFFSET
  100236. */
  100237. static void codeOffset(
  100238. Vdbe *v, /* Generate code into this VM */
  100239. int iOffset, /* Register holding the offset counter */
  100240. int iContinue /* Jump here to skip the current record */
  100241. ){
  100242. if( iOffset>0 ){
  100243. int addr;
  100244. addr = sqlite3VdbeAddOp3(v, OP_IfNeg, iOffset, 0, -1); VdbeCoverage(v);
  100245. sqlite3VdbeAddOp2(v, OP_Goto, 0, iContinue);
  100246. VdbeComment((v, "skip OFFSET records"));
  100247. sqlite3VdbeJumpHere(v, addr);
  100248. }
  100249. }
  100250. /*
  100251. ** Add code that will check to make sure the N registers starting at iMem
  100252. ** form a distinct entry. iTab is a sorting index that holds previously
  100253. ** seen combinations of the N values. A new entry is made in iTab
  100254. ** if the current N values are new.
  100255. **
  100256. ** A jump to addrRepeat is made and the N+1 values are popped from the
  100257. ** stack if the top N elements are not distinct.
  100258. */
  100259. static void codeDistinct(
  100260. Parse *pParse, /* Parsing and code generating context */
  100261. int iTab, /* A sorting index used to test for distinctness */
  100262. int addrRepeat, /* Jump to here if not distinct */
  100263. int N, /* Number of elements */
  100264. int iMem /* First element */
  100265. ){
  100266. Vdbe *v;
  100267. int r1;
  100268. v = pParse->pVdbe;
  100269. r1 = sqlite3GetTempReg(pParse);
  100270. sqlite3VdbeAddOp4Int(v, OP_Found, iTab, addrRepeat, iMem, N); VdbeCoverage(v);
  100271. sqlite3VdbeAddOp3(v, OP_MakeRecord, iMem, N, r1);
  100272. sqlite3VdbeAddOp2(v, OP_IdxInsert, iTab, r1);
  100273. sqlite3ReleaseTempReg(pParse, r1);
  100274. }
  100275. #ifndef SQLITE_OMIT_SUBQUERY
  100276. /*
  100277. ** Generate an error message when a SELECT is used within a subexpression
  100278. ** (example: "a IN (SELECT * FROM table)") but it has more than 1 result
  100279. ** column. We do this in a subroutine because the error used to occur
  100280. ** in multiple places. (The error only occurs in one place now, but we
  100281. ** retain the subroutine to minimize code disruption.)
  100282. */
  100283. static int checkForMultiColumnSelectError(
  100284. Parse *pParse, /* Parse context. */
  100285. SelectDest *pDest, /* Destination of SELECT results */
  100286. int nExpr /* Number of result columns returned by SELECT */
  100287. ){
  100288. int eDest = pDest->eDest;
  100289. if( nExpr>1 && (eDest==SRT_Mem || eDest==SRT_Set) ){
  100290. sqlite3ErrorMsg(pParse, "only a single result allowed for "
  100291. "a SELECT that is part of an expression");
  100292. return 1;
  100293. }else{
  100294. return 0;
  100295. }
  100296. }
  100297. #endif
  100298. /*
  100299. ** This routine generates the code for the inside of the inner loop
  100300. ** of a SELECT.
  100301. **
  100302. ** If srcTab is negative, then the pEList expressions
  100303. ** are evaluated in order to get the data for this row. If srcTab is
  100304. ** zero or more, then data is pulled from srcTab and pEList is used only
  100305. ** to get number columns and the datatype for each column.
  100306. */
  100307. static void selectInnerLoop(
  100308. Parse *pParse, /* The parser context */
  100309. Select *p, /* The complete select statement being coded */
  100310. ExprList *pEList, /* List of values being extracted */
  100311. int srcTab, /* Pull data from this table */
  100312. SortCtx *pSort, /* If not NULL, info on how to process ORDER BY */
  100313. DistinctCtx *pDistinct, /* If not NULL, info on how to process DISTINCT */
  100314. SelectDest *pDest, /* How to dispose of the results */
  100315. int iContinue, /* Jump here to continue with next row */
  100316. int iBreak /* Jump here to break out of the inner loop */
  100317. ){
  100318. Vdbe *v = pParse->pVdbe;
  100319. int i;
  100320. int hasDistinct; /* True if the DISTINCT keyword is present */
  100321. int regResult; /* Start of memory holding result set */
  100322. int eDest = pDest->eDest; /* How to dispose of results */
  100323. int iParm = pDest->iSDParm; /* First argument to disposal method */
  100324. int nResultCol; /* Number of result columns */
  100325. int nPrefixReg = 0; /* Number of extra registers before regResult */
  100326. assert( v );
  100327. assert( pEList!=0 );
  100328. hasDistinct = pDistinct ? pDistinct->eTnctType : WHERE_DISTINCT_NOOP;
  100329. if( pSort && pSort->pOrderBy==0 ) pSort = 0;
  100330. if( pSort==0 && !hasDistinct ){
  100331. assert( iContinue!=0 );
  100332. codeOffset(v, p->iOffset, iContinue);
  100333. }
  100334. /* Pull the requested columns.
  100335. */
  100336. nResultCol = pEList->nExpr;
  100337. if( pDest->iSdst==0 ){
  100338. if( pSort ){
  100339. nPrefixReg = pSort->pOrderBy->nExpr;
  100340. if( !(pSort->sortFlags & SORTFLAG_UseSorter) ) nPrefixReg++;
  100341. pParse->nMem += nPrefixReg;
  100342. }
  100343. pDest->iSdst = pParse->nMem+1;
  100344. pParse->nMem += nResultCol;
  100345. }else if( pDest->iSdst+nResultCol > pParse->nMem ){
  100346. /* This is an error condition that can result, for example, when a SELECT
  100347. ** on the right-hand side of an INSERT contains more result columns than
  100348. ** there are columns in the table on the left. The error will be caught
  100349. ** and reported later. But we need to make sure enough memory is allocated
  100350. ** to avoid other spurious errors in the meantime. */
  100351. pParse->nMem += nResultCol;
  100352. }
  100353. pDest->nSdst = nResultCol;
  100354. regResult = pDest->iSdst;
  100355. if( srcTab>=0 ){
  100356. for(i=0; i<nResultCol; i++){
  100357. sqlite3VdbeAddOp3(v, OP_Column, srcTab, i, regResult+i);
  100358. VdbeComment((v, "%s", pEList->a[i].zName));
  100359. }
  100360. }else if( eDest!=SRT_Exists ){
  100361. /* If the destination is an EXISTS(...) expression, the actual
  100362. ** values returned by the SELECT are not required.
  100363. */
  100364. sqlite3ExprCodeExprList(pParse, pEList, regResult,
  100365. (eDest==SRT_Output||eDest==SRT_Coroutine)?SQLITE_ECEL_DUP:0);
  100366. }
  100367. /* If the DISTINCT keyword was present on the SELECT statement
  100368. ** and this row has been seen before, then do not make this row
  100369. ** part of the result.
  100370. */
  100371. if( hasDistinct ){
  100372. switch( pDistinct->eTnctType ){
  100373. case WHERE_DISTINCT_ORDERED: {
  100374. VdbeOp *pOp; /* No longer required OpenEphemeral instr. */
  100375. int iJump; /* Jump destination */
  100376. int regPrev; /* Previous row content */
  100377. /* Allocate space for the previous row */
  100378. regPrev = pParse->nMem+1;
  100379. pParse->nMem += nResultCol;
  100380. /* Change the OP_OpenEphemeral coded earlier to an OP_Null
  100381. ** sets the MEM_Cleared bit on the first register of the
  100382. ** previous value. This will cause the OP_Ne below to always
  100383. ** fail on the first iteration of the loop even if the first
  100384. ** row is all NULLs.
  100385. */
  100386. sqlite3VdbeChangeToNoop(v, pDistinct->addrTnct);
  100387. pOp = sqlite3VdbeGetOp(v, pDistinct->addrTnct);
  100388. pOp->opcode = OP_Null;
  100389. pOp->p1 = 1;
  100390. pOp->p2 = regPrev;
  100391. iJump = sqlite3VdbeCurrentAddr(v) + nResultCol;
  100392. for(i=0; i<nResultCol; i++){
  100393. CollSeq *pColl = sqlite3ExprCollSeq(pParse, pEList->a[i].pExpr);
  100394. if( i<nResultCol-1 ){
  100395. sqlite3VdbeAddOp3(v, OP_Ne, regResult+i, iJump, regPrev+i);
  100396. VdbeCoverage(v);
  100397. }else{
  100398. sqlite3VdbeAddOp3(v, OP_Eq, regResult+i, iContinue, regPrev+i);
  100399. VdbeCoverage(v);
  100400. }
  100401. sqlite3VdbeChangeP4(v, -1, (const char *)pColl, P4_COLLSEQ);
  100402. sqlite3VdbeChangeP5(v, SQLITE_NULLEQ);
  100403. }
  100404. assert( sqlite3VdbeCurrentAddr(v)==iJump || pParse->db->mallocFailed );
  100405. sqlite3VdbeAddOp3(v, OP_Copy, regResult, regPrev, nResultCol-1);
  100406. break;
  100407. }
  100408. case WHERE_DISTINCT_UNIQUE: {
  100409. sqlite3VdbeChangeToNoop(v, pDistinct->addrTnct);
  100410. break;
  100411. }
  100412. default: {
  100413. assert( pDistinct->eTnctType==WHERE_DISTINCT_UNORDERED );
  100414. codeDistinct(pParse, pDistinct->tabTnct, iContinue, nResultCol, regResult);
  100415. break;
  100416. }
  100417. }
  100418. if( pSort==0 ){
  100419. codeOffset(v, p->iOffset, iContinue);
  100420. }
  100421. }
  100422. switch( eDest ){
  100423. /* In this mode, write each query result to the key of the temporary
  100424. ** table iParm.
  100425. */
  100426. #ifndef SQLITE_OMIT_COMPOUND_SELECT
  100427. case SRT_Union: {
  100428. int r1;
  100429. r1 = sqlite3GetTempReg(pParse);
  100430. sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nResultCol, r1);
  100431. sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, r1);
  100432. sqlite3ReleaseTempReg(pParse, r1);
  100433. break;
  100434. }
  100435. /* Construct a record from the query result, but instead of
  100436. ** saving that record, use it as a key to delete elements from
  100437. ** the temporary table iParm.
  100438. */
  100439. case SRT_Except: {
  100440. sqlite3VdbeAddOp3(v, OP_IdxDelete, iParm, regResult, nResultCol);
  100441. break;
  100442. }
  100443. #endif /* SQLITE_OMIT_COMPOUND_SELECT */
  100444. /* Store the result as data using a unique key.
  100445. */
  100446. case SRT_Fifo:
  100447. case SRT_DistFifo:
  100448. case SRT_Table:
  100449. case SRT_EphemTab: {
  100450. int r1 = sqlite3GetTempRange(pParse, nPrefixReg+1);
  100451. testcase( eDest==SRT_Table );
  100452. testcase( eDest==SRT_EphemTab );
  100453. sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nResultCol, r1+nPrefixReg);
  100454. #ifndef SQLITE_OMIT_CTE
  100455. if( eDest==SRT_DistFifo ){
  100456. /* If the destination is DistFifo, then cursor (iParm+1) is open
  100457. ** on an ephemeral index. If the current row is already present
  100458. ** in the index, do not write it to the output. If not, add the
  100459. ** current row to the index and proceed with writing it to the
  100460. ** output table as well. */
  100461. int addr = sqlite3VdbeCurrentAddr(v) + 4;
  100462. sqlite3VdbeAddOp4Int(v, OP_Found, iParm+1, addr, r1, 0); VdbeCoverage(v);
  100463. sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm+1, r1);
  100464. assert( pSort==0 );
  100465. }
  100466. #endif
  100467. if( pSort ){
  100468. pushOntoSorter(pParse, pSort, p, r1+nPrefixReg, 1, nPrefixReg);
  100469. }else{
  100470. int r2 = sqlite3GetTempReg(pParse);
  100471. sqlite3VdbeAddOp2(v, OP_NewRowid, iParm, r2);
  100472. sqlite3VdbeAddOp3(v, OP_Insert, iParm, r1, r2);
  100473. sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
  100474. sqlite3ReleaseTempReg(pParse, r2);
  100475. }
  100476. sqlite3ReleaseTempRange(pParse, r1, nPrefixReg+1);
  100477. break;
  100478. }
  100479. #ifndef SQLITE_OMIT_SUBQUERY
  100480. /* If we are creating a set for an "expr IN (SELECT ...)" construct,
  100481. ** then there should be a single item on the stack. Write this
  100482. ** item into the set table with bogus data.
  100483. */
  100484. case SRT_Set: {
  100485. assert( nResultCol==1 );
  100486. pDest->affSdst =
  100487. sqlite3CompareAffinity(pEList->a[0].pExpr, pDest->affSdst);
  100488. if( pSort ){
  100489. /* At first glance you would think we could optimize out the
  100490. ** ORDER BY in this case since the order of entries in the set
  100491. ** does not matter. But there might be a LIMIT clause, in which
  100492. ** case the order does matter */
  100493. pushOntoSorter(pParse, pSort, p, regResult, 1, nPrefixReg);
  100494. }else{
  100495. int r1 = sqlite3GetTempReg(pParse);
  100496. sqlite3VdbeAddOp4(v, OP_MakeRecord, regResult,1,r1, &pDest->affSdst, 1);
  100497. sqlite3ExprCacheAffinityChange(pParse, regResult, 1);
  100498. sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, r1);
  100499. sqlite3ReleaseTempReg(pParse, r1);
  100500. }
  100501. break;
  100502. }
  100503. /* If any row exist in the result set, record that fact and abort.
  100504. */
  100505. case SRT_Exists: {
  100506. sqlite3VdbeAddOp2(v, OP_Integer, 1, iParm);
  100507. /* The LIMIT clause will terminate the loop for us */
  100508. break;
  100509. }
  100510. /* If this is a scalar select that is part of an expression, then
  100511. ** store the results in the appropriate memory cell and break out
  100512. ** of the scan loop.
  100513. */
  100514. case SRT_Mem: {
  100515. assert( nResultCol==1 );
  100516. if( pSort ){
  100517. pushOntoSorter(pParse, pSort, p, regResult, 1, nPrefixReg);
  100518. }else{
  100519. assert( regResult==iParm );
  100520. /* The LIMIT clause will jump out of the loop for us */
  100521. }
  100522. break;
  100523. }
  100524. #endif /* #ifndef SQLITE_OMIT_SUBQUERY */
  100525. case SRT_Coroutine: /* Send data to a co-routine */
  100526. case SRT_Output: { /* Return the results */
  100527. testcase( eDest==SRT_Coroutine );
  100528. testcase( eDest==SRT_Output );
  100529. if( pSort ){
  100530. pushOntoSorter(pParse, pSort, p, regResult, nResultCol, nPrefixReg);
  100531. }else if( eDest==SRT_Coroutine ){
  100532. sqlite3VdbeAddOp1(v, OP_Yield, pDest->iSDParm);
  100533. }else{
  100534. sqlite3VdbeAddOp2(v, OP_ResultRow, regResult, nResultCol);
  100535. sqlite3ExprCacheAffinityChange(pParse, regResult, nResultCol);
  100536. }
  100537. break;
  100538. }
  100539. #ifndef SQLITE_OMIT_CTE
  100540. /* Write the results into a priority queue that is order according to
  100541. ** pDest->pOrderBy (in pSO). pDest->iSDParm (in iParm) is the cursor for an
  100542. ** index with pSO->nExpr+2 columns. Build a key using pSO for the first
  100543. ** pSO->nExpr columns, then make sure all keys are unique by adding a
  100544. ** final OP_Sequence column. The last column is the record as a blob.
  100545. */
  100546. case SRT_DistQueue:
  100547. case SRT_Queue: {
  100548. int nKey;
  100549. int r1, r2, r3;
  100550. int addrTest = 0;
  100551. ExprList *pSO;
  100552. pSO = pDest->pOrderBy;
  100553. assert( pSO );
  100554. nKey = pSO->nExpr;
  100555. r1 = sqlite3GetTempReg(pParse);
  100556. r2 = sqlite3GetTempRange(pParse, nKey+2);
  100557. r3 = r2+nKey+1;
  100558. if( eDest==SRT_DistQueue ){
  100559. /* If the destination is DistQueue, then cursor (iParm+1) is open
  100560. ** on a second ephemeral index that holds all values every previously
  100561. ** added to the queue. */
  100562. addrTest = sqlite3VdbeAddOp4Int(v, OP_Found, iParm+1, 0,
  100563. regResult, nResultCol);
  100564. VdbeCoverage(v);
  100565. }
  100566. sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nResultCol, r3);
  100567. if( eDest==SRT_DistQueue ){
  100568. sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm+1, r3);
  100569. sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
  100570. }
  100571. for(i=0; i<nKey; i++){
  100572. sqlite3VdbeAddOp2(v, OP_SCopy,
  100573. regResult + pSO->a[i].u.x.iOrderByCol - 1,
  100574. r2+i);
  100575. }
  100576. sqlite3VdbeAddOp2(v, OP_Sequence, iParm, r2+nKey);
  100577. sqlite3VdbeAddOp3(v, OP_MakeRecord, r2, nKey+2, r1);
  100578. sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, r1);
  100579. if( addrTest ) sqlite3VdbeJumpHere(v, addrTest);
  100580. sqlite3ReleaseTempReg(pParse, r1);
  100581. sqlite3ReleaseTempRange(pParse, r2, nKey+2);
  100582. break;
  100583. }
  100584. #endif /* SQLITE_OMIT_CTE */
  100585. #if !defined(SQLITE_OMIT_TRIGGER)
  100586. /* Discard the results. This is used for SELECT statements inside
  100587. ** the body of a TRIGGER. The purpose of such selects is to call
  100588. ** user-defined functions that have side effects. We do not care
  100589. ** about the actual results of the select.
  100590. */
  100591. default: {
  100592. assert( eDest==SRT_Discard );
  100593. break;
  100594. }
  100595. #endif
  100596. }
  100597. /* Jump to the end of the loop if the LIMIT is reached. Except, if
  100598. ** there is a sorter, in which case the sorter has already limited
  100599. ** the output for us.
  100600. */
  100601. if( pSort==0 && p->iLimit ){
  100602. sqlite3VdbeAddOp2(v, OP_DecrJumpZero, p->iLimit, iBreak); VdbeCoverage(v);
  100603. }
  100604. }
  100605. /*
  100606. ** Allocate a KeyInfo object sufficient for an index of N key columns and
  100607. ** X extra columns.
  100608. */
  100609. SQLITE_PRIVATE KeyInfo *sqlite3KeyInfoAlloc(sqlite3 *db, int N, int X){
  100610. KeyInfo *p = sqlite3DbMallocZero(0,
  100611. sizeof(KeyInfo) + (N+X)*(sizeof(CollSeq*)+1));
  100612. if( p ){
  100613. p->aSortOrder = (u8*)&p->aColl[N+X];
  100614. p->nField = (u16)N;
  100615. p->nXField = (u16)X;
  100616. p->enc = ENC(db);
  100617. p->db = db;
  100618. p->nRef = 1;
  100619. }else{
  100620. db->mallocFailed = 1;
  100621. }
  100622. return p;
  100623. }
  100624. /*
  100625. ** Deallocate a KeyInfo object
  100626. */
  100627. SQLITE_PRIVATE void sqlite3KeyInfoUnref(KeyInfo *p){
  100628. if( p ){
  100629. assert( p->nRef>0 );
  100630. p->nRef--;
  100631. if( p->nRef==0 ) sqlite3DbFree(0, p);
  100632. }
  100633. }
  100634. /*
  100635. ** Make a new pointer to a KeyInfo object
  100636. */
  100637. SQLITE_PRIVATE KeyInfo *sqlite3KeyInfoRef(KeyInfo *p){
  100638. if( p ){
  100639. assert( p->nRef>0 );
  100640. p->nRef++;
  100641. }
  100642. return p;
  100643. }
  100644. #ifdef SQLITE_DEBUG
  100645. /*
  100646. ** Return TRUE if a KeyInfo object can be change. The KeyInfo object
  100647. ** can only be changed if this is just a single reference to the object.
  100648. **
  100649. ** This routine is used only inside of assert() statements.
  100650. */
  100651. SQLITE_PRIVATE int sqlite3KeyInfoIsWriteable(KeyInfo *p){ return p->nRef==1; }
  100652. #endif /* SQLITE_DEBUG */
  100653. /*
  100654. ** Given an expression list, generate a KeyInfo structure that records
  100655. ** the collating sequence for each expression in that expression list.
  100656. **
  100657. ** If the ExprList is an ORDER BY or GROUP BY clause then the resulting
  100658. ** KeyInfo structure is appropriate for initializing a virtual index to
  100659. ** implement that clause. If the ExprList is the result set of a SELECT
  100660. ** then the KeyInfo structure is appropriate for initializing a virtual
  100661. ** index to implement a DISTINCT test.
  100662. **
  100663. ** Space to hold the KeyInfo structure is obtained from malloc. The calling
  100664. ** function is responsible for seeing that this structure is eventually
  100665. ** freed.
  100666. */
  100667. static KeyInfo *keyInfoFromExprList(
  100668. Parse *pParse, /* Parsing context */
  100669. ExprList *pList, /* Form the KeyInfo object from this ExprList */
  100670. int iStart, /* Begin with this column of pList */
  100671. int nExtra /* Add this many extra columns to the end */
  100672. ){
  100673. int nExpr;
  100674. KeyInfo *pInfo;
  100675. struct ExprList_item *pItem;
  100676. sqlite3 *db = pParse->db;
  100677. int i;
  100678. nExpr = pList->nExpr;
  100679. pInfo = sqlite3KeyInfoAlloc(db, nExpr-iStart, nExtra+1);
  100680. if( pInfo ){
  100681. assert( sqlite3KeyInfoIsWriteable(pInfo) );
  100682. for(i=iStart, pItem=pList->a+iStart; i<nExpr; i++, pItem++){
  100683. CollSeq *pColl;
  100684. pColl = sqlite3ExprCollSeq(pParse, pItem->pExpr);
  100685. if( !pColl ) pColl = db->pDfltColl;
  100686. pInfo->aColl[i-iStart] = pColl;
  100687. pInfo->aSortOrder[i-iStart] = pItem->sortOrder;
  100688. }
  100689. }
  100690. return pInfo;
  100691. }
  100692. #ifndef SQLITE_OMIT_COMPOUND_SELECT
  100693. /*
  100694. ** Name of the connection operator, used for error messages.
  100695. */
  100696. static const char *selectOpName(int id){
  100697. char *z;
  100698. switch( id ){
  100699. case TK_ALL: z = "UNION ALL"; break;
  100700. case TK_INTERSECT: z = "INTERSECT"; break;
  100701. case TK_EXCEPT: z = "EXCEPT"; break;
  100702. default: z = "UNION"; break;
  100703. }
  100704. return z;
  100705. }
  100706. #endif /* SQLITE_OMIT_COMPOUND_SELECT */
  100707. #ifndef SQLITE_OMIT_EXPLAIN
  100708. /*
  100709. ** Unless an "EXPLAIN QUERY PLAN" command is being processed, this function
  100710. ** is a no-op. Otherwise, it adds a single row of output to the EQP result,
  100711. ** where the caption is of the form:
  100712. **
  100713. ** "USE TEMP B-TREE FOR xxx"
  100714. **
  100715. ** where xxx is one of "DISTINCT", "ORDER BY" or "GROUP BY". Exactly which
  100716. ** is determined by the zUsage argument.
  100717. */
  100718. static void explainTempTable(Parse *pParse, const char *zUsage){
  100719. if( pParse->explain==2 ){
  100720. Vdbe *v = pParse->pVdbe;
  100721. char *zMsg = sqlite3MPrintf(pParse->db, "USE TEMP B-TREE FOR %s", zUsage);
  100722. sqlite3VdbeAddOp4(v, OP_Explain, pParse->iSelectId, 0, 0, zMsg, P4_DYNAMIC);
  100723. }
  100724. }
  100725. /*
  100726. ** Assign expression b to lvalue a. A second, no-op, version of this macro
  100727. ** is provided when SQLITE_OMIT_EXPLAIN is defined. This allows the code
  100728. ** in sqlite3Select() to assign values to structure member variables that
  100729. ** only exist if SQLITE_OMIT_EXPLAIN is not defined without polluting the
  100730. ** code with #ifndef directives.
  100731. */
  100732. # define explainSetInteger(a, b) a = b
  100733. #else
  100734. /* No-op versions of the explainXXX() functions and macros. */
  100735. # define explainTempTable(y,z)
  100736. # define explainSetInteger(y,z)
  100737. #endif
  100738. #if !defined(SQLITE_OMIT_EXPLAIN) && !defined(SQLITE_OMIT_COMPOUND_SELECT)
  100739. /*
  100740. ** Unless an "EXPLAIN QUERY PLAN" command is being processed, this function
  100741. ** is a no-op. Otherwise, it adds a single row of output to the EQP result,
  100742. ** where the caption is of one of the two forms:
  100743. **
  100744. ** "COMPOSITE SUBQUERIES iSub1 and iSub2 (op)"
  100745. ** "COMPOSITE SUBQUERIES iSub1 and iSub2 USING TEMP B-TREE (op)"
  100746. **
  100747. ** where iSub1 and iSub2 are the integers passed as the corresponding
  100748. ** function parameters, and op is the text representation of the parameter
  100749. ** of the same name. The parameter "op" must be one of TK_UNION, TK_EXCEPT,
  100750. ** TK_INTERSECT or TK_ALL. The first form is used if argument bUseTmp is
  100751. ** false, or the second form if it is true.
  100752. */
  100753. static void explainComposite(
  100754. Parse *pParse, /* Parse context */
  100755. int op, /* One of TK_UNION, TK_EXCEPT etc. */
  100756. int iSub1, /* Subquery id 1 */
  100757. int iSub2, /* Subquery id 2 */
  100758. int bUseTmp /* True if a temp table was used */
  100759. ){
  100760. assert( op==TK_UNION || op==TK_EXCEPT || op==TK_INTERSECT || op==TK_ALL );
  100761. if( pParse->explain==2 ){
  100762. Vdbe *v = pParse->pVdbe;
  100763. char *zMsg = sqlite3MPrintf(
  100764. pParse->db, "COMPOUND SUBQUERIES %d AND %d %s(%s)", iSub1, iSub2,
  100765. bUseTmp?"USING TEMP B-TREE ":"", selectOpName(op)
  100766. );
  100767. sqlite3VdbeAddOp4(v, OP_Explain, pParse->iSelectId, 0, 0, zMsg, P4_DYNAMIC);
  100768. }
  100769. }
  100770. #else
  100771. /* No-op versions of the explainXXX() functions and macros. */
  100772. # define explainComposite(v,w,x,y,z)
  100773. #endif
  100774. /*
  100775. ** If the inner loop was generated using a non-null pOrderBy argument,
  100776. ** then the results were placed in a sorter. After the loop is terminated
  100777. ** we need to run the sorter and output the results. The following
  100778. ** routine generates the code needed to do that.
  100779. */
  100780. static void generateSortTail(
  100781. Parse *pParse, /* Parsing context */
  100782. Select *p, /* The SELECT statement */
  100783. SortCtx *pSort, /* Information on the ORDER BY clause */
  100784. int nColumn, /* Number of columns of data */
  100785. SelectDest *pDest /* Write the sorted results here */
  100786. ){
  100787. Vdbe *v = pParse->pVdbe; /* The prepared statement */
  100788. int addrBreak = sqlite3VdbeMakeLabel(v); /* Jump here to exit loop */
  100789. int addrContinue = sqlite3VdbeMakeLabel(v); /* Jump here for next cycle */
  100790. int addr;
  100791. int addrOnce = 0;
  100792. int iTab;
  100793. ExprList *pOrderBy = pSort->pOrderBy;
  100794. int eDest = pDest->eDest;
  100795. int iParm = pDest->iSDParm;
  100796. int regRow;
  100797. int regRowid;
  100798. int nKey;
  100799. int iSortTab; /* Sorter cursor to read from */
  100800. int nSortData; /* Trailing values to read from sorter */
  100801. int i;
  100802. int bSeq; /* True if sorter record includes seq. no. */
  100803. #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
  100804. struct ExprList_item *aOutEx = p->pEList->a;
  100805. #endif
  100806. if( pSort->labelBkOut ){
  100807. sqlite3VdbeAddOp2(v, OP_Gosub, pSort->regReturn, pSort->labelBkOut);
  100808. sqlite3VdbeAddOp2(v, OP_Goto, 0, addrBreak);
  100809. sqlite3VdbeResolveLabel(v, pSort->labelBkOut);
  100810. }
  100811. iTab = pSort->iECursor;
  100812. if( eDest==SRT_Output || eDest==SRT_Coroutine ){
  100813. regRowid = 0;
  100814. regRow = pDest->iSdst;
  100815. nSortData = nColumn;
  100816. }else{
  100817. regRowid = sqlite3GetTempReg(pParse);
  100818. regRow = sqlite3GetTempReg(pParse);
  100819. nSortData = 1;
  100820. }
  100821. nKey = pOrderBy->nExpr - pSort->nOBSat;
  100822. if( pSort->sortFlags & SORTFLAG_UseSorter ){
  100823. int regSortOut = ++pParse->nMem;
  100824. iSortTab = pParse->nTab++;
  100825. if( pSort->labelBkOut ){
  100826. addrOnce = sqlite3CodeOnce(pParse); VdbeCoverage(v);
  100827. }
  100828. sqlite3VdbeAddOp3(v, OP_OpenPseudo, iSortTab, regSortOut, nKey+1+nSortData);
  100829. if( addrOnce ) sqlite3VdbeJumpHere(v, addrOnce);
  100830. addr = 1 + sqlite3VdbeAddOp2(v, OP_SorterSort, iTab, addrBreak);
  100831. VdbeCoverage(v);
  100832. codeOffset(v, p->iOffset, addrContinue);
  100833. sqlite3VdbeAddOp3(v, OP_SorterData, iTab, regSortOut, iSortTab);
  100834. bSeq = 0;
  100835. }else{
  100836. addr = 1 + sqlite3VdbeAddOp2(v, OP_Sort, iTab, addrBreak); VdbeCoverage(v);
  100837. codeOffset(v, p->iOffset, addrContinue);
  100838. iSortTab = iTab;
  100839. bSeq = 1;
  100840. }
  100841. for(i=0; i<nSortData; i++){
  100842. sqlite3VdbeAddOp3(v, OP_Column, iSortTab, nKey+bSeq+i, regRow+i);
  100843. VdbeComment((v, "%s", aOutEx[i].zName ? aOutEx[i].zName : aOutEx[i].zSpan));
  100844. }
  100845. switch( eDest ){
  100846. case SRT_Table:
  100847. case SRT_EphemTab: {
  100848. testcase( eDest==SRT_Table );
  100849. testcase( eDest==SRT_EphemTab );
  100850. sqlite3VdbeAddOp2(v, OP_NewRowid, iParm, regRowid);
  100851. sqlite3VdbeAddOp3(v, OP_Insert, iParm, regRow, regRowid);
  100852. sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
  100853. break;
  100854. }
  100855. #ifndef SQLITE_OMIT_SUBQUERY
  100856. case SRT_Set: {
  100857. assert( nColumn==1 );
  100858. sqlite3VdbeAddOp4(v, OP_MakeRecord, regRow, 1, regRowid,
  100859. &pDest->affSdst, 1);
  100860. sqlite3ExprCacheAffinityChange(pParse, regRow, 1);
  100861. sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, regRowid);
  100862. break;
  100863. }
  100864. case SRT_Mem: {
  100865. assert( nColumn==1 );
  100866. sqlite3ExprCodeMove(pParse, regRow, iParm, 1);
  100867. /* The LIMIT clause will terminate the loop for us */
  100868. break;
  100869. }
  100870. #endif
  100871. default: {
  100872. assert( eDest==SRT_Output || eDest==SRT_Coroutine );
  100873. testcase( eDest==SRT_Output );
  100874. testcase( eDest==SRT_Coroutine );
  100875. if( eDest==SRT_Output ){
  100876. sqlite3VdbeAddOp2(v, OP_ResultRow, pDest->iSdst, nColumn);
  100877. sqlite3ExprCacheAffinityChange(pParse, pDest->iSdst, nColumn);
  100878. }else{
  100879. sqlite3VdbeAddOp1(v, OP_Yield, pDest->iSDParm);
  100880. }
  100881. break;
  100882. }
  100883. }
  100884. if( regRowid ){
  100885. sqlite3ReleaseTempReg(pParse, regRow);
  100886. sqlite3ReleaseTempReg(pParse, regRowid);
  100887. }
  100888. /* The bottom of the loop
  100889. */
  100890. sqlite3VdbeResolveLabel(v, addrContinue);
  100891. if( pSort->sortFlags & SORTFLAG_UseSorter ){
  100892. sqlite3VdbeAddOp2(v, OP_SorterNext, iTab, addr); VdbeCoverage(v);
  100893. }else{
  100894. sqlite3VdbeAddOp2(v, OP_Next, iTab, addr); VdbeCoverage(v);
  100895. }
  100896. if( pSort->regReturn ) sqlite3VdbeAddOp1(v, OP_Return, pSort->regReturn);
  100897. sqlite3VdbeResolveLabel(v, addrBreak);
  100898. }
  100899. /*
  100900. ** Return a pointer to a string containing the 'declaration type' of the
  100901. ** expression pExpr. The string may be treated as static by the caller.
  100902. **
  100903. ** Also try to estimate the size of the returned value and return that
  100904. ** result in *pEstWidth.
  100905. **
  100906. ** The declaration type is the exact datatype definition extracted from the
  100907. ** original CREATE TABLE statement if the expression is a column. The
  100908. ** declaration type for a ROWID field is INTEGER. Exactly when an expression
  100909. ** is considered a column can be complex in the presence of subqueries. The
  100910. ** result-set expression in all of the following SELECT statements is
  100911. ** considered a column by this function.
  100912. **
  100913. ** SELECT col FROM tbl;
  100914. ** SELECT (SELECT col FROM tbl;
  100915. ** SELECT (SELECT col FROM tbl);
  100916. ** SELECT abc FROM (SELECT col AS abc FROM tbl);
  100917. **
  100918. ** The declaration type for any expression other than a column is NULL.
  100919. **
  100920. ** This routine has either 3 or 6 parameters depending on whether or not
  100921. ** the SQLITE_ENABLE_COLUMN_METADATA compile-time option is used.
  100922. */
  100923. #ifdef SQLITE_ENABLE_COLUMN_METADATA
  100924. # define columnType(A,B,C,D,E,F) columnTypeImpl(A,B,C,D,E,F)
  100925. static const char *columnTypeImpl(
  100926. NameContext *pNC,
  100927. Expr *pExpr,
  100928. const char **pzOrigDb,
  100929. const char **pzOrigTab,
  100930. const char **pzOrigCol,
  100931. u8 *pEstWidth
  100932. ){
  100933. char const *zOrigDb = 0;
  100934. char const *zOrigTab = 0;
  100935. char const *zOrigCol = 0;
  100936. #else /* if !defined(SQLITE_ENABLE_COLUMN_METADATA) */
  100937. # define columnType(A,B,C,D,E,F) columnTypeImpl(A,B,F)
  100938. static const char *columnTypeImpl(
  100939. NameContext *pNC,
  100940. Expr *pExpr,
  100941. u8 *pEstWidth
  100942. ){
  100943. #endif /* !defined(SQLITE_ENABLE_COLUMN_METADATA) */
  100944. char const *zType = 0;
  100945. int j;
  100946. u8 estWidth = 1;
  100947. if( NEVER(pExpr==0) || pNC->pSrcList==0 ) return 0;
  100948. switch( pExpr->op ){
  100949. case TK_AGG_COLUMN:
  100950. case TK_COLUMN: {
  100951. /* The expression is a column. Locate the table the column is being
  100952. ** extracted from in NameContext.pSrcList. This table may be real
  100953. ** database table or a subquery.
  100954. */
  100955. Table *pTab = 0; /* Table structure column is extracted from */
  100956. Select *pS = 0; /* Select the column is extracted from */
  100957. int iCol = pExpr->iColumn; /* Index of column in pTab */
  100958. testcase( pExpr->op==TK_AGG_COLUMN );
  100959. testcase( pExpr->op==TK_COLUMN );
  100960. while( pNC && !pTab ){
  100961. SrcList *pTabList = pNC->pSrcList;
  100962. for(j=0;j<pTabList->nSrc && pTabList->a[j].iCursor!=pExpr->iTable;j++);
  100963. if( j<pTabList->nSrc ){
  100964. pTab = pTabList->a[j].pTab;
  100965. pS = pTabList->a[j].pSelect;
  100966. }else{
  100967. pNC = pNC->pNext;
  100968. }
  100969. }
  100970. if( pTab==0 ){
  100971. /* At one time, code such as "SELECT new.x" within a trigger would
  100972. ** cause this condition to run. Since then, we have restructured how
  100973. ** trigger code is generated and so this condition is no longer
  100974. ** possible. However, it can still be true for statements like
  100975. ** the following:
  100976. **
  100977. ** CREATE TABLE t1(col INTEGER);
  100978. ** SELECT (SELECT t1.col) FROM FROM t1;
  100979. **
  100980. ** when columnType() is called on the expression "t1.col" in the
  100981. ** sub-select. In this case, set the column type to NULL, even
  100982. ** though it should really be "INTEGER".
  100983. **
  100984. ** This is not a problem, as the column type of "t1.col" is never
  100985. ** used. When columnType() is called on the expression
  100986. ** "(SELECT t1.col)", the correct type is returned (see the TK_SELECT
  100987. ** branch below. */
  100988. break;
  100989. }
  100990. assert( pTab && pExpr->pTab==pTab );
  100991. if( pS ){
  100992. /* The "table" is actually a sub-select or a view in the FROM clause
  100993. ** of the SELECT statement. Return the declaration type and origin
  100994. ** data for the result-set column of the sub-select.
  100995. */
  100996. if( iCol>=0 && iCol<pS->pEList->nExpr ){
  100997. /* If iCol is less than zero, then the expression requests the
  100998. ** rowid of the sub-select or view. This expression is legal (see
  100999. ** test case misc2.2.2) - it always evaluates to NULL.
  101000. */
  101001. NameContext sNC;
  101002. Expr *p = pS->pEList->a[iCol].pExpr;
  101003. sNC.pSrcList = pS->pSrc;
  101004. sNC.pNext = pNC;
  101005. sNC.pParse = pNC->pParse;
  101006. zType = columnType(&sNC, p,&zOrigDb,&zOrigTab,&zOrigCol, &estWidth);
  101007. }
  101008. }else if( pTab->pSchema ){
  101009. /* A real table */
  101010. assert( !pS );
  101011. if( iCol<0 ) iCol = pTab->iPKey;
  101012. assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
  101013. #ifdef SQLITE_ENABLE_COLUMN_METADATA
  101014. if( iCol<0 ){
  101015. zType = "INTEGER";
  101016. zOrigCol = "rowid";
  101017. }else{
  101018. zType = pTab->aCol[iCol].zType;
  101019. zOrigCol = pTab->aCol[iCol].zName;
  101020. estWidth = pTab->aCol[iCol].szEst;
  101021. }
  101022. zOrigTab = pTab->zName;
  101023. if( pNC->pParse ){
  101024. int iDb = sqlite3SchemaToIndex(pNC->pParse->db, pTab->pSchema);
  101025. zOrigDb = pNC->pParse->db->aDb[iDb].zName;
  101026. }
  101027. #else
  101028. if( iCol<0 ){
  101029. zType = "INTEGER";
  101030. }else{
  101031. zType = pTab->aCol[iCol].zType;
  101032. estWidth = pTab->aCol[iCol].szEst;
  101033. }
  101034. #endif
  101035. }
  101036. break;
  101037. }
  101038. #ifndef SQLITE_OMIT_SUBQUERY
  101039. case TK_SELECT: {
  101040. /* The expression is a sub-select. Return the declaration type and
  101041. ** origin info for the single column in the result set of the SELECT
  101042. ** statement.
  101043. */
  101044. NameContext sNC;
  101045. Select *pS = pExpr->x.pSelect;
  101046. Expr *p = pS->pEList->a[0].pExpr;
  101047. assert( ExprHasProperty(pExpr, EP_xIsSelect) );
  101048. sNC.pSrcList = pS->pSrc;
  101049. sNC.pNext = pNC;
  101050. sNC.pParse = pNC->pParse;
  101051. zType = columnType(&sNC, p, &zOrigDb, &zOrigTab, &zOrigCol, &estWidth);
  101052. break;
  101053. }
  101054. #endif
  101055. }
  101056. #ifdef SQLITE_ENABLE_COLUMN_METADATA
  101057. if( pzOrigDb ){
  101058. assert( pzOrigTab && pzOrigCol );
  101059. *pzOrigDb = zOrigDb;
  101060. *pzOrigTab = zOrigTab;
  101061. *pzOrigCol = zOrigCol;
  101062. }
  101063. #endif
  101064. if( pEstWidth ) *pEstWidth = estWidth;
  101065. return zType;
  101066. }
  101067. /*
  101068. ** Generate code that will tell the VDBE the declaration types of columns
  101069. ** in the result set.
  101070. */
  101071. static void generateColumnTypes(
  101072. Parse *pParse, /* Parser context */
  101073. SrcList *pTabList, /* List of tables */
  101074. ExprList *pEList /* Expressions defining the result set */
  101075. ){
  101076. #ifndef SQLITE_OMIT_DECLTYPE
  101077. Vdbe *v = pParse->pVdbe;
  101078. int i;
  101079. NameContext sNC;
  101080. sNC.pSrcList = pTabList;
  101081. sNC.pParse = pParse;
  101082. for(i=0; i<pEList->nExpr; i++){
  101083. Expr *p = pEList->a[i].pExpr;
  101084. const char *zType;
  101085. #ifdef SQLITE_ENABLE_COLUMN_METADATA
  101086. const char *zOrigDb = 0;
  101087. const char *zOrigTab = 0;
  101088. const char *zOrigCol = 0;
  101089. zType = columnType(&sNC, p, &zOrigDb, &zOrigTab, &zOrigCol, 0);
  101090. /* The vdbe must make its own copy of the column-type and other
  101091. ** column specific strings, in case the schema is reset before this
  101092. ** virtual machine is deleted.
  101093. */
  101094. sqlite3VdbeSetColName(v, i, COLNAME_DATABASE, zOrigDb, SQLITE_TRANSIENT);
  101095. sqlite3VdbeSetColName(v, i, COLNAME_TABLE, zOrigTab, SQLITE_TRANSIENT);
  101096. sqlite3VdbeSetColName(v, i, COLNAME_COLUMN, zOrigCol, SQLITE_TRANSIENT);
  101097. #else
  101098. zType = columnType(&sNC, p, 0, 0, 0, 0);
  101099. #endif
  101100. sqlite3VdbeSetColName(v, i, COLNAME_DECLTYPE, zType, SQLITE_TRANSIENT);
  101101. }
  101102. #endif /* !defined(SQLITE_OMIT_DECLTYPE) */
  101103. }
  101104. /*
  101105. ** Generate code that will tell the VDBE the names of columns
  101106. ** in the result set. This information is used to provide the
  101107. ** azCol[] values in the callback.
  101108. */
  101109. static void generateColumnNames(
  101110. Parse *pParse, /* Parser context */
  101111. SrcList *pTabList, /* List of tables */
  101112. ExprList *pEList /* Expressions defining the result set */
  101113. ){
  101114. Vdbe *v = pParse->pVdbe;
  101115. int i, j;
  101116. sqlite3 *db = pParse->db;
  101117. int fullNames, shortNames;
  101118. #ifndef SQLITE_OMIT_EXPLAIN
  101119. /* If this is an EXPLAIN, skip this step */
  101120. if( pParse->explain ){
  101121. return;
  101122. }
  101123. #endif
  101124. if( pParse->colNamesSet || NEVER(v==0) || db->mallocFailed ) return;
  101125. pParse->colNamesSet = 1;
  101126. fullNames = (db->flags & SQLITE_FullColNames)!=0;
  101127. shortNames = (db->flags & SQLITE_ShortColNames)!=0;
  101128. sqlite3VdbeSetNumCols(v, pEList->nExpr);
  101129. for(i=0; i<pEList->nExpr; i++){
  101130. Expr *p;
  101131. p = pEList->a[i].pExpr;
  101132. if( NEVER(p==0) ) continue;
  101133. if( pEList->a[i].zName ){
  101134. char *zName = pEList->a[i].zName;
  101135. sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, SQLITE_TRANSIENT);
  101136. }else if( (p->op==TK_COLUMN || p->op==TK_AGG_COLUMN) && pTabList ){
  101137. Table *pTab;
  101138. char *zCol;
  101139. int iCol = p->iColumn;
  101140. for(j=0; ALWAYS(j<pTabList->nSrc); j++){
  101141. if( pTabList->a[j].iCursor==p->iTable ) break;
  101142. }
  101143. assert( j<pTabList->nSrc );
  101144. pTab = pTabList->a[j].pTab;
  101145. if( iCol<0 ) iCol = pTab->iPKey;
  101146. assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
  101147. if( iCol<0 ){
  101148. zCol = "rowid";
  101149. }else{
  101150. zCol = pTab->aCol[iCol].zName;
  101151. }
  101152. if( !shortNames && !fullNames ){
  101153. sqlite3VdbeSetColName(v, i, COLNAME_NAME,
  101154. sqlite3DbStrDup(db, pEList->a[i].zSpan), SQLITE_DYNAMIC);
  101155. }else if( fullNames ){
  101156. char *zName = 0;
  101157. zName = sqlite3MPrintf(db, "%s.%s", pTab->zName, zCol);
  101158. sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, SQLITE_DYNAMIC);
  101159. }else{
  101160. sqlite3VdbeSetColName(v, i, COLNAME_NAME, zCol, SQLITE_TRANSIENT);
  101161. }
  101162. }else{
  101163. const char *z = pEList->a[i].zSpan;
  101164. z = z==0 ? sqlite3MPrintf(db, "column%d", i+1) : sqlite3DbStrDup(db, z);
  101165. sqlite3VdbeSetColName(v, i, COLNAME_NAME, z, SQLITE_DYNAMIC);
  101166. }
  101167. }
  101168. generateColumnTypes(pParse, pTabList, pEList);
  101169. }
  101170. /*
  101171. ** Given an expression list (which is really the list of expressions
  101172. ** that form the result set of a SELECT statement) compute appropriate
  101173. ** column names for a table that would hold the expression list.
  101174. **
  101175. ** All column names will be unique.
  101176. **
  101177. ** Only the column names are computed. Column.zType, Column.zColl,
  101178. ** and other fields of Column are zeroed.
  101179. **
  101180. ** Return SQLITE_OK on success. If a memory allocation error occurs,
  101181. ** store NULL in *paCol and 0 in *pnCol and return SQLITE_NOMEM.
  101182. */
  101183. static int selectColumnsFromExprList(
  101184. Parse *pParse, /* Parsing context */
  101185. ExprList *pEList, /* Expr list from which to derive column names */
  101186. i16 *pnCol, /* Write the number of columns here */
  101187. Column **paCol /* Write the new column list here */
  101188. ){
  101189. sqlite3 *db = pParse->db; /* Database connection */
  101190. int i, j; /* Loop counters */
  101191. int cnt; /* Index added to make the name unique */
  101192. Column *aCol, *pCol; /* For looping over result columns */
  101193. int nCol; /* Number of columns in the result set */
  101194. Expr *p; /* Expression for a single result column */
  101195. char *zName; /* Column name */
  101196. int nName; /* Size of name in zName[] */
  101197. if( pEList ){
  101198. nCol = pEList->nExpr;
  101199. aCol = sqlite3DbMallocZero(db, sizeof(aCol[0])*nCol);
  101200. testcase( aCol==0 );
  101201. }else{
  101202. nCol = 0;
  101203. aCol = 0;
  101204. }
  101205. *pnCol = nCol;
  101206. *paCol = aCol;
  101207. for(i=0, pCol=aCol; i<nCol; i++, pCol++){
  101208. /* Get an appropriate name for the column
  101209. */
  101210. p = sqlite3ExprSkipCollate(pEList->a[i].pExpr);
  101211. if( (zName = pEList->a[i].zName)!=0 ){
  101212. /* If the column contains an "AS <name>" phrase, use <name> as the name */
  101213. zName = sqlite3DbStrDup(db, zName);
  101214. }else{
  101215. Expr *pColExpr = p; /* The expression that is the result column name */
  101216. Table *pTab; /* Table associated with this expression */
  101217. while( pColExpr->op==TK_DOT ){
  101218. pColExpr = pColExpr->pRight;
  101219. assert( pColExpr!=0 );
  101220. }
  101221. if( pColExpr->op==TK_COLUMN && ALWAYS(pColExpr->pTab!=0) ){
  101222. /* For columns use the column name name */
  101223. int iCol = pColExpr->iColumn;
  101224. pTab = pColExpr->pTab;
  101225. if( iCol<0 ) iCol = pTab->iPKey;
  101226. zName = sqlite3MPrintf(db, "%s",
  101227. iCol>=0 ? pTab->aCol[iCol].zName : "rowid");
  101228. }else if( pColExpr->op==TK_ID ){
  101229. assert( !ExprHasProperty(pColExpr, EP_IntValue) );
  101230. zName = sqlite3MPrintf(db, "%s", pColExpr->u.zToken);
  101231. }else{
  101232. /* Use the original text of the column expression as its name */
  101233. zName = sqlite3MPrintf(db, "%s", pEList->a[i].zSpan);
  101234. }
  101235. }
  101236. if( db->mallocFailed ){
  101237. sqlite3DbFree(db, zName);
  101238. break;
  101239. }
  101240. /* Make sure the column name is unique. If the name is not unique,
  101241. ** append an integer to the name so that it becomes unique.
  101242. */
  101243. nName = sqlite3Strlen30(zName);
  101244. for(j=cnt=0; j<i; j++){
  101245. if( sqlite3StrICmp(aCol[j].zName, zName)==0 ){
  101246. char *zNewName;
  101247. int k;
  101248. for(k=nName-1; k>1 && sqlite3Isdigit(zName[k]); k--){}
  101249. if( k>=0 && zName[k]==':' ) nName = k;
  101250. zName[nName] = 0;
  101251. zNewName = sqlite3MPrintf(db, "%s:%d", zName, ++cnt);
  101252. sqlite3DbFree(db, zName);
  101253. zName = zNewName;
  101254. j = -1;
  101255. if( zName==0 ) break;
  101256. }
  101257. }
  101258. pCol->zName = zName;
  101259. }
  101260. if( db->mallocFailed ){
  101261. for(j=0; j<i; j++){
  101262. sqlite3DbFree(db, aCol[j].zName);
  101263. }
  101264. sqlite3DbFree(db, aCol);
  101265. *paCol = 0;
  101266. *pnCol = 0;
  101267. return SQLITE_NOMEM;
  101268. }
  101269. return SQLITE_OK;
  101270. }
  101271. /*
  101272. ** Add type and collation information to a column list based on
  101273. ** a SELECT statement.
  101274. **
  101275. ** The column list presumably came from selectColumnNamesFromExprList().
  101276. ** The column list has only names, not types or collations. This
  101277. ** routine goes through and adds the types and collations.
  101278. **
  101279. ** This routine requires that all identifiers in the SELECT
  101280. ** statement be resolved.
  101281. */
  101282. static void selectAddColumnTypeAndCollation(
  101283. Parse *pParse, /* Parsing contexts */
  101284. Table *pTab, /* Add column type information to this table */
  101285. Select *pSelect /* SELECT used to determine types and collations */
  101286. ){
  101287. sqlite3 *db = pParse->db;
  101288. NameContext sNC;
  101289. Column *pCol;
  101290. CollSeq *pColl;
  101291. int i;
  101292. Expr *p;
  101293. struct ExprList_item *a;
  101294. u64 szAll = 0;
  101295. assert( pSelect!=0 );
  101296. assert( (pSelect->selFlags & SF_Resolved)!=0 );
  101297. assert( pTab->nCol==pSelect->pEList->nExpr || db->mallocFailed );
  101298. if( db->mallocFailed ) return;
  101299. memset(&sNC, 0, sizeof(sNC));
  101300. sNC.pSrcList = pSelect->pSrc;
  101301. a = pSelect->pEList->a;
  101302. for(i=0, pCol=pTab->aCol; i<pTab->nCol; i++, pCol++){
  101303. p = a[i].pExpr;
  101304. if( pCol->zType==0 ){
  101305. pCol->zType = sqlite3DbStrDup(db, columnType(&sNC, p,0,0,0, &pCol->szEst));
  101306. }
  101307. szAll += pCol->szEst;
  101308. pCol->affinity = sqlite3ExprAffinity(p);
  101309. if( pCol->affinity==0 ) pCol->affinity = SQLITE_AFF_NONE;
  101310. pColl = sqlite3ExprCollSeq(pParse, p);
  101311. if( pColl && pCol->zColl==0 ){
  101312. pCol->zColl = sqlite3DbStrDup(db, pColl->zName);
  101313. }
  101314. }
  101315. pTab->szTabRow = sqlite3LogEst(szAll*4);
  101316. }
  101317. /*
  101318. ** Given a SELECT statement, generate a Table structure that describes
  101319. ** the result set of that SELECT.
  101320. */
  101321. SQLITE_PRIVATE Table *sqlite3ResultSetOfSelect(Parse *pParse, Select *pSelect){
  101322. Table *pTab;
  101323. sqlite3 *db = pParse->db;
  101324. int savedFlags;
  101325. savedFlags = db->flags;
  101326. db->flags &= ~SQLITE_FullColNames;
  101327. db->flags |= SQLITE_ShortColNames;
  101328. sqlite3SelectPrep(pParse, pSelect, 0);
  101329. if( pParse->nErr ) return 0;
  101330. while( pSelect->pPrior ) pSelect = pSelect->pPrior;
  101331. db->flags = savedFlags;
  101332. pTab = sqlite3DbMallocZero(db, sizeof(Table) );
  101333. if( pTab==0 ){
  101334. return 0;
  101335. }
  101336. /* The sqlite3ResultSetOfSelect() is only used n contexts where lookaside
  101337. ** is disabled */
  101338. assert( db->lookaside.bEnabled==0 );
  101339. pTab->nRef = 1;
  101340. pTab->zName = 0;
  101341. pTab->nRowLogEst = 200; assert( 200==sqlite3LogEst(1048576) );
  101342. selectColumnsFromExprList(pParse, pSelect->pEList, &pTab->nCol, &pTab->aCol);
  101343. selectAddColumnTypeAndCollation(pParse, pTab, pSelect);
  101344. pTab->iPKey = -1;
  101345. if( db->mallocFailed ){
  101346. sqlite3DeleteTable(db, pTab);
  101347. return 0;
  101348. }
  101349. return pTab;
  101350. }
  101351. /*
  101352. ** Get a VDBE for the given parser context. Create a new one if necessary.
  101353. ** If an error occurs, return NULL and leave a message in pParse.
  101354. */
  101355. SQLITE_PRIVATE Vdbe *sqlite3GetVdbe(Parse *pParse){
  101356. Vdbe *v = pParse->pVdbe;
  101357. if( v==0 ){
  101358. v = pParse->pVdbe = sqlite3VdbeCreate(pParse);
  101359. if( v ) sqlite3VdbeAddOp0(v, OP_Init);
  101360. if( pParse->pToplevel==0
  101361. && OptimizationEnabled(pParse->db,SQLITE_FactorOutConst)
  101362. ){
  101363. pParse->okConstFactor = 1;
  101364. }
  101365. }
  101366. return v;
  101367. }
  101368. /*
  101369. ** Compute the iLimit and iOffset fields of the SELECT based on the
  101370. ** pLimit and pOffset expressions. pLimit and pOffset hold the expressions
  101371. ** that appear in the original SQL statement after the LIMIT and OFFSET
  101372. ** keywords. Or NULL if those keywords are omitted. iLimit and iOffset
  101373. ** are the integer memory register numbers for counters used to compute
  101374. ** the limit and offset. If there is no limit and/or offset, then
  101375. ** iLimit and iOffset are negative.
  101376. **
  101377. ** This routine changes the values of iLimit and iOffset only if
  101378. ** a limit or offset is defined by pLimit and pOffset. iLimit and
  101379. ** iOffset should have been preset to appropriate default values (zero)
  101380. ** prior to calling this routine.
  101381. **
  101382. ** The iOffset register (if it exists) is initialized to the value
  101383. ** of the OFFSET. The iLimit register is initialized to LIMIT. Register
  101384. ** iOffset+1 is initialized to LIMIT+OFFSET.
  101385. **
  101386. ** Only if pLimit!=0 or pOffset!=0 do the limit registers get
  101387. ** redefined. The UNION ALL operator uses this property to force
  101388. ** the reuse of the same limit and offset registers across multiple
  101389. ** SELECT statements.
  101390. */
  101391. static void computeLimitRegisters(Parse *pParse, Select *p, int iBreak){
  101392. Vdbe *v = 0;
  101393. int iLimit = 0;
  101394. int iOffset;
  101395. int addr1, n;
  101396. if( p->iLimit ) return;
  101397. /*
  101398. ** "LIMIT -1" always shows all rows. There is some
  101399. ** controversy about what the correct behavior should be.
  101400. ** The current implementation interprets "LIMIT 0" to mean
  101401. ** no rows.
  101402. */
  101403. sqlite3ExprCacheClear(pParse);
  101404. assert( p->pOffset==0 || p->pLimit!=0 );
  101405. if( p->pLimit ){
  101406. p->iLimit = iLimit = ++pParse->nMem;
  101407. v = sqlite3GetVdbe(pParse);
  101408. assert( v!=0 );
  101409. if( sqlite3ExprIsInteger(p->pLimit, &n) ){
  101410. sqlite3VdbeAddOp2(v, OP_Integer, n, iLimit);
  101411. VdbeComment((v, "LIMIT counter"));
  101412. if( n==0 ){
  101413. sqlite3VdbeAddOp2(v, OP_Goto, 0, iBreak);
  101414. }else if( n>=0 && p->nSelectRow>(u64)n ){
  101415. p->nSelectRow = n;
  101416. }
  101417. }else{
  101418. sqlite3ExprCode(pParse, p->pLimit, iLimit);
  101419. sqlite3VdbeAddOp1(v, OP_MustBeInt, iLimit); VdbeCoverage(v);
  101420. VdbeComment((v, "LIMIT counter"));
  101421. sqlite3VdbeAddOp2(v, OP_IfNot, iLimit, iBreak); VdbeCoverage(v);
  101422. }
  101423. if( p->pOffset ){
  101424. p->iOffset = iOffset = ++pParse->nMem;
  101425. pParse->nMem++; /* Allocate an extra register for limit+offset */
  101426. sqlite3ExprCode(pParse, p->pOffset, iOffset);
  101427. sqlite3VdbeAddOp1(v, OP_MustBeInt, iOffset); VdbeCoverage(v);
  101428. VdbeComment((v, "OFFSET counter"));
  101429. addr1 = sqlite3VdbeAddOp1(v, OP_IfPos, iOffset); VdbeCoverage(v);
  101430. sqlite3VdbeAddOp2(v, OP_Integer, 0, iOffset);
  101431. sqlite3VdbeJumpHere(v, addr1);
  101432. sqlite3VdbeAddOp3(v, OP_Add, iLimit, iOffset, iOffset+1);
  101433. VdbeComment((v, "LIMIT+OFFSET"));
  101434. addr1 = sqlite3VdbeAddOp1(v, OP_IfPos, iLimit); VdbeCoverage(v);
  101435. sqlite3VdbeAddOp2(v, OP_Integer, -1, iOffset+1);
  101436. sqlite3VdbeJumpHere(v, addr1);
  101437. }
  101438. }
  101439. }
  101440. #ifndef SQLITE_OMIT_COMPOUND_SELECT
  101441. /*
  101442. ** Return the appropriate collating sequence for the iCol-th column of
  101443. ** the result set for the compound-select statement "p". Return NULL if
  101444. ** the column has no default collating sequence.
  101445. **
  101446. ** The collating sequence for the compound select is taken from the
  101447. ** left-most term of the select that has a collating sequence.
  101448. */
  101449. static CollSeq *multiSelectCollSeq(Parse *pParse, Select *p, int iCol){
  101450. CollSeq *pRet;
  101451. if( p->pPrior ){
  101452. pRet = multiSelectCollSeq(pParse, p->pPrior, iCol);
  101453. }else{
  101454. pRet = 0;
  101455. }
  101456. assert( iCol>=0 );
  101457. if( pRet==0 && iCol<p->pEList->nExpr ){
  101458. pRet = sqlite3ExprCollSeq(pParse, p->pEList->a[iCol].pExpr);
  101459. }
  101460. return pRet;
  101461. }
  101462. /*
  101463. ** The select statement passed as the second parameter is a compound SELECT
  101464. ** with an ORDER BY clause. This function allocates and returns a KeyInfo
  101465. ** structure suitable for implementing the ORDER BY.
  101466. **
  101467. ** Space to hold the KeyInfo structure is obtained from malloc. The calling
  101468. ** function is responsible for ensuring that this structure is eventually
  101469. ** freed.
  101470. */
  101471. static KeyInfo *multiSelectOrderByKeyInfo(Parse *pParse, Select *p, int nExtra){
  101472. ExprList *pOrderBy = p->pOrderBy;
  101473. int nOrderBy = p->pOrderBy->nExpr;
  101474. sqlite3 *db = pParse->db;
  101475. KeyInfo *pRet = sqlite3KeyInfoAlloc(db, nOrderBy+nExtra, 1);
  101476. if( pRet ){
  101477. int i;
  101478. for(i=0; i<nOrderBy; i++){
  101479. struct ExprList_item *pItem = &pOrderBy->a[i];
  101480. Expr *pTerm = pItem->pExpr;
  101481. CollSeq *pColl;
  101482. if( pTerm->flags & EP_Collate ){
  101483. pColl = sqlite3ExprCollSeq(pParse, pTerm);
  101484. }else{
  101485. pColl = multiSelectCollSeq(pParse, p, pItem->u.x.iOrderByCol-1);
  101486. if( pColl==0 ) pColl = db->pDfltColl;
  101487. pOrderBy->a[i].pExpr =
  101488. sqlite3ExprAddCollateString(pParse, pTerm, pColl->zName);
  101489. }
  101490. assert( sqlite3KeyInfoIsWriteable(pRet) );
  101491. pRet->aColl[i] = pColl;
  101492. pRet->aSortOrder[i] = pOrderBy->a[i].sortOrder;
  101493. }
  101494. }
  101495. return pRet;
  101496. }
  101497. #ifndef SQLITE_OMIT_CTE
  101498. /*
  101499. ** This routine generates VDBE code to compute the content of a WITH RECURSIVE
  101500. ** query of the form:
  101501. **
  101502. ** <recursive-table> AS (<setup-query> UNION [ALL] <recursive-query>)
  101503. ** \___________/ \_______________/
  101504. ** p->pPrior p
  101505. **
  101506. **
  101507. ** There is exactly one reference to the recursive-table in the FROM clause
  101508. ** of recursive-query, marked with the SrcList->a[].isRecursive flag.
  101509. **
  101510. ** The setup-query runs once to generate an initial set of rows that go
  101511. ** into a Queue table. Rows are extracted from the Queue table one by
  101512. ** one. Each row extracted from Queue is output to pDest. Then the single
  101513. ** extracted row (now in the iCurrent table) becomes the content of the
  101514. ** recursive-table for a recursive-query run. The output of the recursive-query
  101515. ** is added back into the Queue table. Then another row is extracted from Queue
  101516. ** and the iteration continues until the Queue table is empty.
  101517. **
  101518. ** If the compound query operator is UNION then no duplicate rows are ever
  101519. ** inserted into the Queue table. The iDistinct table keeps a copy of all rows
  101520. ** that have ever been inserted into Queue and causes duplicates to be
  101521. ** discarded. If the operator is UNION ALL, then duplicates are allowed.
  101522. **
  101523. ** If the query has an ORDER BY, then entries in the Queue table are kept in
  101524. ** ORDER BY order and the first entry is extracted for each cycle. Without
  101525. ** an ORDER BY, the Queue table is just a FIFO.
  101526. **
  101527. ** If a LIMIT clause is provided, then the iteration stops after LIMIT rows
  101528. ** have been output to pDest. A LIMIT of zero means to output no rows and a
  101529. ** negative LIMIT means to output all rows. If there is also an OFFSET clause
  101530. ** with a positive value, then the first OFFSET outputs are discarded rather
  101531. ** than being sent to pDest. The LIMIT count does not begin until after OFFSET
  101532. ** rows have been skipped.
  101533. */
  101534. static void generateWithRecursiveQuery(
  101535. Parse *pParse, /* Parsing context */
  101536. Select *p, /* The recursive SELECT to be coded */
  101537. SelectDest *pDest /* What to do with query results */
  101538. ){
  101539. SrcList *pSrc = p->pSrc; /* The FROM clause of the recursive query */
  101540. int nCol = p->pEList->nExpr; /* Number of columns in the recursive table */
  101541. Vdbe *v = pParse->pVdbe; /* The prepared statement under construction */
  101542. Select *pSetup = p->pPrior; /* The setup query */
  101543. int addrTop; /* Top of the loop */
  101544. int addrCont, addrBreak; /* CONTINUE and BREAK addresses */
  101545. int iCurrent = 0; /* The Current table */
  101546. int regCurrent; /* Register holding Current table */
  101547. int iQueue; /* The Queue table */
  101548. int iDistinct = 0; /* To ensure unique results if UNION */
  101549. int eDest = SRT_Fifo; /* How to write to Queue */
  101550. SelectDest destQueue; /* SelectDest targetting the Queue table */
  101551. int i; /* Loop counter */
  101552. int rc; /* Result code */
  101553. ExprList *pOrderBy; /* The ORDER BY clause */
  101554. Expr *pLimit, *pOffset; /* Saved LIMIT and OFFSET */
  101555. int regLimit, regOffset; /* Registers used by LIMIT and OFFSET */
  101556. /* Obtain authorization to do a recursive query */
  101557. if( sqlite3AuthCheck(pParse, SQLITE_RECURSIVE, 0, 0, 0) ) return;
  101558. /* Process the LIMIT and OFFSET clauses, if they exist */
  101559. addrBreak = sqlite3VdbeMakeLabel(v);
  101560. computeLimitRegisters(pParse, p, addrBreak);
  101561. pLimit = p->pLimit;
  101562. pOffset = p->pOffset;
  101563. regLimit = p->iLimit;
  101564. regOffset = p->iOffset;
  101565. p->pLimit = p->pOffset = 0;
  101566. p->iLimit = p->iOffset = 0;
  101567. pOrderBy = p->pOrderBy;
  101568. /* Locate the cursor number of the Current table */
  101569. for(i=0; ALWAYS(i<pSrc->nSrc); i++){
  101570. if( pSrc->a[i].isRecursive ){
  101571. iCurrent = pSrc->a[i].iCursor;
  101572. break;
  101573. }
  101574. }
  101575. /* Allocate cursors numbers for Queue and Distinct. The cursor number for
  101576. ** the Distinct table must be exactly one greater than Queue in order
  101577. ** for the SRT_DistFifo and SRT_DistQueue destinations to work. */
  101578. iQueue = pParse->nTab++;
  101579. if( p->op==TK_UNION ){
  101580. eDest = pOrderBy ? SRT_DistQueue : SRT_DistFifo;
  101581. iDistinct = pParse->nTab++;
  101582. }else{
  101583. eDest = pOrderBy ? SRT_Queue : SRT_Fifo;
  101584. }
  101585. sqlite3SelectDestInit(&destQueue, eDest, iQueue);
  101586. /* Allocate cursors for Current, Queue, and Distinct. */
  101587. regCurrent = ++pParse->nMem;
  101588. sqlite3VdbeAddOp3(v, OP_OpenPseudo, iCurrent, regCurrent, nCol);
  101589. if( pOrderBy ){
  101590. KeyInfo *pKeyInfo = multiSelectOrderByKeyInfo(pParse, p, 1);
  101591. sqlite3VdbeAddOp4(v, OP_OpenEphemeral, iQueue, pOrderBy->nExpr+2, 0,
  101592. (char*)pKeyInfo, P4_KEYINFO);
  101593. destQueue.pOrderBy = pOrderBy;
  101594. }else{
  101595. sqlite3VdbeAddOp2(v, OP_OpenEphemeral, iQueue, nCol);
  101596. }
  101597. VdbeComment((v, "Queue table"));
  101598. if( iDistinct ){
  101599. p->addrOpenEphm[0] = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, iDistinct, 0);
  101600. p->selFlags |= SF_UsesEphemeral;
  101601. }
  101602. /* Detach the ORDER BY clause from the compound SELECT */
  101603. p->pOrderBy = 0;
  101604. /* Store the results of the setup-query in Queue. */
  101605. pSetup->pNext = 0;
  101606. rc = sqlite3Select(pParse, pSetup, &destQueue);
  101607. pSetup->pNext = p;
  101608. if( rc ) goto end_of_recursive_query;
  101609. /* Find the next row in the Queue and output that row */
  101610. addrTop = sqlite3VdbeAddOp2(v, OP_Rewind, iQueue, addrBreak); VdbeCoverage(v);
  101611. /* Transfer the next row in Queue over to Current */
  101612. sqlite3VdbeAddOp1(v, OP_NullRow, iCurrent); /* To reset column cache */
  101613. if( pOrderBy ){
  101614. sqlite3VdbeAddOp3(v, OP_Column, iQueue, pOrderBy->nExpr+1, regCurrent);
  101615. }else{
  101616. sqlite3VdbeAddOp2(v, OP_RowData, iQueue, regCurrent);
  101617. }
  101618. sqlite3VdbeAddOp1(v, OP_Delete, iQueue);
  101619. /* Output the single row in Current */
  101620. addrCont = sqlite3VdbeMakeLabel(v);
  101621. codeOffset(v, regOffset, addrCont);
  101622. selectInnerLoop(pParse, p, p->pEList, iCurrent,
  101623. 0, 0, pDest, addrCont, addrBreak);
  101624. if( regLimit ){
  101625. sqlite3VdbeAddOp2(v, OP_DecrJumpZero, regLimit, addrBreak);
  101626. VdbeCoverage(v);
  101627. }
  101628. sqlite3VdbeResolveLabel(v, addrCont);
  101629. /* Execute the recursive SELECT taking the single row in Current as
  101630. ** the value for the recursive-table. Store the results in the Queue.
  101631. */
  101632. p->pPrior = 0;
  101633. sqlite3Select(pParse, p, &destQueue);
  101634. assert( p->pPrior==0 );
  101635. p->pPrior = pSetup;
  101636. /* Keep running the loop until the Queue is empty */
  101637. sqlite3VdbeAddOp2(v, OP_Goto, 0, addrTop);
  101638. sqlite3VdbeResolveLabel(v, addrBreak);
  101639. end_of_recursive_query:
  101640. sqlite3ExprListDelete(pParse->db, p->pOrderBy);
  101641. p->pOrderBy = pOrderBy;
  101642. p->pLimit = pLimit;
  101643. p->pOffset = pOffset;
  101644. return;
  101645. }
  101646. #endif /* SQLITE_OMIT_CTE */
  101647. /* Forward references */
  101648. static int multiSelectOrderBy(
  101649. Parse *pParse, /* Parsing context */
  101650. Select *p, /* The right-most of SELECTs to be coded */
  101651. SelectDest *pDest /* What to do with query results */
  101652. );
  101653. /*
  101654. ** Error message for when two or more terms of a compound select have different
  101655. ** size result sets.
  101656. */
  101657. static void selectWrongNumTermsError(Parse *pParse, Select *p){
  101658. if( p->selFlags & SF_Values ){
  101659. sqlite3ErrorMsg(pParse, "all VALUES must have the same number of terms");
  101660. }else{
  101661. sqlite3ErrorMsg(pParse, "SELECTs to the left and right of %s"
  101662. " do not have the same number of result columns", selectOpName(p->op));
  101663. }
  101664. }
  101665. /*
  101666. ** Handle the special case of a compound-select that originates from a
  101667. ** VALUES clause. By handling this as a special case, we avoid deep
  101668. ** recursion, and thus do not need to enforce the SQLITE_LIMIT_COMPOUND_SELECT
  101669. ** on a VALUES clause.
  101670. **
  101671. ** Because the Select object originates from a VALUES clause:
  101672. ** (1) It has no LIMIT or OFFSET
  101673. ** (2) All terms are UNION ALL
  101674. ** (3) There is no ORDER BY clause
  101675. */
  101676. static int multiSelectValues(
  101677. Parse *pParse, /* Parsing context */
  101678. Select *p, /* The right-most of SELECTs to be coded */
  101679. SelectDest *pDest /* What to do with query results */
  101680. ){
  101681. Select *pPrior;
  101682. int nExpr = p->pEList->nExpr;
  101683. int nRow = 1;
  101684. int rc = 0;
  101685. assert( p->selFlags & SF_MultiValue );
  101686. do{
  101687. assert( p->selFlags & SF_Values );
  101688. assert( p->op==TK_ALL || (p->op==TK_SELECT && p->pPrior==0) );
  101689. assert( p->pLimit==0 );
  101690. assert( p->pOffset==0 );
  101691. if( p->pEList->nExpr!=nExpr ){
  101692. selectWrongNumTermsError(pParse, p);
  101693. return 1;
  101694. }
  101695. if( p->pPrior==0 ) break;
  101696. assert( p->pPrior->pNext==p );
  101697. p = p->pPrior;
  101698. nRow++;
  101699. }while(1);
  101700. while( p ){
  101701. pPrior = p->pPrior;
  101702. p->pPrior = 0;
  101703. rc = sqlite3Select(pParse, p, pDest);
  101704. p->pPrior = pPrior;
  101705. if( rc ) break;
  101706. p->nSelectRow = nRow;
  101707. p = p->pNext;
  101708. }
  101709. return rc;
  101710. }
  101711. /*
  101712. ** This routine is called to process a compound query form from
  101713. ** two or more separate queries using UNION, UNION ALL, EXCEPT, or
  101714. ** INTERSECT
  101715. **
  101716. ** "p" points to the right-most of the two queries. the query on the
  101717. ** left is p->pPrior. The left query could also be a compound query
  101718. ** in which case this routine will be called recursively.
  101719. **
  101720. ** The results of the total query are to be written into a destination
  101721. ** of type eDest with parameter iParm.
  101722. **
  101723. ** Example 1: Consider a three-way compound SQL statement.
  101724. **
  101725. ** SELECT a FROM t1 UNION SELECT b FROM t2 UNION SELECT c FROM t3
  101726. **
  101727. ** This statement is parsed up as follows:
  101728. **
  101729. ** SELECT c FROM t3
  101730. ** |
  101731. ** `-----> SELECT b FROM t2
  101732. ** |
  101733. ** `------> SELECT a FROM t1
  101734. **
  101735. ** The arrows in the diagram above represent the Select.pPrior pointer.
  101736. ** So if this routine is called with p equal to the t3 query, then
  101737. ** pPrior will be the t2 query. p->op will be TK_UNION in this case.
  101738. **
  101739. ** Notice that because of the way SQLite parses compound SELECTs, the
  101740. ** individual selects always group from left to right.
  101741. */
  101742. static int multiSelect(
  101743. Parse *pParse, /* Parsing context */
  101744. Select *p, /* The right-most of SELECTs to be coded */
  101745. SelectDest *pDest /* What to do with query results */
  101746. ){
  101747. int rc = SQLITE_OK; /* Success code from a subroutine */
  101748. Select *pPrior; /* Another SELECT immediately to our left */
  101749. Vdbe *v; /* Generate code to this VDBE */
  101750. SelectDest dest; /* Alternative data destination */
  101751. Select *pDelete = 0; /* Chain of simple selects to delete */
  101752. sqlite3 *db; /* Database connection */
  101753. #ifndef SQLITE_OMIT_EXPLAIN
  101754. int iSub1 = 0; /* EQP id of left-hand query */
  101755. int iSub2 = 0; /* EQP id of right-hand query */
  101756. #endif
  101757. /* Make sure there is no ORDER BY or LIMIT clause on prior SELECTs. Only
  101758. ** the last (right-most) SELECT in the series may have an ORDER BY or LIMIT.
  101759. */
  101760. assert( p && p->pPrior ); /* Calling function guarantees this much */
  101761. assert( (p->selFlags & SF_Recursive)==0 || p->op==TK_ALL || p->op==TK_UNION );
  101762. db = pParse->db;
  101763. pPrior = p->pPrior;
  101764. dest = *pDest;
  101765. if( pPrior->pOrderBy ){
  101766. sqlite3ErrorMsg(pParse,"ORDER BY clause should come after %s not before",
  101767. selectOpName(p->op));
  101768. rc = 1;
  101769. goto multi_select_end;
  101770. }
  101771. if( pPrior->pLimit ){
  101772. sqlite3ErrorMsg(pParse,"LIMIT clause should come after %s not before",
  101773. selectOpName(p->op));
  101774. rc = 1;
  101775. goto multi_select_end;
  101776. }
  101777. v = sqlite3GetVdbe(pParse);
  101778. assert( v!=0 ); /* The VDBE already created by calling function */
  101779. /* Create the destination temporary table if necessary
  101780. */
  101781. if( dest.eDest==SRT_EphemTab ){
  101782. assert( p->pEList );
  101783. sqlite3VdbeAddOp2(v, OP_OpenEphemeral, dest.iSDParm, p->pEList->nExpr);
  101784. sqlite3VdbeChangeP5(v, BTREE_UNORDERED);
  101785. dest.eDest = SRT_Table;
  101786. }
  101787. /* Special handling for a compound-select that originates as a VALUES clause.
  101788. */
  101789. if( p->selFlags & SF_MultiValue ){
  101790. rc = multiSelectValues(pParse, p, &dest);
  101791. goto multi_select_end;
  101792. }
  101793. /* Make sure all SELECTs in the statement have the same number of elements
  101794. ** in their result sets.
  101795. */
  101796. assert( p->pEList && pPrior->pEList );
  101797. if( p->pEList->nExpr!=pPrior->pEList->nExpr ){
  101798. selectWrongNumTermsError(pParse, p);
  101799. rc = 1;
  101800. goto multi_select_end;
  101801. }
  101802. #ifndef SQLITE_OMIT_CTE
  101803. if( p->selFlags & SF_Recursive ){
  101804. generateWithRecursiveQuery(pParse, p, &dest);
  101805. }else
  101806. #endif
  101807. /* Compound SELECTs that have an ORDER BY clause are handled separately.
  101808. */
  101809. if( p->pOrderBy ){
  101810. return multiSelectOrderBy(pParse, p, pDest);
  101811. }else
  101812. /* Generate code for the left and right SELECT statements.
  101813. */
  101814. switch( p->op ){
  101815. case TK_ALL: {
  101816. int addr = 0;
  101817. int nLimit;
  101818. assert( !pPrior->pLimit );
  101819. pPrior->iLimit = p->iLimit;
  101820. pPrior->iOffset = p->iOffset;
  101821. pPrior->pLimit = p->pLimit;
  101822. pPrior->pOffset = p->pOffset;
  101823. explainSetInteger(iSub1, pParse->iNextSelectId);
  101824. rc = sqlite3Select(pParse, pPrior, &dest);
  101825. p->pLimit = 0;
  101826. p->pOffset = 0;
  101827. if( rc ){
  101828. goto multi_select_end;
  101829. }
  101830. p->pPrior = 0;
  101831. p->iLimit = pPrior->iLimit;
  101832. p->iOffset = pPrior->iOffset;
  101833. if( p->iLimit ){
  101834. addr = sqlite3VdbeAddOp1(v, OP_IfNot, p->iLimit); VdbeCoverage(v);
  101835. VdbeComment((v, "Jump ahead if LIMIT reached"));
  101836. }
  101837. explainSetInteger(iSub2, pParse->iNextSelectId);
  101838. rc = sqlite3Select(pParse, p, &dest);
  101839. testcase( rc!=SQLITE_OK );
  101840. pDelete = p->pPrior;
  101841. p->pPrior = pPrior;
  101842. p->nSelectRow += pPrior->nSelectRow;
  101843. if( pPrior->pLimit
  101844. && sqlite3ExprIsInteger(pPrior->pLimit, &nLimit)
  101845. && nLimit>0 && p->nSelectRow > (u64)nLimit
  101846. ){
  101847. p->nSelectRow = nLimit;
  101848. }
  101849. if( addr ){
  101850. sqlite3VdbeJumpHere(v, addr);
  101851. }
  101852. break;
  101853. }
  101854. case TK_EXCEPT:
  101855. case TK_UNION: {
  101856. int unionTab; /* Cursor number of the temporary table holding result */
  101857. u8 op = 0; /* One of the SRT_ operations to apply to self */
  101858. int priorOp; /* The SRT_ operation to apply to prior selects */
  101859. Expr *pLimit, *pOffset; /* Saved values of p->nLimit and p->nOffset */
  101860. int addr;
  101861. SelectDest uniondest;
  101862. testcase( p->op==TK_EXCEPT );
  101863. testcase( p->op==TK_UNION );
  101864. priorOp = SRT_Union;
  101865. if( dest.eDest==priorOp ){
  101866. /* We can reuse a temporary table generated by a SELECT to our
  101867. ** right.
  101868. */
  101869. assert( p->pLimit==0 ); /* Not allowed on leftward elements */
  101870. assert( p->pOffset==0 ); /* Not allowed on leftward elements */
  101871. unionTab = dest.iSDParm;
  101872. }else{
  101873. /* We will need to create our own temporary table to hold the
  101874. ** intermediate results.
  101875. */
  101876. unionTab = pParse->nTab++;
  101877. assert( p->pOrderBy==0 );
  101878. addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, unionTab, 0);
  101879. assert( p->addrOpenEphm[0] == -1 );
  101880. p->addrOpenEphm[0] = addr;
  101881. findRightmost(p)->selFlags |= SF_UsesEphemeral;
  101882. assert( p->pEList );
  101883. }
  101884. /* Code the SELECT statements to our left
  101885. */
  101886. assert( !pPrior->pOrderBy );
  101887. sqlite3SelectDestInit(&uniondest, priorOp, unionTab);
  101888. explainSetInteger(iSub1, pParse->iNextSelectId);
  101889. rc = sqlite3Select(pParse, pPrior, &uniondest);
  101890. if( rc ){
  101891. goto multi_select_end;
  101892. }
  101893. /* Code the current SELECT statement
  101894. */
  101895. if( p->op==TK_EXCEPT ){
  101896. op = SRT_Except;
  101897. }else{
  101898. assert( p->op==TK_UNION );
  101899. op = SRT_Union;
  101900. }
  101901. p->pPrior = 0;
  101902. pLimit = p->pLimit;
  101903. p->pLimit = 0;
  101904. pOffset = p->pOffset;
  101905. p->pOffset = 0;
  101906. uniondest.eDest = op;
  101907. explainSetInteger(iSub2, pParse->iNextSelectId);
  101908. rc = sqlite3Select(pParse, p, &uniondest);
  101909. testcase( rc!=SQLITE_OK );
  101910. /* Query flattening in sqlite3Select() might refill p->pOrderBy.
  101911. ** Be sure to delete p->pOrderBy, therefore, to avoid a memory leak. */
  101912. sqlite3ExprListDelete(db, p->pOrderBy);
  101913. pDelete = p->pPrior;
  101914. p->pPrior = pPrior;
  101915. p->pOrderBy = 0;
  101916. if( p->op==TK_UNION ) p->nSelectRow += pPrior->nSelectRow;
  101917. sqlite3ExprDelete(db, p->pLimit);
  101918. p->pLimit = pLimit;
  101919. p->pOffset = pOffset;
  101920. p->iLimit = 0;
  101921. p->iOffset = 0;
  101922. /* Convert the data in the temporary table into whatever form
  101923. ** it is that we currently need.
  101924. */
  101925. assert( unionTab==dest.iSDParm || dest.eDest!=priorOp );
  101926. if( dest.eDest!=priorOp ){
  101927. int iCont, iBreak, iStart;
  101928. assert( p->pEList );
  101929. if( dest.eDest==SRT_Output ){
  101930. Select *pFirst = p;
  101931. while( pFirst->pPrior ) pFirst = pFirst->pPrior;
  101932. generateColumnNames(pParse, 0, pFirst->pEList);
  101933. }
  101934. iBreak = sqlite3VdbeMakeLabel(v);
  101935. iCont = sqlite3VdbeMakeLabel(v);
  101936. computeLimitRegisters(pParse, p, iBreak);
  101937. sqlite3VdbeAddOp2(v, OP_Rewind, unionTab, iBreak); VdbeCoverage(v);
  101938. iStart = sqlite3VdbeCurrentAddr(v);
  101939. selectInnerLoop(pParse, p, p->pEList, unionTab,
  101940. 0, 0, &dest, iCont, iBreak);
  101941. sqlite3VdbeResolveLabel(v, iCont);
  101942. sqlite3VdbeAddOp2(v, OP_Next, unionTab, iStart); VdbeCoverage(v);
  101943. sqlite3VdbeResolveLabel(v, iBreak);
  101944. sqlite3VdbeAddOp2(v, OP_Close, unionTab, 0);
  101945. }
  101946. break;
  101947. }
  101948. default: assert( p->op==TK_INTERSECT ); {
  101949. int tab1, tab2;
  101950. int iCont, iBreak, iStart;
  101951. Expr *pLimit, *pOffset;
  101952. int addr;
  101953. SelectDest intersectdest;
  101954. int r1;
  101955. /* INTERSECT is different from the others since it requires
  101956. ** two temporary tables. Hence it has its own case. Begin
  101957. ** by allocating the tables we will need.
  101958. */
  101959. tab1 = pParse->nTab++;
  101960. tab2 = pParse->nTab++;
  101961. assert( p->pOrderBy==0 );
  101962. addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, tab1, 0);
  101963. assert( p->addrOpenEphm[0] == -1 );
  101964. p->addrOpenEphm[0] = addr;
  101965. findRightmost(p)->selFlags |= SF_UsesEphemeral;
  101966. assert( p->pEList );
  101967. /* Code the SELECTs to our left into temporary table "tab1".
  101968. */
  101969. sqlite3SelectDestInit(&intersectdest, SRT_Union, tab1);
  101970. explainSetInteger(iSub1, pParse->iNextSelectId);
  101971. rc = sqlite3Select(pParse, pPrior, &intersectdest);
  101972. if( rc ){
  101973. goto multi_select_end;
  101974. }
  101975. /* Code the current SELECT into temporary table "tab2"
  101976. */
  101977. addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, tab2, 0);
  101978. assert( p->addrOpenEphm[1] == -1 );
  101979. p->addrOpenEphm[1] = addr;
  101980. p->pPrior = 0;
  101981. pLimit = p->pLimit;
  101982. p->pLimit = 0;
  101983. pOffset = p->pOffset;
  101984. p->pOffset = 0;
  101985. intersectdest.iSDParm = tab2;
  101986. explainSetInteger(iSub2, pParse->iNextSelectId);
  101987. rc = sqlite3Select(pParse, p, &intersectdest);
  101988. testcase( rc!=SQLITE_OK );
  101989. pDelete = p->pPrior;
  101990. p->pPrior = pPrior;
  101991. if( p->nSelectRow>pPrior->nSelectRow ) p->nSelectRow = pPrior->nSelectRow;
  101992. sqlite3ExprDelete(db, p->pLimit);
  101993. p->pLimit = pLimit;
  101994. p->pOffset = pOffset;
  101995. /* Generate code to take the intersection of the two temporary
  101996. ** tables.
  101997. */
  101998. assert( p->pEList );
  101999. if( dest.eDest==SRT_Output ){
  102000. Select *pFirst = p;
  102001. while( pFirst->pPrior ) pFirst = pFirst->pPrior;
  102002. generateColumnNames(pParse, 0, pFirst->pEList);
  102003. }
  102004. iBreak = sqlite3VdbeMakeLabel(v);
  102005. iCont = sqlite3VdbeMakeLabel(v);
  102006. computeLimitRegisters(pParse, p, iBreak);
  102007. sqlite3VdbeAddOp2(v, OP_Rewind, tab1, iBreak); VdbeCoverage(v);
  102008. r1 = sqlite3GetTempReg(pParse);
  102009. iStart = sqlite3VdbeAddOp2(v, OP_RowKey, tab1, r1);
  102010. sqlite3VdbeAddOp4Int(v, OP_NotFound, tab2, iCont, r1, 0); VdbeCoverage(v);
  102011. sqlite3ReleaseTempReg(pParse, r1);
  102012. selectInnerLoop(pParse, p, p->pEList, tab1,
  102013. 0, 0, &dest, iCont, iBreak);
  102014. sqlite3VdbeResolveLabel(v, iCont);
  102015. sqlite3VdbeAddOp2(v, OP_Next, tab1, iStart); VdbeCoverage(v);
  102016. sqlite3VdbeResolveLabel(v, iBreak);
  102017. sqlite3VdbeAddOp2(v, OP_Close, tab2, 0);
  102018. sqlite3VdbeAddOp2(v, OP_Close, tab1, 0);
  102019. break;
  102020. }
  102021. }
  102022. explainComposite(pParse, p->op, iSub1, iSub2, p->op!=TK_ALL);
  102023. /* Compute collating sequences used by
  102024. ** temporary tables needed to implement the compound select.
  102025. ** Attach the KeyInfo structure to all temporary tables.
  102026. **
  102027. ** This section is run by the right-most SELECT statement only.
  102028. ** SELECT statements to the left always skip this part. The right-most
  102029. ** SELECT might also skip this part if it has no ORDER BY clause and
  102030. ** no temp tables are required.
  102031. */
  102032. if( p->selFlags & SF_UsesEphemeral ){
  102033. int i; /* Loop counter */
  102034. KeyInfo *pKeyInfo; /* Collating sequence for the result set */
  102035. Select *pLoop; /* For looping through SELECT statements */
  102036. CollSeq **apColl; /* For looping through pKeyInfo->aColl[] */
  102037. int nCol; /* Number of columns in result set */
  102038. assert( p->pNext==0 );
  102039. nCol = p->pEList->nExpr;
  102040. pKeyInfo = sqlite3KeyInfoAlloc(db, nCol, 1);
  102041. if( !pKeyInfo ){
  102042. rc = SQLITE_NOMEM;
  102043. goto multi_select_end;
  102044. }
  102045. for(i=0, apColl=pKeyInfo->aColl; i<nCol; i++, apColl++){
  102046. *apColl = multiSelectCollSeq(pParse, p, i);
  102047. if( 0==*apColl ){
  102048. *apColl = db->pDfltColl;
  102049. }
  102050. }
  102051. for(pLoop=p; pLoop; pLoop=pLoop->pPrior){
  102052. for(i=0; i<2; i++){
  102053. int addr = pLoop->addrOpenEphm[i];
  102054. if( addr<0 ){
  102055. /* If [0] is unused then [1] is also unused. So we can
  102056. ** always safely abort as soon as the first unused slot is found */
  102057. assert( pLoop->addrOpenEphm[1]<0 );
  102058. break;
  102059. }
  102060. sqlite3VdbeChangeP2(v, addr, nCol);
  102061. sqlite3VdbeChangeP4(v, addr, (char*)sqlite3KeyInfoRef(pKeyInfo),
  102062. P4_KEYINFO);
  102063. pLoop->addrOpenEphm[i] = -1;
  102064. }
  102065. }
  102066. sqlite3KeyInfoUnref(pKeyInfo);
  102067. }
  102068. multi_select_end:
  102069. pDest->iSdst = dest.iSdst;
  102070. pDest->nSdst = dest.nSdst;
  102071. sqlite3SelectDelete(db, pDelete);
  102072. return rc;
  102073. }
  102074. #endif /* SQLITE_OMIT_COMPOUND_SELECT */
  102075. /*
  102076. ** Code an output subroutine for a coroutine implementation of a
  102077. ** SELECT statment.
  102078. **
  102079. ** The data to be output is contained in pIn->iSdst. There are
  102080. ** pIn->nSdst columns to be output. pDest is where the output should
  102081. ** be sent.
  102082. **
  102083. ** regReturn is the number of the register holding the subroutine
  102084. ** return address.
  102085. **
  102086. ** If regPrev>0 then it is the first register in a vector that
  102087. ** records the previous output. mem[regPrev] is a flag that is false
  102088. ** if there has been no previous output. If regPrev>0 then code is
  102089. ** generated to suppress duplicates. pKeyInfo is used for comparing
  102090. ** keys.
  102091. **
  102092. ** If the LIMIT found in p->iLimit is reached, jump immediately to
  102093. ** iBreak.
  102094. */
  102095. static int generateOutputSubroutine(
  102096. Parse *pParse, /* Parsing context */
  102097. Select *p, /* The SELECT statement */
  102098. SelectDest *pIn, /* Coroutine supplying data */
  102099. SelectDest *pDest, /* Where to send the data */
  102100. int regReturn, /* The return address register */
  102101. int regPrev, /* Previous result register. No uniqueness if 0 */
  102102. KeyInfo *pKeyInfo, /* For comparing with previous entry */
  102103. int iBreak /* Jump here if we hit the LIMIT */
  102104. ){
  102105. Vdbe *v = pParse->pVdbe;
  102106. int iContinue;
  102107. int addr;
  102108. addr = sqlite3VdbeCurrentAddr(v);
  102109. iContinue = sqlite3VdbeMakeLabel(v);
  102110. /* Suppress duplicates for UNION, EXCEPT, and INTERSECT
  102111. */
  102112. if( regPrev ){
  102113. int j1, j2;
  102114. j1 = sqlite3VdbeAddOp1(v, OP_IfNot, regPrev); VdbeCoverage(v);
  102115. j2 = sqlite3VdbeAddOp4(v, OP_Compare, pIn->iSdst, regPrev+1, pIn->nSdst,
  102116. (char*)sqlite3KeyInfoRef(pKeyInfo), P4_KEYINFO);
  102117. sqlite3VdbeAddOp3(v, OP_Jump, j2+2, iContinue, j2+2); VdbeCoverage(v);
  102118. sqlite3VdbeJumpHere(v, j1);
  102119. sqlite3VdbeAddOp3(v, OP_Copy, pIn->iSdst, regPrev+1, pIn->nSdst-1);
  102120. sqlite3VdbeAddOp2(v, OP_Integer, 1, regPrev);
  102121. }
  102122. if( pParse->db->mallocFailed ) return 0;
  102123. /* Suppress the first OFFSET entries if there is an OFFSET clause
  102124. */
  102125. codeOffset(v, p->iOffset, iContinue);
  102126. switch( pDest->eDest ){
  102127. /* Store the result as data using a unique key.
  102128. */
  102129. case SRT_Table:
  102130. case SRT_EphemTab: {
  102131. int r1 = sqlite3GetTempReg(pParse);
  102132. int r2 = sqlite3GetTempReg(pParse);
  102133. testcase( pDest->eDest==SRT_Table );
  102134. testcase( pDest->eDest==SRT_EphemTab );
  102135. sqlite3VdbeAddOp3(v, OP_MakeRecord, pIn->iSdst, pIn->nSdst, r1);
  102136. sqlite3VdbeAddOp2(v, OP_NewRowid, pDest->iSDParm, r2);
  102137. sqlite3VdbeAddOp3(v, OP_Insert, pDest->iSDParm, r1, r2);
  102138. sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
  102139. sqlite3ReleaseTempReg(pParse, r2);
  102140. sqlite3ReleaseTempReg(pParse, r1);
  102141. break;
  102142. }
  102143. #ifndef SQLITE_OMIT_SUBQUERY
  102144. /* If we are creating a set for an "expr IN (SELECT ...)" construct,
  102145. ** then there should be a single item on the stack. Write this
  102146. ** item into the set table with bogus data.
  102147. */
  102148. case SRT_Set: {
  102149. int r1;
  102150. assert( pIn->nSdst==1 || pParse->nErr>0 );
  102151. pDest->affSdst =
  102152. sqlite3CompareAffinity(p->pEList->a[0].pExpr, pDest->affSdst);
  102153. r1 = sqlite3GetTempReg(pParse);
  102154. sqlite3VdbeAddOp4(v, OP_MakeRecord, pIn->iSdst, 1, r1, &pDest->affSdst,1);
  102155. sqlite3ExprCacheAffinityChange(pParse, pIn->iSdst, 1);
  102156. sqlite3VdbeAddOp2(v, OP_IdxInsert, pDest->iSDParm, r1);
  102157. sqlite3ReleaseTempReg(pParse, r1);
  102158. break;
  102159. }
  102160. #if 0 /* Never occurs on an ORDER BY query */
  102161. /* If any row exist in the result set, record that fact and abort.
  102162. */
  102163. case SRT_Exists: {
  102164. sqlite3VdbeAddOp2(v, OP_Integer, 1, pDest->iSDParm);
  102165. /* The LIMIT clause will terminate the loop for us */
  102166. break;
  102167. }
  102168. #endif
  102169. /* If this is a scalar select that is part of an expression, then
  102170. ** store the results in the appropriate memory cell and break out
  102171. ** of the scan loop.
  102172. */
  102173. case SRT_Mem: {
  102174. assert( pIn->nSdst==1 || pParse->nErr>0 ); testcase( pIn->nSdst!=1 );
  102175. sqlite3ExprCodeMove(pParse, pIn->iSdst, pDest->iSDParm, 1);
  102176. /* The LIMIT clause will jump out of the loop for us */
  102177. break;
  102178. }
  102179. #endif /* #ifndef SQLITE_OMIT_SUBQUERY */
  102180. /* The results are stored in a sequence of registers
  102181. ** starting at pDest->iSdst. Then the co-routine yields.
  102182. */
  102183. case SRT_Coroutine: {
  102184. if( pDest->iSdst==0 ){
  102185. pDest->iSdst = sqlite3GetTempRange(pParse, pIn->nSdst);
  102186. pDest->nSdst = pIn->nSdst;
  102187. }
  102188. sqlite3ExprCodeMove(pParse, pIn->iSdst, pDest->iSdst, pIn->nSdst);
  102189. sqlite3VdbeAddOp1(v, OP_Yield, pDest->iSDParm);
  102190. break;
  102191. }
  102192. /* If none of the above, then the result destination must be
  102193. ** SRT_Output. This routine is never called with any other
  102194. ** destination other than the ones handled above or SRT_Output.
  102195. **
  102196. ** For SRT_Output, results are stored in a sequence of registers.
  102197. ** Then the OP_ResultRow opcode is used to cause sqlite3_step() to
  102198. ** return the next row of result.
  102199. */
  102200. default: {
  102201. assert( pDest->eDest==SRT_Output );
  102202. sqlite3VdbeAddOp2(v, OP_ResultRow, pIn->iSdst, pIn->nSdst);
  102203. sqlite3ExprCacheAffinityChange(pParse, pIn->iSdst, pIn->nSdst);
  102204. break;
  102205. }
  102206. }
  102207. /* Jump to the end of the loop if the LIMIT is reached.
  102208. */
  102209. if( p->iLimit ){
  102210. sqlite3VdbeAddOp2(v, OP_DecrJumpZero, p->iLimit, iBreak); VdbeCoverage(v);
  102211. }
  102212. /* Generate the subroutine return
  102213. */
  102214. sqlite3VdbeResolveLabel(v, iContinue);
  102215. sqlite3VdbeAddOp1(v, OP_Return, regReturn);
  102216. return addr;
  102217. }
  102218. /*
  102219. ** Alternative compound select code generator for cases when there
  102220. ** is an ORDER BY clause.
  102221. **
  102222. ** We assume a query of the following form:
  102223. **
  102224. ** <selectA> <operator> <selectB> ORDER BY <orderbylist>
  102225. **
  102226. ** <operator> is one of UNION ALL, UNION, EXCEPT, or INTERSECT. The idea
  102227. ** is to code both <selectA> and <selectB> with the ORDER BY clause as
  102228. ** co-routines. Then run the co-routines in parallel and merge the results
  102229. ** into the output. In addition to the two coroutines (called selectA and
  102230. ** selectB) there are 7 subroutines:
  102231. **
  102232. ** outA: Move the output of the selectA coroutine into the output
  102233. ** of the compound query.
  102234. **
  102235. ** outB: Move the output of the selectB coroutine into the output
  102236. ** of the compound query. (Only generated for UNION and
  102237. ** UNION ALL. EXCEPT and INSERTSECT never output a row that
  102238. ** appears only in B.)
  102239. **
  102240. ** AltB: Called when there is data from both coroutines and A<B.
  102241. **
  102242. ** AeqB: Called when there is data from both coroutines and A==B.
  102243. **
  102244. ** AgtB: Called when there is data from both coroutines and A>B.
  102245. **
  102246. ** EofA: Called when data is exhausted from selectA.
  102247. **
  102248. ** EofB: Called when data is exhausted from selectB.
  102249. **
  102250. ** The implementation of the latter five subroutines depend on which
  102251. ** <operator> is used:
  102252. **
  102253. **
  102254. ** UNION ALL UNION EXCEPT INTERSECT
  102255. ** ------------- ----------------- -------------- -----------------
  102256. ** AltB: outA, nextA outA, nextA outA, nextA nextA
  102257. **
  102258. ** AeqB: outA, nextA nextA nextA outA, nextA
  102259. **
  102260. ** AgtB: outB, nextB outB, nextB nextB nextB
  102261. **
  102262. ** EofA: outB, nextB outB, nextB halt halt
  102263. **
  102264. ** EofB: outA, nextA outA, nextA outA, nextA halt
  102265. **
  102266. ** In the AltB, AeqB, and AgtB subroutines, an EOF on A following nextA
  102267. ** causes an immediate jump to EofA and an EOF on B following nextB causes
  102268. ** an immediate jump to EofB. Within EofA and EofB, and EOF on entry or
  102269. ** following nextX causes a jump to the end of the select processing.
  102270. **
  102271. ** Duplicate removal in the UNION, EXCEPT, and INTERSECT cases is handled
  102272. ** within the output subroutine. The regPrev register set holds the previously
  102273. ** output value. A comparison is made against this value and the output
  102274. ** is skipped if the next results would be the same as the previous.
  102275. **
  102276. ** The implementation plan is to implement the two coroutines and seven
  102277. ** subroutines first, then put the control logic at the bottom. Like this:
  102278. **
  102279. ** goto Init
  102280. ** coA: coroutine for left query (A)
  102281. ** coB: coroutine for right query (B)
  102282. ** outA: output one row of A
  102283. ** outB: output one row of B (UNION and UNION ALL only)
  102284. ** EofA: ...
  102285. ** EofB: ...
  102286. ** AltB: ...
  102287. ** AeqB: ...
  102288. ** AgtB: ...
  102289. ** Init: initialize coroutine registers
  102290. ** yield coA
  102291. ** if eof(A) goto EofA
  102292. ** yield coB
  102293. ** if eof(B) goto EofB
  102294. ** Cmpr: Compare A, B
  102295. ** Jump AltB, AeqB, AgtB
  102296. ** End: ...
  102297. **
  102298. ** We call AltB, AeqB, AgtB, EofA, and EofB "subroutines" but they are not
  102299. ** actually called using Gosub and they do not Return. EofA and EofB loop
  102300. ** until all data is exhausted then jump to the "end" labe. AltB, AeqB,
  102301. ** and AgtB jump to either L2 or to one of EofA or EofB.
  102302. */
  102303. #ifndef SQLITE_OMIT_COMPOUND_SELECT
  102304. static int multiSelectOrderBy(
  102305. Parse *pParse, /* Parsing context */
  102306. Select *p, /* The right-most of SELECTs to be coded */
  102307. SelectDest *pDest /* What to do with query results */
  102308. ){
  102309. int i, j; /* Loop counters */
  102310. Select *pPrior; /* Another SELECT immediately to our left */
  102311. Vdbe *v; /* Generate code to this VDBE */
  102312. SelectDest destA; /* Destination for coroutine A */
  102313. SelectDest destB; /* Destination for coroutine B */
  102314. int regAddrA; /* Address register for select-A coroutine */
  102315. int regAddrB; /* Address register for select-B coroutine */
  102316. int addrSelectA; /* Address of the select-A coroutine */
  102317. int addrSelectB; /* Address of the select-B coroutine */
  102318. int regOutA; /* Address register for the output-A subroutine */
  102319. int regOutB; /* Address register for the output-B subroutine */
  102320. int addrOutA; /* Address of the output-A subroutine */
  102321. int addrOutB = 0; /* Address of the output-B subroutine */
  102322. int addrEofA; /* Address of the select-A-exhausted subroutine */
  102323. int addrEofA_noB; /* Alternate addrEofA if B is uninitialized */
  102324. int addrEofB; /* Address of the select-B-exhausted subroutine */
  102325. int addrAltB; /* Address of the A<B subroutine */
  102326. int addrAeqB; /* Address of the A==B subroutine */
  102327. int addrAgtB; /* Address of the A>B subroutine */
  102328. int regLimitA; /* Limit register for select-A */
  102329. int regLimitB; /* Limit register for select-A */
  102330. int regPrev; /* A range of registers to hold previous output */
  102331. int savedLimit; /* Saved value of p->iLimit */
  102332. int savedOffset; /* Saved value of p->iOffset */
  102333. int labelCmpr; /* Label for the start of the merge algorithm */
  102334. int labelEnd; /* Label for the end of the overall SELECT stmt */
  102335. int j1; /* Jump instructions that get retargetted */
  102336. int op; /* One of TK_ALL, TK_UNION, TK_EXCEPT, TK_INTERSECT */
  102337. KeyInfo *pKeyDup = 0; /* Comparison information for duplicate removal */
  102338. KeyInfo *pKeyMerge; /* Comparison information for merging rows */
  102339. sqlite3 *db; /* Database connection */
  102340. ExprList *pOrderBy; /* The ORDER BY clause */
  102341. int nOrderBy; /* Number of terms in the ORDER BY clause */
  102342. int *aPermute; /* Mapping from ORDER BY terms to result set columns */
  102343. #ifndef SQLITE_OMIT_EXPLAIN
  102344. int iSub1; /* EQP id of left-hand query */
  102345. int iSub2; /* EQP id of right-hand query */
  102346. #endif
  102347. assert( p->pOrderBy!=0 );
  102348. assert( pKeyDup==0 ); /* "Managed" code needs this. Ticket #3382. */
  102349. db = pParse->db;
  102350. v = pParse->pVdbe;
  102351. assert( v!=0 ); /* Already thrown the error if VDBE alloc failed */
  102352. labelEnd = sqlite3VdbeMakeLabel(v);
  102353. labelCmpr = sqlite3VdbeMakeLabel(v);
  102354. /* Patch up the ORDER BY clause
  102355. */
  102356. op = p->op;
  102357. pPrior = p->pPrior;
  102358. assert( pPrior->pOrderBy==0 );
  102359. pOrderBy = p->pOrderBy;
  102360. assert( pOrderBy );
  102361. nOrderBy = pOrderBy->nExpr;
  102362. /* For operators other than UNION ALL we have to make sure that
  102363. ** the ORDER BY clause covers every term of the result set. Add
  102364. ** terms to the ORDER BY clause as necessary.
  102365. */
  102366. if( op!=TK_ALL ){
  102367. for(i=1; db->mallocFailed==0 && i<=p->pEList->nExpr; i++){
  102368. struct ExprList_item *pItem;
  102369. for(j=0, pItem=pOrderBy->a; j<nOrderBy; j++, pItem++){
  102370. assert( pItem->u.x.iOrderByCol>0 );
  102371. if( pItem->u.x.iOrderByCol==i ) break;
  102372. }
  102373. if( j==nOrderBy ){
  102374. Expr *pNew = sqlite3Expr(db, TK_INTEGER, 0);
  102375. if( pNew==0 ) return SQLITE_NOMEM;
  102376. pNew->flags |= EP_IntValue;
  102377. pNew->u.iValue = i;
  102378. pOrderBy = sqlite3ExprListAppend(pParse, pOrderBy, pNew);
  102379. if( pOrderBy ) pOrderBy->a[nOrderBy++].u.x.iOrderByCol = (u16)i;
  102380. }
  102381. }
  102382. }
  102383. /* Compute the comparison permutation and keyinfo that is used with
  102384. ** the permutation used to determine if the next
  102385. ** row of results comes from selectA or selectB. Also add explicit
  102386. ** collations to the ORDER BY clause terms so that when the subqueries
  102387. ** to the right and the left are evaluated, they use the correct
  102388. ** collation.
  102389. */
  102390. aPermute = sqlite3DbMallocRaw(db, sizeof(int)*nOrderBy);
  102391. if( aPermute ){
  102392. struct ExprList_item *pItem;
  102393. for(i=0, pItem=pOrderBy->a; i<nOrderBy; i++, pItem++){
  102394. assert( pItem->u.x.iOrderByCol>0 );
  102395. /* assert( pItem->u.x.iOrderByCol<=p->pEList->nExpr ) is also true
  102396. ** but only for well-formed SELECT statements. */
  102397. testcase( pItem->u.x.iOrderByCol > p->pEList->nExpr );
  102398. aPermute[i] = pItem->u.x.iOrderByCol - 1;
  102399. }
  102400. pKeyMerge = multiSelectOrderByKeyInfo(pParse, p, 1);
  102401. }else{
  102402. pKeyMerge = 0;
  102403. }
  102404. /* Reattach the ORDER BY clause to the query.
  102405. */
  102406. p->pOrderBy = pOrderBy;
  102407. pPrior->pOrderBy = sqlite3ExprListDup(pParse->db, pOrderBy, 0);
  102408. /* Allocate a range of temporary registers and the KeyInfo needed
  102409. ** for the logic that removes duplicate result rows when the
  102410. ** operator is UNION, EXCEPT, or INTERSECT (but not UNION ALL).
  102411. */
  102412. if( op==TK_ALL ){
  102413. regPrev = 0;
  102414. }else{
  102415. int nExpr = p->pEList->nExpr;
  102416. assert( nOrderBy>=nExpr || db->mallocFailed );
  102417. regPrev = pParse->nMem+1;
  102418. pParse->nMem += nExpr+1;
  102419. sqlite3VdbeAddOp2(v, OP_Integer, 0, regPrev);
  102420. pKeyDup = sqlite3KeyInfoAlloc(db, nExpr, 1);
  102421. if( pKeyDup ){
  102422. assert( sqlite3KeyInfoIsWriteable(pKeyDup) );
  102423. for(i=0; i<nExpr; i++){
  102424. pKeyDup->aColl[i] = multiSelectCollSeq(pParse, p, i);
  102425. pKeyDup->aSortOrder[i] = 0;
  102426. }
  102427. }
  102428. }
  102429. /* Separate the left and the right query from one another
  102430. */
  102431. p->pPrior = 0;
  102432. pPrior->pNext = 0;
  102433. sqlite3ResolveOrderGroupBy(pParse, p, p->pOrderBy, "ORDER");
  102434. if( pPrior->pPrior==0 ){
  102435. sqlite3ResolveOrderGroupBy(pParse, pPrior, pPrior->pOrderBy, "ORDER");
  102436. }
  102437. /* Compute the limit registers */
  102438. computeLimitRegisters(pParse, p, labelEnd);
  102439. if( p->iLimit && op==TK_ALL ){
  102440. regLimitA = ++pParse->nMem;
  102441. regLimitB = ++pParse->nMem;
  102442. sqlite3VdbeAddOp2(v, OP_Copy, p->iOffset ? p->iOffset+1 : p->iLimit,
  102443. regLimitA);
  102444. sqlite3VdbeAddOp2(v, OP_Copy, regLimitA, regLimitB);
  102445. }else{
  102446. regLimitA = regLimitB = 0;
  102447. }
  102448. sqlite3ExprDelete(db, p->pLimit);
  102449. p->pLimit = 0;
  102450. sqlite3ExprDelete(db, p->pOffset);
  102451. p->pOffset = 0;
  102452. regAddrA = ++pParse->nMem;
  102453. regAddrB = ++pParse->nMem;
  102454. regOutA = ++pParse->nMem;
  102455. regOutB = ++pParse->nMem;
  102456. sqlite3SelectDestInit(&destA, SRT_Coroutine, regAddrA);
  102457. sqlite3SelectDestInit(&destB, SRT_Coroutine, regAddrB);
  102458. /* Generate a coroutine to evaluate the SELECT statement to the
  102459. ** left of the compound operator - the "A" select.
  102460. */
  102461. addrSelectA = sqlite3VdbeCurrentAddr(v) + 1;
  102462. j1 = sqlite3VdbeAddOp3(v, OP_InitCoroutine, regAddrA, 0, addrSelectA);
  102463. VdbeComment((v, "left SELECT"));
  102464. pPrior->iLimit = regLimitA;
  102465. explainSetInteger(iSub1, pParse->iNextSelectId);
  102466. sqlite3Select(pParse, pPrior, &destA);
  102467. sqlite3VdbeAddOp1(v, OP_EndCoroutine, regAddrA);
  102468. sqlite3VdbeJumpHere(v, j1);
  102469. /* Generate a coroutine to evaluate the SELECT statement on
  102470. ** the right - the "B" select
  102471. */
  102472. addrSelectB = sqlite3VdbeCurrentAddr(v) + 1;
  102473. j1 = sqlite3VdbeAddOp3(v, OP_InitCoroutine, regAddrB, 0, addrSelectB);
  102474. VdbeComment((v, "right SELECT"));
  102475. savedLimit = p->iLimit;
  102476. savedOffset = p->iOffset;
  102477. p->iLimit = regLimitB;
  102478. p->iOffset = 0;
  102479. explainSetInteger(iSub2, pParse->iNextSelectId);
  102480. sqlite3Select(pParse, p, &destB);
  102481. p->iLimit = savedLimit;
  102482. p->iOffset = savedOffset;
  102483. sqlite3VdbeAddOp1(v, OP_EndCoroutine, regAddrB);
  102484. /* Generate a subroutine that outputs the current row of the A
  102485. ** select as the next output row of the compound select.
  102486. */
  102487. VdbeNoopComment((v, "Output routine for A"));
  102488. addrOutA = generateOutputSubroutine(pParse,
  102489. p, &destA, pDest, regOutA,
  102490. regPrev, pKeyDup, labelEnd);
  102491. /* Generate a subroutine that outputs the current row of the B
  102492. ** select as the next output row of the compound select.
  102493. */
  102494. if( op==TK_ALL || op==TK_UNION ){
  102495. VdbeNoopComment((v, "Output routine for B"));
  102496. addrOutB = generateOutputSubroutine(pParse,
  102497. p, &destB, pDest, regOutB,
  102498. regPrev, pKeyDup, labelEnd);
  102499. }
  102500. sqlite3KeyInfoUnref(pKeyDup);
  102501. /* Generate a subroutine to run when the results from select A
  102502. ** are exhausted and only data in select B remains.
  102503. */
  102504. if( op==TK_EXCEPT || op==TK_INTERSECT ){
  102505. addrEofA_noB = addrEofA = labelEnd;
  102506. }else{
  102507. VdbeNoopComment((v, "eof-A subroutine"));
  102508. addrEofA = sqlite3VdbeAddOp2(v, OP_Gosub, regOutB, addrOutB);
  102509. addrEofA_noB = sqlite3VdbeAddOp2(v, OP_Yield, regAddrB, labelEnd);
  102510. VdbeCoverage(v);
  102511. sqlite3VdbeAddOp2(v, OP_Goto, 0, addrEofA);
  102512. p->nSelectRow += pPrior->nSelectRow;
  102513. }
  102514. /* Generate a subroutine to run when the results from select B
  102515. ** are exhausted and only data in select A remains.
  102516. */
  102517. if( op==TK_INTERSECT ){
  102518. addrEofB = addrEofA;
  102519. if( p->nSelectRow > pPrior->nSelectRow ) p->nSelectRow = pPrior->nSelectRow;
  102520. }else{
  102521. VdbeNoopComment((v, "eof-B subroutine"));
  102522. addrEofB = sqlite3VdbeAddOp2(v, OP_Gosub, regOutA, addrOutA);
  102523. sqlite3VdbeAddOp2(v, OP_Yield, regAddrA, labelEnd); VdbeCoverage(v);
  102524. sqlite3VdbeAddOp2(v, OP_Goto, 0, addrEofB);
  102525. }
  102526. /* Generate code to handle the case of A<B
  102527. */
  102528. VdbeNoopComment((v, "A-lt-B subroutine"));
  102529. addrAltB = sqlite3VdbeAddOp2(v, OP_Gosub, regOutA, addrOutA);
  102530. sqlite3VdbeAddOp2(v, OP_Yield, regAddrA, addrEofA); VdbeCoverage(v);
  102531. sqlite3VdbeAddOp2(v, OP_Goto, 0, labelCmpr);
  102532. /* Generate code to handle the case of A==B
  102533. */
  102534. if( op==TK_ALL ){
  102535. addrAeqB = addrAltB;
  102536. }else if( op==TK_INTERSECT ){
  102537. addrAeqB = addrAltB;
  102538. addrAltB++;
  102539. }else{
  102540. VdbeNoopComment((v, "A-eq-B subroutine"));
  102541. addrAeqB =
  102542. sqlite3VdbeAddOp2(v, OP_Yield, regAddrA, addrEofA); VdbeCoverage(v);
  102543. sqlite3VdbeAddOp2(v, OP_Goto, 0, labelCmpr);
  102544. }
  102545. /* Generate code to handle the case of A>B
  102546. */
  102547. VdbeNoopComment((v, "A-gt-B subroutine"));
  102548. addrAgtB = sqlite3VdbeCurrentAddr(v);
  102549. if( op==TK_ALL || op==TK_UNION ){
  102550. sqlite3VdbeAddOp2(v, OP_Gosub, regOutB, addrOutB);
  102551. }
  102552. sqlite3VdbeAddOp2(v, OP_Yield, regAddrB, addrEofB); VdbeCoverage(v);
  102553. sqlite3VdbeAddOp2(v, OP_Goto, 0, labelCmpr);
  102554. /* This code runs once to initialize everything.
  102555. */
  102556. sqlite3VdbeJumpHere(v, j1);
  102557. sqlite3VdbeAddOp2(v, OP_Yield, regAddrA, addrEofA_noB); VdbeCoverage(v);
  102558. sqlite3VdbeAddOp2(v, OP_Yield, regAddrB, addrEofB); VdbeCoverage(v);
  102559. /* Implement the main merge loop
  102560. */
  102561. sqlite3VdbeResolveLabel(v, labelCmpr);
  102562. sqlite3VdbeAddOp4(v, OP_Permutation, 0, 0, 0, (char*)aPermute, P4_INTARRAY);
  102563. sqlite3VdbeAddOp4(v, OP_Compare, destA.iSdst, destB.iSdst, nOrderBy,
  102564. (char*)pKeyMerge, P4_KEYINFO);
  102565. sqlite3VdbeChangeP5(v, OPFLAG_PERMUTE);
  102566. sqlite3VdbeAddOp3(v, OP_Jump, addrAltB, addrAeqB, addrAgtB); VdbeCoverage(v);
  102567. /* Jump to the this point in order to terminate the query.
  102568. */
  102569. sqlite3VdbeResolveLabel(v, labelEnd);
  102570. /* Set the number of output columns
  102571. */
  102572. if( pDest->eDest==SRT_Output ){
  102573. Select *pFirst = pPrior;
  102574. while( pFirst->pPrior ) pFirst = pFirst->pPrior;
  102575. generateColumnNames(pParse, 0, pFirst->pEList);
  102576. }
  102577. /* Reassembly the compound query so that it will be freed correctly
  102578. ** by the calling function */
  102579. if( p->pPrior ){
  102580. sqlite3SelectDelete(db, p->pPrior);
  102581. }
  102582. p->pPrior = pPrior;
  102583. pPrior->pNext = p;
  102584. /*** TBD: Insert subroutine calls to close cursors on incomplete
  102585. **** subqueries ****/
  102586. explainComposite(pParse, p->op, iSub1, iSub2, 0);
  102587. return pParse->nErr!=0;
  102588. }
  102589. #endif
  102590. #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
  102591. /* Forward Declarations */
  102592. static void substExprList(sqlite3*, ExprList*, int, ExprList*);
  102593. static void substSelect(sqlite3*, Select *, int, ExprList *);
  102594. /*
  102595. ** Scan through the expression pExpr. Replace every reference to
  102596. ** a column in table number iTable with a copy of the iColumn-th
  102597. ** entry in pEList. (But leave references to the ROWID column
  102598. ** unchanged.)
  102599. **
  102600. ** This routine is part of the flattening procedure. A subquery
  102601. ** whose result set is defined by pEList appears as entry in the
  102602. ** FROM clause of a SELECT such that the VDBE cursor assigned to that
  102603. ** FORM clause entry is iTable. This routine make the necessary
  102604. ** changes to pExpr so that it refers directly to the source table
  102605. ** of the subquery rather the result set of the subquery.
  102606. */
  102607. static Expr *substExpr(
  102608. sqlite3 *db, /* Report malloc errors to this connection */
  102609. Expr *pExpr, /* Expr in which substitution occurs */
  102610. int iTable, /* Table to be substituted */
  102611. ExprList *pEList /* Substitute expressions */
  102612. ){
  102613. if( pExpr==0 ) return 0;
  102614. if( pExpr->op==TK_COLUMN && pExpr->iTable==iTable ){
  102615. if( pExpr->iColumn<0 ){
  102616. pExpr->op = TK_NULL;
  102617. }else{
  102618. Expr *pNew;
  102619. assert( pEList!=0 && pExpr->iColumn<pEList->nExpr );
  102620. assert( pExpr->pLeft==0 && pExpr->pRight==0 );
  102621. pNew = sqlite3ExprDup(db, pEList->a[pExpr->iColumn].pExpr, 0);
  102622. sqlite3ExprDelete(db, pExpr);
  102623. pExpr = pNew;
  102624. }
  102625. }else{
  102626. pExpr->pLeft = substExpr(db, pExpr->pLeft, iTable, pEList);
  102627. pExpr->pRight = substExpr(db, pExpr->pRight, iTable, pEList);
  102628. if( ExprHasProperty(pExpr, EP_xIsSelect) ){
  102629. substSelect(db, pExpr->x.pSelect, iTable, pEList);
  102630. }else{
  102631. substExprList(db, pExpr->x.pList, iTable, pEList);
  102632. }
  102633. }
  102634. return pExpr;
  102635. }
  102636. static void substExprList(
  102637. sqlite3 *db, /* Report malloc errors here */
  102638. ExprList *pList, /* List to scan and in which to make substitutes */
  102639. int iTable, /* Table to be substituted */
  102640. ExprList *pEList /* Substitute values */
  102641. ){
  102642. int i;
  102643. if( pList==0 ) return;
  102644. for(i=0; i<pList->nExpr; i++){
  102645. pList->a[i].pExpr = substExpr(db, pList->a[i].pExpr, iTable, pEList);
  102646. }
  102647. }
  102648. static void substSelect(
  102649. sqlite3 *db, /* Report malloc errors here */
  102650. Select *p, /* SELECT statement in which to make substitutions */
  102651. int iTable, /* Table to be replaced */
  102652. ExprList *pEList /* Substitute values */
  102653. ){
  102654. SrcList *pSrc;
  102655. struct SrcList_item *pItem;
  102656. int i;
  102657. if( !p ) return;
  102658. substExprList(db, p->pEList, iTable, pEList);
  102659. substExprList(db, p->pGroupBy, iTable, pEList);
  102660. substExprList(db, p->pOrderBy, iTable, pEList);
  102661. p->pHaving = substExpr(db, p->pHaving, iTable, pEList);
  102662. p->pWhere = substExpr(db, p->pWhere, iTable, pEList);
  102663. substSelect(db, p->pPrior, iTable, pEList);
  102664. pSrc = p->pSrc;
  102665. assert( pSrc ); /* Even for (SELECT 1) we have: pSrc!=0 but pSrc->nSrc==0 */
  102666. if( ALWAYS(pSrc) ){
  102667. for(i=pSrc->nSrc, pItem=pSrc->a; i>0; i--, pItem++){
  102668. substSelect(db, pItem->pSelect, iTable, pEList);
  102669. }
  102670. }
  102671. }
  102672. #endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */
  102673. #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
  102674. /*
  102675. ** This routine attempts to flatten subqueries as a performance optimization.
  102676. ** This routine returns 1 if it makes changes and 0 if no flattening occurs.
  102677. **
  102678. ** To understand the concept of flattening, consider the following
  102679. ** query:
  102680. **
  102681. ** SELECT a FROM (SELECT x+y AS a FROM t1 WHERE z<100) WHERE a>5
  102682. **
  102683. ** The default way of implementing this query is to execute the
  102684. ** subquery first and store the results in a temporary table, then
  102685. ** run the outer query on that temporary table. This requires two
  102686. ** passes over the data. Furthermore, because the temporary table
  102687. ** has no indices, the WHERE clause on the outer query cannot be
  102688. ** optimized.
  102689. **
  102690. ** This routine attempts to rewrite queries such as the above into
  102691. ** a single flat select, like this:
  102692. **
  102693. ** SELECT x+y AS a FROM t1 WHERE z<100 AND a>5
  102694. **
  102695. ** The code generated for this simplification gives the same result
  102696. ** but only has to scan the data once. And because indices might
  102697. ** exist on the table t1, a complete scan of the data might be
  102698. ** avoided.
  102699. **
  102700. ** Flattening is only attempted if all of the following are true:
  102701. **
  102702. ** (1) The subquery and the outer query do not both use aggregates.
  102703. **
  102704. ** (2) The subquery is not an aggregate or (2a) the outer query is not a join
  102705. ** and (2b) the outer query does not use subqueries other than the one
  102706. ** FROM-clause subquery that is a candidate for flattening. (2b is
  102707. ** due to ticket [2f7170d73bf9abf80] from 2015-02-09.)
  102708. **
  102709. ** (3) The subquery is not the right operand of a left outer join
  102710. ** (Originally ticket #306. Strengthened by ticket #3300)
  102711. **
  102712. ** (4) The subquery is not DISTINCT.
  102713. **
  102714. ** (**) At one point restrictions (4) and (5) defined a subset of DISTINCT
  102715. ** sub-queries that were excluded from this optimization. Restriction
  102716. ** (4) has since been expanded to exclude all DISTINCT subqueries.
  102717. **
  102718. ** (6) The subquery does not use aggregates or the outer query is not
  102719. ** DISTINCT.
  102720. **
  102721. ** (7) The subquery has a FROM clause. TODO: For subqueries without
  102722. ** A FROM clause, consider adding a FROM close with the special
  102723. ** table sqlite_once that consists of a single row containing a
  102724. ** single NULL.
  102725. **
  102726. ** (8) The subquery does not use LIMIT or the outer query is not a join.
  102727. **
  102728. ** (9) The subquery does not use LIMIT or the outer query does not use
  102729. ** aggregates.
  102730. **
  102731. ** (**) Restriction (10) was removed from the code on 2005-02-05 but we
  102732. ** accidently carried the comment forward until 2014-09-15. Original
  102733. ** text: "The subquery does not use aggregates or the outer query does not
  102734. ** use LIMIT."
  102735. **
  102736. ** (11) The subquery and the outer query do not both have ORDER BY clauses.
  102737. **
  102738. ** (**) Not implemented. Subsumed into restriction (3). Was previously
  102739. ** a separate restriction deriving from ticket #350.
  102740. **
  102741. ** (13) The subquery and outer query do not both use LIMIT.
  102742. **
  102743. ** (14) The subquery does not use OFFSET.
  102744. **
  102745. ** (15) The outer query is not part of a compound select or the
  102746. ** subquery does not have a LIMIT clause.
  102747. ** (See ticket #2339 and ticket [02a8e81d44]).
  102748. **
  102749. ** (16) The outer query is not an aggregate or the subquery does
  102750. ** not contain ORDER BY. (Ticket #2942) This used to not matter
  102751. ** until we introduced the group_concat() function.
  102752. **
  102753. ** (17) The sub-query is not a compound select, or it is a UNION ALL
  102754. ** compound clause made up entirely of non-aggregate queries, and
  102755. ** the parent query:
  102756. **
  102757. ** * is not itself part of a compound select,
  102758. ** * is not an aggregate or DISTINCT query, and
  102759. ** * is not a join
  102760. **
  102761. ** The parent and sub-query may contain WHERE clauses. Subject to
  102762. ** rules (11), (13) and (14), they may also contain ORDER BY,
  102763. ** LIMIT and OFFSET clauses. The subquery cannot use any compound
  102764. ** operator other than UNION ALL because all the other compound
  102765. ** operators have an implied DISTINCT which is disallowed by
  102766. ** restriction (4).
  102767. **
  102768. ** Also, each component of the sub-query must return the same number
  102769. ** of result columns. This is actually a requirement for any compound
  102770. ** SELECT statement, but all the code here does is make sure that no
  102771. ** such (illegal) sub-query is flattened. The caller will detect the
  102772. ** syntax error and return a detailed message.
  102773. **
  102774. ** (18) If the sub-query is a compound select, then all terms of the
  102775. ** ORDER by clause of the parent must be simple references to
  102776. ** columns of the sub-query.
  102777. **
  102778. ** (19) The subquery does not use LIMIT or the outer query does not
  102779. ** have a WHERE clause.
  102780. **
  102781. ** (20) If the sub-query is a compound select, then it must not use
  102782. ** an ORDER BY clause. Ticket #3773. We could relax this constraint
  102783. ** somewhat by saying that the terms of the ORDER BY clause must
  102784. ** appear as unmodified result columns in the outer query. But we
  102785. ** have other optimizations in mind to deal with that case.
  102786. **
  102787. ** (21) The subquery does not use LIMIT or the outer query is not
  102788. ** DISTINCT. (See ticket [752e1646fc]).
  102789. **
  102790. ** (22) The subquery is not a recursive CTE.
  102791. **
  102792. ** (23) The parent is not a recursive CTE, or the sub-query is not a
  102793. ** compound query. This restriction is because transforming the
  102794. ** parent to a compound query confuses the code that handles
  102795. ** recursive queries in multiSelect().
  102796. **
  102797. ** (24) The subquery is not an aggregate that uses the built-in min() or
  102798. ** or max() functions. (Without this restriction, a query like:
  102799. ** "SELECT x FROM (SELECT max(y), x FROM t1)" would not necessarily
  102800. ** return the value X for which Y was maximal.)
  102801. **
  102802. **
  102803. ** In this routine, the "p" parameter is a pointer to the outer query.
  102804. ** The subquery is p->pSrc->a[iFrom]. isAgg is true if the outer query
  102805. ** uses aggregates and subqueryIsAgg is true if the subquery uses aggregates.
  102806. **
  102807. ** If flattening is not attempted, this routine is a no-op and returns 0.
  102808. ** If flattening is attempted this routine returns 1.
  102809. **
  102810. ** All of the expression analysis must occur on both the outer query and
  102811. ** the subquery before this routine runs.
  102812. */
  102813. static int flattenSubquery(
  102814. Parse *pParse, /* Parsing context */
  102815. Select *p, /* The parent or outer SELECT statement */
  102816. int iFrom, /* Index in p->pSrc->a[] of the inner subquery */
  102817. int isAgg, /* True if outer SELECT uses aggregate functions */
  102818. int subqueryIsAgg /* True if the subquery uses aggregate functions */
  102819. ){
  102820. const char *zSavedAuthContext = pParse->zAuthContext;
  102821. Select *pParent;
  102822. Select *pSub; /* The inner query or "subquery" */
  102823. Select *pSub1; /* Pointer to the rightmost select in sub-query */
  102824. SrcList *pSrc; /* The FROM clause of the outer query */
  102825. SrcList *pSubSrc; /* The FROM clause of the subquery */
  102826. ExprList *pList; /* The result set of the outer query */
  102827. int iParent; /* VDBE cursor number of the pSub result set temp table */
  102828. int i; /* Loop counter */
  102829. Expr *pWhere; /* The WHERE clause */
  102830. struct SrcList_item *pSubitem; /* The subquery */
  102831. sqlite3 *db = pParse->db;
  102832. /* Check to see if flattening is permitted. Return 0 if not.
  102833. */
  102834. assert( p!=0 );
  102835. assert( p->pPrior==0 ); /* Unable to flatten compound queries */
  102836. if( OptimizationDisabled(db, SQLITE_QueryFlattener) ) return 0;
  102837. pSrc = p->pSrc;
  102838. assert( pSrc && iFrom>=0 && iFrom<pSrc->nSrc );
  102839. pSubitem = &pSrc->a[iFrom];
  102840. iParent = pSubitem->iCursor;
  102841. pSub = pSubitem->pSelect;
  102842. assert( pSub!=0 );
  102843. if( subqueryIsAgg ){
  102844. if( isAgg ) return 0; /* Restriction (1) */
  102845. if( pSrc->nSrc>1 ) return 0; /* Restriction (2a) */
  102846. if( (p->pWhere && ExprHasProperty(p->pWhere,EP_Subquery))
  102847. || (sqlite3ExprListFlags(p->pEList) & EP_Subquery)!=0
  102848. || (sqlite3ExprListFlags(p->pOrderBy) & EP_Subquery)!=0
  102849. ){
  102850. return 0; /* Restriction (2b) */
  102851. }
  102852. }
  102853. pSubSrc = pSub->pSrc;
  102854. assert( pSubSrc );
  102855. /* Prior to version 3.1.2, when LIMIT and OFFSET had to be simple constants,
  102856. ** not arbitrary expressions, we allowed some combining of LIMIT and OFFSET
  102857. ** because they could be computed at compile-time. But when LIMIT and OFFSET
  102858. ** became arbitrary expressions, we were forced to add restrictions (13)
  102859. ** and (14). */
  102860. if( pSub->pLimit && p->pLimit ) return 0; /* Restriction (13) */
  102861. if( pSub->pOffset ) return 0; /* Restriction (14) */
  102862. if( (p->selFlags & SF_Compound)!=0 && pSub->pLimit ){
  102863. return 0; /* Restriction (15) */
  102864. }
  102865. if( pSubSrc->nSrc==0 ) return 0; /* Restriction (7) */
  102866. if( pSub->selFlags & SF_Distinct ) return 0; /* Restriction (5) */
  102867. if( pSub->pLimit && (pSrc->nSrc>1 || isAgg) ){
  102868. return 0; /* Restrictions (8)(9) */
  102869. }
  102870. if( (p->selFlags & SF_Distinct)!=0 && subqueryIsAgg ){
  102871. return 0; /* Restriction (6) */
  102872. }
  102873. if( p->pOrderBy && pSub->pOrderBy ){
  102874. return 0; /* Restriction (11) */
  102875. }
  102876. if( isAgg && pSub->pOrderBy ) return 0; /* Restriction (16) */
  102877. if( pSub->pLimit && p->pWhere ) return 0; /* Restriction (19) */
  102878. if( pSub->pLimit && (p->selFlags & SF_Distinct)!=0 ){
  102879. return 0; /* Restriction (21) */
  102880. }
  102881. testcase( pSub->selFlags & SF_Recursive );
  102882. testcase( pSub->selFlags & SF_MinMaxAgg );
  102883. if( pSub->selFlags & (SF_Recursive|SF_MinMaxAgg) ){
  102884. return 0; /* Restrictions (22) and (24) */
  102885. }
  102886. if( (p->selFlags & SF_Recursive) && pSub->pPrior ){
  102887. return 0; /* Restriction (23) */
  102888. }
  102889. /* OBSOLETE COMMENT 1:
  102890. ** Restriction 3: If the subquery is a join, make sure the subquery is
  102891. ** not used as the right operand of an outer join. Examples of why this
  102892. ** is not allowed:
  102893. **
  102894. ** t1 LEFT OUTER JOIN (t2 JOIN t3)
  102895. **
  102896. ** If we flatten the above, we would get
  102897. **
  102898. ** (t1 LEFT OUTER JOIN t2) JOIN t3
  102899. **
  102900. ** which is not at all the same thing.
  102901. **
  102902. ** OBSOLETE COMMENT 2:
  102903. ** Restriction 12: If the subquery is the right operand of a left outer
  102904. ** join, make sure the subquery has no WHERE clause.
  102905. ** An examples of why this is not allowed:
  102906. **
  102907. ** t1 LEFT OUTER JOIN (SELECT * FROM t2 WHERE t2.x>0)
  102908. **
  102909. ** If we flatten the above, we would get
  102910. **
  102911. ** (t1 LEFT OUTER JOIN t2) WHERE t2.x>0
  102912. **
  102913. ** But the t2.x>0 test will always fail on a NULL row of t2, which
  102914. ** effectively converts the OUTER JOIN into an INNER JOIN.
  102915. **
  102916. ** THIS OVERRIDES OBSOLETE COMMENTS 1 AND 2 ABOVE:
  102917. ** Ticket #3300 shows that flattening the right term of a LEFT JOIN
  102918. ** is fraught with danger. Best to avoid the whole thing. If the
  102919. ** subquery is the right term of a LEFT JOIN, then do not flatten.
  102920. */
  102921. if( (pSubitem->jointype & JT_OUTER)!=0 ){
  102922. return 0;
  102923. }
  102924. /* Restriction 17: If the sub-query is a compound SELECT, then it must
  102925. ** use only the UNION ALL operator. And none of the simple select queries
  102926. ** that make up the compound SELECT are allowed to be aggregate or distinct
  102927. ** queries.
  102928. */
  102929. if( pSub->pPrior ){
  102930. if( pSub->pOrderBy ){
  102931. return 0; /* Restriction 20 */
  102932. }
  102933. if( isAgg || (p->selFlags & SF_Distinct)!=0 || pSrc->nSrc!=1 ){
  102934. return 0;
  102935. }
  102936. for(pSub1=pSub; pSub1; pSub1=pSub1->pPrior){
  102937. testcase( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct );
  102938. testcase( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))==SF_Aggregate );
  102939. assert( pSub->pSrc!=0 );
  102940. if( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))!=0
  102941. || (pSub1->pPrior && pSub1->op!=TK_ALL)
  102942. || pSub1->pSrc->nSrc<1
  102943. || pSub->pEList->nExpr!=pSub1->pEList->nExpr
  102944. ){
  102945. return 0;
  102946. }
  102947. testcase( pSub1->pSrc->nSrc>1 );
  102948. }
  102949. /* Restriction 18. */
  102950. if( p->pOrderBy ){
  102951. int ii;
  102952. for(ii=0; ii<p->pOrderBy->nExpr; ii++){
  102953. if( p->pOrderBy->a[ii].u.x.iOrderByCol==0 ) return 0;
  102954. }
  102955. }
  102956. }
  102957. /***** If we reach this point, flattening is permitted. *****/
  102958. SELECTTRACE(1,pParse,p,("flatten %s.%p from term %d\n",
  102959. pSub->zSelName, pSub, iFrom));
  102960. /* Authorize the subquery */
  102961. pParse->zAuthContext = pSubitem->zName;
  102962. TESTONLY(i =) sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0);
  102963. testcase( i==SQLITE_DENY );
  102964. pParse->zAuthContext = zSavedAuthContext;
  102965. /* If the sub-query is a compound SELECT statement, then (by restrictions
  102966. ** 17 and 18 above) it must be a UNION ALL and the parent query must
  102967. ** be of the form:
  102968. **
  102969. ** SELECT <expr-list> FROM (<sub-query>) <where-clause>
  102970. **
  102971. ** followed by any ORDER BY, LIMIT and/or OFFSET clauses. This block
  102972. ** creates N-1 copies of the parent query without any ORDER BY, LIMIT or
  102973. ** OFFSET clauses and joins them to the left-hand-side of the original
  102974. ** using UNION ALL operators. In this case N is the number of simple
  102975. ** select statements in the compound sub-query.
  102976. **
  102977. ** Example:
  102978. **
  102979. ** SELECT a+1 FROM (
  102980. ** SELECT x FROM tab
  102981. ** UNION ALL
  102982. ** SELECT y FROM tab
  102983. ** UNION ALL
  102984. ** SELECT abs(z*2) FROM tab2
  102985. ** ) WHERE a!=5 ORDER BY 1
  102986. **
  102987. ** Transformed into:
  102988. **
  102989. ** SELECT x+1 FROM tab WHERE x+1!=5
  102990. ** UNION ALL
  102991. ** SELECT y+1 FROM tab WHERE y+1!=5
  102992. ** UNION ALL
  102993. ** SELECT abs(z*2)+1 FROM tab2 WHERE abs(z*2)+1!=5
  102994. ** ORDER BY 1
  102995. **
  102996. ** We call this the "compound-subquery flattening".
  102997. */
  102998. for(pSub=pSub->pPrior; pSub; pSub=pSub->pPrior){
  102999. Select *pNew;
  103000. ExprList *pOrderBy = p->pOrderBy;
  103001. Expr *pLimit = p->pLimit;
  103002. Expr *pOffset = p->pOffset;
  103003. Select *pPrior = p->pPrior;
  103004. p->pOrderBy = 0;
  103005. p->pSrc = 0;
  103006. p->pPrior = 0;
  103007. p->pLimit = 0;
  103008. p->pOffset = 0;
  103009. pNew = sqlite3SelectDup(db, p, 0);
  103010. sqlite3SelectSetName(pNew, pSub->zSelName);
  103011. p->pOffset = pOffset;
  103012. p->pLimit = pLimit;
  103013. p->pOrderBy = pOrderBy;
  103014. p->pSrc = pSrc;
  103015. p->op = TK_ALL;
  103016. if( pNew==0 ){
  103017. p->pPrior = pPrior;
  103018. }else{
  103019. pNew->pPrior = pPrior;
  103020. if( pPrior ) pPrior->pNext = pNew;
  103021. pNew->pNext = p;
  103022. p->pPrior = pNew;
  103023. SELECTTRACE(2,pParse,p,
  103024. ("compound-subquery flattener creates %s.%p as peer\n",
  103025. pNew->zSelName, pNew));
  103026. }
  103027. if( db->mallocFailed ) return 1;
  103028. }
  103029. /* Begin flattening the iFrom-th entry of the FROM clause
  103030. ** in the outer query.
  103031. */
  103032. pSub = pSub1 = pSubitem->pSelect;
  103033. /* Delete the transient table structure associated with the
  103034. ** subquery
  103035. */
  103036. sqlite3DbFree(db, pSubitem->zDatabase);
  103037. sqlite3DbFree(db, pSubitem->zName);
  103038. sqlite3DbFree(db, pSubitem->zAlias);
  103039. pSubitem->zDatabase = 0;
  103040. pSubitem->zName = 0;
  103041. pSubitem->zAlias = 0;
  103042. pSubitem->pSelect = 0;
  103043. /* Defer deleting the Table object associated with the
  103044. ** subquery until code generation is
  103045. ** complete, since there may still exist Expr.pTab entries that
  103046. ** refer to the subquery even after flattening. Ticket #3346.
  103047. **
  103048. ** pSubitem->pTab is always non-NULL by test restrictions and tests above.
  103049. */
  103050. if( ALWAYS(pSubitem->pTab!=0) ){
  103051. Table *pTabToDel = pSubitem->pTab;
  103052. if( pTabToDel->nRef==1 ){
  103053. Parse *pToplevel = sqlite3ParseToplevel(pParse);
  103054. pTabToDel->pNextZombie = pToplevel->pZombieTab;
  103055. pToplevel->pZombieTab = pTabToDel;
  103056. }else{
  103057. pTabToDel->nRef--;
  103058. }
  103059. pSubitem->pTab = 0;
  103060. }
  103061. /* The following loop runs once for each term in a compound-subquery
  103062. ** flattening (as described above). If we are doing a different kind
  103063. ** of flattening - a flattening other than a compound-subquery flattening -
  103064. ** then this loop only runs once.
  103065. **
  103066. ** This loop moves all of the FROM elements of the subquery into the
  103067. ** the FROM clause of the outer query. Before doing this, remember
  103068. ** the cursor number for the original outer query FROM element in
  103069. ** iParent. The iParent cursor will never be used. Subsequent code
  103070. ** will scan expressions looking for iParent references and replace
  103071. ** those references with expressions that resolve to the subquery FROM
  103072. ** elements we are now copying in.
  103073. */
  103074. for(pParent=p; pParent; pParent=pParent->pPrior, pSub=pSub->pPrior){
  103075. int nSubSrc;
  103076. u8 jointype = 0;
  103077. pSubSrc = pSub->pSrc; /* FROM clause of subquery */
  103078. nSubSrc = pSubSrc->nSrc; /* Number of terms in subquery FROM clause */
  103079. pSrc = pParent->pSrc; /* FROM clause of the outer query */
  103080. if( pSrc ){
  103081. assert( pParent==p ); /* First time through the loop */
  103082. jointype = pSubitem->jointype;
  103083. }else{
  103084. assert( pParent!=p ); /* 2nd and subsequent times through the loop */
  103085. pSrc = pParent->pSrc = sqlite3SrcListAppend(db, 0, 0, 0);
  103086. if( pSrc==0 ){
  103087. assert( db->mallocFailed );
  103088. break;
  103089. }
  103090. }
  103091. /* The subquery uses a single slot of the FROM clause of the outer
  103092. ** query. If the subquery has more than one element in its FROM clause,
  103093. ** then expand the outer query to make space for it to hold all elements
  103094. ** of the subquery.
  103095. **
  103096. ** Example:
  103097. **
  103098. ** SELECT * FROM tabA, (SELECT * FROM sub1, sub2), tabB;
  103099. **
  103100. ** The outer query has 3 slots in its FROM clause. One slot of the
  103101. ** outer query (the middle slot) is used by the subquery. The next
  103102. ** block of code will expand the out query to 4 slots. The middle
  103103. ** slot is expanded to two slots in order to make space for the
  103104. ** two elements in the FROM clause of the subquery.
  103105. */
  103106. if( nSubSrc>1 ){
  103107. pParent->pSrc = pSrc = sqlite3SrcListEnlarge(db, pSrc, nSubSrc-1,iFrom+1);
  103108. if( db->mallocFailed ){
  103109. break;
  103110. }
  103111. }
  103112. /* Transfer the FROM clause terms from the subquery into the
  103113. ** outer query.
  103114. */
  103115. for(i=0; i<nSubSrc; i++){
  103116. sqlite3IdListDelete(db, pSrc->a[i+iFrom].pUsing);
  103117. pSrc->a[i+iFrom] = pSubSrc->a[i];
  103118. memset(&pSubSrc->a[i], 0, sizeof(pSubSrc->a[i]));
  103119. }
  103120. pSrc->a[iFrom].jointype = jointype;
  103121. /* Now begin substituting subquery result set expressions for
  103122. ** references to the iParent in the outer query.
  103123. **
  103124. ** Example:
  103125. **
  103126. ** SELECT a+5, b*10 FROM (SELECT x*3 AS a, y+10 AS b FROM t1) WHERE a>b;
  103127. ** \ \_____________ subquery __________/ /
  103128. ** \_____________________ outer query ______________________________/
  103129. **
  103130. ** We look at every expression in the outer query and every place we see
  103131. ** "a" we substitute "x*3" and every place we see "b" we substitute "y+10".
  103132. */
  103133. pList = pParent->pEList;
  103134. for(i=0; i<pList->nExpr; i++){
  103135. if( pList->a[i].zName==0 ){
  103136. char *zName = sqlite3DbStrDup(db, pList->a[i].zSpan);
  103137. sqlite3Dequote(zName);
  103138. pList->a[i].zName = zName;
  103139. }
  103140. }
  103141. substExprList(db, pParent->pEList, iParent, pSub->pEList);
  103142. if( isAgg ){
  103143. substExprList(db, pParent->pGroupBy, iParent, pSub->pEList);
  103144. pParent->pHaving = substExpr(db, pParent->pHaving, iParent, pSub->pEList);
  103145. }
  103146. if( pSub->pOrderBy ){
  103147. /* At this point, any non-zero iOrderByCol values indicate that the
  103148. ** ORDER BY column expression is identical to the iOrderByCol'th
  103149. ** expression returned by SELECT statement pSub. Since these values
  103150. ** do not necessarily correspond to columns in SELECT statement pParent,
  103151. ** zero them before transfering the ORDER BY clause.
  103152. **
  103153. ** Not doing this may cause an error if a subsequent call to this
  103154. ** function attempts to flatten a compound sub-query into pParent
  103155. ** (the only way this can happen is if the compound sub-query is
  103156. ** currently part of pSub->pSrc). See ticket [d11a6e908f]. */
  103157. ExprList *pOrderBy = pSub->pOrderBy;
  103158. for(i=0; i<pOrderBy->nExpr; i++){
  103159. pOrderBy->a[i].u.x.iOrderByCol = 0;
  103160. }
  103161. assert( pParent->pOrderBy==0 );
  103162. assert( pSub->pPrior==0 );
  103163. pParent->pOrderBy = pOrderBy;
  103164. pSub->pOrderBy = 0;
  103165. }else if( pParent->pOrderBy ){
  103166. substExprList(db, pParent->pOrderBy, iParent, pSub->pEList);
  103167. }
  103168. if( pSub->pWhere ){
  103169. pWhere = sqlite3ExprDup(db, pSub->pWhere, 0);
  103170. }else{
  103171. pWhere = 0;
  103172. }
  103173. if( subqueryIsAgg ){
  103174. assert( pParent->pHaving==0 );
  103175. pParent->pHaving = pParent->pWhere;
  103176. pParent->pWhere = pWhere;
  103177. pParent->pHaving = substExpr(db, pParent->pHaving, iParent, pSub->pEList);
  103178. pParent->pHaving = sqlite3ExprAnd(db, pParent->pHaving,
  103179. sqlite3ExprDup(db, pSub->pHaving, 0));
  103180. assert( pParent->pGroupBy==0 );
  103181. pParent->pGroupBy = sqlite3ExprListDup(db, pSub->pGroupBy, 0);
  103182. }else{
  103183. pParent->pWhere = substExpr(db, pParent->pWhere, iParent, pSub->pEList);
  103184. pParent->pWhere = sqlite3ExprAnd(db, pParent->pWhere, pWhere);
  103185. }
  103186. /* The flattened query is distinct if either the inner or the
  103187. ** outer query is distinct.
  103188. */
  103189. pParent->selFlags |= pSub->selFlags & SF_Distinct;
  103190. /*
  103191. ** SELECT ... FROM (SELECT ... LIMIT a OFFSET b) LIMIT x OFFSET y;
  103192. **
  103193. ** One is tempted to try to add a and b to combine the limits. But this
  103194. ** does not work if either limit is negative.
  103195. */
  103196. if( pSub->pLimit ){
  103197. pParent->pLimit = pSub->pLimit;
  103198. pSub->pLimit = 0;
  103199. }
  103200. }
  103201. /* Finially, delete what is left of the subquery and return
  103202. ** success.
  103203. */
  103204. sqlite3SelectDelete(db, pSub1);
  103205. #if SELECTTRACE_ENABLED
  103206. if( sqlite3SelectTrace & 0x100 ){
  103207. sqlite3DebugPrintf("After flattening:\n");
  103208. sqlite3TreeViewSelect(0, p, 0);
  103209. }
  103210. #endif
  103211. return 1;
  103212. }
  103213. #endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */
  103214. /*
  103215. ** Based on the contents of the AggInfo structure indicated by the first
  103216. ** argument, this function checks if the following are true:
  103217. **
  103218. ** * the query contains just a single aggregate function,
  103219. ** * the aggregate function is either min() or max(), and
  103220. ** * the argument to the aggregate function is a column value.
  103221. **
  103222. ** If all of the above are true, then WHERE_ORDERBY_MIN or WHERE_ORDERBY_MAX
  103223. ** is returned as appropriate. Also, *ppMinMax is set to point to the
  103224. ** list of arguments passed to the aggregate before returning.
  103225. **
  103226. ** Or, if the conditions above are not met, *ppMinMax is set to 0 and
  103227. ** WHERE_ORDERBY_NORMAL is returned.
  103228. */
  103229. static u8 minMaxQuery(AggInfo *pAggInfo, ExprList **ppMinMax){
  103230. int eRet = WHERE_ORDERBY_NORMAL; /* Return value */
  103231. *ppMinMax = 0;
  103232. if( pAggInfo->nFunc==1 ){
  103233. Expr *pExpr = pAggInfo->aFunc[0].pExpr; /* Aggregate function */
  103234. ExprList *pEList = pExpr->x.pList; /* Arguments to agg function */
  103235. assert( pExpr->op==TK_AGG_FUNCTION );
  103236. if( pEList && pEList->nExpr==1 && pEList->a[0].pExpr->op==TK_AGG_COLUMN ){
  103237. const char *zFunc = pExpr->u.zToken;
  103238. if( sqlite3StrICmp(zFunc, "min")==0 ){
  103239. eRet = WHERE_ORDERBY_MIN;
  103240. *ppMinMax = pEList;
  103241. }else if( sqlite3StrICmp(zFunc, "max")==0 ){
  103242. eRet = WHERE_ORDERBY_MAX;
  103243. *ppMinMax = pEList;
  103244. }
  103245. }
  103246. }
  103247. assert( *ppMinMax==0 || (*ppMinMax)->nExpr==1 );
  103248. return eRet;
  103249. }
  103250. /*
  103251. ** The select statement passed as the first argument is an aggregate query.
  103252. ** The second argument is the associated aggregate-info object. This
  103253. ** function tests if the SELECT is of the form:
  103254. **
  103255. ** SELECT count(*) FROM <tbl>
  103256. **
  103257. ** where table is a database table, not a sub-select or view. If the query
  103258. ** does match this pattern, then a pointer to the Table object representing
  103259. ** <tbl> is returned. Otherwise, 0 is returned.
  103260. */
  103261. static Table *isSimpleCount(Select *p, AggInfo *pAggInfo){
  103262. Table *pTab;
  103263. Expr *pExpr;
  103264. assert( !p->pGroupBy );
  103265. if( p->pWhere || p->pEList->nExpr!=1
  103266. || p->pSrc->nSrc!=1 || p->pSrc->a[0].pSelect
  103267. ){
  103268. return 0;
  103269. }
  103270. pTab = p->pSrc->a[0].pTab;
  103271. pExpr = p->pEList->a[0].pExpr;
  103272. assert( pTab && !pTab->pSelect && pExpr );
  103273. if( IsVirtual(pTab) ) return 0;
  103274. if( pExpr->op!=TK_AGG_FUNCTION ) return 0;
  103275. if( NEVER(pAggInfo->nFunc==0) ) return 0;
  103276. if( (pAggInfo->aFunc[0].pFunc->funcFlags&SQLITE_FUNC_COUNT)==0 ) return 0;
  103277. if( pExpr->flags&EP_Distinct ) return 0;
  103278. return pTab;
  103279. }
  103280. /*
  103281. ** If the source-list item passed as an argument was augmented with an
  103282. ** INDEXED BY clause, then try to locate the specified index. If there
  103283. ** was such a clause and the named index cannot be found, return
  103284. ** SQLITE_ERROR and leave an error in pParse. Otherwise, populate
  103285. ** pFrom->pIndex and return SQLITE_OK.
  103286. */
  103287. SQLITE_PRIVATE int sqlite3IndexedByLookup(Parse *pParse, struct SrcList_item *pFrom){
  103288. if( pFrom->pTab && pFrom->zIndex ){
  103289. Table *pTab = pFrom->pTab;
  103290. char *zIndex = pFrom->zIndex;
  103291. Index *pIdx;
  103292. for(pIdx=pTab->pIndex;
  103293. pIdx && sqlite3StrICmp(pIdx->zName, zIndex);
  103294. pIdx=pIdx->pNext
  103295. );
  103296. if( !pIdx ){
  103297. sqlite3ErrorMsg(pParse, "no such index: %s", zIndex, 0);
  103298. pParse->checkSchema = 1;
  103299. return SQLITE_ERROR;
  103300. }
  103301. pFrom->pIndex = pIdx;
  103302. }
  103303. return SQLITE_OK;
  103304. }
  103305. /*
  103306. ** Detect compound SELECT statements that use an ORDER BY clause with
  103307. ** an alternative collating sequence.
  103308. **
  103309. ** SELECT ... FROM t1 EXCEPT SELECT ... FROM t2 ORDER BY .. COLLATE ...
  103310. **
  103311. ** These are rewritten as a subquery:
  103312. **
  103313. ** SELECT * FROM (SELECT ... FROM t1 EXCEPT SELECT ... FROM t2)
  103314. ** ORDER BY ... COLLATE ...
  103315. **
  103316. ** This transformation is necessary because the multiSelectOrderBy() routine
  103317. ** above that generates the code for a compound SELECT with an ORDER BY clause
  103318. ** uses a merge algorithm that requires the same collating sequence on the
  103319. ** result columns as on the ORDER BY clause. See ticket
  103320. ** http://www.sqlite.org/src/info/6709574d2a
  103321. **
  103322. ** This transformation is only needed for EXCEPT, INTERSECT, and UNION.
  103323. ** The UNION ALL operator works fine with multiSelectOrderBy() even when
  103324. ** there are COLLATE terms in the ORDER BY.
  103325. */
  103326. static int convertCompoundSelectToSubquery(Walker *pWalker, Select *p){
  103327. int i;
  103328. Select *pNew;
  103329. Select *pX;
  103330. sqlite3 *db;
  103331. struct ExprList_item *a;
  103332. SrcList *pNewSrc;
  103333. Parse *pParse;
  103334. Token dummy;
  103335. if( p->pPrior==0 ) return WRC_Continue;
  103336. if( p->pOrderBy==0 ) return WRC_Continue;
  103337. for(pX=p; pX && (pX->op==TK_ALL || pX->op==TK_SELECT); pX=pX->pPrior){}
  103338. if( pX==0 ) return WRC_Continue;
  103339. a = p->pOrderBy->a;
  103340. for(i=p->pOrderBy->nExpr-1; i>=0; i--){
  103341. if( a[i].pExpr->flags & EP_Collate ) break;
  103342. }
  103343. if( i<0 ) return WRC_Continue;
  103344. /* If we reach this point, that means the transformation is required. */
  103345. pParse = pWalker->pParse;
  103346. db = pParse->db;
  103347. pNew = sqlite3DbMallocZero(db, sizeof(*pNew) );
  103348. if( pNew==0 ) return WRC_Abort;
  103349. memset(&dummy, 0, sizeof(dummy));
  103350. pNewSrc = sqlite3SrcListAppendFromTerm(pParse,0,0,0,&dummy,pNew,0,0);
  103351. if( pNewSrc==0 ) return WRC_Abort;
  103352. *pNew = *p;
  103353. p->pSrc = pNewSrc;
  103354. p->pEList = sqlite3ExprListAppend(pParse, 0, sqlite3Expr(db, TK_ALL, 0));
  103355. p->op = TK_SELECT;
  103356. p->pWhere = 0;
  103357. pNew->pGroupBy = 0;
  103358. pNew->pHaving = 0;
  103359. pNew->pOrderBy = 0;
  103360. p->pPrior = 0;
  103361. p->pNext = 0;
  103362. p->pWith = 0;
  103363. p->selFlags &= ~SF_Compound;
  103364. assert( (p->selFlags & SF_Converted)==0 );
  103365. p->selFlags |= SF_Converted;
  103366. assert( pNew->pPrior!=0 );
  103367. pNew->pPrior->pNext = pNew;
  103368. pNew->pLimit = 0;
  103369. pNew->pOffset = 0;
  103370. return WRC_Continue;
  103371. }
  103372. #ifndef SQLITE_OMIT_CTE
  103373. /*
  103374. ** Argument pWith (which may be NULL) points to a linked list of nested
  103375. ** WITH contexts, from inner to outermost. If the table identified by
  103376. ** FROM clause element pItem is really a common-table-expression (CTE)
  103377. ** then return a pointer to the CTE definition for that table. Otherwise
  103378. ** return NULL.
  103379. **
  103380. ** If a non-NULL value is returned, set *ppContext to point to the With
  103381. ** object that the returned CTE belongs to.
  103382. */
  103383. static struct Cte *searchWith(
  103384. With *pWith, /* Current outermost WITH clause */
  103385. struct SrcList_item *pItem, /* FROM clause element to resolve */
  103386. With **ppContext /* OUT: WITH clause return value belongs to */
  103387. ){
  103388. const char *zName;
  103389. if( pItem->zDatabase==0 && (zName = pItem->zName)!=0 ){
  103390. With *p;
  103391. for(p=pWith; p; p=p->pOuter){
  103392. int i;
  103393. for(i=0; i<p->nCte; i++){
  103394. if( sqlite3StrICmp(zName, p->a[i].zName)==0 ){
  103395. *ppContext = p;
  103396. return &p->a[i];
  103397. }
  103398. }
  103399. }
  103400. }
  103401. return 0;
  103402. }
  103403. /* The code generator maintains a stack of active WITH clauses
  103404. ** with the inner-most WITH clause being at the top of the stack.
  103405. **
  103406. ** This routine pushes the WITH clause passed as the second argument
  103407. ** onto the top of the stack. If argument bFree is true, then this
  103408. ** WITH clause will never be popped from the stack. In this case it
  103409. ** should be freed along with the Parse object. In other cases, when
  103410. ** bFree==0, the With object will be freed along with the SELECT
  103411. ** statement with which it is associated.
  103412. */
  103413. SQLITE_PRIVATE void sqlite3WithPush(Parse *pParse, With *pWith, u8 bFree){
  103414. assert( bFree==0 || pParse->pWith==0 );
  103415. if( pWith ){
  103416. pWith->pOuter = pParse->pWith;
  103417. pParse->pWith = pWith;
  103418. pParse->bFreeWith = bFree;
  103419. }
  103420. }
  103421. /*
  103422. ** This function checks if argument pFrom refers to a CTE declared by
  103423. ** a WITH clause on the stack currently maintained by the parser. And,
  103424. ** if currently processing a CTE expression, if it is a recursive
  103425. ** reference to the current CTE.
  103426. **
  103427. ** If pFrom falls into either of the two categories above, pFrom->pTab
  103428. ** and other fields are populated accordingly. The caller should check
  103429. ** (pFrom->pTab!=0) to determine whether or not a successful match
  103430. ** was found.
  103431. **
  103432. ** Whether or not a match is found, SQLITE_OK is returned if no error
  103433. ** occurs. If an error does occur, an error message is stored in the
  103434. ** parser and some error code other than SQLITE_OK returned.
  103435. */
  103436. static int withExpand(
  103437. Walker *pWalker,
  103438. struct SrcList_item *pFrom
  103439. ){
  103440. Parse *pParse = pWalker->pParse;
  103441. sqlite3 *db = pParse->db;
  103442. struct Cte *pCte; /* Matched CTE (or NULL if no match) */
  103443. With *pWith; /* WITH clause that pCte belongs to */
  103444. assert( pFrom->pTab==0 );
  103445. pCte = searchWith(pParse->pWith, pFrom, &pWith);
  103446. if( pCte ){
  103447. Table *pTab;
  103448. ExprList *pEList;
  103449. Select *pSel;
  103450. Select *pLeft; /* Left-most SELECT statement */
  103451. int bMayRecursive; /* True if compound joined by UNION [ALL] */
  103452. With *pSavedWith; /* Initial value of pParse->pWith */
  103453. /* If pCte->zErr is non-NULL at this point, then this is an illegal
  103454. ** recursive reference to CTE pCte. Leave an error in pParse and return
  103455. ** early. If pCte->zErr is NULL, then this is not a recursive reference.
  103456. ** In this case, proceed. */
  103457. if( pCte->zErr ){
  103458. sqlite3ErrorMsg(pParse, pCte->zErr, pCte->zName);
  103459. return SQLITE_ERROR;
  103460. }
  103461. assert( pFrom->pTab==0 );
  103462. pFrom->pTab = pTab = sqlite3DbMallocZero(db, sizeof(Table));
  103463. if( pTab==0 ) return WRC_Abort;
  103464. pTab->nRef = 1;
  103465. pTab->zName = sqlite3DbStrDup(db, pCte->zName);
  103466. pTab->iPKey = -1;
  103467. pTab->nRowLogEst = 200; assert( 200==sqlite3LogEst(1048576) );
  103468. pTab->tabFlags |= TF_Ephemeral;
  103469. pFrom->pSelect = sqlite3SelectDup(db, pCte->pSelect, 0);
  103470. if( db->mallocFailed ) return SQLITE_NOMEM;
  103471. assert( pFrom->pSelect );
  103472. /* Check if this is a recursive CTE. */
  103473. pSel = pFrom->pSelect;
  103474. bMayRecursive = ( pSel->op==TK_ALL || pSel->op==TK_UNION );
  103475. if( bMayRecursive ){
  103476. int i;
  103477. SrcList *pSrc = pFrom->pSelect->pSrc;
  103478. for(i=0; i<pSrc->nSrc; i++){
  103479. struct SrcList_item *pItem = &pSrc->a[i];
  103480. if( pItem->zDatabase==0
  103481. && pItem->zName!=0
  103482. && 0==sqlite3StrICmp(pItem->zName, pCte->zName)
  103483. ){
  103484. pItem->pTab = pTab;
  103485. pItem->isRecursive = 1;
  103486. pTab->nRef++;
  103487. pSel->selFlags |= SF_Recursive;
  103488. }
  103489. }
  103490. }
  103491. /* Only one recursive reference is permitted. */
  103492. if( pTab->nRef>2 ){
  103493. sqlite3ErrorMsg(
  103494. pParse, "multiple references to recursive table: %s", pCte->zName
  103495. );
  103496. return SQLITE_ERROR;
  103497. }
  103498. assert( pTab->nRef==1 || ((pSel->selFlags&SF_Recursive) && pTab->nRef==2 ));
  103499. pCte->zErr = "circular reference: %s";
  103500. pSavedWith = pParse->pWith;
  103501. pParse->pWith = pWith;
  103502. sqlite3WalkSelect(pWalker, bMayRecursive ? pSel->pPrior : pSel);
  103503. for(pLeft=pSel; pLeft->pPrior; pLeft=pLeft->pPrior);
  103504. pEList = pLeft->pEList;
  103505. if( pCte->pCols ){
  103506. if( pEList && pEList->nExpr!=pCte->pCols->nExpr ){
  103507. sqlite3ErrorMsg(pParse, "table %s has %d values for %d columns",
  103508. pCte->zName, pEList->nExpr, pCte->pCols->nExpr
  103509. );
  103510. pParse->pWith = pSavedWith;
  103511. return SQLITE_ERROR;
  103512. }
  103513. pEList = pCte->pCols;
  103514. }
  103515. selectColumnsFromExprList(pParse, pEList, &pTab->nCol, &pTab->aCol);
  103516. if( bMayRecursive ){
  103517. if( pSel->selFlags & SF_Recursive ){
  103518. pCte->zErr = "multiple recursive references: %s";
  103519. }else{
  103520. pCte->zErr = "recursive reference in a subquery: %s";
  103521. }
  103522. sqlite3WalkSelect(pWalker, pSel);
  103523. }
  103524. pCte->zErr = 0;
  103525. pParse->pWith = pSavedWith;
  103526. }
  103527. return SQLITE_OK;
  103528. }
  103529. #endif
  103530. #ifndef SQLITE_OMIT_CTE
  103531. /*
  103532. ** If the SELECT passed as the second argument has an associated WITH
  103533. ** clause, pop it from the stack stored as part of the Parse object.
  103534. **
  103535. ** This function is used as the xSelectCallback2() callback by
  103536. ** sqlite3SelectExpand() when walking a SELECT tree to resolve table
  103537. ** names and other FROM clause elements.
  103538. */
  103539. static void selectPopWith(Walker *pWalker, Select *p){
  103540. Parse *pParse = pWalker->pParse;
  103541. With *pWith = findRightmost(p)->pWith;
  103542. if( pWith!=0 ){
  103543. assert( pParse->pWith==pWith );
  103544. pParse->pWith = pWith->pOuter;
  103545. }
  103546. }
  103547. #else
  103548. #define selectPopWith 0
  103549. #endif
  103550. /*
  103551. ** This routine is a Walker callback for "expanding" a SELECT statement.
  103552. ** "Expanding" means to do the following:
  103553. **
  103554. ** (1) Make sure VDBE cursor numbers have been assigned to every
  103555. ** element of the FROM clause.
  103556. **
  103557. ** (2) Fill in the pTabList->a[].pTab fields in the SrcList that
  103558. ** defines FROM clause. When views appear in the FROM clause,
  103559. ** fill pTabList->a[].pSelect with a copy of the SELECT statement
  103560. ** that implements the view. A copy is made of the view's SELECT
  103561. ** statement so that we can freely modify or delete that statement
  103562. ** without worrying about messing up the persistent representation
  103563. ** of the view.
  103564. **
  103565. ** (3) Add terms to the WHERE clause to accommodate the NATURAL keyword
  103566. ** on joins and the ON and USING clause of joins.
  103567. **
  103568. ** (4) Scan the list of columns in the result set (pEList) looking
  103569. ** for instances of the "*" operator or the TABLE.* operator.
  103570. ** If found, expand each "*" to be every column in every table
  103571. ** and TABLE.* to be every column in TABLE.
  103572. **
  103573. */
  103574. static int selectExpander(Walker *pWalker, Select *p){
  103575. Parse *pParse = pWalker->pParse;
  103576. int i, j, k;
  103577. SrcList *pTabList;
  103578. ExprList *pEList;
  103579. struct SrcList_item *pFrom;
  103580. sqlite3 *db = pParse->db;
  103581. Expr *pE, *pRight, *pExpr;
  103582. u16 selFlags = p->selFlags;
  103583. p->selFlags |= SF_Expanded;
  103584. if( db->mallocFailed ){
  103585. return WRC_Abort;
  103586. }
  103587. if( NEVER(p->pSrc==0) || (selFlags & SF_Expanded)!=0 ){
  103588. return WRC_Prune;
  103589. }
  103590. pTabList = p->pSrc;
  103591. pEList = p->pEList;
  103592. if( pWalker->xSelectCallback2==selectPopWith ){
  103593. sqlite3WithPush(pParse, findRightmost(p)->pWith, 0);
  103594. }
  103595. /* Make sure cursor numbers have been assigned to all entries in
  103596. ** the FROM clause of the SELECT statement.
  103597. */
  103598. sqlite3SrcListAssignCursors(pParse, pTabList);
  103599. /* Look up every table named in the FROM clause of the select. If
  103600. ** an entry of the FROM clause is a subquery instead of a table or view,
  103601. ** then create a transient table structure to describe the subquery.
  103602. */
  103603. for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
  103604. Table *pTab;
  103605. assert( pFrom->isRecursive==0 || pFrom->pTab );
  103606. if( pFrom->isRecursive ) continue;
  103607. if( pFrom->pTab!=0 ){
  103608. /* This statement has already been prepared. There is no need
  103609. ** to go further. */
  103610. assert( i==0 );
  103611. #ifndef SQLITE_OMIT_CTE
  103612. selectPopWith(pWalker, p);
  103613. #endif
  103614. return WRC_Prune;
  103615. }
  103616. #ifndef SQLITE_OMIT_CTE
  103617. if( withExpand(pWalker, pFrom) ) return WRC_Abort;
  103618. if( pFrom->pTab ) {} else
  103619. #endif
  103620. if( pFrom->zName==0 ){
  103621. #ifndef SQLITE_OMIT_SUBQUERY
  103622. Select *pSel = pFrom->pSelect;
  103623. /* A sub-query in the FROM clause of a SELECT */
  103624. assert( pSel!=0 );
  103625. assert( pFrom->pTab==0 );
  103626. if( sqlite3WalkSelect(pWalker, pSel) ) return WRC_Abort;
  103627. pFrom->pTab = pTab = sqlite3DbMallocZero(db, sizeof(Table));
  103628. if( pTab==0 ) return WRC_Abort;
  103629. pTab->nRef = 1;
  103630. pTab->zName = sqlite3MPrintf(db, "sqlite_sq_%p", (void*)pTab);
  103631. while( pSel->pPrior ){ pSel = pSel->pPrior; }
  103632. selectColumnsFromExprList(pParse, pSel->pEList, &pTab->nCol, &pTab->aCol);
  103633. pTab->iPKey = -1;
  103634. pTab->nRowLogEst = 200; assert( 200==sqlite3LogEst(1048576) );
  103635. pTab->tabFlags |= TF_Ephemeral;
  103636. #endif
  103637. }else{
  103638. /* An ordinary table or view name in the FROM clause */
  103639. assert( pFrom->pTab==0 );
  103640. pFrom->pTab = pTab = sqlite3LocateTableItem(pParse, 0, pFrom);
  103641. if( pTab==0 ) return WRC_Abort;
  103642. if( pTab->nRef==0xffff ){
  103643. sqlite3ErrorMsg(pParse, "too many references to \"%s\": max 65535",
  103644. pTab->zName);
  103645. pFrom->pTab = 0;
  103646. return WRC_Abort;
  103647. }
  103648. pTab->nRef++;
  103649. #if !defined(SQLITE_OMIT_VIEW) || !defined (SQLITE_OMIT_VIRTUALTABLE)
  103650. if( pTab->pSelect || IsVirtual(pTab) ){
  103651. /* We reach here if the named table is a really a view */
  103652. if( sqlite3ViewGetColumnNames(pParse, pTab) ) return WRC_Abort;
  103653. assert( pFrom->pSelect==0 );
  103654. pFrom->pSelect = sqlite3SelectDup(db, pTab->pSelect, 0);
  103655. sqlite3SelectSetName(pFrom->pSelect, pTab->zName);
  103656. sqlite3WalkSelect(pWalker, pFrom->pSelect);
  103657. }
  103658. #endif
  103659. }
  103660. /* Locate the index named by the INDEXED BY clause, if any. */
  103661. if( sqlite3IndexedByLookup(pParse, pFrom) ){
  103662. return WRC_Abort;
  103663. }
  103664. }
  103665. /* Process NATURAL keywords, and ON and USING clauses of joins.
  103666. */
  103667. if( db->mallocFailed || sqliteProcessJoin(pParse, p) ){
  103668. return WRC_Abort;
  103669. }
  103670. /* For every "*" that occurs in the column list, insert the names of
  103671. ** all columns in all tables. And for every TABLE.* insert the names
  103672. ** of all columns in TABLE. The parser inserted a special expression
  103673. ** with the TK_ALL operator for each "*" that it found in the column list.
  103674. ** The following code just has to locate the TK_ALL expressions and expand
  103675. ** each one to the list of all columns in all tables.
  103676. **
  103677. ** The first loop just checks to see if there are any "*" operators
  103678. ** that need expanding.
  103679. */
  103680. for(k=0; k<pEList->nExpr; k++){
  103681. pE = pEList->a[k].pExpr;
  103682. if( pE->op==TK_ALL ) break;
  103683. assert( pE->op!=TK_DOT || pE->pRight!=0 );
  103684. assert( pE->op!=TK_DOT || (pE->pLeft!=0 && pE->pLeft->op==TK_ID) );
  103685. if( pE->op==TK_DOT && pE->pRight->op==TK_ALL ) break;
  103686. }
  103687. if( k<pEList->nExpr ){
  103688. /*
  103689. ** If we get here it means the result set contains one or more "*"
  103690. ** operators that need to be expanded. Loop through each expression
  103691. ** in the result set and expand them one by one.
  103692. */
  103693. struct ExprList_item *a = pEList->a;
  103694. ExprList *pNew = 0;
  103695. int flags = pParse->db->flags;
  103696. int longNames = (flags & SQLITE_FullColNames)!=0
  103697. && (flags & SQLITE_ShortColNames)==0;
  103698. /* When processing FROM-clause subqueries, it is always the case
  103699. ** that full_column_names=OFF and short_column_names=ON. The
  103700. ** sqlite3ResultSetOfSelect() routine makes it so. */
  103701. assert( (p->selFlags & SF_NestedFrom)==0
  103702. || ((flags & SQLITE_FullColNames)==0 &&
  103703. (flags & SQLITE_ShortColNames)!=0) );
  103704. for(k=0; k<pEList->nExpr; k++){
  103705. pE = a[k].pExpr;
  103706. pRight = pE->pRight;
  103707. assert( pE->op!=TK_DOT || pRight!=0 );
  103708. if( pE->op!=TK_ALL && (pE->op!=TK_DOT || pRight->op!=TK_ALL) ){
  103709. /* This particular expression does not need to be expanded.
  103710. */
  103711. pNew = sqlite3ExprListAppend(pParse, pNew, a[k].pExpr);
  103712. if( pNew ){
  103713. pNew->a[pNew->nExpr-1].zName = a[k].zName;
  103714. pNew->a[pNew->nExpr-1].zSpan = a[k].zSpan;
  103715. a[k].zName = 0;
  103716. a[k].zSpan = 0;
  103717. }
  103718. a[k].pExpr = 0;
  103719. }else{
  103720. /* This expression is a "*" or a "TABLE.*" and needs to be
  103721. ** expanded. */
  103722. int tableSeen = 0; /* Set to 1 when TABLE matches */
  103723. char *zTName = 0; /* text of name of TABLE */
  103724. if( pE->op==TK_DOT ){
  103725. assert( pE->pLeft!=0 );
  103726. assert( !ExprHasProperty(pE->pLeft, EP_IntValue) );
  103727. zTName = pE->pLeft->u.zToken;
  103728. }
  103729. for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
  103730. Table *pTab = pFrom->pTab;
  103731. Select *pSub = pFrom->pSelect;
  103732. char *zTabName = pFrom->zAlias;
  103733. const char *zSchemaName = 0;
  103734. int iDb;
  103735. if( zTabName==0 ){
  103736. zTabName = pTab->zName;
  103737. }
  103738. if( db->mallocFailed ) break;
  103739. if( pSub==0 || (pSub->selFlags & SF_NestedFrom)==0 ){
  103740. pSub = 0;
  103741. if( zTName && sqlite3StrICmp(zTName, zTabName)!=0 ){
  103742. continue;
  103743. }
  103744. iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  103745. zSchemaName = iDb>=0 ? db->aDb[iDb].zName : "*";
  103746. }
  103747. for(j=0; j<pTab->nCol; j++){
  103748. char *zName = pTab->aCol[j].zName;
  103749. char *zColname; /* The computed column name */
  103750. char *zToFree; /* Malloced string that needs to be freed */
  103751. Token sColname; /* Computed column name as a token */
  103752. assert( zName );
  103753. if( zTName && pSub
  103754. && sqlite3MatchSpanName(pSub->pEList->a[j].zSpan, 0, zTName, 0)==0
  103755. ){
  103756. continue;
  103757. }
  103758. /* If a column is marked as 'hidden' (currently only possible
  103759. ** for virtual tables), do not include it in the expanded
  103760. ** result-set list.
  103761. */
  103762. if( IsHiddenColumn(&pTab->aCol[j]) ){
  103763. assert(IsVirtual(pTab));
  103764. continue;
  103765. }
  103766. tableSeen = 1;
  103767. if( i>0 && zTName==0 ){
  103768. if( (pFrom->jointype & JT_NATURAL)!=0
  103769. && tableAndColumnIndex(pTabList, i, zName, 0, 0)
  103770. ){
  103771. /* In a NATURAL join, omit the join columns from the
  103772. ** table to the right of the join */
  103773. continue;
  103774. }
  103775. if( sqlite3IdListIndex(pFrom->pUsing, zName)>=0 ){
  103776. /* In a join with a USING clause, omit columns in the
  103777. ** using clause from the table on the right. */
  103778. continue;
  103779. }
  103780. }
  103781. pRight = sqlite3Expr(db, TK_ID, zName);
  103782. zColname = zName;
  103783. zToFree = 0;
  103784. if( longNames || pTabList->nSrc>1 ){
  103785. Expr *pLeft;
  103786. pLeft = sqlite3Expr(db, TK_ID, zTabName);
  103787. pExpr = sqlite3PExpr(pParse, TK_DOT, pLeft, pRight, 0);
  103788. if( zSchemaName ){
  103789. pLeft = sqlite3Expr(db, TK_ID, zSchemaName);
  103790. pExpr = sqlite3PExpr(pParse, TK_DOT, pLeft, pExpr, 0);
  103791. }
  103792. if( longNames ){
  103793. zColname = sqlite3MPrintf(db, "%s.%s", zTabName, zName);
  103794. zToFree = zColname;
  103795. }
  103796. }else{
  103797. pExpr = pRight;
  103798. }
  103799. pNew = sqlite3ExprListAppend(pParse, pNew, pExpr);
  103800. sColname.z = zColname;
  103801. sColname.n = sqlite3Strlen30(zColname);
  103802. sqlite3ExprListSetName(pParse, pNew, &sColname, 0);
  103803. if( pNew && (p->selFlags & SF_NestedFrom)!=0 ){
  103804. struct ExprList_item *pX = &pNew->a[pNew->nExpr-1];
  103805. if( pSub ){
  103806. pX->zSpan = sqlite3DbStrDup(db, pSub->pEList->a[j].zSpan);
  103807. testcase( pX->zSpan==0 );
  103808. }else{
  103809. pX->zSpan = sqlite3MPrintf(db, "%s.%s.%s",
  103810. zSchemaName, zTabName, zColname);
  103811. testcase( pX->zSpan==0 );
  103812. }
  103813. pX->bSpanIsTab = 1;
  103814. }
  103815. sqlite3DbFree(db, zToFree);
  103816. }
  103817. }
  103818. if( !tableSeen ){
  103819. if( zTName ){
  103820. sqlite3ErrorMsg(pParse, "no such table: %s", zTName);
  103821. }else{
  103822. sqlite3ErrorMsg(pParse, "no tables specified");
  103823. }
  103824. }
  103825. }
  103826. }
  103827. sqlite3ExprListDelete(db, pEList);
  103828. p->pEList = pNew;
  103829. }
  103830. #if SQLITE_MAX_COLUMN
  103831. if( p->pEList && p->pEList->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
  103832. sqlite3ErrorMsg(pParse, "too many columns in result set");
  103833. }
  103834. #endif
  103835. return WRC_Continue;
  103836. }
  103837. /*
  103838. ** No-op routine for the parse-tree walker.
  103839. **
  103840. ** When this routine is the Walker.xExprCallback then expression trees
  103841. ** are walked without any actions being taken at each node. Presumably,
  103842. ** when this routine is used for Walker.xExprCallback then
  103843. ** Walker.xSelectCallback is set to do something useful for every
  103844. ** subquery in the parser tree.
  103845. */
  103846. static int exprWalkNoop(Walker *NotUsed, Expr *NotUsed2){
  103847. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  103848. return WRC_Continue;
  103849. }
  103850. /*
  103851. ** This routine "expands" a SELECT statement and all of its subqueries.
  103852. ** For additional information on what it means to "expand" a SELECT
  103853. ** statement, see the comment on the selectExpand worker callback above.
  103854. **
  103855. ** Expanding a SELECT statement is the first step in processing a
  103856. ** SELECT statement. The SELECT statement must be expanded before
  103857. ** name resolution is performed.
  103858. **
  103859. ** If anything goes wrong, an error message is written into pParse.
  103860. ** The calling function can detect the problem by looking at pParse->nErr
  103861. ** and/or pParse->db->mallocFailed.
  103862. */
  103863. static void sqlite3SelectExpand(Parse *pParse, Select *pSelect){
  103864. Walker w;
  103865. memset(&w, 0, sizeof(w));
  103866. w.xExprCallback = exprWalkNoop;
  103867. w.pParse = pParse;
  103868. if( pParse->hasCompound ){
  103869. w.xSelectCallback = convertCompoundSelectToSubquery;
  103870. sqlite3WalkSelect(&w, pSelect);
  103871. }
  103872. w.xSelectCallback = selectExpander;
  103873. if( (pSelect->selFlags & SF_MultiValue)==0 ){
  103874. w.xSelectCallback2 = selectPopWith;
  103875. }
  103876. sqlite3WalkSelect(&w, pSelect);
  103877. }
  103878. #ifndef SQLITE_OMIT_SUBQUERY
  103879. /*
  103880. ** This is a Walker.xSelectCallback callback for the sqlite3SelectTypeInfo()
  103881. ** interface.
  103882. **
  103883. ** For each FROM-clause subquery, add Column.zType and Column.zColl
  103884. ** information to the Table structure that represents the result set
  103885. ** of that subquery.
  103886. **
  103887. ** The Table structure that represents the result set was constructed
  103888. ** by selectExpander() but the type and collation information was omitted
  103889. ** at that point because identifiers had not yet been resolved. This
  103890. ** routine is called after identifier resolution.
  103891. */
  103892. static void selectAddSubqueryTypeInfo(Walker *pWalker, Select *p){
  103893. Parse *pParse;
  103894. int i;
  103895. SrcList *pTabList;
  103896. struct SrcList_item *pFrom;
  103897. assert( p->selFlags & SF_Resolved );
  103898. if( (p->selFlags & SF_HasTypeInfo)==0 ){
  103899. p->selFlags |= SF_HasTypeInfo;
  103900. pParse = pWalker->pParse;
  103901. pTabList = p->pSrc;
  103902. for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
  103903. Table *pTab = pFrom->pTab;
  103904. if( ALWAYS(pTab!=0) && (pTab->tabFlags & TF_Ephemeral)!=0 ){
  103905. /* A sub-query in the FROM clause of a SELECT */
  103906. Select *pSel = pFrom->pSelect;
  103907. if( pSel ){
  103908. while( pSel->pPrior ) pSel = pSel->pPrior;
  103909. selectAddColumnTypeAndCollation(pParse, pTab, pSel);
  103910. }
  103911. }
  103912. }
  103913. }
  103914. }
  103915. #endif
  103916. /*
  103917. ** This routine adds datatype and collating sequence information to
  103918. ** the Table structures of all FROM-clause subqueries in a
  103919. ** SELECT statement.
  103920. **
  103921. ** Use this routine after name resolution.
  103922. */
  103923. static void sqlite3SelectAddTypeInfo(Parse *pParse, Select *pSelect){
  103924. #ifndef SQLITE_OMIT_SUBQUERY
  103925. Walker w;
  103926. memset(&w, 0, sizeof(w));
  103927. w.xSelectCallback2 = selectAddSubqueryTypeInfo;
  103928. w.xExprCallback = exprWalkNoop;
  103929. w.pParse = pParse;
  103930. sqlite3WalkSelect(&w, pSelect);
  103931. #endif
  103932. }
  103933. /*
  103934. ** This routine sets up a SELECT statement for processing. The
  103935. ** following is accomplished:
  103936. **
  103937. ** * VDBE Cursor numbers are assigned to all FROM-clause terms.
  103938. ** * Ephemeral Table objects are created for all FROM-clause subqueries.
  103939. ** * ON and USING clauses are shifted into WHERE statements
  103940. ** * Wildcards "*" and "TABLE.*" in result sets are expanded.
  103941. ** * Identifiers in expression are matched to tables.
  103942. **
  103943. ** This routine acts recursively on all subqueries within the SELECT.
  103944. */
  103945. SQLITE_PRIVATE void sqlite3SelectPrep(
  103946. Parse *pParse, /* The parser context */
  103947. Select *p, /* The SELECT statement being coded. */
  103948. NameContext *pOuterNC /* Name context for container */
  103949. ){
  103950. sqlite3 *db;
  103951. if( NEVER(p==0) ) return;
  103952. db = pParse->db;
  103953. if( db->mallocFailed ) return;
  103954. if( p->selFlags & SF_HasTypeInfo ) return;
  103955. sqlite3SelectExpand(pParse, p);
  103956. if( pParse->nErr || db->mallocFailed ) return;
  103957. sqlite3ResolveSelectNames(pParse, p, pOuterNC);
  103958. if( pParse->nErr || db->mallocFailed ) return;
  103959. sqlite3SelectAddTypeInfo(pParse, p);
  103960. }
  103961. /*
  103962. ** Reset the aggregate accumulator.
  103963. **
  103964. ** The aggregate accumulator is a set of memory cells that hold
  103965. ** intermediate results while calculating an aggregate. This
  103966. ** routine generates code that stores NULLs in all of those memory
  103967. ** cells.
  103968. */
  103969. static void resetAccumulator(Parse *pParse, AggInfo *pAggInfo){
  103970. Vdbe *v = pParse->pVdbe;
  103971. int i;
  103972. struct AggInfo_func *pFunc;
  103973. int nReg = pAggInfo->nFunc + pAggInfo->nColumn;
  103974. if( nReg==0 ) return;
  103975. #ifdef SQLITE_DEBUG
  103976. /* Verify that all AggInfo registers are within the range specified by
  103977. ** AggInfo.mnReg..AggInfo.mxReg */
  103978. assert( nReg==pAggInfo->mxReg-pAggInfo->mnReg+1 );
  103979. for(i=0; i<pAggInfo->nColumn; i++){
  103980. assert( pAggInfo->aCol[i].iMem>=pAggInfo->mnReg
  103981. && pAggInfo->aCol[i].iMem<=pAggInfo->mxReg );
  103982. }
  103983. for(i=0; i<pAggInfo->nFunc; i++){
  103984. assert( pAggInfo->aFunc[i].iMem>=pAggInfo->mnReg
  103985. && pAggInfo->aFunc[i].iMem<=pAggInfo->mxReg );
  103986. }
  103987. #endif
  103988. sqlite3VdbeAddOp3(v, OP_Null, 0, pAggInfo->mnReg, pAggInfo->mxReg);
  103989. for(pFunc=pAggInfo->aFunc, i=0; i<pAggInfo->nFunc; i++, pFunc++){
  103990. if( pFunc->iDistinct>=0 ){
  103991. Expr *pE = pFunc->pExpr;
  103992. assert( !ExprHasProperty(pE, EP_xIsSelect) );
  103993. if( pE->x.pList==0 || pE->x.pList->nExpr!=1 ){
  103994. sqlite3ErrorMsg(pParse, "DISTINCT aggregates must have exactly one "
  103995. "argument");
  103996. pFunc->iDistinct = -1;
  103997. }else{
  103998. KeyInfo *pKeyInfo = keyInfoFromExprList(pParse, pE->x.pList, 0, 0);
  103999. sqlite3VdbeAddOp4(v, OP_OpenEphemeral, pFunc->iDistinct, 0, 0,
  104000. (char*)pKeyInfo, P4_KEYINFO);
  104001. }
  104002. }
  104003. }
  104004. }
  104005. /*
  104006. ** Invoke the OP_AggFinalize opcode for every aggregate function
  104007. ** in the AggInfo structure.
  104008. */
  104009. static void finalizeAggFunctions(Parse *pParse, AggInfo *pAggInfo){
  104010. Vdbe *v = pParse->pVdbe;
  104011. int i;
  104012. struct AggInfo_func *pF;
  104013. for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){
  104014. ExprList *pList = pF->pExpr->x.pList;
  104015. assert( !ExprHasProperty(pF->pExpr, EP_xIsSelect) );
  104016. sqlite3VdbeAddOp4(v, OP_AggFinal, pF->iMem, pList ? pList->nExpr : 0, 0,
  104017. (void*)pF->pFunc, P4_FUNCDEF);
  104018. }
  104019. }
  104020. /*
  104021. ** Update the accumulator memory cells for an aggregate based on
  104022. ** the current cursor position.
  104023. */
  104024. static void updateAccumulator(Parse *pParse, AggInfo *pAggInfo){
  104025. Vdbe *v = pParse->pVdbe;
  104026. int i;
  104027. int regHit = 0;
  104028. int addrHitTest = 0;
  104029. struct AggInfo_func *pF;
  104030. struct AggInfo_col *pC;
  104031. pAggInfo->directMode = 1;
  104032. for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){
  104033. int nArg;
  104034. int addrNext = 0;
  104035. int regAgg;
  104036. ExprList *pList = pF->pExpr->x.pList;
  104037. assert( !ExprHasProperty(pF->pExpr, EP_xIsSelect) );
  104038. if( pList ){
  104039. nArg = pList->nExpr;
  104040. regAgg = sqlite3GetTempRange(pParse, nArg);
  104041. sqlite3ExprCodeExprList(pParse, pList, regAgg, SQLITE_ECEL_DUP);
  104042. }else{
  104043. nArg = 0;
  104044. regAgg = 0;
  104045. }
  104046. if( pF->iDistinct>=0 ){
  104047. addrNext = sqlite3VdbeMakeLabel(v);
  104048. testcase( nArg==0 ); /* Error condition */
  104049. testcase( nArg>1 ); /* Also an error */
  104050. codeDistinct(pParse, pF->iDistinct, addrNext, 1, regAgg);
  104051. }
  104052. if( pF->pFunc->funcFlags & SQLITE_FUNC_NEEDCOLL ){
  104053. CollSeq *pColl = 0;
  104054. struct ExprList_item *pItem;
  104055. int j;
  104056. assert( pList!=0 ); /* pList!=0 if pF->pFunc has NEEDCOLL */
  104057. for(j=0, pItem=pList->a; !pColl && j<nArg; j++, pItem++){
  104058. pColl = sqlite3ExprCollSeq(pParse, pItem->pExpr);
  104059. }
  104060. if( !pColl ){
  104061. pColl = pParse->db->pDfltColl;
  104062. }
  104063. if( regHit==0 && pAggInfo->nAccumulator ) regHit = ++pParse->nMem;
  104064. sqlite3VdbeAddOp4(v, OP_CollSeq, regHit, 0, 0, (char *)pColl, P4_COLLSEQ);
  104065. }
  104066. sqlite3VdbeAddOp4(v, OP_AggStep, 0, regAgg, pF->iMem,
  104067. (void*)pF->pFunc, P4_FUNCDEF);
  104068. sqlite3VdbeChangeP5(v, (u8)nArg);
  104069. sqlite3ExprCacheAffinityChange(pParse, regAgg, nArg);
  104070. sqlite3ReleaseTempRange(pParse, regAgg, nArg);
  104071. if( addrNext ){
  104072. sqlite3VdbeResolveLabel(v, addrNext);
  104073. sqlite3ExprCacheClear(pParse);
  104074. }
  104075. }
  104076. /* Before populating the accumulator registers, clear the column cache.
  104077. ** Otherwise, if any of the required column values are already present
  104078. ** in registers, sqlite3ExprCode() may use OP_SCopy to copy the value
  104079. ** to pC->iMem. But by the time the value is used, the original register
  104080. ** may have been used, invalidating the underlying buffer holding the
  104081. ** text or blob value. See ticket [883034dcb5].
  104082. **
  104083. ** Another solution would be to change the OP_SCopy used to copy cached
  104084. ** values to an OP_Copy.
  104085. */
  104086. if( regHit ){
  104087. addrHitTest = sqlite3VdbeAddOp1(v, OP_If, regHit); VdbeCoverage(v);
  104088. }
  104089. sqlite3ExprCacheClear(pParse);
  104090. for(i=0, pC=pAggInfo->aCol; i<pAggInfo->nAccumulator; i++, pC++){
  104091. sqlite3ExprCode(pParse, pC->pExpr, pC->iMem);
  104092. }
  104093. pAggInfo->directMode = 0;
  104094. sqlite3ExprCacheClear(pParse);
  104095. if( addrHitTest ){
  104096. sqlite3VdbeJumpHere(v, addrHitTest);
  104097. }
  104098. }
  104099. /*
  104100. ** Add a single OP_Explain instruction to the VDBE to explain a simple
  104101. ** count(*) query ("SELECT count(*) FROM pTab").
  104102. */
  104103. #ifndef SQLITE_OMIT_EXPLAIN
  104104. static void explainSimpleCount(
  104105. Parse *pParse, /* Parse context */
  104106. Table *pTab, /* Table being queried */
  104107. Index *pIdx /* Index used to optimize scan, or NULL */
  104108. ){
  104109. if( pParse->explain==2 ){
  104110. int bCover = (pIdx!=0 && (HasRowid(pTab) || !IsPrimaryKeyIndex(pIdx)));
  104111. char *zEqp = sqlite3MPrintf(pParse->db, "SCAN TABLE %s%s%s",
  104112. pTab->zName,
  104113. bCover ? " USING COVERING INDEX " : "",
  104114. bCover ? pIdx->zName : ""
  104115. );
  104116. sqlite3VdbeAddOp4(
  104117. pParse->pVdbe, OP_Explain, pParse->iSelectId, 0, 0, zEqp, P4_DYNAMIC
  104118. );
  104119. }
  104120. }
  104121. #else
  104122. # define explainSimpleCount(a,b,c)
  104123. #endif
  104124. /*
  104125. ** Generate code for the SELECT statement given in the p argument.
  104126. **
  104127. ** The results are returned according to the SelectDest structure.
  104128. ** See comments in sqliteInt.h for further information.
  104129. **
  104130. ** This routine returns the number of errors. If any errors are
  104131. ** encountered, then an appropriate error message is left in
  104132. ** pParse->zErrMsg.
  104133. **
  104134. ** This routine does NOT free the Select structure passed in. The
  104135. ** calling function needs to do that.
  104136. */
  104137. SQLITE_PRIVATE int sqlite3Select(
  104138. Parse *pParse, /* The parser context */
  104139. Select *p, /* The SELECT statement being coded. */
  104140. SelectDest *pDest /* What to do with the query results */
  104141. ){
  104142. int i, j; /* Loop counters */
  104143. WhereInfo *pWInfo; /* Return from sqlite3WhereBegin() */
  104144. Vdbe *v; /* The virtual machine under construction */
  104145. int isAgg; /* True for select lists like "count(*)" */
  104146. ExprList *pEList; /* List of columns to extract. */
  104147. SrcList *pTabList; /* List of tables to select from */
  104148. Expr *pWhere; /* The WHERE clause. May be NULL */
  104149. ExprList *pGroupBy; /* The GROUP BY clause. May be NULL */
  104150. Expr *pHaving; /* The HAVING clause. May be NULL */
  104151. int rc = 1; /* Value to return from this function */
  104152. DistinctCtx sDistinct; /* Info on how to code the DISTINCT keyword */
  104153. SortCtx sSort; /* Info on how to code the ORDER BY clause */
  104154. AggInfo sAggInfo; /* Information used by aggregate queries */
  104155. int iEnd; /* Address of the end of the query */
  104156. sqlite3 *db; /* The database connection */
  104157. #ifndef SQLITE_OMIT_EXPLAIN
  104158. int iRestoreSelectId = pParse->iSelectId;
  104159. pParse->iSelectId = pParse->iNextSelectId++;
  104160. #endif
  104161. db = pParse->db;
  104162. if( p==0 || db->mallocFailed || pParse->nErr ){
  104163. return 1;
  104164. }
  104165. if( sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0) ) return 1;
  104166. memset(&sAggInfo, 0, sizeof(sAggInfo));
  104167. #if SELECTTRACE_ENABLED
  104168. pParse->nSelectIndent++;
  104169. SELECTTRACE(1,pParse,p, ("begin processing:\n"));
  104170. if( sqlite3SelectTrace & 0x100 ){
  104171. sqlite3TreeViewSelect(0, p, 0);
  104172. }
  104173. #endif
  104174. assert( p->pOrderBy==0 || pDest->eDest!=SRT_DistFifo );
  104175. assert( p->pOrderBy==0 || pDest->eDest!=SRT_Fifo );
  104176. assert( p->pOrderBy==0 || pDest->eDest!=SRT_DistQueue );
  104177. assert( p->pOrderBy==0 || pDest->eDest!=SRT_Queue );
  104178. if( IgnorableOrderby(pDest) ){
  104179. assert(pDest->eDest==SRT_Exists || pDest->eDest==SRT_Union ||
  104180. pDest->eDest==SRT_Except || pDest->eDest==SRT_Discard ||
  104181. pDest->eDest==SRT_Queue || pDest->eDest==SRT_DistFifo ||
  104182. pDest->eDest==SRT_DistQueue || pDest->eDest==SRT_Fifo);
  104183. /* If ORDER BY makes no difference in the output then neither does
  104184. ** DISTINCT so it can be removed too. */
  104185. sqlite3ExprListDelete(db, p->pOrderBy);
  104186. p->pOrderBy = 0;
  104187. p->selFlags &= ~SF_Distinct;
  104188. }
  104189. sqlite3SelectPrep(pParse, p, 0);
  104190. memset(&sSort, 0, sizeof(sSort));
  104191. sSort.pOrderBy = p->pOrderBy;
  104192. pTabList = p->pSrc;
  104193. pEList = p->pEList;
  104194. if( pParse->nErr || db->mallocFailed ){
  104195. goto select_end;
  104196. }
  104197. isAgg = (p->selFlags & SF_Aggregate)!=0;
  104198. assert( pEList!=0 );
  104199. #if SELECTTRACE_ENABLED
  104200. if( sqlite3SelectTrace & 0x100 ){
  104201. SELECTTRACE(0x100,pParse,p, ("after name resolution:\n"));
  104202. sqlite3TreeViewSelect(0, p, 0);
  104203. }
  104204. #endif
  104205. /* Begin generating code.
  104206. */
  104207. v = sqlite3GetVdbe(pParse);
  104208. if( v==0 ) goto select_end;
  104209. /* If writing to memory or generating a set
  104210. ** only a single column may be output.
  104211. */
  104212. #ifndef SQLITE_OMIT_SUBQUERY
  104213. if( checkForMultiColumnSelectError(pParse, pDest, pEList->nExpr) ){
  104214. goto select_end;
  104215. }
  104216. #endif
  104217. /* Generate code for all sub-queries in the FROM clause
  104218. */
  104219. #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
  104220. for(i=0; !p->pPrior && i<pTabList->nSrc; i++){
  104221. struct SrcList_item *pItem = &pTabList->a[i];
  104222. SelectDest dest;
  104223. Select *pSub = pItem->pSelect;
  104224. int isAggSub;
  104225. if( pSub==0 ) continue;
  104226. /* Sometimes the code for a subquery will be generated more than
  104227. ** once, if the subquery is part of the WHERE clause in a LEFT JOIN,
  104228. ** for example. In that case, do not regenerate the code to manifest
  104229. ** a view or the co-routine to implement a view. The first instance
  104230. ** is sufficient, though the subroutine to manifest the view does need
  104231. ** to be invoked again. */
  104232. if( pItem->addrFillSub ){
  104233. if( pItem->viaCoroutine==0 ){
  104234. sqlite3VdbeAddOp2(v, OP_Gosub, pItem->regReturn, pItem->addrFillSub);
  104235. }
  104236. continue;
  104237. }
  104238. /* Increment Parse.nHeight by the height of the largest expression
  104239. ** tree referred to by this, the parent select. The child select
  104240. ** may contain expression trees of at most
  104241. ** (SQLITE_MAX_EXPR_DEPTH-Parse.nHeight) height. This is a bit
  104242. ** more conservative than necessary, but much easier than enforcing
  104243. ** an exact limit.
  104244. */
  104245. pParse->nHeight += sqlite3SelectExprHeight(p);
  104246. isAggSub = (pSub->selFlags & SF_Aggregate)!=0;
  104247. if( flattenSubquery(pParse, p, i, isAgg, isAggSub) ){
  104248. /* This subquery can be absorbed into its parent. */
  104249. if( isAggSub ){
  104250. isAgg = 1;
  104251. p->selFlags |= SF_Aggregate;
  104252. }
  104253. i = -1;
  104254. }else if( pTabList->nSrc==1
  104255. && OptimizationEnabled(db, SQLITE_SubqCoroutine)
  104256. ){
  104257. /* Implement a co-routine that will return a single row of the result
  104258. ** set on each invocation.
  104259. */
  104260. int addrTop = sqlite3VdbeCurrentAddr(v)+1;
  104261. pItem->regReturn = ++pParse->nMem;
  104262. sqlite3VdbeAddOp3(v, OP_InitCoroutine, pItem->regReturn, 0, addrTop);
  104263. VdbeComment((v, "%s", pItem->pTab->zName));
  104264. pItem->addrFillSub = addrTop;
  104265. sqlite3SelectDestInit(&dest, SRT_Coroutine, pItem->regReturn);
  104266. explainSetInteger(pItem->iSelectId, (u8)pParse->iNextSelectId);
  104267. sqlite3Select(pParse, pSub, &dest);
  104268. pItem->pTab->nRowLogEst = sqlite3LogEst(pSub->nSelectRow);
  104269. pItem->viaCoroutine = 1;
  104270. pItem->regResult = dest.iSdst;
  104271. sqlite3VdbeAddOp1(v, OP_EndCoroutine, pItem->regReturn);
  104272. sqlite3VdbeJumpHere(v, addrTop-1);
  104273. sqlite3ClearTempRegCache(pParse);
  104274. }else{
  104275. /* Generate a subroutine that will fill an ephemeral table with
  104276. ** the content of this subquery. pItem->addrFillSub will point
  104277. ** to the address of the generated subroutine. pItem->regReturn
  104278. ** is a register allocated to hold the subroutine return address
  104279. */
  104280. int topAddr;
  104281. int onceAddr = 0;
  104282. int retAddr;
  104283. assert( pItem->addrFillSub==0 );
  104284. pItem->regReturn = ++pParse->nMem;
  104285. topAddr = sqlite3VdbeAddOp2(v, OP_Integer, 0, pItem->regReturn);
  104286. pItem->addrFillSub = topAddr+1;
  104287. if( pItem->isCorrelated==0 ){
  104288. /* If the subquery is not correlated and if we are not inside of
  104289. ** a trigger, then we only need to compute the value of the subquery
  104290. ** once. */
  104291. onceAddr = sqlite3CodeOnce(pParse); VdbeCoverage(v);
  104292. VdbeComment((v, "materialize \"%s\"", pItem->pTab->zName));
  104293. }else{
  104294. VdbeNoopComment((v, "materialize \"%s\"", pItem->pTab->zName));
  104295. }
  104296. sqlite3SelectDestInit(&dest, SRT_EphemTab, pItem->iCursor);
  104297. explainSetInteger(pItem->iSelectId, (u8)pParse->iNextSelectId);
  104298. sqlite3Select(pParse, pSub, &dest);
  104299. pItem->pTab->nRowLogEst = sqlite3LogEst(pSub->nSelectRow);
  104300. if( onceAddr ) sqlite3VdbeJumpHere(v, onceAddr);
  104301. retAddr = sqlite3VdbeAddOp1(v, OP_Return, pItem->regReturn);
  104302. VdbeComment((v, "end %s", pItem->pTab->zName));
  104303. sqlite3VdbeChangeP1(v, topAddr, retAddr);
  104304. sqlite3ClearTempRegCache(pParse);
  104305. }
  104306. if( /*pParse->nErr ||*/ db->mallocFailed ){
  104307. goto select_end;
  104308. }
  104309. pParse->nHeight -= sqlite3SelectExprHeight(p);
  104310. pTabList = p->pSrc;
  104311. if( !IgnorableOrderby(pDest) ){
  104312. sSort.pOrderBy = p->pOrderBy;
  104313. }
  104314. }
  104315. pEList = p->pEList;
  104316. #endif
  104317. pWhere = p->pWhere;
  104318. pGroupBy = p->pGroupBy;
  104319. pHaving = p->pHaving;
  104320. sDistinct.isTnct = (p->selFlags & SF_Distinct)!=0;
  104321. #ifndef SQLITE_OMIT_COMPOUND_SELECT
  104322. /* If there is are a sequence of queries, do the earlier ones first.
  104323. */
  104324. if( p->pPrior ){
  104325. rc = multiSelect(pParse, p, pDest);
  104326. explainSetInteger(pParse->iSelectId, iRestoreSelectId);
  104327. #if SELECTTRACE_ENABLED
  104328. SELECTTRACE(1,pParse,p,("end compound-select processing\n"));
  104329. pParse->nSelectIndent--;
  104330. #endif
  104331. return rc;
  104332. }
  104333. #endif
  104334. /* If the query is DISTINCT with an ORDER BY but is not an aggregate, and
  104335. ** if the select-list is the same as the ORDER BY list, then this query
  104336. ** can be rewritten as a GROUP BY. In other words, this:
  104337. **
  104338. ** SELECT DISTINCT xyz FROM ... ORDER BY xyz
  104339. **
  104340. ** is transformed to:
  104341. **
  104342. ** SELECT xyz FROM ... GROUP BY xyz ORDER BY xyz
  104343. **
  104344. ** The second form is preferred as a single index (or temp-table) may be
  104345. ** used for both the ORDER BY and DISTINCT processing. As originally
  104346. ** written the query must use a temp-table for at least one of the ORDER
  104347. ** BY and DISTINCT, and an index or separate temp-table for the other.
  104348. */
  104349. if( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct
  104350. && sqlite3ExprListCompare(sSort.pOrderBy, p->pEList, -1)==0
  104351. ){
  104352. p->selFlags &= ~SF_Distinct;
  104353. p->pGroupBy = sqlite3ExprListDup(db, p->pEList, 0);
  104354. pGroupBy = p->pGroupBy;
  104355. /* Notice that even thought SF_Distinct has been cleared from p->selFlags,
  104356. ** the sDistinct.isTnct is still set. Hence, isTnct represents the
  104357. ** original setting of the SF_Distinct flag, not the current setting */
  104358. assert( sDistinct.isTnct );
  104359. }
  104360. /* If there is an ORDER BY clause, then this sorting
  104361. ** index might end up being unused if the data can be
  104362. ** extracted in pre-sorted order. If that is the case, then the
  104363. ** OP_OpenEphemeral instruction will be changed to an OP_Noop once
  104364. ** we figure out that the sorting index is not needed. The addrSortIndex
  104365. ** variable is used to facilitate that change.
  104366. */
  104367. if( sSort.pOrderBy ){
  104368. KeyInfo *pKeyInfo;
  104369. pKeyInfo = keyInfoFromExprList(pParse, sSort.pOrderBy, 0, pEList->nExpr);
  104370. sSort.iECursor = pParse->nTab++;
  104371. sSort.addrSortIndex =
  104372. sqlite3VdbeAddOp4(v, OP_OpenEphemeral,
  104373. sSort.iECursor, sSort.pOrderBy->nExpr+1+pEList->nExpr, 0,
  104374. (char*)pKeyInfo, P4_KEYINFO
  104375. );
  104376. }else{
  104377. sSort.addrSortIndex = -1;
  104378. }
  104379. /* If the output is destined for a temporary table, open that table.
  104380. */
  104381. if( pDest->eDest==SRT_EphemTab ){
  104382. sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pDest->iSDParm, pEList->nExpr);
  104383. }
  104384. /* Set the limiter.
  104385. */
  104386. iEnd = sqlite3VdbeMakeLabel(v);
  104387. p->nSelectRow = LARGEST_INT64;
  104388. computeLimitRegisters(pParse, p, iEnd);
  104389. if( p->iLimit==0 && sSort.addrSortIndex>=0 ){
  104390. sqlite3VdbeGetOp(v, sSort.addrSortIndex)->opcode = OP_SorterOpen;
  104391. sSort.sortFlags |= SORTFLAG_UseSorter;
  104392. }
  104393. /* Open a virtual index to use for the distinct set.
  104394. */
  104395. if( p->selFlags & SF_Distinct ){
  104396. sDistinct.tabTnct = pParse->nTab++;
  104397. sDistinct.addrTnct = sqlite3VdbeAddOp4(v, OP_OpenEphemeral,
  104398. sDistinct.tabTnct, 0, 0,
  104399. (char*)keyInfoFromExprList(pParse, p->pEList,0,0),
  104400. P4_KEYINFO);
  104401. sqlite3VdbeChangeP5(v, BTREE_UNORDERED);
  104402. sDistinct.eTnctType = WHERE_DISTINCT_UNORDERED;
  104403. }else{
  104404. sDistinct.eTnctType = WHERE_DISTINCT_NOOP;
  104405. }
  104406. if( !isAgg && pGroupBy==0 ){
  104407. /* No aggregate functions and no GROUP BY clause */
  104408. u16 wctrlFlags = (sDistinct.isTnct ? WHERE_WANT_DISTINCT : 0);
  104409. /* Begin the database scan. */
  104410. pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, sSort.pOrderBy,
  104411. p->pEList, wctrlFlags, 0);
  104412. if( pWInfo==0 ) goto select_end;
  104413. if( sqlite3WhereOutputRowCount(pWInfo) < p->nSelectRow ){
  104414. p->nSelectRow = sqlite3WhereOutputRowCount(pWInfo);
  104415. }
  104416. if( sDistinct.isTnct && sqlite3WhereIsDistinct(pWInfo) ){
  104417. sDistinct.eTnctType = sqlite3WhereIsDistinct(pWInfo);
  104418. }
  104419. if( sSort.pOrderBy ){
  104420. sSort.nOBSat = sqlite3WhereIsOrdered(pWInfo);
  104421. if( sSort.nOBSat==sSort.pOrderBy->nExpr ){
  104422. sSort.pOrderBy = 0;
  104423. }
  104424. }
  104425. /* If sorting index that was created by a prior OP_OpenEphemeral
  104426. ** instruction ended up not being needed, then change the OP_OpenEphemeral
  104427. ** into an OP_Noop.
  104428. */
  104429. if( sSort.addrSortIndex>=0 && sSort.pOrderBy==0 ){
  104430. sqlite3VdbeChangeToNoop(v, sSort.addrSortIndex);
  104431. }
  104432. /* Use the standard inner loop. */
  104433. selectInnerLoop(pParse, p, pEList, -1, &sSort, &sDistinct, pDest,
  104434. sqlite3WhereContinueLabel(pWInfo),
  104435. sqlite3WhereBreakLabel(pWInfo));
  104436. /* End the database scan loop.
  104437. */
  104438. sqlite3WhereEnd(pWInfo);
  104439. }else{
  104440. /* This case when there exist aggregate functions or a GROUP BY clause
  104441. ** or both */
  104442. NameContext sNC; /* Name context for processing aggregate information */
  104443. int iAMem; /* First Mem address for storing current GROUP BY */
  104444. int iBMem; /* First Mem address for previous GROUP BY */
  104445. int iUseFlag; /* Mem address holding flag indicating that at least
  104446. ** one row of the input to the aggregator has been
  104447. ** processed */
  104448. int iAbortFlag; /* Mem address which causes query abort if positive */
  104449. int groupBySort; /* Rows come from source in GROUP BY order */
  104450. int addrEnd; /* End of processing for this SELECT */
  104451. int sortPTab = 0; /* Pseudotable used to decode sorting results */
  104452. int sortOut = 0; /* Output register from the sorter */
  104453. int orderByGrp = 0; /* True if the GROUP BY and ORDER BY are the same */
  104454. /* Remove any and all aliases between the result set and the
  104455. ** GROUP BY clause.
  104456. */
  104457. if( pGroupBy ){
  104458. int k; /* Loop counter */
  104459. struct ExprList_item *pItem; /* For looping over expression in a list */
  104460. for(k=p->pEList->nExpr, pItem=p->pEList->a; k>0; k--, pItem++){
  104461. pItem->u.x.iAlias = 0;
  104462. }
  104463. for(k=pGroupBy->nExpr, pItem=pGroupBy->a; k>0; k--, pItem++){
  104464. pItem->u.x.iAlias = 0;
  104465. }
  104466. if( p->nSelectRow>100 ) p->nSelectRow = 100;
  104467. }else{
  104468. p->nSelectRow = 1;
  104469. }
  104470. /* If there is both a GROUP BY and an ORDER BY clause and they are
  104471. ** identical, then it may be possible to disable the ORDER BY clause
  104472. ** on the grounds that the GROUP BY will cause elements to come out
  104473. ** in the correct order. It also may not - the GROUP BY may use a
  104474. ** database index that causes rows to be grouped together as required
  104475. ** but not actually sorted. Either way, record the fact that the
  104476. ** ORDER BY and GROUP BY clauses are the same by setting the orderByGrp
  104477. ** variable. */
  104478. if( sqlite3ExprListCompare(pGroupBy, sSort.pOrderBy, -1)==0 ){
  104479. orderByGrp = 1;
  104480. }
  104481. /* Create a label to jump to when we want to abort the query */
  104482. addrEnd = sqlite3VdbeMakeLabel(v);
  104483. /* Convert TK_COLUMN nodes into TK_AGG_COLUMN and make entries in
  104484. ** sAggInfo for all TK_AGG_FUNCTION nodes in expressions of the
  104485. ** SELECT statement.
  104486. */
  104487. memset(&sNC, 0, sizeof(sNC));
  104488. sNC.pParse = pParse;
  104489. sNC.pSrcList = pTabList;
  104490. sNC.pAggInfo = &sAggInfo;
  104491. sAggInfo.mnReg = pParse->nMem+1;
  104492. sAggInfo.nSortingColumn = pGroupBy ? pGroupBy->nExpr : 0;
  104493. sAggInfo.pGroupBy = pGroupBy;
  104494. sqlite3ExprAnalyzeAggList(&sNC, pEList);
  104495. sqlite3ExprAnalyzeAggList(&sNC, sSort.pOrderBy);
  104496. if( pHaving ){
  104497. sqlite3ExprAnalyzeAggregates(&sNC, pHaving);
  104498. }
  104499. sAggInfo.nAccumulator = sAggInfo.nColumn;
  104500. for(i=0; i<sAggInfo.nFunc; i++){
  104501. assert( !ExprHasProperty(sAggInfo.aFunc[i].pExpr, EP_xIsSelect) );
  104502. sNC.ncFlags |= NC_InAggFunc;
  104503. sqlite3ExprAnalyzeAggList(&sNC, sAggInfo.aFunc[i].pExpr->x.pList);
  104504. sNC.ncFlags &= ~NC_InAggFunc;
  104505. }
  104506. sAggInfo.mxReg = pParse->nMem;
  104507. if( db->mallocFailed ) goto select_end;
  104508. /* Processing for aggregates with GROUP BY is very different and
  104509. ** much more complex than aggregates without a GROUP BY.
  104510. */
  104511. if( pGroupBy ){
  104512. KeyInfo *pKeyInfo; /* Keying information for the group by clause */
  104513. int j1; /* A-vs-B comparision jump */
  104514. int addrOutputRow; /* Start of subroutine that outputs a result row */
  104515. int regOutputRow; /* Return address register for output subroutine */
  104516. int addrSetAbort; /* Set the abort flag and return */
  104517. int addrTopOfLoop; /* Top of the input loop */
  104518. int addrSortingIdx; /* The OP_OpenEphemeral for the sorting index */
  104519. int addrReset; /* Subroutine for resetting the accumulator */
  104520. int regReset; /* Return address register for reset subroutine */
  104521. /* If there is a GROUP BY clause we might need a sorting index to
  104522. ** implement it. Allocate that sorting index now. If it turns out
  104523. ** that we do not need it after all, the OP_SorterOpen instruction
  104524. ** will be converted into a Noop.
  104525. */
  104526. sAggInfo.sortingIdx = pParse->nTab++;
  104527. pKeyInfo = keyInfoFromExprList(pParse, pGroupBy, 0, sAggInfo.nColumn);
  104528. addrSortingIdx = sqlite3VdbeAddOp4(v, OP_SorterOpen,
  104529. sAggInfo.sortingIdx, sAggInfo.nSortingColumn,
  104530. 0, (char*)pKeyInfo, P4_KEYINFO);
  104531. /* Initialize memory locations used by GROUP BY aggregate processing
  104532. */
  104533. iUseFlag = ++pParse->nMem;
  104534. iAbortFlag = ++pParse->nMem;
  104535. regOutputRow = ++pParse->nMem;
  104536. addrOutputRow = sqlite3VdbeMakeLabel(v);
  104537. regReset = ++pParse->nMem;
  104538. addrReset = sqlite3VdbeMakeLabel(v);
  104539. iAMem = pParse->nMem + 1;
  104540. pParse->nMem += pGroupBy->nExpr;
  104541. iBMem = pParse->nMem + 1;
  104542. pParse->nMem += pGroupBy->nExpr;
  104543. sqlite3VdbeAddOp2(v, OP_Integer, 0, iAbortFlag);
  104544. VdbeComment((v, "clear abort flag"));
  104545. sqlite3VdbeAddOp2(v, OP_Integer, 0, iUseFlag);
  104546. VdbeComment((v, "indicate accumulator empty"));
  104547. sqlite3VdbeAddOp3(v, OP_Null, 0, iAMem, iAMem+pGroupBy->nExpr-1);
  104548. /* Begin a loop that will extract all source rows in GROUP BY order.
  104549. ** This might involve two separate loops with an OP_Sort in between, or
  104550. ** it might be a single loop that uses an index to extract information
  104551. ** in the right order to begin with.
  104552. */
  104553. sqlite3VdbeAddOp2(v, OP_Gosub, regReset, addrReset);
  104554. pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, pGroupBy, 0,
  104555. WHERE_GROUPBY | (orderByGrp ? WHERE_SORTBYGROUP : 0), 0
  104556. );
  104557. if( pWInfo==0 ) goto select_end;
  104558. if( sqlite3WhereIsOrdered(pWInfo)==pGroupBy->nExpr ){
  104559. /* The optimizer is able to deliver rows in group by order so
  104560. ** we do not have to sort. The OP_OpenEphemeral table will be
  104561. ** cancelled later because we still need to use the pKeyInfo
  104562. */
  104563. groupBySort = 0;
  104564. }else{
  104565. /* Rows are coming out in undetermined order. We have to push
  104566. ** each row into a sorting index, terminate the first loop,
  104567. ** then loop over the sorting index in order to get the output
  104568. ** in sorted order
  104569. */
  104570. int regBase;
  104571. int regRecord;
  104572. int nCol;
  104573. int nGroupBy;
  104574. explainTempTable(pParse,
  104575. (sDistinct.isTnct && (p->selFlags&SF_Distinct)==0) ?
  104576. "DISTINCT" : "GROUP BY");
  104577. groupBySort = 1;
  104578. nGroupBy = pGroupBy->nExpr;
  104579. nCol = nGroupBy;
  104580. j = nGroupBy;
  104581. for(i=0; i<sAggInfo.nColumn; i++){
  104582. if( sAggInfo.aCol[i].iSorterColumn>=j ){
  104583. nCol++;
  104584. j++;
  104585. }
  104586. }
  104587. regBase = sqlite3GetTempRange(pParse, nCol);
  104588. sqlite3ExprCacheClear(pParse);
  104589. sqlite3ExprCodeExprList(pParse, pGroupBy, regBase, 0);
  104590. j = nGroupBy;
  104591. for(i=0; i<sAggInfo.nColumn; i++){
  104592. struct AggInfo_col *pCol = &sAggInfo.aCol[i];
  104593. if( pCol->iSorterColumn>=j ){
  104594. int r1 = j + regBase;
  104595. int r2;
  104596. r2 = sqlite3ExprCodeGetColumn(pParse,
  104597. pCol->pTab, pCol->iColumn, pCol->iTable, r1, 0);
  104598. if( r1!=r2 ){
  104599. sqlite3VdbeAddOp2(v, OP_SCopy, r2, r1);
  104600. }
  104601. j++;
  104602. }
  104603. }
  104604. regRecord = sqlite3GetTempReg(pParse);
  104605. sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nCol, regRecord);
  104606. sqlite3VdbeAddOp2(v, OP_SorterInsert, sAggInfo.sortingIdx, regRecord);
  104607. sqlite3ReleaseTempReg(pParse, regRecord);
  104608. sqlite3ReleaseTempRange(pParse, regBase, nCol);
  104609. sqlite3WhereEnd(pWInfo);
  104610. sAggInfo.sortingIdxPTab = sortPTab = pParse->nTab++;
  104611. sortOut = sqlite3GetTempReg(pParse);
  104612. sqlite3VdbeAddOp3(v, OP_OpenPseudo, sortPTab, sortOut, nCol);
  104613. sqlite3VdbeAddOp2(v, OP_SorterSort, sAggInfo.sortingIdx, addrEnd);
  104614. VdbeComment((v, "GROUP BY sort")); VdbeCoverage(v);
  104615. sAggInfo.useSortingIdx = 1;
  104616. sqlite3ExprCacheClear(pParse);
  104617. }
  104618. /* If the index or temporary table used by the GROUP BY sort
  104619. ** will naturally deliver rows in the order required by the ORDER BY
  104620. ** clause, cancel the ephemeral table open coded earlier.
  104621. **
  104622. ** This is an optimization - the correct answer should result regardless.
  104623. ** Use the SQLITE_GroupByOrder flag with SQLITE_TESTCTRL_OPTIMIZER to
  104624. ** disable this optimization for testing purposes. */
  104625. if( orderByGrp && OptimizationEnabled(db, SQLITE_GroupByOrder)
  104626. && (groupBySort || sqlite3WhereIsSorted(pWInfo))
  104627. ){
  104628. sSort.pOrderBy = 0;
  104629. sqlite3VdbeChangeToNoop(v, sSort.addrSortIndex);
  104630. }
  104631. /* Evaluate the current GROUP BY terms and store in b0, b1, b2...
  104632. ** (b0 is memory location iBMem+0, b1 is iBMem+1, and so forth)
  104633. ** Then compare the current GROUP BY terms against the GROUP BY terms
  104634. ** from the previous row currently stored in a0, a1, a2...
  104635. */
  104636. addrTopOfLoop = sqlite3VdbeCurrentAddr(v);
  104637. sqlite3ExprCacheClear(pParse);
  104638. if( groupBySort ){
  104639. sqlite3VdbeAddOp3(v, OP_SorterData, sAggInfo.sortingIdx, sortOut,sortPTab);
  104640. }
  104641. for(j=0; j<pGroupBy->nExpr; j++){
  104642. if( groupBySort ){
  104643. sqlite3VdbeAddOp3(v, OP_Column, sortPTab, j, iBMem+j);
  104644. }else{
  104645. sAggInfo.directMode = 1;
  104646. sqlite3ExprCode(pParse, pGroupBy->a[j].pExpr, iBMem+j);
  104647. }
  104648. }
  104649. sqlite3VdbeAddOp4(v, OP_Compare, iAMem, iBMem, pGroupBy->nExpr,
  104650. (char*)sqlite3KeyInfoRef(pKeyInfo), P4_KEYINFO);
  104651. j1 = sqlite3VdbeCurrentAddr(v);
  104652. sqlite3VdbeAddOp3(v, OP_Jump, j1+1, 0, j1+1); VdbeCoverage(v);
  104653. /* Generate code that runs whenever the GROUP BY changes.
  104654. ** Changes in the GROUP BY are detected by the previous code
  104655. ** block. If there were no changes, this block is skipped.
  104656. **
  104657. ** This code copies current group by terms in b0,b1,b2,...
  104658. ** over to a0,a1,a2. It then calls the output subroutine
  104659. ** and resets the aggregate accumulator registers in preparation
  104660. ** for the next GROUP BY batch.
  104661. */
  104662. sqlite3ExprCodeMove(pParse, iBMem, iAMem, pGroupBy->nExpr);
  104663. sqlite3VdbeAddOp2(v, OP_Gosub, regOutputRow, addrOutputRow);
  104664. VdbeComment((v, "output one row"));
  104665. sqlite3VdbeAddOp2(v, OP_IfPos, iAbortFlag, addrEnd); VdbeCoverage(v);
  104666. VdbeComment((v, "check abort flag"));
  104667. sqlite3VdbeAddOp2(v, OP_Gosub, regReset, addrReset);
  104668. VdbeComment((v, "reset accumulator"));
  104669. /* Update the aggregate accumulators based on the content of
  104670. ** the current row
  104671. */
  104672. sqlite3VdbeJumpHere(v, j1);
  104673. updateAccumulator(pParse, &sAggInfo);
  104674. sqlite3VdbeAddOp2(v, OP_Integer, 1, iUseFlag);
  104675. VdbeComment((v, "indicate data in accumulator"));
  104676. /* End of the loop
  104677. */
  104678. if( groupBySort ){
  104679. sqlite3VdbeAddOp2(v, OP_SorterNext, sAggInfo.sortingIdx, addrTopOfLoop);
  104680. VdbeCoverage(v);
  104681. }else{
  104682. sqlite3WhereEnd(pWInfo);
  104683. sqlite3VdbeChangeToNoop(v, addrSortingIdx);
  104684. }
  104685. /* Output the final row of result
  104686. */
  104687. sqlite3VdbeAddOp2(v, OP_Gosub, regOutputRow, addrOutputRow);
  104688. VdbeComment((v, "output final row"));
  104689. /* Jump over the subroutines
  104690. */
  104691. sqlite3VdbeAddOp2(v, OP_Goto, 0, addrEnd);
  104692. /* Generate a subroutine that outputs a single row of the result
  104693. ** set. This subroutine first looks at the iUseFlag. If iUseFlag
  104694. ** is less than or equal to zero, the subroutine is a no-op. If
  104695. ** the processing calls for the query to abort, this subroutine
  104696. ** increments the iAbortFlag memory location before returning in
  104697. ** order to signal the caller to abort.
  104698. */
  104699. addrSetAbort = sqlite3VdbeCurrentAddr(v);
  104700. sqlite3VdbeAddOp2(v, OP_Integer, 1, iAbortFlag);
  104701. VdbeComment((v, "set abort flag"));
  104702. sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
  104703. sqlite3VdbeResolveLabel(v, addrOutputRow);
  104704. addrOutputRow = sqlite3VdbeCurrentAddr(v);
  104705. sqlite3VdbeAddOp2(v, OP_IfPos, iUseFlag, addrOutputRow+2); VdbeCoverage(v);
  104706. VdbeComment((v, "Groupby result generator entry point"));
  104707. sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
  104708. finalizeAggFunctions(pParse, &sAggInfo);
  104709. sqlite3ExprIfFalse(pParse, pHaving, addrOutputRow+1, SQLITE_JUMPIFNULL);
  104710. selectInnerLoop(pParse, p, p->pEList, -1, &sSort,
  104711. &sDistinct, pDest,
  104712. addrOutputRow+1, addrSetAbort);
  104713. sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
  104714. VdbeComment((v, "end groupby result generator"));
  104715. /* Generate a subroutine that will reset the group-by accumulator
  104716. */
  104717. sqlite3VdbeResolveLabel(v, addrReset);
  104718. resetAccumulator(pParse, &sAggInfo);
  104719. sqlite3VdbeAddOp1(v, OP_Return, regReset);
  104720. } /* endif pGroupBy. Begin aggregate queries without GROUP BY: */
  104721. else {
  104722. ExprList *pDel = 0;
  104723. #ifndef SQLITE_OMIT_BTREECOUNT
  104724. Table *pTab;
  104725. if( (pTab = isSimpleCount(p, &sAggInfo))!=0 ){
  104726. /* If isSimpleCount() returns a pointer to a Table structure, then
  104727. ** the SQL statement is of the form:
  104728. **
  104729. ** SELECT count(*) FROM <tbl>
  104730. **
  104731. ** where the Table structure returned represents table <tbl>.
  104732. **
  104733. ** This statement is so common that it is optimized specially. The
  104734. ** OP_Count instruction is executed either on the intkey table that
  104735. ** contains the data for table <tbl> or on one of its indexes. It
  104736. ** is better to execute the op on an index, as indexes are almost
  104737. ** always spread across less pages than their corresponding tables.
  104738. */
  104739. const int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
  104740. const int iCsr = pParse->nTab++; /* Cursor to scan b-tree */
  104741. Index *pIdx; /* Iterator variable */
  104742. KeyInfo *pKeyInfo = 0; /* Keyinfo for scanned index */
  104743. Index *pBest = 0; /* Best index found so far */
  104744. int iRoot = pTab->tnum; /* Root page of scanned b-tree */
  104745. sqlite3CodeVerifySchema(pParse, iDb);
  104746. sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
  104747. /* Search for the index that has the lowest scan cost.
  104748. **
  104749. ** (2011-04-15) Do not do a full scan of an unordered index.
  104750. **
  104751. ** (2013-10-03) Do not count the entries in a partial index.
  104752. **
  104753. ** In practice the KeyInfo structure will not be used. It is only
  104754. ** passed to keep OP_OpenRead happy.
  104755. */
  104756. if( !HasRowid(pTab) ) pBest = sqlite3PrimaryKeyIndex(pTab);
  104757. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  104758. if( pIdx->bUnordered==0
  104759. && pIdx->szIdxRow<pTab->szTabRow
  104760. && pIdx->pPartIdxWhere==0
  104761. && (!pBest || pIdx->szIdxRow<pBest->szIdxRow)
  104762. ){
  104763. pBest = pIdx;
  104764. }
  104765. }
  104766. if( pBest ){
  104767. iRoot = pBest->tnum;
  104768. pKeyInfo = sqlite3KeyInfoOfIndex(pParse, pBest);
  104769. }
  104770. /* Open a read-only cursor, execute the OP_Count, close the cursor. */
  104771. sqlite3VdbeAddOp4Int(v, OP_OpenRead, iCsr, iRoot, iDb, 1);
  104772. if( pKeyInfo ){
  104773. sqlite3VdbeChangeP4(v, -1, (char *)pKeyInfo, P4_KEYINFO);
  104774. }
  104775. sqlite3VdbeAddOp2(v, OP_Count, iCsr, sAggInfo.aFunc[0].iMem);
  104776. sqlite3VdbeAddOp1(v, OP_Close, iCsr);
  104777. explainSimpleCount(pParse, pTab, pBest);
  104778. }else
  104779. #endif /* SQLITE_OMIT_BTREECOUNT */
  104780. {
  104781. /* Check if the query is of one of the following forms:
  104782. **
  104783. ** SELECT min(x) FROM ...
  104784. ** SELECT max(x) FROM ...
  104785. **
  104786. ** If it is, then ask the code in where.c to attempt to sort results
  104787. ** as if there was an "ORDER ON x" or "ORDER ON x DESC" clause.
  104788. ** If where.c is able to produce results sorted in this order, then
  104789. ** add vdbe code to break out of the processing loop after the
  104790. ** first iteration (since the first iteration of the loop is
  104791. ** guaranteed to operate on the row with the minimum or maximum
  104792. ** value of x, the only row required).
  104793. **
  104794. ** A special flag must be passed to sqlite3WhereBegin() to slightly
  104795. ** modify behavior as follows:
  104796. **
  104797. ** + If the query is a "SELECT min(x)", then the loop coded by
  104798. ** where.c should not iterate over any values with a NULL value
  104799. ** for x.
  104800. **
  104801. ** + The optimizer code in where.c (the thing that decides which
  104802. ** index or indices to use) should place a different priority on
  104803. ** satisfying the 'ORDER BY' clause than it does in other cases.
  104804. ** Refer to code and comments in where.c for details.
  104805. */
  104806. ExprList *pMinMax = 0;
  104807. u8 flag = WHERE_ORDERBY_NORMAL;
  104808. assert( p->pGroupBy==0 );
  104809. assert( flag==0 );
  104810. if( p->pHaving==0 ){
  104811. flag = minMaxQuery(&sAggInfo, &pMinMax);
  104812. }
  104813. assert( flag==0 || (pMinMax!=0 && pMinMax->nExpr==1) );
  104814. if( flag ){
  104815. pMinMax = sqlite3ExprListDup(db, pMinMax, 0);
  104816. pDel = pMinMax;
  104817. if( pMinMax && !db->mallocFailed ){
  104818. pMinMax->a[0].sortOrder = flag!=WHERE_ORDERBY_MIN ?1:0;
  104819. pMinMax->a[0].pExpr->op = TK_COLUMN;
  104820. }
  104821. }
  104822. /* This case runs if the aggregate has no GROUP BY clause. The
  104823. ** processing is much simpler since there is only a single row
  104824. ** of output.
  104825. */
  104826. resetAccumulator(pParse, &sAggInfo);
  104827. pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, pMinMax,0,flag,0);
  104828. if( pWInfo==0 ){
  104829. sqlite3ExprListDelete(db, pDel);
  104830. goto select_end;
  104831. }
  104832. updateAccumulator(pParse, &sAggInfo);
  104833. assert( pMinMax==0 || pMinMax->nExpr==1 );
  104834. if( sqlite3WhereIsOrdered(pWInfo)>0 ){
  104835. sqlite3VdbeAddOp2(v, OP_Goto, 0, sqlite3WhereBreakLabel(pWInfo));
  104836. VdbeComment((v, "%s() by index",
  104837. (flag==WHERE_ORDERBY_MIN?"min":"max")));
  104838. }
  104839. sqlite3WhereEnd(pWInfo);
  104840. finalizeAggFunctions(pParse, &sAggInfo);
  104841. }
  104842. sSort.pOrderBy = 0;
  104843. sqlite3ExprIfFalse(pParse, pHaving, addrEnd, SQLITE_JUMPIFNULL);
  104844. selectInnerLoop(pParse, p, p->pEList, -1, 0, 0,
  104845. pDest, addrEnd, addrEnd);
  104846. sqlite3ExprListDelete(db, pDel);
  104847. }
  104848. sqlite3VdbeResolveLabel(v, addrEnd);
  104849. } /* endif aggregate query */
  104850. if( sDistinct.eTnctType==WHERE_DISTINCT_UNORDERED ){
  104851. explainTempTable(pParse, "DISTINCT");
  104852. }
  104853. /* If there is an ORDER BY clause, then we need to sort the results
  104854. ** and send them to the callback one by one.
  104855. */
  104856. if( sSort.pOrderBy ){
  104857. explainTempTable(pParse, sSort.nOBSat>0 ? "RIGHT PART OF ORDER BY":"ORDER BY");
  104858. generateSortTail(pParse, p, &sSort, pEList->nExpr, pDest);
  104859. }
  104860. /* Jump here to skip this query
  104861. */
  104862. sqlite3VdbeResolveLabel(v, iEnd);
  104863. /* The SELECT has been coded. If there is an error in the Parse structure,
  104864. ** set the return code to 1. Otherwise 0. */
  104865. rc = (pParse->nErr>0);
  104866. /* Control jumps to here if an error is encountered above, or upon
  104867. ** successful coding of the SELECT.
  104868. */
  104869. select_end:
  104870. explainSetInteger(pParse->iSelectId, iRestoreSelectId);
  104871. /* Identify column names if results of the SELECT are to be output.
  104872. */
  104873. if( rc==SQLITE_OK && pDest->eDest==SRT_Output ){
  104874. generateColumnNames(pParse, pTabList, pEList);
  104875. }
  104876. sqlite3DbFree(db, sAggInfo.aCol);
  104877. sqlite3DbFree(db, sAggInfo.aFunc);
  104878. #if SELECTTRACE_ENABLED
  104879. SELECTTRACE(1,pParse,p,("end processing\n"));
  104880. pParse->nSelectIndent--;
  104881. #endif
  104882. return rc;
  104883. }
  104884. #ifdef SQLITE_DEBUG
  104885. /*
  104886. ** Generate a human-readable description of a the Select object.
  104887. */
  104888. SQLITE_PRIVATE void sqlite3TreeViewSelect(TreeView *pView, const Select *p, u8 moreToFollow){
  104889. int n = 0;
  104890. pView = sqlite3TreeViewPush(pView, moreToFollow);
  104891. sqlite3TreeViewLine(pView, "SELECT%s%s (0x%p)",
  104892. ((p->selFlags & SF_Distinct) ? " DISTINCT" : ""),
  104893. ((p->selFlags & SF_Aggregate) ? " agg_flag" : ""), p
  104894. );
  104895. if( p->pSrc && p->pSrc->nSrc ) n++;
  104896. if( p->pWhere ) n++;
  104897. if( p->pGroupBy ) n++;
  104898. if( p->pHaving ) n++;
  104899. if( p->pOrderBy ) n++;
  104900. if( p->pLimit ) n++;
  104901. if( p->pOffset ) n++;
  104902. if( p->pPrior ) n++;
  104903. sqlite3TreeViewExprList(pView, p->pEList, (n--)>0, "result-set");
  104904. if( p->pSrc && p->pSrc->nSrc ){
  104905. int i;
  104906. pView = sqlite3TreeViewPush(pView, (n--)>0);
  104907. sqlite3TreeViewLine(pView, "FROM");
  104908. for(i=0; i<p->pSrc->nSrc; i++){
  104909. struct SrcList_item *pItem = &p->pSrc->a[i];
  104910. StrAccum x;
  104911. char zLine[100];
  104912. sqlite3StrAccumInit(&x, 0, zLine, sizeof(zLine), 0);
  104913. sqlite3XPrintf(&x, 0, "{%d,*}", pItem->iCursor);
  104914. if( pItem->zDatabase ){
  104915. sqlite3XPrintf(&x, 0, " %s.%s", pItem->zDatabase, pItem->zName);
  104916. }else if( pItem->zName ){
  104917. sqlite3XPrintf(&x, 0, " %s", pItem->zName);
  104918. }
  104919. if( pItem->pTab ){
  104920. sqlite3XPrintf(&x, 0, " tabname=%Q", pItem->pTab->zName);
  104921. }
  104922. if( pItem->zAlias ){
  104923. sqlite3XPrintf(&x, 0, " (AS %s)", pItem->zAlias);
  104924. }
  104925. if( pItem->jointype & JT_LEFT ){
  104926. sqlite3XPrintf(&x, 0, " LEFT-JOIN");
  104927. }
  104928. sqlite3StrAccumFinish(&x);
  104929. sqlite3TreeViewItem(pView, zLine, i<p->pSrc->nSrc-1);
  104930. if( pItem->pSelect ){
  104931. sqlite3TreeViewSelect(pView, pItem->pSelect, 0);
  104932. }
  104933. sqlite3TreeViewPop(pView);
  104934. }
  104935. sqlite3TreeViewPop(pView);
  104936. }
  104937. if( p->pWhere ){
  104938. sqlite3TreeViewItem(pView, "WHERE", (n--)>0);
  104939. sqlite3TreeViewExpr(pView, p->pWhere, 0);
  104940. sqlite3TreeViewPop(pView);
  104941. }
  104942. if( p->pGroupBy ){
  104943. sqlite3TreeViewExprList(pView, p->pGroupBy, (n--)>0, "GROUPBY");
  104944. }
  104945. if( p->pHaving ){
  104946. sqlite3TreeViewItem(pView, "HAVING", (n--)>0);
  104947. sqlite3TreeViewExpr(pView, p->pHaving, 0);
  104948. sqlite3TreeViewPop(pView);
  104949. }
  104950. if( p->pOrderBy ){
  104951. sqlite3TreeViewExprList(pView, p->pOrderBy, (n--)>0, "ORDERBY");
  104952. }
  104953. if( p->pLimit ){
  104954. sqlite3TreeViewItem(pView, "LIMIT", (n--)>0);
  104955. sqlite3TreeViewExpr(pView, p->pLimit, 0);
  104956. sqlite3TreeViewPop(pView);
  104957. }
  104958. if( p->pOffset ){
  104959. sqlite3TreeViewItem(pView, "OFFSET", (n--)>0);
  104960. sqlite3TreeViewExpr(pView, p->pOffset, 0);
  104961. sqlite3TreeViewPop(pView);
  104962. }
  104963. if( p->pPrior ){
  104964. const char *zOp = "UNION";
  104965. switch( p->op ){
  104966. case TK_ALL: zOp = "UNION ALL"; break;
  104967. case TK_INTERSECT: zOp = "INTERSECT"; break;
  104968. case TK_EXCEPT: zOp = "EXCEPT"; break;
  104969. }
  104970. sqlite3TreeViewItem(pView, zOp, (n--)>0);
  104971. sqlite3TreeViewSelect(pView, p->pPrior, 0);
  104972. sqlite3TreeViewPop(pView);
  104973. }
  104974. sqlite3TreeViewPop(pView);
  104975. }
  104976. #endif /* SQLITE_DEBUG */
  104977. /************** End of select.c **********************************************/
  104978. /************** Begin file table.c *******************************************/
  104979. /*
  104980. ** 2001 September 15
  104981. **
  104982. ** The author disclaims copyright to this source code. In place of
  104983. ** a legal notice, here is a blessing:
  104984. **
  104985. ** May you do good and not evil.
  104986. ** May you find forgiveness for yourself and forgive others.
  104987. ** May you share freely, never taking more than you give.
  104988. **
  104989. *************************************************************************
  104990. ** This file contains the sqlite3_get_table() and sqlite3_free_table()
  104991. ** interface routines. These are just wrappers around the main
  104992. ** interface routine of sqlite3_exec().
  104993. **
  104994. ** These routines are in a separate files so that they will not be linked
  104995. ** if they are not used.
  104996. */
  104997. /* #include <stdlib.h> */
  104998. /* #include <string.h> */
  104999. #ifndef SQLITE_OMIT_GET_TABLE
  105000. /*
  105001. ** This structure is used to pass data from sqlite3_get_table() through
  105002. ** to the callback function is uses to build the result.
  105003. */
  105004. typedef struct TabResult {
  105005. char **azResult; /* Accumulated output */
  105006. char *zErrMsg; /* Error message text, if an error occurs */
  105007. u32 nAlloc; /* Slots allocated for azResult[] */
  105008. u32 nRow; /* Number of rows in the result */
  105009. u32 nColumn; /* Number of columns in the result */
  105010. u32 nData; /* Slots used in azResult[]. (nRow+1)*nColumn */
  105011. int rc; /* Return code from sqlite3_exec() */
  105012. } TabResult;
  105013. /*
  105014. ** This routine is called once for each row in the result table. Its job
  105015. ** is to fill in the TabResult structure appropriately, allocating new
  105016. ** memory as necessary.
  105017. */
  105018. static int sqlite3_get_table_cb(void *pArg, int nCol, char **argv, char **colv){
  105019. TabResult *p = (TabResult*)pArg; /* Result accumulator */
  105020. int need; /* Slots needed in p->azResult[] */
  105021. int i; /* Loop counter */
  105022. char *z; /* A single column of result */
  105023. /* Make sure there is enough space in p->azResult to hold everything
  105024. ** we need to remember from this invocation of the callback.
  105025. */
  105026. if( p->nRow==0 && argv!=0 ){
  105027. need = nCol*2;
  105028. }else{
  105029. need = nCol;
  105030. }
  105031. if( p->nData + need > p->nAlloc ){
  105032. char **azNew;
  105033. p->nAlloc = p->nAlloc*2 + need;
  105034. azNew = sqlite3_realloc64( p->azResult, sizeof(char*)*p->nAlloc );
  105035. if( azNew==0 ) goto malloc_failed;
  105036. p->azResult = azNew;
  105037. }
  105038. /* If this is the first row, then generate an extra row containing
  105039. ** the names of all columns.
  105040. */
  105041. if( p->nRow==0 ){
  105042. p->nColumn = nCol;
  105043. for(i=0; i<nCol; i++){
  105044. z = sqlite3_mprintf("%s", colv[i]);
  105045. if( z==0 ) goto malloc_failed;
  105046. p->azResult[p->nData++] = z;
  105047. }
  105048. }else if( (int)p->nColumn!=nCol ){
  105049. sqlite3_free(p->zErrMsg);
  105050. p->zErrMsg = sqlite3_mprintf(
  105051. "sqlite3_get_table() called with two or more incompatible queries"
  105052. );
  105053. p->rc = SQLITE_ERROR;
  105054. return 1;
  105055. }
  105056. /* Copy over the row data
  105057. */
  105058. if( argv!=0 ){
  105059. for(i=0; i<nCol; i++){
  105060. if( argv[i]==0 ){
  105061. z = 0;
  105062. }else{
  105063. int n = sqlite3Strlen30(argv[i])+1;
  105064. z = sqlite3_malloc64( n );
  105065. if( z==0 ) goto malloc_failed;
  105066. memcpy(z, argv[i], n);
  105067. }
  105068. p->azResult[p->nData++] = z;
  105069. }
  105070. p->nRow++;
  105071. }
  105072. return 0;
  105073. malloc_failed:
  105074. p->rc = SQLITE_NOMEM;
  105075. return 1;
  105076. }
  105077. /*
  105078. ** Query the database. But instead of invoking a callback for each row,
  105079. ** malloc() for space to hold the result and return the entire results
  105080. ** at the conclusion of the call.
  105081. **
  105082. ** The result that is written to ***pazResult is held in memory obtained
  105083. ** from malloc(). But the caller cannot free this memory directly.
  105084. ** Instead, the entire table should be passed to sqlite3_free_table() when
  105085. ** the calling procedure is finished using it.
  105086. */
  105087. SQLITE_API int SQLITE_STDCALL sqlite3_get_table(
  105088. sqlite3 *db, /* The database on which the SQL executes */
  105089. const char *zSql, /* The SQL to be executed */
  105090. char ***pazResult, /* Write the result table here */
  105091. int *pnRow, /* Write the number of rows in the result here */
  105092. int *pnColumn, /* Write the number of columns of result here */
  105093. char **pzErrMsg /* Write error messages here */
  105094. ){
  105095. int rc;
  105096. TabResult res;
  105097. #ifdef SQLITE_ENABLE_API_ARMOR
  105098. if( !sqlite3SafetyCheckOk(db) || pazResult==0 ) return SQLITE_MISUSE_BKPT;
  105099. #endif
  105100. *pazResult = 0;
  105101. if( pnColumn ) *pnColumn = 0;
  105102. if( pnRow ) *pnRow = 0;
  105103. if( pzErrMsg ) *pzErrMsg = 0;
  105104. res.zErrMsg = 0;
  105105. res.nRow = 0;
  105106. res.nColumn = 0;
  105107. res.nData = 1;
  105108. res.nAlloc = 20;
  105109. res.rc = SQLITE_OK;
  105110. res.azResult = sqlite3_malloc64(sizeof(char*)*res.nAlloc );
  105111. if( res.azResult==0 ){
  105112. db->errCode = SQLITE_NOMEM;
  105113. return SQLITE_NOMEM;
  105114. }
  105115. res.azResult[0] = 0;
  105116. rc = sqlite3_exec(db, zSql, sqlite3_get_table_cb, &res, pzErrMsg);
  105117. assert( sizeof(res.azResult[0])>= sizeof(res.nData) );
  105118. res.azResult[0] = SQLITE_INT_TO_PTR(res.nData);
  105119. if( (rc&0xff)==SQLITE_ABORT ){
  105120. sqlite3_free_table(&res.azResult[1]);
  105121. if( res.zErrMsg ){
  105122. if( pzErrMsg ){
  105123. sqlite3_free(*pzErrMsg);
  105124. *pzErrMsg = sqlite3_mprintf("%s",res.zErrMsg);
  105125. }
  105126. sqlite3_free(res.zErrMsg);
  105127. }
  105128. db->errCode = res.rc; /* Assume 32-bit assignment is atomic */
  105129. return res.rc;
  105130. }
  105131. sqlite3_free(res.zErrMsg);
  105132. if( rc!=SQLITE_OK ){
  105133. sqlite3_free_table(&res.azResult[1]);
  105134. return rc;
  105135. }
  105136. if( res.nAlloc>res.nData ){
  105137. char **azNew;
  105138. azNew = sqlite3_realloc64( res.azResult, sizeof(char*)*res.nData );
  105139. if( azNew==0 ){
  105140. sqlite3_free_table(&res.azResult[1]);
  105141. db->errCode = SQLITE_NOMEM;
  105142. return SQLITE_NOMEM;
  105143. }
  105144. res.azResult = azNew;
  105145. }
  105146. *pazResult = &res.azResult[1];
  105147. if( pnColumn ) *pnColumn = res.nColumn;
  105148. if( pnRow ) *pnRow = res.nRow;
  105149. return rc;
  105150. }
  105151. /*
  105152. ** This routine frees the space the sqlite3_get_table() malloced.
  105153. */
  105154. SQLITE_API void SQLITE_STDCALL sqlite3_free_table(
  105155. char **azResult /* Result returned from sqlite3_get_table() */
  105156. ){
  105157. if( azResult ){
  105158. int i, n;
  105159. azResult--;
  105160. assert( azResult!=0 );
  105161. n = SQLITE_PTR_TO_INT(azResult[0]);
  105162. for(i=1; i<n; i++){ if( azResult[i] ) sqlite3_free(azResult[i]); }
  105163. sqlite3_free(azResult);
  105164. }
  105165. }
  105166. #endif /* SQLITE_OMIT_GET_TABLE */
  105167. /************** End of table.c ***********************************************/
  105168. /************** Begin file trigger.c *****************************************/
  105169. /*
  105170. **
  105171. ** The author disclaims copyright to this source code. In place of
  105172. ** a legal notice, here is a blessing:
  105173. **
  105174. ** May you do good and not evil.
  105175. ** May you find forgiveness for yourself and forgive others.
  105176. ** May you share freely, never taking more than you give.
  105177. **
  105178. *************************************************************************
  105179. ** This file contains the implementation for TRIGGERs
  105180. */
  105181. #ifndef SQLITE_OMIT_TRIGGER
  105182. /*
  105183. ** Delete a linked list of TriggerStep structures.
  105184. */
  105185. SQLITE_PRIVATE void sqlite3DeleteTriggerStep(sqlite3 *db, TriggerStep *pTriggerStep){
  105186. while( pTriggerStep ){
  105187. TriggerStep * pTmp = pTriggerStep;
  105188. pTriggerStep = pTriggerStep->pNext;
  105189. sqlite3ExprDelete(db, pTmp->pWhere);
  105190. sqlite3ExprListDelete(db, pTmp->pExprList);
  105191. sqlite3SelectDelete(db, pTmp->pSelect);
  105192. sqlite3IdListDelete(db, pTmp->pIdList);
  105193. sqlite3DbFree(db, pTmp);
  105194. }
  105195. }
  105196. /*
  105197. ** Given table pTab, return a list of all the triggers attached to
  105198. ** the table. The list is connected by Trigger.pNext pointers.
  105199. **
  105200. ** All of the triggers on pTab that are in the same database as pTab
  105201. ** are already attached to pTab->pTrigger. But there might be additional
  105202. ** triggers on pTab in the TEMP schema. This routine prepends all
  105203. ** TEMP triggers on pTab to the beginning of the pTab->pTrigger list
  105204. ** and returns the combined list.
  105205. **
  105206. ** To state it another way: This routine returns a list of all triggers
  105207. ** that fire off of pTab. The list will include any TEMP triggers on
  105208. ** pTab as well as the triggers lised in pTab->pTrigger.
  105209. */
  105210. SQLITE_PRIVATE Trigger *sqlite3TriggerList(Parse *pParse, Table *pTab){
  105211. Schema * const pTmpSchema = pParse->db->aDb[1].pSchema;
  105212. Trigger *pList = 0; /* List of triggers to return */
  105213. if( pParse->disableTriggers ){
  105214. return 0;
  105215. }
  105216. if( pTmpSchema!=pTab->pSchema ){
  105217. HashElem *p;
  105218. assert( sqlite3SchemaMutexHeld(pParse->db, 0, pTmpSchema) );
  105219. for(p=sqliteHashFirst(&pTmpSchema->trigHash); p; p=sqliteHashNext(p)){
  105220. Trigger *pTrig = (Trigger *)sqliteHashData(p);
  105221. if( pTrig->pTabSchema==pTab->pSchema
  105222. && 0==sqlite3StrICmp(pTrig->table, pTab->zName)
  105223. ){
  105224. pTrig->pNext = (pList ? pList : pTab->pTrigger);
  105225. pList = pTrig;
  105226. }
  105227. }
  105228. }
  105229. return (pList ? pList : pTab->pTrigger);
  105230. }
  105231. /*
  105232. ** This is called by the parser when it sees a CREATE TRIGGER statement
  105233. ** up to the point of the BEGIN before the trigger actions. A Trigger
  105234. ** structure is generated based on the information available and stored
  105235. ** in pParse->pNewTrigger. After the trigger actions have been parsed, the
  105236. ** sqlite3FinishTrigger() function is called to complete the trigger
  105237. ** construction process.
  105238. */
  105239. SQLITE_PRIVATE void sqlite3BeginTrigger(
  105240. Parse *pParse, /* The parse context of the CREATE TRIGGER statement */
  105241. Token *pName1, /* The name of the trigger */
  105242. Token *pName2, /* The name of the trigger */
  105243. int tr_tm, /* One of TK_BEFORE, TK_AFTER, TK_INSTEAD */
  105244. int op, /* One of TK_INSERT, TK_UPDATE, TK_DELETE */
  105245. IdList *pColumns, /* column list if this is an UPDATE OF trigger */
  105246. SrcList *pTableName,/* The name of the table/view the trigger applies to */
  105247. Expr *pWhen, /* WHEN clause */
  105248. int isTemp, /* True if the TEMPORARY keyword is present */
  105249. int noErr /* Suppress errors if the trigger already exists */
  105250. ){
  105251. Trigger *pTrigger = 0; /* The new trigger */
  105252. Table *pTab; /* Table that the trigger fires off of */
  105253. char *zName = 0; /* Name of the trigger */
  105254. sqlite3 *db = pParse->db; /* The database connection */
  105255. int iDb; /* The database to store the trigger in */
  105256. Token *pName; /* The unqualified db name */
  105257. DbFixer sFix; /* State vector for the DB fixer */
  105258. int iTabDb; /* Index of the database holding pTab */
  105259. assert( pName1!=0 ); /* pName1->z might be NULL, but not pName1 itself */
  105260. assert( pName2!=0 );
  105261. assert( op==TK_INSERT || op==TK_UPDATE || op==TK_DELETE );
  105262. assert( op>0 && op<0xff );
  105263. if( isTemp ){
  105264. /* If TEMP was specified, then the trigger name may not be qualified. */
  105265. if( pName2->n>0 ){
  105266. sqlite3ErrorMsg(pParse, "temporary trigger may not have qualified name");
  105267. goto trigger_cleanup;
  105268. }
  105269. iDb = 1;
  105270. pName = pName1;
  105271. }else{
  105272. /* Figure out the db that the trigger will be created in */
  105273. iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
  105274. if( iDb<0 ){
  105275. goto trigger_cleanup;
  105276. }
  105277. }
  105278. if( !pTableName || db->mallocFailed ){
  105279. goto trigger_cleanup;
  105280. }
  105281. /* A long-standing parser bug is that this syntax was allowed:
  105282. **
  105283. ** CREATE TRIGGER attached.demo AFTER INSERT ON attached.tab ....
  105284. ** ^^^^^^^^
  105285. **
  105286. ** To maintain backwards compatibility, ignore the database
  105287. ** name on pTableName if we are reparsing out of SQLITE_MASTER.
  105288. */
  105289. if( db->init.busy && iDb!=1 ){
  105290. sqlite3DbFree(db, pTableName->a[0].zDatabase);
  105291. pTableName->a[0].zDatabase = 0;
  105292. }
  105293. /* If the trigger name was unqualified, and the table is a temp table,
  105294. ** then set iDb to 1 to create the trigger in the temporary database.
  105295. ** If sqlite3SrcListLookup() returns 0, indicating the table does not
  105296. ** exist, the error is caught by the block below.
  105297. */
  105298. pTab = sqlite3SrcListLookup(pParse, pTableName);
  105299. if( db->init.busy==0 && pName2->n==0 && pTab
  105300. && pTab->pSchema==db->aDb[1].pSchema ){
  105301. iDb = 1;
  105302. }
  105303. /* Ensure the table name matches database name and that the table exists */
  105304. if( db->mallocFailed ) goto trigger_cleanup;
  105305. assert( pTableName->nSrc==1 );
  105306. sqlite3FixInit(&sFix, pParse, iDb, "trigger", pName);
  105307. if( sqlite3FixSrcList(&sFix, pTableName) ){
  105308. goto trigger_cleanup;
  105309. }
  105310. pTab = sqlite3SrcListLookup(pParse, pTableName);
  105311. if( !pTab ){
  105312. /* The table does not exist. */
  105313. if( db->init.iDb==1 ){
  105314. /* Ticket #3810.
  105315. ** Normally, whenever a table is dropped, all associated triggers are
  105316. ** dropped too. But if a TEMP trigger is created on a non-TEMP table
  105317. ** and the table is dropped by a different database connection, the
  105318. ** trigger is not visible to the database connection that does the
  105319. ** drop so the trigger cannot be dropped. This results in an
  105320. ** "orphaned trigger" - a trigger whose associated table is missing.
  105321. */
  105322. db->init.orphanTrigger = 1;
  105323. }
  105324. goto trigger_cleanup;
  105325. }
  105326. if( IsVirtual(pTab) ){
  105327. sqlite3ErrorMsg(pParse, "cannot create triggers on virtual tables");
  105328. goto trigger_cleanup;
  105329. }
  105330. /* Check that the trigger name is not reserved and that no trigger of the
  105331. ** specified name exists */
  105332. zName = sqlite3NameFromToken(db, pName);
  105333. if( !zName || SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
  105334. goto trigger_cleanup;
  105335. }
  105336. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  105337. if( sqlite3HashFind(&(db->aDb[iDb].pSchema->trigHash),zName) ){
  105338. if( !noErr ){
  105339. sqlite3ErrorMsg(pParse, "trigger %T already exists", pName);
  105340. }else{
  105341. assert( !db->init.busy );
  105342. sqlite3CodeVerifySchema(pParse, iDb);
  105343. }
  105344. goto trigger_cleanup;
  105345. }
  105346. /* Do not create a trigger on a system table */
  105347. if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0 ){
  105348. sqlite3ErrorMsg(pParse, "cannot create trigger on system table");
  105349. goto trigger_cleanup;
  105350. }
  105351. /* INSTEAD of triggers are only for views and views only support INSTEAD
  105352. ** of triggers.
  105353. */
  105354. if( pTab->pSelect && tr_tm!=TK_INSTEAD ){
  105355. sqlite3ErrorMsg(pParse, "cannot create %s trigger on view: %S",
  105356. (tr_tm == TK_BEFORE)?"BEFORE":"AFTER", pTableName, 0);
  105357. goto trigger_cleanup;
  105358. }
  105359. if( !pTab->pSelect && tr_tm==TK_INSTEAD ){
  105360. sqlite3ErrorMsg(pParse, "cannot create INSTEAD OF"
  105361. " trigger on table: %S", pTableName, 0);
  105362. goto trigger_cleanup;
  105363. }
  105364. iTabDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  105365. #ifndef SQLITE_OMIT_AUTHORIZATION
  105366. {
  105367. int code = SQLITE_CREATE_TRIGGER;
  105368. const char *zDb = db->aDb[iTabDb].zName;
  105369. const char *zDbTrig = isTemp ? db->aDb[1].zName : zDb;
  105370. if( iTabDb==1 || isTemp ) code = SQLITE_CREATE_TEMP_TRIGGER;
  105371. if( sqlite3AuthCheck(pParse, code, zName, pTab->zName, zDbTrig) ){
  105372. goto trigger_cleanup;
  105373. }
  105374. if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(iTabDb),0,zDb)){
  105375. goto trigger_cleanup;
  105376. }
  105377. }
  105378. #endif
  105379. /* INSTEAD OF triggers can only appear on views and BEFORE triggers
  105380. ** cannot appear on views. So we might as well translate every
  105381. ** INSTEAD OF trigger into a BEFORE trigger. It simplifies code
  105382. ** elsewhere.
  105383. */
  105384. if (tr_tm == TK_INSTEAD){
  105385. tr_tm = TK_BEFORE;
  105386. }
  105387. /* Build the Trigger object */
  105388. pTrigger = (Trigger*)sqlite3DbMallocZero(db, sizeof(Trigger));
  105389. if( pTrigger==0 ) goto trigger_cleanup;
  105390. pTrigger->zName = zName;
  105391. zName = 0;
  105392. pTrigger->table = sqlite3DbStrDup(db, pTableName->a[0].zName);
  105393. pTrigger->pSchema = db->aDb[iDb].pSchema;
  105394. pTrigger->pTabSchema = pTab->pSchema;
  105395. pTrigger->op = (u8)op;
  105396. pTrigger->tr_tm = tr_tm==TK_BEFORE ? TRIGGER_BEFORE : TRIGGER_AFTER;
  105397. pTrigger->pWhen = sqlite3ExprDup(db, pWhen, EXPRDUP_REDUCE);
  105398. pTrigger->pColumns = sqlite3IdListDup(db, pColumns);
  105399. assert( pParse->pNewTrigger==0 );
  105400. pParse->pNewTrigger = pTrigger;
  105401. trigger_cleanup:
  105402. sqlite3DbFree(db, zName);
  105403. sqlite3SrcListDelete(db, pTableName);
  105404. sqlite3IdListDelete(db, pColumns);
  105405. sqlite3ExprDelete(db, pWhen);
  105406. if( !pParse->pNewTrigger ){
  105407. sqlite3DeleteTrigger(db, pTrigger);
  105408. }else{
  105409. assert( pParse->pNewTrigger==pTrigger );
  105410. }
  105411. }
  105412. /*
  105413. ** This routine is called after all of the trigger actions have been parsed
  105414. ** in order to complete the process of building the trigger.
  105415. */
  105416. SQLITE_PRIVATE void sqlite3FinishTrigger(
  105417. Parse *pParse, /* Parser context */
  105418. TriggerStep *pStepList, /* The triggered program */
  105419. Token *pAll /* Token that describes the complete CREATE TRIGGER */
  105420. ){
  105421. Trigger *pTrig = pParse->pNewTrigger; /* Trigger being finished */
  105422. char *zName; /* Name of trigger */
  105423. sqlite3 *db = pParse->db; /* The database */
  105424. DbFixer sFix; /* Fixer object */
  105425. int iDb; /* Database containing the trigger */
  105426. Token nameToken; /* Trigger name for error reporting */
  105427. pParse->pNewTrigger = 0;
  105428. if( NEVER(pParse->nErr) || !pTrig ) goto triggerfinish_cleanup;
  105429. zName = pTrig->zName;
  105430. iDb = sqlite3SchemaToIndex(pParse->db, pTrig->pSchema);
  105431. pTrig->step_list = pStepList;
  105432. while( pStepList ){
  105433. pStepList->pTrig = pTrig;
  105434. pStepList = pStepList->pNext;
  105435. }
  105436. nameToken.z = pTrig->zName;
  105437. nameToken.n = sqlite3Strlen30(nameToken.z);
  105438. sqlite3FixInit(&sFix, pParse, iDb, "trigger", &nameToken);
  105439. if( sqlite3FixTriggerStep(&sFix, pTrig->step_list)
  105440. || sqlite3FixExpr(&sFix, pTrig->pWhen)
  105441. ){
  105442. goto triggerfinish_cleanup;
  105443. }
  105444. /* if we are not initializing,
  105445. ** build the sqlite_master entry
  105446. */
  105447. if( !db->init.busy ){
  105448. Vdbe *v;
  105449. char *z;
  105450. /* Make an entry in the sqlite_master table */
  105451. v = sqlite3GetVdbe(pParse);
  105452. if( v==0 ) goto triggerfinish_cleanup;
  105453. sqlite3BeginWriteOperation(pParse, 0, iDb);
  105454. z = sqlite3DbStrNDup(db, (char*)pAll->z, pAll->n);
  105455. sqlite3NestedParse(pParse,
  105456. "INSERT INTO %Q.%s VALUES('trigger',%Q,%Q,0,'CREATE TRIGGER %q')",
  105457. db->aDb[iDb].zName, SCHEMA_TABLE(iDb), zName,
  105458. pTrig->table, z);
  105459. sqlite3DbFree(db, z);
  105460. sqlite3ChangeCookie(pParse, iDb);
  105461. sqlite3VdbeAddParseSchemaOp(v, iDb,
  105462. sqlite3MPrintf(db, "type='trigger' AND name='%q'", zName));
  105463. }
  105464. if( db->init.busy ){
  105465. Trigger *pLink = pTrig;
  105466. Hash *pHash = &db->aDb[iDb].pSchema->trigHash;
  105467. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  105468. pTrig = sqlite3HashInsert(pHash, zName, pTrig);
  105469. if( pTrig ){
  105470. db->mallocFailed = 1;
  105471. }else if( pLink->pSchema==pLink->pTabSchema ){
  105472. Table *pTab;
  105473. pTab = sqlite3HashFind(&pLink->pTabSchema->tblHash, pLink->table);
  105474. assert( pTab!=0 );
  105475. pLink->pNext = pTab->pTrigger;
  105476. pTab->pTrigger = pLink;
  105477. }
  105478. }
  105479. triggerfinish_cleanup:
  105480. sqlite3DeleteTrigger(db, pTrig);
  105481. assert( !pParse->pNewTrigger );
  105482. sqlite3DeleteTriggerStep(db, pStepList);
  105483. }
  105484. /*
  105485. ** Turn a SELECT statement (that the pSelect parameter points to) into
  105486. ** a trigger step. Return a pointer to a TriggerStep structure.
  105487. **
  105488. ** The parser calls this routine when it finds a SELECT statement in
  105489. ** body of a TRIGGER.
  105490. */
  105491. SQLITE_PRIVATE TriggerStep *sqlite3TriggerSelectStep(sqlite3 *db, Select *pSelect){
  105492. TriggerStep *pTriggerStep = sqlite3DbMallocZero(db, sizeof(TriggerStep));
  105493. if( pTriggerStep==0 ) {
  105494. sqlite3SelectDelete(db, pSelect);
  105495. return 0;
  105496. }
  105497. pTriggerStep->op = TK_SELECT;
  105498. pTriggerStep->pSelect = pSelect;
  105499. pTriggerStep->orconf = OE_Default;
  105500. return pTriggerStep;
  105501. }
  105502. /*
  105503. ** Allocate space to hold a new trigger step. The allocated space
  105504. ** holds both the TriggerStep object and the TriggerStep.target.z string.
  105505. **
  105506. ** If an OOM error occurs, NULL is returned and db->mallocFailed is set.
  105507. */
  105508. static TriggerStep *triggerStepAllocate(
  105509. sqlite3 *db, /* Database connection */
  105510. u8 op, /* Trigger opcode */
  105511. Token *pName /* The target name */
  105512. ){
  105513. TriggerStep *pTriggerStep;
  105514. pTriggerStep = sqlite3DbMallocZero(db, sizeof(TriggerStep) + pName->n + 1);
  105515. if( pTriggerStep ){
  105516. char *z = (char*)&pTriggerStep[1];
  105517. memcpy(z, pName->z, pName->n);
  105518. sqlite3Dequote(z);
  105519. pTriggerStep->zTarget = z;
  105520. pTriggerStep->op = op;
  105521. }
  105522. return pTriggerStep;
  105523. }
  105524. /*
  105525. ** Build a trigger step out of an INSERT statement. Return a pointer
  105526. ** to the new trigger step.
  105527. **
  105528. ** The parser calls this routine when it sees an INSERT inside the
  105529. ** body of a trigger.
  105530. */
  105531. SQLITE_PRIVATE TriggerStep *sqlite3TriggerInsertStep(
  105532. sqlite3 *db, /* The database connection */
  105533. Token *pTableName, /* Name of the table into which we insert */
  105534. IdList *pColumn, /* List of columns in pTableName to insert into */
  105535. Select *pSelect, /* A SELECT statement that supplies values */
  105536. u8 orconf /* The conflict algorithm (OE_Abort, OE_Replace, etc.) */
  105537. ){
  105538. TriggerStep *pTriggerStep;
  105539. assert(pSelect != 0 || db->mallocFailed);
  105540. pTriggerStep = triggerStepAllocate(db, TK_INSERT, pTableName);
  105541. if( pTriggerStep ){
  105542. pTriggerStep->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
  105543. pTriggerStep->pIdList = pColumn;
  105544. pTriggerStep->orconf = orconf;
  105545. }else{
  105546. sqlite3IdListDelete(db, pColumn);
  105547. }
  105548. sqlite3SelectDelete(db, pSelect);
  105549. return pTriggerStep;
  105550. }
  105551. /*
  105552. ** Construct a trigger step that implements an UPDATE statement and return
  105553. ** a pointer to that trigger step. The parser calls this routine when it
  105554. ** sees an UPDATE statement inside the body of a CREATE TRIGGER.
  105555. */
  105556. SQLITE_PRIVATE TriggerStep *sqlite3TriggerUpdateStep(
  105557. sqlite3 *db, /* The database connection */
  105558. Token *pTableName, /* Name of the table to be updated */
  105559. ExprList *pEList, /* The SET clause: list of column and new values */
  105560. Expr *pWhere, /* The WHERE clause */
  105561. u8 orconf /* The conflict algorithm. (OE_Abort, OE_Ignore, etc) */
  105562. ){
  105563. TriggerStep *pTriggerStep;
  105564. pTriggerStep = triggerStepAllocate(db, TK_UPDATE, pTableName);
  105565. if( pTriggerStep ){
  105566. pTriggerStep->pExprList = sqlite3ExprListDup(db, pEList, EXPRDUP_REDUCE);
  105567. pTriggerStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE);
  105568. pTriggerStep->orconf = orconf;
  105569. }
  105570. sqlite3ExprListDelete(db, pEList);
  105571. sqlite3ExprDelete(db, pWhere);
  105572. return pTriggerStep;
  105573. }
  105574. /*
  105575. ** Construct a trigger step that implements a DELETE statement and return
  105576. ** a pointer to that trigger step. The parser calls this routine when it
  105577. ** sees a DELETE statement inside the body of a CREATE TRIGGER.
  105578. */
  105579. SQLITE_PRIVATE TriggerStep *sqlite3TriggerDeleteStep(
  105580. sqlite3 *db, /* Database connection */
  105581. Token *pTableName, /* The table from which rows are deleted */
  105582. Expr *pWhere /* The WHERE clause */
  105583. ){
  105584. TriggerStep *pTriggerStep;
  105585. pTriggerStep = triggerStepAllocate(db, TK_DELETE, pTableName);
  105586. if( pTriggerStep ){
  105587. pTriggerStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE);
  105588. pTriggerStep->orconf = OE_Default;
  105589. }
  105590. sqlite3ExprDelete(db, pWhere);
  105591. return pTriggerStep;
  105592. }
  105593. /*
  105594. ** Recursively delete a Trigger structure
  105595. */
  105596. SQLITE_PRIVATE void sqlite3DeleteTrigger(sqlite3 *db, Trigger *pTrigger){
  105597. if( pTrigger==0 ) return;
  105598. sqlite3DeleteTriggerStep(db, pTrigger->step_list);
  105599. sqlite3DbFree(db, pTrigger->zName);
  105600. sqlite3DbFree(db, pTrigger->table);
  105601. sqlite3ExprDelete(db, pTrigger->pWhen);
  105602. sqlite3IdListDelete(db, pTrigger->pColumns);
  105603. sqlite3DbFree(db, pTrigger);
  105604. }
  105605. /*
  105606. ** This function is called to drop a trigger from the database schema.
  105607. **
  105608. ** This may be called directly from the parser and therefore identifies
  105609. ** the trigger by name. The sqlite3DropTriggerPtr() routine does the
  105610. ** same job as this routine except it takes a pointer to the trigger
  105611. ** instead of the trigger name.
  105612. **/
  105613. SQLITE_PRIVATE void sqlite3DropTrigger(Parse *pParse, SrcList *pName, int noErr){
  105614. Trigger *pTrigger = 0;
  105615. int i;
  105616. const char *zDb;
  105617. const char *zName;
  105618. sqlite3 *db = pParse->db;
  105619. if( db->mallocFailed ) goto drop_trigger_cleanup;
  105620. if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
  105621. goto drop_trigger_cleanup;
  105622. }
  105623. assert( pName->nSrc==1 );
  105624. zDb = pName->a[0].zDatabase;
  105625. zName = pName->a[0].zName;
  105626. assert( zDb!=0 || sqlite3BtreeHoldsAllMutexes(db) );
  105627. for(i=OMIT_TEMPDB; i<db->nDb; i++){
  105628. int j = (i<2) ? i^1 : i; /* Search TEMP before MAIN */
  105629. if( zDb && sqlite3StrICmp(db->aDb[j].zName, zDb) ) continue;
  105630. assert( sqlite3SchemaMutexHeld(db, j, 0) );
  105631. pTrigger = sqlite3HashFind(&(db->aDb[j].pSchema->trigHash), zName);
  105632. if( pTrigger ) break;
  105633. }
  105634. if( !pTrigger ){
  105635. if( !noErr ){
  105636. sqlite3ErrorMsg(pParse, "no such trigger: %S", pName, 0);
  105637. }else{
  105638. sqlite3CodeVerifyNamedSchema(pParse, zDb);
  105639. }
  105640. pParse->checkSchema = 1;
  105641. goto drop_trigger_cleanup;
  105642. }
  105643. sqlite3DropTriggerPtr(pParse, pTrigger);
  105644. drop_trigger_cleanup:
  105645. sqlite3SrcListDelete(db, pName);
  105646. }
  105647. /*
  105648. ** Return a pointer to the Table structure for the table that a trigger
  105649. ** is set on.
  105650. */
  105651. static Table *tableOfTrigger(Trigger *pTrigger){
  105652. return sqlite3HashFind(&pTrigger->pTabSchema->tblHash, pTrigger->table);
  105653. }
  105654. /*
  105655. ** Drop a trigger given a pointer to that trigger.
  105656. */
  105657. SQLITE_PRIVATE void sqlite3DropTriggerPtr(Parse *pParse, Trigger *pTrigger){
  105658. Table *pTable;
  105659. Vdbe *v;
  105660. sqlite3 *db = pParse->db;
  105661. int iDb;
  105662. iDb = sqlite3SchemaToIndex(pParse->db, pTrigger->pSchema);
  105663. assert( iDb>=0 && iDb<db->nDb );
  105664. pTable = tableOfTrigger(pTrigger);
  105665. assert( pTable );
  105666. assert( pTable->pSchema==pTrigger->pSchema || iDb==1 );
  105667. #ifndef SQLITE_OMIT_AUTHORIZATION
  105668. {
  105669. int code = SQLITE_DROP_TRIGGER;
  105670. const char *zDb = db->aDb[iDb].zName;
  105671. const char *zTab = SCHEMA_TABLE(iDb);
  105672. if( iDb==1 ) code = SQLITE_DROP_TEMP_TRIGGER;
  105673. if( sqlite3AuthCheck(pParse, code, pTrigger->zName, pTable->zName, zDb) ||
  105674. sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb) ){
  105675. return;
  105676. }
  105677. }
  105678. #endif
  105679. /* Generate code to destroy the database record of the trigger.
  105680. */
  105681. assert( pTable!=0 );
  105682. if( (v = sqlite3GetVdbe(pParse))!=0 ){
  105683. int base;
  105684. static const int iLn = VDBE_OFFSET_LINENO(2);
  105685. static const VdbeOpList dropTrigger[] = {
  105686. { OP_Rewind, 0, ADDR(9), 0},
  105687. { OP_String8, 0, 1, 0}, /* 1 */
  105688. { OP_Column, 0, 1, 2},
  105689. { OP_Ne, 2, ADDR(8), 1},
  105690. { OP_String8, 0, 1, 0}, /* 4: "trigger" */
  105691. { OP_Column, 0, 0, 2},
  105692. { OP_Ne, 2, ADDR(8), 1},
  105693. { OP_Delete, 0, 0, 0},
  105694. { OP_Next, 0, ADDR(1), 0}, /* 8 */
  105695. };
  105696. sqlite3BeginWriteOperation(pParse, 0, iDb);
  105697. sqlite3OpenMasterTable(pParse, iDb);
  105698. base = sqlite3VdbeAddOpList(v, ArraySize(dropTrigger), dropTrigger, iLn);
  105699. sqlite3VdbeChangeP4(v, base+1, pTrigger->zName, P4_TRANSIENT);
  105700. sqlite3VdbeChangeP4(v, base+4, "trigger", P4_STATIC);
  105701. sqlite3ChangeCookie(pParse, iDb);
  105702. sqlite3VdbeAddOp2(v, OP_Close, 0, 0);
  105703. sqlite3VdbeAddOp4(v, OP_DropTrigger, iDb, 0, 0, pTrigger->zName, 0);
  105704. if( pParse->nMem<3 ){
  105705. pParse->nMem = 3;
  105706. }
  105707. }
  105708. }
  105709. /*
  105710. ** Remove a trigger from the hash tables of the sqlite* pointer.
  105711. */
  105712. SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTrigger(sqlite3 *db, int iDb, const char *zName){
  105713. Trigger *pTrigger;
  105714. Hash *pHash;
  105715. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  105716. pHash = &(db->aDb[iDb].pSchema->trigHash);
  105717. pTrigger = sqlite3HashInsert(pHash, zName, 0);
  105718. if( ALWAYS(pTrigger) ){
  105719. if( pTrigger->pSchema==pTrigger->pTabSchema ){
  105720. Table *pTab = tableOfTrigger(pTrigger);
  105721. Trigger **pp;
  105722. for(pp=&pTab->pTrigger; *pp!=pTrigger; pp=&((*pp)->pNext));
  105723. *pp = (*pp)->pNext;
  105724. }
  105725. sqlite3DeleteTrigger(db, pTrigger);
  105726. db->flags |= SQLITE_InternChanges;
  105727. }
  105728. }
  105729. /*
  105730. ** pEList is the SET clause of an UPDATE statement. Each entry
  105731. ** in pEList is of the format <id>=<expr>. If any of the entries
  105732. ** in pEList have an <id> which matches an identifier in pIdList,
  105733. ** then return TRUE. If pIdList==NULL, then it is considered a
  105734. ** wildcard that matches anything. Likewise if pEList==NULL then
  105735. ** it matches anything so always return true. Return false only
  105736. ** if there is no match.
  105737. */
  105738. static int checkColumnOverlap(IdList *pIdList, ExprList *pEList){
  105739. int e;
  105740. if( pIdList==0 || NEVER(pEList==0) ) return 1;
  105741. for(e=0; e<pEList->nExpr; e++){
  105742. if( sqlite3IdListIndex(pIdList, pEList->a[e].zName)>=0 ) return 1;
  105743. }
  105744. return 0;
  105745. }
  105746. /*
  105747. ** Return a list of all triggers on table pTab if there exists at least
  105748. ** one trigger that must be fired when an operation of type 'op' is
  105749. ** performed on the table, and, if that operation is an UPDATE, if at
  105750. ** least one of the columns in pChanges is being modified.
  105751. */
  105752. SQLITE_PRIVATE Trigger *sqlite3TriggersExist(
  105753. Parse *pParse, /* Parse context */
  105754. Table *pTab, /* The table the contains the triggers */
  105755. int op, /* one of TK_DELETE, TK_INSERT, TK_UPDATE */
  105756. ExprList *pChanges, /* Columns that change in an UPDATE statement */
  105757. int *pMask /* OUT: Mask of TRIGGER_BEFORE|TRIGGER_AFTER */
  105758. ){
  105759. int mask = 0;
  105760. Trigger *pList = 0;
  105761. Trigger *p;
  105762. if( (pParse->db->flags & SQLITE_EnableTrigger)!=0 ){
  105763. pList = sqlite3TriggerList(pParse, pTab);
  105764. }
  105765. assert( pList==0 || IsVirtual(pTab)==0 );
  105766. for(p=pList; p; p=p->pNext){
  105767. if( p->op==op && checkColumnOverlap(p->pColumns, pChanges) ){
  105768. mask |= p->tr_tm;
  105769. }
  105770. }
  105771. if( pMask ){
  105772. *pMask = mask;
  105773. }
  105774. return (mask ? pList : 0);
  105775. }
  105776. /*
  105777. ** Convert the pStep->zTarget string into a SrcList and return a pointer
  105778. ** to that SrcList.
  105779. **
  105780. ** This routine adds a specific database name, if needed, to the target when
  105781. ** forming the SrcList. This prevents a trigger in one database from
  105782. ** referring to a target in another database. An exception is when the
  105783. ** trigger is in TEMP in which case it can refer to any other database it
  105784. ** wants.
  105785. */
  105786. static SrcList *targetSrcList(
  105787. Parse *pParse, /* The parsing context */
  105788. TriggerStep *pStep /* The trigger containing the target token */
  105789. ){
  105790. sqlite3 *db = pParse->db;
  105791. int iDb; /* Index of the database to use */
  105792. SrcList *pSrc; /* SrcList to be returned */
  105793. pSrc = sqlite3SrcListAppend(db, 0, 0, 0);
  105794. if( pSrc ){
  105795. assert( pSrc->nSrc>0 );
  105796. pSrc->a[pSrc->nSrc-1].zName = sqlite3DbStrDup(db, pStep->zTarget);
  105797. iDb = sqlite3SchemaToIndex(db, pStep->pTrig->pSchema);
  105798. if( iDb==0 || iDb>=2 ){
  105799. assert( iDb<db->nDb );
  105800. pSrc->a[pSrc->nSrc-1].zDatabase = sqlite3DbStrDup(db, db->aDb[iDb].zName);
  105801. }
  105802. }
  105803. return pSrc;
  105804. }
  105805. /*
  105806. ** Generate VDBE code for the statements inside the body of a single
  105807. ** trigger.
  105808. */
  105809. static int codeTriggerProgram(
  105810. Parse *pParse, /* The parser context */
  105811. TriggerStep *pStepList, /* List of statements inside the trigger body */
  105812. int orconf /* Conflict algorithm. (OE_Abort, etc) */
  105813. ){
  105814. TriggerStep *pStep;
  105815. Vdbe *v = pParse->pVdbe;
  105816. sqlite3 *db = pParse->db;
  105817. assert( pParse->pTriggerTab && pParse->pToplevel );
  105818. assert( pStepList );
  105819. assert( v!=0 );
  105820. for(pStep=pStepList; pStep; pStep=pStep->pNext){
  105821. /* Figure out the ON CONFLICT policy that will be used for this step
  105822. ** of the trigger program. If the statement that caused this trigger
  105823. ** to fire had an explicit ON CONFLICT, then use it. Otherwise, use
  105824. ** the ON CONFLICT policy that was specified as part of the trigger
  105825. ** step statement. Example:
  105826. **
  105827. ** CREATE TRIGGER AFTER INSERT ON t1 BEGIN;
  105828. ** INSERT OR REPLACE INTO t2 VALUES(new.a, new.b);
  105829. ** END;
  105830. **
  105831. ** INSERT INTO t1 ... ; -- insert into t2 uses REPLACE policy
  105832. ** INSERT OR IGNORE INTO t1 ... ; -- insert into t2 uses IGNORE policy
  105833. */
  105834. pParse->eOrconf = (orconf==OE_Default)?pStep->orconf:(u8)orconf;
  105835. assert( pParse->okConstFactor==0 );
  105836. switch( pStep->op ){
  105837. case TK_UPDATE: {
  105838. sqlite3Update(pParse,
  105839. targetSrcList(pParse, pStep),
  105840. sqlite3ExprListDup(db, pStep->pExprList, 0),
  105841. sqlite3ExprDup(db, pStep->pWhere, 0),
  105842. pParse->eOrconf
  105843. );
  105844. break;
  105845. }
  105846. case TK_INSERT: {
  105847. sqlite3Insert(pParse,
  105848. targetSrcList(pParse, pStep),
  105849. sqlite3SelectDup(db, pStep->pSelect, 0),
  105850. sqlite3IdListDup(db, pStep->pIdList),
  105851. pParse->eOrconf
  105852. );
  105853. break;
  105854. }
  105855. case TK_DELETE: {
  105856. sqlite3DeleteFrom(pParse,
  105857. targetSrcList(pParse, pStep),
  105858. sqlite3ExprDup(db, pStep->pWhere, 0)
  105859. );
  105860. break;
  105861. }
  105862. default: assert( pStep->op==TK_SELECT ); {
  105863. SelectDest sDest;
  105864. Select *pSelect = sqlite3SelectDup(db, pStep->pSelect, 0);
  105865. sqlite3SelectDestInit(&sDest, SRT_Discard, 0);
  105866. sqlite3Select(pParse, pSelect, &sDest);
  105867. sqlite3SelectDelete(db, pSelect);
  105868. break;
  105869. }
  105870. }
  105871. if( pStep->op!=TK_SELECT ){
  105872. sqlite3VdbeAddOp0(v, OP_ResetCount);
  105873. }
  105874. }
  105875. return 0;
  105876. }
  105877. #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
  105878. /*
  105879. ** This function is used to add VdbeComment() annotations to a VDBE
  105880. ** program. It is not used in production code, only for debugging.
  105881. */
  105882. static const char *onErrorText(int onError){
  105883. switch( onError ){
  105884. case OE_Abort: return "abort";
  105885. case OE_Rollback: return "rollback";
  105886. case OE_Fail: return "fail";
  105887. case OE_Replace: return "replace";
  105888. case OE_Ignore: return "ignore";
  105889. case OE_Default: return "default";
  105890. }
  105891. return "n/a";
  105892. }
  105893. #endif
  105894. /*
  105895. ** Parse context structure pFrom has just been used to create a sub-vdbe
  105896. ** (trigger program). If an error has occurred, transfer error information
  105897. ** from pFrom to pTo.
  105898. */
  105899. static void transferParseError(Parse *pTo, Parse *pFrom){
  105900. assert( pFrom->zErrMsg==0 || pFrom->nErr );
  105901. assert( pTo->zErrMsg==0 || pTo->nErr );
  105902. if( pTo->nErr==0 ){
  105903. pTo->zErrMsg = pFrom->zErrMsg;
  105904. pTo->nErr = pFrom->nErr;
  105905. pTo->rc = pFrom->rc;
  105906. }else{
  105907. sqlite3DbFree(pFrom->db, pFrom->zErrMsg);
  105908. }
  105909. }
  105910. /*
  105911. ** Create and populate a new TriggerPrg object with a sub-program
  105912. ** implementing trigger pTrigger with ON CONFLICT policy orconf.
  105913. */
  105914. static TriggerPrg *codeRowTrigger(
  105915. Parse *pParse, /* Current parse context */
  105916. Trigger *pTrigger, /* Trigger to code */
  105917. Table *pTab, /* The table pTrigger is attached to */
  105918. int orconf /* ON CONFLICT policy to code trigger program with */
  105919. ){
  105920. Parse *pTop = sqlite3ParseToplevel(pParse);
  105921. sqlite3 *db = pParse->db; /* Database handle */
  105922. TriggerPrg *pPrg; /* Value to return */
  105923. Expr *pWhen = 0; /* Duplicate of trigger WHEN expression */
  105924. Vdbe *v; /* Temporary VM */
  105925. NameContext sNC; /* Name context for sub-vdbe */
  105926. SubProgram *pProgram = 0; /* Sub-vdbe for trigger program */
  105927. Parse *pSubParse; /* Parse context for sub-vdbe */
  105928. int iEndTrigger = 0; /* Label to jump to if WHEN is false */
  105929. assert( pTrigger->zName==0 || pTab==tableOfTrigger(pTrigger) );
  105930. assert( pTop->pVdbe );
  105931. /* Allocate the TriggerPrg and SubProgram objects. To ensure that they
  105932. ** are freed if an error occurs, link them into the Parse.pTriggerPrg
  105933. ** list of the top-level Parse object sooner rather than later. */
  105934. pPrg = sqlite3DbMallocZero(db, sizeof(TriggerPrg));
  105935. if( !pPrg ) return 0;
  105936. pPrg->pNext = pTop->pTriggerPrg;
  105937. pTop->pTriggerPrg = pPrg;
  105938. pPrg->pProgram = pProgram = sqlite3DbMallocZero(db, sizeof(SubProgram));
  105939. if( !pProgram ) return 0;
  105940. sqlite3VdbeLinkSubProgram(pTop->pVdbe, pProgram);
  105941. pPrg->pTrigger = pTrigger;
  105942. pPrg->orconf = orconf;
  105943. pPrg->aColmask[0] = 0xffffffff;
  105944. pPrg->aColmask[1] = 0xffffffff;
  105945. /* Allocate and populate a new Parse context to use for coding the
  105946. ** trigger sub-program. */
  105947. pSubParse = sqlite3StackAllocZero(db, sizeof(Parse));
  105948. if( !pSubParse ) return 0;
  105949. memset(&sNC, 0, sizeof(sNC));
  105950. sNC.pParse = pSubParse;
  105951. pSubParse->db = db;
  105952. pSubParse->pTriggerTab = pTab;
  105953. pSubParse->pToplevel = pTop;
  105954. pSubParse->zAuthContext = pTrigger->zName;
  105955. pSubParse->eTriggerOp = pTrigger->op;
  105956. pSubParse->nQueryLoop = pParse->nQueryLoop;
  105957. v = sqlite3GetVdbe(pSubParse);
  105958. if( v ){
  105959. VdbeComment((v, "Start: %s.%s (%s %s%s%s ON %s)",
  105960. pTrigger->zName, onErrorText(orconf),
  105961. (pTrigger->tr_tm==TRIGGER_BEFORE ? "BEFORE" : "AFTER"),
  105962. (pTrigger->op==TK_UPDATE ? "UPDATE" : ""),
  105963. (pTrigger->op==TK_INSERT ? "INSERT" : ""),
  105964. (pTrigger->op==TK_DELETE ? "DELETE" : ""),
  105965. pTab->zName
  105966. ));
  105967. #ifndef SQLITE_OMIT_TRACE
  105968. sqlite3VdbeChangeP4(v, -1,
  105969. sqlite3MPrintf(db, "-- TRIGGER %s", pTrigger->zName), P4_DYNAMIC
  105970. );
  105971. #endif
  105972. /* If one was specified, code the WHEN clause. If it evaluates to false
  105973. ** (or NULL) the sub-vdbe is immediately halted by jumping to the
  105974. ** OP_Halt inserted at the end of the program. */
  105975. if( pTrigger->pWhen ){
  105976. pWhen = sqlite3ExprDup(db, pTrigger->pWhen, 0);
  105977. if( SQLITE_OK==sqlite3ResolveExprNames(&sNC, pWhen)
  105978. && db->mallocFailed==0
  105979. ){
  105980. iEndTrigger = sqlite3VdbeMakeLabel(v);
  105981. sqlite3ExprIfFalse(pSubParse, pWhen, iEndTrigger, SQLITE_JUMPIFNULL);
  105982. }
  105983. sqlite3ExprDelete(db, pWhen);
  105984. }
  105985. /* Code the trigger program into the sub-vdbe. */
  105986. codeTriggerProgram(pSubParse, pTrigger->step_list, orconf);
  105987. /* Insert an OP_Halt at the end of the sub-program. */
  105988. if( iEndTrigger ){
  105989. sqlite3VdbeResolveLabel(v, iEndTrigger);
  105990. }
  105991. sqlite3VdbeAddOp0(v, OP_Halt);
  105992. VdbeComment((v, "End: %s.%s", pTrigger->zName, onErrorText(orconf)));
  105993. transferParseError(pParse, pSubParse);
  105994. if( db->mallocFailed==0 ){
  105995. pProgram->aOp = sqlite3VdbeTakeOpArray(v, &pProgram->nOp, &pTop->nMaxArg);
  105996. }
  105997. pProgram->nMem = pSubParse->nMem;
  105998. pProgram->nCsr = pSubParse->nTab;
  105999. pProgram->nOnce = pSubParse->nOnce;
  106000. pProgram->token = (void *)pTrigger;
  106001. pPrg->aColmask[0] = pSubParse->oldmask;
  106002. pPrg->aColmask[1] = pSubParse->newmask;
  106003. sqlite3VdbeDelete(v);
  106004. }
  106005. assert( !pSubParse->pAinc && !pSubParse->pZombieTab );
  106006. assert( !pSubParse->pTriggerPrg && !pSubParse->nMaxArg );
  106007. sqlite3ParserReset(pSubParse);
  106008. sqlite3StackFree(db, pSubParse);
  106009. return pPrg;
  106010. }
  106011. /*
  106012. ** Return a pointer to a TriggerPrg object containing the sub-program for
  106013. ** trigger pTrigger with default ON CONFLICT algorithm orconf. If no such
  106014. ** TriggerPrg object exists, a new object is allocated and populated before
  106015. ** being returned.
  106016. */
  106017. static TriggerPrg *getRowTrigger(
  106018. Parse *pParse, /* Current parse context */
  106019. Trigger *pTrigger, /* Trigger to code */
  106020. Table *pTab, /* The table trigger pTrigger is attached to */
  106021. int orconf /* ON CONFLICT algorithm. */
  106022. ){
  106023. Parse *pRoot = sqlite3ParseToplevel(pParse);
  106024. TriggerPrg *pPrg;
  106025. assert( pTrigger->zName==0 || pTab==tableOfTrigger(pTrigger) );
  106026. /* It may be that this trigger has already been coded (or is in the
  106027. ** process of being coded). If this is the case, then an entry with
  106028. ** a matching TriggerPrg.pTrigger field will be present somewhere
  106029. ** in the Parse.pTriggerPrg list. Search for such an entry. */
  106030. for(pPrg=pRoot->pTriggerPrg;
  106031. pPrg && (pPrg->pTrigger!=pTrigger || pPrg->orconf!=orconf);
  106032. pPrg=pPrg->pNext
  106033. );
  106034. /* If an existing TriggerPrg could not be located, create a new one. */
  106035. if( !pPrg ){
  106036. pPrg = codeRowTrigger(pParse, pTrigger, pTab, orconf);
  106037. }
  106038. return pPrg;
  106039. }
  106040. /*
  106041. ** Generate code for the trigger program associated with trigger p on
  106042. ** table pTab. The reg, orconf and ignoreJump parameters passed to this
  106043. ** function are the same as those described in the header function for
  106044. ** sqlite3CodeRowTrigger()
  106045. */
  106046. SQLITE_PRIVATE void sqlite3CodeRowTriggerDirect(
  106047. Parse *pParse, /* Parse context */
  106048. Trigger *p, /* Trigger to code */
  106049. Table *pTab, /* The table to code triggers from */
  106050. int reg, /* Reg array containing OLD.* and NEW.* values */
  106051. int orconf, /* ON CONFLICT policy */
  106052. int ignoreJump /* Instruction to jump to for RAISE(IGNORE) */
  106053. ){
  106054. Vdbe *v = sqlite3GetVdbe(pParse); /* Main VM */
  106055. TriggerPrg *pPrg;
  106056. pPrg = getRowTrigger(pParse, p, pTab, orconf);
  106057. assert( pPrg || pParse->nErr || pParse->db->mallocFailed );
  106058. /* Code the OP_Program opcode in the parent VDBE. P4 of the OP_Program
  106059. ** is a pointer to the sub-vdbe containing the trigger program. */
  106060. if( pPrg ){
  106061. int bRecursive = (p->zName && 0==(pParse->db->flags&SQLITE_RecTriggers));
  106062. sqlite3VdbeAddOp3(v, OP_Program, reg, ignoreJump, ++pParse->nMem);
  106063. sqlite3VdbeChangeP4(v, -1, (const char *)pPrg->pProgram, P4_SUBPROGRAM);
  106064. VdbeComment(
  106065. (v, "Call: %s.%s", (p->zName?p->zName:"fkey"), onErrorText(orconf)));
  106066. /* Set the P5 operand of the OP_Program instruction to non-zero if
  106067. ** recursive invocation of this trigger program is disallowed. Recursive
  106068. ** invocation is disallowed if (a) the sub-program is really a trigger,
  106069. ** not a foreign key action, and (b) the flag to enable recursive triggers
  106070. ** is clear. */
  106071. sqlite3VdbeChangeP5(v, (u8)bRecursive);
  106072. }
  106073. }
  106074. /*
  106075. ** This is called to code the required FOR EACH ROW triggers for an operation
  106076. ** on table pTab. The operation to code triggers for (INSERT, UPDATE or DELETE)
  106077. ** is given by the op parameter. The tr_tm parameter determines whether the
  106078. ** BEFORE or AFTER triggers are coded. If the operation is an UPDATE, then
  106079. ** parameter pChanges is passed the list of columns being modified.
  106080. **
  106081. ** If there are no triggers that fire at the specified time for the specified
  106082. ** operation on pTab, this function is a no-op.
  106083. **
  106084. ** The reg argument is the address of the first in an array of registers
  106085. ** that contain the values substituted for the new.* and old.* references
  106086. ** in the trigger program. If N is the number of columns in table pTab
  106087. ** (a copy of pTab->nCol), then registers are populated as follows:
  106088. **
  106089. ** Register Contains
  106090. ** ------------------------------------------------------
  106091. ** reg+0 OLD.rowid
  106092. ** reg+1 OLD.* value of left-most column of pTab
  106093. ** ... ...
  106094. ** reg+N OLD.* value of right-most column of pTab
  106095. ** reg+N+1 NEW.rowid
  106096. ** reg+N+2 OLD.* value of left-most column of pTab
  106097. ** ... ...
  106098. ** reg+N+N+1 NEW.* value of right-most column of pTab
  106099. **
  106100. ** For ON DELETE triggers, the registers containing the NEW.* values will
  106101. ** never be accessed by the trigger program, so they are not allocated or
  106102. ** populated by the caller (there is no data to populate them with anyway).
  106103. ** Similarly, for ON INSERT triggers the values stored in the OLD.* registers
  106104. ** are never accessed, and so are not allocated by the caller. So, for an
  106105. ** ON INSERT trigger, the value passed to this function as parameter reg
  106106. ** is not a readable register, although registers (reg+N) through
  106107. ** (reg+N+N+1) are.
  106108. **
  106109. ** Parameter orconf is the default conflict resolution algorithm for the
  106110. ** trigger program to use (REPLACE, IGNORE etc.). Parameter ignoreJump
  106111. ** is the instruction that control should jump to if a trigger program
  106112. ** raises an IGNORE exception.
  106113. */
  106114. SQLITE_PRIVATE void sqlite3CodeRowTrigger(
  106115. Parse *pParse, /* Parse context */
  106116. Trigger *pTrigger, /* List of triggers on table pTab */
  106117. int op, /* One of TK_UPDATE, TK_INSERT, TK_DELETE */
  106118. ExprList *pChanges, /* Changes list for any UPDATE OF triggers */
  106119. int tr_tm, /* One of TRIGGER_BEFORE, TRIGGER_AFTER */
  106120. Table *pTab, /* The table to code triggers from */
  106121. int reg, /* The first in an array of registers (see above) */
  106122. int orconf, /* ON CONFLICT policy */
  106123. int ignoreJump /* Instruction to jump to for RAISE(IGNORE) */
  106124. ){
  106125. Trigger *p; /* Used to iterate through pTrigger list */
  106126. assert( op==TK_UPDATE || op==TK_INSERT || op==TK_DELETE );
  106127. assert( tr_tm==TRIGGER_BEFORE || tr_tm==TRIGGER_AFTER );
  106128. assert( (op==TK_UPDATE)==(pChanges!=0) );
  106129. for(p=pTrigger; p; p=p->pNext){
  106130. /* Sanity checking: The schema for the trigger and for the table are
  106131. ** always defined. The trigger must be in the same schema as the table
  106132. ** or else it must be a TEMP trigger. */
  106133. assert( p->pSchema!=0 );
  106134. assert( p->pTabSchema!=0 );
  106135. assert( p->pSchema==p->pTabSchema
  106136. || p->pSchema==pParse->db->aDb[1].pSchema );
  106137. /* Determine whether we should code this trigger */
  106138. if( p->op==op
  106139. && p->tr_tm==tr_tm
  106140. && checkColumnOverlap(p->pColumns, pChanges)
  106141. ){
  106142. sqlite3CodeRowTriggerDirect(pParse, p, pTab, reg, orconf, ignoreJump);
  106143. }
  106144. }
  106145. }
  106146. /*
  106147. ** Triggers may access values stored in the old.* or new.* pseudo-table.
  106148. ** This function returns a 32-bit bitmask indicating which columns of the
  106149. ** old.* or new.* tables actually are used by triggers. This information
  106150. ** may be used by the caller, for example, to avoid having to load the entire
  106151. ** old.* record into memory when executing an UPDATE or DELETE command.
  106152. **
  106153. ** Bit 0 of the returned mask is set if the left-most column of the
  106154. ** table may be accessed using an [old|new].<col> reference. Bit 1 is set if
  106155. ** the second leftmost column value is required, and so on. If there
  106156. ** are more than 32 columns in the table, and at least one of the columns
  106157. ** with an index greater than 32 may be accessed, 0xffffffff is returned.
  106158. **
  106159. ** It is not possible to determine if the old.rowid or new.rowid column is
  106160. ** accessed by triggers. The caller must always assume that it is.
  106161. **
  106162. ** Parameter isNew must be either 1 or 0. If it is 0, then the mask returned
  106163. ** applies to the old.* table. If 1, the new.* table.
  106164. **
  106165. ** Parameter tr_tm must be a mask with one or both of the TRIGGER_BEFORE
  106166. ** and TRIGGER_AFTER bits set. Values accessed by BEFORE triggers are only
  106167. ** included in the returned mask if the TRIGGER_BEFORE bit is set in the
  106168. ** tr_tm parameter. Similarly, values accessed by AFTER triggers are only
  106169. ** included in the returned mask if the TRIGGER_AFTER bit is set in tr_tm.
  106170. */
  106171. SQLITE_PRIVATE u32 sqlite3TriggerColmask(
  106172. Parse *pParse, /* Parse context */
  106173. Trigger *pTrigger, /* List of triggers on table pTab */
  106174. ExprList *pChanges, /* Changes list for any UPDATE OF triggers */
  106175. int isNew, /* 1 for new.* ref mask, 0 for old.* ref mask */
  106176. int tr_tm, /* Mask of TRIGGER_BEFORE|TRIGGER_AFTER */
  106177. Table *pTab, /* The table to code triggers from */
  106178. int orconf /* Default ON CONFLICT policy for trigger steps */
  106179. ){
  106180. const int op = pChanges ? TK_UPDATE : TK_DELETE;
  106181. u32 mask = 0;
  106182. Trigger *p;
  106183. assert( isNew==1 || isNew==0 );
  106184. for(p=pTrigger; p; p=p->pNext){
  106185. if( p->op==op && (tr_tm&p->tr_tm)
  106186. && checkColumnOverlap(p->pColumns,pChanges)
  106187. ){
  106188. TriggerPrg *pPrg;
  106189. pPrg = getRowTrigger(pParse, p, pTab, orconf);
  106190. if( pPrg ){
  106191. mask |= pPrg->aColmask[isNew];
  106192. }
  106193. }
  106194. }
  106195. return mask;
  106196. }
  106197. #endif /* !defined(SQLITE_OMIT_TRIGGER) */
  106198. /************** End of trigger.c *********************************************/
  106199. /************** Begin file update.c ******************************************/
  106200. /*
  106201. ** 2001 September 15
  106202. **
  106203. ** The author disclaims copyright to this source code. In place of
  106204. ** a legal notice, here is a blessing:
  106205. **
  106206. ** May you do good and not evil.
  106207. ** May you find forgiveness for yourself and forgive others.
  106208. ** May you share freely, never taking more than you give.
  106209. **
  106210. *************************************************************************
  106211. ** This file contains C code routines that are called by the parser
  106212. ** to handle UPDATE statements.
  106213. */
  106214. #ifndef SQLITE_OMIT_VIRTUALTABLE
  106215. /* Forward declaration */
  106216. static void updateVirtualTable(
  106217. Parse *pParse, /* The parsing context */
  106218. SrcList *pSrc, /* The virtual table to be modified */
  106219. Table *pTab, /* The virtual table */
  106220. ExprList *pChanges, /* The columns to change in the UPDATE statement */
  106221. Expr *pRowidExpr, /* Expression used to recompute the rowid */
  106222. int *aXRef, /* Mapping from columns of pTab to entries in pChanges */
  106223. Expr *pWhere, /* WHERE clause of the UPDATE statement */
  106224. int onError /* ON CONFLICT strategy */
  106225. );
  106226. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  106227. /*
  106228. ** The most recently coded instruction was an OP_Column to retrieve the
  106229. ** i-th column of table pTab. This routine sets the P4 parameter of the
  106230. ** OP_Column to the default value, if any.
  106231. **
  106232. ** The default value of a column is specified by a DEFAULT clause in the
  106233. ** column definition. This was either supplied by the user when the table
  106234. ** was created, or added later to the table definition by an ALTER TABLE
  106235. ** command. If the latter, then the row-records in the table btree on disk
  106236. ** may not contain a value for the column and the default value, taken
  106237. ** from the P4 parameter of the OP_Column instruction, is returned instead.
  106238. ** If the former, then all row-records are guaranteed to include a value
  106239. ** for the column and the P4 value is not required.
  106240. **
  106241. ** Column definitions created by an ALTER TABLE command may only have
  106242. ** literal default values specified: a number, null or a string. (If a more
  106243. ** complicated default expression value was provided, it is evaluated
  106244. ** when the ALTER TABLE is executed and one of the literal values written
  106245. ** into the sqlite_master table.)
  106246. **
  106247. ** Therefore, the P4 parameter is only required if the default value for
  106248. ** the column is a literal number, string or null. The sqlite3ValueFromExpr()
  106249. ** function is capable of transforming these types of expressions into
  106250. ** sqlite3_value objects.
  106251. **
  106252. ** If parameter iReg is not negative, code an OP_RealAffinity instruction
  106253. ** on register iReg. This is used when an equivalent integer value is
  106254. ** stored in place of an 8-byte floating point value in order to save
  106255. ** space.
  106256. */
  106257. SQLITE_PRIVATE void sqlite3ColumnDefault(Vdbe *v, Table *pTab, int i, int iReg){
  106258. assert( pTab!=0 );
  106259. if( !pTab->pSelect ){
  106260. sqlite3_value *pValue = 0;
  106261. u8 enc = ENC(sqlite3VdbeDb(v));
  106262. Column *pCol = &pTab->aCol[i];
  106263. VdbeComment((v, "%s.%s", pTab->zName, pCol->zName));
  106264. assert( i<pTab->nCol );
  106265. sqlite3ValueFromExpr(sqlite3VdbeDb(v), pCol->pDflt, enc,
  106266. pCol->affinity, &pValue);
  106267. if( pValue ){
  106268. sqlite3VdbeChangeP4(v, -1, (const char *)pValue, P4_MEM);
  106269. }
  106270. #ifndef SQLITE_OMIT_FLOATING_POINT
  106271. if( pTab->aCol[i].affinity==SQLITE_AFF_REAL ){
  106272. sqlite3VdbeAddOp1(v, OP_RealAffinity, iReg);
  106273. }
  106274. #endif
  106275. }
  106276. }
  106277. /*
  106278. ** Process an UPDATE statement.
  106279. **
  106280. ** UPDATE OR IGNORE table_wxyz SET a=b, c=d WHERE e<5 AND f NOT NULL;
  106281. ** \_______/ \________/ \______/ \________________/
  106282. * onError pTabList pChanges pWhere
  106283. */
  106284. SQLITE_PRIVATE void sqlite3Update(
  106285. Parse *pParse, /* The parser context */
  106286. SrcList *pTabList, /* The table in which we should change things */
  106287. ExprList *pChanges, /* Things to be changed */
  106288. Expr *pWhere, /* The WHERE clause. May be null */
  106289. int onError /* How to handle constraint errors */
  106290. ){
  106291. int i, j; /* Loop counters */
  106292. Table *pTab; /* The table to be updated */
  106293. int addrTop = 0; /* VDBE instruction address of the start of the loop */
  106294. WhereInfo *pWInfo; /* Information about the WHERE clause */
  106295. Vdbe *v; /* The virtual database engine */
  106296. Index *pIdx; /* For looping over indices */
  106297. Index *pPk; /* The PRIMARY KEY index for WITHOUT ROWID tables */
  106298. int nIdx; /* Number of indices that need updating */
  106299. int iBaseCur; /* Base cursor number */
  106300. int iDataCur; /* Cursor for the canonical data btree */
  106301. int iIdxCur; /* Cursor for the first index */
  106302. sqlite3 *db; /* The database structure */
  106303. int *aRegIdx = 0; /* One register assigned to each index to be updated */
  106304. int *aXRef = 0; /* aXRef[i] is the index in pChanges->a[] of the
  106305. ** an expression for the i-th column of the table.
  106306. ** aXRef[i]==-1 if the i-th column is not changed. */
  106307. u8 *aToOpen; /* 1 for tables and indices to be opened */
  106308. u8 chngPk; /* PRIMARY KEY changed in a WITHOUT ROWID table */
  106309. u8 chngRowid; /* Rowid changed in a normal table */
  106310. u8 chngKey; /* Either chngPk or chngRowid */
  106311. Expr *pRowidExpr = 0; /* Expression defining the new record number */
  106312. AuthContext sContext; /* The authorization context */
  106313. NameContext sNC; /* The name-context to resolve expressions in */
  106314. int iDb; /* Database containing the table being updated */
  106315. int okOnePass; /* True for one-pass algorithm without the FIFO */
  106316. int hasFK; /* True if foreign key processing is required */
  106317. int labelBreak; /* Jump here to break out of UPDATE loop */
  106318. int labelContinue; /* Jump here to continue next step of UPDATE loop */
  106319. #ifndef SQLITE_OMIT_TRIGGER
  106320. int isView; /* True when updating a view (INSTEAD OF trigger) */
  106321. Trigger *pTrigger; /* List of triggers on pTab, if required */
  106322. int tmask; /* Mask of TRIGGER_BEFORE|TRIGGER_AFTER */
  106323. #endif
  106324. int newmask; /* Mask of NEW.* columns accessed by BEFORE triggers */
  106325. int iEph = 0; /* Ephemeral table holding all primary key values */
  106326. int nKey = 0; /* Number of elements in regKey for WITHOUT ROWID */
  106327. int aiCurOnePass[2]; /* The write cursors opened by WHERE_ONEPASS */
  106328. /* Register Allocations */
  106329. int regRowCount = 0; /* A count of rows changed */
  106330. int regOldRowid; /* The old rowid */
  106331. int regNewRowid; /* The new rowid */
  106332. int regNew; /* Content of the NEW.* table in triggers */
  106333. int regOld = 0; /* Content of OLD.* table in triggers */
  106334. int regRowSet = 0; /* Rowset of rows to be updated */
  106335. int regKey = 0; /* composite PRIMARY KEY value */
  106336. memset(&sContext, 0, sizeof(sContext));
  106337. db = pParse->db;
  106338. if( pParse->nErr || db->mallocFailed ){
  106339. goto update_cleanup;
  106340. }
  106341. assert( pTabList->nSrc==1 );
  106342. /* Locate the table which we want to update.
  106343. */
  106344. pTab = sqlite3SrcListLookup(pParse, pTabList);
  106345. if( pTab==0 ) goto update_cleanup;
  106346. iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
  106347. /* Figure out if we have any triggers and if the table being
  106348. ** updated is a view.
  106349. */
  106350. #ifndef SQLITE_OMIT_TRIGGER
  106351. pTrigger = sqlite3TriggersExist(pParse, pTab, TK_UPDATE, pChanges, &tmask);
  106352. isView = pTab->pSelect!=0;
  106353. assert( pTrigger || tmask==0 );
  106354. #else
  106355. # define pTrigger 0
  106356. # define isView 0
  106357. # define tmask 0
  106358. #endif
  106359. #ifdef SQLITE_OMIT_VIEW
  106360. # undef isView
  106361. # define isView 0
  106362. #endif
  106363. if( sqlite3ViewGetColumnNames(pParse, pTab) ){
  106364. goto update_cleanup;
  106365. }
  106366. if( sqlite3IsReadOnly(pParse, pTab, tmask) ){
  106367. goto update_cleanup;
  106368. }
  106369. /* Allocate a cursors for the main database table and for all indices.
  106370. ** The index cursors might not be used, but if they are used they
  106371. ** need to occur right after the database cursor. So go ahead and
  106372. ** allocate enough space, just in case.
  106373. */
  106374. pTabList->a[0].iCursor = iBaseCur = iDataCur = pParse->nTab++;
  106375. iIdxCur = iDataCur+1;
  106376. pPk = HasRowid(pTab) ? 0 : sqlite3PrimaryKeyIndex(pTab);
  106377. for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){
  106378. if( IsPrimaryKeyIndex(pIdx) && pPk!=0 ){
  106379. iDataCur = pParse->nTab;
  106380. pTabList->a[0].iCursor = iDataCur;
  106381. }
  106382. pParse->nTab++;
  106383. }
  106384. /* Allocate space for aXRef[], aRegIdx[], and aToOpen[].
  106385. ** Initialize aXRef[] and aToOpen[] to their default values.
  106386. */
  106387. aXRef = sqlite3DbMallocRaw(db, sizeof(int) * (pTab->nCol+nIdx) + nIdx+2 );
  106388. if( aXRef==0 ) goto update_cleanup;
  106389. aRegIdx = aXRef+pTab->nCol;
  106390. aToOpen = (u8*)(aRegIdx+nIdx);
  106391. memset(aToOpen, 1, nIdx+1);
  106392. aToOpen[nIdx+1] = 0;
  106393. for(i=0; i<pTab->nCol; i++) aXRef[i] = -1;
  106394. /* Initialize the name-context */
  106395. memset(&sNC, 0, sizeof(sNC));
  106396. sNC.pParse = pParse;
  106397. sNC.pSrcList = pTabList;
  106398. /* Resolve the column names in all the expressions of the
  106399. ** of the UPDATE statement. Also find the column index
  106400. ** for each column to be updated in the pChanges array. For each
  106401. ** column to be updated, make sure we have authorization to change
  106402. ** that column.
  106403. */
  106404. chngRowid = chngPk = 0;
  106405. for(i=0; i<pChanges->nExpr; i++){
  106406. if( sqlite3ResolveExprNames(&sNC, pChanges->a[i].pExpr) ){
  106407. goto update_cleanup;
  106408. }
  106409. for(j=0; j<pTab->nCol; j++){
  106410. if( sqlite3StrICmp(pTab->aCol[j].zName, pChanges->a[i].zName)==0 ){
  106411. if( j==pTab->iPKey ){
  106412. chngRowid = 1;
  106413. pRowidExpr = pChanges->a[i].pExpr;
  106414. }else if( pPk && (pTab->aCol[j].colFlags & COLFLAG_PRIMKEY)!=0 ){
  106415. chngPk = 1;
  106416. }
  106417. aXRef[j] = i;
  106418. break;
  106419. }
  106420. }
  106421. if( j>=pTab->nCol ){
  106422. if( pPk==0 && sqlite3IsRowid(pChanges->a[i].zName) ){
  106423. j = -1;
  106424. chngRowid = 1;
  106425. pRowidExpr = pChanges->a[i].pExpr;
  106426. }else{
  106427. sqlite3ErrorMsg(pParse, "no such column: %s", pChanges->a[i].zName);
  106428. pParse->checkSchema = 1;
  106429. goto update_cleanup;
  106430. }
  106431. }
  106432. #ifndef SQLITE_OMIT_AUTHORIZATION
  106433. {
  106434. int rc;
  106435. rc = sqlite3AuthCheck(pParse, SQLITE_UPDATE, pTab->zName,
  106436. j<0 ? "ROWID" : pTab->aCol[j].zName,
  106437. db->aDb[iDb].zName);
  106438. if( rc==SQLITE_DENY ){
  106439. goto update_cleanup;
  106440. }else if( rc==SQLITE_IGNORE ){
  106441. aXRef[j] = -1;
  106442. }
  106443. }
  106444. #endif
  106445. }
  106446. assert( (chngRowid & chngPk)==0 );
  106447. assert( chngRowid==0 || chngRowid==1 );
  106448. assert( chngPk==0 || chngPk==1 );
  106449. chngKey = chngRowid + chngPk;
  106450. /* The SET expressions are not actually used inside the WHERE loop.
  106451. ** So reset the colUsed mask
  106452. */
  106453. pTabList->a[0].colUsed = 0;
  106454. hasFK = sqlite3FkRequired(pParse, pTab, aXRef, chngKey);
  106455. /* There is one entry in the aRegIdx[] array for each index on the table
  106456. ** being updated. Fill in aRegIdx[] with a register number that will hold
  106457. ** the key for accessing each index.
  106458. */
  106459. for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
  106460. int reg;
  106461. if( chngKey || hasFK || pIdx->pPartIdxWhere || pIdx==pPk ){
  106462. reg = ++pParse->nMem;
  106463. }else{
  106464. reg = 0;
  106465. for(i=0; i<pIdx->nKeyCol; i++){
  106466. if( aXRef[pIdx->aiColumn[i]]>=0 ){
  106467. reg = ++pParse->nMem;
  106468. break;
  106469. }
  106470. }
  106471. }
  106472. if( reg==0 ) aToOpen[j+1] = 0;
  106473. aRegIdx[j] = reg;
  106474. }
  106475. /* Begin generating code. */
  106476. v = sqlite3GetVdbe(pParse);
  106477. if( v==0 ) goto update_cleanup;
  106478. if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
  106479. sqlite3BeginWriteOperation(pParse, 1, iDb);
  106480. #ifndef SQLITE_OMIT_VIRTUALTABLE
  106481. /* Virtual tables must be handled separately */
  106482. if( IsVirtual(pTab) ){
  106483. updateVirtualTable(pParse, pTabList, pTab, pChanges, pRowidExpr, aXRef,
  106484. pWhere, onError);
  106485. pWhere = 0;
  106486. pTabList = 0;
  106487. goto update_cleanup;
  106488. }
  106489. #endif
  106490. /* Allocate required registers. */
  106491. regRowSet = ++pParse->nMem;
  106492. regOldRowid = regNewRowid = ++pParse->nMem;
  106493. if( chngPk || pTrigger || hasFK ){
  106494. regOld = pParse->nMem + 1;
  106495. pParse->nMem += pTab->nCol;
  106496. }
  106497. if( chngKey || pTrigger || hasFK ){
  106498. regNewRowid = ++pParse->nMem;
  106499. }
  106500. regNew = pParse->nMem + 1;
  106501. pParse->nMem += pTab->nCol;
  106502. /* Start the view context. */
  106503. if( isView ){
  106504. sqlite3AuthContextPush(pParse, &sContext, pTab->zName);
  106505. }
  106506. /* If we are trying to update a view, realize that view into
  106507. ** an ephemeral table.
  106508. */
  106509. #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
  106510. if( isView ){
  106511. sqlite3MaterializeView(pParse, pTab, pWhere, iDataCur);
  106512. }
  106513. #endif
  106514. /* Resolve the column names in all the expressions in the
  106515. ** WHERE clause.
  106516. */
  106517. if( sqlite3ResolveExprNames(&sNC, pWhere) ){
  106518. goto update_cleanup;
  106519. }
  106520. /* Begin the database scan
  106521. */
  106522. if( HasRowid(pTab) ){
  106523. sqlite3VdbeAddOp3(v, OP_Null, 0, regRowSet, regOldRowid);
  106524. pWInfo = sqlite3WhereBegin(
  106525. pParse, pTabList, pWhere, 0, 0, WHERE_ONEPASS_DESIRED, iIdxCur
  106526. );
  106527. if( pWInfo==0 ) goto update_cleanup;
  106528. okOnePass = sqlite3WhereOkOnePass(pWInfo, aiCurOnePass);
  106529. /* Remember the rowid of every item to be updated.
  106530. */
  106531. sqlite3VdbeAddOp2(v, OP_Rowid, iDataCur, regOldRowid);
  106532. if( !okOnePass ){
  106533. sqlite3VdbeAddOp2(v, OP_RowSetAdd, regRowSet, regOldRowid);
  106534. }
  106535. /* End the database scan loop.
  106536. */
  106537. sqlite3WhereEnd(pWInfo);
  106538. }else{
  106539. int iPk; /* First of nPk memory cells holding PRIMARY KEY value */
  106540. i16 nPk; /* Number of components of the PRIMARY KEY */
  106541. int addrOpen; /* Address of the OpenEphemeral instruction */
  106542. assert( pPk!=0 );
  106543. nPk = pPk->nKeyCol;
  106544. iPk = pParse->nMem+1;
  106545. pParse->nMem += nPk;
  106546. regKey = ++pParse->nMem;
  106547. iEph = pParse->nTab++;
  106548. sqlite3VdbeAddOp2(v, OP_Null, 0, iPk);
  106549. addrOpen = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, iEph, nPk);
  106550. sqlite3VdbeSetP4KeyInfo(pParse, pPk);
  106551. pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, 0, 0,
  106552. WHERE_ONEPASS_DESIRED, iIdxCur);
  106553. if( pWInfo==0 ) goto update_cleanup;
  106554. okOnePass = sqlite3WhereOkOnePass(pWInfo, aiCurOnePass);
  106555. for(i=0; i<nPk; i++){
  106556. sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur, pPk->aiColumn[i],
  106557. iPk+i);
  106558. }
  106559. if( okOnePass ){
  106560. sqlite3VdbeChangeToNoop(v, addrOpen);
  106561. nKey = nPk;
  106562. regKey = iPk;
  106563. }else{
  106564. sqlite3VdbeAddOp4(v, OP_MakeRecord, iPk, nPk, regKey,
  106565. sqlite3IndexAffinityStr(v, pPk), nPk);
  106566. sqlite3VdbeAddOp2(v, OP_IdxInsert, iEph, regKey);
  106567. }
  106568. sqlite3WhereEnd(pWInfo);
  106569. }
  106570. /* Initialize the count of updated rows
  106571. */
  106572. if( (db->flags & SQLITE_CountRows) && !pParse->pTriggerTab ){
  106573. regRowCount = ++pParse->nMem;
  106574. sqlite3VdbeAddOp2(v, OP_Integer, 0, regRowCount);
  106575. }
  106576. labelBreak = sqlite3VdbeMakeLabel(v);
  106577. if( !isView ){
  106578. /*
  106579. ** Open every index that needs updating. Note that if any
  106580. ** index could potentially invoke a REPLACE conflict resolution
  106581. ** action, then we need to open all indices because we might need
  106582. ** to be deleting some records.
  106583. */
  106584. if( onError==OE_Replace ){
  106585. memset(aToOpen, 1, nIdx+1);
  106586. }else{
  106587. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  106588. if( pIdx->onError==OE_Replace ){
  106589. memset(aToOpen, 1, nIdx+1);
  106590. break;
  106591. }
  106592. }
  106593. }
  106594. if( okOnePass ){
  106595. if( aiCurOnePass[0]>=0 ) aToOpen[aiCurOnePass[0]-iBaseCur] = 0;
  106596. if( aiCurOnePass[1]>=0 ) aToOpen[aiCurOnePass[1]-iBaseCur] = 0;
  106597. }
  106598. sqlite3OpenTableAndIndices(pParse, pTab, OP_OpenWrite, iBaseCur, aToOpen,
  106599. 0, 0);
  106600. }
  106601. /* Top of the update loop */
  106602. if( okOnePass ){
  106603. if( aToOpen[iDataCur-iBaseCur] && !isView ){
  106604. assert( pPk );
  106605. sqlite3VdbeAddOp4Int(v, OP_NotFound, iDataCur, labelBreak, regKey, nKey);
  106606. VdbeCoverageNeverTaken(v);
  106607. }
  106608. labelContinue = labelBreak;
  106609. sqlite3VdbeAddOp2(v, OP_IsNull, pPk ? regKey : regOldRowid, labelBreak);
  106610. VdbeCoverageIf(v, pPk==0);
  106611. VdbeCoverageIf(v, pPk!=0);
  106612. }else if( pPk ){
  106613. labelContinue = sqlite3VdbeMakeLabel(v);
  106614. sqlite3VdbeAddOp2(v, OP_Rewind, iEph, labelBreak); VdbeCoverage(v);
  106615. addrTop = sqlite3VdbeAddOp2(v, OP_RowKey, iEph, regKey);
  106616. sqlite3VdbeAddOp4Int(v, OP_NotFound, iDataCur, labelContinue, regKey, 0);
  106617. VdbeCoverage(v);
  106618. }else{
  106619. labelContinue = sqlite3VdbeAddOp3(v, OP_RowSetRead, regRowSet, labelBreak,
  106620. regOldRowid);
  106621. VdbeCoverage(v);
  106622. sqlite3VdbeAddOp3(v, OP_NotExists, iDataCur, labelContinue, regOldRowid);
  106623. VdbeCoverage(v);
  106624. }
  106625. /* If the record number will change, set register regNewRowid to
  106626. ** contain the new value. If the record number is not being modified,
  106627. ** then regNewRowid is the same register as regOldRowid, which is
  106628. ** already populated. */
  106629. assert( chngKey || pTrigger || hasFK || regOldRowid==regNewRowid );
  106630. if( chngRowid ){
  106631. sqlite3ExprCode(pParse, pRowidExpr, regNewRowid);
  106632. sqlite3VdbeAddOp1(v, OP_MustBeInt, regNewRowid); VdbeCoverage(v);
  106633. }
  106634. /* Compute the old pre-UPDATE content of the row being changed, if that
  106635. ** information is needed */
  106636. if( chngPk || hasFK || pTrigger ){
  106637. u32 oldmask = (hasFK ? sqlite3FkOldmask(pParse, pTab) : 0);
  106638. oldmask |= sqlite3TriggerColmask(pParse,
  106639. pTrigger, pChanges, 0, TRIGGER_BEFORE|TRIGGER_AFTER, pTab, onError
  106640. );
  106641. for(i=0; i<pTab->nCol; i++){
  106642. if( oldmask==0xffffffff
  106643. || (i<32 && (oldmask & MASKBIT32(i))!=0)
  106644. || (pTab->aCol[i].colFlags & COLFLAG_PRIMKEY)!=0
  106645. ){
  106646. testcase( oldmask!=0xffffffff && i==31 );
  106647. sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur, i, regOld+i);
  106648. }else{
  106649. sqlite3VdbeAddOp2(v, OP_Null, 0, regOld+i);
  106650. }
  106651. }
  106652. if( chngRowid==0 && pPk==0 ){
  106653. sqlite3VdbeAddOp2(v, OP_Copy, regOldRowid, regNewRowid);
  106654. }
  106655. }
  106656. /* Populate the array of registers beginning at regNew with the new
  106657. ** row data. This array is used to check constants, create the new
  106658. ** table and index records, and as the values for any new.* references
  106659. ** made by triggers.
  106660. **
  106661. ** If there are one or more BEFORE triggers, then do not populate the
  106662. ** registers associated with columns that are (a) not modified by
  106663. ** this UPDATE statement and (b) not accessed by new.* references. The
  106664. ** values for registers not modified by the UPDATE must be reloaded from
  106665. ** the database after the BEFORE triggers are fired anyway (as the trigger
  106666. ** may have modified them). So not loading those that are not going to
  106667. ** be used eliminates some redundant opcodes.
  106668. */
  106669. newmask = sqlite3TriggerColmask(
  106670. pParse, pTrigger, pChanges, 1, TRIGGER_BEFORE, pTab, onError
  106671. );
  106672. /*sqlite3VdbeAddOp3(v, OP_Null, 0, regNew, regNew+pTab->nCol-1);*/
  106673. for(i=0; i<pTab->nCol; i++){
  106674. if( i==pTab->iPKey ){
  106675. sqlite3VdbeAddOp2(v, OP_Null, 0, regNew+i);
  106676. }else{
  106677. j = aXRef[i];
  106678. if( j>=0 ){
  106679. sqlite3ExprCode(pParse, pChanges->a[j].pExpr, regNew+i);
  106680. }else if( 0==(tmask&TRIGGER_BEFORE) || i>31 || (newmask & MASKBIT32(i)) ){
  106681. /* This branch loads the value of a column that will not be changed
  106682. ** into a register. This is done if there are no BEFORE triggers, or
  106683. ** if there are one or more BEFORE triggers that use this value via
  106684. ** a new.* reference in a trigger program.
  106685. */
  106686. testcase( i==31 );
  106687. testcase( i==32 );
  106688. sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur, i, regNew+i);
  106689. }else{
  106690. sqlite3VdbeAddOp2(v, OP_Null, 0, regNew+i);
  106691. }
  106692. }
  106693. }
  106694. /* Fire any BEFORE UPDATE triggers. This happens before constraints are
  106695. ** verified. One could argue that this is wrong.
  106696. */
  106697. if( tmask&TRIGGER_BEFORE ){
  106698. sqlite3TableAffinity(v, pTab, regNew);
  106699. sqlite3CodeRowTrigger(pParse, pTrigger, TK_UPDATE, pChanges,
  106700. TRIGGER_BEFORE, pTab, regOldRowid, onError, labelContinue);
  106701. /* The row-trigger may have deleted the row being updated. In this
  106702. ** case, jump to the next row. No updates or AFTER triggers are
  106703. ** required. This behavior - what happens when the row being updated
  106704. ** is deleted or renamed by a BEFORE trigger - is left undefined in the
  106705. ** documentation.
  106706. */
  106707. if( pPk ){
  106708. sqlite3VdbeAddOp4Int(v, OP_NotFound, iDataCur, labelContinue,regKey,nKey);
  106709. VdbeCoverage(v);
  106710. }else{
  106711. sqlite3VdbeAddOp3(v, OP_NotExists, iDataCur, labelContinue, regOldRowid);
  106712. VdbeCoverage(v);
  106713. }
  106714. /* If it did not delete it, the row-trigger may still have modified
  106715. ** some of the columns of the row being updated. Load the values for
  106716. ** all columns not modified by the update statement into their
  106717. ** registers in case this has happened.
  106718. */
  106719. for(i=0; i<pTab->nCol; i++){
  106720. if( aXRef[i]<0 && i!=pTab->iPKey ){
  106721. sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur, i, regNew+i);
  106722. }
  106723. }
  106724. }
  106725. if( !isView ){
  106726. int j1 = 0; /* Address of jump instruction */
  106727. int bReplace = 0; /* True if REPLACE conflict resolution might happen */
  106728. /* Do constraint checks. */
  106729. assert( regOldRowid>0 );
  106730. sqlite3GenerateConstraintChecks(pParse, pTab, aRegIdx, iDataCur, iIdxCur,
  106731. regNewRowid, regOldRowid, chngKey, onError, labelContinue, &bReplace);
  106732. /* Do FK constraint checks. */
  106733. if( hasFK ){
  106734. sqlite3FkCheck(pParse, pTab, regOldRowid, 0, aXRef, chngKey);
  106735. }
  106736. /* Delete the index entries associated with the current record. */
  106737. if( bReplace || chngKey ){
  106738. if( pPk ){
  106739. j1 = sqlite3VdbeAddOp4Int(v, OP_NotFound, iDataCur, 0, regKey, nKey);
  106740. }else{
  106741. j1 = sqlite3VdbeAddOp3(v, OP_NotExists, iDataCur, 0, regOldRowid);
  106742. }
  106743. VdbeCoverageNeverTaken(v);
  106744. }
  106745. sqlite3GenerateRowIndexDelete(pParse, pTab, iDataCur, iIdxCur, aRegIdx);
  106746. /* If changing the record number, delete the old record. */
  106747. if( hasFK || chngKey || pPk!=0 ){
  106748. sqlite3VdbeAddOp2(v, OP_Delete, iDataCur, 0);
  106749. }
  106750. if( bReplace || chngKey ){
  106751. sqlite3VdbeJumpHere(v, j1);
  106752. }
  106753. if( hasFK ){
  106754. sqlite3FkCheck(pParse, pTab, 0, regNewRowid, aXRef, chngKey);
  106755. }
  106756. /* Insert the new index entries and the new record. */
  106757. sqlite3CompleteInsertion(pParse, pTab, iDataCur, iIdxCur,
  106758. regNewRowid, aRegIdx, 1, 0, 0);
  106759. /* Do any ON CASCADE, SET NULL or SET DEFAULT operations required to
  106760. ** handle rows (possibly in other tables) that refer via a foreign key
  106761. ** to the row just updated. */
  106762. if( hasFK ){
  106763. sqlite3FkActions(pParse, pTab, pChanges, regOldRowid, aXRef, chngKey);
  106764. }
  106765. }
  106766. /* Increment the row counter
  106767. */
  106768. if( (db->flags & SQLITE_CountRows) && !pParse->pTriggerTab){
  106769. sqlite3VdbeAddOp2(v, OP_AddImm, regRowCount, 1);
  106770. }
  106771. sqlite3CodeRowTrigger(pParse, pTrigger, TK_UPDATE, pChanges,
  106772. TRIGGER_AFTER, pTab, regOldRowid, onError, labelContinue);
  106773. /* Repeat the above with the next record to be updated, until
  106774. ** all record selected by the WHERE clause have been updated.
  106775. */
  106776. if( okOnePass ){
  106777. /* Nothing to do at end-of-loop for a single-pass */
  106778. }else if( pPk ){
  106779. sqlite3VdbeResolveLabel(v, labelContinue);
  106780. sqlite3VdbeAddOp2(v, OP_Next, iEph, addrTop); VdbeCoverage(v);
  106781. }else{
  106782. sqlite3VdbeAddOp2(v, OP_Goto, 0, labelContinue);
  106783. }
  106784. sqlite3VdbeResolveLabel(v, labelBreak);
  106785. /* Close all tables */
  106786. for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
  106787. assert( aRegIdx );
  106788. if( aToOpen[i+1] ){
  106789. sqlite3VdbeAddOp2(v, OP_Close, iIdxCur+i, 0);
  106790. }
  106791. }
  106792. if( iDataCur<iIdxCur ) sqlite3VdbeAddOp2(v, OP_Close, iDataCur, 0);
  106793. /* Update the sqlite_sequence table by storing the content of the
  106794. ** maximum rowid counter values recorded while inserting into
  106795. ** autoincrement tables.
  106796. */
  106797. if( pParse->nested==0 && pParse->pTriggerTab==0 ){
  106798. sqlite3AutoincrementEnd(pParse);
  106799. }
  106800. /*
  106801. ** Return the number of rows that were changed. If this routine is
  106802. ** generating code because of a call to sqlite3NestedParse(), do not
  106803. ** invoke the callback function.
  106804. */
  106805. if( (db->flags&SQLITE_CountRows) && !pParse->pTriggerTab && !pParse->nested ){
  106806. sqlite3VdbeAddOp2(v, OP_ResultRow, regRowCount, 1);
  106807. sqlite3VdbeSetNumCols(v, 1);
  106808. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows updated", SQLITE_STATIC);
  106809. }
  106810. update_cleanup:
  106811. sqlite3AuthContextPop(&sContext);
  106812. sqlite3DbFree(db, aXRef); /* Also frees aRegIdx[] and aToOpen[] */
  106813. sqlite3SrcListDelete(db, pTabList);
  106814. sqlite3ExprListDelete(db, pChanges);
  106815. sqlite3ExprDelete(db, pWhere);
  106816. return;
  106817. }
  106818. /* Make sure "isView" and other macros defined above are undefined. Otherwise
  106819. ** they may interfere with compilation of other functions in this file
  106820. ** (or in another file, if this file becomes part of the amalgamation). */
  106821. #ifdef isView
  106822. #undef isView
  106823. #endif
  106824. #ifdef pTrigger
  106825. #undef pTrigger
  106826. #endif
  106827. #ifndef SQLITE_OMIT_VIRTUALTABLE
  106828. /*
  106829. ** Generate code for an UPDATE of a virtual table.
  106830. **
  106831. ** The strategy is that we create an ephemeral table that contains
  106832. ** for each row to be changed:
  106833. **
  106834. ** (A) The original rowid of that row.
  106835. ** (B) The revised rowid for the row. (note1)
  106836. ** (C) The content of every column in the row.
  106837. **
  106838. ** Then we loop over this ephemeral table and for each row in
  106839. ** the ephemeral table call VUpdate.
  106840. **
  106841. ** When finished, drop the ephemeral table.
  106842. **
  106843. ** (note1) Actually, if we know in advance that (A) is always the same
  106844. ** as (B) we only store (A), then duplicate (A) when pulling
  106845. ** it out of the ephemeral table before calling VUpdate.
  106846. */
  106847. static void updateVirtualTable(
  106848. Parse *pParse, /* The parsing context */
  106849. SrcList *pSrc, /* The virtual table to be modified */
  106850. Table *pTab, /* The virtual table */
  106851. ExprList *pChanges, /* The columns to change in the UPDATE statement */
  106852. Expr *pRowid, /* Expression used to recompute the rowid */
  106853. int *aXRef, /* Mapping from columns of pTab to entries in pChanges */
  106854. Expr *pWhere, /* WHERE clause of the UPDATE statement */
  106855. int onError /* ON CONFLICT strategy */
  106856. ){
  106857. Vdbe *v = pParse->pVdbe; /* Virtual machine under construction */
  106858. ExprList *pEList = 0; /* The result set of the SELECT statement */
  106859. Select *pSelect = 0; /* The SELECT statement */
  106860. Expr *pExpr; /* Temporary expression */
  106861. int ephemTab; /* Table holding the result of the SELECT */
  106862. int i; /* Loop counter */
  106863. int addr; /* Address of top of loop */
  106864. int iReg; /* First register in set passed to OP_VUpdate */
  106865. sqlite3 *db = pParse->db; /* Database connection */
  106866. const char *pVTab = (const char*)sqlite3GetVTable(db, pTab);
  106867. SelectDest dest;
  106868. /* Construct the SELECT statement that will find the new values for
  106869. ** all updated rows.
  106870. */
  106871. pEList = sqlite3ExprListAppend(pParse, 0, sqlite3Expr(db, TK_ID, "_rowid_"));
  106872. if( pRowid ){
  106873. pEList = sqlite3ExprListAppend(pParse, pEList,
  106874. sqlite3ExprDup(db, pRowid, 0));
  106875. }
  106876. assert( pTab->iPKey<0 );
  106877. for(i=0; i<pTab->nCol; i++){
  106878. if( aXRef[i]>=0 ){
  106879. pExpr = sqlite3ExprDup(db, pChanges->a[aXRef[i]].pExpr, 0);
  106880. }else{
  106881. pExpr = sqlite3Expr(db, TK_ID, pTab->aCol[i].zName);
  106882. }
  106883. pEList = sqlite3ExprListAppend(pParse, pEList, pExpr);
  106884. }
  106885. pSelect = sqlite3SelectNew(pParse, pEList, pSrc, pWhere, 0, 0, 0, 0, 0, 0);
  106886. /* Create the ephemeral table into which the update results will
  106887. ** be stored.
  106888. */
  106889. assert( v );
  106890. ephemTab = pParse->nTab++;
  106891. sqlite3VdbeAddOp2(v, OP_OpenEphemeral, ephemTab, pTab->nCol+1+(pRowid!=0));
  106892. sqlite3VdbeChangeP5(v, BTREE_UNORDERED);
  106893. /* fill the ephemeral table
  106894. */
  106895. sqlite3SelectDestInit(&dest, SRT_Table, ephemTab);
  106896. sqlite3Select(pParse, pSelect, &dest);
  106897. /* Generate code to scan the ephemeral table and call VUpdate. */
  106898. iReg = ++pParse->nMem;
  106899. pParse->nMem += pTab->nCol+1;
  106900. addr = sqlite3VdbeAddOp2(v, OP_Rewind, ephemTab, 0); VdbeCoverage(v);
  106901. sqlite3VdbeAddOp3(v, OP_Column, ephemTab, 0, iReg);
  106902. sqlite3VdbeAddOp3(v, OP_Column, ephemTab, (pRowid?1:0), iReg+1);
  106903. for(i=0; i<pTab->nCol; i++){
  106904. sqlite3VdbeAddOp3(v, OP_Column, ephemTab, i+1+(pRowid!=0), iReg+2+i);
  106905. }
  106906. sqlite3VtabMakeWritable(pParse, pTab);
  106907. sqlite3VdbeAddOp4(v, OP_VUpdate, 0, pTab->nCol+2, iReg, pVTab, P4_VTAB);
  106908. sqlite3VdbeChangeP5(v, onError==OE_Default ? OE_Abort : onError);
  106909. sqlite3MayAbort(pParse);
  106910. sqlite3VdbeAddOp2(v, OP_Next, ephemTab, addr+1); VdbeCoverage(v);
  106911. sqlite3VdbeJumpHere(v, addr);
  106912. sqlite3VdbeAddOp2(v, OP_Close, ephemTab, 0);
  106913. /* Cleanup */
  106914. sqlite3SelectDelete(db, pSelect);
  106915. }
  106916. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  106917. /************** End of update.c **********************************************/
  106918. /************** Begin file vacuum.c ******************************************/
  106919. /*
  106920. ** 2003 April 6
  106921. **
  106922. ** The author disclaims copyright to this source code. In place of
  106923. ** a legal notice, here is a blessing:
  106924. **
  106925. ** May you do good and not evil.
  106926. ** May you find forgiveness for yourself and forgive others.
  106927. ** May you share freely, never taking more than you give.
  106928. **
  106929. *************************************************************************
  106930. ** This file contains code used to implement the VACUUM command.
  106931. **
  106932. ** Most of the code in this file may be omitted by defining the
  106933. ** SQLITE_OMIT_VACUUM macro.
  106934. */
  106935. #if !defined(SQLITE_OMIT_VACUUM) && !defined(SQLITE_OMIT_ATTACH)
  106936. /*
  106937. ** Finalize a prepared statement. If there was an error, store the
  106938. ** text of the error message in *pzErrMsg. Return the result code.
  106939. */
  106940. static int vacuumFinalize(sqlite3 *db, sqlite3_stmt *pStmt, char **pzErrMsg){
  106941. int rc;
  106942. rc = sqlite3VdbeFinalize((Vdbe*)pStmt);
  106943. if( rc ){
  106944. sqlite3SetString(pzErrMsg, db, sqlite3_errmsg(db));
  106945. }
  106946. return rc;
  106947. }
  106948. /*
  106949. ** Execute zSql on database db. Return an error code.
  106950. */
  106951. static int execSql(sqlite3 *db, char **pzErrMsg, const char *zSql){
  106952. sqlite3_stmt *pStmt;
  106953. VVA_ONLY( int rc; )
  106954. if( !zSql ){
  106955. return SQLITE_NOMEM;
  106956. }
  106957. if( SQLITE_OK!=sqlite3_prepare(db, zSql, -1, &pStmt, 0) ){
  106958. sqlite3SetString(pzErrMsg, db, sqlite3_errmsg(db));
  106959. return sqlite3_errcode(db);
  106960. }
  106961. VVA_ONLY( rc = ) sqlite3_step(pStmt);
  106962. assert( rc!=SQLITE_ROW || (db->flags&SQLITE_CountRows) );
  106963. return vacuumFinalize(db, pStmt, pzErrMsg);
  106964. }
  106965. /*
  106966. ** Execute zSql on database db. The statement returns exactly
  106967. ** one column. Execute this as SQL on the same database.
  106968. */
  106969. static int execExecSql(sqlite3 *db, char **pzErrMsg, const char *zSql){
  106970. sqlite3_stmt *pStmt;
  106971. int rc;
  106972. rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
  106973. if( rc!=SQLITE_OK ) return rc;
  106974. while( SQLITE_ROW==sqlite3_step(pStmt) ){
  106975. rc = execSql(db, pzErrMsg, (char*)sqlite3_column_text(pStmt, 0));
  106976. if( rc!=SQLITE_OK ){
  106977. vacuumFinalize(db, pStmt, pzErrMsg);
  106978. return rc;
  106979. }
  106980. }
  106981. return vacuumFinalize(db, pStmt, pzErrMsg);
  106982. }
  106983. /*
  106984. ** The VACUUM command is used to clean up the database,
  106985. ** collapse free space, etc. It is modelled after the VACUUM command
  106986. ** in PostgreSQL. The VACUUM command works as follows:
  106987. **
  106988. ** (1) Create a new transient database file
  106989. ** (2) Copy all content from the database being vacuumed into
  106990. ** the new transient database file
  106991. ** (3) Copy content from the transient database back into the
  106992. ** original database.
  106993. **
  106994. ** The transient database requires temporary disk space approximately
  106995. ** equal to the size of the original database. The copy operation of
  106996. ** step (3) requires additional temporary disk space approximately equal
  106997. ** to the size of the original database for the rollback journal.
  106998. ** Hence, temporary disk space that is approximately 2x the size of the
  106999. ** original database is required. Every page of the database is written
  107000. ** approximately 3 times: Once for step (2) and twice for step (3).
  107001. ** Two writes per page are required in step (3) because the original
  107002. ** database content must be written into the rollback journal prior to
  107003. ** overwriting the database with the vacuumed content.
  107004. **
  107005. ** Only 1x temporary space and only 1x writes would be required if
  107006. ** the copy of step (3) were replaced by deleting the original database
  107007. ** and renaming the transient database as the original. But that will
  107008. ** not work if other processes are attached to the original database.
  107009. ** And a power loss in between deleting the original and renaming the
  107010. ** transient would cause the database file to appear to be deleted
  107011. ** following reboot.
  107012. */
  107013. SQLITE_PRIVATE void sqlite3Vacuum(Parse *pParse){
  107014. Vdbe *v = sqlite3GetVdbe(pParse);
  107015. if( v ){
  107016. sqlite3VdbeAddOp2(v, OP_Vacuum, 0, 0);
  107017. sqlite3VdbeUsesBtree(v, 0);
  107018. }
  107019. return;
  107020. }
  107021. /*
  107022. ** This routine implements the OP_Vacuum opcode of the VDBE.
  107023. */
  107024. SQLITE_PRIVATE int sqlite3RunVacuum(char **pzErrMsg, sqlite3 *db){
  107025. int rc = SQLITE_OK; /* Return code from service routines */
  107026. Btree *pMain; /* The database being vacuumed */
  107027. Btree *pTemp; /* The temporary database we vacuum into */
  107028. char *zSql = 0; /* SQL statements */
  107029. int saved_flags; /* Saved value of the db->flags */
  107030. int saved_nChange; /* Saved value of db->nChange */
  107031. int saved_nTotalChange; /* Saved value of db->nTotalChange */
  107032. void (*saved_xTrace)(void*,const char*); /* Saved db->xTrace */
  107033. Db *pDb = 0; /* Database to detach at end of vacuum */
  107034. int isMemDb; /* True if vacuuming a :memory: database */
  107035. int nRes; /* Bytes of reserved space at the end of each page */
  107036. int nDb; /* Number of attached databases */
  107037. if( !db->autoCommit ){
  107038. sqlite3SetString(pzErrMsg, db, "cannot VACUUM from within a transaction");
  107039. return SQLITE_ERROR;
  107040. }
  107041. if( db->nVdbeActive>1 ){
  107042. sqlite3SetString(pzErrMsg, db,"cannot VACUUM - SQL statements in progress");
  107043. return SQLITE_ERROR;
  107044. }
  107045. /* Save the current value of the database flags so that it can be
  107046. ** restored before returning. Then set the writable-schema flag, and
  107047. ** disable CHECK and foreign key constraints. */
  107048. saved_flags = db->flags;
  107049. saved_nChange = db->nChange;
  107050. saved_nTotalChange = db->nTotalChange;
  107051. saved_xTrace = db->xTrace;
  107052. db->flags |= SQLITE_WriteSchema | SQLITE_IgnoreChecks | SQLITE_PreferBuiltin;
  107053. db->flags &= ~(SQLITE_ForeignKeys | SQLITE_ReverseOrder);
  107054. db->xTrace = 0;
  107055. pMain = db->aDb[0].pBt;
  107056. isMemDb = sqlite3PagerIsMemdb(sqlite3BtreePager(pMain));
  107057. /* Attach the temporary database as 'vacuum_db'. The synchronous pragma
  107058. ** can be set to 'off' for this file, as it is not recovered if a crash
  107059. ** occurs anyway. The integrity of the database is maintained by a
  107060. ** (possibly synchronous) transaction opened on the main database before
  107061. ** sqlite3BtreeCopyFile() is called.
  107062. **
  107063. ** An optimisation would be to use a non-journaled pager.
  107064. ** (Later:) I tried setting "PRAGMA vacuum_db.journal_mode=OFF" but
  107065. ** that actually made the VACUUM run slower. Very little journalling
  107066. ** actually occurs when doing a vacuum since the vacuum_db is initially
  107067. ** empty. Only the journal header is written. Apparently it takes more
  107068. ** time to parse and run the PRAGMA to turn journalling off than it does
  107069. ** to write the journal header file.
  107070. */
  107071. nDb = db->nDb;
  107072. if( sqlite3TempInMemory(db) ){
  107073. zSql = "ATTACH ':memory:' AS vacuum_db;";
  107074. }else{
  107075. zSql = "ATTACH '' AS vacuum_db;";
  107076. }
  107077. rc = execSql(db, pzErrMsg, zSql);
  107078. if( db->nDb>nDb ){
  107079. pDb = &db->aDb[db->nDb-1];
  107080. assert( strcmp(pDb->zName,"vacuum_db")==0 );
  107081. }
  107082. if( rc!=SQLITE_OK ) goto end_of_vacuum;
  107083. pTemp = db->aDb[db->nDb-1].pBt;
  107084. /* The call to execSql() to attach the temp database has left the file
  107085. ** locked (as there was more than one active statement when the transaction
  107086. ** to read the schema was concluded. Unlock it here so that this doesn't
  107087. ** cause problems for the call to BtreeSetPageSize() below. */
  107088. sqlite3BtreeCommit(pTemp);
  107089. nRes = sqlite3BtreeGetOptimalReserve(pMain);
  107090. /* A VACUUM cannot change the pagesize of an encrypted database. */
  107091. #ifdef SQLITE_HAS_CODEC
  107092. if( db->nextPagesize ){
  107093. extern void sqlite3CodecGetKey(sqlite3*, int, void**, int*);
  107094. int nKey;
  107095. char *zKey;
  107096. sqlite3CodecGetKey(db, 0, (void**)&zKey, &nKey);
  107097. if( nKey ) db->nextPagesize = 0;
  107098. }
  107099. #endif
  107100. rc = execSql(db, pzErrMsg, "PRAGMA vacuum_db.synchronous=OFF");
  107101. if( rc!=SQLITE_OK ) goto end_of_vacuum;
  107102. /* Begin a transaction and take an exclusive lock on the main database
  107103. ** file. This is done before the sqlite3BtreeGetPageSize(pMain) call below,
  107104. ** to ensure that we do not try to change the page-size on a WAL database.
  107105. */
  107106. rc = execSql(db, pzErrMsg, "BEGIN;");
  107107. if( rc!=SQLITE_OK ) goto end_of_vacuum;
  107108. rc = sqlite3BtreeBeginTrans(pMain, 2);
  107109. if( rc!=SQLITE_OK ) goto end_of_vacuum;
  107110. /* Do not attempt to change the page size for a WAL database */
  107111. if( sqlite3PagerGetJournalMode(sqlite3BtreePager(pMain))
  107112. ==PAGER_JOURNALMODE_WAL ){
  107113. db->nextPagesize = 0;
  107114. }
  107115. if( sqlite3BtreeSetPageSize(pTemp, sqlite3BtreeGetPageSize(pMain), nRes, 0)
  107116. || (!isMemDb && sqlite3BtreeSetPageSize(pTemp, db->nextPagesize, nRes, 0))
  107117. || NEVER(db->mallocFailed)
  107118. ){
  107119. rc = SQLITE_NOMEM;
  107120. goto end_of_vacuum;
  107121. }
  107122. #ifndef SQLITE_OMIT_AUTOVACUUM
  107123. sqlite3BtreeSetAutoVacuum(pTemp, db->nextAutovac>=0 ? db->nextAutovac :
  107124. sqlite3BtreeGetAutoVacuum(pMain));
  107125. #endif
  107126. /* Query the schema of the main database. Create a mirror schema
  107127. ** in the temporary database.
  107128. */
  107129. rc = execExecSql(db, pzErrMsg,
  107130. "SELECT 'CREATE TABLE vacuum_db.' || substr(sql,14) "
  107131. " FROM sqlite_master WHERE type='table' AND name!='sqlite_sequence'"
  107132. " AND coalesce(rootpage,1)>0"
  107133. );
  107134. if( rc!=SQLITE_OK ) goto end_of_vacuum;
  107135. rc = execExecSql(db, pzErrMsg,
  107136. "SELECT 'CREATE INDEX vacuum_db.' || substr(sql,14)"
  107137. " FROM sqlite_master WHERE sql LIKE 'CREATE INDEX %' ");
  107138. if( rc!=SQLITE_OK ) goto end_of_vacuum;
  107139. rc = execExecSql(db, pzErrMsg,
  107140. "SELECT 'CREATE UNIQUE INDEX vacuum_db.' || substr(sql,21) "
  107141. " FROM sqlite_master WHERE sql LIKE 'CREATE UNIQUE INDEX %'");
  107142. if( rc!=SQLITE_OK ) goto end_of_vacuum;
  107143. /* Loop through the tables in the main database. For each, do
  107144. ** an "INSERT INTO vacuum_db.xxx SELECT * FROM main.xxx;" to copy
  107145. ** the contents to the temporary database.
  107146. */
  107147. assert( (db->flags & SQLITE_Vacuum)==0 );
  107148. db->flags |= SQLITE_Vacuum;
  107149. rc = execExecSql(db, pzErrMsg,
  107150. "SELECT 'INSERT INTO vacuum_db.' || quote(name) "
  107151. "|| ' SELECT * FROM main.' || quote(name) || ';'"
  107152. "FROM main.sqlite_master "
  107153. "WHERE type = 'table' AND name!='sqlite_sequence' "
  107154. " AND coalesce(rootpage,1)>0"
  107155. );
  107156. assert( (db->flags & SQLITE_Vacuum)!=0 );
  107157. db->flags &= ~SQLITE_Vacuum;
  107158. if( rc!=SQLITE_OK ) goto end_of_vacuum;
  107159. /* Copy over the sequence table
  107160. */
  107161. rc = execExecSql(db, pzErrMsg,
  107162. "SELECT 'DELETE FROM vacuum_db.' || quote(name) || ';' "
  107163. "FROM vacuum_db.sqlite_master WHERE name='sqlite_sequence' "
  107164. );
  107165. if( rc!=SQLITE_OK ) goto end_of_vacuum;
  107166. rc = execExecSql(db, pzErrMsg,
  107167. "SELECT 'INSERT INTO vacuum_db.' || quote(name) "
  107168. "|| ' SELECT * FROM main.' || quote(name) || ';' "
  107169. "FROM vacuum_db.sqlite_master WHERE name=='sqlite_sequence';"
  107170. );
  107171. if( rc!=SQLITE_OK ) goto end_of_vacuum;
  107172. /* Copy the triggers, views, and virtual tables from the main database
  107173. ** over to the temporary database. None of these objects has any
  107174. ** associated storage, so all we have to do is copy their entries
  107175. ** from the SQLITE_MASTER table.
  107176. */
  107177. rc = execSql(db, pzErrMsg,
  107178. "INSERT INTO vacuum_db.sqlite_master "
  107179. " SELECT type, name, tbl_name, rootpage, sql"
  107180. " FROM main.sqlite_master"
  107181. " WHERE type='view' OR type='trigger'"
  107182. " OR (type='table' AND rootpage=0)"
  107183. );
  107184. if( rc ) goto end_of_vacuum;
  107185. /* At this point, there is a write transaction open on both the
  107186. ** vacuum database and the main database. Assuming no error occurs,
  107187. ** both transactions are closed by this block - the main database
  107188. ** transaction by sqlite3BtreeCopyFile() and the other by an explicit
  107189. ** call to sqlite3BtreeCommit().
  107190. */
  107191. {
  107192. u32 meta;
  107193. int i;
  107194. /* This array determines which meta meta values are preserved in the
  107195. ** vacuum. Even entries are the meta value number and odd entries
  107196. ** are an increment to apply to the meta value after the vacuum.
  107197. ** The increment is used to increase the schema cookie so that other
  107198. ** connections to the same database will know to reread the schema.
  107199. */
  107200. static const unsigned char aCopy[] = {
  107201. BTREE_SCHEMA_VERSION, 1, /* Add one to the old schema cookie */
  107202. BTREE_DEFAULT_CACHE_SIZE, 0, /* Preserve the default page cache size */
  107203. BTREE_TEXT_ENCODING, 0, /* Preserve the text encoding */
  107204. BTREE_USER_VERSION, 0, /* Preserve the user version */
  107205. BTREE_APPLICATION_ID, 0, /* Preserve the application id */
  107206. };
  107207. assert( 1==sqlite3BtreeIsInTrans(pTemp) );
  107208. assert( 1==sqlite3BtreeIsInTrans(pMain) );
  107209. /* Copy Btree meta values */
  107210. for(i=0; i<ArraySize(aCopy); i+=2){
  107211. /* GetMeta() and UpdateMeta() cannot fail in this context because
  107212. ** we already have page 1 loaded into cache and marked dirty. */
  107213. sqlite3BtreeGetMeta(pMain, aCopy[i], &meta);
  107214. rc = sqlite3BtreeUpdateMeta(pTemp, aCopy[i], meta+aCopy[i+1]);
  107215. if( NEVER(rc!=SQLITE_OK) ) goto end_of_vacuum;
  107216. }
  107217. rc = sqlite3BtreeCopyFile(pMain, pTemp);
  107218. if( rc!=SQLITE_OK ) goto end_of_vacuum;
  107219. rc = sqlite3BtreeCommit(pTemp);
  107220. if( rc!=SQLITE_OK ) goto end_of_vacuum;
  107221. #ifndef SQLITE_OMIT_AUTOVACUUM
  107222. sqlite3BtreeSetAutoVacuum(pMain, sqlite3BtreeGetAutoVacuum(pTemp));
  107223. #endif
  107224. }
  107225. assert( rc==SQLITE_OK );
  107226. rc = sqlite3BtreeSetPageSize(pMain, sqlite3BtreeGetPageSize(pTemp), nRes,1);
  107227. end_of_vacuum:
  107228. /* Restore the original value of db->flags */
  107229. db->flags = saved_flags;
  107230. db->nChange = saved_nChange;
  107231. db->nTotalChange = saved_nTotalChange;
  107232. db->xTrace = saved_xTrace;
  107233. sqlite3BtreeSetPageSize(pMain, -1, -1, 1);
  107234. /* Currently there is an SQL level transaction open on the vacuum
  107235. ** database. No locks are held on any other files (since the main file
  107236. ** was committed at the btree level). So it safe to end the transaction
  107237. ** by manually setting the autoCommit flag to true and detaching the
  107238. ** vacuum database. The vacuum_db journal file is deleted when the pager
  107239. ** is closed by the DETACH.
  107240. */
  107241. db->autoCommit = 1;
  107242. if( pDb ){
  107243. sqlite3BtreeClose(pDb->pBt);
  107244. pDb->pBt = 0;
  107245. pDb->pSchema = 0;
  107246. }
  107247. /* This both clears the schemas and reduces the size of the db->aDb[]
  107248. ** array. */
  107249. sqlite3ResetAllSchemasOfConnection(db);
  107250. return rc;
  107251. }
  107252. #endif /* SQLITE_OMIT_VACUUM && SQLITE_OMIT_ATTACH */
  107253. /************** End of vacuum.c **********************************************/
  107254. /************** Begin file vtab.c ********************************************/
  107255. /*
  107256. ** 2006 June 10
  107257. **
  107258. ** The author disclaims copyright to this source code. In place of
  107259. ** a legal notice, here is a blessing:
  107260. **
  107261. ** May you do good and not evil.
  107262. ** May you find forgiveness for yourself and forgive others.
  107263. ** May you share freely, never taking more than you give.
  107264. **
  107265. *************************************************************************
  107266. ** This file contains code used to help implement virtual tables.
  107267. */
  107268. #ifndef SQLITE_OMIT_VIRTUALTABLE
  107269. /*
  107270. ** Before a virtual table xCreate() or xConnect() method is invoked, the
  107271. ** sqlite3.pVtabCtx member variable is set to point to an instance of
  107272. ** this struct allocated on the stack. It is used by the implementation of
  107273. ** the sqlite3_declare_vtab() and sqlite3_vtab_config() APIs, both of which
  107274. ** are invoked only from within xCreate and xConnect methods.
  107275. */
  107276. struct VtabCtx {
  107277. VTable *pVTable; /* The virtual table being constructed */
  107278. Table *pTab; /* The Table object to which the virtual table belongs */
  107279. VtabCtx *pPrior; /* Parent context (if any) */
  107280. int bDeclared; /* True after sqlite3_declare_vtab() is called */
  107281. };
  107282. /*
  107283. ** The actual function that does the work of creating a new module.
  107284. ** This function implements the sqlite3_create_module() and
  107285. ** sqlite3_create_module_v2() interfaces.
  107286. */
  107287. static int createModule(
  107288. sqlite3 *db, /* Database in which module is registered */
  107289. const char *zName, /* Name assigned to this module */
  107290. const sqlite3_module *pModule, /* The definition of the module */
  107291. void *pAux, /* Context pointer for xCreate/xConnect */
  107292. void (*xDestroy)(void *) /* Module destructor function */
  107293. ){
  107294. int rc = SQLITE_OK;
  107295. int nName;
  107296. sqlite3_mutex_enter(db->mutex);
  107297. nName = sqlite3Strlen30(zName);
  107298. if( sqlite3HashFind(&db->aModule, zName) ){
  107299. rc = SQLITE_MISUSE_BKPT;
  107300. }else{
  107301. Module *pMod;
  107302. pMod = (Module *)sqlite3DbMallocRaw(db, sizeof(Module) + nName + 1);
  107303. if( pMod ){
  107304. Module *pDel;
  107305. char *zCopy = (char *)(&pMod[1]);
  107306. memcpy(zCopy, zName, nName+1);
  107307. pMod->zName = zCopy;
  107308. pMod->pModule = pModule;
  107309. pMod->pAux = pAux;
  107310. pMod->xDestroy = xDestroy;
  107311. pDel = (Module *)sqlite3HashInsert(&db->aModule,zCopy,(void*)pMod);
  107312. assert( pDel==0 || pDel==pMod );
  107313. if( pDel ){
  107314. db->mallocFailed = 1;
  107315. sqlite3DbFree(db, pDel);
  107316. }
  107317. }
  107318. }
  107319. rc = sqlite3ApiExit(db, rc);
  107320. if( rc!=SQLITE_OK && xDestroy ) xDestroy(pAux);
  107321. sqlite3_mutex_leave(db->mutex);
  107322. return rc;
  107323. }
  107324. /*
  107325. ** External API function used to create a new virtual-table module.
  107326. */
  107327. SQLITE_API int SQLITE_STDCALL sqlite3_create_module(
  107328. sqlite3 *db, /* Database in which module is registered */
  107329. const char *zName, /* Name assigned to this module */
  107330. const sqlite3_module *pModule, /* The definition of the module */
  107331. void *pAux /* Context pointer for xCreate/xConnect */
  107332. ){
  107333. #ifdef SQLITE_ENABLE_API_ARMOR
  107334. if( !sqlite3SafetyCheckOk(db) || zName==0 ) return SQLITE_MISUSE_BKPT;
  107335. #endif
  107336. return createModule(db, zName, pModule, pAux, 0);
  107337. }
  107338. /*
  107339. ** External API function used to create a new virtual-table module.
  107340. */
  107341. SQLITE_API int SQLITE_STDCALL sqlite3_create_module_v2(
  107342. sqlite3 *db, /* Database in which module is registered */
  107343. const char *zName, /* Name assigned to this module */
  107344. const sqlite3_module *pModule, /* The definition of the module */
  107345. void *pAux, /* Context pointer for xCreate/xConnect */
  107346. void (*xDestroy)(void *) /* Module destructor function */
  107347. ){
  107348. #ifdef SQLITE_ENABLE_API_ARMOR
  107349. if( !sqlite3SafetyCheckOk(db) || zName==0 ) return SQLITE_MISUSE_BKPT;
  107350. #endif
  107351. return createModule(db, zName, pModule, pAux, xDestroy);
  107352. }
  107353. /*
  107354. ** Lock the virtual table so that it cannot be disconnected.
  107355. ** Locks nest. Every lock should have a corresponding unlock.
  107356. ** If an unlock is omitted, resources leaks will occur.
  107357. **
  107358. ** If a disconnect is attempted while a virtual table is locked,
  107359. ** the disconnect is deferred until all locks have been removed.
  107360. */
  107361. SQLITE_PRIVATE void sqlite3VtabLock(VTable *pVTab){
  107362. pVTab->nRef++;
  107363. }
  107364. /*
  107365. ** pTab is a pointer to a Table structure representing a virtual-table.
  107366. ** Return a pointer to the VTable object used by connection db to access
  107367. ** this virtual-table, if one has been created, or NULL otherwise.
  107368. */
  107369. SQLITE_PRIVATE VTable *sqlite3GetVTable(sqlite3 *db, Table *pTab){
  107370. VTable *pVtab;
  107371. assert( IsVirtual(pTab) );
  107372. for(pVtab=pTab->pVTable; pVtab && pVtab->db!=db; pVtab=pVtab->pNext);
  107373. return pVtab;
  107374. }
  107375. /*
  107376. ** Decrement the ref-count on a virtual table object. When the ref-count
  107377. ** reaches zero, call the xDisconnect() method to delete the object.
  107378. */
  107379. SQLITE_PRIVATE void sqlite3VtabUnlock(VTable *pVTab){
  107380. sqlite3 *db = pVTab->db;
  107381. assert( db );
  107382. assert( pVTab->nRef>0 );
  107383. assert( db->magic==SQLITE_MAGIC_OPEN || db->magic==SQLITE_MAGIC_ZOMBIE );
  107384. pVTab->nRef--;
  107385. if( pVTab->nRef==0 ){
  107386. sqlite3_vtab *p = pVTab->pVtab;
  107387. if( p ){
  107388. p->pModule->xDisconnect(p);
  107389. }
  107390. sqlite3DbFree(db, pVTab);
  107391. }
  107392. }
  107393. /*
  107394. ** Table p is a virtual table. This function moves all elements in the
  107395. ** p->pVTable list to the sqlite3.pDisconnect lists of their associated
  107396. ** database connections to be disconnected at the next opportunity.
  107397. ** Except, if argument db is not NULL, then the entry associated with
  107398. ** connection db is left in the p->pVTable list.
  107399. */
  107400. static VTable *vtabDisconnectAll(sqlite3 *db, Table *p){
  107401. VTable *pRet = 0;
  107402. VTable *pVTable = p->pVTable;
  107403. p->pVTable = 0;
  107404. /* Assert that the mutex (if any) associated with the BtShared database
  107405. ** that contains table p is held by the caller. See header comments
  107406. ** above function sqlite3VtabUnlockList() for an explanation of why
  107407. ** this makes it safe to access the sqlite3.pDisconnect list of any
  107408. ** database connection that may have an entry in the p->pVTable list.
  107409. */
  107410. assert( db==0 || sqlite3SchemaMutexHeld(db, 0, p->pSchema) );
  107411. while( pVTable ){
  107412. sqlite3 *db2 = pVTable->db;
  107413. VTable *pNext = pVTable->pNext;
  107414. assert( db2 );
  107415. if( db2==db ){
  107416. pRet = pVTable;
  107417. p->pVTable = pRet;
  107418. pRet->pNext = 0;
  107419. }else{
  107420. pVTable->pNext = db2->pDisconnect;
  107421. db2->pDisconnect = pVTable;
  107422. }
  107423. pVTable = pNext;
  107424. }
  107425. assert( !db || pRet );
  107426. return pRet;
  107427. }
  107428. /*
  107429. ** Table *p is a virtual table. This function removes the VTable object
  107430. ** for table *p associated with database connection db from the linked
  107431. ** list in p->pVTab. It also decrements the VTable ref count. This is
  107432. ** used when closing database connection db to free all of its VTable
  107433. ** objects without disturbing the rest of the Schema object (which may
  107434. ** be being used by other shared-cache connections).
  107435. */
  107436. SQLITE_PRIVATE void sqlite3VtabDisconnect(sqlite3 *db, Table *p){
  107437. VTable **ppVTab;
  107438. assert( IsVirtual(p) );
  107439. assert( sqlite3BtreeHoldsAllMutexes(db) );
  107440. assert( sqlite3_mutex_held(db->mutex) );
  107441. for(ppVTab=&p->pVTable; *ppVTab; ppVTab=&(*ppVTab)->pNext){
  107442. if( (*ppVTab)->db==db ){
  107443. VTable *pVTab = *ppVTab;
  107444. *ppVTab = pVTab->pNext;
  107445. sqlite3VtabUnlock(pVTab);
  107446. break;
  107447. }
  107448. }
  107449. }
  107450. /*
  107451. ** Disconnect all the virtual table objects in the sqlite3.pDisconnect list.
  107452. **
  107453. ** This function may only be called when the mutexes associated with all
  107454. ** shared b-tree databases opened using connection db are held by the
  107455. ** caller. This is done to protect the sqlite3.pDisconnect list. The
  107456. ** sqlite3.pDisconnect list is accessed only as follows:
  107457. **
  107458. ** 1) By this function. In this case, all BtShared mutexes and the mutex
  107459. ** associated with the database handle itself must be held.
  107460. **
  107461. ** 2) By function vtabDisconnectAll(), when it adds a VTable entry to
  107462. ** the sqlite3.pDisconnect list. In this case either the BtShared mutex
  107463. ** associated with the database the virtual table is stored in is held
  107464. ** or, if the virtual table is stored in a non-sharable database, then
  107465. ** the database handle mutex is held.
  107466. **
  107467. ** As a result, a sqlite3.pDisconnect cannot be accessed simultaneously
  107468. ** by multiple threads. It is thread-safe.
  107469. */
  107470. SQLITE_PRIVATE void sqlite3VtabUnlockList(sqlite3 *db){
  107471. VTable *p = db->pDisconnect;
  107472. db->pDisconnect = 0;
  107473. assert( sqlite3BtreeHoldsAllMutexes(db) );
  107474. assert( sqlite3_mutex_held(db->mutex) );
  107475. if( p ){
  107476. sqlite3ExpirePreparedStatements(db);
  107477. do {
  107478. VTable *pNext = p->pNext;
  107479. sqlite3VtabUnlock(p);
  107480. p = pNext;
  107481. }while( p );
  107482. }
  107483. }
  107484. /*
  107485. ** Clear any and all virtual-table information from the Table record.
  107486. ** This routine is called, for example, just before deleting the Table
  107487. ** record.
  107488. **
  107489. ** Since it is a virtual-table, the Table structure contains a pointer
  107490. ** to the head of a linked list of VTable structures. Each VTable
  107491. ** structure is associated with a single sqlite3* user of the schema.
  107492. ** The reference count of the VTable structure associated with database
  107493. ** connection db is decremented immediately (which may lead to the
  107494. ** structure being xDisconnected and free). Any other VTable structures
  107495. ** in the list are moved to the sqlite3.pDisconnect list of the associated
  107496. ** database connection.
  107497. */
  107498. SQLITE_PRIVATE void sqlite3VtabClear(sqlite3 *db, Table *p){
  107499. if( !db || db->pnBytesFreed==0 ) vtabDisconnectAll(0, p);
  107500. if( p->azModuleArg ){
  107501. int i;
  107502. for(i=0; i<p->nModuleArg; i++){
  107503. if( i!=1 ) sqlite3DbFree(db, p->azModuleArg[i]);
  107504. }
  107505. sqlite3DbFree(db, p->azModuleArg);
  107506. }
  107507. }
  107508. /*
  107509. ** Add a new module argument to pTable->azModuleArg[].
  107510. ** The string is not copied - the pointer is stored. The
  107511. ** string will be freed automatically when the table is
  107512. ** deleted.
  107513. */
  107514. static void addModuleArgument(sqlite3 *db, Table *pTable, char *zArg){
  107515. int i = pTable->nModuleArg++;
  107516. int nBytes = sizeof(char *)*(1+pTable->nModuleArg);
  107517. char **azModuleArg;
  107518. azModuleArg = sqlite3DbRealloc(db, pTable->azModuleArg, nBytes);
  107519. if( azModuleArg==0 ){
  107520. int j;
  107521. for(j=0; j<i; j++){
  107522. sqlite3DbFree(db, pTable->azModuleArg[j]);
  107523. }
  107524. sqlite3DbFree(db, zArg);
  107525. sqlite3DbFree(db, pTable->azModuleArg);
  107526. pTable->nModuleArg = 0;
  107527. }else{
  107528. azModuleArg[i] = zArg;
  107529. azModuleArg[i+1] = 0;
  107530. }
  107531. pTable->azModuleArg = azModuleArg;
  107532. }
  107533. /*
  107534. ** The parser calls this routine when it first sees a CREATE VIRTUAL TABLE
  107535. ** statement. The module name has been parsed, but the optional list
  107536. ** of parameters that follow the module name are still pending.
  107537. */
  107538. SQLITE_PRIVATE void sqlite3VtabBeginParse(
  107539. Parse *pParse, /* Parsing context */
  107540. Token *pName1, /* Name of new table, or database name */
  107541. Token *pName2, /* Name of new table or NULL */
  107542. Token *pModuleName, /* Name of the module for the virtual table */
  107543. int ifNotExists /* No error if the table already exists */
  107544. ){
  107545. int iDb; /* The database the table is being created in */
  107546. Table *pTable; /* The new virtual table */
  107547. sqlite3 *db; /* Database connection */
  107548. sqlite3StartTable(pParse, pName1, pName2, 0, 0, 1, ifNotExists);
  107549. pTable = pParse->pNewTable;
  107550. if( pTable==0 ) return;
  107551. assert( 0==pTable->pIndex );
  107552. db = pParse->db;
  107553. iDb = sqlite3SchemaToIndex(db, pTable->pSchema);
  107554. assert( iDb>=0 );
  107555. pTable->tabFlags |= TF_Virtual;
  107556. pTable->nModuleArg = 0;
  107557. addModuleArgument(db, pTable, sqlite3NameFromToken(db, pModuleName));
  107558. addModuleArgument(db, pTable, 0);
  107559. addModuleArgument(db, pTable, sqlite3DbStrDup(db, pTable->zName));
  107560. assert( (pParse->sNameToken.z==pName2->z && pName2->z!=0)
  107561. || (pParse->sNameToken.z==pName1->z && pName2->z==0)
  107562. );
  107563. pParse->sNameToken.n = (int)(
  107564. &pModuleName->z[pModuleName->n] - pParse->sNameToken.z
  107565. );
  107566. #ifndef SQLITE_OMIT_AUTHORIZATION
  107567. /* Creating a virtual table invokes the authorization callback twice.
  107568. ** The first invocation, to obtain permission to INSERT a row into the
  107569. ** sqlite_master table, has already been made by sqlite3StartTable().
  107570. ** The second call, to obtain permission to create the table, is made now.
  107571. */
  107572. if( pTable->azModuleArg ){
  107573. sqlite3AuthCheck(pParse, SQLITE_CREATE_VTABLE, pTable->zName,
  107574. pTable->azModuleArg[0], pParse->db->aDb[iDb].zName);
  107575. }
  107576. #endif
  107577. }
  107578. /*
  107579. ** This routine takes the module argument that has been accumulating
  107580. ** in pParse->zArg[] and appends it to the list of arguments on the
  107581. ** virtual table currently under construction in pParse->pTable.
  107582. */
  107583. static void addArgumentToVtab(Parse *pParse){
  107584. if( pParse->sArg.z && pParse->pNewTable ){
  107585. const char *z = (const char*)pParse->sArg.z;
  107586. int n = pParse->sArg.n;
  107587. sqlite3 *db = pParse->db;
  107588. addModuleArgument(db, pParse->pNewTable, sqlite3DbStrNDup(db, z, n));
  107589. }
  107590. }
  107591. /*
  107592. ** The parser calls this routine after the CREATE VIRTUAL TABLE statement
  107593. ** has been completely parsed.
  107594. */
  107595. SQLITE_PRIVATE void sqlite3VtabFinishParse(Parse *pParse, Token *pEnd){
  107596. Table *pTab = pParse->pNewTable; /* The table being constructed */
  107597. sqlite3 *db = pParse->db; /* The database connection */
  107598. if( pTab==0 ) return;
  107599. addArgumentToVtab(pParse);
  107600. pParse->sArg.z = 0;
  107601. if( pTab->nModuleArg<1 ) return;
  107602. /* If the CREATE VIRTUAL TABLE statement is being entered for the
  107603. ** first time (in other words if the virtual table is actually being
  107604. ** created now instead of just being read out of sqlite_master) then
  107605. ** do additional initialization work and store the statement text
  107606. ** in the sqlite_master table.
  107607. */
  107608. if( !db->init.busy ){
  107609. char *zStmt;
  107610. char *zWhere;
  107611. int iDb;
  107612. int iReg;
  107613. Vdbe *v;
  107614. /* Compute the complete text of the CREATE VIRTUAL TABLE statement */
  107615. if( pEnd ){
  107616. pParse->sNameToken.n = (int)(pEnd->z - pParse->sNameToken.z) + pEnd->n;
  107617. }
  107618. zStmt = sqlite3MPrintf(db, "CREATE VIRTUAL TABLE %T", &pParse->sNameToken);
  107619. /* A slot for the record has already been allocated in the
  107620. ** SQLITE_MASTER table. We just need to update that slot with all
  107621. ** the information we've collected.
  107622. **
  107623. ** The VM register number pParse->regRowid holds the rowid of an
  107624. ** entry in the sqlite_master table tht was created for this vtab
  107625. ** by sqlite3StartTable().
  107626. */
  107627. iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  107628. sqlite3NestedParse(pParse,
  107629. "UPDATE %Q.%s "
  107630. "SET type='table', name=%Q, tbl_name=%Q, rootpage=0, sql=%Q "
  107631. "WHERE rowid=#%d",
  107632. db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
  107633. pTab->zName,
  107634. pTab->zName,
  107635. zStmt,
  107636. pParse->regRowid
  107637. );
  107638. sqlite3DbFree(db, zStmt);
  107639. v = sqlite3GetVdbe(pParse);
  107640. sqlite3ChangeCookie(pParse, iDb);
  107641. sqlite3VdbeAddOp2(v, OP_Expire, 0, 0);
  107642. zWhere = sqlite3MPrintf(db, "name='%q' AND type='table'", pTab->zName);
  107643. sqlite3VdbeAddParseSchemaOp(v, iDb, zWhere);
  107644. iReg = ++pParse->nMem;
  107645. sqlite3VdbeAddOp4(v, OP_String8, 0, iReg, 0, pTab->zName, 0);
  107646. sqlite3VdbeAddOp2(v, OP_VCreate, iDb, iReg);
  107647. }
  107648. /* If we are rereading the sqlite_master table create the in-memory
  107649. ** record of the table. The xConnect() method is not called until
  107650. ** the first time the virtual table is used in an SQL statement. This
  107651. ** allows a schema that contains virtual tables to be loaded before
  107652. ** the required virtual table implementations are registered. */
  107653. else {
  107654. Table *pOld;
  107655. Schema *pSchema = pTab->pSchema;
  107656. const char *zName = pTab->zName;
  107657. assert( sqlite3SchemaMutexHeld(db, 0, pSchema) );
  107658. pOld = sqlite3HashInsert(&pSchema->tblHash, zName, pTab);
  107659. if( pOld ){
  107660. db->mallocFailed = 1;
  107661. assert( pTab==pOld ); /* Malloc must have failed inside HashInsert() */
  107662. return;
  107663. }
  107664. pParse->pNewTable = 0;
  107665. }
  107666. }
  107667. /*
  107668. ** The parser calls this routine when it sees the first token
  107669. ** of an argument to the module name in a CREATE VIRTUAL TABLE statement.
  107670. */
  107671. SQLITE_PRIVATE void sqlite3VtabArgInit(Parse *pParse){
  107672. addArgumentToVtab(pParse);
  107673. pParse->sArg.z = 0;
  107674. pParse->sArg.n = 0;
  107675. }
  107676. /*
  107677. ** The parser calls this routine for each token after the first token
  107678. ** in an argument to the module name in a CREATE VIRTUAL TABLE statement.
  107679. */
  107680. SQLITE_PRIVATE void sqlite3VtabArgExtend(Parse *pParse, Token *p){
  107681. Token *pArg = &pParse->sArg;
  107682. if( pArg->z==0 ){
  107683. pArg->z = p->z;
  107684. pArg->n = p->n;
  107685. }else{
  107686. assert(pArg->z <= p->z);
  107687. pArg->n = (int)(&p->z[p->n] - pArg->z);
  107688. }
  107689. }
  107690. /*
  107691. ** Invoke a virtual table constructor (either xCreate or xConnect). The
  107692. ** pointer to the function to invoke is passed as the fourth parameter
  107693. ** to this procedure.
  107694. */
  107695. static int vtabCallConstructor(
  107696. sqlite3 *db,
  107697. Table *pTab,
  107698. Module *pMod,
  107699. int (*xConstruct)(sqlite3*,void*,int,const char*const*,sqlite3_vtab**,char**),
  107700. char **pzErr
  107701. ){
  107702. VtabCtx sCtx;
  107703. VTable *pVTable;
  107704. int rc;
  107705. const char *const*azArg = (const char *const*)pTab->azModuleArg;
  107706. int nArg = pTab->nModuleArg;
  107707. char *zErr = 0;
  107708. char *zModuleName;
  107709. int iDb;
  107710. VtabCtx *pCtx;
  107711. /* Check that the virtual-table is not already being initialized */
  107712. for(pCtx=db->pVtabCtx; pCtx; pCtx=pCtx->pPrior){
  107713. if( pCtx->pTab==pTab ){
  107714. *pzErr = sqlite3MPrintf(db,
  107715. "vtable constructor called recursively: %s", pTab->zName
  107716. );
  107717. return SQLITE_LOCKED;
  107718. }
  107719. }
  107720. zModuleName = sqlite3MPrintf(db, "%s", pTab->zName);
  107721. if( !zModuleName ){
  107722. return SQLITE_NOMEM;
  107723. }
  107724. pVTable = sqlite3DbMallocZero(db, sizeof(VTable));
  107725. if( !pVTable ){
  107726. sqlite3DbFree(db, zModuleName);
  107727. return SQLITE_NOMEM;
  107728. }
  107729. pVTable->db = db;
  107730. pVTable->pMod = pMod;
  107731. iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  107732. pTab->azModuleArg[1] = db->aDb[iDb].zName;
  107733. /* Invoke the virtual table constructor */
  107734. assert( &db->pVtabCtx );
  107735. assert( xConstruct );
  107736. sCtx.pTab = pTab;
  107737. sCtx.pVTable = pVTable;
  107738. sCtx.pPrior = db->pVtabCtx;
  107739. sCtx.bDeclared = 0;
  107740. db->pVtabCtx = &sCtx;
  107741. rc = xConstruct(db, pMod->pAux, nArg, azArg, &pVTable->pVtab, &zErr);
  107742. db->pVtabCtx = sCtx.pPrior;
  107743. if( rc==SQLITE_NOMEM ) db->mallocFailed = 1;
  107744. assert( sCtx.pTab==pTab );
  107745. if( SQLITE_OK!=rc ){
  107746. if( zErr==0 ){
  107747. *pzErr = sqlite3MPrintf(db, "vtable constructor failed: %s", zModuleName);
  107748. }else {
  107749. *pzErr = sqlite3MPrintf(db, "%s", zErr);
  107750. sqlite3_free(zErr);
  107751. }
  107752. sqlite3DbFree(db, pVTable);
  107753. }else if( ALWAYS(pVTable->pVtab) ){
  107754. /* Justification of ALWAYS(): A correct vtab constructor must allocate
  107755. ** the sqlite3_vtab object if successful. */
  107756. memset(pVTable->pVtab, 0, sizeof(pVTable->pVtab[0]));
  107757. pVTable->pVtab->pModule = pMod->pModule;
  107758. pVTable->nRef = 1;
  107759. if( sCtx.bDeclared==0 ){
  107760. const char *zFormat = "vtable constructor did not declare schema: %s";
  107761. *pzErr = sqlite3MPrintf(db, zFormat, pTab->zName);
  107762. sqlite3VtabUnlock(pVTable);
  107763. rc = SQLITE_ERROR;
  107764. }else{
  107765. int iCol;
  107766. u8 oooHidden = 0;
  107767. /* If everything went according to plan, link the new VTable structure
  107768. ** into the linked list headed by pTab->pVTable. Then loop through the
  107769. ** columns of the table to see if any of them contain the token "hidden".
  107770. ** If so, set the Column COLFLAG_HIDDEN flag and remove the token from
  107771. ** the type string. */
  107772. pVTable->pNext = pTab->pVTable;
  107773. pTab->pVTable = pVTable;
  107774. for(iCol=0; iCol<pTab->nCol; iCol++){
  107775. char *zType = pTab->aCol[iCol].zType;
  107776. int nType;
  107777. int i = 0;
  107778. if( !zType ){
  107779. pTab->tabFlags |= oooHidden;
  107780. continue;
  107781. }
  107782. nType = sqlite3Strlen30(zType);
  107783. if( sqlite3StrNICmp("hidden", zType, 6)||(zType[6] && zType[6]!=' ') ){
  107784. for(i=0; i<nType; i++){
  107785. if( (0==sqlite3StrNICmp(" hidden", &zType[i], 7))
  107786. && (zType[i+7]=='\0' || zType[i+7]==' ')
  107787. ){
  107788. i++;
  107789. break;
  107790. }
  107791. }
  107792. }
  107793. if( i<nType ){
  107794. int j;
  107795. int nDel = 6 + (zType[i+6] ? 1 : 0);
  107796. for(j=i; (j+nDel)<=nType; j++){
  107797. zType[j] = zType[j+nDel];
  107798. }
  107799. if( zType[i]=='\0' && i>0 ){
  107800. assert(zType[i-1]==' ');
  107801. zType[i-1] = '\0';
  107802. }
  107803. pTab->aCol[iCol].colFlags |= COLFLAG_HIDDEN;
  107804. oooHidden = TF_OOOHidden;
  107805. }else{
  107806. pTab->tabFlags |= oooHidden;
  107807. }
  107808. }
  107809. }
  107810. }
  107811. sqlite3DbFree(db, zModuleName);
  107812. return rc;
  107813. }
  107814. /*
  107815. ** This function is invoked by the parser to call the xConnect() method
  107816. ** of the virtual table pTab. If an error occurs, an error code is returned
  107817. ** and an error left in pParse.
  107818. **
  107819. ** This call is a no-op if table pTab is not a virtual table.
  107820. */
  107821. SQLITE_PRIVATE int sqlite3VtabCallConnect(Parse *pParse, Table *pTab){
  107822. sqlite3 *db = pParse->db;
  107823. const char *zMod;
  107824. Module *pMod;
  107825. int rc;
  107826. assert( pTab );
  107827. if( (pTab->tabFlags & TF_Virtual)==0 || sqlite3GetVTable(db, pTab) ){
  107828. return SQLITE_OK;
  107829. }
  107830. /* Locate the required virtual table module */
  107831. zMod = pTab->azModuleArg[0];
  107832. pMod = (Module*)sqlite3HashFind(&db->aModule, zMod);
  107833. if( !pMod ){
  107834. const char *zModule = pTab->azModuleArg[0];
  107835. sqlite3ErrorMsg(pParse, "no such module: %s", zModule);
  107836. rc = SQLITE_ERROR;
  107837. }else{
  107838. char *zErr = 0;
  107839. rc = vtabCallConstructor(db, pTab, pMod, pMod->pModule->xConnect, &zErr);
  107840. if( rc!=SQLITE_OK ){
  107841. sqlite3ErrorMsg(pParse, "%s", zErr);
  107842. }
  107843. sqlite3DbFree(db, zErr);
  107844. }
  107845. return rc;
  107846. }
  107847. /*
  107848. ** Grow the db->aVTrans[] array so that there is room for at least one
  107849. ** more v-table. Return SQLITE_NOMEM if a malloc fails, or SQLITE_OK otherwise.
  107850. */
  107851. static int growVTrans(sqlite3 *db){
  107852. const int ARRAY_INCR = 5;
  107853. /* Grow the sqlite3.aVTrans array if required */
  107854. if( (db->nVTrans%ARRAY_INCR)==0 ){
  107855. VTable **aVTrans;
  107856. int nBytes = sizeof(sqlite3_vtab *) * (db->nVTrans + ARRAY_INCR);
  107857. aVTrans = sqlite3DbRealloc(db, (void *)db->aVTrans, nBytes);
  107858. if( !aVTrans ){
  107859. return SQLITE_NOMEM;
  107860. }
  107861. memset(&aVTrans[db->nVTrans], 0, sizeof(sqlite3_vtab *)*ARRAY_INCR);
  107862. db->aVTrans = aVTrans;
  107863. }
  107864. return SQLITE_OK;
  107865. }
  107866. /*
  107867. ** Add the virtual table pVTab to the array sqlite3.aVTrans[]. Space should
  107868. ** have already been reserved using growVTrans().
  107869. */
  107870. static void addToVTrans(sqlite3 *db, VTable *pVTab){
  107871. /* Add pVtab to the end of sqlite3.aVTrans */
  107872. db->aVTrans[db->nVTrans++] = pVTab;
  107873. sqlite3VtabLock(pVTab);
  107874. }
  107875. /*
  107876. ** This function is invoked by the vdbe to call the xCreate method
  107877. ** of the virtual table named zTab in database iDb.
  107878. **
  107879. ** If an error occurs, *pzErr is set to point an an English language
  107880. ** description of the error and an SQLITE_XXX error code is returned.
  107881. ** In this case the caller must call sqlite3DbFree(db, ) on *pzErr.
  107882. */
  107883. SQLITE_PRIVATE int sqlite3VtabCallCreate(sqlite3 *db, int iDb, const char *zTab, char **pzErr){
  107884. int rc = SQLITE_OK;
  107885. Table *pTab;
  107886. Module *pMod;
  107887. const char *zMod;
  107888. pTab = sqlite3FindTable(db, zTab, db->aDb[iDb].zName);
  107889. assert( pTab && (pTab->tabFlags & TF_Virtual)!=0 && !pTab->pVTable );
  107890. /* Locate the required virtual table module */
  107891. zMod = pTab->azModuleArg[0];
  107892. pMod = (Module*)sqlite3HashFind(&db->aModule, zMod);
  107893. /* If the module has been registered and includes a Create method,
  107894. ** invoke it now. If the module has not been registered, return an
  107895. ** error. Otherwise, do nothing.
  107896. */
  107897. if( !pMod ){
  107898. *pzErr = sqlite3MPrintf(db, "no such module: %s", zMod);
  107899. rc = SQLITE_ERROR;
  107900. }else{
  107901. rc = vtabCallConstructor(db, pTab, pMod, pMod->pModule->xCreate, pzErr);
  107902. }
  107903. /* Justification of ALWAYS(): The xConstructor method is required to
  107904. ** create a valid sqlite3_vtab if it returns SQLITE_OK. */
  107905. if( rc==SQLITE_OK && ALWAYS(sqlite3GetVTable(db, pTab)) ){
  107906. rc = growVTrans(db);
  107907. if( rc==SQLITE_OK ){
  107908. addToVTrans(db, sqlite3GetVTable(db, pTab));
  107909. }
  107910. }
  107911. return rc;
  107912. }
  107913. /*
  107914. ** This function is used to set the schema of a virtual table. It is only
  107915. ** valid to call this function from within the xCreate() or xConnect() of a
  107916. ** virtual table module.
  107917. */
  107918. SQLITE_API int SQLITE_STDCALL sqlite3_declare_vtab(sqlite3 *db, const char *zCreateTable){
  107919. VtabCtx *pCtx;
  107920. Parse *pParse;
  107921. int rc = SQLITE_OK;
  107922. Table *pTab;
  107923. char *zErr = 0;
  107924. #ifdef SQLITE_ENABLE_API_ARMOR
  107925. if( !sqlite3SafetyCheckOk(db) || zCreateTable==0 ){
  107926. return SQLITE_MISUSE_BKPT;
  107927. }
  107928. #endif
  107929. sqlite3_mutex_enter(db->mutex);
  107930. pCtx = db->pVtabCtx;
  107931. if( !pCtx || pCtx->bDeclared ){
  107932. sqlite3Error(db, SQLITE_MISUSE);
  107933. sqlite3_mutex_leave(db->mutex);
  107934. return SQLITE_MISUSE_BKPT;
  107935. }
  107936. pTab = pCtx->pTab;
  107937. assert( (pTab->tabFlags & TF_Virtual)!=0 );
  107938. pParse = sqlite3StackAllocZero(db, sizeof(*pParse));
  107939. if( pParse==0 ){
  107940. rc = SQLITE_NOMEM;
  107941. }else{
  107942. pParse->declareVtab = 1;
  107943. pParse->db = db;
  107944. pParse->nQueryLoop = 1;
  107945. if( SQLITE_OK==sqlite3RunParser(pParse, zCreateTable, &zErr)
  107946. && pParse->pNewTable
  107947. && !db->mallocFailed
  107948. && !pParse->pNewTable->pSelect
  107949. && (pParse->pNewTable->tabFlags & TF_Virtual)==0
  107950. ){
  107951. if( !pTab->aCol ){
  107952. pTab->aCol = pParse->pNewTable->aCol;
  107953. pTab->nCol = pParse->pNewTable->nCol;
  107954. pParse->pNewTable->nCol = 0;
  107955. pParse->pNewTable->aCol = 0;
  107956. }
  107957. pCtx->bDeclared = 1;
  107958. }else{
  107959. sqlite3ErrorWithMsg(db, SQLITE_ERROR, (zErr ? "%s" : 0), zErr);
  107960. sqlite3DbFree(db, zErr);
  107961. rc = SQLITE_ERROR;
  107962. }
  107963. pParse->declareVtab = 0;
  107964. if( pParse->pVdbe ){
  107965. sqlite3VdbeFinalize(pParse->pVdbe);
  107966. }
  107967. sqlite3DeleteTable(db, pParse->pNewTable);
  107968. sqlite3ParserReset(pParse);
  107969. sqlite3StackFree(db, pParse);
  107970. }
  107971. assert( (rc&0xff)==rc );
  107972. rc = sqlite3ApiExit(db, rc);
  107973. sqlite3_mutex_leave(db->mutex);
  107974. return rc;
  107975. }
  107976. /*
  107977. ** This function is invoked by the vdbe to call the xDestroy method
  107978. ** of the virtual table named zTab in database iDb. This occurs
  107979. ** when a DROP TABLE is mentioned.
  107980. **
  107981. ** This call is a no-op if zTab is not a virtual table.
  107982. */
  107983. SQLITE_PRIVATE int sqlite3VtabCallDestroy(sqlite3 *db, int iDb, const char *zTab){
  107984. int rc = SQLITE_OK;
  107985. Table *pTab;
  107986. pTab = sqlite3FindTable(db, zTab, db->aDb[iDb].zName);
  107987. if( ALWAYS(pTab!=0 && pTab->pVTable!=0) ){
  107988. VTable *p;
  107989. for(p=pTab->pVTable; p; p=p->pNext){
  107990. assert( p->pVtab );
  107991. if( p->pVtab->nRef>0 ){
  107992. return SQLITE_LOCKED;
  107993. }
  107994. }
  107995. p = vtabDisconnectAll(db, pTab);
  107996. rc = p->pMod->pModule->xDestroy(p->pVtab);
  107997. /* Remove the sqlite3_vtab* from the aVTrans[] array, if applicable */
  107998. if( rc==SQLITE_OK ){
  107999. assert( pTab->pVTable==p && p->pNext==0 );
  108000. p->pVtab = 0;
  108001. pTab->pVTable = 0;
  108002. sqlite3VtabUnlock(p);
  108003. }
  108004. }
  108005. return rc;
  108006. }
  108007. /*
  108008. ** This function invokes either the xRollback or xCommit method
  108009. ** of each of the virtual tables in the sqlite3.aVTrans array. The method
  108010. ** called is identified by the second argument, "offset", which is
  108011. ** the offset of the method to call in the sqlite3_module structure.
  108012. **
  108013. ** The array is cleared after invoking the callbacks.
  108014. */
  108015. static void callFinaliser(sqlite3 *db, int offset){
  108016. int i;
  108017. if( db->aVTrans ){
  108018. for(i=0; i<db->nVTrans; i++){
  108019. VTable *pVTab = db->aVTrans[i];
  108020. sqlite3_vtab *p = pVTab->pVtab;
  108021. if( p ){
  108022. int (*x)(sqlite3_vtab *);
  108023. x = *(int (**)(sqlite3_vtab *))((char *)p->pModule + offset);
  108024. if( x ) x(p);
  108025. }
  108026. pVTab->iSavepoint = 0;
  108027. sqlite3VtabUnlock(pVTab);
  108028. }
  108029. sqlite3DbFree(db, db->aVTrans);
  108030. db->nVTrans = 0;
  108031. db->aVTrans = 0;
  108032. }
  108033. }
  108034. /*
  108035. ** Invoke the xSync method of all virtual tables in the sqlite3.aVTrans
  108036. ** array. Return the error code for the first error that occurs, or
  108037. ** SQLITE_OK if all xSync operations are successful.
  108038. **
  108039. ** If an error message is available, leave it in p->zErrMsg.
  108040. */
  108041. SQLITE_PRIVATE int sqlite3VtabSync(sqlite3 *db, Vdbe *p){
  108042. int i;
  108043. int rc = SQLITE_OK;
  108044. VTable **aVTrans = db->aVTrans;
  108045. db->aVTrans = 0;
  108046. for(i=0; rc==SQLITE_OK && i<db->nVTrans; i++){
  108047. int (*x)(sqlite3_vtab *);
  108048. sqlite3_vtab *pVtab = aVTrans[i]->pVtab;
  108049. if( pVtab && (x = pVtab->pModule->xSync)!=0 ){
  108050. rc = x(pVtab);
  108051. sqlite3VtabImportErrmsg(p, pVtab);
  108052. }
  108053. }
  108054. db->aVTrans = aVTrans;
  108055. return rc;
  108056. }
  108057. /*
  108058. ** Invoke the xRollback method of all virtual tables in the
  108059. ** sqlite3.aVTrans array. Then clear the array itself.
  108060. */
  108061. SQLITE_PRIVATE int sqlite3VtabRollback(sqlite3 *db){
  108062. callFinaliser(db, offsetof(sqlite3_module,xRollback));
  108063. return SQLITE_OK;
  108064. }
  108065. /*
  108066. ** Invoke the xCommit method of all virtual tables in the
  108067. ** sqlite3.aVTrans array. Then clear the array itself.
  108068. */
  108069. SQLITE_PRIVATE int sqlite3VtabCommit(sqlite3 *db){
  108070. callFinaliser(db, offsetof(sqlite3_module,xCommit));
  108071. return SQLITE_OK;
  108072. }
  108073. /*
  108074. ** If the virtual table pVtab supports the transaction interface
  108075. ** (xBegin/xRollback/xCommit and optionally xSync) and a transaction is
  108076. ** not currently open, invoke the xBegin method now.
  108077. **
  108078. ** If the xBegin call is successful, place the sqlite3_vtab pointer
  108079. ** in the sqlite3.aVTrans array.
  108080. */
  108081. SQLITE_PRIVATE int sqlite3VtabBegin(sqlite3 *db, VTable *pVTab){
  108082. int rc = SQLITE_OK;
  108083. const sqlite3_module *pModule;
  108084. /* Special case: If db->aVTrans is NULL and db->nVTrans is greater
  108085. ** than zero, then this function is being called from within a
  108086. ** virtual module xSync() callback. It is illegal to write to
  108087. ** virtual module tables in this case, so return SQLITE_LOCKED.
  108088. */
  108089. if( sqlite3VtabInSync(db) ){
  108090. return SQLITE_LOCKED;
  108091. }
  108092. if( !pVTab ){
  108093. return SQLITE_OK;
  108094. }
  108095. pModule = pVTab->pVtab->pModule;
  108096. if( pModule->xBegin ){
  108097. int i;
  108098. /* If pVtab is already in the aVTrans array, return early */
  108099. for(i=0; i<db->nVTrans; i++){
  108100. if( db->aVTrans[i]==pVTab ){
  108101. return SQLITE_OK;
  108102. }
  108103. }
  108104. /* Invoke the xBegin method. If successful, add the vtab to the
  108105. ** sqlite3.aVTrans[] array. */
  108106. rc = growVTrans(db);
  108107. if( rc==SQLITE_OK ){
  108108. rc = pModule->xBegin(pVTab->pVtab);
  108109. if( rc==SQLITE_OK ){
  108110. addToVTrans(db, pVTab);
  108111. }
  108112. }
  108113. }
  108114. return rc;
  108115. }
  108116. /*
  108117. ** Invoke either the xSavepoint, xRollbackTo or xRelease method of all
  108118. ** virtual tables that currently have an open transaction. Pass iSavepoint
  108119. ** as the second argument to the virtual table method invoked.
  108120. **
  108121. ** If op is SAVEPOINT_BEGIN, the xSavepoint method is invoked. If it is
  108122. ** SAVEPOINT_ROLLBACK, the xRollbackTo method. Otherwise, if op is
  108123. ** SAVEPOINT_RELEASE, then the xRelease method of each virtual table with
  108124. ** an open transaction is invoked.
  108125. **
  108126. ** If any virtual table method returns an error code other than SQLITE_OK,
  108127. ** processing is abandoned and the error returned to the caller of this
  108128. ** function immediately. If all calls to virtual table methods are successful,
  108129. ** SQLITE_OK is returned.
  108130. */
  108131. SQLITE_PRIVATE int sqlite3VtabSavepoint(sqlite3 *db, int op, int iSavepoint){
  108132. int rc = SQLITE_OK;
  108133. assert( op==SAVEPOINT_RELEASE||op==SAVEPOINT_ROLLBACK||op==SAVEPOINT_BEGIN );
  108134. assert( iSavepoint>=-1 );
  108135. if( db->aVTrans ){
  108136. int i;
  108137. for(i=0; rc==SQLITE_OK && i<db->nVTrans; i++){
  108138. VTable *pVTab = db->aVTrans[i];
  108139. const sqlite3_module *pMod = pVTab->pMod->pModule;
  108140. if( pVTab->pVtab && pMod->iVersion>=2 ){
  108141. int (*xMethod)(sqlite3_vtab *, int);
  108142. switch( op ){
  108143. case SAVEPOINT_BEGIN:
  108144. xMethod = pMod->xSavepoint;
  108145. pVTab->iSavepoint = iSavepoint+1;
  108146. break;
  108147. case SAVEPOINT_ROLLBACK:
  108148. xMethod = pMod->xRollbackTo;
  108149. break;
  108150. default:
  108151. xMethod = pMod->xRelease;
  108152. break;
  108153. }
  108154. if( xMethod && pVTab->iSavepoint>iSavepoint ){
  108155. rc = xMethod(pVTab->pVtab, iSavepoint);
  108156. }
  108157. }
  108158. }
  108159. }
  108160. return rc;
  108161. }
  108162. /*
  108163. ** The first parameter (pDef) is a function implementation. The
  108164. ** second parameter (pExpr) is the first argument to this function.
  108165. ** If pExpr is a column in a virtual table, then let the virtual
  108166. ** table implementation have an opportunity to overload the function.
  108167. **
  108168. ** This routine is used to allow virtual table implementations to
  108169. ** overload MATCH, LIKE, GLOB, and REGEXP operators.
  108170. **
  108171. ** Return either the pDef argument (indicating no change) or a
  108172. ** new FuncDef structure that is marked as ephemeral using the
  108173. ** SQLITE_FUNC_EPHEM flag.
  108174. */
  108175. SQLITE_PRIVATE FuncDef *sqlite3VtabOverloadFunction(
  108176. sqlite3 *db, /* Database connection for reporting malloc problems */
  108177. FuncDef *pDef, /* Function to possibly overload */
  108178. int nArg, /* Number of arguments to the function */
  108179. Expr *pExpr /* First argument to the function */
  108180. ){
  108181. Table *pTab;
  108182. sqlite3_vtab *pVtab;
  108183. sqlite3_module *pMod;
  108184. void (*xFunc)(sqlite3_context*,int,sqlite3_value**) = 0;
  108185. void *pArg = 0;
  108186. FuncDef *pNew;
  108187. int rc = 0;
  108188. char *zLowerName;
  108189. unsigned char *z;
  108190. /* Check to see the left operand is a column in a virtual table */
  108191. if( NEVER(pExpr==0) ) return pDef;
  108192. if( pExpr->op!=TK_COLUMN ) return pDef;
  108193. pTab = pExpr->pTab;
  108194. if( NEVER(pTab==0) ) return pDef;
  108195. if( (pTab->tabFlags & TF_Virtual)==0 ) return pDef;
  108196. pVtab = sqlite3GetVTable(db, pTab)->pVtab;
  108197. assert( pVtab!=0 );
  108198. assert( pVtab->pModule!=0 );
  108199. pMod = (sqlite3_module *)pVtab->pModule;
  108200. if( pMod->xFindFunction==0 ) return pDef;
  108201. /* Call the xFindFunction method on the virtual table implementation
  108202. ** to see if the implementation wants to overload this function
  108203. */
  108204. zLowerName = sqlite3DbStrDup(db, pDef->zName);
  108205. if( zLowerName ){
  108206. for(z=(unsigned char*)zLowerName; *z; z++){
  108207. *z = sqlite3UpperToLower[*z];
  108208. }
  108209. rc = pMod->xFindFunction(pVtab, nArg, zLowerName, &xFunc, &pArg);
  108210. sqlite3DbFree(db, zLowerName);
  108211. }
  108212. if( rc==0 ){
  108213. return pDef;
  108214. }
  108215. /* Create a new ephemeral function definition for the overloaded
  108216. ** function */
  108217. pNew = sqlite3DbMallocZero(db, sizeof(*pNew)
  108218. + sqlite3Strlen30(pDef->zName) + 1);
  108219. if( pNew==0 ){
  108220. return pDef;
  108221. }
  108222. *pNew = *pDef;
  108223. pNew->zName = (char *)&pNew[1];
  108224. memcpy(pNew->zName, pDef->zName, sqlite3Strlen30(pDef->zName)+1);
  108225. pNew->xFunc = xFunc;
  108226. pNew->pUserData = pArg;
  108227. pNew->funcFlags |= SQLITE_FUNC_EPHEM;
  108228. return pNew;
  108229. }
  108230. /*
  108231. ** Make sure virtual table pTab is contained in the pParse->apVirtualLock[]
  108232. ** array so that an OP_VBegin will get generated for it. Add pTab to the
  108233. ** array if it is missing. If pTab is already in the array, this routine
  108234. ** is a no-op.
  108235. */
  108236. SQLITE_PRIVATE void sqlite3VtabMakeWritable(Parse *pParse, Table *pTab){
  108237. Parse *pToplevel = sqlite3ParseToplevel(pParse);
  108238. int i, n;
  108239. Table **apVtabLock;
  108240. assert( IsVirtual(pTab) );
  108241. for(i=0; i<pToplevel->nVtabLock; i++){
  108242. if( pTab==pToplevel->apVtabLock[i] ) return;
  108243. }
  108244. n = (pToplevel->nVtabLock+1)*sizeof(pToplevel->apVtabLock[0]);
  108245. apVtabLock = sqlite3_realloc64(pToplevel->apVtabLock, n);
  108246. if( apVtabLock ){
  108247. pToplevel->apVtabLock = apVtabLock;
  108248. pToplevel->apVtabLock[pToplevel->nVtabLock++] = pTab;
  108249. }else{
  108250. pToplevel->db->mallocFailed = 1;
  108251. }
  108252. }
  108253. /*
  108254. ** Return the ON CONFLICT resolution mode in effect for the virtual
  108255. ** table update operation currently in progress.
  108256. **
  108257. ** The results of this routine are undefined unless it is called from
  108258. ** within an xUpdate method.
  108259. */
  108260. SQLITE_API int SQLITE_STDCALL sqlite3_vtab_on_conflict(sqlite3 *db){
  108261. static const unsigned char aMap[] = {
  108262. SQLITE_ROLLBACK, SQLITE_ABORT, SQLITE_FAIL, SQLITE_IGNORE, SQLITE_REPLACE
  108263. };
  108264. #ifdef SQLITE_ENABLE_API_ARMOR
  108265. if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
  108266. #endif
  108267. assert( OE_Rollback==1 && OE_Abort==2 && OE_Fail==3 );
  108268. assert( OE_Ignore==4 && OE_Replace==5 );
  108269. assert( db->vtabOnConflict>=1 && db->vtabOnConflict<=5 );
  108270. return (int)aMap[db->vtabOnConflict-1];
  108271. }
  108272. /*
  108273. ** Call from within the xCreate() or xConnect() methods to provide
  108274. ** the SQLite core with additional information about the behavior
  108275. ** of the virtual table being implemented.
  108276. */
  108277. SQLITE_API int SQLITE_CDECL sqlite3_vtab_config(sqlite3 *db, int op, ...){
  108278. va_list ap;
  108279. int rc = SQLITE_OK;
  108280. #ifdef SQLITE_ENABLE_API_ARMOR
  108281. if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
  108282. #endif
  108283. sqlite3_mutex_enter(db->mutex);
  108284. va_start(ap, op);
  108285. switch( op ){
  108286. case SQLITE_VTAB_CONSTRAINT_SUPPORT: {
  108287. VtabCtx *p = db->pVtabCtx;
  108288. if( !p ){
  108289. rc = SQLITE_MISUSE_BKPT;
  108290. }else{
  108291. assert( p->pTab==0 || (p->pTab->tabFlags & TF_Virtual)!=0 );
  108292. p->pVTable->bConstraint = (u8)va_arg(ap, int);
  108293. }
  108294. break;
  108295. }
  108296. default:
  108297. rc = SQLITE_MISUSE_BKPT;
  108298. break;
  108299. }
  108300. va_end(ap);
  108301. if( rc!=SQLITE_OK ) sqlite3Error(db, rc);
  108302. sqlite3_mutex_leave(db->mutex);
  108303. return rc;
  108304. }
  108305. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  108306. /************** End of vtab.c ************************************************/
  108307. /************** Begin file where.c *******************************************/
  108308. /*
  108309. ** 2001 September 15
  108310. **
  108311. ** The author disclaims copyright to this source code. In place of
  108312. ** a legal notice, here is a blessing:
  108313. **
  108314. ** May you do good and not evil.
  108315. ** May you find forgiveness for yourself and forgive others.
  108316. ** May you share freely, never taking more than you give.
  108317. **
  108318. *************************************************************************
  108319. ** This module contains C code that generates VDBE code used to process
  108320. ** the WHERE clause of SQL statements. This module is responsible for
  108321. ** generating the code that loops through a table looking for applicable
  108322. ** rows. Indices are selected and used to speed the search when doing
  108323. ** so is applicable. Because this module is responsible for selecting
  108324. ** indices, you might also think of this module as the "query optimizer".
  108325. */
  108326. /************** Include whereInt.h in the middle of where.c ******************/
  108327. /************** Begin file whereInt.h ****************************************/
  108328. /*
  108329. ** 2013-11-12
  108330. **
  108331. ** The author disclaims copyright to this source code. In place of
  108332. ** a legal notice, here is a blessing:
  108333. **
  108334. ** May you do good and not evil.
  108335. ** May you find forgiveness for yourself and forgive others.
  108336. ** May you share freely, never taking more than you give.
  108337. **
  108338. *************************************************************************
  108339. **
  108340. ** This file contains structure and macro definitions for the query
  108341. ** planner logic in "where.c". These definitions are broken out into
  108342. ** a separate source file for easier editing.
  108343. */
  108344. /*
  108345. ** Trace output macros
  108346. */
  108347. #if defined(SQLITE_TEST) || defined(SQLITE_DEBUG)
  108348. /***/ int sqlite3WhereTrace = 0;
  108349. #endif
  108350. #if defined(SQLITE_DEBUG) \
  108351. && (defined(SQLITE_TEST) || defined(SQLITE_ENABLE_WHERETRACE))
  108352. # define WHERETRACE(K,X) if(sqlite3WhereTrace&(K)) sqlite3DebugPrintf X
  108353. # define WHERETRACE_ENABLED 1
  108354. #else
  108355. # define WHERETRACE(K,X)
  108356. #endif
  108357. /* Forward references
  108358. */
  108359. typedef struct WhereClause WhereClause;
  108360. typedef struct WhereMaskSet WhereMaskSet;
  108361. typedef struct WhereOrInfo WhereOrInfo;
  108362. typedef struct WhereAndInfo WhereAndInfo;
  108363. typedef struct WhereLevel WhereLevel;
  108364. typedef struct WhereLoop WhereLoop;
  108365. typedef struct WherePath WherePath;
  108366. typedef struct WhereTerm WhereTerm;
  108367. typedef struct WhereLoopBuilder WhereLoopBuilder;
  108368. typedef struct WhereScan WhereScan;
  108369. typedef struct WhereOrCost WhereOrCost;
  108370. typedef struct WhereOrSet WhereOrSet;
  108371. /*
  108372. ** This object contains information needed to implement a single nested
  108373. ** loop in WHERE clause.
  108374. **
  108375. ** Contrast this object with WhereLoop. This object describes the
  108376. ** implementation of the loop. WhereLoop describes the algorithm.
  108377. ** This object contains a pointer to the WhereLoop algorithm as one of
  108378. ** its elements.
  108379. **
  108380. ** The WhereInfo object contains a single instance of this object for
  108381. ** each term in the FROM clause (which is to say, for each of the
  108382. ** nested loops as implemented). The order of WhereLevel objects determines
  108383. ** the loop nested order, with WhereInfo.a[0] being the outer loop and
  108384. ** WhereInfo.a[WhereInfo.nLevel-1] being the inner loop.
  108385. */
  108386. struct WhereLevel {
  108387. int iLeftJoin; /* Memory cell used to implement LEFT OUTER JOIN */
  108388. int iTabCur; /* The VDBE cursor used to access the table */
  108389. int iIdxCur; /* The VDBE cursor used to access pIdx */
  108390. int addrBrk; /* Jump here to break out of the loop */
  108391. int addrNxt; /* Jump here to start the next IN combination */
  108392. int addrSkip; /* Jump here for next iteration of skip-scan */
  108393. int addrCont; /* Jump here to continue with the next loop cycle */
  108394. int addrFirst; /* First instruction of interior of the loop */
  108395. int addrBody; /* Beginning of the body of this loop */
  108396. int iLikeRepCntr; /* LIKE range processing counter register */
  108397. int addrLikeRep; /* LIKE range processing address */
  108398. u8 iFrom; /* Which entry in the FROM clause */
  108399. u8 op, p3, p5; /* Opcode, P3 & P5 of the opcode that ends the loop */
  108400. int p1, p2; /* Operands of the opcode used to ends the loop */
  108401. union { /* Information that depends on pWLoop->wsFlags */
  108402. struct {
  108403. int nIn; /* Number of entries in aInLoop[] */
  108404. struct InLoop {
  108405. int iCur; /* The VDBE cursor used by this IN operator */
  108406. int addrInTop; /* Top of the IN loop */
  108407. u8 eEndLoopOp; /* IN Loop terminator. OP_Next or OP_Prev */
  108408. } *aInLoop; /* Information about each nested IN operator */
  108409. } in; /* Used when pWLoop->wsFlags&WHERE_IN_ABLE */
  108410. Index *pCovidx; /* Possible covering index for WHERE_MULTI_OR */
  108411. } u;
  108412. struct WhereLoop *pWLoop; /* The selected WhereLoop object */
  108413. Bitmask notReady; /* FROM entries not usable at this level */
  108414. #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
  108415. int addrVisit; /* Address at which row is visited */
  108416. #endif
  108417. };
  108418. /*
  108419. ** Each instance of this object represents an algorithm for evaluating one
  108420. ** term of a join. Every term of the FROM clause will have at least
  108421. ** one corresponding WhereLoop object (unless INDEXED BY constraints
  108422. ** prevent a query solution - which is an error) and many terms of the
  108423. ** FROM clause will have multiple WhereLoop objects, each describing a
  108424. ** potential way of implementing that FROM-clause term, together with
  108425. ** dependencies and cost estimates for using the chosen algorithm.
  108426. **
  108427. ** Query planning consists of building up a collection of these WhereLoop
  108428. ** objects, then computing a particular sequence of WhereLoop objects, with
  108429. ** one WhereLoop object per FROM clause term, that satisfy all dependencies
  108430. ** and that minimize the overall cost.
  108431. */
  108432. struct WhereLoop {
  108433. Bitmask prereq; /* Bitmask of other loops that must run first */
  108434. Bitmask maskSelf; /* Bitmask identifying table iTab */
  108435. #ifdef SQLITE_DEBUG
  108436. char cId; /* Symbolic ID of this loop for debugging use */
  108437. #endif
  108438. u8 iTab; /* Position in FROM clause of table for this loop */
  108439. u8 iSortIdx; /* Sorting index number. 0==None */
  108440. LogEst rSetup; /* One-time setup cost (ex: create transient index) */
  108441. LogEst rRun; /* Cost of running each loop */
  108442. LogEst nOut; /* Estimated number of output rows */
  108443. union {
  108444. struct { /* Information for internal btree tables */
  108445. u16 nEq; /* Number of equality constraints */
  108446. Index *pIndex; /* Index used, or NULL */
  108447. } btree;
  108448. struct { /* Information for virtual tables */
  108449. int idxNum; /* Index number */
  108450. u8 needFree; /* True if sqlite3_free(idxStr) is needed */
  108451. i8 isOrdered; /* True if satisfies ORDER BY */
  108452. u16 omitMask; /* Terms that may be omitted */
  108453. char *idxStr; /* Index identifier string */
  108454. } vtab;
  108455. } u;
  108456. u32 wsFlags; /* WHERE_* flags describing the plan */
  108457. u16 nLTerm; /* Number of entries in aLTerm[] */
  108458. u16 nSkip; /* Number of NULL aLTerm[] entries */
  108459. /**** whereLoopXfer() copies fields above ***********************/
  108460. # define WHERE_LOOP_XFER_SZ offsetof(WhereLoop,nLSlot)
  108461. u16 nLSlot; /* Number of slots allocated for aLTerm[] */
  108462. WhereTerm **aLTerm; /* WhereTerms used */
  108463. WhereLoop *pNextLoop; /* Next WhereLoop object in the WhereClause */
  108464. WhereTerm *aLTermSpace[3]; /* Initial aLTerm[] space */
  108465. };
  108466. /* This object holds the prerequisites and the cost of running a
  108467. ** subquery on one operand of an OR operator in the WHERE clause.
  108468. ** See WhereOrSet for additional information
  108469. */
  108470. struct WhereOrCost {
  108471. Bitmask prereq; /* Prerequisites */
  108472. LogEst rRun; /* Cost of running this subquery */
  108473. LogEst nOut; /* Number of outputs for this subquery */
  108474. };
  108475. /* The WhereOrSet object holds a set of possible WhereOrCosts that
  108476. ** correspond to the subquery(s) of OR-clause processing. Only the
  108477. ** best N_OR_COST elements are retained.
  108478. */
  108479. #define N_OR_COST 3
  108480. struct WhereOrSet {
  108481. u16 n; /* Number of valid a[] entries */
  108482. WhereOrCost a[N_OR_COST]; /* Set of best costs */
  108483. };
  108484. /* Forward declaration of methods */
  108485. static int whereLoopResize(sqlite3*, WhereLoop*, int);
  108486. /*
  108487. ** Each instance of this object holds a sequence of WhereLoop objects
  108488. ** that implement some or all of a query plan.
  108489. **
  108490. ** Think of each WhereLoop object as a node in a graph with arcs
  108491. ** showing dependencies and costs for travelling between nodes. (That is
  108492. ** not a completely accurate description because WhereLoop costs are a
  108493. ** vector, not a scalar, and because dependencies are many-to-one, not
  108494. ** one-to-one as are graph nodes. But it is a useful visualization aid.)
  108495. ** Then a WherePath object is a path through the graph that visits some
  108496. ** or all of the WhereLoop objects once.
  108497. **
  108498. ** The "solver" works by creating the N best WherePath objects of length
  108499. ** 1. Then using those as a basis to compute the N best WherePath objects
  108500. ** of length 2. And so forth until the length of WherePaths equals the
  108501. ** number of nodes in the FROM clause. The best (lowest cost) WherePath
  108502. ** at the end is the chosen query plan.
  108503. */
  108504. struct WherePath {
  108505. Bitmask maskLoop; /* Bitmask of all WhereLoop objects in this path */
  108506. Bitmask revLoop; /* aLoop[]s that should be reversed for ORDER BY */
  108507. LogEst nRow; /* Estimated number of rows generated by this path */
  108508. LogEst rCost; /* Total cost of this path */
  108509. LogEst rUnsorted; /* Total cost of this path ignoring sorting costs */
  108510. i8 isOrdered; /* No. of ORDER BY terms satisfied. -1 for unknown */
  108511. WhereLoop **aLoop; /* Array of WhereLoop objects implementing this path */
  108512. };
  108513. /*
  108514. ** The query generator uses an array of instances of this structure to
  108515. ** help it analyze the subexpressions of the WHERE clause. Each WHERE
  108516. ** clause subexpression is separated from the others by AND operators,
  108517. ** usually, or sometimes subexpressions separated by OR.
  108518. **
  108519. ** All WhereTerms are collected into a single WhereClause structure.
  108520. ** The following identity holds:
  108521. **
  108522. ** WhereTerm.pWC->a[WhereTerm.idx] == WhereTerm
  108523. **
  108524. ** When a term is of the form:
  108525. **
  108526. ** X <op> <expr>
  108527. **
  108528. ** where X is a column name and <op> is one of certain operators,
  108529. ** then WhereTerm.leftCursor and WhereTerm.u.leftColumn record the
  108530. ** cursor number and column number for X. WhereTerm.eOperator records
  108531. ** the <op> using a bitmask encoding defined by WO_xxx below. The
  108532. ** use of a bitmask encoding for the operator allows us to search
  108533. ** quickly for terms that match any of several different operators.
  108534. **
  108535. ** A WhereTerm might also be two or more subterms connected by OR:
  108536. **
  108537. ** (t1.X <op> <expr>) OR (t1.Y <op> <expr>) OR ....
  108538. **
  108539. ** In this second case, wtFlag has the TERM_ORINFO bit set and eOperator==WO_OR
  108540. ** and the WhereTerm.u.pOrInfo field points to auxiliary information that
  108541. ** is collected about the OR clause.
  108542. **
  108543. ** If a term in the WHERE clause does not match either of the two previous
  108544. ** categories, then eOperator==0. The WhereTerm.pExpr field is still set
  108545. ** to the original subexpression content and wtFlags is set up appropriately
  108546. ** but no other fields in the WhereTerm object are meaningful.
  108547. **
  108548. ** When eOperator!=0, prereqRight and prereqAll record sets of cursor numbers,
  108549. ** but they do so indirectly. A single WhereMaskSet structure translates
  108550. ** cursor number into bits and the translated bit is stored in the prereq
  108551. ** fields. The translation is used in order to maximize the number of
  108552. ** bits that will fit in a Bitmask. The VDBE cursor numbers might be
  108553. ** spread out over the non-negative integers. For example, the cursor
  108554. ** numbers might be 3, 8, 9, 10, 20, 23, 41, and 45. The WhereMaskSet
  108555. ** translates these sparse cursor numbers into consecutive integers
  108556. ** beginning with 0 in order to make the best possible use of the available
  108557. ** bits in the Bitmask. So, in the example above, the cursor numbers
  108558. ** would be mapped into integers 0 through 7.
  108559. **
  108560. ** The number of terms in a join is limited by the number of bits
  108561. ** in prereqRight and prereqAll. The default is 64 bits, hence SQLite
  108562. ** is only able to process joins with 64 or fewer tables.
  108563. */
  108564. struct WhereTerm {
  108565. Expr *pExpr; /* Pointer to the subexpression that is this term */
  108566. int iParent; /* Disable pWC->a[iParent] when this term disabled */
  108567. int leftCursor; /* Cursor number of X in "X <op> <expr>" */
  108568. union {
  108569. int leftColumn; /* Column number of X in "X <op> <expr>" */
  108570. WhereOrInfo *pOrInfo; /* Extra information if (eOperator & WO_OR)!=0 */
  108571. WhereAndInfo *pAndInfo; /* Extra information if (eOperator& WO_AND)!=0 */
  108572. } u;
  108573. LogEst truthProb; /* Probability of truth for this expression */
  108574. u16 eOperator; /* A WO_xx value describing <op> */
  108575. u16 wtFlags; /* TERM_xxx bit flags. See below */
  108576. u8 nChild; /* Number of children that must disable us */
  108577. WhereClause *pWC; /* The clause this term is part of */
  108578. Bitmask prereqRight; /* Bitmask of tables used by pExpr->pRight */
  108579. Bitmask prereqAll; /* Bitmask of tables referenced by pExpr */
  108580. };
  108581. /*
  108582. ** Allowed values of WhereTerm.wtFlags
  108583. */
  108584. #define TERM_DYNAMIC 0x01 /* Need to call sqlite3ExprDelete(db, pExpr) */
  108585. #define TERM_VIRTUAL 0x02 /* Added by the optimizer. Do not code */
  108586. #define TERM_CODED 0x04 /* This term is already coded */
  108587. #define TERM_COPIED 0x08 /* Has a child */
  108588. #define TERM_ORINFO 0x10 /* Need to free the WhereTerm.u.pOrInfo object */
  108589. #define TERM_ANDINFO 0x20 /* Need to free the WhereTerm.u.pAndInfo obj */
  108590. #define TERM_OR_OK 0x40 /* Used during OR-clause processing */
  108591. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  108592. # define TERM_VNULL 0x80 /* Manufactured x>NULL or x<=NULL term */
  108593. #else
  108594. # define TERM_VNULL 0x00 /* Disabled if not using stat3 */
  108595. #endif
  108596. #define TERM_LIKEOPT 0x100 /* Virtual terms from the LIKE optimization */
  108597. #define TERM_LIKECOND 0x200 /* Conditionally this LIKE operator term */
  108598. #define TERM_LIKE 0x400 /* The original LIKE operator */
  108599. /*
  108600. ** An instance of the WhereScan object is used as an iterator for locating
  108601. ** terms in the WHERE clause that are useful to the query planner.
  108602. */
  108603. struct WhereScan {
  108604. WhereClause *pOrigWC; /* Original, innermost WhereClause */
  108605. WhereClause *pWC; /* WhereClause currently being scanned */
  108606. char *zCollName; /* Required collating sequence, if not NULL */
  108607. char idxaff; /* Must match this affinity, if zCollName!=NULL */
  108608. unsigned char nEquiv; /* Number of entries in aEquiv[] */
  108609. unsigned char iEquiv; /* Next unused slot in aEquiv[] */
  108610. u32 opMask; /* Acceptable operators */
  108611. int k; /* Resume scanning at this->pWC->a[this->k] */
  108612. int aEquiv[22]; /* Cursor,Column pairs for equivalence classes */
  108613. };
  108614. /*
  108615. ** An instance of the following structure holds all information about a
  108616. ** WHERE clause. Mostly this is a container for one or more WhereTerms.
  108617. **
  108618. ** Explanation of pOuter: For a WHERE clause of the form
  108619. **
  108620. ** a AND ((b AND c) OR (d AND e)) AND f
  108621. **
  108622. ** There are separate WhereClause objects for the whole clause and for
  108623. ** the subclauses "(b AND c)" and "(d AND e)". The pOuter field of the
  108624. ** subclauses points to the WhereClause object for the whole clause.
  108625. */
  108626. struct WhereClause {
  108627. WhereInfo *pWInfo; /* WHERE clause processing context */
  108628. WhereClause *pOuter; /* Outer conjunction */
  108629. u8 op; /* Split operator. TK_AND or TK_OR */
  108630. int nTerm; /* Number of terms */
  108631. int nSlot; /* Number of entries in a[] */
  108632. WhereTerm *a; /* Each a[] describes a term of the WHERE cluase */
  108633. #if defined(SQLITE_SMALL_STACK)
  108634. WhereTerm aStatic[1]; /* Initial static space for a[] */
  108635. #else
  108636. WhereTerm aStatic[8]; /* Initial static space for a[] */
  108637. #endif
  108638. };
  108639. /*
  108640. ** A WhereTerm with eOperator==WO_OR has its u.pOrInfo pointer set to
  108641. ** a dynamically allocated instance of the following structure.
  108642. */
  108643. struct WhereOrInfo {
  108644. WhereClause wc; /* Decomposition into subterms */
  108645. Bitmask indexable; /* Bitmask of all indexable tables in the clause */
  108646. };
  108647. /*
  108648. ** A WhereTerm with eOperator==WO_AND has its u.pAndInfo pointer set to
  108649. ** a dynamically allocated instance of the following structure.
  108650. */
  108651. struct WhereAndInfo {
  108652. WhereClause wc; /* The subexpression broken out */
  108653. };
  108654. /*
  108655. ** An instance of the following structure keeps track of a mapping
  108656. ** between VDBE cursor numbers and bits of the bitmasks in WhereTerm.
  108657. **
  108658. ** The VDBE cursor numbers are small integers contained in
  108659. ** SrcList_item.iCursor and Expr.iTable fields. For any given WHERE
  108660. ** clause, the cursor numbers might not begin with 0 and they might
  108661. ** contain gaps in the numbering sequence. But we want to make maximum
  108662. ** use of the bits in our bitmasks. This structure provides a mapping
  108663. ** from the sparse cursor numbers into consecutive integers beginning
  108664. ** with 0.
  108665. **
  108666. ** If WhereMaskSet.ix[A]==B it means that The A-th bit of a Bitmask
  108667. ** corresponds VDBE cursor number B. The A-th bit of a bitmask is 1<<A.
  108668. **
  108669. ** For example, if the WHERE clause expression used these VDBE
  108670. ** cursors: 4, 5, 8, 29, 57, 73. Then the WhereMaskSet structure
  108671. ** would map those cursor numbers into bits 0 through 5.
  108672. **
  108673. ** Note that the mapping is not necessarily ordered. In the example
  108674. ** above, the mapping might go like this: 4->3, 5->1, 8->2, 29->0,
  108675. ** 57->5, 73->4. Or one of 719 other combinations might be used. It
  108676. ** does not really matter. What is important is that sparse cursor
  108677. ** numbers all get mapped into bit numbers that begin with 0 and contain
  108678. ** no gaps.
  108679. */
  108680. struct WhereMaskSet {
  108681. int n; /* Number of assigned cursor values */
  108682. int ix[BMS]; /* Cursor assigned to each bit */
  108683. };
  108684. /*
  108685. ** This object is a convenience wrapper holding all information needed
  108686. ** to construct WhereLoop objects for a particular query.
  108687. */
  108688. struct WhereLoopBuilder {
  108689. WhereInfo *pWInfo; /* Information about this WHERE */
  108690. WhereClause *pWC; /* WHERE clause terms */
  108691. ExprList *pOrderBy; /* ORDER BY clause */
  108692. WhereLoop *pNew; /* Template WhereLoop */
  108693. WhereOrSet *pOrSet; /* Record best loops here, if not NULL */
  108694. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  108695. UnpackedRecord *pRec; /* Probe for stat4 (if required) */
  108696. int nRecValid; /* Number of valid fields currently in pRec */
  108697. #endif
  108698. };
  108699. /*
  108700. ** The WHERE clause processing routine has two halves. The
  108701. ** first part does the start of the WHERE loop and the second
  108702. ** half does the tail of the WHERE loop. An instance of
  108703. ** this structure is returned by the first half and passed
  108704. ** into the second half to give some continuity.
  108705. **
  108706. ** An instance of this object holds the complete state of the query
  108707. ** planner.
  108708. */
  108709. struct WhereInfo {
  108710. Parse *pParse; /* Parsing and code generating context */
  108711. SrcList *pTabList; /* List of tables in the join */
  108712. ExprList *pOrderBy; /* The ORDER BY clause or NULL */
  108713. ExprList *pResultSet; /* Result set. DISTINCT operates on these */
  108714. WhereLoop *pLoops; /* List of all WhereLoop objects */
  108715. Bitmask revMask; /* Mask of ORDER BY terms that need reversing */
  108716. LogEst nRowOut; /* Estimated number of output rows */
  108717. u16 wctrlFlags; /* Flags originally passed to sqlite3WhereBegin() */
  108718. i8 nOBSat; /* Number of ORDER BY terms satisfied by indices */
  108719. u8 sorted; /* True if really sorted (not just grouped) */
  108720. u8 okOnePass; /* Ok to use one-pass algorithm for UPDATE/DELETE */
  108721. u8 untestedTerms; /* Not all WHERE terms resolved by outer loop */
  108722. u8 eDistinct; /* One of the WHERE_DISTINCT_* values below */
  108723. u8 nLevel; /* Number of nested loop */
  108724. int iTop; /* The very beginning of the WHERE loop */
  108725. int iContinue; /* Jump here to continue with next record */
  108726. int iBreak; /* Jump here to break out of the loop */
  108727. int savedNQueryLoop; /* pParse->nQueryLoop outside the WHERE loop */
  108728. int aiCurOnePass[2]; /* OP_OpenWrite cursors for the ONEPASS opt */
  108729. WhereMaskSet sMaskSet; /* Map cursor numbers to bitmasks */
  108730. WhereClause sWC; /* Decomposition of the WHERE clause */
  108731. WhereLevel a[1]; /* Information about each nest loop in WHERE */
  108732. };
  108733. /*
  108734. ** Bitmasks for the operators on WhereTerm objects. These are all
  108735. ** operators that are of interest to the query planner. An
  108736. ** OR-ed combination of these values can be used when searching for
  108737. ** particular WhereTerms within a WhereClause.
  108738. */
  108739. #define WO_IN 0x001
  108740. #define WO_EQ 0x002
  108741. #define WO_LT (WO_EQ<<(TK_LT-TK_EQ))
  108742. #define WO_LE (WO_EQ<<(TK_LE-TK_EQ))
  108743. #define WO_GT (WO_EQ<<(TK_GT-TK_EQ))
  108744. #define WO_GE (WO_EQ<<(TK_GE-TK_EQ))
  108745. #define WO_MATCH 0x040
  108746. #define WO_ISNULL 0x080
  108747. #define WO_OR 0x100 /* Two or more OR-connected terms */
  108748. #define WO_AND 0x200 /* Two or more AND-connected terms */
  108749. #define WO_EQUIV 0x400 /* Of the form A==B, both columns */
  108750. #define WO_NOOP 0x800 /* This term does not restrict search space */
  108751. #define WO_ALL 0xfff /* Mask of all possible WO_* values */
  108752. #define WO_SINGLE 0x0ff /* Mask of all non-compound WO_* values */
  108753. /*
  108754. ** These are definitions of bits in the WhereLoop.wsFlags field.
  108755. ** The particular combination of bits in each WhereLoop help to
  108756. ** determine the algorithm that WhereLoop represents.
  108757. */
  108758. #define WHERE_COLUMN_EQ 0x00000001 /* x=EXPR */
  108759. #define WHERE_COLUMN_RANGE 0x00000002 /* x<EXPR and/or x>EXPR */
  108760. #define WHERE_COLUMN_IN 0x00000004 /* x IN (...) */
  108761. #define WHERE_COLUMN_NULL 0x00000008 /* x IS NULL */
  108762. #define WHERE_CONSTRAINT 0x0000000f /* Any of the WHERE_COLUMN_xxx values */
  108763. #define WHERE_TOP_LIMIT 0x00000010 /* x<EXPR or x<=EXPR constraint */
  108764. #define WHERE_BTM_LIMIT 0x00000020 /* x>EXPR or x>=EXPR constraint */
  108765. #define WHERE_BOTH_LIMIT 0x00000030 /* Both x>EXPR and x<EXPR */
  108766. #define WHERE_IDX_ONLY 0x00000040 /* Use index only - omit table */
  108767. #define WHERE_IPK 0x00000100 /* x is the INTEGER PRIMARY KEY */
  108768. #define WHERE_INDEXED 0x00000200 /* WhereLoop.u.btree.pIndex is valid */
  108769. #define WHERE_VIRTUALTABLE 0x00000400 /* WhereLoop.u.vtab is valid */
  108770. #define WHERE_IN_ABLE 0x00000800 /* Able to support an IN operator */
  108771. #define WHERE_ONEROW 0x00001000 /* Selects no more than one row */
  108772. #define WHERE_MULTI_OR 0x00002000 /* OR using multiple indices */
  108773. #define WHERE_AUTO_INDEX 0x00004000 /* Uses an ephemeral index */
  108774. #define WHERE_SKIPSCAN 0x00008000 /* Uses the skip-scan algorithm */
  108775. #define WHERE_UNQ_WANTED 0x00010000 /* WHERE_ONEROW would have been helpful*/
  108776. #define WHERE_PARTIALIDX 0x00020000 /* The automatic index is partial */
  108777. /************** End of whereInt.h ********************************************/
  108778. /************** Continuing where we left off in where.c **********************/
  108779. /*
  108780. ** Return the estimated number of output rows from a WHERE clause
  108781. */
  108782. SQLITE_PRIVATE u64 sqlite3WhereOutputRowCount(WhereInfo *pWInfo){
  108783. return sqlite3LogEstToInt(pWInfo->nRowOut);
  108784. }
  108785. /*
  108786. ** Return one of the WHERE_DISTINCT_xxxxx values to indicate how this
  108787. ** WHERE clause returns outputs for DISTINCT processing.
  108788. */
  108789. SQLITE_PRIVATE int sqlite3WhereIsDistinct(WhereInfo *pWInfo){
  108790. return pWInfo->eDistinct;
  108791. }
  108792. /*
  108793. ** Return TRUE if the WHERE clause returns rows in ORDER BY order.
  108794. ** Return FALSE if the output needs to be sorted.
  108795. */
  108796. SQLITE_PRIVATE int sqlite3WhereIsOrdered(WhereInfo *pWInfo){
  108797. return pWInfo->nOBSat;
  108798. }
  108799. /*
  108800. ** Return the VDBE address or label to jump to in order to continue
  108801. ** immediately with the next row of a WHERE clause.
  108802. */
  108803. SQLITE_PRIVATE int sqlite3WhereContinueLabel(WhereInfo *pWInfo){
  108804. assert( pWInfo->iContinue!=0 );
  108805. return pWInfo->iContinue;
  108806. }
  108807. /*
  108808. ** Return the VDBE address or label to jump to in order to break
  108809. ** out of a WHERE loop.
  108810. */
  108811. SQLITE_PRIVATE int sqlite3WhereBreakLabel(WhereInfo *pWInfo){
  108812. return pWInfo->iBreak;
  108813. }
  108814. /*
  108815. ** Return TRUE if an UPDATE or DELETE statement can operate directly on
  108816. ** the rowids returned by a WHERE clause. Return FALSE if doing an
  108817. ** UPDATE or DELETE might change subsequent WHERE clause results.
  108818. **
  108819. ** If the ONEPASS optimization is used (if this routine returns true)
  108820. ** then also write the indices of open cursors used by ONEPASS
  108821. ** into aiCur[0] and aiCur[1]. iaCur[0] gets the cursor of the data
  108822. ** table and iaCur[1] gets the cursor used by an auxiliary index.
  108823. ** Either value may be -1, indicating that cursor is not used.
  108824. ** Any cursors returned will have been opened for writing.
  108825. **
  108826. ** aiCur[0] and aiCur[1] both get -1 if the where-clause logic is
  108827. ** unable to use the ONEPASS optimization.
  108828. */
  108829. SQLITE_PRIVATE int sqlite3WhereOkOnePass(WhereInfo *pWInfo, int *aiCur){
  108830. memcpy(aiCur, pWInfo->aiCurOnePass, sizeof(int)*2);
  108831. return pWInfo->okOnePass;
  108832. }
  108833. /*
  108834. ** Move the content of pSrc into pDest
  108835. */
  108836. static void whereOrMove(WhereOrSet *pDest, WhereOrSet *pSrc){
  108837. pDest->n = pSrc->n;
  108838. memcpy(pDest->a, pSrc->a, pDest->n*sizeof(pDest->a[0]));
  108839. }
  108840. /*
  108841. ** Try to insert a new prerequisite/cost entry into the WhereOrSet pSet.
  108842. **
  108843. ** The new entry might overwrite an existing entry, or it might be
  108844. ** appended, or it might be discarded. Do whatever is the right thing
  108845. ** so that pSet keeps the N_OR_COST best entries seen so far.
  108846. */
  108847. static int whereOrInsert(
  108848. WhereOrSet *pSet, /* The WhereOrSet to be updated */
  108849. Bitmask prereq, /* Prerequisites of the new entry */
  108850. LogEst rRun, /* Run-cost of the new entry */
  108851. LogEst nOut /* Number of outputs for the new entry */
  108852. ){
  108853. u16 i;
  108854. WhereOrCost *p;
  108855. for(i=pSet->n, p=pSet->a; i>0; i--, p++){
  108856. if( rRun<=p->rRun && (prereq & p->prereq)==prereq ){
  108857. goto whereOrInsert_done;
  108858. }
  108859. if( p->rRun<=rRun && (p->prereq & prereq)==p->prereq ){
  108860. return 0;
  108861. }
  108862. }
  108863. if( pSet->n<N_OR_COST ){
  108864. p = &pSet->a[pSet->n++];
  108865. p->nOut = nOut;
  108866. }else{
  108867. p = pSet->a;
  108868. for(i=1; i<pSet->n; i++){
  108869. if( p->rRun>pSet->a[i].rRun ) p = pSet->a + i;
  108870. }
  108871. if( p->rRun<=rRun ) return 0;
  108872. }
  108873. whereOrInsert_done:
  108874. p->prereq = prereq;
  108875. p->rRun = rRun;
  108876. if( p->nOut>nOut ) p->nOut = nOut;
  108877. return 1;
  108878. }
  108879. /*
  108880. ** Initialize a preallocated WhereClause structure.
  108881. */
  108882. static void whereClauseInit(
  108883. WhereClause *pWC, /* The WhereClause to be initialized */
  108884. WhereInfo *pWInfo /* The WHERE processing context */
  108885. ){
  108886. pWC->pWInfo = pWInfo;
  108887. pWC->pOuter = 0;
  108888. pWC->nTerm = 0;
  108889. pWC->nSlot = ArraySize(pWC->aStatic);
  108890. pWC->a = pWC->aStatic;
  108891. }
  108892. /* Forward reference */
  108893. static void whereClauseClear(WhereClause*);
  108894. /*
  108895. ** Deallocate all memory associated with a WhereOrInfo object.
  108896. */
  108897. static void whereOrInfoDelete(sqlite3 *db, WhereOrInfo *p){
  108898. whereClauseClear(&p->wc);
  108899. sqlite3DbFree(db, p);
  108900. }
  108901. /*
  108902. ** Deallocate all memory associated with a WhereAndInfo object.
  108903. */
  108904. static void whereAndInfoDelete(sqlite3 *db, WhereAndInfo *p){
  108905. whereClauseClear(&p->wc);
  108906. sqlite3DbFree(db, p);
  108907. }
  108908. /*
  108909. ** Deallocate a WhereClause structure. The WhereClause structure
  108910. ** itself is not freed. This routine is the inverse of whereClauseInit().
  108911. */
  108912. static void whereClauseClear(WhereClause *pWC){
  108913. int i;
  108914. WhereTerm *a;
  108915. sqlite3 *db = pWC->pWInfo->pParse->db;
  108916. for(i=pWC->nTerm-1, a=pWC->a; i>=0; i--, a++){
  108917. if( a->wtFlags & TERM_DYNAMIC ){
  108918. sqlite3ExprDelete(db, a->pExpr);
  108919. }
  108920. if( a->wtFlags & TERM_ORINFO ){
  108921. whereOrInfoDelete(db, a->u.pOrInfo);
  108922. }else if( a->wtFlags & TERM_ANDINFO ){
  108923. whereAndInfoDelete(db, a->u.pAndInfo);
  108924. }
  108925. }
  108926. if( pWC->a!=pWC->aStatic ){
  108927. sqlite3DbFree(db, pWC->a);
  108928. }
  108929. }
  108930. /*
  108931. ** Add a single new WhereTerm entry to the WhereClause object pWC.
  108932. ** The new WhereTerm object is constructed from Expr p and with wtFlags.
  108933. ** The index in pWC->a[] of the new WhereTerm is returned on success.
  108934. ** 0 is returned if the new WhereTerm could not be added due to a memory
  108935. ** allocation error. The memory allocation failure will be recorded in
  108936. ** the db->mallocFailed flag so that higher-level functions can detect it.
  108937. **
  108938. ** This routine will increase the size of the pWC->a[] array as necessary.
  108939. **
  108940. ** If the wtFlags argument includes TERM_DYNAMIC, then responsibility
  108941. ** for freeing the expression p is assumed by the WhereClause object pWC.
  108942. ** This is true even if this routine fails to allocate a new WhereTerm.
  108943. **
  108944. ** WARNING: This routine might reallocate the space used to store
  108945. ** WhereTerms. All pointers to WhereTerms should be invalidated after
  108946. ** calling this routine. Such pointers may be reinitialized by referencing
  108947. ** the pWC->a[] array.
  108948. */
  108949. static int whereClauseInsert(WhereClause *pWC, Expr *p, u16 wtFlags){
  108950. WhereTerm *pTerm;
  108951. int idx;
  108952. testcase( wtFlags & TERM_VIRTUAL );
  108953. if( pWC->nTerm>=pWC->nSlot ){
  108954. WhereTerm *pOld = pWC->a;
  108955. sqlite3 *db = pWC->pWInfo->pParse->db;
  108956. pWC->a = sqlite3DbMallocRaw(db, sizeof(pWC->a[0])*pWC->nSlot*2 );
  108957. if( pWC->a==0 ){
  108958. if( wtFlags & TERM_DYNAMIC ){
  108959. sqlite3ExprDelete(db, p);
  108960. }
  108961. pWC->a = pOld;
  108962. return 0;
  108963. }
  108964. memcpy(pWC->a, pOld, sizeof(pWC->a[0])*pWC->nTerm);
  108965. if( pOld!=pWC->aStatic ){
  108966. sqlite3DbFree(db, pOld);
  108967. }
  108968. pWC->nSlot = sqlite3DbMallocSize(db, pWC->a)/sizeof(pWC->a[0]);
  108969. memset(&pWC->a[pWC->nTerm], 0, sizeof(pWC->a[0])*(pWC->nSlot-pWC->nTerm));
  108970. }
  108971. pTerm = &pWC->a[idx = pWC->nTerm++];
  108972. if( p && ExprHasProperty(p, EP_Unlikely) ){
  108973. pTerm->truthProb = sqlite3LogEst(p->iTable) - 270;
  108974. }else{
  108975. pTerm->truthProb = 1;
  108976. }
  108977. pTerm->pExpr = sqlite3ExprSkipCollate(p);
  108978. pTerm->wtFlags = wtFlags;
  108979. pTerm->pWC = pWC;
  108980. pTerm->iParent = -1;
  108981. return idx;
  108982. }
  108983. /*
  108984. ** This routine identifies subexpressions in the WHERE clause where
  108985. ** each subexpression is separated by the AND operator or some other
  108986. ** operator specified in the op parameter. The WhereClause structure
  108987. ** is filled with pointers to subexpressions. For example:
  108988. **
  108989. ** WHERE a=='hello' AND coalesce(b,11)<10 AND (c+12!=d OR c==22)
  108990. ** \________/ \_______________/ \________________/
  108991. ** slot[0] slot[1] slot[2]
  108992. **
  108993. ** The original WHERE clause in pExpr is unaltered. All this routine
  108994. ** does is make slot[] entries point to substructure within pExpr.
  108995. **
  108996. ** In the previous sentence and in the diagram, "slot[]" refers to
  108997. ** the WhereClause.a[] array. The slot[] array grows as needed to contain
  108998. ** all terms of the WHERE clause.
  108999. */
  109000. static void whereSplit(WhereClause *pWC, Expr *pExpr, u8 op){
  109001. Expr *pE2 = sqlite3ExprSkipCollate(pExpr);
  109002. pWC->op = op;
  109003. if( pE2==0 ) return;
  109004. if( pE2->op!=op ){
  109005. whereClauseInsert(pWC, pExpr, 0);
  109006. }else{
  109007. whereSplit(pWC, pE2->pLeft, op);
  109008. whereSplit(pWC, pE2->pRight, op);
  109009. }
  109010. }
  109011. /*
  109012. ** Initialize a WhereMaskSet object
  109013. */
  109014. #define initMaskSet(P) (P)->n=0
  109015. /*
  109016. ** Return the bitmask for the given cursor number. Return 0 if
  109017. ** iCursor is not in the set.
  109018. */
  109019. static Bitmask getMask(WhereMaskSet *pMaskSet, int iCursor){
  109020. int i;
  109021. assert( pMaskSet->n<=(int)sizeof(Bitmask)*8 );
  109022. for(i=0; i<pMaskSet->n; i++){
  109023. if( pMaskSet->ix[i]==iCursor ){
  109024. return MASKBIT(i);
  109025. }
  109026. }
  109027. return 0;
  109028. }
  109029. /*
  109030. ** Create a new mask for cursor iCursor.
  109031. **
  109032. ** There is one cursor per table in the FROM clause. The number of
  109033. ** tables in the FROM clause is limited by a test early in the
  109034. ** sqlite3WhereBegin() routine. So we know that the pMaskSet->ix[]
  109035. ** array will never overflow.
  109036. */
  109037. static void createMask(WhereMaskSet *pMaskSet, int iCursor){
  109038. assert( pMaskSet->n < ArraySize(pMaskSet->ix) );
  109039. pMaskSet->ix[pMaskSet->n++] = iCursor;
  109040. }
  109041. /*
  109042. ** These routines walk (recursively) an expression tree and generate
  109043. ** a bitmask indicating which tables are used in that expression
  109044. ** tree.
  109045. */
  109046. static Bitmask exprListTableUsage(WhereMaskSet*, ExprList*);
  109047. static Bitmask exprSelectTableUsage(WhereMaskSet*, Select*);
  109048. static Bitmask exprTableUsage(WhereMaskSet *pMaskSet, Expr *p){
  109049. Bitmask mask = 0;
  109050. if( p==0 ) return 0;
  109051. if( p->op==TK_COLUMN ){
  109052. mask = getMask(pMaskSet, p->iTable);
  109053. return mask;
  109054. }
  109055. mask = exprTableUsage(pMaskSet, p->pRight);
  109056. mask |= exprTableUsage(pMaskSet, p->pLeft);
  109057. if( ExprHasProperty(p, EP_xIsSelect) ){
  109058. mask |= exprSelectTableUsage(pMaskSet, p->x.pSelect);
  109059. }else{
  109060. mask |= exprListTableUsage(pMaskSet, p->x.pList);
  109061. }
  109062. return mask;
  109063. }
  109064. static Bitmask exprListTableUsage(WhereMaskSet *pMaskSet, ExprList *pList){
  109065. int i;
  109066. Bitmask mask = 0;
  109067. if( pList ){
  109068. for(i=0; i<pList->nExpr; i++){
  109069. mask |= exprTableUsage(pMaskSet, pList->a[i].pExpr);
  109070. }
  109071. }
  109072. return mask;
  109073. }
  109074. static Bitmask exprSelectTableUsage(WhereMaskSet *pMaskSet, Select *pS){
  109075. Bitmask mask = 0;
  109076. while( pS ){
  109077. SrcList *pSrc = pS->pSrc;
  109078. mask |= exprListTableUsage(pMaskSet, pS->pEList);
  109079. mask |= exprListTableUsage(pMaskSet, pS->pGroupBy);
  109080. mask |= exprListTableUsage(pMaskSet, pS->pOrderBy);
  109081. mask |= exprTableUsage(pMaskSet, pS->pWhere);
  109082. mask |= exprTableUsage(pMaskSet, pS->pHaving);
  109083. if( ALWAYS(pSrc!=0) ){
  109084. int i;
  109085. for(i=0; i<pSrc->nSrc; i++){
  109086. mask |= exprSelectTableUsage(pMaskSet, pSrc->a[i].pSelect);
  109087. mask |= exprTableUsage(pMaskSet, pSrc->a[i].pOn);
  109088. }
  109089. }
  109090. pS = pS->pPrior;
  109091. }
  109092. return mask;
  109093. }
  109094. /*
  109095. ** Return TRUE if the given operator is one of the operators that is
  109096. ** allowed for an indexable WHERE clause term. The allowed operators are
  109097. ** "=", "<", ">", "<=", ">=", "IN", and "IS NULL"
  109098. */
  109099. static int allowedOp(int op){
  109100. assert( TK_GT>TK_EQ && TK_GT<TK_GE );
  109101. assert( TK_LT>TK_EQ && TK_LT<TK_GE );
  109102. assert( TK_LE>TK_EQ && TK_LE<TK_GE );
  109103. assert( TK_GE==TK_EQ+4 );
  109104. return op==TK_IN || (op>=TK_EQ && op<=TK_GE) || op==TK_ISNULL;
  109105. }
  109106. /*
  109107. ** Commute a comparison operator. Expressions of the form "X op Y"
  109108. ** are converted into "Y op X".
  109109. **
  109110. ** If left/right precedence rules come into play when determining the
  109111. ** collating sequence, then COLLATE operators are adjusted to ensure
  109112. ** that the collating sequence does not change. For example:
  109113. ** "Y collate NOCASE op X" becomes "X op Y" because any collation sequence on
  109114. ** the left hand side of a comparison overrides any collation sequence
  109115. ** attached to the right. For the same reason the EP_Collate flag
  109116. ** is not commuted.
  109117. */
  109118. static void exprCommute(Parse *pParse, Expr *pExpr){
  109119. u16 expRight = (pExpr->pRight->flags & EP_Collate);
  109120. u16 expLeft = (pExpr->pLeft->flags & EP_Collate);
  109121. assert( allowedOp(pExpr->op) && pExpr->op!=TK_IN );
  109122. if( expRight==expLeft ){
  109123. /* Either X and Y both have COLLATE operator or neither do */
  109124. if( expRight ){
  109125. /* Both X and Y have COLLATE operators. Make sure X is always
  109126. ** used by clearing the EP_Collate flag from Y. */
  109127. pExpr->pRight->flags &= ~EP_Collate;
  109128. }else if( sqlite3ExprCollSeq(pParse, pExpr->pLeft)!=0 ){
  109129. /* Neither X nor Y have COLLATE operators, but X has a non-default
  109130. ** collating sequence. So add the EP_Collate marker on X to cause
  109131. ** it to be searched first. */
  109132. pExpr->pLeft->flags |= EP_Collate;
  109133. }
  109134. }
  109135. SWAP(Expr*,pExpr->pRight,pExpr->pLeft);
  109136. if( pExpr->op>=TK_GT ){
  109137. assert( TK_LT==TK_GT+2 );
  109138. assert( TK_GE==TK_LE+2 );
  109139. assert( TK_GT>TK_EQ );
  109140. assert( TK_GT<TK_LE );
  109141. assert( pExpr->op>=TK_GT && pExpr->op<=TK_GE );
  109142. pExpr->op = ((pExpr->op-TK_GT)^2)+TK_GT;
  109143. }
  109144. }
  109145. /*
  109146. ** Translate from TK_xx operator to WO_xx bitmask.
  109147. */
  109148. static u16 operatorMask(int op){
  109149. u16 c;
  109150. assert( allowedOp(op) );
  109151. if( op==TK_IN ){
  109152. c = WO_IN;
  109153. }else if( op==TK_ISNULL ){
  109154. c = WO_ISNULL;
  109155. }else{
  109156. assert( (WO_EQ<<(op-TK_EQ)) < 0x7fff );
  109157. c = (u16)(WO_EQ<<(op-TK_EQ));
  109158. }
  109159. assert( op!=TK_ISNULL || c==WO_ISNULL );
  109160. assert( op!=TK_IN || c==WO_IN );
  109161. assert( op!=TK_EQ || c==WO_EQ );
  109162. assert( op!=TK_LT || c==WO_LT );
  109163. assert( op!=TK_LE || c==WO_LE );
  109164. assert( op!=TK_GT || c==WO_GT );
  109165. assert( op!=TK_GE || c==WO_GE );
  109166. return c;
  109167. }
  109168. /*
  109169. ** Advance to the next WhereTerm that matches according to the criteria
  109170. ** established when the pScan object was initialized by whereScanInit().
  109171. ** Return NULL if there are no more matching WhereTerms.
  109172. */
  109173. static WhereTerm *whereScanNext(WhereScan *pScan){
  109174. int iCur; /* The cursor on the LHS of the term */
  109175. int iColumn; /* The column on the LHS of the term. -1 for IPK */
  109176. Expr *pX; /* An expression being tested */
  109177. WhereClause *pWC; /* Shorthand for pScan->pWC */
  109178. WhereTerm *pTerm; /* The term being tested */
  109179. int k = pScan->k; /* Where to start scanning */
  109180. while( pScan->iEquiv<=pScan->nEquiv ){
  109181. iCur = pScan->aEquiv[pScan->iEquiv-2];
  109182. iColumn = pScan->aEquiv[pScan->iEquiv-1];
  109183. while( (pWC = pScan->pWC)!=0 ){
  109184. for(pTerm=pWC->a+k; k<pWC->nTerm; k++, pTerm++){
  109185. if( pTerm->leftCursor==iCur
  109186. && pTerm->u.leftColumn==iColumn
  109187. && (pScan->iEquiv<=2 || !ExprHasProperty(pTerm->pExpr, EP_FromJoin))
  109188. ){
  109189. if( (pTerm->eOperator & WO_EQUIV)!=0
  109190. && pScan->nEquiv<ArraySize(pScan->aEquiv)
  109191. ){
  109192. int j;
  109193. pX = sqlite3ExprSkipCollate(pTerm->pExpr->pRight);
  109194. assert( pX->op==TK_COLUMN );
  109195. for(j=0; j<pScan->nEquiv; j+=2){
  109196. if( pScan->aEquiv[j]==pX->iTable
  109197. && pScan->aEquiv[j+1]==pX->iColumn ){
  109198. break;
  109199. }
  109200. }
  109201. if( j==pScan->nEquiv ){
  109202. pScan->aEquiv[j] = pX->iTable;
  109203. pScan->aEquiv[j+1] = pX->iColumn;
  109204. pScan->nEquiv += 2;
  109205. }
  109206. }
  109207. if( (pTerm->eOperator & pScan->opMask)!=0 ){
  109208. /* Verify the affinity and collating sequence match */
  109209. if( pScan->zCollName && (pTerm->eOperator & WO_ISNULL)==0 ){
  109210. CollSeq *pColl;
  109211. Parse *pParse = pWC->pWInfo->pParse;
  109212. pX = pTerm->pExpr;
  109213. if( !sqlite3IndexAffinityOk(pX, pScan->idxaff) ){
  109214. continue;
  109215. }
  109216. assert(pX->pLeft);
  109217. pColl = sqlite3BinaryCompareCollSeq(pParse,
  109218. pX->pLeft, pX->pRight);
  109219. if( pColl==0 ) pColl = pParse->db->pDfltColl;
  109220. if( sqlite3StrICmp(pColl->zName, pScan->zCollName) ){
  109221. continue;
  109222. }
  109223. }
  109224. if( (pTerm->eOperator & WO_EQ)!=0
  109225. && (pX = pTerm->pExpr->pRight)->op==TK_COLUMN
  109226. && pX->iTable==pScan->aEquiv[0]
  109227. && pX->iColumn==pScan->aEquiv[1]
  109228. ){
  109229. continue;
  109230. }
  109231. pScan->k = k+1;
  109232. return pTerm;
  109233. }
  109234. }
  109235. }
  109236. pScan->pWC = pScan->pWC->pOuter;
  109237. k = 0;
  109238. }
  109239. pScan->pWC = pScan->pOrigWC;
  109240. k = 0;
  109241. pScan->iEquiv += 2;
  109242. }
  109243. return 0;
  109244. }
  109245. /*
  109246. ** Initialize a WHERE clause scanner object. Return a pointer to the
  109247. ** first match. Return NULL if there are no matches.
  109248. **
  109249. ** The scanner will be searching the WHERE clause pWC. It will look
  109250. ** for terms of the form "X <op> <expr>" where X is column iColumn of table
  109251. ** iCur. The <op> must be one of the operators described by opMask.
  109252. **
  109253. ** If the search is for X and the WHERE clause contains terms of the
  109254. ** form X=Y then this routine might also return terms of the form
  109255. ** "Y <op> <expr>". The number of levels of transitivity is limited,
  109256. ** but is enough to handle most commonly occurring SQL statements.
  109257. **
  109258. ** If X is not the INTEGER PRIMARY KEY then X must be compatible with
  109259. ** index pIdx.
  109260. */
  109261. static WhereTerm *whereScanInit(
  109262. WhereScan *pScan, /* The WhereScan object being initialized */
  109263. WhereClause *pWC, /* The WHERE clause to be scanned */
  109264. int iCur, /* Cursor to scan for */
  109265. int iColumn, /* Column to scan for */
  109266. u32 opMask, /* Operator(s) to scan for */
  109267. Index *pIdx /* Must be compatible with this index */
  109268. ){
  109269. int j;
  109270. /* memset(pScan, 0, sizeof(*pScan)); */
  109271. pScan->pOrigWC = pWC;
  109272. pScan->pWC = pWC;
  109273. if( pIdx && iColumn>=0 ){
  109274. pScan->idxaff = pIdx->pTable->aCol[iColumn].affinity;
  109275. for(j=0; pIdx->aiColumn[j]!=iColumn; j++){
  109276. if( NEVER(j>pIdx->nColumn) ) return 0;
  109277. }
  109278. pScan->zCollName = pIdx->azColl[j];
  109279. }else{
  109280. pScan->idxaff = 0;
  109281. pScan->zCollName = 0;
  109282. }
  109283. pScan->opMask = opMask;
  109284. pScan->k = 0;
  109285. pScan->aEquiv[0] = iCur;
  109286. pScan->aEquiv[1] = iColumn;
  109287. pScan->nEquiv = 2;
  109288. pScan->iEquiv = 2;
  109289. return whereScanNext(pScan);
  109290. }
  109291. /*
  109292. ** Search for a term in the WHERE clause that is of the form "X <op> <expr>"
  109293. ** where X is a reference to the iColumn of table iCur and <op> is one of
  109294. ** the WO_xx operator codes specified by the op parameter.
  109295. ** Return a pointer to the term. Return 0 if not found.
  109296. **
  109297. ** The term returned might by Y=<expr> if there is another constraint in
  109298. ** the WHERE clause that specifies that X=Y. Any such constraints will be
  109299. ** identified by the WO_EQUIV bit in the pTerm->eOperator field. The
  109300. ** aEquiv[] array holds X and all its equivalents, with each SQL variable
  109301. ** taking up two slots in aEquiv[]. The first slot is for the cursor number
  109302. ** and the second is for the column number. There are 22 slots in aEquiv[]
  109303. ** so that means we can look for X plus up to 10 other equivalent values.
  109304. ** Hence a search for X will return <expr> if X=A1 and A1=A2 and A2=A3
  109305. ** and ... and A9=A10 and A10=<expr>.
  109306. **
  109307. ** If there are multiple terms in the WHERE clause of the form "X <op> <expr>"
  109308. ** then try for the one with no dependencies on <expr> - in other words where
  109309. ** <expr> is a constant expression of some kind. Only return entries of
  109310. ** the form "X <op> Y" where Y is a column in another table if no terms of
  109311. ** the form "X <op> <const-expr>" exist. If no terms with a constant RHS
  109312. ** exist, try to return a term that does not use WO_EQUIV.
  109313. */
  109314. static WhereTerm *findTerm(
  109315. WhereClause *pWC, /* The WHERE clause to be searched */
  109316. int iCur, /* Cursor number of LHS */
  109317. int iColumn, /* Column number of LHS */
  109318. Bitmask notReady, /* RHS must not overlap with this mask */
  109319. u32 op, /* Mask of WO_xx values describing operator */
  109320. Index *pIdx /* Must be compatible with this index, if not NULL */
  109321. ){
  109322. WhereTerm *pResult = 0;
  109323. WhereTerm *p;
  109324. WhereScan scan;
  109325. p = whereScanInit(&scan, pWC, iCur, iColumn, op, pIdx);
  109326. while( p ){
  109327. if( (p->prereqRight & notReady)==0 ){
  109328. if( p->prereqRight==0 && (p->eOperator&WO_EQ)!=0 ){
  109329. return p;
  109330. }
  109331. if( pResult==0 ) pResult = p;
  109332. }
  109333. p = whereScanNext(&scan);
  109334. }
  109335. return pResult;
  109336. }
  109337. /* Forward reference */
  109338. static void exprAnalyze(SrcList*, WhereClause*, int);
  109339. /*
  109340. ** Call exprAnalyze on all terms in a WHERE clause.
  109341. */
  109342. static void exprAnalyzeAll(
  109343. SrcList *pTabList, /* the FROM clause */
  109344. WhereClause *pWC /* the WHERE clause to be analyzed */
  109345. ){
  109346. int i;
  109347. for(i=pWC->nTerm-1; i>=0; i--){
  109348. exprAnalyze(pTabList, pWC, i);
  109349. }
  109350. }
  109351. #ifndef SQLITE_OMIT_LIKE_OPTIMIZATION
  109352. /*
  109353. ** Check to see if the given expression is a LIKE or GLOB operator that
  109354. ** can be optimized using inequality constraints. Return TRUE if it is
  109355. ** so and false if not.
  109356. **
  109357. ** In order for the operator to be optimizible, the RHS must be a string
  109358. ** literal that does not begin with a wildcard. The LHS must be a column
  109359. ** that may only be NULL, a string, or a BLOB, never a number. (This means
  109360. ** that virtual tables cannot participate in the LIKE optimization.) If the
  109361. ** collating sequence for the column on the LHS must be appropriate for
  109362. ** the operator.
  109363. */
  109364. static int isLikeOrGlob(
  109365. Parse *pParse, /* Parsing and code generating context */
  109366. Expr *pExpr, /* Test this expression */
  109367. Expr **ppPrefix, /* Pointer to TK_STRING expression with pattern prefix */
  109368. int *pisComplete, /* True if the only wildcard is % in the last character */
  109369. int *pnoCase /* True if uppercase is equivalent to lowercase */
  109370. ){
  109371. const char *z = 0; /* String on RHS of LIKE operator */
  109372. Expr *pRight, *pLeft; /* Right and left size of LIKE operator */
  109373. ExprList *pList; /* List of operands to the LIKE operator */
  109374. int c; /* One character in z[] */
  109375. int cnt; /* Number of non-wildcard prefix characters */
  109376. char wc[3]; /* Wildcard characters */
  109377. sqlite3 *db = pParse->db; /* Database connection */
  109378. sqlite3_value *pVal = 0;
  109379. int op; /* Opcode of pRight */
  109380. if( !sqlite3IsLikeFunction(db, pExpr, pnoCase, wc) ){
  109381. return 0;
  109382. }
  109383. #ifdef SQLITE_EBCDIC
  109384. if( *pnoCase ) return 0;
  109385. #endif
  109386. pList = pExpr->x.pList;
  109387. pLeft = pList->a[1].pExpr;
  109388. if( pLeft->op!=TK_COLUMN
  109389. || sqlite3ExprAffinity(pLeft)!=SQLITE_AFF_TEXT
  109390. || IsVirtual(pLeft->pTab) /* Value might be numeric */
  109391. ){
  109392. /* IMP: R-02065-49465 The left-hand side of the LIKE or GLOB operator must
  109393. ** be the name of an indexed column with TEXT affinity. */
  109394. return 0;
  109395. }
  109396. assert( pLeft->iColumn!=(-1) ); /* Because IPK never has AFF_TEXT */
  109397. pRight = sqlite3ExprSkipCollate(pList->a[0].pExpr);
  109398. op = pRight->op;
  109399. if( op==TK_VARIABLE ){
  109400. Vdbe *pReprepare = pParse->pReprepare;
  109401. int iCol = pRight->iColumn;
  109402. pVal = sqlite3VdbeGetBoundValue(pReprepare, iCol, SQLITE_AFF_NONE);
  109403. if( pVal && sqlite3_value_type(pVal)==SQLITE_TEXT ){
  109404. z = (char *)sqlite3_value_text(pVal);
  109405. }
  109406. sqlite3VdbeSetVarmask(pParse->pVdbe, iCol);
  109407. assert( pRight->op==TK_VARIABLE || pRight->op==TK_REGISTER );
  109408. }else if( op==TK_STRING ){
  109409. z = pRight->u.zToken;
  109410. }
  109411. if( z ){
  109412. cnt = 0;
  109413. while( (c=z[cnt])!=0 && c!=wc[0] && c!=wc[1] && c!=wc[2] ){
  109414. cnt++;
  109415. }
  109416. if( cnt!=0 && 255!=(u8)z[cnt-1] ){
  109417. Expr *pPrefix;
  109418. *pisComplete = c==wc[0] && z[cnt+1]==0;
  109419. pPrefix = sqlite3Expr(db, TK_STRING, z);
  109420. if( pPrefix ) pPrefix->u.zToken[cnt] = 0;
  109421. *ppPrefix = pPrefix;
  109422. if( op==TK_VARIABLE ){
  109423. Vdbe *v = pParse->pVdbe;
  109424. sqlite3VdbeSetVarmask(v, pRight->iColumn);
  109425. if( *pisComplete && pRight->u.zToken[1] ){
  109426. /* If the rhs of the LIKE expression is a variable, and the current
  109427. ** value of the variable means there is no need to invoke the LIKE
  109428. ** function, then no OP_Variable will be added to the program.
  109429. ** This causes problems for the sqlite3_bind_parameter_name()
  109430. ** API. To work around them, add a dummy OP_Variable here.
  109431. */
  109432. int r1 = sqlite3GetTempReg(pParse);
  109433. sqlite3ExprCodeTarget(pParse, pRight, r1);
  109434. sqlite3VdbeChangeP3(v, sqlite3VdbeCurrentAddr(v)-1, 0);
  109435. sqlite3ReleaseTempReg(pParse, r1);
  109436. }
  109437. }
  109438. }else{
  109439. z = 0;
  109440. }
  109441. }
  109442. sqlite3ValueFree(pVal);
  109443. return (z!=0);
  109444. }
  109445. #endif /* SQLITE_OMIT_LIKE_OPTIMIZATION */
  109446. #ifndef SQLITE_OMIT_VIRTUALTABLE
  109447. /*
  109448. ** Check to see if the given expression is of the form
  109449. **
  109450. ** column MATCH expr
  109451. **
  109452. ** If it is then return TRUE. If not, return FALSE.
  109453. */
  109454. static int isMatchOfColumn(
  109455. Expr *pExpr /* Test this expression */
  109456. ){
  109457. ExprList *pList;
  109458. if( pExpr->op!=TK_FUNCTION ){
  109459. return 0;
  109460. }
  109461. if( sqlite3StrICmp(pExpr->u.zToken,"match")!=0 ){
  109462. return 0;
  109463. }
  109464. pList = pExpr->x.pList;
  109465. if( pList->nExpr!=2 ){
  109466. return 0;
  109467. }
  109468. if( pList->a[1].pExpr->op != TK_COLUMN ){
  109469. return 0;
  109470. }
  109471. return 1;
  109472. }
  109473. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  109474. /*
  109475. ** If the pBase expression originated in the ON or USING clause of
  109476. ** a join, then transfer the appropriate markings over to derived.
  109477. */
  109478. static void transferJoinMarkings(Expr *pDerived, Expr *pBase){
  109479. if( pDerived ){
  109480. pDerived->flags |= pBase->flags & EP_FromJoin;
  109481. pDerived->iRightJoinTable = pBase->iRightJoinTable;
  109482. }
  109483. }
  109484. /*
  109485. ** Mark term iChild as being a child of term iParent
  109486. */
  109487. static void markTermAsChild(WhereClause *pWC, int iChild, int iParent){
  109488. pWC->a[iChild].iParent = iParent;
  109489. pWC->a[iChild].truthProb = pWC->a[iParent].truthProb;
  109490. pWC->a[iParent].nChild++;
  109491. }
  109492. /*
  109493. ** Return the N-th AND-connected subterm of pTerm. Or if pTerm is not
  109494. ** a conjunction, then return just pTerm when N==0. If N is exceeds
  109495. ** the number of available subterms, return NULL.
  109496. */
  109497. static WhereTerm *whereNthSubterm(WhereTerm *pTerm, int N){
  109498. if( pTerm->eOperator!=WO_AND ){
  109499. return N==0 ? pTerm : 0;
  109500. }
  109501. if( N<pTerm->u.pAndInfo->wc.nTerm ){
  109502. return &pTerm->u.pAndInfo->wc.a[N];
  109503. }
  109504. return 0;
  109505. }
  109506. /*
  109507. ** Subterms pOne and pTwo are contained within WHERE clause pWC. The
  109508. ** two subterms are in disjunction - they are OR-ed together.
  109509. **
  109510. ** If these two terms are both of the form: "A op B" with the same
  109511. ** A and B values but different operators and if the operators are
  109512. ** compatible (if one is = and the other is <, for example) then
  109513. ** add a new virtual AND term to pWC that is the combination of the
  109514. ** two.
  109515. **
  109516. ** Some examples:
  109517. **
  109518. ** x<y OR x=y --> x<=y
  109519. ** x=y OR x=y --> x=y
  109520. ** x<=y OR x<y --> x<=y
  109521. **
  109522. ** The following is NOT generated:
  109523. **
  109524. ** x<y OR x>y --> x!=y
  109525. */
  109526. static void whereCombineDisjuncts(
  109527. SrcList *pSrc, /* the FROM clause */
  109528. WhereClause *pWC, /* The complete WHERE clause */
  109529. WhereTerm *pOne, /* First disjunct */
  109530. WhereTerm *pTwo /* Second disjunct */
  109531. ){
  109532. u16 eOp = pOne->eOperator | pTwo->eOperator;
  109533. sqlite3 *db; /* Database connection (for malloc) */
  109534. Expr *pNew; /* New virtual expression */
  109535. int op; /* Operator for the combined expression */
  109536. int idxNew; /* Index in pWC of the next virtual term */
  109537. if( (pOne->eOperator & (WO_EQ|WO_LT|WO_LE|WO_GT|WO_GE))==0 ) return;
  109538. if( (pTwo->eOperator & (WO_EQ|WO_LT|WO_LE|WO_GT|WO_GE))==0 ) return;
  109539. if( (eOp & (WO_EQ|WO_LT|WO_LE))!=eOp
  109540. && (eOp & (WO_EQ|WO_GT|WO_GE))!=eOp ) return;
  109541. assert( pOne->pExpr->pLeft!=0 && pOne->pExpr->pRight!=0 );
  109542. assert( pTwo->pExpr->pLeft!=0 && pTwo->pExpr->pRight!=0 );
  109543. if( sqlite3ExprCompare(pOne->pExpr->pLeft, pTwo->pExpr->pLeft, -1) ) return;
  109544. if( sqlite3ExprCompare(pOne->pExpr->pRight, pTwo->pExpr->pRight, -1) )return;
  109545. /* If we reach this point, it means the two subterms can be combined */
  109546. if( (eOp & (eOp-1))!=0 ){
  109547. if( eOp & (WO_LT|WO_LE) ){
  109548. eOp = WO_LE;
  109549. }else{
  109550. assert( eOp & (WO_GT|WO_GE) );
  109551. eOp = WO_GE;
  109552. }
  109553. }
  109554. db = pWC->pWInfo->pParse->db;
  109555. pNew = sqlite3ExprDup(db, pOne->pExpr, 0);
  109556. if( pNew==0 ) return;
  109557. for(op=TK_EQ; eOp!=(WO_EQ<<(op-TK_EQ)); op++){ assert( op<TK_GE ); }
  109558. pNew->op = op;
  109559. idxNew = whereClauseInsert(pWC, pNew, TERM_VIRTUAL|TERM_DYNAMIC);
  109560. exprAnalyze(pSrc, pWC, idxNew);
  109561. }
  109562. #if !defined(SQLITE_OMIT_OR_OPTIMIZATION) && !defined(SQLITE_OMIT_SUBQUERY)
  109563. /*
  109564. ** Analyze a term that consists of two or more OR-connected
  109565. ** subterms. So in:
  109566. **
  109567. ** ... WHERE (a=5) AND (b=7 OR c=9 OR d=13) AND (d=13)
  109568. ** ^^^^^^^^^^^^^^^^^^^^
  109569. **
  109570. ** This routine analyzes terms such as the middle term in the above example.
  109571. ** A WhereOrTerm object is computed and attached to the term under
  109572. ** analysis, regardless of the outcome of the analysis. Hence:
  109573. **
  109574. ** WhereTerm.wtFlags |= TERM_ORINFO
  109575. ** WhereTerm.u.pOrInfo = a dynamically allocated WhereOrTerm object
  109576. **
  109577. ** The term being analyzed must have two or more of OR-connected subterms.
  109578. ** A single subterm might be a set of AND-connected sub-subterms.
  109579. ** Examples of terms under analysis:
  109580. **
  109581. ** (A) t1.x=t2.y OR t1.x=t2.z OR t1.y=15 OR t1.z=t3.a+5
  109582. ** (B) x=expr1 OR expr2=x OR x=expr3
  109583. ** (C) t1.x=t2.y OR (t1.x=t2.z AND t1.y=15)
  109584. ** (D) x=expr1 OR (y>11 AND y<22 AND z LIKE '*hello*')
  109585. ** (E) (p.a=1 AND q.b=2 AND r.c=3) OR (p.x=4 AND q.y=5 AND r.z=6)
  109586. ** (F) x>A OR (x=A AND y>=B)
  109587. **
  109588. ** CASE 1:
  109589. **
  109590. ** If all subterms are of the form T.C=expr for some single column of C and
  109591. ** a single table T (as shown in example B above) then create a new virtual
  109592. ** term that is an equivalent IN expression. In other words, if the term
  109593. ** being analyzed is:
  109594. **
  109595. ** x = expr1 OR expr2 = x OR x = expr3
  109596. **
  109597. ** then create a new virtual term like this:
  109598. **
  109599. ** x IN (expr1,expr2,expr3)
  109600. **
  109601. ** CASE 2:
  109602. **
  109603. ** If there are exactly two disjuncts one side has x>A and the other side
  109604. ** has x=A (for the same x and A) then add a new virtual conjunct term to the
  109605. ** WHERE clause of the form "x>=A". Example:
  109606. **
  109607. ** x>A OR (x=A AND y>B) adds: x>=A
  109608. **
  109609. ** The added conjunct can sometimes be helpful in query planning.
  109610. **
  109611. ** CASE 3:
  109612. **
  109613. ** If all subterms are indexable by a single table T, then set
  109614. **
  109615. ** WhereTerm.eOperator = WO_OR
  109616. ** WhereTerm.u.pOrInfo->indexable |= the cursor number for table T
  109617. **
  109618. ** A subterm is "indexable" if it is of the form
  109619. ** "T.C <op> <expr>" where C is any column of table T and
  109620. ** <op> is one of "=", "<", "<=", ">", ">=", "IS NULL", or "IN".
  109621. ** A subterm is also indexable if it is an AND of two or more
  109622. ** subsubterms at least one of which is indexable. Indexable AND
  109623. ** subterms have their eOperator set to WO_AND and they have
  109624. ** u.pAndInfo set to a dynamically allocated WhereAndTerm object.
  109625. **
  109626. ** From another point of view, "indexable" means that the subterm could
  109627. ** potentially be used with an index if an appropriate index exists.
  109628. ** This analysis does not consider whether or not the index exists; that
  109629. ** is decided elsewhere. This analysis only looks at whether subterms
  109630. ** appropriate for indexing exist.
  109631. **
  109632. ** All examples A through E above satisfy case 2. But if a term
  109633. ** also satisfies case 1 (such as B) we know that the optimizer will
  109634. ** always prefer case 1, so in that case we pretend that case 2 is not
  109635. ** satisfied.
  109636. **
  109637. ** It might be the case that multiple tables are indexable. For example,
  109638. ** (E) above is indexable on tables P, Q, and R.
  109639. **
  109640. ** Terms that satisfy case 2 are candidates for lookup by using
  109641. ** separate indices to find rowids for each subterm and composing
  109642. ** the union of all rowids using a RowSet object. This is similar
  109643. ** to "bitmap indices" in other database engines.
  109644. **
  109645. ** OTHERWISE:
  109646. **
  109647. ** If neither case 1 nor case 2 apply, then leave the eOperator set to
  109648. ** zero. This term is not useful for search.
  109649. */
  109650. static void exprAnalyzeOrTerm(
  109651. SrcList *pSrc, /* the FROM clause */
  109652. WhereClause *pWC, /* the complete WHERE clause */
  109653. int idxTerm /* Index of the OR-term to be analyzed */
  109654. ){
  109655. WhereInfo *pWInfo = pWC->pWInfo; /* WHERE clause processing context */
  109656. Parse *pParse = pWInfo->pParse; /* Parser context */
  109657. sqlite3 *db = pParse->db; /* Database connection */
  109658. WhereTerm *pTerm = &pWC->a[idxTerm]; /* The term to be analyzed */
  109659. Expr *pExpr = pTerm->pExpr; /* The expression of the term */
  109660. int i; /* Loop counters */
  109661. WhereClause *pOrWc; /* Breakup of pTerm into subterms */
  109662. WhereTerm *pOrTerm; /* A Sub-term within the pOrWc */
  109663. WhereOrInfo *pOrInfo; /* Additional information associated with pTerm */
  109664. Bitmask chngToIN; /* Tables that might satisfy case 1 */
  109665. Bitmask indexable; /* Tables that are indexable, satisfying case 2 */
  109666. /*
  109667. ** Break the OR clause into its separate subterms. The subterms are
  109668. ** stored in a WhereClause structure containing within the WhereOrInfo
  109669. ** object that is attached to the original OR clause term.
  109670. */
  109671. assert( (pTerm->wtFlags & (TERM_DYNAMIC|TERM_ORINFO|TERM_ANDINFO))==0 );
  109672. assert( pExpr->op==TK_OR );
  109673. pTerm->u.pOrInfo = pOrInfo = sqlite3DbMallocZero(db, sizeof(*pOrInfo));
  109674. if( pOrInfo==0 ) return;
  109675. pTerm->wtFlags |= TERM_ORINFO;
  109676. pOrWc = &pOrInfo->wc;
  109677. whereClauseInit(pOrWc, pWInfo);
  109678. whereSplit(pOrWc, pExpr, TK_OR);
  109679. exprAnalyzeAll(pSrc, pOrWc);
  109680. if( db->mallocFailed ) return;
  109681. assert( pOrWc->nTerm>=2 );
  109682. /*
  109683. ** Compute the set of tables that might satisfy cases 1 or 2.
  109684. */
  109685. indexable = ~(Bitmask)0;
  109686. chngToIN = ~(Bitmask)0;
  109687. for(i=pOrWc->nTerm-1, pOrTerm=pOrWc->a; i>=0 && indexable; i--, pOrTerm++){
  109688. if( (pOrTerm->eOperator & WO_SINGLE)==0 ){
  109689. WhereAndInfo *pAndInfo;
  109690. assert( (pOrTerm->wtFlags & (TERM_ANDINFO|TERM_ORINFO))==0 );
  109691. chngToIN = 0;
  109692. pAndInfo = sqlite3DbMallocRaw(db, sizeof(*pAndInfo));
  109693. if( pAndInfo ){
  109694. WhereClause *pAndWC;
  109695. WhereTerm *pAndTerm;
  109696. int j;
  109697. Bitmask b = 0;
  109698. pOrTerm->u.pAndInfo = pAndInfo;
  109699. pOrTerm->wtFlags |= TERM_ANDINFO;
  109700. pOrTerm->eOperator = WO_AND;
  109701. pAndWC = &pAndInfo->wc;
  109702. whereClauseInit(pAndWC, pWC->pWInfo);
  109703. whereSplit(pAndWC, pOrTerm->pExpr, TK_AND);
  109704. exprAnalyzeAll(pSrc, pAndWC);
  109705. pAndWC->pOuter = pWC;
  109706. testcase( db->mallocFailed );
  109707. if( !db->mallocFailed ){
  109708. for(j=0, pAndTerm=pAndWC->a; j<pAndWC->nTerm; j++, pAndTerm++){
  109709. assert( pAndTerm->pExpr );
  109710. if( allowedOp(pAndTerm->pExpr->op) ){
  109711. b |= getMask(&pWInfo->sMaskSet, pAndTerm->leftCursor);
  109712. }
  109713. }
  109714. }
  109715. indexable &= b;
  109716. }
  109717. }else if( pOrTerm->wtFlags & TERM_COPIED ){
  109718. /* Skip this term for now. We revisit it when we process the
  109719. ** corresponding TERM_VIRTUAL term */
  109720. }else{
  109721. Bitmask b;
  109722. b = getMask(&pWInfo->sMaskSet, pOrTerm->leftCursor);
  109723. if( pOrTerm->wtFlags & TERM_VIRTUAL ){
  109724. WhereTerm *pOther = &pOrWc->a[pOrTerm->iParent];
  109725. b |= getMask(&pWInfo->sMaskSet, pOther->leftCursor);
  109726. }
  109727. indexable &= b;
  109728. if( (pOrTerm->eOperator & WO_EQ)==0 ){
  109729. chngToIN = 0;
  109730. }else{
  109731. chngToIN &= b;
  109732. }
  109733. }
  109734. }
  109735. /*
  109736. ** Record the set of tables that satisfy case 3. The set might be
  109737. ** empty.
  109738. */
  109739. pOrInfo->indexable = indexable;
  109740. pTerm->eOperator = indexable==0 ? 0 : WO_OR;
  109741. /* For a two-way OR, attempt to implementation case 2.
  109742. */
  109743. if( indexable && pOrWc->nTerm==2 ){
  109744. int iOne = 0;
  109745. WhereTerm *pOne;
  109746. while( (pOne = whereNthSubterm(&pOrWc->a[0],iOne++))!=0 ){
  109747. int iTwo = 0;
  109748. WhereTerm *pTwo;
  109749. while( (pTwo = whereNthSubterm(&pOrWc->a[1],iTwo++))!=0 ){
  109750. whereCombineDisjuncts(pSrc, pWC, pOne, pTwo);
  109751. }
  109752. }
  109753. }
  109754. /*
  109755. ** chngToIN holds a set of tables that *might* satisfy case 1. But
  109756. ** we have to do some additional checking to see if case 1 really
  109757. ** is satisfied.
  109758. **
  109759. ** chngToIN will hold either 0, 1, or 2 bits. The 0-bit case means
  109760. ** that there is no possibility of transforming the OR clause into an
  109761. ** IN operator because one or more terms in the OR clause contain
  109762. ** something other than == on a column in the single table. The 1-bit
  109763. ** case means that every term of the OR clause is of the form
  109764. ** "table.column=expr" for some single table. The one bit that is set
  109765. ** will correspond to the common table. We still need to check to make
  109766. ** sure the same column is used on all terms. The 2-bit case is when
  109767. ** the all terms are of the form "table1.column=table2.column". It
  109768. ** might be possible to form an IN operator with either table1.column
  109769. ** or table2.column as the LHS if either is common to every term of
  109770. ** the OR clause.
  109771. **
  109772. ** Note that terms of the form "table.column1=table.column2" (the
  109773. ** same table on both sizes of the ==) cannot be optimized.
  109774. */
  109775. if( chngToIN ){
  109776. int okToChngToIN = 0; /* True if the conversion to IN is valid */
  109777. int iColumn = -1; /* Column index on lhs of IN operator */
  109778. int iCursor = -1; /* Table cursor common to all terms */
  109779. int j = 0; /* Loop counter */
  109780. /* Search for a table and column that appears on one side or the
  109781. ** other of the == operator in every subterm. That table and column
  109782. ** will be recorded in iCursor and iColumn. There might not be any
  109783. ** such table and column. Set okToChngToIN if an appropriate table
  109784. ** and column is found but leave okToChngToIN false if not found.
  109785. */
  109786. for(j=0; j<2 && !okToChngToIN; j++){
  109787. pOrTerm = pOrWc->a;
  109788. for(i=pOrWc->nTerm-1; i>=0; i--, pOrTerm++){
  109789. assert( pOrTerm->eOperator & WO_EQ );
  109790. pOrTerm->wtFlags &= ~TERM_OR_OK;
  109791. if( pOrTerm->leftCursor==iCursor ){
  109792. /* This is the 2-bit case and we are on the second iteration and
  109793. ** current term is from the first iteration. So skip this term. */
  109794. assert( j==1 );
  109795. continue;
  109796. }
  109797. if( (chngToIN & getMask(&pWInfo->sMaskSet, pOrTerm->leftCursor))==0 ){
  109798. /* This term must be of the form t1.a==t2.b where t2 is in the
  109799. ** chngToIN set but t1 is not. This term will be either preceded
  109800. ** or follwed by an inverted copy (t2.b==t1.a). Skip this term
  109801. ** and use its inversion. */
  109802. testcase( pOrTerm->wtFlags & TERM_COPIED );
  109803. testcase( pOrTerm->wtFlags & TERM_VIRTUAL );
  109804. assert( pOrTerm->wtFlags & (TERM_COPIED|TERM_VIRTUAL) );
  109805. continue;
  109806. }
  109807. iColumn = pOrTerm->u.leftColumn;
  109808. iCursor = pOrTerm->leftCursor;
  109809. break;
  109810. }
  109811. if( i<0 ){
  109812. /* No candidate table+column was found. This can only occur
  109813. ** on the second iteration */
  109814. assert( j==1 );
  109815. assert( IsPowerOfTwo(chngToIN) );
  109816. assert( chngToIN==getMask(&pWInfo->sMaskSet, iCursor) );
  109817. break;
  109818. }
  109819. testcase( j==1 );
  109820. /* We have found a candidate table and column. Check to see if that
  109821. ** table and column is common to every term in the OR clause */
  109822. okToChngToIN = 1;
  109823. for(; i>=0 && okToChngToIN; i--, pOrTerm++){
  109824. assert( pOrTerm->eOperator & WO_EQ );
  109825. if( pOrTerm->leftCursor!=iCursor ){
  109826. pOrTerm->wtFlags &= ~TERM_OR_OK;
  109827. }else if( pOrTerm->u.leftColumn!=iColumn ){
  109828. okToChngToIN = 0;
  109829. }else{
  109830. int affLeft, affRight;
  109831. /* If the right-hand side is also a column, then the affinities
  109832. ** of both right and left sides must be such that no type
  109833. ** conversions are required on the right. (Ticket #2249)
  109834. */
  109835. affRight = sqlite3ExprAffinity(pOrTerm->pExpr->pRight);
  109836. affLeft = sqlite3ExprAffinity(pOrTerm->pExpr->pLeft);
  109837. if( affRight!=0 && affRight!=affLeft ){
  109838. okToChngToIN = 0;
  109839. }else{
  109840. pOrTerm->wtFlags |= TERM_OR_OK;
  109841. }
  109842. }
  109843. }
  109844. }
  109845. /* At this point, okToChngToIN is true if original pTerm satisfies
  109846. ** case 1. In that case, construct a new virtual term that is
  109847. ** pTerm converted into an IN operator.
  109848. */
  109849. if( okToChngToIN ){
  109850. Expr *pDup; /* A transient duplicate expression */
  109851. ExprList *pList = 0; /* The RHS of the IN operator */
  109852. Expr *pLeft = 0; /* The LHS of the IN operator */
  109853. Expr *pNew; /* The complete IN operator */
  109854. for(i=pOrWc->nTerm-1, pOrTerm=pOrWc->a; i>=0; i--, pOrTerm++){
  109855. if( (pOrTerm->wtFlags & TERM_OR_OK)==0 ) continue;
  109856. assert( pOrTerm->eOperator & WO_EQ );
  109857. assert( pOrTerm->leftCursor==iCursor );
  109858. assert( pOrTerm->u.leftColumn==iColumn );
  109859. pDup = sqlite3ExprDup(db, pOrTerm->pExpr->pRight, 0);
  109860. pList = sqlite3ExprListAppend(pWInfo->pParse, pList, pDup);
  109861. pLeft = pOrTerm->pExpr->pLeft;
  109862. }
  109863. assert( pLeft!=0 );
  109864. pDup = sqlite3ExprDup(db, pLeft, 0);
  109865. pNew = sqlite3PExpr(pParse, TK_IN, pDup, 0, 0);
  109866. if( pNew ){
  109867. int idxNew;
  109868. transferJoinMarkings(pNew, pExpr);
  109869. assert( !ExprHasProperty(pNew, EP_xIsSelect) );
  109870. pNew->x.pList = pList;
  109871. idxNew = whereClauseInsert(pWC, pNew, TERM_VIRTUAL|TERM_DYNAMIC);
  109872. testcase( idxNew==0 );
  109873. exprAnalyze(pSrc, pWC, idxNew);
  109874. pTerm = &pWC->a[idxTerm];
  109875. markTermAsChild(pWC, idxNew, idxTerm);
  109876. }else{
  109877. sqlite3ExprListDelete(db, pList);
  109878. }
  109879. pTerm->eOperator = WO_NOOP; /* case 1 trumps case 3 */
  109880. }
  109881. }
  109882. }
  109883. #endif /* !SQLITE_OMIT_OR_OPTIMIZATION && !SQLITE_OMIT_SUBQUERY */
  109884. /*
  109885. ** The input to this routine is an WhereTerm structure with only the
  109886. ** "pExpr" field filled in. The job of this routine is to analyze the
  109887. ** subexpression and populate all the other fields of the WhereTerm
  109888. ** structure.
  109889. **
  109890. ** If the expression is of the form "<expr> <op> X" it gets commuted
  109891. ** to the standard form of "X <op> <expr>".
  109892. **
  109893. ** If the expression is of the form "X <op> Y" where both X and Y are
  109894. ** columns, then the original expression is unchanged and a new virtual
  109895. ** term of the form "Y <op> X" is added to the WHERE clause and
  109896. ** analyzed separately. The original term is marked with TERM_COPIED
  109897. ** and the new term is marked with TERM_DYNAMIC (because it's pExpr
  109898. ** needs to be freed with the WhereClause) and TERM_VIRTUAL (because it
  109899. ** is a commuted copy of a prior term.) The original term has nChild=1
  109900. ** and the copy has idxParent set to the index of the original term.
  109901. */
  109902. static void exprAnalyze(
  109903. SrcList *pSrc, /* the FROM clause */
  109904. WhereClause *pWC, /* the WHERE clause */
  109905. int idxTerm /* Index of the term to be analyzed */
  109906. ){
  109907. WhereInfo *pWInfo = pWC->pWInfo; /* WHERE clause processing context */
  109908. WhereTerm *pTerm; /* The term to be analyzed */
  109909. WhereMaskSet *pMaskSet; /* Set of table index masks */
  109910. Expr *pExpr; /* The expression to be analyzed */
  109911. Bitmask prereqLeft; /* Prerequesites of the pExpr->pLeft */
  109912. Bitmask prereqAll; /* Prerequesites of pExpr */
  109913. Bitmask extraRight = 0; /* Extra dependencies on LEFT JOIN */
  109914. Expr *pStr1 = 0; /* RHS of LIKE/GLOB operator */
  109915. int isComplete = 0; /* RHS of LIKE/GLOB ends with wildcard */
  109916. int noCase = 0; /* uppercase equivalent to lowercase */
  109917. int op; /* Top-level operator. pExpr->op */
  109918. Parse *pParse = pWInfo->pParse; /* Parsing context */
  109919. sqlite3 *db = pParse->db; /* Database connection */
  109920. if( db->mallocFailed ){
  109921. return;
  109922. }
  109923. pTerm = &pWC->a[idxTerm];
  109924. pMaskSet = &pWInfo->sMaskSet;
  109925. pExpr = pTerm->pExpr;
  109926. assert( pExpr->op!=TK_AS && pExpr->op!=TK_COLLATE );
  109927. prereqLeft = exprTableUsage(pMaskSet, pExpr->pLeft);
  109928. op = pExpr->op;
  109929. if( op==TK_IN ){
  109930. assert( pExpr->pRight==0 );
  109931. if( ExprHasProperty(pExpr, EP_xIsSelect) ){
  109932. pTerm->prereqRight = exprSelectTableUsage(pMaskSet, pExpr->x.pSelect);
  109933. }else{
  109934. pTerm->prereqRight = exprListTableUsage(pMaskSet, pExpr->x.pList);
  109935. }
  109936. }else if( op==TK_ISNULL ){
  109937. pTerm->prereqRight = 0;
  109938. }else{
  109939. pTerm->prereqRight = exprTableUsage(pMaskSet, pExpr->pRight);
  109940. }
  109941. prereqAll = exprTableUsage(pMaskSet, pExpr);
  109942. if( ExprHasProperty(pExpr, EP_FromJoin) ){
  109943. Bitmask x = getMask(pMaskSet, pExpr->iRightJoinTable);
  109944. prereqAll |= x;
  109945. extraRight = x-1; /* ON clause terms may not be used with an index
  109946. ** on left table of a LEFT JOIN. Ticket #3015 */
  109947. }
  109948. pTerm->prereqAll = prereqAll;
  109949. pTerm->leftCursor = -1;
  109950. pTerm->iParent = -1;
  109951. pTerm->eOperator = 0;
  109952. if( allowedOp(op) ){
  109953. Expr *pLeft = sqlite3ExprSkipCollate(pExpr->pLeft);
  109954. Expr *pRight = sqlite3ExprSkipCollate(pExpr->pRight);
  109955. u16 opMask = (pTerm->prereqRight & prereqLeft)==0 ? WO_ALL : WO_EQUIV;
  109956. if( pLeft->op==TK_COLUMN ){
  109957. pTerm->leftCursor = pLeft->iTable;
  109958. pTerm->u.leftColumn = pLeft->iColumn;
  109959. pTerm->eOperator = operatorMask(op) & opMask;
  109960. }
  109961. if( pRight && pRight->op==TK_COLUMN ){
  109962. WhereTerm *pNew;
  109963. Expr *pDup;
  109964. u16 eExtraOp = 0; /* Extra bits for pNew->eOperator */
  109965. if( pTerm->leftCursor>=0 ){
  109966. int idxNew;
  109967. pDup = sqlite3ExprDup(db, pExpr, 0);
  109968. if( db->mallocFailed ){
  109969. sqlite3ExprDelete(db, pDup);
  109970. return;
  109971. }
  109972. idxNew = whereClauseInsert(pWC, pDup, TERM_VIRTUAL|TERM_DYNAMIC);
  109973. if( idxNew==0 ) return;
  109974. pNew = &pWC->a[idxNew];
  109975. markTermAsChild(pWC, idxNew, idxTerm);
  109976. pTerm = &pWC->a[idxTerm];
  109977. pTerm->wtFlags |= TERM_COPIED;
  109978. if( pExpr->op==TK_EQ
  109979. && !ExprHasProperty(pExpr, EP_FromJoin)
  109980. && OptimizationEnabled(db, SQLITE_Transitive)
  109981. ){
  109982. pTerm->eOperator |= WO_EQUIV;
  109983. eExtraOp = WO_EQUIV;
  109984. }
  109985. }else{
  109986. pDup = pExpr;
  109987. pNew = pTerm;
  109988. }
  109989. exprCommute(pParse, pDup);
  109990. pLeft = sqlite3ExprSkipCollate(pDup->pLeft);
  109991. pNew->leftCursor = pLeft->iTable;
  109992. pNew->u.leftColumn = pLeft->iColumn;
  109993. testcase( (prereqLeft | extraRight) != prereqLeft );
  109994. pNew->prereqRight = prereqLeft | extraRight;
  109995. pNew->prereqAll = prereqAll;
  109996. pNew->eOperator = (operatorMask(pDup->op) + eExtraOp) & opMask;
  109997. }
  109998. }
  109999. #ifndef SQLITE_OMIT_BETWEEN_OPTIMIZATION
  110000. /* If a term is the BETWEEN operator, create two new virtual terms
  110001. ** that define the range that the BETWEEN implements. For example:
  110002. **
  110003. ** a BETWEEN b AND c
  110004. **
  110005. ** is converted into:
  110006. **
  110007. ** (a BETWEEN b AND c) AND (a>=b) AND (a<=c)
  110008. **
  110009. ** The two new terms are added onto the end of the WhereClause object.
  110010. ** The new terms are "dynamic" and are children of the original BETWEEN
  110011. ** term. That means that if the BETWEEN term is coded, the children are
  110012. ** skipped. Or, if the children are satisfied by an index, the original
  110013. ** BETWEEN term is skipped.
  110014. */
  110015. else if( pExpr->op==TK_BETWEEN && pWC->op==TK_AND ){
  110016. ExprList *pList = pExpr->x.pList;
  110017. int i;
  110018. static const u8 ops[] = {TK_GE, TK_LE};
  110019. assert( pList!=0 );
  110020. assert( pList->nExpr==2 );
  110021. for(i=0; i<2; i++){
  110022. Expr *pNewExpr;
  110023. int idxNew;
  110024. pNewExpr = sqlite3PExpr(pParse, ops[i],
  110025. sqlite3ExprDup(db, pExpr->pLeft, 0),
  110026. sqlite3ExprDup(db, pList->a[i].pExpr, 0), 0);
  110027. transferJoinMarkings(pNewExpr, pExpr);
  110028. idxNew = whereClauseInsert(pWC, pNewExpr, TERM_VIRTUAL|TERM_DYNAMIC);
  110029. testcase( idxNew==0 );
  110030. exprAnalyze(pSrc, pWC, idxNew);
  110031. pTerm = &pWC->a[idxTerm];
  110032. markTermAsChild(pWC, idxNew, idxTerm);
  110033. }
  110034. }
  110035. #endif /* SQLITE_OMIT_BETWEEN_OPTIMIZATION */
  110036. #if !defined(SQLITE_OMIT_OR_OPTIMIZATION) && !defined(SQLITE_OMIT_SUBQUERY)
  110037. /* Analyze a term that is composed of two or more subterms connected by
  110038. ** an OR operator.
  110039. */
  110040. else if( pExpr->op==TK_OR ){
  110041. assert( pWC->op==TK_AND );
  110042. exprAnalyzeOrTerm(pSrc, pWC, idxTerm);
  110043. pTerm = &pWC->a[idxTerm];
  110044. }
  110045. #endif /* SQLITE_OMIT_OR_OPTIMIZATION */
  110046. #ifndef SQLITE_OMIT_LIKE_OPTIMIZATION
  110047. /* Add constraints to reduce the search space on a LIKE or GLOB
  110048. ** operator.
  110049. **
  110050. ** A like pattern of the form "x LIKE 'aBc%'" is changed into constraints
  110051. **
  110052. ** x>='ABC' AND x<'abd' AND x LIKE 'aBc%'
  110053. **
  110054. ** The last character of the prefix "abc" is incremented to form the
  110055. ** termination condition "abd". If case is not significant (the default
  110056. ** for LIKE) then the lower-bound is made all uppercase and the upper-
  110057. ** bound is made all lowercase so that the bounds also work when comparing
  110058. ** BLOBs.
  110059. */
  110060. if( pWC->op==TK_AND
  110061. && isLikeOrGlob(pParse, pExpr, &pStr1, &isComplete, &noCase)
  110062. ){
  110063. Expr *pLeft; /* LHS of LIKE/GLOB operator */
  110064. Expr *pStr2; /* Copy of pStr1 - RHS of LIKE/GLOB operator */
  110065. Expr *pNewExpr1;
  110066. Expr *pNewExpr2;
  110067. int idxNew1;
  110068. int idxNew2;
  110069. const char *zCollSeqName; /* Name of collating sequence */
  110070. const u16 wtFlags = TERM_LIKEOPT | TERM_VIRTUAL | TERM_DYNAMIC;
  110071. pLeft = pExpr->x.pList->a[1].pExpr;
  110072. pStr2 = sqlite3ExprDup(db, pStr1, 0);
  110073. /* Convert the lower bound to upper-case and the upper bound to
  110074. ** lower-case (upper-case is less than lower-case in ASCII) so that
  110075. ** the range constraints also work for BLOBs
  110076. */
  110077. if( noCase && !pParse->db->mallocFailed ){
  110078. int i;
  110079. char c;
  110080. pTerm->wtFlags |= TERM_LIKE;
  110081. for(i=0; (c = pStr1->u.zToken[i])!=0; i++){
  110082. pStr1->u.zToken[i] = sqlite3Toupper(c);
  110083. pStr2->u.zToken[i] = sqlite3Tolower(c);
  110084. }
  110085. }
  110086. if( !db->mallocFailed ){
  110087. u8 c, *pC; /* Last character before the first wildcard */
  110088. pC = (u8*)&pStr2->u.zToken[sqlite3Strlen30(pStr2->u.zToken)-1];
  110089. c = *pC;
  110090. if( noCase ){
  110091. /* The point is to increment the last character before the first
  110092. ** wildcard. But if we increment '@', that will push it into the
  110093. ** alphabetic range where case conversions will mess up the
  110094. ** inequality. To avoid this, make sure to also run the full
  110095. ** LIKE on all candidate expressions by clearing the isComplete flag
  110096. */
  110097. if( c=='A'-1 ) isComplete = 0;
  110098. c = sqlite3UpperToLower[c];
  110099. }
  110100. *pC = c + 1;
  110101. }
  110102. zCollSeqName = noCase ? "NOCASE" : "BINARY";
  110103. pNewExpr1 = sqlite3ExprDup(db, pLeft, 0);
  110104. pNewExpr1 = sqlite3PExpr(pParse, TK_GE,
  110105. sqlite3ExprAddCollateString(pParse,pNewExpr1,zCollSeqName),
  110106. pStr1, 0);
  110107. transferJoinMarkings(pNewExpr1, pExpr);
  110108. idxNew1 = whereClauseInsert(pWC, pNewExpr1, wtFlags);
  110109. testcase( idxNew1==0 );
  110110. exprAnalyze(pSrc, pWC, idxNew1);
  110111. pNewExpr2 = sqlite3ExprDup(db, pLeft, 0);
  110112. pNewExpr2 = sqlite3PExpr(pParse, TK_LT,
  110113. sqlite3ExprAddCollateString(pParse,pNewExpr2,zCollSeqName),
  110114. pStr2, 0);
  110115. transferJoinMarkings(pNewExpr2, pExpr);
  110116. idxNew2 = whereClauseInsert(pWC, pNewExpr2, wtFlags);
  110117. testcase( idxNew2==0 );
  110118. exprAnalyze(pSrc, pWC, idxNew2);
  110119. pTerm = &pWC->a[idxTerm];
  110120. if( isComplete ){
  110121. markTermAsChild(pWC, idxNew1, idxTerm);
  110122. markTermAsChild(pWC, idxNew2, idxTerm);
  110123. }
  110124. }
  110125. #endif /* SQLITE_OMIT_LIKE_OPTIMIZATION */
  110126. #ifndef SQLITE_OMIT_VIRTUALTABLE
  110127. /* Add a WO_MATCH auxiliary term to the constraint set if the
  110128. ** current expression is of the form: column MATCH expr.
  110129. ** This information is used by the xBestIndex methods of
  110130. ** virtual tables. The native query optimizer does not attempt
  110131. ** to do anything with MATCH functions.
  110132. */
  110133. if( isMatchOfColumn(pExpr) ){
  110134. int idxNew;
  110135. Expr *pRight, *pLeft;
  110136. WhereTerm *pNewTerm;
  110137. Bitmask prereqColumn, prereqExpr;
  110138. pRight = pExpr->x.pList->a[0].pExpr;
  110139. pLeft = pExpr->x.pList->a[1].pExpr;
  110140. prereqExpr = exprTableUsage(pMaskSet, pRight);
  110141. prereqColumn = exprTableUsage(pMaskSet, pLeft);
  110142. if( (prereqExpr & prereqColumn)==0 ){
  110143. Expr *pNewExpr;
  110144. pNewExpr = sqlite3PExpr(pParse, TK_MATCH,
  110145. 0, sqlite3ExprDup(db, pRight, 0), 0);
  110146. idxNew = whereClauseInsert(pWC, pNewExpr, TERM_VIRTUAL|TERM_DYNAMIC);
  110147. testcase( idxNew==0 );
  110148. pNewTerm = &pWC->a[idxNew];
  110149. pNewTerm->prereqRight = prereqExpr;
  110150. pNewTerm->leftCursor = pLeft->iTable;
  110151. pNewTerm->u.leftColumn = pLeft->iColumn;
  110152. pNewTerm->eOperator = WO_MATCH;
  110153. markTermAsChild(pWC, idxNew, idxTerm);
  110154. pTerm = &pWC->a[idxTerm];
  110155. pTerm->wtFlags |= TERM_COPIED;
  110156. pNewTerm->prereqAll = pTerm->prereqAll;
  110157. }
  110158. }
  110159. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  110160. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  110161. /* When sqlite_stat3 histogram data is available an operator of the
  110162. ** form "x IS NOT NULL" can sometimes be evaluated more efficiently
  110163. ** as "x>NULL" if x is not an INTEGER PRIMARY KEY. So construct a
  110164. ** virtual term of that form.
  110165. **
  110166. ** Note that the virtual term must be tagged with TERM_VNULL. This
  110167. ** TERM_VNULL tag will suppress the not-null check at the beginning
  110168. ** of the loop. Without the TERM_VNULL flag, the not-null check at
  110169. ** the start of the loop will prevent any results from being returned.
  110170. */
  110171. if( pExpr->op==TK_NOTNULL
  110172. && pExpr->pLeft->op==TK_COLUMN
  110173. && pExpr->pLeft->iColumn>=0
  110174. && OptimizationEnabled(db, SQLITE_Stat34)
  110175. ){
  110176. Expr *pNewExpr;
  110177. Expr *pLeft = pExpr->pLeft;
  110178. int idxNew;
  110179. WhereTerm *pNewTerm;
  110180. pNewExpr = sqlite3PExpr(pParse, TK_GT,
  110181. sqlite3ExprDup(db, pLeft, 0),
  110182. sqlite3PExpr(pParse, TK_NULL, 0, 0, 0), 0);
  110183. idxNew = whereClauseInsert(pWC, pNewExpr,
  110184. TERM_VIRTUAL|TERM_DYNAMIC|TERM_VNULL);
  110185. if( idxNew ){
  110186. pNewTerm = &pWC->a[idxNew];
  110187. pNewTerm->prereqRight = 0;
  110188. pNewTerm->leftCursor = pLeft->iTable;
  110189. pNewTerm->u.leftColumn = pLeft->iColumn;
  110190. pNewTerm->eOperator = WO_GT;
  110191. markTermAsChild(pWC, idxNew, idxTerm);
  110192. pTerm = &pWC->a[idxTerm];
  110193. pTerm->wtFlags |= TERM_COPIED;
  110194. pNewTerm->prereqAll = pTerm->prereqAll;
  110195. }
  110196. }
  110197. #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
  110198. /* Prevent ON clause terms of a LEFT JOIN from being used to drive
  110199. ** an index for tables to the left of the join.
  110200. */
  110201. pTerm->prereqRight |= extraRight;
  110202. }
  110203. /*
  110204. ** This function searches pList for an entry that matches the iCol-th column
  110205. ** of index pIdx.
  110206. **
  110207. ** If such an expression is found, its index in pList->a[] is returned. If
  110208. ** no expression is found, -1 is returned.
  110209. */
  110210. static int findIndexCol(
  110211. Parse *pParse, /* Parse context */
  110212. ExprList *pList, /* Expression list to search */
  110213. int iBase, /* Cursor for table associated with pIdx */
  110214. Index *pIdx, /* Index to match column of */
  110215. int iCol /* Column of index to match */
  110216. ){
  110217. int i;
  110218. const char *zColl = pIdx->azColl[iCol];
  110219. for(i=0; i<pList->nExpr; i++){
  110220. Expr *p = sqlite3ExprSkipCollate(pList->a[i].pExpr);
  110221. if( p->op==TK_COLUMN
  110222. && p->iColumn==pIdx->aiColumn[iCol]
  110223. && p->iTable==iBase
  110224. ){
  110225. CollSeq *pColl = sqlite3ExprCollSeq(pParse, pList->a[i].pExpr);
  110226. if( pColl && 0==sqlite3StrICmp(pColl->zName, zColl) ){
  110227. return i;
  110228. }
  110229. }
  110230. }
  110231. return -1;
  110232. }
  110233. /*
  110234. ** Return true if the DISTINCT expression-list passed as the third argument
  110235. ** is redundant.
  110236. **
  110237. ** A DISTINCT list is redundant if the database contains some subset of
  110238. ** columns that are unique and non-null.
  110239. */
  110240. static int isDistinctRedundant(
  110241. Parse *pParse, /* Parsing context */
  110242. SrcList *pTabList, /* The FROM clause */
  110243. WhereClause *pWC, /* The WHERE clause */
  110244. ExprList *pDistinct /* The result set that needs to be DISTINCT */
  110245. ){
  110246. Table *pTab;
  110247. Index *pIdx;
  110248. int i;
  110249. int iBase;
  110250. /* If there is more than one table or sub-select in the FROM clause of
  110251. ** this query, then it will not be possible to show that the DISTINCT
  110252. ** clause is redundant. */
  110253. if( pTabList->nSrc!=1 ) return 0;
  110254. iBase = pTabList->a[0].iCursor;
  110255. pTab = pTabList->a[0].pTab;
  110256. /* If any of the expressions is an IPK column on table iBase, then return
  110257. ** true. Note: The (p->iTable==iBase) part of this test may be false if the
  110258. ** current SELECT is a correlated sub-query.
  110259. */
  110260. for(i=0; i<pDistinct->nExpr; i++){
  110261. Expr *p = sqlite3ExprSkipCollate(pDistinct->a[i].pExpr);
  110262. if( p->op==TK_COLUMN && p->iTable==iBase && p->iColumn<0 ) return 1;
  110263. }
  110264. /* Loop through all indices on the table, checking each to see if it makes
  110265. ** the DISTINCT qualifier redundant. It does so if:
  110266. **
  110267. ** 1. The index is itself UNIQUE, and
  110268. **
  110269. ** 2. All of the columns in the index are either part of the pDistinct
  110270. ** list, or else the WHERE clause contains a term of the form "col=X",
  110271. ** where X is a constant value. The collation sequences of the
  110272. ** comparison and select-list expressions must match those of the index.
  110273. **
  110274. ** 3. All of those index columns for which the WHERE clause does not
  110275. ** contain a "col=X" term are subject to a NOT NULL constraint.
  110276. */
  110277. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  110278. if( !IsUniqueIndex(pIdx) ) continue;
  110279. for(i=0; i<pIdx->nKeyCol; i++){
  110280. i16 iCol = pIdx->aiColumn[i];
  110281. if( 0==findTerm(pWC, iBase, iCol, ~(Bitmask)0, WO_EQ, pIdx) ){
  110282. int iIdxCol = findIndexCol(pParse, pDistinct, iBase, pIdx, i);
  110283. if( iIdxCol<0 || pTab->aCol[iCol].notNull==0 ){
  110284. break;
  110285. }
  110286. }
  110287. }
  110288. if( i==pIdx->nKeyCol ){
  110289. /* This index implies that the DISTINCT qualifier is redundant. */
  110290. return 1;
  110291. }
  110292. }
  110293. return 0;
  110294. }
  110295. /*
  110296. ** Estimate the logarithm of the input value to base 2.
  110297. */
  110298. static LogEst estLog(LogEst N){
  110299. return N<=10 ? 0 : sqlite3LogEst(N) - 33;
  110300. }
  110301. /*
  110302. ** Two routines for printing the content of an sqlite3_index_info
  110303. ** structure. Used for testing and debugging only. If neither
  110304. ** SQLITE_TEST or SQLITE_DEBUG are defined, then these routines
  110305. ** are no-ops.
  110306. */
  110307. #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(WHERETRACE_ENABLED)
  110308. static void TRACE_IDX_INPUTS(sqlite3_index_info *p){
  110309. int i;
  110310. if( !sqlite3WhereTrace ) return;
  110311. for(i=0; i<p->nConstraint; i++){
  110312. sqlite3DebugPrintf(" constraint[%d]: col=%d termid=%d op=%d usabled=%d\n",
  110313. i,
  110314. p->aConstraint[i].iColumn,
  110315. p->aConstraint[i].iTermOffset,
  110316. p->aConstraint[i].op,
  110317. p->aConstraint[i].usable);
  110318. }
  110319. for(i=0; i<p->nOrderBy; i++){
  110320. sqlite3DebugPrintf(" orderby[%d]: col=%d desc=%d\n",
  110321. i,
  110322. p->aOrderBy[i].iColumn,
  110323. p->aOrderBy[i].desc);
  110324. }
  110325. }
  110326. static void TRACE_IDX_OUTPUTS(sqlite3_index_info *p){
  110327. int i;
  110328. if( !sqlite3WhereTrace ) return;
  110329. for(i=0; i<p->nConstraint; i++){
  110330. sqlite3DebugPrintf(" usage[%d]: argvIdx=%d omit=%d\n",
  110331. i,
  110332. p->aConstraintUsage[i].argvIndex,
  110333. p->aConstraintUsage[i].omit);
  110334. }
  110335. sqlite3DebugPrintf(" idxNum=%d\n", p->idxNum);
  110336. sqlite3DebugPrintf(" idxStr=%s\n", p->idxStr);
  110337. sqlite3DebugPrintf(" orderByConsumed=%d\n", p->orderByConsumed);
  110338. sqlite3DebugPrintf(" estimatedCost=%g\n", p->estimatedCost);
  110339. sqlite3DebugPrintf(" estimatedRows=%lld\n", p->estimatedRows);
  110340. }
  110341. #else
  110342. #define TRACE_IDX_INPUTS(A)
  110343. #define TRACE_IDX_OUTPUTS(A)
  110344. #endif
  110345. #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
  110346. /*
  110347. ** Return TRUE if the WHERE clause term pTerm is of a form where it
  110348. ** could be used with an index to access pSrc, assuming an appropriate
  110349. ** index existed.
  110350. */
  110351. static int termCanDriveIndex(
  110352. WhereTerm *pTerm, /* WHERE clause term to check */
  110353. struct SrcList_item *pSrc, /* Table we are trying to access */
  110354. Bitmask notReady /* Tables in outer loops of the join */
  110355. ){
  110356. char aff;
  110357. if( pTerm->leftCursor!=pSrc->iCursor ) return 0;
  110358. if( (pTerm->eOperator & WO_EQ)==0 ) return 0;
  110359. if( (pTerm->prereqRight & notReady)!=0 ) return 0;
  110360. if( pTerm->u.leftColumn<0 ) return 0;
  110361. aff = pSrc->pTab->aCol[pTerm->u.leftColumn].affinity;
  110362. if( !sqlite3IndexAffinityOk(pTerm->pExpr, aff) ) return 0;
  110363. return 1;
  110364. }
  110365. #endif
  110366. #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
  110367. /*
  110368. ** Generate code to construct the Index object for an automatic index
  110369. ** and to set up the WhereLevel object pLevel so that the code generator
  110370. ** makes use of the automatic index.
  110371. */
  110372. static void constructAutomaticIndex(
  110373. Parse *pParse, /* The parsing context */
  110374. WhereClause *pWC, /* The WHERE clause */
  110375. struct SrcList_item *pSrc, /* The FROM clause term to get the next index */
  110376. Bitmask notReady, /* Mask of cursors that are not available */
  110377. WhereLevel *pLevel /* Write new index here */
  110378. ){
  110379. int nKeyCol; /* Number of columns in the constructed index */
  110380. WhereTerm *pTerm; /* A single term of the WHERE clause */
  110381. WhereTerm *pWCEnd; /* End of pWC->a[] */
  110382. Index *pIdx; /* Object describing the transient index */
  110383. Vdbe *v; /* Prepared statement under construction */
  110384. int addrInit; /* Address of the initialization bypass jump */
  110385. Table *pTable; /* The table being indexed */
  110386. int addrTop; /* Top of the index fill loop */
  110387. int regRecord; /* Register holding an index record */
  110388. int n; /* Column counter */
  110389. int i; /* Loop counter */
  110390. int mxBitCol; /* Maximum column in pSrc->colUsed */
  110391. CollSeq *pColl; /* Collating sequence to on a column */
  110392. WhereLoop *pLoop; /* The Loop object */
  110393. char *zNotUsed; /* Extra space on the end of pIdx */
  110394. Bitmask idxCols; /* Bitmap of columns used for indexing */
  110395. Bitmask extraCols; /* Bitmap of additional columns */
  110396. u8 sentWarning = 0; /* True if a warnning has been issued */
  110397. Expr *pPartial = 0; /* Partial Index Expression */
  110398. int iContinue = 0; /* Jump here to skip excluded rows */
  110399. /* Generate code to skip over the creation and initialization of the
  110400. ** transient index on 2nd and subsequent iterations of the loop. */
  110401. v = pParse->pVdbe;
  110402. assert( v!=0 );
  110403. addrInit = sqlite3CodeOnce(pParse); VdbeCoverage(v);
  110404. /* Count the number of columns that will be added to the index
  110405. ** and used to match WHERE clause constraints */
  110406. nKeyCol = 0;
  110407. pTable = pSrc->pTab;
  110408. pWCEnd = &pWC->a[pWC->nTerm];
  110409. pLoop = pLevel->pWLoop;
  110410. idxCols = 0;
  110411. for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){
  110412. Expr *pExpr = pTerm->pExpr;
  110413. assert( !ExprHasProperty(pExpr, EP_FromJoin) /* prereq always non-zero */
  110414. || pExpr->iRightJoinTable!=pSrc->iCursor /* for the right-hand */
  110415. || pLoop->prereq!=0 ); /* table of a LEFT JOIN */
  110416. if( pLoop->prereq==0
  110417. && (pTerm->wtFlags & TERM_VIRTUAL)==0
  110418. && !ExprHasProperty(pExpr, EP_FromJoin)
  110419. && sqlite3ExprIsTableConstant(pExpr, pSrc->iCursor) ){
  110420. pPartial = sqlite3ExprAnd(pParse->db, pPartial,
  110421. sqlite3ExprDup(pParse->db, pExpr, 0));
  110422. }
  110423. if( termCanDriveIndex(pTerm, pSrc, notReady) ){
  110424. int iCol = pTerm->u.leftColumn;
  110425. Bitmask cMask = iCol>=BMS ? MASKBIT(BMS-1) : MASKBIT(iCol);
  110426. testcase( iCol==BMS );
  110427. testcase( iCol==BMS-1 );
  110428. if( !sentWarning ){
  110429. sqlite3_log(SQLITE_WARNING_AUTOINDEX,
  110430. "automatic index on %s(%s)", pTable->zName,
  110431. pTable->aCol[iCol].zName);
  110432. sentWarning = 1;
  110433. }
  110434. if( (idxCols & cMask)==0 ){
  110435. if( whereLoopResize(pParse->db, pLoop, nKeyCol+1) ){
  110436. goto end_auto_index_create;
  110437. }
  110438. pLoop->aLTerm[nKeyCol++] = pTerm;
  110439. idxCols |= cMask;
  110440. }
  110441. }
  110442. }
  110443. assert( nKeyCol>0 );
  110444. pLoop->u.btree.nEq = pLoop->nLTerm = nKeyCol;
  110445. pLoop->wsFlags = WHERE_COLUMN_EQ | WHERE_IDX_ONLY | WHERE_INDEXED
  110446. | WHERE_AUTO_INDEX;
  110447. /* Count the number of additional columns needed to create a
  110448. ** covering index. A "covering index" is an index that contains all
  110449. ** columns that are needed by the query. With a covering index, the
  110450. ** original table never needs to be accessed. Automatic indices must
  110451. ** be a covering index because the index will not be updated if the
  110452. ** original table changes and the index and table cannot both be used
  110453. ** if they go out of sync.
  110454. */
  110455. extraCols = pSrc->colUsed & (~idxCols | MASKBIT(BMS-1));
  110456. mxBitCol = MIN(BMS-1,pTable->nCol);
  110457. testcase( pTable->nCol==BMS-1 );
  110458. testcase( pTable->nCol==BMS-2 );
  110459. for(i=0; i<mxBitCol; i++){
  110460. if( extraCols & MASKBIT(i) ) nKeyCol++;
  110461. }
  110462. if( pSrc->colUsed & MASKBIT(BMS-1) ){
  110463. nKeyCol += pTable->nCol - BMS + 1;
  110464. }
  110465. /* Construct the Index object to describe this index */
  110466. pIdx = sqlite3AllocateIndexObject(pParse->db, nKeyCol+1, 0, &zNotUsed);
  110467. if( pIdx==0 ) goto end_auto_index_create;
  110468. pLoop->u.btree.pIndex = pIdx;
  110469. pIdx->zName = "auto-index";
  110470. pIdx->pTable = pTable;
  110471. n = 0;
  110472. idxCols = 0;
  110473. for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){
  110474. if( termCanDriveIndex(pTerm, pSrc, notReady) ){
  110475. int iCol = pTerm->u.leftColumn;
  110476. Bitmask cMask = iCol>=BMS ? MASKBIT(BMS-1) : MASKBIT(iCol);
  110477. testcase( iCol==BMS-1 );
  110478. testcase( iCol==BMS );
  110479. if( (idxCols & cMask)==0 ){
  110480. Expr *pX = pTerm->pExpr;
  110481. idxCols |= cMask;
  110482. pIdx->aiColumn[n] = pTerm->u.leftColumn;
  110483. pColl = sqlite3BinaryCompareCollSeq(pParse, pX->pLeft, pX->pRight);
  110484. pIdx->azColl[n] = pColl ? pColl->zName : "BINARY";
  110485. n++;
  110486. }
  110487. }
  110488. }
  110489. assert( (u32)n==pLoop->u.btree.nEq );
  110490. /* Add additional columns needed to make the automatic index into
  110491. ** a covering index */
  110492. for(i=0; i<mxBitCol; i++){
  110493. if( extraCols & MASKBIT(i) ){
  110494. pIdx->aiColumn[n] = i;
  110495. pIdx->azColl[n] = "BINARY";
  110496. n++;
  110497. }
  110498. }
  110499. if( pSrc->colUsed & MASKBIT(BMS-1) ){
  110500. for(i=BMS-1; i<pTable->nCol; i++){
  110501. pIdx->aiColumn[n] = i;
  110502. pIdx->azColl[n] = "BINARY";
  110503. n++;
  110504. }
  110505. }
  110506. assert( n==nKeyCol );
  110507. pIdx->aiColumn[n] = -1;
  110508. pIdx->azColl[n] = "BINARY";
  110509. /* Create the automatic index */
  110510. assert( pLevel->iIdxCur>=0 );
  110511. pLevel->iIdxCur = pParse->nTab++;
  110512. sqlite3VdbeAddOp2(v, OP_OpenAutoindex, pLevel->iIdxCur, nKeyCol+1);
  110513. sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
  110514. VdbeComment((v, "for %s", pTable->zName));
  110515. /* Fill the automatic index with content */
  110516. sqlite3ExprCachePush(pParse);
  110517. addrTop = sqlite3VdbeAddOp1(v, OP_Rewind, pLevel->iTabCur); VdbeCoverage(v);
  110518. if( pPartial ){
  110519. iContinue = sqlite3VdbeMakeLabel(v);
  110520. sqlite3ExprIfFalse(pParse, pPartial, iContinue, SQLITE_JUMPIFNULL);
  110521. pLoop->wsFlags |= WHERE_PARTIALIDX;
  110522. }
  110523. regRecord = sqlite3GetTempReg(pParse);
  110524. sqlite3GenerateIndexKey(pParse, pIdx, pLevel->iTabCur, regRecord, 0, 0, 0, 0);
  110525. sqlite3VdbeAddOp2(v, OP_IdxInsert, pLevel->iIdxCur, regRecord);
  110526. sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
  110527. if( pPartial ) sqlite3VdbeResolveLabel(v, iContinue);
  110528. sqlite3VdbeAddOp2(v, OP_Next, pLevel->iTabCur, addrTop+1); VdbeCoverage(v);
  110529. sqlite3VdbeChangeP5(v, SQLITE_STMTSTATUS_AUTOINDEX);
  110530. sqlite3VdbeJumpHere(v, addrTop);
  110531. sqlite3ReleaseTempReg(pParse, regRecord);
  110532. sqlite3ExprCachePop(pParse);
  110533. /* Jump here when skipping the initialization */
  110534. sqlite3VdbeJumpHere(v, addrInit);
  110535. end_auto_index_create:
  110536. sqlite3ExprDelete(pParse->db, pPartial);
  110537. }
  110538. #endif /* SQLITE_OMIT_AUTOMATIC_INDEX */
  110539. #ifndef SQLITE_OMIT_VIRTUALTABLE
  110540. /*
  110541. ** Allocate and populate an sqlite3_index_info structure. It is the
  110542. ** responsibility of the caller to eventually release the structure
  110543. ** by passing the pointer returned by this function to sqlite3_free().
  110544. */
  110545. static sqlite3_index_info *allocateIndexInfo(
  110546. Parse *pParse,
  110547. WhereClause *pWC,
  110548. struct SrcList_item *pSrc,
  110549. ExprList *pOrderBy
  110550. ){
  110551. int i, j;
  110552. int nTerm;
  110553. struct sqlite3_index_constraint *pIdxCons;
  110554. struct sqlite3_index_orderby *pIdxOrderBy;
  110555. struct sqlite3_index_constraint_usage *pUsage;
  110556. WhereTerm *pTerm;
  110557. int nOrderBy;
  110558. sqlite3_index_info *pIdxInfo;
  110559. /* Count the number of possible WHERE clause constraints referring
  110560. ** to this virtual table */
  110561. for(i=nTerm=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
  110562. if( pTerm->leftCursor != pSrc->iCursor ) continue;
  110563. assert( IsPowerOfTwo(pTerm->eOperator & ~WO_EQUIV) );
  110564. testcase( pTerm->eOperator & WO_IN );
  110565. testcase( pTerm->eOperator & WO_ISNULL );
  110566. testcase( pTerm->eOperator & WO_ALL );
  110567. if( (pTerm->eOperator & ~(WO_ISNULL|WO_EQUIV))==0 ) continue;
  110568. if( pTerm->wtFlags & TERM_VNULL ) continue;
  110569. nTerm++;
  110570. }
  110571. /* If the ORDER BY clause contains only columns in the current
  110572. ** virtual table then allocate space for the aOrderBy part of
  110573. ** the sqlite3_index_info structure.
  110574. */
  110575. nOrderBy = 0;
  110576. if( pOrderBy ){
  110577. int n = pOrderBy->nExpr;
  110578. for(i=0; i<n; i++){
  110579. Expr *pExpr = pOrderBy->a[i].pExpr;
  110580. if( pExpr->op!=TK_COLUMN || pExpr->iTable!=pSrc->iCursor ) break;
  110581. }
  110582. if( i==n){
  110583. nOrderBy = n;
  110584. }
  110585. }
  110586. /* Allocate the sqlite3_index_info structure
  110587. */
  110588. pIdxInfo = sqlite3DbMallocZero(pParse->db, sizeof(*pIdxInfo)
  110589. + (sizeof(*pIdxCons) + sizeof(*pUsage))*nTerm
  110590. + sizeof(*pIdxOrderBy)*nOrderBy );
  110591. if( pIdxInfo==0 ){
  110592. sqlite3ErrorMsg(pParse, "out of memory");
  110593. return 0;
  110594. }
  110595. /* Initialize the structure. The sqlite3_index_info structure contains
  110596. ** many fields that are declared "const" to prevent xBestIndex from
  110597. ** changing them. We have to do some funky casting in order to
  110598. ** initialize those fields.
  110599. */
  110600. pIdxCons = (struct sqlite3_index_constraint*)&pIdxInfo[1];
  110601. pIdxOrderBy = (struct sqlite3_index_orderby*)&pIdxCons[nTerm];
  110602. pUsage = (struct sqlite3_index_constraint_usage*)&pIdxOrderBy[nOrderBy];
  110603. *(int*)&pIdxInfo->nConstraint = nTerm;
  110604. *(int*)&pIdxInfo->nOrderBy = nOrderBy;
  110605. *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint = pIdxCons;
  110606. *(struct sqlite3_index_orderby**)&pIdxInfo->aOrderBy = pIdxOrderBy;
  110607. *(struct sqlite3_index_constraint_usage**)&pIdxInfo->aConstraintUsage =
  110608. pUsage;
  110609. for(i=j=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
  110610. u8 op;
  110611. if( pTerm->leftCursor != pSrc->iCursor ) continue;
  110612. assert( IsPowerOfTwo(pTerm->eOperator & ~WO_EQUIV) );
  110613. testcase( pTerm->eOperator & WO_IN );
  110614. testcase( pTerm->eOperator & WO_ISNULL );
  110615. testcase( pTerm->eOperator & WO_ALL );
  110616. if( (pTerm->eOperator & ~(WO_ISNULL|WO_EQUIV))==0 ) continue;
  110617. if( pTerm->wtFlags & TERM_VNULL ) continue;
  110618. pIdxCons[j].iColumn = pTerm->u.leftColumn;
  110619. pIdxCons[j].iTermOffset = i;
  110620. op = (u8)pTerm->eOperator & WO_ALL;
  110621. if( op==WO_IN ) op = WO_EQ;
  110622. pIdxCons[j].op = op;
  110623. /* The direct assignment in the previous line is possible only because
  110624. ** the WO_ and SQLITE_INDEX_CONSTRAINT_ codes are identical. The
  110625. ** following asserts verify this fact. */
  110626. assert( WO_EQ==SQLITE_INDEX_CONSTRAINT_EQ );
  110627. assert( WO_LT==SQLITE_INDEX_CONSTRAINT_LT );
  110628. assert( WO_LE==SQLITE_INDEX_CONSTRAINT_LE );
  110629. assert( WO_GT==SQLITE_INDEX_CONSTRAINT_GT );
  110630. assert( WO_GE==SQLITE_INDEX_CONSTRAINT_GE );
  110631. assert( WO_MATCH==SQLITE_INDEX_CONSTRAINT_MATCH );
  110632. assert( pTerm->eOperator & (WO_IN|WO_EQ|WO_LT|WO_LE|WO_GT|WO_GE|WO_MATCH) );
  110633. j++;
  110634. }
  110635. for(i=0; i<nOrderBy; i++){
  110636. Expr *pExpr = pOrderBy->a[i].pExpr;
  110637. pIdxOrderBy[i].iColumn = pExpr->iColumn;
  110638. pIdxOrderBy[i].desc = pOrderBy->a[i].sortOrder;
  110639. }
  110640. return pIdxInfo;
  110641. }
  110642. /*
  110643. ** The table object reference passed as the second argument to this function
  110644. ** must represent a virtual table. This function invokes the xBestIndex()
  110645. ** method of the virtual table with the sqlite3_index_info object that
  110646. ** comes in as the 3rd argument to this function.
  110647. **
  110648. ** If an error occurs, pParse is populated with an error message and a
  110649. ** non-zero value is returned. Otherwise, 0 is returned and the output
  110650. ** part of the sqlite3_index_info structure is left populated.
  110651. **
  110652. ** Whether or not an error is returned, it is the responsibility of the
  110653. ** caller to eventually free p->idxStr if p->needToFreeIdxStr indicates
  110654. ** that this is required.
  110655. */
  110656. static int vtabBestIndex(Parse *pParse, Table *pTab, sqlite3_index_info *p){
  110657. sqlite3_vtab *pVtab = sqlite3GetVTable(pParse->db, pTab)->pVtab;
  110658. int i;
  110659. int rc;
  110660. TRACE_IDX_INPUTS(p);
  110661. rc = pVtab->pModule->xBestIndex(pVtab, p);
  110662. TRACE_IDX_OUTPUTS(p);
  110663. if( rc!=SQLITE_OK ){
  110664. if( rc==SQLITE_NOMEM ){
  110665. pParse->db->mallocFailed = 1;
  110666. }else if( !pVtab->zErrMsg ){
  110667. sqlite3ErrorMsg(pParse, "%s", sqlite3ErrStr(rc));
  110668. }else{
  110669. sqlite3ErrorMsg(pParse, "%s", pVtab->zErrMsg);
  110670. }
  110671. }
  110672. sqlite3_free(pVtab->zErrMsg);
  110673. pVtab->zErrMsg = 0;
  110674. for(i=0; i<p->nConstraint; i++){
  110675. if( !p->aConstraint[i].usable && p->aConstraintUsage[i].argvIndex>0 ){
  110676. sqlite3ErrorMsg(pParse,
  110677. "table %s: xBestIndex returned an invalid plan", pTab->zName);
  110678. }
  110679. }
  110680. return pParse->nErr;
  110681. }
  110682. #endif /* !defined(SQLITE_OMIT_VIRTUALTABLE) */
  110683. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  110684. /*
  110685. ** Estimate the location of a particular key among all keys in an
  110686. ** index. Store the results in aStat as follows:
  110687. **
  110688. ** aStat[0] Est. number of rows less than pRec
  110689. ** aStat[1] Est. number of rows equal to pRec
  110690. **
  110691. ** Return the index of the sample that is the smallest sample that
  110692. ** is greater than or equal to pRec. Note that this index is not an index
  110693. ** into the aSample[] array - it is an index into a virtual set of samples
  110694. ** based on the contents of aSample[] and the number of fields in record
  110695. ** pRec.
  110696. */
  110697. static int whereKeyStats(
  110698. Parse *pParse, /* Database connection */
  110699. Index *pIdx, /* Index to consider domain of */
  110700. UnpackedRecord *pRec, /* Vector of values to consider */
  110701. int roundUp, /* Round up if true. Round down if false */
  110702. tRowcnt *aStat /* OUT: stats written here */
  110703. ){
  110704. IndexSample *aSample = pIdx->aSample;
  110705. int iCol; /* Index of required stats in anEq[] etc. */
  110706. int i; /* Index of first sample >= pRec */
  110707. int iSample; /* Smallest sample larger than or equal to pRec */
  110708. int iMin = 0; /* Smallest sample not yet tested */
  110709. int iTest; /* Next sample to test */
  110710. int res; /* Result of comparison operation */
  110711. int nField; /* Number of fields in pRec */
  110712. tRowcnt iLower = 0; /* anLt[] + anEq[] of largest sample pRec is > */
  110713. #ifndef SQLITE_DEBUG
  110714. UNUSED_PARAMETER( pParse );
  110715. #endif
  110716. assert( pRec!=0 );
  110717. assert( pIdx->nSample>0 );
  110718. assert( pRec->nField>0 && pRec->nField<=pIdx->nSampleCol );
  110719. /* Do a binary search to find the first sample greater than or equal
  110720. ** to pRec. If pRec contains a single field, the set of samples to search
  110721. ** is simply the aSample[] array. If the samples in aSample[] contain more
  110722. ** than one fields, all fields following the first are ignored.
  110723. **
  110724. ** If pRec contains N fields, where N is more than one, then as well as the
  110725. ** samples in aSample[] (truncated to N fields), the search also has to
  110726. ** consider prefixes of those samples. For example, if the set of samples
  110727. ** in aSample is:
  110728. **
  110729. ** aSample[0] = (a, 5)
  110730. ** aSample[1] = (a, 10)
  110731. ** aSample[2] = (b, 5)
  110732. ** aSample[3] = (c, 100)
  110733. ** aSample[4] = (c, 105)
  110734. **
  110735. ** Then the search space should ideally be the samples above and the
  110736. ** unique prefixes [a], [b] and [c]. But since that is hard to organize,
  110737. ** the code actually searches this set:
  110738. **
  110739. ** 0: (a)
  110740. ** 1: (a, 5)
  110741. ** 2: (a, 10)
  110742. ** 3: (a, 10)
  110743. ** 4: (b)
  110744. ** 5: (b, 5)
  110745. ** 6: (c)
  110746. ** 7: (c, 100)
  110747. ** 8: (c, 105)
  110748. ** 9: (c, 105)
  110749. **
  110750. ** For each sample in the aSample[] array, N samples are present in the
  110751. ** effective sample array. In the above, samples 0 and 1 are based on
  110752. ** sample aSample[0]. Samples 2 and 3 on aSample[1] etc.
  110753. **
  110754. ** Often, sample i of each block of N effective samples has (i+1) fields.
  110755. ** Except, each sample may be extended to ensure that it is greater than or
  110756. ** equal to the previous sample in the array. For example, in the above,
  110757. ** sample 2 is the first sample of a block of N samples, so at first it
  110758. ** appears that it should be 1 field in size. However, that would make it
  110759. ** smaller than sample 1, so the binary search would not work. As a result,
  110760. ** it is extended to two fields. The duplicates that this creates do not
  110761. ** cause any problems.
  110762. */
  110763. nField = pRec->nField;
  110764. iCol = 0;
  110765. iSample = pIdx->nSample * nField;
  110766. do{
  110767. int iSamp; /* Index in aSample[] of test sample */
  110768. int n; /* Number of fields in test sample */
  110769. iTest = (iMin+iSample)/2;
  110770. iSamp = iTest / nField;
  110771. if( iSamp>0 ){
  110772. /* The proposed effective sample is a prefix of sample aSample[iSamp].
  110773. ** Specifically, the shortest prefix of at least (1 + iTest%nField)
  110774. ** fields that is greater than the previous effective sample. */
  110775. for(n=(iTest % nField) + 1; n<nField; n++){
  110776. if( aSample[iSamp-1].anLt[n-1]!=aSample[iSamp].anLt[n-1] ) break;
  110777. }
  110778. }else{
  110779. n = iTest + 1;
  110780. }
  110781. pRec->nField = n;
  110782. res = sqlite3VdbeRecordCompare(aSample[iSamp].n, aSample[iSamp].p, pRec);
  110783. if( res<0 ){
  110784. iLower = aSample[iSamp].anLt[n-1] + aSample[iSamp].anEq[n-1];
  110785. iMin = iTest+1;
  110786. }else if( res==0 && n<nField ){
  110787. iLower = aSample[iSamp].anLt[n-1];
  110788. iMin = iTest+1;
  110789. res = -1;
  110790. }else{
  110791. iSample = iTest;
  110792. iCol = n-1;
  110793. }
  110794. }while( res && iMin<iSample );
  110795. i = iSample / nField;
  110796. #ifdef SQLITE_DEBUG
  110797. /* The following assert statements check that the binary search code
  110798. ** above found the right answer. This block serves no purpose other
  110799. ** than to invoke the asserts. */
  110800. if( pParse->db->mallocFailed==0 ){
  110801. if( res==0 ){
  110802. /* If (res==0) is true, then pRec must be equal to sample i. */
  110803. assert( i<pIdx->nSample );
  110804. assert( iCol==nField-1 );
  110805. pRec->nField = nField;
  110806. assert( 0==sqlite3VdbeRecordCompare(aSample[i].n, aSample[i].p, pRec)
  110807. || pParse->db->mallocFailed
  110808. );
  110809. }else{
  110810. /* Unless i==pIdx->nSample, indicating that pRec is larger than
  110811. ** all samples in the aSample[] array, pRec must be smaller than the
  110812. ** (iCol+1) field prefix of sample i. */
  110813. assert( i<=pIdx->nSample && i>=0 );
  110814. pRec->nField = iCol+1;
  110815. assert( i==pIdx->nSample
  110816. || sqlite3VdbeRecordCompare(aSample[i].n, aSample[i].p, pRec)>0
  110817. || pParse->db->mallocFailed );
  110818. /* if i==0 and iCol==0, then record pRec is smaller than all samples
  110819. ** in the aSample[] array. Otherwise, if (iCol>0) then pRec must
  110820. ** be greater than or equal to the (iCol) field prefix of sample i.
  110821. ** If (i>0), then pRec must also be greater than sample (i-1). */
  110822. if( iCol>0 ){
  110823. pRec->nField = iCol;
  110824. assert( sqlite3VdbeRecordCompare(aSample[i].n, aSample[i].p, pRec)<=0
  110825. || pParse->db->mallocFailed );
  110826. }
  110827. if( i>0 ){
  110828. pRec->nField = nField;
  110829. assert( sqlite3VdbeRecordCompare(aSample[i-1].n, aSample[i-1].p, pRec)<0
  110830. || pParse->db->mallocFailed );
  110831. }
  110832. }
  110833. }
  110834. #endif /* ifdef SQLITE_DEBUG */
  110835. if( res==0 ){
  110836. /* Record pRec is equal to sample i */
  110837. assert( iCol==nField-1 );
  110838. aStat[0] = aSample[i].anLt[iCol];
  110839. aStat[1] = aSample[i].anEq[iCol];
  110840. }else{
  110841. /* At this point, the (iCol+1) field prefix of aSample[i] is the first
  110842. ** sample that is greater than pRec. Or, if i==pIdx->nSample then pRec
  110843. ** is larger than all samples in the array. */
  110844. tRowcnt iUpper, iGap;
  110845. if( i>=pIdx->nSample ){
  110846. iUpper = sqlite3LogEstToInt(pIdx->aiRowLogEst[0]);
  110847. }else{
  110848. iUpper = aSample[i].anLt[iCol];
  110849. }
  110850. if( iLower>=iUpper ){
  110851. iGap = 0;
  110852. }else{
  110853. iGap = iUpper - iLower;
  110854. }
  110855. if( roundUp ){
  110856. iGap = (iGap*2)/3;
  110857. }else{
  110858. iGap = iGap/3;
  110859. }
  110860. aStat[0] = iLower + iGap;
  110861. aStat[1] = pIdx->aAvgEq[iCol];
  110862. }
  110863. /* Restore the pRec->nField value before returning. */
  110864. pRec->nField = nField;
  110865. return i;
  110866. }
  110867. #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
  110868. /*
  110869. ** If it is not NULL, pTerm is a term that provides an upper or lower
  110870. ** bound on a range scan. Without considering pTerm, it is estimated
  110871. ** that the scan will visit nNew rows. This function returns the number
  110872. ** estimated to be visited after taking pTerm into account.
  110873. **
  110874. ** If the user explicitly specified a likelihood() value for this term,
  110875. ** then the return value is the likelihood multiplied by the number of
  110876. ** input rows. Otherwise, this function assumes that an "IS NOT NULL" term
  110877. ** has a likelihood of 0.50, and any other term a likelihood of 0.25.
  110878. */
  110879. static LogEst whereRangeAdjust(WhereTerm *pTerm, LogEst nNew){
  110880. LogEst nRet = nNew;
  110881. if( pTerm ){
  110882. if( pTerm->truthProb<=0 ){
  110883. nRet += pTerm->truthProb;
  110884. }else if( (pTerm->wtFlags & TERM_VNULL)==0 ){
  110885. nRet -= 20; assert( 20==sqlite3LogEst(4) );
  110886. }
  110887. }
  110888. return nRet;
  110889. }
  110890. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  110891. /*
  110892. ** This function is called to estimate the number of rows visited by a
  110893. ** range-scan on a skip-scan index. For example:
  110894. **
  110895. ** CREATE INDEX i1 ON t1(a, b, c);
  110896. ** SELECT * FROM t1 WHERE a=? AND c BETWEEN ? AND ?;
  110897. **
  110898. ** Value pLoop->nOut is currently set to the estimated number of rows
  110899. ** visited for scanning (a=? AND b=?). This function reduces that estimate
  110900. ** by some factor to account for the (c BETWEEN ? AND ?) expression based
  110901. ** on the stat4 data for the index. this scan will be peformed multiple
  110902. ** times (once for each (a,b) combination that matches a=?) is dealt with
  110903. ** by the caller.
  110904. **
  110905. ** It does this by scanning through all stat4 samples, comparing values
  110906. ** extracted from pLower and pUpper with the corresponding column in each
  110907. ** sample. If L and U are the number of samples found to be less than or
  110908. ** equal to the values extracted from pLower and pUpper respectively, and
  110909. ** N is the total number of samples, the pLoop->nOut value is adjusted
  110910. ** as follows:
  110911. **
  110912. ** nOut = nOut * ( min(U - L, 1) / N )
  110913. **
  110914. ** If pLower is NULL, or a value cannot be extracted from the term, L is
  110915. ** set to zero. If pUpper is NULL, or a value cannot be extracted from it,
  110916. ** U is set to N.
  110917. **
  110918. ** Normally, this function sets *pbDone to 1 before returning. However,
  110919. ** if no value can be extracted from either pLower or pUpper (and so the
  110920. ** estimate of the number of rows delivered remains unchanged), *pbDone
  110921. ** is left as is.
  110922. **
  110923. ** If an error occurs, an SQLite error code is returned. Otherwise,
  110924. ** SQLITE_OK.
  110925. */
  110926. static int whereRangeSkipScanEst(
  110927. Parse *pParse, /* Parsing & code generating context */
  110928. WhereTerm *pLower, /* Lower bound on the range. ex: "x>123" Might be NULL */
  110929. WhereTerm *pUpper, /* Upper bound on the range. ex: "x<455" Might be NULL */
  110930. WhereLoop *pLoop, /* Update the .nOut value of this loop */
  110931. int *pbDone /* Set to true if at least one expr. value extracted */
  110932. ){
  110933. Index *p = pLoop->u.btree.pIndex;
  110934. int nEq = pLoop->u.btree.nEq;
  110935. sqlite3 *db = pParse->db;
  110936. int nLower = -1;
  110937. int nUpper = p->nSample+1;
  110938. int rc = SQLITE_OK;
  110939. int iCol = p->aiColumn[nEq];
  110940. u8 aff = iCol>=0 ? p->pTable->aCol[iCol].affinity : SQLITE_AFF_INTEGER;
  110941. CollSeq *pColl;
  110942. sqlite3_value *p1 = 0; /* Value extracted from pLower */
  110943. sqlite3_value *p2 = 0; /* Value extracted from pUpper */
  110944. sqlite3_value *pVal = 0; /* Value extracted from record */
  110945. pColl = sqlite3LocateCollSeq(pParse, p->azColl[nEq]);
  110946. if( pLower ){
  110947. rc = sqlite3Stat4ValueFromExpr(pParse, pLower->pExpr->pRight, aff, &p1);
  110948. nLower = 0;
  110949. }
  110950. if( pUpper && rc==SQLITE_OK ){
  110951. rc = sqlite3Stat4ValueFromExpr(pParse, pUpper->pExpr->pRight, aff, &p2);
  110952. nUpper = p2 ? 0 : p->nSample;
  110953. }
  110954. if( p1 || p2 ){
  110955. int i;
  110956. int nDiff;
  110957. for(i=0; rc==SQLITE_OK && i<p->nSample; i++){
  110958. rc = sqlite3Stat4Column(db, p->aSample[i].p, p->aSample[i].n, nEq, &pVal);
  110959. if( rc==SQLITE_OK && p1 ){
  110960. int res = sqlite3MemCompare(p1, pVal, pColl);
  110961. if( res>=0 ) nLower++;
  110962. }
  110963. if( rc==SQLITE_OK && p2 ){
  110964. int res = sqlite3MemCompare(p2, pVal, pColl);
  110965. if( res>=0 ) nUpper++;
  110966. }
  110967. }
  110968. nDiff = (nUpper - nLower);
  110969. if( nDiff<=0 ) nDiff = 1;
  110970. /* If there is both an upper and lower bound specified, and the
  110971. ** comparisons indicate that they are close together, use the fallback
  110972. ** method (assume that the scan visits 1/64 of the rows) for estimating
  110973. ** the number of rows visited. Otherwise, estimate the number of rows
  110974. ** using the method described in the header comment for this function. */
  110975. if( nDiff!=1 || pUpper==0 || pLower==0 ){
  110976. int nAdjust = (sqlite3LogEst(p->nSample) - sqlite3LogEst(nDiff));
  110977. pLoop->nOut -= nAdjust;
  110978. *pbDone = 1;
  110979. WHERETRACE(0x10, ("range skip-scan regions: %u..%u adjust=%d est=%d\n",
  110980. nLower, nUpper, nAdjust*-1, pLoop->nOut));
  110981. }
  110982. }else{
  110983. assert( *pbDone==0 );
  110984. }
  110985. sqlite3ValueFree(p1);
  110986. sqlite3ValueFree(p2);
  110987. sqlite3ValueFree(pVal);
  110988. return rc;
  110989. }
  110990. #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
  110991. /*
  110992. ** This function is used to estimate the number of rows that will be visited
  110993. ** by scanning an index for a range of values. The range may have an upper
  110994. ** bound, a lower bound, or both. The WHERE clause terms that set the upper
  110995. ** and lower bounds are represented by pLower and pUpper respectively. For
  110996. ** example, assuming that index p is on t1(a):
  110997. **
  110998. ** ... FROM t1 WHERE a > ? AND a < ? ...
  110999. ** |_____| |_____|
  111000. ** | |
  111001. ** pLower pUpper
  111002. **
  111003. ** If either of the upper or lower bound is not present, then NULL is passed in
  111004. ** place of the corresponding WhereTerm.
  111005. **
  111006. ** The value in (pBuilder->pNew->u.btree.nEq) is the number of the index
  111007. ** column subject to the range constraint. Or, equivalently, the number of
  111008. ** equality constraints optimized by the proposed index scan. For example,
  111009. ** assuming index p is on t1(a, b), and the SQL query is:
  111010. **
  111011. ** ... FROM t1 WHERE a = ? AND b > ? AND b < ? ...
  111012. **
  111013. ** then nEq is set to 1 (as the range restricted column, b, is the second
  111014. ** left-most column of the index). Or, if the query is:
  111015. **
  111016. ** ... FROM t1 WHERE a > ? AND a < ? ...
  111017. **
  111018. ** then nEq is set to 0.
  111019. **
  111020. ** When this function is called, *pnOut is set to the sqlite3LogEst() of the
  111021. ** number of rows that the index scan is expected to visit without
  111022. ** considering the range constraints. If nEq is 0, then *pnOut is the number of
  111023. ** rows in the index. Assuming no error occurs, *pnOut is adjusted (reduced)
  111024. ** to account for the range constraints pLower and pUpper.
  111025. **
  111026. ** In the absence of sqlite_stat4 ANALYZE data, or if such data cannot be
  111027. ** used, a single range inequality reduces the search space by a factor of 4.
  111028. ** and a pair of constraints (x>? AND x<?) reduces the expected number of
  111029. ** rows visited by a factor of 64.
  111030. */
  111031. static int whereRangeScanEst(
  111032. Parse *pParse, /* Parsing & code generating context */
  111033. WhereLoopBuilder *pBuilder,
  111034. WhereTerm *pLower, /* Lower bound on the range. ex: "x>123" Might be NULL */
  111035. WhereTerm *pUpper, /* Upper bound on the range. ex: "x<455" Might be NULL */
  111036. WhereLoop *pLoop /* Modify the .nOut and maybe .rRun fields */
  111037. ){
  111038. int rc = SQLITE_OK;
  111039. int nOut = pLoop->nOut;
  111040. LogEst nNew;
  111041. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  111042. Index *p = pLoop->u.btree.pIndex;
  111043. int nEq = pLoop->u.btree.nEq;
  111044. if( p->nSample>0 && nEq<p->nSampleCol ){
  111045. if( nEq==pBuilder->nRecValid ){
  111046. UnpackedRecord *pRec = pBuilder->pRec;
  111047. tRowcnt a[2];
  111048. u8 aff;
  111049. /* Variable iLower will be set to the estimate of the number of rows in
  111050. ** the index that are less than the lower bound of the range query. The
  111051. ** lower bound being the concatenation of $P and $L, where $P is the
  111052. ** key-prefix formed by the nEq values matched against the nEq left-most
  111053. ** columns of the index, and $L is the value in pLower.
  111054. **
  111055. ** Or, if pLower is NULL or $L cannot be extracted from it (because it
  111056. ** is not a simple variable or literal value), the lower bound of the
  111057. ** range is $P. Due to a quirk in the way whereKeyStats() works, even
  111058. ** if $L is available, whereKeyStats() is called for both ($P) and
  111059. ** ($P:$L) and the larger of the two returned values is used.
  111060. **
  111061. ** Similarly, iUpper is to be set to the estimate of the number of rows
  111062. ** less than the upper bound of the range query. Where the upper bound
  111063. ** is either ($P) or ($P:$U). Again, even if $U is available, both values
  111064. ** of iUpper are requested of whereKeyStats() and the smaller used.
  111065. **
  111066. ** The number of rows between the two bounds is then just iUpper-iLower.
  111067. */
  111068. tRowcnt iLower; /* Rows less than the lower bound */
  111069. tRowcnt iUpper; /* Rows less than the upper bound */
  111070. int iLwrIdx = -2; /* aSample[] for the lower bound */
  111071. int iUprIdx = -1; /* aSample[] for the upper bound */
  111072. if( pRec ){
  111073. testcase( pRec->nField!=pBuilder->nRecValid );
  111074. pRec->nField = pBuilder->nRecValid;
  111075. }
  111076. if( nEq==p->nKeyCol ){
  111077. aff = SQLITE_AFF_INTEGER;
  111078. }else{
  111079. aff = p->pTable->aCol[p->aiColumn[nEq]].affinity;
  111080. }
  111081. /* Determine iLower and iUpper using ($P) only. */
  111082. if( nEq==0 ){
  111083. iLower = 0;
  111084. iUpper = p->nRowEst0;
  111085. }else{
  111086. /* Note: this call could be optimized away - since the same values must
  111087. ** have been requested when testing key $P in whereEqualScanEst(). */
  111088. whereKeyStats(pParse, p, pRec, 0, a);
  111089. iLower = a[0];
  111090. iUpper = a[0] + a[1];
  111091. }
  111092. assert( pLower==0 || (pLower->eOperator & (WO_GT|WO_GE))!=0 );
  111093. assert( pUpper==0 || (pUpper->eOperator & (WO_LT|WO_LE))!=0 );
  111094. assert( p->aSortOrder!=0 );
  111095. if( p->aSortOrder[nEq] ){
  111096. /* The roles of pLower and pUpper are swapped for a DESC index */
  111097. SWAP(WhereTerm*, pLower, pUpper);
  111098. }
  111099. /* If possible, improve on the iLower estimate using ($P:$L). */
  111100. if( pLower ){
  111101. int bOk; /* True if value is extracted from pExpr */
  111102. Expr *pExpr = pLower->pExpr->pRight;
  111103. rc = sqlite3Stat4ProbeSetValue(pParse, p, &pRec, pExpr, aff, nEq, &bOk);
  111104. if( rc==SQLITE_OK && bOk ){
  111105. tRowcnt iNew;
  111106. iLwrIdx = whereKeyStats(pParse, p, pRec, 0, a);
  111107. iNew = a[0] + ((pLower->eOperator & (WO_GT|WO_LE)) ? a[1] : 0);
  111108. if( iNew>iLower ) iLower = iNew;
  111109. nOut--;
  111110. pLower = 0;
  111111. }
  111112. }
  111113. /* If possible, improve on the iUpper estimate using ($P:$U). */
  111114. if( pUpper ){
  111115. int bOk; /* True if value is extracted from pExpr */
  111116. Expr *pExpr = pUpper->pExpr->pRight;
  111117. rc = sqlite3Stat4ProbeSetValue(pParse, p, &pRec, pExpr, aff, nEq, &bOk);
  111118. if( rc==SQLITE_OK && bOk ){
  111119. tRowcnt iNew;
  111120. iUprIdx = whereKeyStats(pParse, p, pRec, 1, a);
  111121. iNew = a[0] + ((pUpper->eOperator & (WO_GT|WO_LE)) ? a[1] : 0);
  111122. if( iNew<iUpper ) iUpper = iNew;
  111123. nOut--;
  111124. pUpper = 0;
  111125. }
  111126. }
  111127. pBuilder->pRec = pRec;
  111128. if( rc==SQLITE_OK ){
  111129. if( iUpper>iLower ){
  111130. nNew = sqlite3LogEst(iUpper - iLower);
  111131. /* TUNING: If both iUpper and iLower are derived from the same
  111132. ** sample, then assume they are 4x more selective. This brings
  111133. ** the estimated selectivity more in line with what it would be
  111134. ** if estimated without the use of STAT3/4 tables. */
  111135. if( iLwrIdx==iUprIdx ) nNew -= 20; assert( 20==sqlite3LogEst(4) );
  111136. }else{
  111137. nNew = 10; assert( 10==sqlite3LogEst(2) );
  111138. }
  111139. if( nNew<nOut ){
  111140. nOut = nNew;
  111141. }
  111142. WHERETRACE(0x10, ("STAT4 range scan: %u..%u est=%d\n",
  111143. (u32)iLower, (u32)iUpper, nOut));
  111144. }
  111145. }else{
  111146. int bDone = 0;
  111147. rc = whereRangeSkipScanEst(pParse, pLower, pUpper, pLoop, &bDone);
  111148. if( bDone ) return rc;
  111149. }
  111150. }
  111151. #else
  111152. UNUSED_PARAMETER(pParse);
  111153. UNUSED_PARAMETER(pBuilder);
  111154. assert( pLower || pUpper );
  111155. #endif
  111156. assert( pUpper==0 || (pUpper->wtFlags & TERM_VNULL)==0 );
  111157. nNew = whereRangeAdjust(pLower, nOut);
  111158. nNew = whereRangeAdjust(pUpper, nNew);
  111159. /* TUNING: If there is both an upper and lower limit and neither limit
  111160. ** has an application-defined likelihood(), assume the range is
  111161. ** reduced by an additional 75%. This means that, by default, an open-ended
  111162. ** range query (e.g. col > ?) is assumed to match 1/4 of the rows in the
  111163. ** index. While a closed range (e.g. col BETWEEN ? AND ?) is estimated to
  111164. ** match 1/64 of the index. */
  111165. if( pLower && pLower->truthProb>0 && pUpper && pUpper->truthProb>0 ){
  111166. nNew -= 20;
  111167. }
  111168. nOut -= (pLower!=0) + (pUpper!=0);
  111169. if( nNew<10 ) nNew = 10;
  111170. if( nNew<nOut ) nOut = nNew;
  111171. #if defined(WHERETRACE_ENABLED)
  111172. if( pLoop->nOut>nOut ){
  111173. WHERETRACE(0x10,("Range scan lowers nOut from %d to %d\n",
  111174. pLoop->nOut, nOut));
  111175. }
  111176. #endif
  111177. pLoop->nOut = (LogEst)nOut;
  111178. return rc;
  111179. }
  111180. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  111181. /*
  111182. ** Estimate the number of rows that will be returned based on
  111183. ** an equality constraint x=VALUE and where that VALUE occurs in
  111184. ** the histogram data. This only works when x is the left-most
  111185. ** column of an index and sqlite_stat3 histogram data is available
  111186. ** for that index. When pExpr==NULL that means the constraint is
  111187. ** "x IS NULL" instead of "x=VALUE".
  111188. **
  111189. ** Write the estimated row count into *pnRow and return SQLITE_OK.
  111190. ** If unable to make an estimate, leave *pnRow unchanged and return
  111191. ** non-zero.
  111192. **
  111193. ** This routine can fail if it is unable to load a collating sequence
  111194. ** required for string comparison, or if unable to allocate memory
  111195. ** for a UTF conversion required for comparison. The error is stored
  111196. ** in the pParse structure.
  111197. */
  111198. static int whereEqualScanEst(
  111199. Parse *pParse, /* Parsing & code generating context */
  111200. WhereLoopBuilder *pBuilder,
  111201. Expr *pExpr, /* Expression for VALUE in the x=VALUE constraint */
  111202. tRowcnt *pnRow /* Write the revised row estimate here */
  111203. ){
  111204. Index *p = pBuilder->pNew->u.btree.pIndex;
  111205. int nEq = pBuilder->pNew->u.btree.nEq;
  111206. UnpackedRecord *pRec = pBuilder->pRec;
  111207. u8 aff; /* Column affinity */
  111208. int rc; /* Subfunction return code */
  111209. tRowcnt a[2]; /* Statistics */
  111210. int bOk;
  111211. assert( nEq>=1 );
  111212. assert( nEq<=p->nColumn );
  111213. assert( p->aSample!=0 );
  111214. assert( p->nSample>0 );
  111215. assert( pBuilder->nRecValid<nEq );
  111216. /* If values are not available for all fields of the index to the left
  111217. ** of this one, no estimate can be made. Return SQLITE_NOTFOUND. */
  111218. if( pBuilder->nRecValid<(nEq-1) ){
  111219. return SQLITE_NOTFOUND;
  111220. }
  111221. /* This is an optimization only. The call to sqlite3Stat4ProbeSetValue()
  111222. ** below would return the same value. */
  111223. if( nEq>=p->nColumn ){
  111224. *pnRow = 1;
  111225. return SQLITE_OK;
  111226. }
  111227. aff = p->pTable->aCol[p->aiColumn[nEq-1]].affinity;
  111228. rc = sqlite3Stat4ProbeSetValue(pParse, p, &pRec, pExpr, aff, nEq-1, &bOk);
  111229. pBuilder->pRec = pRec;
  111230. if( rc!=SQLITE_OK ) return rc;
  111231. if( bOk==0 ) return SQLITE_NOTFOUND;
  111232. pBuilder->nRecValid = nEq;
  111233. whereKeyStats(pParse, p, pRec, 0, a);
  111234. WHERETRACE(0x10,("equality scan regions: %d\n", (int)a[1]));
  111235. *pnRow = a[1];
  111236. return rc;
  111237. }
  111238. #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
  111239. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  111240. /*
  111241. ** Estimate the number of rows that will be returned based on
  111242. ** an IN constraint where the right-hand side of the IN operator
  111243. ** is a list of values. Example:
  111244. **
  111245. ** WHERE x IN (1,2,3,4)
  111246. **
  111247. ** Write the estimated row count into *pnRow and return SQLITE_OK.
  111248. ** If unable to make an estimate, leave *pnRow unchanged and return
  111249. ** non-zero.
  111250. **
  111251. ** This routine can fail if it is unable to load a collating sequence
  111252. ** required for string comparison, or if unable to allocate memory
  111253. ** for a UTF conversion required for comparison. The error is stored
  111254. ** in the pParse structure.
  111255. */
  111256. static int whereInScanEst(
  111257. Parse *pParse, /* Parsing & code generating context */
  111258. WhereLoopBuilder *pBuilder,
  111259. ExprList *pList, /* The value list on the RHS of "x IN (v1,v2,v3,...)" */
  111260. tRowcnt *pnRow /* Write the revised row estimate here */
  111261. ){
  111262. Index *p = pBuilder->pNew->u.btree.pIndex;
  111263. i64 nRow0 = sqlite3LogEstToInt(p->aiRowLogEst[0]);
  111264. int nRecValid = pBuilder->nRecValid;
  111265. int rc = SQLITE_OK; /* Subfunction return code */
  111266. tRowcnt nEst; /* Number of rows for a single term */
  111267. tRowcnt nRowEst = 0; /* New estimate of the number of rows */
  111268. int i; /* Loop counter */
  111269. assert( p->aSample!=0 );
  111270. for(i=0; rc==SQLITE_OK && i<pList->nExpr; i++){
  111271. nEst = nRow0;
  111272. rc = whereEqualScanEst(pParse, pBuilder, pList->a[i].pExpr, &nEst);
  111273. nRowEst += nEst;
  111274. pBuilder->nRecValid = nRecValid;
  111275. }
  111276. if( rc==SQLITE_OK ){
  111277. if( nRowEst > nRow0 ) nRowEst = nRow0;
  111278. *pnRow = nRowEst;
  111279. WHERETRACE(0x10,("IN row estimate: est=%d\n", nRowEst));
  111280. }
  111281. assert( pBuilder->nRecValid==nRecValid );
  111282. return rc;
  111283. }
  111284. #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
  111285. /*
  111286. ** Disable a term in the WHERE clause. Except, do not disable the term
  111287. ** if it controls a LEFT OUTER JOIN and it did not originate in the ON
  111288. ** or USING clause of that join.
  111289. **
  111290. ** Consider the term t2.z='ok' in the following queries:
  111291. **
  111292. ** (1) SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x WHERE t2.z='ok'
  111293. ** (2) SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x AND t2.z='ok'
  111294. ** (3) SELECT * FROM t1, t2 WHERE t1.a=t2.x AND t2.z='ok'
  111295. **
  111296. ** The t2.z='ok' is disabled in the in (2) because it originates
  111297. ** in the ON clause. The term is disabled in (3) because it is not part
  111298. ** of a LEFT OUTER JOIN. In (1), the term is not disabled.
  111299. **
  111300. ** Disabling a term causes that term to not be tested in the inner loop
  111301. ** of the join. Disabling is an optimization. When terms are satisfied
  111302. ** by indices, we disable them to prevent redundant tests in the inner
  111303. ** loop. We would get the correct results if nothing were ever disabled,
  111304. ** but joins might run a little slower. The trick is to disable as much
  111305. ** as we can without disabling too much. If we disabled in (1), we'd get
  111306. ** the wrong answer. See ticket #813.
  111307. **
  111308. ** If all the children of a term are disabled, then that term is also
  111309. ** automatically disabled. In this way, terms get disabled if derived
  111310. ** virtual terms are tested first. For example:
  111311. **
  111312. ** x GLOB 'abc*' AND x>='abc' AND x<'acd'
  111313. ** \___________/ \______/ \_____/
  111314. ** parent child1 child2
  111315. **
  111316. ** Only the parent term was in the original WHERE clause. The child1
  111317. ** and child2 terms were added by the LIKE optimization. If both of
  111318. ** the virtual child terms are valid, then testing of the parent can be
  111319. ** skipped.
  111320. **
  111321. ** Usually the parent term is marked as TERM_CODED. But if the parent
  111322. ** term was originally TERM_LIKE, then the parent gets TERM_LIKECOND instead.
  111323. ** The TERM_LIKECOND marking indicates that the term should be coded inside
  111324. ** a conditional such that is only evaluated on the second pass of a
  111325. ** LIKE-optimization loop, when scanning BLOBs instead of strings.
  111326. */
  111327. static void disableTerm(WhereLevel *pLevel, WhereTerm *pTerm){
  111328. int nLoop = 0;
  111329. while( pTerm
  111330. && (pTerm->wtFlags & TERM_CODED)==0
  111331. && (pLevel->iLeftJoin==0 || ExprHasProperty(pTerm->pExpr, EP_FromJoin))
  111332. && (pLevel->notReady & pTerm->prereqAll)==0
  111333. ){
  111334. if( nLoop && (pTerm->wtFlags & TERM_LIKE)!=0 ){
  111335. pTerm->wtFlags |= TERM_LIKECOND;
  111336. }else{
  111337. pTerm->wtFlags |= TERM_CODED;
  111338. }
  111339. if( pTerm->iParent<0 ) break;
  111340. pTerm = &pTerm->pWC->a[pTerm->iParent];
  111341. pTerm->nChild--;
  111342. if( pTerm->nChild!=0 ) break;
  111343. nLoop++;
  111344. }
  111345. }
  111346. /*
  111347. ** Code an OP_Affinity opcode to apply the column affinity string zAff
  111348. ** to the n registers starting at base.
  111349. **
  111350. ** As an optimization, SQLITE_AFF_NONE entries (which are no-ops) at the
  111351. ** beginning and end of zAff are ignored. If all entries in zAff are
  111352. ** SQLITE_AFF_NONE, then no code gets generated.
  111353. **
  111354. ** This routine makes its own copy of zAff so that the caller is free
  111355. ** to modify zAff after this routine returns.
  111356. */
  111357. static void codeApplyAffinity(Parse *pParse, int base, int n, char *zAff){
  111358. Vdbe *v = pParse->pVdbe;
  111359. if( zAff==0 ){
  111360. assert( pParse->db->mallocFailed );
  111361. return;
  111362. }
  111363. assert( v!=0 );
  111364. /* Adjust base and n to skip over SQLITE_AFF_NONE entries at the beginning
  111365. ** and end of the affinity string.
  111366. */
  111367. while( n>0 && zAff[0]==SQLITE_AFF_NONE ){
  111368. n--;
  111369. base++;
  111370. zAff++;
  111371. }
  111372. while( n>1 && zAff[n-1]==SQLITE_AFF_NONE ){
  111373. n--;
  111374. }
  111375. /* Code the OP_Affinity opcode if there is anything left to do. */
  111376. if( n>0 ){
  111377. sqlite3VdbeAddOp2(v, OP_Affinity, base, n);
  111378. sqlite3VdbeChangeP4(v, -1, zAff, n);
  111379. sqlite3ExprCacheAffinityChange(pParse, base, n);
  111380. }
  111381. }
  111382. /*
  111383. ** Generate code for a single equality term of the WHERE clause. An equality
  111384. ** term can be either X=expr or X IN (...). pTerm is the term to be
  111385. ** coded.
  111386. **
  111387. ** The current value for the constraint is left in register iReg.
  111388. **
  111389. ** For a constraint of the form X=expr, the expression is evaluated and its
  111390. ** result is left on the stack. For constraints of the form X IN (...)
  111391. ** this routine sets up a loop that will iterate over all values of X.
  111392. */
  111393. static int codeEqualityTerm(
  111394. Parse *pParse, /* The parsing context */
  111395. WhereTerm *pTerm, /* The term of the WHERE clause to be coded */
  111396. WhereLevel *pLevel, /* The level of the FROM clause we are working on */
  111397. int iEq, /* Index of the equality term within this level */
  111398. int bRev, /* True for reverse-order IN operations */
  111399. int iTarget /* Attempt to leave results in this register */
  111400. ){
  111401. Expr *pX = pTerm->pExpr;
  111402. Vdbe *v = pParse->pVdbe;
  111403. int iReg; /* Register holding results */
  111404. assert( iTarget>0 );
  111405. if( pX->op==TK_EQ ){
  111406. iReg = sqlite3ExprCodeTarget(pParse, pX->pRight, iTarget);
  111407. }else if( pX->op==TK_ISNULL ){
  111408. iReg = iTarget;
  111409. sqlite3VdbeAddOp2(v, OP_Null, 0, iReg);
  111410. #ifndef SQLITE_OMIT_SUBQUERY
  111411. }else{
  111412. int eType;
  111413. int iTab;
  111414. struct InLoop *pIn;
  111415. WhereLoop *pLoop = pLevel->pWLoop;
  111416. if( (pLoop->wsFlags & WHERE_VIRTUALTABLE)==0
  111417. && pLoop->u.btree.pIndex!=0
  111418. && pLoop->u.btree.pIndex->aSortOrder[iEq]
  111419. ){
  111420. testcase( iEq==0 );
  111421. testcase( bRev );
  111422. bRev = !bRev;
  111423. }
  111424. assert( pX->op==TK_IN );
  111425. iReg = iTarget;
  111426. eType = sqlite3FindInIndex(pParse, pX, IN_INDEX_LOOP, 0);
  111427. if( eType==IN_INDEX_INDEX_DESC ){
  111428. testcase( bRev );
  111429. bRev = !bRev;
  111430. }
  111431. iTab = pX->iTable;
  111432. sqlite3VdbeAddOp2(v, bRev ? OP_Last : OP_Rewind, iTab, 0);
  111433. VdbeCoverageIf(v, bRev);
  111434. VdbeCoverageIf(v, !bRev);
  111435. assert( (pLoop->wsFlags & WHERE_MULTI_OR)==0 );
  111436. pLoop->wsFlags |= WHERE_IN_ABLE;
  111437. if( pLevel->u.in.nIn==0 ){
  111438. pLevel->addrNxt = sqlite3VdbeMakeLabel(v);
  111439. }
  111440. pLevel->u.in.nIn++;
  111441. pLevel->u.in.aInLoop =
  111442. sqlite3DbReallocOrFree(pParse->db, pLevel->u.in.aInLoop,
  111443. sizeof(pLevel->u.in.aInLoop[0])*pLevel->u.in.nIn);
  111444. pIn = pLevel->u.in.aInLoop;
  111445. if( pIn ){
  111446. pIn += pLevel->u.in.nIn - 1;
  111447. pIn->iCur = iTab;
  111448. if( eType==IN_INDEX_ROWID ){
  111449. pIn->addrInTop = sqlite3VdbeAddOp2(v, OP_Rowid, iTab, iReg);
  111450. }else{
  111451. pIn->addrInTop = sqlite3VdbeAddOp3(v, OP_Column, iTab, 0, iReg);
  111452. }
  111453. pIn->eEndLoopOp = bRev ? OP_PrevIfOpen : OP_NextIfOpen;
  111454. sqlite3VdbeAddOp1(v, OP_IsNull, iReg); VdbeCoverage(v);
  111455. }else{
  111456. pLevel->u.in.nIn = 0;
  111457. }
  111458. #endif
  111459. }
  111460. disableTerm(pLevel, pTerm);
  111461. return iReg;
  111462. }
  111463. /*
  111464. ** Generate code that will evaluate all == and IN constraints for an
  111465. ** index scan.
  111466. **
  111467. ** For example, consider table t1(a,b,c,d,e,f) with index i1(a,b,c).
  111468. ** Suppose the WHERE clause is this: a==5 AND b IN (1,2,3) AND c>5 AND c<10
  111469. ** The index has as many as three equality constraints, but in this
  111470. ** example, the third "c" value is an inequality. So only two
  111471. ** constraints are coded. This routine will generate code to evaluate
  111472. ** a==5 and b IN (1,2,3). The current values for a and b will be stored
  111473. ** in consecutive registers and the index of the first register is returned.
  111474. **
  111475. ** In the example above nEq==2. But this subroutine works for any value
  111476. ** of nEq including 0. If nEq==0, this routine is nearly a no-op.
  111477. ** The only thing it does is allocate the pLevel->iMem memory cell and
  111478. ** compute the affinity string.
  111479. **
  111480. ** The nExtraReg parameter is 0 or 1. It is 0 if all WHERE clause constraints
  111481. ** are == or IN and are covered by the nEq. nExtraReg is 1 if there is
  111482. ** an inequality constraint (such as the "c>=5 AND c<10" in the example) that
  111483. ** occurs after the nEq quality constraints.
  111484. **
  111485. ** This routine allocates a range of nEq+nExtraReg memory cells and returns
  111486. ** the index of the first memory cell in that range. The code that
  111487. ** calls this routine will use that memory range to store keys for
  111488. ** start and termination conditions of the loop.
  111489. ** key value of the loop. If one or more IN operators appear, then
  111490. ** this routine allocates an additional nEq memory cells for internal
  111491. ** use.
  111492. **
  111493. ** Before returning, *pzAff is set to point to a buffer containing a
  111494. ** copy of the column affinity string of the index allocated using
  111495. ** sqlite3DbMalloc(). Except, entries in the copy of the string associated
  111496. ** with equality constraints that use NONE affinity are set to
  111497. ** SQLITE_AFF_NONE. This is to deal with SQL such as the following:
  111498. **
  111499. ** CREATE TABLE t1(a TEXT PRIMARY KEY, b);
  111500. ** SELECT ... FROM t1 AS t2, t1 WHERE t1.a = t2.b;
  111501. **
  111502. ** In the example above, the index on t1(a) has TEXT affinity. But since
  111503. ** the right hand side of the equality constraint (t2.b) has NONE affinity,
  111504. ** no conversion should be attempted before using a t2.b value as part of
  111505. ** a key to search the index. Hence the first byte in the returned affinity
  111506. ** string in this example would be set to SQLITE_AFF_NONE.
  111507. */
  111508. static int codeAllEqualityTerms(
  111509. Parse *pParse, /* Parsing context */
  111510. WhereLevel *pLevel, /* Which nested loop of the FROM we are coding */
  111511. int bRev, /* Reverse the order of IN operators */
  111512. int nExtraReg, /* Number of extra registers to allocate */
  111513. char **pzAff /* OUT: Set to point to affinity string */
  111514. ){
  111515. u16 nEq; /* The number of == or IN constraints to code */
  111516. u16 nSkip; /* Number of left-most columns to skip */
  111517. Vdbe *v = pParse->pVdbe; /* The vm under construction */
  111518. Index *pIdx; /* The index being used for this loop */
  111519. WhereTerm *pTerm; /* A single constraint term */
  111520. WhereLoop *pLoop; /* The WhereLoop object */
  111521. int j; /* Loop counter */
  111522. int regBase; /* Base register */
  111523. int nReg; /* Number of registers to allocate */
  111524. char *zAff; /* Affinity string to return */
  111525. /* This module is only called on query plans that use an index. */
  111526. pLoop = pLevel->pWLoop;
  111527. assert( (pLoop->wsFlags & WHERE_VIRTUALTABLE)==0 );
  111528. nEq = pLoop->u.btree.nEq;
  111529. nSkip = pLoop->nSkip;
  111530. pIdx = pLoop->u.btree.pIndex;
  111531. assert( pIdx!=0 );
  111532. /* Figure out how many memory cells we will need then allocate them.
  111533. */
  111534. regBase = pParse->nMem + 1;
  111535. nReg = pLoop->u.btree.nEq + nExtraReg;
  111536. pParse->nMem += nReg;
  111537. zAff = sqlite3DbStrDup(pParse->db, sqlite3IndexAffinityStr(v, pIdx));
  111538. if( !zAff ){
  111539. pParse->db->mallocFailed = 1;
  111540. }
  111541. if( nSkip ){
  111542. int iIdxCur = pLevel->iIdxCur;
  111543. sqlite3VdbeAddOp1(v, (bRev?OP_Last:OP_Rewind), iIdxCur);
  111544. VdbeCoverageIf(v, bRev==0);
  111545. VdbeCoverageIf(v, bRev!=0);
  111546. VdbeComment((v, "begin skip-scan on %s", pIdx->zName));
  111547. j = sqlite3VdbeAddOp0(v, OP_Goto);
  111548. pLevel->addrSkip = sqlite3VdbeAddOp4Int(v, (bRev?OP_SeekLT:OP_SeekGT),
  111549. iIdxCur, 0, regBase, nSkip);
  111550. VdbeCoverageIf(v, bRev==0);
  111551. VdbeCoverageIf(v, bRev!=0);
  111552. sqlite3VdbeJumpHere(v, j);
  111553. for(j=0; j<nSkip; j++){
  111554. sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, j, regBase+j);
  111555. assert( pIdx->aiColumn[j]>=0 );
  111556. VdbeComment((v, "%s", pIdx->pTable->aCol[pIdx->aiColumn[j]].zName));
  111557. }
  111558. }
  111559. /* Evaluate the equality constraints
  111560. */
  111561. assert( zAff==0 || (int)strlen(zAff)>=nEq );
  111562. for(j=nSkip; j<nEq; j++){
  111563. int r1;
  111564. pTerm = pLoop->aLTerm[j];
  111565. assert( pTerm!=0 );
  111566. /* The following testcase is true for indices with redundant columns.
  111567. ** Ex: CREATE INDEX i1 ON t1(a,b,a); SELECT * FROM t1 WHERE a=0 AND b=0; */
  111568. testcase( (pTerm->wtFlags & TERM_CODED)!=0 );
  111569. testcase( pTerm->wtFlags & TERM_VIRTUAL );
  111570. r1 = codeEqualityTerm(pParse, pTerm, pLevel, j, bRev, regBase+j);
  111571. if( r1!=regBase+j ){
  111572. if( nReg==1 ){
  111573. sqlite3ReleaseTempReg(pParse, regBase);
  111574. regBase = r1;
  111575. }else{
  111576. sqlite3VdbeAddOp2(v, OP_SCopy, r1, regBase+j);
  111577. }
  111578. }
  111579. testcase( pTerm->eOperator & WO_ISNULL );
  111580. testcase( pTerm->eOperator & WO_IN );
  111581. if( (pTerm->eOperator & (WO_ISNULL|WO_IN))==0 ){
  111582. Expr *pRight = pTerm->pExpr->pRight;
  111583. if( sqlite3ExprCanBeNull(pRight) ){
  111584. sqlite3VdbeAddOp2(v, OP_IsNull, regBase+j, pLevel->addrBrk);
  111585. VdbeCoverage(v);
  111586. }
  111587. if( zAff ){
  111588. if( sqlite3CompareAffinity(pRight, zAff[j])==SQLITE_AFF_NONE ){
  111589. zAff[j] = SQLITE_AFF_NONE;
  111590. }
  111591. if( sqlite3ExprNeedsNoAffinityChange(pRight, zAff[j]) ){
  111592. zAff[j] = SQLITE_AFF_NONE;
  111593. }
  111594. }
  111595. }
  111596. }
  111597. *pzAff = zAff;
  111598. return regBase;
  111599. }
  111600. #ifndef SQLITE_OMIT_EXPLAIN
  111601. /*
  111602. ** This routine is a helper for explainIndexRange() below
  111603. **
  111604. ** pStr holds the text of an expression that we are building up one term
  111605. ** at a time. This routine adds a new term to the end of the expression.
  111606. ** Terms are separated by AND so add the "AND" text for second and subsequent
  111607. ** terms only.
  111608. */
  111609. static void explainAppendTerm(
  111610. StrAccum *pStr, /* The text expression being built */
  111611. int iTerm, /* Index of this term. First is zero */
  111612. const char *zColumn, /* Name of the column */
  111613. const char *zOp /* Name of the operator */
  111614. ){
  111615. if( iTerm ) sqlite3StrAccumAppend(pStr, " AND ", 5);
  111616. sqlite3StrAccumAppendAll(pStr, zColumn);
  111617. sqlite3StrAccumAppend(pStr, zOp, 1);
  111618. sqlite3StrAccumAppend(pStr, "?", 1);
  111619. }
  111620. /*
  111621. ** Argument pLevel describes a strategy for scanning table pTab. This
  111622. ** function appends text to pStr that describes the subset of table
  111623. ** rows scanned by the strategy in the form of an SQL expression.
  111624. **
  111625. ** For example, if the query:
  111626. **
  111627. ** SELECT * FROM t1 WHERE a=1 AND b>2;
  111628. **
  111629. ** is run and there is an index on (a, b), then this function returns a
  111630. ** string similar to:
  111631. **
  111632. ** "a=? AND b>?"
  111633. */
  111634. static void explainIndexRange(StrAccum *pStr, WhereLoop *pLoop, Table *pTab){
  111635. Index *pIndex = pLoop->u.btree.pIndex;
  111636. u16 nEq = pLoop->u.btree.nEq;
  111637. u16 nSkip = pLoop->nSkip;
  111638. int i, j;
  111639. Column *aCol = pTab->aCol;
  111640. i16 *aiColumn = pIndex->aiColumn;
  111641. if( nEq==0 && (pLoop->wsFlags&(WHERE_BTM_LIMIT|WHERE_TOP_LIMIT))==0 ) return;
  111642. sqlite3StrAccumAppend(pStr, " (", 2);
  111643. for(i=0; i<nEq; i++){
  111644. char *z = aiColumn[i] < 0 ? "rowid" : aCol[aiColumn[i]].zName;
  111645. if( i>=nSkip ){
  111646. explainAppendTerm(pStr, i, z, "=");
  111647. }else{
  111648. if( i ) sqlite3StrAccumAppend(pStr, " AND ", 5);
  111649. sqlite3XPrintf(pStr, 0, "ANY(%s)", z);
  111650. }
  111651. }
  111652. j = i;
  111653. if( pLoop->wsFlags&WHERE_BTM_LIMIT ){
  111654. char *z = aiColumn[j] < 0 ? "rowid" : aCol[aiColumn[j]].zName;
  111655. explainAppendTerm(pStr, i++, z, ">");
  111656. }
  111657. if( pLoop->wsFlags&WHERE_TOP_LIMIT ){
  111658. char *z = aiColumn[j] < 0 ? "rowid" : aCol[aiColumn[j]].zName;
  111659. explainAppendTerm(pStr, i, z, "<");
  111660. }
  111661. sqlite3StrAccumAppend(pStr, ")", 1);
  111662. }
  111663. /*
  111664. ** This function is a no-op unless currently processing an EXPLAIN QUERY PLAN
  111665. ** command, or if either SQLITE_DEBUG or SQLITE_ENABLE_STMT_SCANSTATUS was
  111666. ** defined at compile-time. If it is not a no-op, a single OP_Explain opcode
  111667. ** is added to the output to describe the table scan strategy in pLevel.
  111668. **
  111669. ** If an OP_Explain opcode is added to the VM, its address is returned.
  111670. ** Otherwise, if no OP_Explain is coded, zero is returned.
  111671. */
  111672. static int explainOneScan(
  111673. Parse *pParse, /* Parse context */
  111674. SrcList *pTabList, /* Table list this loop refers to */
  111675. WhereLevel *pLevel, /* Scan to write OP_Explain opcode for */
  111676. int iLevel, /* Value for "level" column of output */
  111677. int iFrom, /* Value for "from" column of output */
  111678. u16 wctrlFlags /* Flags passed to sqlite3WhereBegin() */
  111679. ){
  111680. int ret = 0;
  111681. #if !defined(SQLITE_DEBUG) && !defined(SQLITE_ENABLE_STMT_SCANSTATUS)
  111682. if( pParse->explain==2 )
  111683. #endif
  111684. {
  111685. struct SrcList_item *pItem = &pTabList->a[pLevel->iFrom];
  111686. Vdbe *v = pParse->pVdbe; /* VM being constructed */
  111687. sqlite3 *db = pParse->db; /* Database handle */
  111688. int iId = pParse->iSelectId; /* Select id (left-most output column) */
  111689. int isSearch; /* True for a SEARCH. False for SCAN. */
  111690. WhereLoop *pLoop; /* The controlling WhereLoop object */
  111691. u32 flags; /* Flags that describe this loop */
  111692. char *zMsg; /* Text to add to EQP output */
  111693. StrAccum str; /* EQP output string */
  111694. char zBuf[100]; /* Initial space for EQP output string */
  111695. pLoop = pLevel->pWLoop;
  111696. flags = pLoop->wsFlags;
  111697. if( (flags&WHERE_MULTI_OR) || (wctrlFlags&WHERE_ONETABLE_ONLY) ) return 0;
  111698. isSearch = (flags&(WHERE_BTM_LIMIT|WHERE_TOP_LIMIT))!=0
  111699. || ((flags&WHERE_VIRTUALTABLE)==0 && (pLoop->u.btree.nEq>0))
  111700. || (wctrlFlags&(WHERE_ORDERBY_MIN|WHERE_ORDERBY_MAX));
  111701. sqlite3StrAccumInit(&str, db, zBuf, sizeof(zBuf), SQLITE_MAX_LENGTH);
  111702. sqlite3StrAccumAppendAll(&str, isSearch ? "SEARCH" : "SCAN");
  111703. if( pItem->pSelect ){
  111704. sqlite3XPrintf(&str, 0, " SUBQUERY %d", pItem->iSelectId);
  111705. }else{
  111706. sqlite3XPrintf(&str, 0, " TABLE %s", pItem->zName);
  111707. }
  111708. if( pItem->zAlias ){
  111709. sqlite3XPrintf(&str, 0, " AS %s", pItem->zAlias);
  111710. }
  111711. if( (flags & (WHERE_IPK|WHERE_VIRTUALTABLE))==0 ){
  111712. const char *zFmt = 0;
  111713. Index *pIdx;
  111714. assert( pLoop->u.btree.pIndex!=0 );
  111715. pIdx = pLoop->u.btree.pIndex;
  111716. assert( !(flags&WHERE_AUTO_INDEX) || (flags&WHERE_IDX_ONLY) );
  111717. if( !HasRowid(pItem->pTab) && IsPrimaryKeyIndex(pIdx) ){
  111718. if( isSearch ){
  111719. zFmt = "PRIMARY KEY";
  111720. }
  111721. }else if( flags & WHERE_PARTIALIDX ){
  111722. zFmt = "AUTOMATIC PARTIAL COVERING INDEX";
  111723. }else if( flags & WHERE_AUTO_INDEX ){
  111724. zFmt = "AUTOMATIC COVERING INDEX";
  111725. }else if( flags & WHERE_IDX_ONLY ){
  111726. zFmt = "COVERING INDEX %s";
  111727. }else{
  111728. zFmt = "INDEX %s";
  111729. }
  111730. if( zFmt ){
  111731. sqlite3StrAccumAppend(&str, " USING ", 7);
  111732. sqlite3XPrintf(&str, 0, zFmt, pIdx->zName);
  111733. explainIndexRange(&str, pLoop, pItem->pTab);
  111734. }
  111735. }else if( (flags & WHERE_IPK)!=0 && (flags & WHERE_CONSTRAINT)!=0 ){
  111736. const char *zRange;
  111737. if( flags&(WHERE_COLUMN_EQ|WHERE_COLUMN_IN) ){
  111738. zRange = "(rowid=?)";
  111739. }else if( (flags&WHERE_BOTH_LIMIT)==WHERE_BOTH_LIMIT ){
  111740. zRange = "(rowid>? AND rowid<?)";
  111741. }else if( flags&WHERE_BTM_LIMIT ){
  111742. zRange = "(rowid>?)";
  111743. }else{
  111744. assert( flags&WHERE_TOP_LIMIT);
  111745. zRange = "(rowid<?)";
  111746. }
  111747. sqlite3StrAccumAppendAll(&str, " USING INTEGER PRIMARY KEY ");
  111748. sqlite3StrAccumAppendAll(&str, zRange);
  111749. }
  111750. #ifndef SQLITE_OMIT_VIRTUALTABLE
  111751. else if( (flags & WHERE_VIRTUALTABLE)!=0 ){
  111752. sqlite3XPrintf(&str, 0, " VIRTUAL TABLE INDEX %d:%s",
  111753. pLoop->u.vtab.idxNum, pLoop->u.vtab.idxStr);
  111754. }
  111755. #endif
  111756. #ifdef SQLITE_EXPLAIN_ESTIMATED_ROWS
  111757. if( pLoop->nOut>=10 ){
  111758. sqlite3XPrintf(&str, 0, " (~%llu rows)", sqlite3LogEstToInt(pLoop->nOut));
  111759. }else{
  111760. sqlite3StrAccumAppend(&str, " (~1 row)", 9);
  111761. }
  111762. #endif
  111763. zMsg = sqlite3StrAccumFinish(&str);
  111764. ret = sqlite3VdbeAddOp4(v, OP_Explain, iId, iLevel, iFrom, zMsg,P4_DYNAMIC);
  111765. }
  111766. return ret;
  111767. }
  111768. #else
  111769. # define explainOneScan(u,v,w,x,y,z) 0
  111770. #endif /* SQLITE_OMIT_EXPLAIN */
  111771. #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
  111772. /*
  111773. ** Configure the VM passed as the first argument with an
  111774. ** sqlite3_stmt_scanstatus() entry corresponding to the scan used to
  111775. ** implement level pLvl. Argument pSrclist is a pointer to the FROM
  111776. ** clause that the scan reads data from.
  111777. **
  111778. ** If argument addrExplain is not 0, it must be the address of an
  111779. ** OP_Explain instruction that describes the same loop.
  111780. */
  111781. static void addScanStatus(
  111782. Vdbe *v, /* Vdbe to add scanstatus entry to */
  111783. SrcList *pSrclist, /* FROM clause pLvl reads data from */
  111784. WhereLevel *pLvl, /* Level to add scanstatus() entry for */
  111785. int addrExplain /* Address of OP_Explain (or 0) */
  111786. ){
  111787. const char *zObj = 0;
  111788. WhereLoop *pLoop = pLvl->pWLoop;
  111789. if( (pLoop->wsFlags & WHERE_VIRTUALTABLE)==0 && pLoop->u.btree.pIndex!=0 ){
  111790. zObj = pLoop->u.btree.pIndex->zName;
  111791. }else{
  111792. zObj = pSrclist->a[pLvl->iFrom].zName;
  111793. }
  111794. sqlite3VdbeScanStatus(
  111795. v, addrExplain, pLvl->addrBody, pLvl->addrVisit, pLoop->nOut, zObj
  111796. );
  111797. }
  111798. #else
  111799. # define addScanStatus(a, b, c, d) ((void)d)
  111800. #endif
  111801. /*
  111802. ** If the most recently coded instruction is a constant range contraint
  111803. ** that originated from the LIKE optimization, then change the P3 to be
  111804. ** pLoop->iLikeRepCntr and set P5.
  111805. **
  111806. ** The LIKE optimization trys to evaluate "x LIKE 'abc%'" as a range
  111807. ** expression: "x>='ABC' AND x<'abd'". But this requires that the range
  111808. ** scan loop run twice, once for strings and a second time for BLOBs.
  111809. ** The OP_String opcodes on the second pass convert the upper and lower
  111810. ** bound string contants to blobs. This routine makes the necessary changes
  111811. ** to the OP_String opcodes for that to happen.
  111812. */
  111813. static void whereLikeOptimizationStringFixup(
  111814. Vdbe *v, /* prepared statement under construction */
  111815. WhereLevel *pLevel, /* The loop that contains the LIKE operator */
  111816. WhereTerm *pTerm /* The upper or lower bound just coded */
  111817. ){
  111818. if( pTerm->wtFlags & TERM_LIKEOPT ){
  111819. VdbeOp *pOp;
  111820. assert( pLevel->iLikeRepCntr>0 );
  111821. pOp = sqlite3VdbeGetOp(v, -1);
  111822. assert( pOp!=0 );
  111823. assert( pOp->opcode==OP_String8
  111824. || pTerm->pWC->pWInfo->pParse->db->mallocFailed );
  111825. pOp->p3 = pLevel->iLikeRepCntr;
  111826. pOp->p5 = 1;
  111827. }
  111828. }
  111829. /*
  111830. ** Generate code for the start of the iLevel-th loop in the WHERE clause
  111831. ** implementation described by pWInfo.
  111832. */
  111833. static Bitmask codeOneLoopStart(
  111834. WhereInfo *pWInfo, /* Complete information about the WHERE clause */
  111835. int iLevel, /* Which level of pWInfo->a[] should be coded */
  111836. Bitmask notReady /* Which tables are currently available */
  111837. ){
  111838. int j, k; /* Loop counters */
  111839. int iCur; /* The VDBE cursor for the table */
  111840. int addrNxt; /* Where to jump to continue with the next IN case */
  111841. int omitTable; /* True if we use the index only */
  111842. int bRev; /* True if we need to scan in reverse order */
  111843. WhereLevel *pLevel; /* The where level to be coded */
  111844. WhereLoop *pLoop; /* The WhereLoop object being coded */
  111845. WhereClause *pWC; /* Decomposition of the entire WHERE clause */
  111846. WhereTerm *pTerm; /* A WHERE clause term */
  111847. Parse *pParse; /* Parsing context */
  111848. sqlite3 *db; /* Database connection */
  111849. Vdbe *v; /* The prepared stmt under constructions */
  111850. struct SrcList_item *pTabItem; /* FROM clause term being coded */
  111851. int addrBrk; /* Jump here to break out of the loop */
  111852. int addrCont; /* Jump here to continue with next cycle */
  111853. int iRowidReg = 0; /* Rowid is stored in this register, if not zero */
  111854. int iReleaseReg = 0; /* Temp register to free before returning */
  111855. pParse = pWInfo->pParse;
  111856. v = pParse->pVdbe;
  111857. pWC = &pWInfo->sWC;
  111858. db = pParse->db;
  111859. pLevel = &pWInfo->a[iLevel];
  111860. pLoop = pLevel->pWLoop;
  111861. pTabItem = &pWInfo->pTabList->a[pLevel->iFrom];
  111862. iCur = pTabItem->iCursor;
  111863. pLevel->notReady = notReady & ~getMask(&pWInfo->sMaskSet, iCur);
  111864. bRev = (pWInfo->revMask>>iLevel)&1;
  111865. omitTable = (pLoop->wsFlags & WHERE_IDX_ONLY)!=0
  111866. && (pWInfo->wctrlFlags & WHERE_FORCE_TABLE)==0;
  111867. VdbeModuleComment((v, "Begin WHERE-loop%d: %s",iLevel,pTabItem->pTab->zName));
  111868. /* Create labels for the "break" and "continue" instructions
  111869. ** for the current loop. Jump to addrBrk to break out of a loop.
  111870. ** Jump to cont to go immediately to the next iteration of the
  111871. ** loop.
  111872. **
  111873. ** When there is an IN operator, we also have a "addrNxt" label that
  111874. ** means to continue with the next IN value combination. When
  111875. ** there are no IN operators in the constraints, the "addrNxt" label
  111876. ** is the same as "addrBrk".
  111877. */
  111878. addrBrk = pLevel->addrBrk = pLevel->addrNxt = sqlite3VdbeMakeLabel(v);
  111879. addrCont = pLevel->addrCont = sqlite3VdbeMakeLabel(v);
  111880. /* If this is the right table of a LEFT OUTER JOIN, allocate and
  111881. ** initialize a memory cell that records if this table matches any
  111882. ** row of the left table of the join.
  111883. */
  111884. if( pLevel->iFrom>0 && (pTabItem[0].jointype & JT_LEFT)!=0 ){
  111885. pLevel->iLeftJoin = ++pParse->nMem;
  111886. sqlite3VdbeAddOp2(v, OP_Integer, 0, pLevel->iLeftJoin);
  111887. VdbeComment((v, "init LEFT JOIN no-match flag"));
  111888. }
  111889. /* Special case of a FROM clause subquery implemented as a co-routine */
  111890. if( pTabItem->viaCoroutine ){
  111891. int regYield = pTabItem->regReturn;
  111892. sqlite3VdbeAddOp3(v, OP_InitCoroutine, regYield, 0, pTabItem->addrFillSub);
  111893. pLevel->p2 = sqlite3VdbeAddOp2(v, OP_Yield, regYield, addrBrk);
  111894. VdbeCoverage(v);
  111895. VdbeComment((v, "next row of \"%s\"", pTabItem->pTab->zName));
  111896. pLevel->op = OP_Goto;
  111897. }else
  111898. #ifndef SQLITE_OMIT_VIRTUALTABLE
  111899. if( (pLoop->wsFlags & WHERE_VIRTUALTABLE)!=0 ){
  111900. /* Case 1: The table is a virtual-table. Use the VFilter and VNext
  111901. ** to access the data.
  111902. */
  111903. int iReg; /* P3 Value for OP_VFilter */
  111904. int addrNotFound;
  111905. int nConstraint = pLoop->nLTerm;
  111906. sqlite3ExprCachePush(pParse);
  111907. iReg = sqlite3GetTempRange(pParse, nConstraint+2);
  111908. addrNotFound = pLevel->addrBrk;
  111909. for(j=0; j<nConstraint; j++){
  111910. int iTarget = iReg+j+2;
  111911. pTerm = pLoop->aLTerm[j];
  111912. if( pTerm==0 ) continue;
  111913. if( pTerm->eOperator & WO_IN ){
  111914. codeEqualityTerm(pParse, pTerm, pLevel, j, bRev, iTarget);
  111915. addrNotFound = pLevel->addrNxt;
  111916. }else{
  111917. sqlite3ExprCode(pParse, pTerm->pExpr->pRight, iTarget);
  111918. }
  111919. }
  111920. sqlite3VdbeAddOp2(v, OP_Integer, pLoop->u.vtab.idxNum, iReg);
  111921. sqlite3VdbeAddOp2(v, OP_Integer, nConstraint, iReg+1);
  111922. sqlite3VdbeAddOp4(v, OP_VFilter, iCur, addrNotFound, iReg,
  111923. pLoop->u.vtab.idxStr,
  111924. pLoop->u.vtab.needFree ? P4_MPRINTF : P4_STATIC);
  111925. VdbeCoverage(v);
  111926. pLoop->u.vtab.needFree = 0;
  111927. for(j=0; j<nConstraint && j<16; j++){
  111928. if( (pLoop->u.vtab.omitMask>>j)&1 ){
  111929. disableTerm(pLevel, pLoop->aLTerm[j]);
  111930. }
  111931. }
  111932. pLevel->op = OP_VNext;
  111933. pLevel->p1 = iCur;
  111934. pLevel->p2 = sqlite3VdbeCurrentAddr(v);
  111935. sqlite3ReleaseTempRange(pParse, iReg, nConstraint+2);
  111936. sqlite3ExprCachePop(pParse);
  111937. }else
  111938. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  111939. if( (pLoop->wsFlags & WHERE_IPK)!=0
  111940. && (pLoop->wsFlags & (WHERE_COLUMN_IN|WHERE_COLUMN_EQ))!=0
  111941. ){
  111942. /* Case 2: We can directly reference a single row using an
  111943. ** equality comparison against the ROWID field. Or
  111944. ** we reference multiple rows using a "rowid IN (...)"
  111945. ** construct.
  111946. */
  111947. assert( pLoop->u.btree.nEq==1 );
  111948. pTerm = pLoop->aLTerm[0];
  111949. assert( pTerm!=0 );
  111950. assert( pTerm->pExpr!=0 );
  111951. assert( omitTable==0 );
  111952. testcase( pTerm->wtFlags & TERM_VIRTUAL );
  111953. iReleaseReg = ++pParse->nMem;
  111954. iRowidReg = codeEqualityTerm(pParse, pTerm, pLevel, 0, bRev, iReleaseReg);
  111955. if( iRowidReg!=iReleaseReg ) sqlite3ReleaseTempReg(pParse, iReleaseReg);
  111956. addrNxt = pLevel->addrNxt;
  111957. sqlite3VdbeAddOp2(v, OP_MustBeInt, iRowidReg, addrNxt); VdbeCoverage(v);
  111958. sqlite3VdbeAddOp3(v, OP_NotExists, iCur, addrNxt, iRowidReg);
  111959. VdbeCoverage(v);
  111960. sqlite3ExprCacheAffinityChange(pParse, iRowidReg, 1);
  111961. sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
  111962. VdbeComment((v, "pk"));
  111963. pLevel->op = OP_Noop;
  111964. }else if( (pLoop->wsFlags & WHERE_IPK)!=0
  111965. && (pLoop->wsFlags & WHERE_COLUMN_RANGE)!=0
  111966. ){
  111967. /* Case 3: We have an inequality comparison against the ROWID field.
  111968. */
  111969. int testOp = OP_Noop;
  111970. int start;
  111971. int memEndValue = 0;
  111972. WhereTerm *pStart, *pEnd;
  111973. assert( omitTable==0 );
  111974. j = 0;
  111975. pStart = pEnd = 0;
  111976. if( pLoop->wsFlags & WHERE_BTM_LIMIT ) pStart = pLoop->aLTerm[j++];
  111977. if( pLoop->wsFlags & WHERE_TOP_LIMIT ) pEnd = pLoop->aLTerm[j++];
  111978. assert( pStart!=0 || pEnd!=0 );
  111979. if( bRev ){
  111980. pTerm = pStart;
  111981. pStart = pEnd;
  111982. pEnd = pTerm;
  111983. }
  111984. if( pStart ){
  111985. Expr *pX; /* The expression that defines the start bound */
  111986. int r1, rTemp; /* Registers for holding the start boundary */
  111987. /* The following constant maps TK_xx codes into corresponding
  111988. ** seek opcodes. It depends on a particular ordering of TK_xx
  111989. */
  111990. const u8 aMoveOp[] = {
  111991. /* TK_GT */ OP_SeekGT,
  111992. /* TK_LE */ OP_SeekLE,
  111993. /* TK_LT */ OP_SeekLT,
  111994. /* TK_GE */ OP_SeekGE
  111995. };
  111996. assert( TK_LE==TK_GT+1 ); /* Make sure the ordering.. */
  111997. assert( TK_LT==TK_GT+2 ); /* ... of the TK_xx values... */
  111998. assert( TK_GE==TK_GT+3 ); /* ... is correcct. */
  111999. assert( (pStart->wtFlags & TERM_VNULL)==0 );
  112000. testcase( pStart->wtFlags & TERM_VIRTUAL );
  112001. pX = pStart->pExpr;
  112002. assert( pX!=0 );
  112003. testcase( pStart->leftCursor!=iCur ); /* transitive constraints */
  112004. r1 = sqlite3ExprCodeTemp(pParse, pX->pRight, &rTemp);
  112005. sqlite3VdbeAddOp3(v, aMoveOp[pX->op-TK_GT], iCur, addrBrk, r1);
  112006. VdbeComment((v, "pk"));
  112007. VdbeCoverageIf(v, pX->op==TK_GT);
  112008. VdbeCoverageIf(v, pX->op==TK_LE);
  112009. VdbeCoverageIf(v, pX->op==TK_LT);
  112010. VdbeCoverageIf(v, pX->op==TK_GE);
  112011. sqlite3ExprCacheAffinityChange(pParse, r1, 1);
  112012. sqlite3ReleaseTempReg(pParse, rTemp);
  112013. disableTerm(pLevel, pStart);
  112014. }else{
  112015. sqlite3VdbeAddOp2(v, bRev ? OP_Last : OP_Rewind, iCur, addrBrk);
  112016. VdbeCoverageIf(v, bRev==0);
  112017. VdbeCoverageIf(v, bRev!=0);
  112018. }
  112019. if( pEnd ){
  112020. Expr *pX;
  112021. pX = pEnd->pExpr;
  112022. assert( pX!=0 );
  112023. assert( (pEnd->wtFlags & TERM_VNULL)==0 );
  112024. testcase( pEnd->leftCursor!=iCur ); /* Transitive constraints */
  112025. testcase( pEnd->wtFlags & TERM_VIRTUAL );
  112026. memEndValue = ++pParse->nMem;
  112027. sqlite3ExprCode(pParse, pX->pRight, memEndValue);
  112028. if( pX->op==TK_LT || pX->op==TK_GT ){
  112029. testOp = bRev ? OP_Le : OP_Ge;
  112030. }else{
  112031. testOp = bRev ? OP_Lt : OP_Gt;
  112032. }
  112033. disableTerm(pLevel, pEnd);
  112034. }
  112035. start = sqlite3VdbeCurrentAddr(v);
  112036. pLevel->op = bRev ? OP_Prev : OP_Next;
  112037. pLevel->p1 = iCur;
  112038. pLevel->p2 = start;
  112039. assert( pLevel->p5==0 );
  112040. if( testOp!=OP_Noop ){
  112041. iRowidReg = ++pParse->nMem;
  112042. sqlite3VdbeAddOp2(v, OP_Rowid, iCur, iRowidReg);
  112043. sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
  112044. sqlite3VdbeAddOp3(v, testOp, memEndValue, addrBrk, iRowidReg);
  112045. VdbeCoverageIf(v, testOp==OP_Le);
  112046. VdbeCoverageIf(v, testOp==OP_Lt);
  112047. VdbeCoverageIf(v, testOp==OP_Ge);
  112048. VdbeCoverageIf(v, testOp==OP_Gt);
  112049. sqlite3VdbeChangeP5(v, SQLITE_AFF_NUMERIC | SQLITE_JUMPIFNULL);
  112050. }
  112051. }else if( pLoop->wsFlags & WHERE_INDEXED ){
  112052. /* Case 4: A scan using an index.
  112053. **
  112054. ** The WHERE clause may contain zero or more equality
  112055. ** terms ("==" or "IN" operators) that refer to the N
  112056. ** left-most columns of the index. It may also contain
  112057. ** inequality constraints (>, <, >= or <=) on the indexed
  112058. ** column that immediately follows the N equalities. Only
  112059. ** the right-most column can be an inequality - the rest must
  112060. ** use the "==" and "IN" operators. For example, if the
  112061. ** index is on (x,y,z), then the following clauses are all
  112062. ** optimized:
  112063. **
  112064. ** x=5
  112065. ** x=5 AND y=10
  112066. ** x=5 AND y<10
  112067. ** x=5 AND y>5 AND y<10
  112068. ** x=5 AND y=5 AND z<=10
  112069. **
  112070. ** The z<10 term of the following cannot be used, only
  112071. ** the x=5 term:
  112072. **
  112073. ** x=5 AND z<10
  112074. **
  112075. ** N may be zero if there are inequality constraints.
  112076. ** If there are no inequality constraints, then N is at
  112077. ** least one.
  112078. **
  112079. ** This case is also used when there are no WHERE clause
  112080. ** constraints but an index is selected anyway, in order
  112081. ** to force the output order to conform to an ORDER BY.
  112082. */
  112083. static const u8 aStartOp[] = {
  112084. 0,
  112085. 0,
  112086. OP_Rewind, /* 2: (!start_constraints && startEq && !bRev) */
  112087. OP_Last, /* 3: (!start_constraints && startEq && bRev) */
  112088. OP_SeekGT, /* 4: (start_constraints && !startEq && !bRev) */
  112089. OP_SeekLT, /* 5: (start_constraints && !startEq && bRev) */
  112090. OP_SeekGE, /* 6: (start_constraints && startEq && !bRev) */
  112091. OP_SeekLE /* 7: (start_constraints && startEq && bRev) */
  112092. };
  112093. static const u8 aEndOp[] = {
  112094. OP_IdxGE, /* 0: (end_constraints && !bRev && !endEq) */
  112095. OP_IdxGT, /* 1: (end_constraints && !bRev && endEq) */
  112096. OP_IdxLE, /* 2: (end_constraints && bRev && !endEq) */
  112097. OP_IdxLT, /* 3: (end_constraints && bRev && endEq) */
  112098. };
  112099. u16 nEq = pLoop->u.btree.nEq; /* Number of == or IN terms */
  112100. int regBase; /* Base register holding constraint values */
  112101. WhereTerm *pRangeStart = 0; /* Inequality constraint at range start */
  112102. WhereTerm *pRangeEnd = 0; /* Inequality constraint at range end */
  112103. int startEq; /* True if range start uses ==, >= or <= */
  112104. int endEq; /* True if range end uses ==, >= or <= */
  112105. int start_constraints; /* Start of range is constrained */
  112106. int nConstraint; /* Number of constraint terms */
  112107. Index *pIdx; /* The index we will be using */
  112108. int iIdxCur; /* The VDBE cursor for the index */
  112109. int nExtraReg = 0; /* Number of extra registers needed */
  112110. int op; /* Instruction opcode */
  112111. char *zStartAff; /* Affinity for start of range constraint */
  112112. char cEndAff = 0; /* Affinity for end of range constraint */
  112113. u8 bSeekPastNull = 0; /* True to seek past initial nulls */
  112114. u8 bStopAtNull = 0; /* Add condition to terminate at NULLs */
  112115. pIdx = pLoop->u.btree.pIndex;
  112116. iIdxCur = pLevel->iIdxCur;
  112117. assert( nEq>=pLoop->nSkip );
  112118. /* If this loop satisfies a sort order (pOrderBy) request that
  112119. ** was passed to this function to implement a "SELECT min(x) ..."
  112120. ** query, then the caller will only allow the loop to run for
  112121. ** a single iteration. This means that the first row returned
  112122. ** should not have a NULL value stored in 'x'. If column 'x' is
  112123. ** the first one after the nEq equality constraints in the index,
  112124. ** this requires some special handling.
  112125. */
  112126. assert( pWInfo->pOrderBy==0
  112127. || pWInfo->pOrderBy->nExpr==1
  112128. || (pWInfo->wctrlFlags&WHERE_ORDERBY_MIN)==0 );
  112129. if( (pWInfo->wctrlFlags&WHERE_ORDERBY_MIN)!=0
  112130. && pWInfo->nOBSat>0
  112131. && (pIdx->nKeyCol>nEq)
  112132. ){
  112133. assert( pLoop->nSkip==0 );
  112134. bSeekPastNull = 1;
  112135. nExtraReg = 1;
  112136. }
  112137. /* Find any inequality constraint terms for the start and end
  112138. ** of the range.
  112139. */
  112140. j = nEq;
  112141. if( pLoop->wsFlags & WHERE_BTM_LIMIT ){
  112142. pRangeStart = pLoop->aLTerm[j++];
  112143. nExtraReg = 1;
  112144. /* Like optimization range constraints always occur in pairs */
  112145. assert( (pRangeStart->wtFlags & TERM_LIKEOPT)==0 ||
  112146. (pLoop->wsFlags & WHERE_TOP_LIMIT)!=0 );
  112147. }
  112148. if( pLoop->wsFlags & WHERE_TOP_LIMIT ){
  112149. pRangeEnd = pLoop->aLTerm[j++];
  112150. nExtraReg = 1;
  112151. if( (pRangeEnd->wtFlags & TERM_LIKEOPT)!=0 ){
  112152. assert( pRangeStart!=0 ); /* LIKE opt constraints */
  112153. assert( pRangeStart->wtFlags & TERM_LIKEOPT ); /* occur in pairs */
  112154. pLevel->iLikeRepCntr = ++pParse->nMem;
  112155. testcase( bRev );
  112156. testcase( pIdx->aSortOrder[nEq]==SQLITE_SO_DESC );
  112157. sqlite3VdbeAddOp2(v, OP_Integer,
  112158. bRev ^ (pIdx->aSortOrder[nEq]==SQLITE_SO_DESC),
  112159. pLevel->iLikeRepCntr);
  112160. VdbeComment((v, "LIKE loop counter"));
  112161. pLevel->addrLikeRep = sqlite3VdbeCurrentAddr(v);
  112162. }
  112163. if( pRangeStart==0
  112164. && (j = pIdx->aiColumn[nEq])>=0
  112165. && pIdx->pTable->aCol[j].notNull==0
  112166. ){
  112167. bSeekPastNull = 1;
  112168. }
  112169. }
  112170. assert( pRangeEnd==0 || (pRangeEnd->wtFlags & TERM_VNULL)==0 );
  112171. /* Generate code to evaluate all constraint terms using == or IN
  112172. ** and store the values of those terms in an array of registers
  112173. ** starting at regBase.
  112174. */
  112175. regBase = codeAllEqualityTerms(pParse,pLevel,bRev,nExtraReg,&zStartAff);
  112176. assert( zStartAff==0 || sqlite3Strlen30(zStartAff)>=nEq );
  112177. if( zStartAff ) cEndAff = zStartAff[nEq];
  112178. addrNxt = pLevel->addrNxt;
  112179. /* If we are doing a reverse order scan on an ascending index, or
  112180. ** a forward order scan on a descending index, interchange the
  112181. ** start and end terms (pRangeStart and pRangeEnd).
  112182. */
  112183. if( (nEq<pIdx->nKeyCol && bRev==(pIdx->aSortOrder[nEq]==SQLITE_SO_ASC))
  112184. || (bRev && pIdx->nKeyCol==nEq)
  112185. ){
  112186. SWAP(WhereTerm *, pRangeEnd, pRangeStart);
  112187. SWAP(u8, bSeekPastNull, bStopAtNull);
  112188. }
  112189. testcase( pRangeStart && (pRangeStart->eOperator & WO_LE)!=0 );
  112190. testcase( pRangeStart && (pRangeStart->eOperator & WO_GE)!=0 );
  112191. testcase( pRangeEnd && (pRangeEnd->eOperator & WO_LE)!=0 );
  112192. testcase( pRangeEnd && (pRangeEnd->eOperator & WO_GE)!=0 );
  112193. startEq = !pRangeStart || pRangeStart->eOperator & (WO_LE|WO_GE);
  112194. endEq = !pRangeEnd || pRangeEnd->eOperator & (WO_LE|WO_GE);
  112195. start_constraints = pRangeStart || nEq>0;
  112196. /* Seek the index cursor to the start of the range. */
  112197. nConstraint = nEq;
  112198. if( pRangeStart ){
  112199. Expr *pRight = pRangeStart->pExpr->pRight;
  112200. sqlite3ExprCode(pParse, pRight, regBase+nEq);
  112201. whereLikeOptimizationStringFixup(v, pLevel, pRangeStart);
  112202. if( (pRangeStart->wtFlags & TERM_VNULL)==0
  112203. && sqlite3ExprCanBeNull(pRight)
  112204. ){
  112205. sqlite3VdbeAddOp2(v, OP_IsNull, regBase+nEq, addrNxt);
  112206. VdbeCoverage(v);
  112207. }
  112208. if( zStartAff ){
  112209. if( sqlite3CompareAffinity(pRight, zStartAff[nEq])==SQLITE_AFF_NONE){
  112210. /* Since the comparison is to be performed with no conversions
  112211. ** applied to the operands, set the affinity to apply to pRight to
  112212. ** SQLITE_AFF_NONE. */
  112213. zStartAff[nEq] = SQLITE_AFF_NONE;
  112214. }
  112215. if( sqlite3ExprNeedsNoAffinityChange(pRight, zStartAff[nEq]) ){
  112216. zStartAff[nEq] = SQLITE_AFF_NONE;
  112217. }
  112218. }
  112219. nConstraint++;
  112220. testcase( pRangeStart->wtFlags & TERM_VIRTUAL );
  112221. }else if( bSeekPastNull ){
  112222. sqlite3VdbeAddOp2(v, OP_Null, 0, regBase+nEq);
  112223. nConstraint++;
  112224. startEq = 0;
  112225. start_constraints = 1;
  112226. }
  112227. codeApplyAffinity(pParse, regBase, nConstraint - bSeekPastNull, zStartAff);
  112228. op = aStartOp[(start_constraints<<2) + (startEq<<1) + bRev];
  112229. assert( op!=0 );
  112230. sqlite3VdbeAddOp4Int(v, op, iIdxCur, addrNxt, regBase, nConstraint);
  112231. VdbeCoverage(v);
  112232. VdbeCoverageIf(v, op==OP_Rewind); testcase( op==OP_Rewind );
  112233. VdbeCoverageIf(v, op==OP_Last); testcase( op==OP_Last );
  112234. VdbeCoverageIf(v, op==OP_SeekGT); testcase( op==OP_SeekGT );
  112235. VdbeCoverageIf(v, op==OP_SeekGE); testcase( op==OP_SeekGE );
  112236. VdbeCoverageIf(v, op==OP_SeekLE); testcase( op==OP_SeekLE );
  112237. VdbeCoverageIf(v, op==OP_SeekLT); testcase( op==OP_SeekLT );
  112238. /* Load the value for the inequality constraint at the end of the
  112239. ** range (if any).
  112240. */
  112241. nConstraint = nEq;
  112242. if( pRangeEnd ){
  112243. Expr *pRight = pRangeEnd->pExpr->pRight;
  112244. sqlite3ExprCacheRemove(pParse, regBase+nEq, 1);
  112245. sqlite3ExprCode(pParse, pRight, regBase+nEq);
  112246. whereLikeOptimizationStringFixup(v, pLevel, pRangeEnd);
  112247. if( (pRangeEnd->wtFlags & TERM_VNULL)==0
  112248. && sqlite3ExprCanBeNull(pRight)
  112249. ){
  112250. sqlite3VdbeAddOp2(v, OP_IsNull, regBase+nEq, addrNxt);
  112251. VdbeCoverage(v);
  112252. }
  112253. if( sqlite3CompareAffinity(pRight, cEndAff)!=SQLITE_AFF_NONE
  112254. && !sqlite3ExprNeedsNoAffinityChange(pRight, cEndAff)
  112255. ){
  112256. codeApplyAffinity(pParse, regBase+nEq, 1, &cEndAff);
  112257. }
  112258. nConstraint++;
  112259. testcase( pRangeEnd->wtFlags & TERM_VIRTUAL );
  112260. }else if( bStopAtNull ){
  112261. sqlite3VdbeAddOp2(v, OP_Null, 0, regBase+nEq);
  112262. endEq = 0;
  112263. nConstraint++;
  112264. }
  112265. sqlite3DbFree(db, zStartAff);
  112266. /* Top of the loop body */
  112267. pLevel->p2 = sqlite3VdbeCurrentAddr(v);
  112268. /* Check if the index cursor is past the end of the range. */
  112269. if( nConstraint ){
  112270. op = aEndOp[bRev*2 + endEq];
  112271. sqlite3VdbeAddOp4Int(v, op, iIdxCur, addrNxt, regBase, nConstraint);
  112272. testcase( op==OP_IdxGT ); VdbeCoverageIf(v, op==OP_IdxGT );
  112273. testcase( op==OP_IdxGE ); VdbeCoverageIf(v, op==OP_IdxGE );
  112274. testcase( op==OP_IdxLT ); VdbeCoverageIf(v, op==OP_IdxLT );
  112275. testcase( op==OP_IdxLE ); VdbeCoverageIf(v, op==OP_IdxLE );
  112276. }
  112277. /* Seek the table cursor, if required */
  112278. disableTerm(pLevel, pRangeStart);
  112279. disableTerm(pLevel, pRangeEnd);
  112280. if( omitTable ){
  112281. /* pIdx is a covering index. No need to access the main table. */
  112282. }else if( HasRowid(pIdx->pTable) ){
  112283. iRowidReg = ++pParse->nMem;
  112284. sqlite3VdbeAddOp2(v, OP_IdxRowid, iIdxCur, iRowidReg);
  112285. sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
  112286. sqlite3VdbeAddOp2(v, OP_Seek, iCur, iRowidReg); /* Deferred seek */
  112287. }else if( iCur!=iIdxCur ){
  112288. Index *pPk = sqlite3PrimaryKeyIndex(pIdx->pTable);
  112289. iRowidReg = sqlite3GetTempRange(pParse, pPk->nKeyCol);
  112290. for(j=0; j<pPk->nKeyCol; j++){
  112291. k = sqlite3ColumnOfIndex(pIdx, pPk->aiColumn[j]);
  112292. sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, k, iRowidReg+j);
  112293. }
  112294. sqlite3VdbeAddOp4Int(v, OP_NotFound, iCur, addrCont,
  112295. iRowidReg, pPk->nKeyCol); VdbeCoverage(v);
  112296. }
  112297. /* Record the instruction used to terminate the loop. Disable
  112298. ** WHERE clause terms made redundant by the index range scan.
  112299. */
  112300. if( pLoop->wsFlags & WHERE_ONEROW ){
  112301. pLevel->op = OP_Noop;
  112302. }else if( bRev ){
  112303. pLevel->op = OP_Prev;
  112304. }else{
  112305. pLevel->op = OP_Next;
  112306. }
  112307. pLevel->p1 = iIdxCur;
  112308. pLevel->p3 = (pLoop->wsFlags&WHERE_UNQ_WANTED)!=0 ? 1:0;
  112309. if( (pLoop->wsFlags & WHERE_CONSTRAINT)==0 ){
  112310. pLevel->p5 = SQLITE_STMTSTATUS_FULLSCAN_STEP;
  112311. }else{
  112312. assert( pLevel->p5==0 );
  112313. }
  112314. }else
  112315. #ifndef SQLITE_OMIT_OR_OPTIMIZATION
  112316. if( pLoop->wsFlags & WHERE_MULTI_OR ){
  112317. /* Case 5: Two or more separately indexed terms connected by OR
  112318. **
  112319. ** Example:
  112320. **
  112321. ** CREATE TABLE t1(a,b,c,d);
  112322. ** CREATE INDEX i1 ON t1(a);
  112323. ** CREATE INDEX i2 ON t1(b);
  112324. ** CREATE INDEX i3 ON t1(c);
  112325. **
  112326. ** SELECT * FROM t1 WHERE a=5 OR b=7 OR (c=11 AND d=13)
  112327. **
  112328. ** In the example, there are three indexed terms connected by OR.
  112329. ** The top of the loop looks like this:
  112330. **
  112331. ** Null 1 # Zero the rowset in reg 1
  112332. **
  112333. ** Then, for each indexed term, the following. The arguments to
  112334. ** RowSetTest are such that the rowid of the current row is inserted
  112335. ** into the RowSet. If it is already present, control skips the
  112336. ** Gosub opcode and jumps straight to the code generated by WhereEnd().
  112337. **
  112338. ** sqlite3WhereBegin(<term>)
  112339. ** RowSetTest # Insert rowid into rowset
  112340. ** Gosub 2 A
  112341. ** sqlite3WhereEnd()
  112342. **
  112343. ** Following the above, code to terminate the loop. Label A, the target
  112344. ** of the Gosub above, jumps to the instruction right after the Goto.
  112345. **
  112346. ** Null 1 # Zero the rowset in reg 1
  112347. ** Goto B # The loop is finished.
  112348. **
  112349. ** A: <loop body> # Return data, whatever.
  112350. **
  112351. ** Return 2 # Jump back to the Gosub
  112352. **
  112353. ** B: <after the loop>
  112354. **
  112355. ** Added 2014-05-26: If the table is a WITHOUT ROWID table, then
  112356. ** use an ephemeral index instead of a RowSet to record the primary
  112357. ** keys of the rows we have already seen.
  112358. **
  112359. */
  112360. WhereClause *pOrWc; /* The OR-clause broken out into subterms */
  112361. SrcList *pOrTab; /* Shortened table list or OR-clause generation */
  112362. Index *pCov = 0; /* Potential covering index (or NULL) */
  112363. int iCovCur = pParse->nTab++; /* Cursor used for index scans (if any) */
  112364. int regReturn = ++pParse->nMem; /* Register used with OP_Gosub */
  112365. int regRowset = 0; /* Register for RowSet object */
  112366. int regRowid = 0; /* Register holding rowid */
  112367. int iLoopBody = sqlite3VdbeMakeLabel(v); /* Start of loop body */
  112368. int iRetInit; /* Address of regReturn init */
  112369. int untestedTerms = 0; /* Some terms not completely tested */
  112370. int ii; /* Loop counter */
  112371. u16 wctrlFlags; /* Flags for sub-WHERE clause */
  112372. Expr *pAndExpr = 0; /* An ".. AND (...)" expression */
  112373. Table *pTab = pTabItem->pTab;
  112374. pTerm = pLoop->aLTerm[0];
  112375. assert( pTerm!=0 );
  112376. assert( pTerm->eOperator & WO_OR );
  112377. assert( (pTerm->wtFlags & TERM_ORINFO)!=0 );
  112378. pOrWc = &pTerm->u.pOrInfo->wc;
  112379. pLevel->op = OP_Return;
  112380. pLevel->p1 = regReturn;
  112381. /* Set up a new SrcList in pOrTab containing the table being scanned
  112382. ** by this loop in the a[0] slot and all notReady tables in a[1..] slots.
  112383. ** This becomes the SrcList in the recursive call to sqlite3WhereBegin().
  112384. */
  112385. if( pWInfo->nLevel>1 ){
  112386. int nNotReady; /* The number of notReady tables */
  112387. struct SrcList_item *origSrc; /* Original list of tables */
  112388. nNotReady = pWInfo->nLevel - iLevel - 1;
  112389. pOrTab = sqlite3StackAllocRaw(db,
  112390. sizeof(*pOrTab)+ nNotReady*sizeof(pOrTab->a[0]));
  112391. if( pOrTab==0 ) return notReady;
  112392. pOrTab->nAlloc = (u8)(nNotReady + 1);
  112393. pOrTab->nSrc = pOrTab->nAlloc;
  112394. memcpy(pOrTab->a, pTabItem, sizeof(*pTabItem));
  112395. origSrc = pWInfo->pTabList->a;
  112396. for(k=1; k<=nNotReady; k++){
  112397. memcpy(&pOrTab->a[k], &origSrc[pLevel[k].iFrom], sizeof(pOrTab->a[k]));
  112398. }
  112399. }else{
  112400. pOrTab = pWInfo->pTabList;
  112401. }
  112402. /* Initialize the rowset register to contain NULL. An SQL NULL is
  112403. ** equivalent to an empty rowset. Or, create an ephemeral index
  112404. ** capable of holding primary keys in the case of a WITHOUT ROWID.
  112405. **
  112406. ** Also initialize regReturn to contain the address of the instruction
  112407. ** immediately following the OP_Return at the bottom of the loop. This
  112408. ** is required in a few obscure LEFT JOIN cases where control jumps
  112409. ** over the top of the loop into the body of it. In this case the
  112410. ** correct response for the end-of-loop code (the OP_Return) is to
  112411. ** fall through to the next instruction, just as an OP_Next does if
  112412. ** called on an uninitialized cursor.
  112413. */
  112414. if( (pWInfo->wctrlFlags & WHERE_DUPLICATES_OK)==0 ){
  112415. if( HasRowid(pTab) ){
  112416. regRowset = ++pParse->nMem;
  112417. sqlite3VdbeAddOp2(v, OP_Null, 0, regRowset);
  112418. }else{
  112419. Index *pPk = sqlite3PrimaryKeyIndex(pTab);
  112420. regRowset = pParse->nTab++;
  112421. sqlite3VdbeAddOp2(v, OP_OpenEphemeral, regRowset, pPk->nKeyCol);
  112422. sqlite3VdbeSetP4KeyInfo(pParse, pPk);
  112423. }
  112424. regRowid = ++pParse->nMem;
  112425. }
  112426. iRetInit = sqlite3VdbeAddOp2(v, OP_Integer, 0, regReturn);
  112427. /* If the original WHERE clause is z of the form: (x1 OR x2 OR ...) AND y
  112428. ** Then for every term xN, evaluate as the subexpression: xN AND z
  112429. ** That way, terms in y that are factored into the disjunction will
  112430. ** be picked up by the recursive calls to sqlite3WhereBegin() below.
  112431. **
  112432. ** Actually, each subexpression is converted to "xN AND w" where w is
  112433. ** the "interesting" terms of z - terms that did not originate in the
  112434. ** ON or USING clause of a LEFT JOIN, and terms that are usable as
  112435. ** indices.
  112436. **
  112437. ** This optimization also only applies if the (x1 OR x2 OR ...) term
  112438. ** is not contained in the ON clause of a LEFT JOIN.
  112439. ** See ticket http://www.sqlite.org/src/info/f2369304e4
  112440. */
  112441. if( pWC->nTerm>1 ){
  112442. int iTerm;
  112443. for(iTerm=0; iTerm<pWC->nTerm; iTerm++){
  112444. Expr *pExpr = pWC->a[iTerm].pExpr;
  112445. if( &pWC->a[iTerm] == pTerm ) continue;
  112446. if( ExprHasProperty(pExpr, EP_FromJoin) ) continue;
  112447. if( (pWC->a[iTerm].wtFlags & TERM_VIRTUAL)!=0 ) continue;
  112448. if( (pWC->a[iTerm].eOperator & WO_ALL)==0 ) continue;
  112449. testcase( pWC->a[iTerm].wtFlags & TERM_ORINFO );
  112450. pExpr = sqlite3ExprDup(db, pExpr, 0);
  112451. pAndExpr = sqlite3ExprAnd(db, pAndExpr, pExpr);
  112452. }
  112453. if( pAndExpr ){
  112454. pAndExpr = sqlite3PExpr(pParse, TK_AND, 0, pAndExpr, 0);
  112455. }
  112456. }
  112457. /* Run a separate WHERE clause for each term of the OR clause. After
  112458. ** eliminating duplicates from other WHERE clauses, the action for each
  112459. ** sub-WHERE clause is to to invoke the main loop body as a subroutine.
  112460. */
  112461. wctrlFlags = WHERE_OMIT_OPEN_CLOSE
  112462. | WHERE_FORCE_TABLE
  112463. | WHERE_ONETABLE_ONLY
  112464. | WHERE_NO_AUTOINDEX;
  112465. for(ii=0; ii<pOrWc->nTerm; ii++){
  112466. WhereTerm *pOrTerm = &pOrWc->a[ii];
  112467. if( pOrTerm->leftCursor==iCur || (pOrTerm->eOperator & WO_AND)!=0 ){
  112468. WhereInfo *pSubWInfo; /* Info for single OR-term scan */
  112469. Expr *pOrExpr = pOrTerm->pExpr; /* Current OR clause term */
  112470. int j1 = 0; /* Address of jump operation */
  112471. if( pAndExpr && !ExprHasProperty(pOrExpr, EP_FromJoin) ){
  112472. pAndExpr->pLeft = pOrExpr;
  112473. pOrExpr = pAndExpr;
  112474. }
  112475. /* Loop through table entries that match term pOrTerm. */
  112476. WHERETRACE(0xffff, ("Subplan for OR-clause:\n"));
  112477. pSubWInfo = sqlite3WhereBegin(pParse, pOrTab, pOrExpr, 0, 0,
  112478. wctrlFlags, iCovCur);
  112479. assert( pSubWInfo || pParse->nErr || db->mallocFailed );
  112480. if( pSubWInfo ){
  112481. WhereLoop *pSubLoop;
  112482. int addrExplain = explainOneScan(
  112483. pParse, pOrTab, &pSubWInfo->a[0], iLevel, pLevel->iFrom, 0
  112484. );
  112485. addScanStatus(v, pOrTab, &pSubWInfo->a[0], addrExplain);
  112486. /* This is the sub-WHERE clause body. First skip over
  112487. ** duplicate rows from prior sub-WHERE clauses, and record the
  112488. ** rowid (or PRIMARY KEY) for the current row so that the same
  112489. ** row will be skipped in subsequent sub-WHERE clauses.
  112490. */
  112491. if( (pWInfo->wctrlFlags & WHERE_DUPLICATES_OK)==0 ){
  112492. int r;
  112493. int iSet = ((ii==pOrWc->nTerm-1)?-1:ii);
  112494. if( HasRowid(pTab) ){
  112495. r = sqlite3ExprCodeGetColumn(pParse, pTab, -1, iCur, regRowid, 0);
  112496. j1 = sqlite3VdbeAddOp4Int(v, OP_RowSetTest, regRowset, 0, r,iSet);
  112497. VdbeCoverage(v);
  112498. }else{
  112499. Index *pPk = sqlite3PrimaryKeyIndex(pTab);
  112500. int nPk = pPk->nKeyCol;
  112501. int iPk;
  112502. /* Read the PK into an array of temp registers. */
  112503. r = sqlite3GetTempRange(pParse, nPk);
  112504. for(iPk=0; iPk<nPk; iPk++){
  112505. int iCol = pPk->aiColumn[iPk];
  112506. sqlite3ExprCodeGetColumn(pParse, pTab, iCol, iCur, r+iPk, 0);
  112507. }
  112508. /* Check if the temp table already contains this key. If so,
  112509. ** the row has already been included in the result set and
  112510. ** can be ignored (by jumping past the Gosub below). Otherwise,
  112511. ** insert the key into the temp table and proceed with processing
  112512. ** the row.
  112513. **
  112514. ** Use some of the same optimizations as OP_RowSetTest: If iSet
  112515. ** is zero, assume that the key cannot already be present in
  112516. ** the temp table. And if iSet is -1, assume that there is no
  112517. ** need to insert the key into the temp table, as it will never
  112518. ** be tested for. */
  112519. if( iSet ){
  112520. j1 = sqlite3VdbeAddOp4Int(v, OP_Found, regRowset, 0, r, nPk);
  112521. VdbeCoverage(v);
  112522. }
  112523. if( iSet>=0 ){
  112524. sqlite3VdbeAddOp3(v, OP_MakeRecord, r, nPk, regRowid);
  112525. sqlite3VdbeAddOp3(v, OP_IdxInsert, regRowset, regRowid, 0);
  112526. if( iSet ) sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
  112527. }
  112528. /* Release the array of temp registers */
  112529. sqlite3ReleaseTempRange(pParse, r, nPk);
  112530. }
  112531. }
  112532. /* Invoke the main loop body as a subroutine */
  112533. sqlite3VdbeAddOp2(v, OP_Gosub, regReturn, iLoopBody);
  112534. /* Jump here (skipping the main loop body subroutine) if the
  112535. ** current sub-WHERE row is a duplicate from prior sub-WHEREs. */
  112536. if( j1 ) sqlite3VdbeJumpHere(v, j1);
  112537. /* The pSubWInfo->untestedTerms flag means that this OR term
  112538. ** contained one or more AND term from a notReady table. The
  112539. ** terms from the notReady table could not be tested and will
  112540. ** need to be tested later.
  112541. */
  112542. if( pSubWInfo->untestedTerms ) untestedTerms = 1;
  112543. /* If all of the OR-connected terms are optimized using the same
  112544. ** index, and the index is opened using the same cursor number
  112545. ** by each call to sqlite3WhereBegin() made by this loop, it may
  112546. ** be possible to use that index as a covering index.
  112547. **
  112548. ** If the call to sqlite3WhereBegin() above resulted in a scan that
  112549. ** uses an index, and this is either the first OR-connected term
  112550. ** processed or the index is the same as that used by all previous
  112551. ** terms, set pCov to the candidate covering index. Otherwise, set
  112552. ** pCov to NULL to indicate that no candidate covering index will
  112553. ** be available.
  112554. */
  112555. pSubLoop = pSubWInfo->a[0].pWLoop;
  112556. assert( (pSubLoop->wsFlags & WHERE_AUTO_INDEX)==0 );
  112557. if( (pSubLoop->wsFlags & WHERE_INDEXED)!=0
  112558. && (ii==0 || pSubLoop->u.btree.pIndex==pCov)
  112559. && (HasRowid(pTab) || !IsPrimaryKeyIndex(pSubLoop->u.btree.pIndex))
  112560. ){
  112561. assert( pSubWInfo->a[0].iIdxCur==iCovCur );
  112562. pCov = pSubLoop->u.btree.pIndex;
  112563. wctrlFlags |= WHERE_REOPEN_IDX;
  112564. }else{
  112565. pCov = 0;
  112566. }
  112567. /* Finish the loop through table entries that match term pOrTerm. */
  112568. sqlite3WhereEnd(pSubWInfo);
  112569. }
  112570. }
  112571. }
  112572. pLevel->u.pCovidx = pCov;
  112573. if( pCov ) pLevel->iIdxCur = iCovCur;
  112574. if( pAndExpr ){
  112575. pAndExpr->pLeft = 0;
  112576. sqlite3ExprDelete(db, pAndExpr);
  112577. }
  112578. sqlite3VdbeChangeP1(v, iRetInit, sqlite3VdbeCurrentAddr(v));
  112579. sqlite3VdbeAddOp2(v, OP_Goto, 0, pLevel->addrBrk);
  112580. sqlite3VdbeResolveLabel(v, iLoopBody);
  112581. if( pWInfo->nLevel>1 ) sqlite3StackFree(db, pOrTab);
  112582. if( !untestedTerms ) disableTerm(pLevel, pTerm);
  112583. }else
  112584. #endif /* SQLITE_OMIT_OR_OPTIMIZATION */
  112585. {
  112586. /* Case 6: There is no usable index. We must do a complete
  112587. ** scan of the entire table.
  112588. */
  112589. static const u8 aStep[] = { OP_Next, OP_Prev };
  112590. static const u8 aStart[] = { OP_Rewind, OP_Last };
  112591. assert( bRev==0 || bRev==1 );
  112592. if( pTabItem->isRecursive ){
  112593. /* Tables marked isRecursive have only a single row that is stored in
  112594. ** a pseudo-cursor. No need to Rewind or Next such cursors. */
  112595. pLevel->op = OP_Noop;
  112596. }else{
  112597. pLevel->op = aStep[bRev];
  112598. pLevel->p1 = iCur;
  112599. pLevel->p2 = 1 + sqlite3VdbeAddOp2(v, aStart[bRev], iCur, addrBrk);
  112600. VdbeCoverageIf(v, bRev==0);
  112601. VdbeCoverageIf(v, bRev!=0);
  112602. pLevel->p5 = SQLITE_STMTSTATUS_FULLSCAN_STEP;
  112603. }
  112604. }
  112605. #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
  112606. pLevel->addrVisit = sqlite3VdbeCurrentAddr(v);
  112607. #endif
  112608. /* Insert code to test every subexpression that can be completely
  112609. ** computed using the current set of tables.
  112610. */
  112611. for(pTerm=pWC->a, j=pWC->nTerm; j>0; j--, pTerm++){
  112612. Expr *pE;
  112613. int skipLikeAddr = 0;
  112614. testcase( pTerm->wtFlags & TERM_VIRTUAL );
  112615. testcase( pTerm->wtFlags & TERM_CODED );
  112616. if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
  112617. if( (pTerm->prereqAll & pLevel->notReady)!=0 ){
  112618. testcase( pWInfo->untestedTerms==0
  112619. && (pWInfo->wctrlFlags & WHERE_ONETABLE_ONLY)!=0 );
  112620. pWInfo->untestedTerms = 1;
  112621. continue;
  112622. }
  112623. pE = pTerm->pExpr;
  112624. assert( pE!=0 );
  112625. if( pLevel->iLeftJoin && !ExprHasProperty(pE, EP_FromJoin) ){
  112626. continue;
  112627. }
  112628. if( pTerm->wtFlags & TERM_LIKECOND ){
  112629. assert( pLevel->iLikeRepCntr>0 );
  112630. skipLikeAddr = sqlite3VdbeAddOp1(v, OP_IfNot, pLevel->iLikeRepCntr);
  112631. VdbeCoverage(v);
  112632. }
  112633. sqlite3ExprIfFalse(pParse, pE, addrCont, SQLITE_JUMPIFNULL);
  112634. if( skipLikeAddr ) sqlite3VdbeJumpHere(v, skipLikeAddr);
  112635. pTerm->wtFlags |= TERM_CODED;
  112636. }
  112637. /* Insert code to test for implied constraints based on transitivity
  112638. ** of the "==" operator.
  112639. **
  112640. ** Example: If the WHERE clause contains "t1.a=t2.b" and "t2.b=123"
  112641. ** and we are coding the t1 loop and the t2 loop has not yet coded,
  112642. ** then we cannot use the "t1.a=t2.b" constraint, but we can code
  112643. ** the implied "t1.a=123" constraint.
  112644. */
  112645. for(pTerm=pWC->a, j=pWC->nTerm; j>0; j--, pTerm++){
  112646. Expr *pE, *pEAlt;
  112647. WhereTerm *pAlt;
  112648. if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
  112649. if( pTerm->eOperator!=(WO_EQUIV|WO_EQ) ) continue;
  112650. if( pTerm->leftCursor!=iCur ) continue;
  112651. if( pLevel->iLeftJoin ) continue;
  112652. pE = pTerm->pExpr;
  112653. assert( !ExprHasProperty(pE, EP_FromJoin) );
  112654. assert( (pTerm->prereqRight & pLevel->notReady)!=0 );
  112655. pAlt = findTerm(pWC, iCur, pTerm->u.leftColumn, notReady, WO_EQ|WO_IN, 0);
  112656. if( pAlt==0 ) continue;
  112657. if( pAlt->wtFlags & (TERM_CODED) ) continue;
  112658. testcase( pAlt->eOperator & WO_EQ );
  112659. testcase( pAlt->eOperator & WO_IN );
  112660. VdbeModuleComment((v, "begin transitive constraint"));
  112661. pEAlt = sqlite3StackAllocRaw(db, sizeof(*pEAlt));
  112662. if( pEAlt ){
  112663. *pEAlt = *pAlt->pExpr;
  112664. pEAlt->pLeft = pE->pLeft;
  112665. sqlite3ExprIfFalse(pParse, pEAlt, addrCont, SQLITE_JUMPIFNULL);
  112666. sqlite3StackFree(db, pEAlt);
  112667. }
  112668. }
  112669. /* For a LEFT OUTER JOIN, generate code that will record the fact that
  112670. ** at least one row of the right table has matched the left table.
  112671. */
  112672. if( pLevel->iLeftJoin ){
  112673. pLevel->addrFirst = sqlite3VdbeCurrentAddr(v);
  112674. sqlite3VdbeAddOp2(v, OP_Integer, 1, pLevel->iLeftJoin);
  112675. VdbeComment((v, "record LEFT JOIN hit"));
  112676. sqlite3ExprCacheClear(pParse);
  112677. for(pTerm=pWC->a, j=0; j<pWC->nTerm; j++, pTerm++){
  112678. testcase( pTerm->wtFlags & TERM_VIRTUAL );
  112679. testcase( pTerm->wtFlags & TERM_CODED );
  112680. if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
  112681. if( (pTerm->prereqAll & pLevel->notReady)!=0 ){
  112682. assert( pWInfo->untestedTerms );
  112683. continue;
  112684. }
  112685. assert( pTerm->pExpr );
  112686. sqlite3ExprIfFalse(pParse, pTerm->pExpr, addrCont, SQLITE_JUMPIFNULL);
  112687. pTerm->wtFlags |= TERM_CODED;
  112688. }
  112689. }
  112690. return pLevel->notReady;
  112691. }
  112692. #ifdef WHERETRACE_ENABLED
  112693. /*
  112694. ** Print the content of a WhereTerm object
  112695. */
  112696. static void whereTermPrint(WhereTerm *pTerm, int iTerm){
  112697. if( pTerm==0 ){
  112698. sqlite3DebugPrintf("TERM-%-3d NULL\n", iTerm);
  112699. }else{
  112700. char zType[4];
  112701. memcpy(zType, "...", 4);
  112702. if( pTerm->wtFlags & TERM_VIRTUAL ) zType[0] = 'V';
  112703. if( pTerm->eOperator & WO_EQUIV ) zType[1] = 'E';
  112704. if( ExprHasProperty(pTerm->pExpr, EP_FromJoin) ) zType[2] = 'L';
  112705. sqlite3DebugPrintf("TERM-%-3d %p %s cursor=%-3d prob=%-3d op=0x%03x\n",
  112706. iTerm, pTerm, zType, pTerm->leftCursor, pTerm->truthProb,
  112707. pTerm->eOperator);
  112708. sqlite3TreeViewExpr(0, pTerm->pExpr, 0);
  112709. }
  112710. }
  112711. #endif
  112712. #ifdef WHERETRACE_ENABLED
  112713. /*
  112714. ** Print a WhereLoop object for debugging purposes
  112715. */
  112716. static void whereLoopPrint(WhereLoop *p, WhereClause *pWC){
  112717. WhereInfo *pWInfo = pWC->pWInfo;
  112718. int nb = 1+(pWInfo->pTabList->nSrc+7)/8;
  112719. struct SrcList_item *pItem = pWInfo->pTabList->a + p->iTab;
  112720. Table *pTab = pItem->pTab;
  112721. sqlite3DebugPrintf("%c%2d.%0*llx.%0*llx", p->cId,
  112722. p->iTab, nb, p->maskSelf, nb, p->prereq);
  112723. sqlite3DebugPrintf(" %12s",
  112724. pItem->zAlias ? pItem->zAlias : pTab->zName);
  112725. if( (p->wsFlags & WHERE_VIRTUALTABLE)==0 ){
  112726. const char *zName;
  112727. if( p->u.btree.pIndex && (zName = p->u.btree.pIndex->zName)!=0 ){
  112728. if( strncmp(zName, "sqlite_autoindex_", 17)==0 ){
  112729. int i = sqlite3Strlen30(zName) - 1;
  112730. while( zName[i]!='_' ) i--;
  112731. zName += i;
  112732. }
  112733. sqlite3DebugPrintf(".%-16s %2d", zName, p->u.btree.nEq);
  112734. }else{
  112735. sqlite3DebugPrintf("%20s","");
  112736. }
  112737. }else{
  112738. char *z;
  112739. if( p->u.vtab.idxStr ){
  112740. z = sqlite3_mprintf("(%d,\"%s\",%x)",
  112741. p->u.vtab.idxNum, p->u.vtab.idxStr, p->u.vtab.omitMask);
  112742. }else{
  112743. z = sqlite3_mprintf("(%d,%x)", p->u.vtab.idxNum, p->u.vtab.omitMask);
  112744. }
  112745. sqlite3DebugPrintf(" %-19s", z);
  112746. sqlite3_free(z);
  112747. }
  112748. if( p->wsFlags & WHERE_SKIPSCAN ){
  112749. sqlite3DebugPrintf(" f %05x %d-%d", p->wsFlags, p->nLTerm,p->nSkip);
  112750. }else{
  112751. sqlite3DebugPrintf(" f %05x N %d", p->wsFlags, p->nLTerm);
  112752. }
  112753. sqlite3DebugPrintf(" cost %d,%d,%d\n", p->rSetup, p->rRun, p->nOut);
  112754. if( p->nLTerm && (sqlite3WhereTrace & 0x100)!=0 ){
  112755. int i;
  112756. for(i=0; i<p->nLTerm; i++){
  112757. whereTermPrint(p->aLTerm[i], i);
  112758. }
  112759. }
  112760. }
  112761. #endif
  112762. /*
  112763. ** Convert bulk memory into a valid WhereLoop that can be passed
  112764. ** to whereLoopClear harmlessly.
  112765. */
  112766. static void whereLoopInit(WhereLoop *p){
  112767. p->aLTerm = p->aLTermSpace;
  112768. p->nLTerm = 0;
  112769. p->nLSlot = ArraySize(p->aLTermSpace);
  112770. p->wsFlags = 0;
  112771. }
  112772. /*
  112773. ** Clear the WhereLoop.u union. Leave WhereLoop.pLTerm intact.
  112774. */
  112775. static void whereLoopClearUnion(sqlite3 *db, WhereLoop *p){
  112776. if( p->wsFlags & (WHERE_VIRTUALTABLE|WHERE_AUTO_INDEX) ){
  112777. if( (p->wsFlags & WHERE_VIRTUALTABLE)!=0 && p->u.vtab.needFree ){
  112778. sqlite3_free(p->u.vtab.idxStr);
  112779. p->u.vtab.needFree = 0;
  112780. p->u.vtab.idxStr = 0;
  112781. }else if( (p->wsFlags & WHERE_AUTO_INDEX)!=0 && p->u.btree.pIndex!=0 ){
  112782. sqlite3DbFree(db, p->u.btree.pIndex->zColAff);
  112783. sqlite3DbFree(db, p->u.btree.pIndex);
  112784. p->u.btree.pIndex = 0;
  112785. }
  112786. }
  112787. }
  112788. /*
  112789. ** Deallocate internal memory used by a WhereLoop object
  112790. */
  112791. static void whereLoopClear(sqlite3 *db, WhereLoop *p){
  112792. if( p->aLTerm!=p->aLTermSpace ) sqlite3DbFree(db, p->aLTerm);
  112793. whereLoopClearUnion(db, p);
  112794. whereLoopInit(p);
  112795. }
  112796. /*
  112797. ** Increase the memory allocation for pLoop->aLTerm[] to be at least n.
  112798. */
  112799. static int whereLoopResize(sqlite3 *db, WhereLoop *p, int n){
  112800. WhereTerm **paNew;
  112801. if( p->nLSlot>=n ) return SQLITE_OK;
  112802. n = (n+7)&~7;
  112803. paNew = sqlite3DbMallocRaw(db, sizeof(p->aLTerm[0])*n);
  112804. if( paNew==0 ) return SQLITE_NOMEM;
  112805. memcpy(paNew, p->aLTerm, sizeof(p->aLTerm[0])*p->nLSlot);
  112806. if( p->aLTerm!=p->aLTermSpace ) sqlite3DbFree(db, p->aLTerm);
  112807. p->aLTerm = paNew;
  112808. p->nLSlot = n;
  112809. return SQLITE_OK;
  112810. }
  112811. /*
  112812. ** Transfer content from the second pLoop into the first.
  112813. */
  112814. static int whereLoopXfer(sqlite3 *db, WhereLoop *pTo, WhereLoop *pFrom){
  112815. whereLoopClearUnion(db, pTo);
  112816. if( whereLoopResize(db, pTo, pFrom->nLTerm) ){
  112817. memset(&pTo->u, 0, sizeof(pTo->u));
  112818. return SQLITE_NOMEM;
  112819. }
  112820. memcpy(pTo, pFrom, WHERE_LOOP_XFER_SZ);
  112821. memcpy(pTo->aLTerm, pFrom->aLTerm, pTo->nLTerm*sizeof(pTo->aLTerm[0]));
  112822. if( pFrom->wsFlags & WHERE_VIRTUALTABLE ){
  112823. pFrom->u.vtab.needFree = 0;
  112824. }else if( (pFrom->wsFlags & WHERE_AUTO_INDEX)!=0 ){
  112825. pFrom->u.btree.pIndex = 0;
  112826. }
  112827. return SQLITE_OK;
  112828. }
  112829. /*
  112830. ** Delete a WhereLoop object
  112831. */
  112832. static void whereLoopDelete(sqlite3 *db, WhereLoop *p){
  112833. whereLoopClear(db, p);
  112834. sqlite3DbFree(db, p);
  112835. }
  112836. /*
  112837. ** Free a WhereInfo structure
  112838. */
  112839. static void whereInfoFree(sqlite3 *db, WhereInfo *pWInfo){
  112840. if( ALWAYS(pWInfo) ){
  112841. int i;
  112842. for(i=0; i<pWInfo->nLevel; i++){
  112843. WhereLevel *pLevel = &pWInfo->a[i];
  112844. if( pLevel->pWLoop && (pLevel->pWLoop->wsFlags & WHERE_IN_ABLE) ){
  112845. sqlite3DbFree(db, pLevel->u.in.aInLoop);
  112846. }
  112847. }
  112848. whereClauseClear(&pWInfo->sWC);
  112849. while( pWInfo->pLoops ){
  112850. WhereLoop *p = pWInfo->pLoops;
  112851. pWInfo->pLoops = p->pNextLoop;
  112852. whereLoopDelete(db, p);
  112853. }
  112854. sqlite3DbFree(db, pWInfo);
  112855. }
  112856. }
  112857. /*
  112858. ** Return TRUE if all of the following are true:
  112859. **
  112860. ** (1) X has the same or lower cost that Y
  112861. ** (2) X is a proper subset of Y
  112862. ** (3) X skips at least as many columns as Y
  112863. **
  112864. ** By "proper subset" we mean that X uses fewer WHERE clause terms
  112865. ** than Y and that every WHERE clause term used by X is also used
  112866. ** by Y.
  112867. **
  112868. ** If X is a proper subset of Y then Y is a better choice and ought
  112869. ** to have a lower cost. This routine returns TRUE when that cost
  112870. ** relationship is inverted and needs to be adjusted. The third rule
  112871. ** was added because if X uses skip-scan less than Y it still might
  112872. ** deserve a lower cost even if it is a proper subset of Y.
  112873. */
  112874. static int whereLoopCheaperProperSubset(
  112875. const WhereLoop *pX, /* First WhereLoop to compare */
  112876. const WhereLoop *pY /* Compare against this WhereLoop */
  112877. ){
  112878. int i, j;
  112879. if( pX->nLTerm-pX->nSkip >= pY->nLTerm-pY->nSkip ){
  112880. return 0; /* X is not a subset of Y */
  112881. }
  112882. if( pY->nSkip > pX->nSkip ) return 0;
  112883. if( pX->rRun >= pY->rRun ){
  112884. if( pX->rRun > pY->rRun ) return 0; /* X costs more than Y */
  112885. if( pX->nOut > pY->nOut ) return 0; /* X costs more than Y */
  112886. }
  112887. for(i=pX->nLTerm-1; i>=0; i--){
  112888. if( pX->aLTerm[i]==0 ) continue;
  112889. for(j=pY->nLTerm-1; j>=0; j--){
  112890. if( pY->aLTerm[j]==pX->aLTerm[i] ) break;
  112891. }
  112892. if( j<0 ) return 0; /* X not a subset of Y since term X[i] not used by Y */
  112893. }
  112894. return 1; /* All conditions meet */
  112895. }
  112896. /*
  112897. ** Try to adjust the cost of WhereLoop pTemplate upwards or downwards so
  112898. ** that:
  112899. **
  112900. ** (1) pTemplate costs less than any other WhereLoops that are a proper
  112901. ** subset of pTemplate
  112902. **
  112903. ** (2) pTemplate costs more than any other WhereLoops for which pTemplate
  112904. ** is a proper subset.
  112905. **
  112906. ** To say "WhereLoop X is a proper subset of Y" means that X uses fewer
  112907. ** WHERE clause terms than Y and that every WHERE clause term used by X is
  112908. ** also used by Y.
  112909. */
  112910. static void whereLoopAdjustCost(const WhereLoop *p, WhereLoop *pTemplate){
  112911. if( (pTemplate->wsFlags & WHERE_INDEXED)==0 ) return;
  112912. for(; p; p=p->pNextLoop){
  112913. if( p->iTab!=pTemplate->iTab ) continue;
  112914. if( (p->wsFlags & WHERE_INDEXED)==0 ) continue;
  112915. if( whereLoopCheaperProperSubset(p, pTemplate) ){
  112916. /* Adjust pTemplate cost downward so that it is cheaper than its
  112917. ** subset p. */
  112918. WHERETRACE(0x80,("subset cost adjustment %d,%d to %d,%d\n",
  112919. pTemplate->rRun, pTemplate->nOut, p->rRun, p->nOut-1));
  112920. pTemplate->rRun = p->rRun;
  112921. pTemplate->nOut = p->nOut - 1;
  112922. }else if( whereLoopCheaperProperSubset(pTemplate, p) ){
  112923. /* Adjust pTemplate cost upward so that it is costlier than p since
  112924. ** pTemplate is a proper subset of p */
  112925. WHERETRACE(0x80,("subset cost adjustment %d,%d to %d,%d\n",
  112926. pTemplate->rRun, pTemplate->nOut, p->rRun, p->nOut+1));
  112927. pTemplate->rRun = p->rRun;
  112928. pTemplate->nOut = p->nOut + 1;
  112929. }
  112930. }
  112931. }
  112932. /*
  112933. ** Search the list of WhereLoops in *ppPrev looking for one that can be
  112934. ** supplanted by pTemplate.
  112935. **
  112936. ** Return NULL if the WhereLoop list contains an entry that can supplant
  112937. ** pTemplate, in other words if pTemplate does not belong on the list.
  112938. **
  112939. ** If pX is a WhereLoop that pTemplate can supplant, then return the
  112940. ** link that points to pX.
  112941. **
  112942. ** If pTemplate cannot supplant any existing element of the list but needs
  112943. ** to be added to the list, then return a pointer to the tail of the list.
  112944. */
  112945. static WhereLoop **whereLoopFindLesser(
  112946. WhereLoop **ppPrev,
  112947. const WhereLoop *pTemplate
  112948. ){
  112949. WhereLoop *p;
  112950. for(p=(*ppPrev); p; ppPrev=&p->pNextLoop, p=*ppPrev){
  112951. if( p->iTab!=pTemplate->iTab || p->iSortIdx!=pTemplate->iSortIdx ){
  112952. /* If either the iTab or iSortIdx values for two WhereLoop are different
  112953. ** then those WhereLoops need to be considered separately. Neither is
  112954. ** a candidate to replace the other. */
  112955. continue;
  112956. }
  112957. /* In the current implementation, the rSetup value is either zero
  112958. ** or the cost of building an automatic index (NlogN) and the NlogN
  112959. ** is the same for compatible WhereLoops. */
  112960. assert( p->rSetup==0 || pTemplate->rSetup==0
  112961. || p->rSetup==pTemplate->rSetup );
  112962. /* whereLoopAddBtree() always generates and inserts the automatic index
  112963. ** case first. Hence compatible candidate WhereLoops never have a larger
  112964. ** rSetup. Call this SETUP-INVARIANT */
  112965. assert( p->rSetup>=pTemplate->rSetup );
  112966. /* Any loop using an appliation-defined index (or PRIMARY KEY or
  112967. ** UNIQUE constraint) with one or more == constraints is better
  112968. ** than an automatic index. Unless it is a skip-scan. */
  112969. if( (p->wsFlags & WHERE_AUTO_INDEX)!=0
  112970. && (pTemplate->nSkip)==0
  112971. && (pTemplate->wsFlags & WHERE_INDEXED)!=0
  112972. && (pTemplate->wsFlags & WHERE_COLUMN_EQ)!=0
  112973. && (p->prereq & pTemplate->prereq)==pTemplate->prereq
  112974. ){
  112975. break;
  112976. }
  112977. /* If existing WhereLoop p is better than pTemplate, pTemplate can be
  112978. ** discarded. WhereLoop p is better if:
  112979. ** (1) p has no more dependencies than pTemplate, and
  112980. ** (2) p has an equal or lower cost than pTemplate
  112981. */
  112982. if( (p->prereq & pTemplate->prereq)==p->prereq /* (1) */
  112983. && p->rSetup<=pTemplate->rSetup /* (2a) */
  112984. && p->rRun<=pTemplate->rRun /* (2b) */
  112985. && p->nOut<=pTemplate->nOut /* (2c) */
  112986. ){
  112987. return 0; /* Discard pTemplate */
  112988. }
  112989. /* If pTemplate is always better than p, then cause p to be overwritten
  112990. ** with pTemplate. pTemplate is better than p if:
  112991. ** (1) pTemplate has no more dependences than p, and
  112992. ** (2) pTemplate has an equal or lower cost than p.
  112993. */
  112994. if( (p->prereq & pTemplate->prereq)==pTemplate->prereq /* (1) */
  112995. && p->rRun>=pTemplate->rRun /* (2a) */
  112996. && p->nOut>=pTemplate->nOut /* (2b) */
  112997. ){
  112998. assert( p->rSetup>=pTemplate->rSetup ); /* SETUP-INVARIANT above */
  112999. break; /* Cause p to be overwritten by pTemplate */
  113000. }
  113001. }
  113002. return ppPrev;
  113003. }
  113004. /*
  113005. ** Insert or replace a WhereLoop entry using the template supplied.
  113006. **
  113007. ** An existing WhereLoop entry might be overwritten if the new template
  113008. ** is better and has fewer dependencies. Or the template will be ignored
  113009. ** and no insert will occur if an existing WhereLoop is faster and has
  113010. ** fewer dependencies than the template. Otherwise a new WhereLoop is
  113011. ** added based on the template.
  113012. **
  113013. ** If pBuilder->pOrSet is not NULL then we care about only the
  113014. ** prerequisites and rRun and nOut costs of the N best loops. That
  113015. ** information is gathered in the pBuilder->pOrSet object. This special
  113016. ** processing mode is used only for OR clause processing.
  113017. **
  113018. ** When accumulating multiple loops (when pBuilder->pOrSet is NULL) we
  113019. ** still might overwrite similar loops with the new template if the
  113020. ** new template is better. Loops may be overwritten if the following
  113021. ** conditions are met:
  113022. **
  113023. ** (1) They have the same iTab.
  113024. ** (2) They have the same iSortIdx.
  113025. ** (3) The template has same or fewer dependencies than the current loop
  113026. ** (4) The template has the same or lower cost than the current loop
  113027. */
  113028. static int whereLoopInsert(WhereLoopBuilder *pBuilder, WhereLoop *pTemplate){
  113029. WhereLoop **ppPrev, *p;
  113030. WhereInfo *pWInfo = pBuilder->pWInfo;
  113031. sqlite3 *db = pWInfo->pParse->db;
  113032. /* If pBuilder->pOrSet is defined, then only keep track of the costs
  113033. ** and prereqs.
  113034. */
  113035. if( pBuilder->pOrSet!=0 ){
  113036. #if WHERETRACE_ENABLED
  113037. u16 n = pBuilder->pOrSet->n;
  113038. int x =
  113039. #endif
  113040. whereOrInsert(pBuilder->pOrSet, pTemplate->prereq, pTemplate->rRun,
  113041. pTemplate->nOut);
  113042. #if WHERETRACE_ENABLED /* 0x8 */
  113043. if( sqlite3WhereTrace & 0x8 ){
  113044. sqlite3DebugPrintf(x?" or-%d: ":" or-X: ", n);
  113045. whereLoopPrint(pTemplate, pBuilder->pWC);
  113046. }
  113047. #endif
  113048. return SQLITE_OK;
  113049. }
  113050. /* Look for an existing WhereLoop to replace with pTemplate
  113051. */
  113052. whereLoopAdjustCost(pWInfo->pLoops, pTemplate);
  113053. ppPrev = whereLoopFindLesser(&pWInfo->pLoops, pTemplate);
  113054. if( ppPrev==0 ){
  113055. /* There already exists a WhereLoop on the list that is better
  113056. ** than pTemplate, so just ignore pTemplate */
  113057. #if WHERETRACE_ENABLED /* 0x8 */
  113058. if( sqlite3WhereTrace & 0x8 ){
  113059. sqlite3DebugPrintf(" skip: ");
  113060. whereLoopPrint(pTemplate, pBuilder->pWC);
  113061. }
  113062. #endif
  113063. return SQLITE_OK;
  113064. }else{
  113065. p = *ppPrev;
  113066. }
  113067. /* If we reach this point it means that either p[] should be overwritten
  113068. ** with pTemplate[] if p[] exists, or if p==NULL then allocate a new
  113069. ** WhereLoop and insert it.
  113070. */
  113071. #if WHERETRACE_ENABLED /* 0x8 */
  113072. if( sqlite3WhereTrace & 0x8 ){
  113073. if( p!=0 ){
  113074. sqlite3DebugPrintf("replace: ");
  113075. whereLoopPrint(p, pBuilder->pWC);
  113076. }
  113077. sqlite3DebugPrintf(" add: ");
  113078. whereLoopPrint(pTemplate, pBuilder->pWC);
  113079. }
  113080. #endif
  113081. if( p==0 ){
  113082. /* Allocate a new WhereLoop to add to the end of the list */
  113083. *ppPrev = p = sqlite3DbMallocRaw(db, sizeof(WhereLoop));
  113084. if( p==0 ) return SQLITE_NOMEM;
  113085. whereLoopInit(p);
  113086. p->pNextLoop = 0;
  113087. }else{
  113088. /* We will be overwriting WhereLoop p[]. But before we do, first
  113089. ** go through the rest of the list and delete any other entries besides
  113090. ** p[] that are also supplated by pTemplate */
  113091. WhereLoop **ppTail = &p->pNextLoop;
  113092. WhereLoop *pToDel;
  113093. while( *ppTail ){
  113094. ppTail = whereLoopFindLesser(ppTail, pTemplate);
  113095. if( ppTail==0 ) break;
  113096. pToDel = *ppTail;
  113097. if( pToDel==0 ) break;
  113098. *ppTail = pToDel->pNextLoop;
  113099. #if WHERETRACE_ENABLED /* 0x8 */
  113100. if( sqlite3WhereTrace & 0x8 ){
  113101. sqlite3DebugPrintf(" delete: ");
  113102. whereLoopPrint(pToDel, pBuilder->pWC);
  113103. }
  113104. #endif
  113105. whereLoopDelete(db, pToDel);
  113106. }
  113107. }
  113108. whereLoopXfer(db, p, pTemplate);
  113109. if( (p->wsFlags & WHERE_VIRTUALTABLE)==0 ){
  113110. Index *pIndex = p->u.btree.pIndex;
  113111. if( pIndex && pIndex->tnum==0 ){
  113112. p->u.btree.pIndex = 0;
  113113. }
  113114. }
  113115. return SQLITE_OK;
  113116. }
  113117. /*
  113118. ** Adjust the WhereLoop.nOut value downward to account for terms of the
  113119. ** WHERE clause that reference the loop but which are not used by an
  113120. ** index.
  113121. *
  113122. ** For every WHERE clause term that is not used by the index
  113123. ** and which has a truth probability assigned by one of the likelihood(),
  113124. ** likely(), or unlikely() SQL functions, reduce the estimated number
  113125. ** of output rows by the probability specified.
  113126. **
  113127. ** TUNING: For every WHERE clause term that is not used by the index
  113128. ** and which does not have an assigned truth probability, heuristics
  113129. ** described below are used to try to estimate the truth probability.
  113130. ** TODO --> Perhaps this is something that could be improved by better
  113131. ** table statistics.
  113132. **
  113133. ** Heuristic 1: Estimate the truth probability as 93.75%. The 93.75%
  113134. ** value corresponds to -1 in LogEst notation, so this means decrement
  113135. ** the WhereLoop.nOut field for every such WHERE clause term.
  113136. **
  113137. ** Heuristic 2: If there exists one or more WHERE clause terms of the
  113138. ** form "x==EXPR" and EXPR is not a constant 0 or 1, then make sure the
  113139. ** final output row estimate is no greater than 1/4 of the total number
  113140. ** of rows in the table. In other words, assume that x==EXPR will filter
  113141. ** out at least 3 out of 4 rows. If EXPR is -1 or 0 or 1, then maybe the
  113142. ** "x" column is boolean or else -1 or 0 or 1 is a common default value
  113143. ** on the "x" column and so in that case only cap the output row estimate
  113144. ** at 1/2 instead of 1/4.
  113145. */
  113146. static void whereLoopOutputAdjust(
  113147. WhereClause *pWC, /* The WHERE clause */
  113148. WhereLoop *pLoop, /* The loop to adjust downward */
  113149. LogEst nRow /* Number of rows in the entire table */
  113150. ){
  113151. WhereTerm *pTerm, *pX;
  113152. Bitmask notAllowed = ~(pLoop->prereq|pLoop->maskSelf);
  113153. int i, j, k;
  113154. LogEst iReduce = 0; /* pLoop->nOut should not exceed nRow-iReduce */
  113155. assert( (pLoop->wsFlags & WHERE_AUTO_INDEX)==0 );
  113156. for(i=pWC->nTerm, pTerm=pWC->a; i>0; i--, pTerm++){
  113157. if( (pTerm->wtFlags & TERM_VIRTUAL)!=0 ) break;
  113158. if( (pTerm->prereqAll & pLoop->maskSelf)==0 ) continue;
  113159. if( (pTerm->prereqAll & notAllowed)!=0 ) continue;
  113160. for(j=pLoop->nLTerm-1; j>=0; j--){
  113161. pX = pLoop->aLTerm[j];
  113162. if( pX==0 ) continue;
  113163. if( pX==pTerm ) break;
  113164. if( pX->iParent>=0 && (&pWC->a[pX->iParent])==pTerm ) break;
  113165. }
  113166. if( j<0 ){
  113167. if( pTerm->truthProb<=0 ){
  113168. /* If a truth probability is specified using the likelihood() hints,
  113169. ** then use the probability provided by the application. */
  113170. pLoop->nOut += pTerm->truthProb;
  113171. }else{
  113172. /* In the absence of explicit truth probabilities, use heuristics to
  113173. ** guess a reasonable truth probability. */
  113174. pLoop->nOut--;
  113175. if( pTerm->eOperator&WO_EQ ){
  113176. Expr *pRight = pTerm->pExpr->pRight;
  113177. if( sqlite3ExprIsInteger(pRight, &k) && k>=(-1) && k<=1 ){
  113178. k = 10;
  113179. }else{
  113180. k = 20;
  113181. }
  113182. if( iReduce<k ) iReduce = k;
  113183. }
  113184. }
  113185. }
  113186. }
  113187. if( pLoop->nOut > nRow-iReduce ) pLoop->nOut = nRow - iReduce;
  113188. }
  113189. /*
  113190. ** Adjust the cost C by the costMult facter T. This only occurs if
  113191. ** compiled with -DSQLITE_ENABLE_COSTMULT
  113192. */
  113193. #ifdef SQLITE_ENABLE_COSTMULT
  113194. # define ApplyCostMultiplier(C,T) C += T
  113195. #else
  113196. # define ApplyCostMultiplier(C,T)
  113197. #endif
  113198. /*
  113199. ** We have so far matched pBuilder->pNew->u.btree.nEq terms of the
  113200. ** index pIndex. Try to match one more.
  113201. **
  113202. ** When this function is called, pBuilder->pNew->nOut contains the
  113203. ** number of rows expected to be visited by filtering using the nEq
  113204. ** terms only. If it is modified, this value is restored before this
  113205. ** function returns.
  113206. **
  113207. ** If pProbe->tnum==0, that means pIndex is a fake index used for the
  113208. ** INTEGER PRIMARY KEY.
  113209. */
  113210. static int whereLoopAddBtreeIndex(
  113211. WhereLoopBuilder *pBuilder, /* The WhereLoop factory */
  113212. struct SrcList_item *pSrc, /* FROM clause term being analyzed */
  113213. Index *pProbe, /* An index on pSrc */
  113214. LogEst nInMul /* log(Number of iterations due to IN) */
  113215. ){
  113216. WhereInfo *pWInfo = pBuilder->pWInfo; /* WHERE analyse context */
  113217. Parse *pParse = pWInfo->pParse; /* Parsing context */
  113218. sqlite3 *db = pParse->db; /* Database connection malloc context */
  113219. WhereLoop *pNew; /* Template WhereLoop under construction */
  113220. WhereTerm *pTerm; /* A WhereTerm under consideration */
  113221. int opMask; /* Valid operators for constraints */
  113222. WhereScan scan; /* Iterator for WHERE terms */
  113223. Bitmask saved_prereq; /* Original value of pNew->prereq */
  113224. u16 saved_nLTerm; /* Original value of pNew->nLTerm */
  113225. u16 saved_nEq; /* Original value of pNew->u.btree.nEq */
  113226. u16 saved_nSkip; /* Original value of pNew->nSkip */
  113227. u32 saved_wsFlags; /* Original value of pNew->wsFlags */
  113228. LogEst saved_nOut; /* Original value of pNew->nOut */
  113229. int iCol; /* Index of the column in the table */
  113230. int rc = SQLITE_OK; /* Return code */
  113231. LogEst rSize; /* Number of rows in the table */
  113232. LogEst rLogSize; /* Logarithm of table size */
  113233. WhereTerm *pTop = 0, *pBtm = 0; /* Top and bottom range constraints */
  113234. pNew = pBuilder->pNew;
  113235. if( db->mallocFailed ) return SQLITE_NOMEM;
  113236. assert( (pNew->wsFlags & WHERE_VIRTUALTABLE)==0 );
  113237. assert( (pNew->wsFlags & WHERE_TOP_LIMIT)==0 );
  113238. if( pNew->wsFlags & WHERE_BTM_LIMIT ){
  113239. opMask = WO_LT|WO_LE;
  113240. }else if( pProbe->tnum<=0 || (pSrc->jointype & JT_LEFT)!=0 ){
  113241. opMask = WO_EQ|WO_IN|WO_GT|WO_GE|WO_LT|WO_LE;
  113242. }else{
  113243. opMask = WO_EQ|WO_IN|WO_ISNULL|WO_GT|WO_GE|WO_LT|WO_LE;
  113244. }
  113245. if( pProbe->bUnordered ) opMask &= ~(WO_GT|WO_GE|WO_LT|WO_LE);
  113246. assert( pNew->u.btree.nEq<pProbe->nColumn );
  113247. iCol = pProbe->aiColumn[pNew->u.btree.nEq];
  113248. pTerm = whereScanInit(&scan, pBuilder->pWC, pSrc->iCursor, iCol,
  113249. opMask, pProbe);
  113250. saved_nEq = pNew->u.btree.nEq;
  113251. saved_nSkip = pNew->nSkip;
  113252. saved_nLTerm = pNew->nLTerm;
  113253. saved_wsFlags = pNew->wsFlags;
  113254. saved_prereq = pNew->prereq;
  113255. saved_nOut = pNew->nOut;
  113256. pNew->rSetup = 0;
  113257. rSize = pProbe->aiRowLogEst[0];
  113258. rLogSize = estLog(rSize);
  113259. for(; rc==SQLITE_OK && pTerm!=0; pTerm = whereScanNext(&scan)){
  113260. u16 eOp = pTerm->eOperator; /* Shorthand for pTerm->eOperator */
  113261. LogEst rCostIdx;
  113262. LogEst nOutUnadjusted; /* nOut before IN() and WHERE adjustments */
  113263. int nIn = 0;
  113264. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  113265. int nRecValid = pBuilder->nRecValid;
  113266. #endif
  113267. if( (eOp==WO_ISNULL || (pTerm->wtFlags&TERM_VNULL)!=0)
  113268. && (iCol<0 || pSrc->pTab->aCol[iCol].notNull)
  113269. ){
  113270. continue; /* ignore IS [NOT] NULL constraints on NOT NULL columns */
  113271. }
  113272. if( pTerm->prereqRight & pNew->maskSelf ) continue;
  113273. /* Do not allow the upper bound of a LIKE optimization range constraint
  113274. ** to mix with a lower range bound from some other source */
  113275. if( pTerm->wtFlags & TERM_LIKEOPT && pTerm->eOperator==WO_LT ) continue;
  113276. pNew->wsFlags = saved_wsFlags;
  113277. pNew->u.btree.nEq = saved_nEq;
  113278. pNew->nLTerm = saved_nLTerm;
  113279. if( whereLoopResize(db, pNew, pNew->nLTerm+1) ) break; /* OOM */
  113280. pNew->aLTerm[pNew->nLTerm++] = pTerm;
  113281. pNew->prereq = (saved_prereq | pTerm->prereqRight) & ~pNew->maskSelf;
  113282. assert( nInMul==0
  113283. || (pNew->wsFlags & WHERE_COLUMN_NULL)!=0
  113284. || (pNew->wsFlags & WHERE_COLUMN_IN)!=0
  113285. || (pNew->wsFlags & WHERE_SKIPSCAN)!=0
  113286. );
  113287. if( eOp & WO_IN ){
  113288. Expr *pExpr = pTerm->pExpr;
  113289. pNew->wsFlags |= WHERE_COLUMN_IN;
  113290. if( ExprHasProperty(pExpr, EP_xIsSelect) ){
  113291. /* "x IN (SELECT ...)": TUNING: the SELECT returns 25 rows */
  113292. nIn = 46; assert( 46==sqlite3LogEst(25) );
  113293. }else if( ALWAYS(pExpr->x.pList && pExpr->x.pList->nExpr) ){
  113294. /* "x IN (value, value, ...)" */
  113295. nIn = sqlite3LogEst(pExpr->x.pList->nExpr);
  113296. }
  113297. assert( nIn>0 ); /* RHS always has 2 or more terms... The parser
  113298. ** changes "x IN (?)" into "x=?". */
  113299. }else if( eOp & (WO_EQ) ){
  113300. pNew->wsFlags |= WHERE_COLUMN_EQ;
  113301. if( iCol<0 || (nInMul==0 && pNew->u.btree.nEq==pProbe->nKeyCol-1) ){
  113302. if( iCol>=0 && pProbe->uniqNotNull==0 ){
  113303. pNew->wsFlags |= WHERE_UNQ_WANTED;
  113304. }else{
  113305. pNew->wsFlags |= WHERE_ONEROW;
  113306. }
  113307. }
  113308. }else if( eOp & WO_ISNULL ){
  113309. pNew->wsFlags |= WHERE_COLUMN_NULL;
  113310. }else if( eOp & (WO_GT|WO_GE) ){
  113311. testcase( eOp & WO_GT );
  113312. testcase( eOp & WO_GE );
  113313. pNew->wsFlags |= WHERE_COLUMN_RANGE|WHERE_BTM_LIMIT;
  113314. pBtm = pTerm;
  113315. pTop = 0;
  113316. if( pTerm->wtFlags & TERM_LIKEOPT ){
  113317. /* Range contraints that come from the LIKE optimization are
  113318. ** always used in pairs. */
  113319. pTop = &pTerm[1];
  113320. assert( (pTop-(pTerm->pWC->a))<pTerm->pWC->nTerm );
  113321. assert( pTop->wtFlags & TERM_LIKEOPT );
  113322. assert( pTop->eOperator==WO_LT );
  113323. if( whereLoopResize(db, pNew, pNew->nLTerm+1) ) break; /* OOM */
  113324. pNew->aLTerm[pNew->nLTerm++] = pTop;
  113325. pNew->wsFlags |= WHERE_TOP_LIMIT;
  113326. }
  113327. }else{
  113328. assert( eOp & (WO_LT|WO_LE) );
  113329. testcase( eOp & WO_LT );
  113330. testcase( eOp & WO_LE );
  113331. pNew->wsFlags |= WHERE_COLUMN_RANGE|WHERE_TOP_LIMIT;
  113332. pTop = pTerm;
  113333. pBtm = (pNew->wsFlags & WHERE_BTM_LIMIT)!=0 ?
  113334. pNew->aLTerm[pNew->nLTerm-2] : 0;
  113335. }
  113336. /* At this point pNew->nOut is set to the number of rows expected to
  113337. ** be visited by the index scan before considering term pTerm, or the
  113338. ** values of nIn and nInMul. In other words, assuming that all
  113339. ** "x IN(...)" terms are replaced with "x = ?". This block updates
  113340. ** the value of pNew->nOut to account for pTerm (but not nIn/nInMul). */
  113341. assert( pNew->nOut==saved_nOut );
  113342. if( pNew->wsFlags & WHERE_COLUMN_RANGE ){
  113343. /* Adjust nOut using stat3/stat4 data. Or, if there is no stat3/stat4
  113344. ** data, using some other estimate. */
  113345. whereRangeScanEst(pParse, pBuilder, pBtm, pTop, pNew);
  113346. }else{
  113347. int nEq = ++pNew->u.btree.nEq;
  113348. assert( eOp & (WO_ISNULL|WO_EQ|WO_IN) );
  113349. assert( pNew->nOut==saved_nOut );
  113350. if( pTerm->truthProb<=0 && iCol>=0 ){
  113351. assert( (eOp & WO_IN) || nIn==0 );
  113352. testcase( eOp & WO_IN );
  113353. pNew->nOut += pTerm->truthProb;
  113354. pNew->nOut -= nIn;
  113355. }else{
  113356. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  113357. tRowcnt nOut = 0;
  113358. if( nInMul==0
  113359. && pProbe->nSample
  113360. && pNew->u.btree.nEq<=pProbe->nSampleCol
  113361. && ((eOp & WO_IN)==0 || !ExprHasProperty(pTerm->pExpr, EP_xIsSelect))
  113362. ){
  113363. Expr *pExpr = pTerm->pExpr;
  113364. if( (eOp & (WO_EQ|WO_ISNULL))!=0 ){
  113365. testcase( eOp & WO_EQ );
  113366. testcase( eOp & WO_ISNULL );
  113367. rc = whereEqualScanEst(pParse, pBuilder, pExpr->pRight, &nOut);
  113368. }else{
  113369. rc = whereInScanEst(pParse, pBuilder, pExpr->x.pList, &nOut);
  113370. }
  113371. if( rc==SQLITE_NOTFOUND ) rc = SQLITE_OK;
  113372. if( rc!=SQLITE_OK ) break; /* Jump out of the pTerm loop */
  113373. if( nOut ){
  113374. pNew->nOut = sqlite3LogEst(nOut);
  113375. if( pNew->nOut>saved_nOut ) pNew->nOut = saved_nOut;
  113376. pNew->nOut -= nIn;
  113377. }
  113378. }
  113379. if( nOut==0 )
  113380. #endif
  113381. {
  113382. pNew->nOut += (pProbe->aiRowLogEst[nEq] - pProbe->aiRowLogEst[nEq-1]);
  113383. if( eOp & WO_ISNULL ){
  113384. /* TUNING: If there is no likelihood() value, assume that a
  113385. ** "col IS NULL" expression matches twice as many rows
  113386. ** as (col=?). */
  113387. pNew->nOut += 10;
  113388. }
  113389. }
  113390. }
  113391. }
  113392. /* Set rCostIdx to the cost of visiting selected rows in index. Add
  113393. ** it to pNew->rRun, which is currently set to the cost of the index
  113394. ** seek only. Then, if this is a non-covering index, add the cost of
  113395. ** visiting the rows in the main table. */
  113396. rCostIdx = pNew->nOut + 1 + (15*pProbe->szIdxRow)/pSrc->pTab->szTabRow;
  113397. pNew->rRun = sqlite3LogEstAdd(rLogSize, rCostIdx);
  113398. if( (pNew->wsFlags & (WHERE_IDX_ONLY|WHERE_IPK))==0 ){
  113399. pNew->rRun = sqlite3LogEstAdd(pNew->rRun, pNew->nOut + 16);
  113400. }
  113401. ApplyCostMultiplier(pNew->rRun, pProbe->pTable->costMult);
  113402. nOutUnadjusted = pNew->nOut;
  113403. pNew->rRun += nInMul + nIn;
  113404. pNew->nOut += nInMul + nIn;
  113405. whereLoopOutputAdjust(pBuilder->pWC, pNew, rSize);
  113406. rc = whereLoopInsert(pBuilder, pNew);
  113407. if( pNew->wsFlags & WHERE_COLUMN_RANGE ){
  113408. pNew->nOut = saved_nOut;
  113409. }else{
  113410. pNew->nOut = nOutUnadjusted;
  113411. }
  113412. if( (pNew->wsFlags & WHERE_TOP_LIMIT)==0
  113413. && pNew->u.btree.nEq<pProbe->nColumn
  113414. ){
  113415. whereLoopAddBtreeIndex(pBuilder, pSrc, pProbe, nInMul+nIn);
  113416. }
  113417. pNew->nOut = saved_nOut;
  113418. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  113419. pBuilder->nRecValid = nRecValid;
  113420. #endif
  113421. }
  113422. pNew->prereq = saved_prereq;
  113423. pNew->u.btree.nEq = saved_nEq;
  113424. pNew->nSkip = saved_nSkip;
  113425. pNew->wsFlags = saved_wsFlags;
  113426. pNew->nOut = saved_nOut;
  113427. pNew->nLTerm = saved_nLTerm;
  113428. /* Consider using a skip-scan if there are no WHERE clause constraints
  113429. ** available for the left-most terms of the index, and if the average
  113430. ** number of repeats in the left-most terms is at least 18.
  113431. **
  113432. ** The magic number 18 is selected on the basis that scanning 17 rows
  113433. ** is almost always quicker than an index seek (even though if the index
  113434. ** contains fewer than 2^17 rows we assume otherwise in other parts of
  113435. ** the code). And, even if it is not, it should not be too much slower.
  113436. ** On the other hand, the extra seeks could end up being significantly
  113437. ** more expensive. */
  113438. assert( 42==sqlite3LogEst(18) );
  113439. if( saved_nEq==saved_nSkip
  113440. && saved_nEq+1<pProbe->nKeyCol
  113441. && pProbe->noSkipScan==0
  113442. && pProbe->aiRowLogEst[saved_nEq+1]>=42 /* TUNING: Minimum for skip-scan */
  113443. && (rc = whereLoopResize(db, pNew, pNew->nLTerm+1))==SQLITE_OK
  113444. ){
  113445. LogEst nIter;
  113446. pNew->u.btree.nEq++;
  113447. pNew->nSkip++;
  113448. pNew->aLTerm[pNew->nLTerm++] = 0;
  113449. pNew->wsFlags |= WHERE_SKIPSCAN;
  113450. nIter = pProbe->aiRowLogEst[saved_nEq] - pProbe->aiRowLogEst[saved_nEq+1];
  113451. pNew->nOut -= nIter;
  113452. /* TUNING: Because uncertainties in the estimates for skip-scan queries,
  113453. ** add a 1.375 fudge factor to make skip-scan slightly less likely. */
  113454. nIter += 5;
  113455. whereLoopAddBtreeIndex(pBuilder, pSrc, pProbe, nIter + nInMul);
  113456. pNew->nOut = saved_nOut;
  113457. pNew->u.btree.nEq = saved_nEq;
  113458. pNew->nSkip = saved_nSkip;
  113459. pNew->wsFlags = saved_wsFlags;
  113460. }
  113461. return rc;
  113462. }
  113463. /*
  113464. ** Return True if it is possible that pIndex might be useful in
  113465. ** implementing the ORDER BY clause in pBuilder.
  113466. **
  113467. ** Return False if pBuilder does not contain an ORDER BY clause or
  113468. ** if there is no way for pIndex to be useful in implementing that
  113469. ** ORDER BY clause.
  113470. */
  113471. static int indexMightHelpWithOrderBy(
  113472. WhereLoopBuilder *pBuilder,
  113473. Index *pIndex,
  113474. int iCursor
  113475. ){
  113476. ExprList *pOB;
  113477. int ii, jj;
  113478. if( pIndex->bUnordered ) return 0;
  113479. if( (pOB = pBuilder->pWInfo->pOrderBy)==0 ) return 0;
  113480. for(ii=0; ii<pOB->nExpr; ii++){
  113481. Expr *pExpr = sqlite3ExprSkipCollate(pOB->a[ii].pExpr);
  113482. if( pExpr->op!=TK_COLUMN ) return 0;
  113483. if( pExpr->iTable==iCursor ){
  113484. if( pExpr->iColumn<0 ) return 1;
  113485. for(jj=0; jj<pIndex->nKeyCol; jj++){
  113486. if( pExpr->iColumn==pIndex->aiColumn[jj] ) return 1;
  113487. }
  113488. }
  113489. }
  113490. return 0;
  113491. }
  113492. /*
  113493. ** Return a bitmask where 1s indicate that the corresponding column of
  113494. ** the table is used by an index. Only the first 63 columns are considered.
  113495. */
  113496. static Bitmask columnsInIndex(Index *pIdx){
  113497. Bitmask m = 0;
  113498. int j;
  113499. for(j=pIdx->nColumn-1; j>=0; j--){
  113500. int x = pIdx->aiColumn[j];
  113501. if( x>=0 ){
  113502. testcase( x==BMS-1 );
  113503. testcase( x==BMS-2 );
  113504. if( x<BMS-1 ) m |= MASKBIT(x);
  113505. }
  113506. }
  113507. return m;
  113508. }
  113509. /* Check to see if a partial index with pPartIndexWhere can be used
  113510. ** in the current query. Return true if it can be and false if not.
  113511. */
  113512. static int whereUsablePartialIndex(int iTab, WhereClause *pWC, Expr *pWhere){
  113513. int i;
  113514. WhereTerm *pTerm;
  113515. for(i=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
  113516. Expr *pExpr = pTerm->pExpr;
  113517. if( sqlite3ExprImpliesExpr(pExpr, pWhere, iTab)
  113518. && (!ExprHasProperty(pExpr, EP_FromJoin) || pExpr->iRightJoinTable==iTab)
  113519. ){
  113520. return 1;
  113521. }
  113522. }
  113523. return 0;
  113524. }
  113525. /*
  113526. ** Add all WhereLoop objects for a single table of the join where the table
  113527. ** is idenfied by pBuilder->pNew->iTab. That table is guaranteed to be
  113528. ** a b-tree table, not a virtual table.
  113529. **
  113530. ** The costs (WhereLoop.rRun) of the b-tree loops added by this function
  113531. ** are calculated as follows:
  113532. **
  113533. ** For a full scan, assuming the table (or index) contains nRow rows:
  113534. **
  113535. ** cost = nRow * 3.0 // full-table scan
  113536. ** cost = nRow * K // scan of covering index
  113537. ** cost = nRow * (K+3.0) // scan of non-covering index
  113538. **
  113539. ** where K is a value between 1.1 and 3.0 set based on the relative
  113540. ** estimated average size of the index and table records.
  113541. **
  113542. ** For an index scan, where nVisit is the number of index rows visited
  113543. ** by the scan, and nSeek is the number of seek operations required on
  113544. ** the index b-tree:
  113545. **
  113546. ** cost = nSeek * (log(nRow) + K * nVisit) // covering index
  113547. ** cost = nSeek * (log(nRow) + (K+3.0) * nVisit) // non-covering index
  113548. **
  113549. ** Normally, nSeek is 1. nSeek values greater than 1 come about if the
  113550. ** WHERE clause includes "x IN (....)" terms used in place of "x=?". Or when
  113551. ** implicit "x IN (SELECT x FROM tbl)" terms are added for skip-scans.
  113552. **
  113553. ** The estimated values (nRow, nVisit, nSeek) often contain a large amount
  113554. ** of uncertainty. For this reason, scoring is designed to pick plans that
  113555. ** "do the least harm" if the estimates are inaccurate. For example, a
  113556. ** log(nRow) factor is omitted from a non-covering index scan in order to
  113557. ** bias the scoring in favor of using an index, since the worst-case
  113558. ** performance of using an index is far better than the worst-case performance
  113559. ** of a full table scan.
  113560. */
  113561. static int whereLoopAddBtree(
  113562. WhereLoopBuilder *pBuilder, /* WHERE clause information */
  113563. Bitmask mExtra /* Extra prerequesites for using this table */
  113564. ){
  113565. WhereInfo *pWInfo; /* WHERE analysis context */
  113566. Index *pProbe; /* An index we are evaluating */
  113567. Index sPk; /* A fake index object for the primary key */
  113568. LogEst aiRowEstPk[2]; /* The aiRowLogEst[] value for the sPk index */
  113569. i16 aiColumnPk = -1; /* The aColumn[] value for the sPk index */
  113570. SrcList *pTabList; /* The FROM clause */
  113571. struct SrcList_item *pSrc; /* The FROM clause btree term to add */
  113572. WhereLoop *pNew; /* Template WhereLoop object */
  113573. int rc = SQLITE_OK; /* Return code */
  113574. int iSortIdx = 1; /* Index number */
  113575. int b; /* A boolean value */
  113576. LogEst rSize; /* number of rows in the table */
  113577. LogEst rLogSize; /* Logarithm of the number of rows in the table */
  113578. WhereClause *pWC; /* The parsed WHERE clause */
  113579. Table *pTab; /* Table being queried */
  113580. pNew = pBuilder->pNew;
  113581. pWInfo = pBuilder->pWInfo;
  113582. pTabList = pWInfo->pTabList;
  113583. pSrc = pTabList->a + pNew->iTab;
  113584. pTab = pSrc->pTab;
  113585. pWC = pBuilder->pWC;
  113586. assert( !IsVirtual(pSrc->pTab) );
  113587. if( pSrc->pIndex ){
  113588. /* An INDEXED BY clause specifies a particular index to use */
  113589. pProbe = pSrc->pIndex;
  113590. }else if( !HasRowid(pTab) ){
  113591. pProbe = pTab->pIndex;
  113592. }else{
  113593. /* There is no INDEXED BY clause. Create a fake Index object in local
  113594. ** variable sPk to represent the rowid primary key index. Make this
  113595. ** fake index the first in a chain of Index objects with all of the real
  113596. ** indices to follow */
  113597. Index *pFirst; /* First of real indices on the table */
  113598. memset(&sPk, 0, sizeof(Index));
  113599. sPk.nKeyCol = 1;
  113600. sPk.nColumn = 1;
  113601. sPk.aiColumn = &aiColumnPk;
  113602. sPk.aiRowLogEst = aiRowEstPk;
  113603. sPk.onError = OE_Replace;
  113604. sPk.pTable = pTab;
  113605. sPk.szIdxRow = pTab->szTabRow;
  113606. aiRowEstPk[0] = pTab->nRowLogEst;
  113607. aiRowEstPk[1] = 0;
  113608. pFirst = pSrc->pTab->pIndex;
  113609. if( pSrc->notIndexed==0 ){
  113610. /* The real indices of the table are only considered if the
  113611. ** NOT INDEXED qualifier is omitted from the FROM clause */
  113612. sPk.pNext = pFirst;
  113613. }
  113614. pProbe = &sPk;
  113615. }
  113616. rSize = pTab->nRowLogEst;
  113617. rLogSize = estLog(rSize);
  113618. #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
  113619. /* Automatic indexes */
  113620. if( !pBuilder->pOrSet
  113621. && (pWInfo->wctrlFlags & WHERE_NO_AUTOINDEX)==0
  113622. && (pWInfo->pParse->db->flags & SQLITE_AutoIndex)!=0
  113623. && pSrc->pIndex==0
  113624. && !pSrc->viaCoroutine
  113625. && !pSrc->notIndexed
  113626. && HasRowid(pTab)
  113627. && !pSrc->isCorrelated
  113628. && !pSrc->isRecursive
  113629. ){
  113630. /* Generate auto-index WhereLoops */
  113631. WhereTerm *pTerm;
  113632. WhereTerm *pWCEnd = pWC->a + pWC->nTerm;
  113633. for(pTerm=pWC->a; rc==SQLITE_OK && pTerm<pWCEnd; pTerm++){
  113634. if( pTerm->prereqRight & pNew->maskSelf ) continue;
  113635. if( termCanDriveIndex(pTerm, pSrc, 0) ){
  113636. pNew->u.btree.nEq = 1;
  113637. pNew->nSkip = 0;
  113638. pNew->u.btree.pIndex = 0;
  113639. pNew->nLTerm = 1;
  113640. pNew->aLTerm[0] = pTerm;
  113641. /* TUNING: One-time cost for computing the automatic index is
  113642. ** estimated to be X*N*log2(N) where N is the number of rows in
  113643. ** the table being indexed and where X is 7 (LogEst=28) for normal
  113644. ** tables or 1.375 (LogEst=4) for views and subqueries. The value
  113645. ** of X is smaller for views and subqueries so that the query planner
  113646. ** will be more aggressive about generating automatic indexes for
  113647. ** those objects, since there is no opportunity to add schema
  113648. ** indexes on subqueries and views. */
  113649. pNew->rSetup = rLogSize + rSize + 4;
  113650. if( pTab->pSelect==0 && (pTab->tabFlags & TF_Ephemeral)==0 ){
  113651. pNew->rSetup += 24;
  113652. }
  113653. ApplyCostMultiplier(pNew->rSetup, pTab->costMult);
  113654. /* TUNING: Each index lookup yields 20 rows in the table. This
  113655. ** is more than the usual guess of 10 rows, since we have no way
  113656. ** of knowing how selective the index will ultimately be. It would
  113657. ** not be unreasonable to make this value much larger. */
  113658. pNew->nOut = 43; assert( 43==sqlite3LogEst(20) );
  113659. pNew->rRun = sqlite3LogEstAdd(rLogSize,pNew->nOut);
  113660. pNew->wsFlags = WHERE_AUTO_INDEX;
  113661. pNew->prereq = mExtra | pTerm->prereqRight;
  113662. rc = whereLoopInsert(pBuilder, pNew);
  113663. }
  113664. }
  113665. }
  113666. #endif /* SQLITE_OMIT_AUTOMATIC_INDEX */
  113667. /* Loop over all indices
  113668. */
  113669. for(; rc==SQLITE_OK && pProbe; pProbe=pProbe->pNext, iSortIdx++){
  113670. if( pProbe->pPartIdxWhere!=0
  113671. && !whereUsablePartialIndex(pSrc->iCursor, pWC, pProbe->pPartIdxWhere) ){
  113672. testcase( pNew->iTab!=pSrc->iCursor ); /* See ticket [98d973b8f5] */
  113673. continue; /* Partial index inappropriate for this query */
  113674. }
  113675. rSize = pProbe->aiRowLogEst[0];
  113676. pNew->u.btree.nEq = 0;
  113677. pNew->nSkip = 0;
  113678. pNew->nLTerm = 0;
  113679. pNew->iSortIdx = 0;
  113680. pNew->rSetup = 0;
  113681. pNew->prereq = mExtra;
  113682. pNew->nOut = rSize;
  113683. pNew->u.btree.pIndex = pProbe;
  113684. b = indexMightHelpWithOrderBy(pBuilder, pProbe, pSrc->iCursor);
  113685. /* The ONEPASS_DESIRED flags never occurs together with ORDER BY */
  113686. assert( (pWInfo->wctrlFlags & WHERE_ONEPASS_DESIRED)==0 || b==0 );
  113687. if( pProbe->tnum<=0 ){
  113688. /* Integer primary key index */
  113689. pNew->wsFlags = WHERE_IPK;
  113690. /* Full table scan */
  113691. pNew->iSortIdx = b ? iSortIdx : 0;
  113692. /* TUNING: Cost of full table scan is (N*3.0). */
  113693. pNew->rRun = rSize + 16;
  113694. ApplyCostMultiplier(pNew->rRun, pTab->costMult);
  113695. whereLoopOutputAdjust(pWC, pNew, rSize);
  113696. rc = whereLoopInsert(pBuilder, pNew);
  113697. pNew->nOut = rSize;
  113698. if( rc ) break;
  113699. }else{
  113700. Bitmask m;
  113701. if( pProbe->isCovering ){
  113702. pNew->wsFlags = WHERE_IDX_ONLY | WHERE_INDEXED;
  113703. m = 0;
  113704. }else{
  113705. m = pSrc->colUsed & ~columnsInIndex(pProbe);
  113706. pNew->wsFlags = (m==0) ? (WHERE_IDX_ONLY|WHERE_INDEXED) : WHERE_INDEXED;
  113707. }
  113708. /* Full scan via index */
  113709. if( b
  113710. || !HasRowid(pTab)
  113711. || ( m==0
  113712. && pProbe->bUnordered==0
  113713. && (pProbe->szIdxRow<pTab->szTabRow)
  113714. && (pWInfo->wctrlFlags & WHERE_ONEPASS_DESIRED)==0
  113715. && sqlite3GlobalConfig.bUseCis
  113716. && OptimizationEnabled(pWInfo->pParse->db, SQLITE_CoverIdxScan)
  113717. )
  113718. ){
  113719. pNew->iSortIdx = b ? iSortIdx : 0;
  113720. /* The cost of visiting the index rows is N*K, where K is
  113721. ** between 1.1 and 3.0, depending on the relative sizes of the
  113722. ** index and table rows. If this is a non-covering index scan,
  113723. ** also add the cost of visiting table rows (N*3.0). */
  113724. pNew->rRun = rSize + 1 + (15*pProbe->szIdxRow)/pTab->szTabRow;
  113725. if( m!=0 ){
  113726. pNew->rRun = sqlite3LogEstAdd(pNew->rRun, rSize+16);
  113727. }
  113728. ApplyCostMultiplier(pNew->rRun, pTab->costMult);
  113729. whereLoopOutputAdjust(pWC, pNew, rSize);
  113730. rc = whereLoopInsert(pBuilder, pNew);
  113731. pNew->nOut = rSize;
  113732. if( rc ) break;
  113733. }
  113734. }
  113735. rc = whereLoopAddBtreeIndex(pBuilder, pSrc, pProbe, 0);
  113736. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  113737. sqlite3Stat4ProbeFree(pBuilder->pRec);
  113738. pBuilder->nRecValid = 0;
  113739. pBuilder->pRec = 0;
  113740. #endif
  113741. /* If there was an INDEXED BY clause, then only that one index is
  113742. ** considered. */
  113743. if( pSrc->pIndex ) break;
  113744. }
  113745. return rc;
  113746. }
  113747. #ifndef SQLITE_OMIT_VIRTUALTABLE
  113748. /*
  113749. ** Add all WhereLoop objects for a table of the join identified by
  113750. ** pBuilder->pNew->iTab. That table is guaranteed to be a virtual table.
  113751. */
  113752. static int whereLoopAddVirtual(
  113753. WhereLoopBuilder *pBuilder, /* WHERE clause information */
  113754. Bitmask mExtra
  113755. ){
  113756. WhereInfo *pWInfo; /* WHERE analysis context */
  113757. Parse *pParse; /* The parsing context */
  113758. WhereClause *pWC; /* The WHERE clause */
  113759. struct SrcList_item *pSrc; /* The FROM clause term to search */
  113760. Table *pTab;
  113761. sqlite3 *db;
  113762. sqlite3_index_info *pIdxInfo;
  113763. struct sqlite3_index_constraint *pIdxCons;
  113764. struct sqlite3_index_constraint_usage *pUsage;
  113765. WhereTerm *pTerm;
  113766. int i, j;
  113767. int iTerm, mxTerm;
  113768. int nConstraint;
  113769. int seenIn = 0; /* True if an IN operator is seen */
  113770. int seenVar = 0; /* True if a non-constant constraint is seen */
  113771. int iPhase; /* 0: const w/o IN, 1: const, 2: no IN, 2: IN */
  113772. WhereLoop *pNew;
  113773. int rc = SQLITE_OK;
  113774. pWInfo = pBuilder->pWInfo;
  113775. pParse = pWInfo->pParse;
  113776. db = pParse->db;
  113777. pWC = pBuilder->pWC;
  113778. pNew = pBuilder->pNew;
  113779. pSrc = &pWInfo->pTabList->a[pNew->iTab];
  113780. pTab = pSrc->pTab;
  113781. assert( IsVirtual(pTab) );
  113782. pIdxInfo = allocateIndexInfo(pParse, pWC, pSrc, pBuilder->pOrderBy);
  113783. if( pIdxInfo==0 ) return SQLITE_NOMEM;
  113784. pNew->prereq = 0;
  113785. pNew->rSetup = 0;
  113786. pNew->wsFlags = WHERE_VIRTUALTABLE;
  113787. pNew->nLTerm = 0;
  113788. pNew->u.vtab.needFree = 0;
  113789. pUsage = pIdxInfo->aConstraintUsage;
  113790. nConstraint = pIdxInfo->nConstraint;
  113791. if( whereLoopResize(db, pNew, nConstraint) ){
  113792. sqlite3DbFree(db, pIdxInfo);
  113793. return SQLITE_NOMEM;
  113794. }
  113795. for(iPhase=0; iPhase<=3; iPhase++){
  113796. if( !seenIn && (iPhase&1)!=0 ){
  113797. iPhase++;
  113798. if( iPhase>3 ) break;
  113799. }
  113800. if( !seenVar && iPhase>1 ) break;
  113801. pIdxCons = *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint;
  113802. for(i=0; i<pIdxInfo->nConstraint; i++, pIdxCons++){
  113803. j = pIdxCons->iTermOffset;
  113804. pTerm = &pWC->a[j];
  113805. switch( iPhase ){
  113806. case 0: /* Constants without IN operator */
  113807. pIdxCons->usable = 0;
  113808. if( (pTerm->eOperator & WO_IN)!=0 ){
  113809. seenIn = 1;
  113810. }
  113811. if( pTerm->prereqRight!=0 ){
  113812. seenVar = 1;
  113813. }else if( (pTerm->eOperator & WO_IN)==0 ){
  113814. pIdxCons->usable = 1;
  113815. }
  113816. break;
  113817. case 1: /* Constants with IN operators */
  113818. assert( seenIn );
  113819. pIdxCons->usable = (pTerm->prereqRight==0);
  113820. break;
  113821. case 2: /* Variables without IN */
  113822. assert( seenVar );
  113823. pIdxCons->usable = (pTerm->eOperator & WO_IN)==0;
  113824. break;
  113825. default: /* Variables with IN */
  113826. assert( seenVar && seenIn );
  113827. pIdxCons->usable = 1;
  113828. break;
  113829. }
  113830. }
  113831. memset(pUsage, 0, sizeof(pUsage[0])*pIdxInfo->nConstraint);
  113832. if( pIdxInfo->needToFreeIdxStr ) sqlite3_free(pIdxInfo->idxStr);
  113833. pIdxInfo->idxStr = 0;
  113834. pIdxInfo->idxNum = 0;
  113835. pIdxInfo->needToFreeIdxStr = 0;
  113836. pIdxInfo->orderByConsumed = 0;
  113837. pIdxInfo->estimatedCost = SQLITE_BIG_DBL / (double)2;
  113838. pIdxInfo->estimatedRows = 25;
  113839. rc = vtabBestIndex(pParse, pTab, pIdxInfo);
  113840. if( rc ) goto whereLoopAddVtab_exit;
  113841. pIdxCons = *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint;
  113842. pNew->prereq = mExtra;
  113843. mxTerm = -1;
  113844. assert( pNew->nLSlot>=nConstraint );
  113845. for(i=0; i<nConstraint; i++) pNew->aLTerm[i] = 0;
  113846. pNew->u.vtab.omitMask = 0;
  113847. for(i=0; i<nConstraint; i++, pIdxCons++){
  113848. if( (iTerm = pUsage[i].argvIndex - 1)>=0 ){
  113849. j = pIdxCons->iTermOffset;
  113850. if( iTerm>=nConstraint
  113851. || j<0
  113852. || j>=pWC->nTerm
  113853. || pNew->aLTerm[iTerm]!=0
  113854. ){
  113855. rc = SQLITE_ERROR;
  113856. sqlite3ErrorMsg(pParse, "%s.xBestIndex() malfunction", pTab->zName);
  113857. goto whereLoopAddVtab_exit;
  113858. }
  113859. testcase( iTerm==nConstraint-1 );
  113860. testcase( j==0 );
  113861. testcase( j==pWC->nTerm-1 );
  113862. pTerm = &pWC->a[j];
  113863. pNew->prereq |= pTerm->prereqRight;
  113864. assert( iTerm<pNew->nLSlot );
  113865. pNew->aLTerm[iTerm] = pTerm;
  113866. if( iTerm>mxTerm ) mxTerm = iTerm;
  113867. testcase( iTerm==15 );
  113868. testcase( iTerm==16 );
  113869. if( iTerm<16 && pUsage[i].omit ) pNew->u.vtab.omitMask |= 1<<iTerm;
  113870. if( (pTerm->eOperator & WO_IN)!=0 ){
  113871. if( pUsage[i].omit==0 ){
  113872. /* Do not attempt to use an IN constraint if the virtual table
  113873. ** says that the equivalent EQ constraint cannot be safely omitted.
  113874. ** If we do attempt to use such a constraint, some rows might be
  113875. ** repeated in the output. */
  113876. break;
  113877. }
  113878. /* A virtual table that is constrained by an IN clause may not
  113879. ** consume the ORDER BY clause because (1) the order of IN terms
  113880. ** is not necessarily related to the order of output terms and
  113881. ** (2) Multiple outputs from a single IN value will not merge
  113882. ** together. */
  113883. pIdxInfo->orderByConsumed = 0;
  113884. }
  113885. }
  113886. }
  113887. if( i>=nConstraint ){
  113888. pNew->nLTerm = mxTerm+1;
  113889. assert( pNew->nLTerm<=pNew->nLSlot );
  113890. pNew->u.vtab.idxNum = pIdxInfo->idxNum;
  113891. pNew->u.vtab.needFree = pIdxInfo->needToFreeIdxStr;
  113892. pIdxInfo->needToFreeIdxStr = 0;
  113893. pNew->u.vtab.idxStr = pIdxInfo->idxStr;
  113894. pNew->u.vtab.isOrdered = (i8)(pIdxInfo->orderByConsumed ?
  113895. pIdxInfo->nOrderBy : 0);
  113896. pNew->rSetup = 0;
  113897. pNew->rRun = sqlite3LogEstFromDouble(pIdxInfo->estimatedCost);
  113898. pNew->nOut = sqlite3LogEst(pIdxInfo->estimatedRows);
  113899. whereLoopInsert(pBuilder, pNew);
  113900. if( pNew->u.vtab.needFree ){
  113901. sqlite3_free(pNew->u.vtab.idxStr);
  113902. pNew->u.vtab.needFree = 0;
  113903. }
  113904. }
  113905. }
  113906. whereLoopAddVtab_exit:
  113907. if( pIdxInfo->needToFreeIdxStr ) sqlite3_free(pIdxInfo->idxStr);
  113908. sqlite3DbFree(db, pIdxInfo);
  113909. return rc;
  113910. }
  113911. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  113912. /*
  113913. ** Add WhereLoop entries to handle OR terms. This works for either
  113914. ** btrees or virtual tables.
  113915. */
  113916. static int whereLoopAddOr(WhereLoopBuilder *pBuilder, Bitmask mExtra){
  113917. WhereInfo *pWInfo = pBuilder->pWInfo;
  113918. WhereClause *pWC;
  113919. WhereLoop *pNew;
  113920. WhereTerm *pTerm, *pWCEnd;
  113921. int rc = SQLITE_OK;
  113922. int iCur;
  113923. WhereClause tempWC;
  113924. WhereLoopBuilder sSubBuild;
  113925. WhereOrSet sSum, sCur;
  113926. struct SrcList_item *pItem;
  113927. pWC = pBuilder->pWC;
  113928. pWCEnd = pWC->a + pWC->nTerm;
  113929. pNew = pBuilder->pNew;
  113930. memset(&sSum, 0, sizeof(sSum));
  113931. pItem = pWInfo->pTabList->a + pNew->iTab;
  113932. iCur = pItem->iCursor;
  113933. for(pTerm=pWC->a; pTerm<pWCEnd && rc==SQLITE_OK; pTerm++){
  113934. if( (pTerm->eOperator & WO_OR)!=0
  113935. && (pTerm->u.pOrInfo->indexable & pNew->maskSelf)!=0
  113936. ){
  113937. WhereClause * const pOrWC = &pTerm->u.pOrInfo->wc;
  113938. WhereTerm * const pOrWCEnd = &pOrWC->a[pOrWC->nTerm];
  113939. WhereTerm *pOrTerm;
  113940. int once = 1;
  113941. int i, j;
  113942. sSubBuild = *pBuilder;
  113943. sSubBuild.pOrderBy = 0;
  113944. sSubBuild.pOrSet = &sCur;
  113945. WHERETRACE(0x200, ("Begin processing OR-clause %p\n", pTerm));
  113946. for(pOrTerm=pOrWC->a; pOrTerm<pOrWCEnd; pOrTerm++){
  113947. if( (pOrTerm->eOperator & WO_AND)!=0 ){
  113948. sSubBuild.pWC = &pOrTerm->u.pAndInfo->wc;
  113949. }else if( pOrTerm->leftCursor==iCur ){
  113950. tempWC.pWInfo = pWC->pWInfo;
  113951. tempWC.pOuter = pWC;
  113952. tempWC.op = TK_AND;
  113953. tempWC.nTerm = 1;
  113954. tempWC.a = pOrTerm;
  113955. sSubBuild.pWC = &tempWC;
  113956. }else{
  113957. continue;
  113958. }
  113959. sCur.n = 0;
  113960. #ifdef WHERETRACE_ENABLED
  113961. WHERETRACE(0x200, ("OR-term %d of %p has %d subterms:\n",
  113962. (int)(pOrTerm-pOrWC->a), pTerm, sSubBuild.pWC->nTerm));
  113963. if( sqlite3WhereTrace & 0x400 ){
  113964. for(i=0; i<sSubBuild.pWC->nTerm; i++){
  113965. whereTermPrint(&sSubBuild.pWC->a[i], i);
  113966. }
  113967. }
  113968. #endif
  113969. #ifndef SQLITE_OMIT_VIRTUALTABLE
  113970. if( IsVirtual(pItem->pTab) ){
  113971. rc = whereLoopAddVirtual(&sSubBuild, mExtra);
  113972. }else
  113973. #endif
  113974. {
  113975. rc = whereLoopAddBtree(&sSubBuild, mExtra);
  113976. }
  113977. if( rc==SQLITE_OK ){
  113978. rc = whereLoopAddOr(&sSubBuild, mExtra);
  113979. }
  113980. assert( rc==SQLITE_OK || sCur.n==0 );
  113981. if( sCur.n==0 ){
  113982. sSum.n = 0;
  113983. break;
  113984. }else if( once ){
  113985. whereOrMove(&sSum, &sCur);
  113986. once = 0;
  113987. }else{
  113988. WhereOrSet sPrev;
  113989. whereOrMove(&sPrev, &sSum);
  113990. sSum.n = 0;
  113991. for(i=0; i<sPrev.n; i++){
  113992. for(j=0; j<sCur.n; j++){
  113993. whereOrInsert(&sSum, sPrev.a[i].prereq | sCur.a[j].prereq,
  113994. sqlite3LogEstAdd(sPrev.a[i].rRun, sCur.a[j].rRun),
  113995. sqlite3LogEstAdd(sPrev.a[i].nOut, sCur.a[j].nOut));
  113996. }
  113997. }
  113998. }
  113999. }
  114000. pNew->nLTerm = 1;
  114001. pNew->aLTerm[0] = pTerm;
  114002. pNew->wsFlags = WHERE_MULTI_OR;
  114003. pNew->rSetup = 0;
  114004. pNew->iSortIdx = 0;
  114005. memset(&pNew->u, 0, sizeof(pNew->u));
  114006. for(i=0; rc==SQLITE_OK && i<sSum.n; i++){
  114007. /* TUNING: Currently sSum.a[i].rRun is set to the sum of the costs
  114008. ** of all sub-scans required by the OR-scan. However, due to rounding
  114009. ** errors, it may be that the cost of the OR-scan is equal to its
  114010. ** most expensive sub-scan. Add the smallest possible penalty
  114011. ** (equivalent to multiplying the cost by 1.07) to ensure that
  114012. ** this does not happen. Otherwise, for WHERE clauses such as the
  114013. ** following where there is an index on "y":
  114014. **
  114015. ** WHERE likelihood(x=?, 0.99) OR y=?
  114016. **
  114017. ** the planner may elect to "OR" together a full-table scan and an
  114018. ** index lookup. And other similarly odd results. */
  114019. pNew->rRun = sSum.a[i].rRun + 1;
  114020. pNew->nOut = sSum.a[i].nOut;
  114021. pNew->prereq = sSum.a[i].prereq;
  114022. rc = whereLoopInsert(pBuilder, pNew);
  114023. }
  114024. WHERETRACE(0x200, ("End processing OR-clause %p\n", pTerm));
  114025. }
  114026. }
  114027. return rc;
  114028. }
  114029. /*
  114030. ** Add all WhereLoop objects for all tables
  114031. */
  114032. static int whereLoopAddAll(WhereLoopBuilder *pBuilder){
  114033. WhereInfo *pWInfo = pBuilder->pWInfo;
  114034. Bitmask mExtra = 0;
  114035. Bitmask mPrior = 0;
  114036. int iTab;
  114037. SrcList *pTabList = pWInfo->pTabList;
  114038. struct SrcList_item *pItem;
  114039. sqlite3 *db = pWInfo->pParse->db;
  114040. int nTabList = pWInfo->nLevel;
  114041. int rc = SQLITE_OK;
  114042. u8 priorJoinType = 0;
  114043. WhereLoop *pNew;
  114044. /* Loop over the tables in the join, from left to right */
  114045. pNew = pBuilder->pNew;
  114046. whereLoopInit(pNew);
  114047. for(iTab=0, pItem=pTabList->a; iTab<nTabList; iTab++, pItem++){
  114048. pNew->iTab = iTab;
  114049. pNew->maskSelf = getMask(&pWInfo->sMaskSet, pItem->iCursor);
  114050. if( ((pItem->jointype|priorJoinType) & (JT_LEFT|JT_CROSS))!=0 ){
  114051. mExtra = mPrior;
  114052. }
  114053. priorJoinType = pItem->jointype;
  114054. if( IsVirtual(pItem->pTab) ){
  114055. rc = whereLoopAddVirtual(pBuilder, mExtra);
  114056. }else{
  114057. rc = whereLoopAddBtree(pBuilder, mExtra);
  114058. }
  114059. if( rc==SQLITE_OK ){
  114060. rc = whereLoopAddOr(pBuilder, mExtra);
  114061. }
  114062. mPrior |= pNew->maskSelf;
  114063. if( rc || db->mallocFailed ) break;
  114064. }
  114065. whereLoopClear(db, pNew);
  114066. return rc;
  114067. }
  114068. /*
  114069. ** Examine a WherePath (with the addition of the extra WhereLoop of the 5th
  114070. ** parameters) to see if it outputs rows in the requested ORDER BY
  114071. ** (or GROUP BY) without requiring a separate sort operation. Return N:
  114072. **
  114073. ** N>0: N terms of the ORDER BY clause are satisfied
  114074. ** N==0: No terms of the ORDER BY clause are satisfied
  114075. ** N<0: Unknown yet how many terms of ORDER BY might be satisfied.
  114076. **
  114077. ** Note that processing for WHERE_GROUPBY and WHERE_DISTINCTBY is not as
  114078. ** strict. With GROUP BY and DISTINCT the only requirement is that
  114079. ** equivalent rows appear immediately adjacent to one another. GROUP BY
  114080. ** and DISTINCT do not require rows to appear in any particular order as long
  114081. ** as equivalent rows are grouped together. Thus for GROUP BY and DISTINCT
  114082. ** the pOrderBy terms can be matched in any order. With ORDER BY, the
  114083. ** pOrderBy terms must be matched in strict left-to-right order.
  114084. */
  114085. static i8 wherePathSatisfiesOrderBy(
  114086. WhereInfo *pWInfo, /* The WHERE clause */
  114087. ExprList *pOrderBy, /* ORDER BY or GROUP BY or DISTINCT clause to check */
  114088. WherePath *pPath, /* The WherePath to check */
  114089. u16 wctrlFlags, /* Might contain WHERE_GROUPBY or WHERE_DISTINCTBY */
  114090. u16 nLoop, /* Number of entries in pPath->aLoop[] */
  114091. WhereLoop *pLast, /* Add this WhereLoop to the end of pPath->aLoop[] */
  114092. Bitmask *pRevMask /* OUT: Mask of WhereLoops to run in reverse order */
  114093. ){
  114094. u8 revSet; /* True if rev is known */
  114095. u8 rev; /* Composite sort order */
  114096. u8 revIdx; /* Index sort order */
  114097. u8 isOrderDistinct; /* All prior WhereLoops are order-distinct */
  114098. u8 distinctColumns; /* True if the loop has UNIQUE NOT NULL columns */
  114099. u8 isMatch; /* iColumn matches a term of the ORDER BY clause */
  114100. u16 nKeyCol; /* Number of key columns in pIndex */
  114101. u16 nColumn; /* Total number of ordered columns in the index */
  114102. u16 nOrderBy; /* Number terms in the ORDER BY clause */
  114103. int iLoop; /* Index of WhereLoop in pPath being processed */
  114104. int i, j; /* Loop counters */
  114105. int iCur; /* Cursor number for current WhereLoop */
  114106. int iColumn; /* A column number within table iCur */
  114107. WhereLoop *pLoop = 0; /* Current WhereLoop being processed. */
  114108. WhereTerm *pTerm; /* A single term of the WHERE clause */
  114109. Expr *pOBExpr; /* An expression from the ORDER BY clause */
  114110. CollSeq *pColl; /* COLLATE function from an ORDER BY clause term */
  114111. Index *pIndex; /* The index associated with pLoop */
  114112. sqlite3 *db = pWInfo->pParse->db; /* Database connection */
  114113. Bitmask obSat = 0; /* Mask of ORDER BY terms satisfied so far */
  114114. Bitmask obDone; /* Mask of all ORDER BY terms */
  114115. Bitmask orderDistinctMask; /* Mask of all well-ordered loops */
  114116. Bitmask ready; /* Mask of inner loops */
  114117. /*
  114118. ** We say the WhereLoop is "one-row" if it generates no more than one
  114119. ** row of output. A WhereLoop is one-row if all of the following are true:
  114120. ** (a) All index columns match with WHERE_COLUMN_EQ.
  114121. ** (b) The index is unique
  114122. ** Any WhereLoop with an WHERE_COLUMN_EQ constraint on the rowid is one-row.
  114123. ** Every one-row WhereLoop will have the WHERE_ONEROW bit set in wsFlags.
  114124. **
  114125. ** We say the WhereLoop is "order-distinct" if the set of columns from
  114126. ** that WhereLoop that are in the ORDER BY clause are different for every
  114127. ** row of the WhereLoop. Every one-row WhereLoop is automatically
  114128. ** order-distinct. A WhereLoop that has no columns in the ORDER BY clause
  114129. ** is not order-distinct. To be order-distinct is not quite the same as being
  114130. ** UNIQUE since a UNIQUE column or index can have multiple rows that
  114131. ** are NULL and NULL values are equivalent for the purpose of order-distinct.
  114132. ** To be order-distinct, the columns must be UNIQUE and NOT NULL.
  114133. **
  114134. ** The rowid for a table is always UNIQUE and NOT NULL so whenever the
  114135. ** rowid appears in the ORDER BY clause, the corresponding WhereLoop is
  114136. ** automatically order-distinct.
  114137. */
  114138. assert( pOrderBy!=0 );
  114139. if( nLoop && OptimizationDisabled(db, SQLITE_OrderByIdxJoin) ) return 0;
  114140. nOrderBy = pOrderBy->nExpr;
  114141. testcase( nOrderBy==BMS-1 );
  114142. if( nOrderBy>BMS-1 ) return 0; /* Cannot optimize overly large ORDER BYs */
  114143. isOrderDistinct = 1;
  114144. obDone = MASKBIT(nOrderBy)-1;
  114145. orderDistinctMask = 0;
  114146. ready = 0;
  114147. for(iLoop=0; isOrderDistinct && obSat<obDone && iLoop<=nLoop; iLoop++){
  114148. if( iLoop>0 ) ready |= pLoop->maskSelf;
  114149. pLoop = iLoop<nLoop ? pPath->aLoop[iLoop] : pLast;
  114150. if( pLoop->wsFlags & WHERE_VIRTUALTABLE ){
  114151. if( pLoop->u.vtab.isOrdered ) obSat = obDone;
  114152. break;
  114153. }
  114154. iCur = pWInfo->pTabList->a[pLoop->iTab].iCursor;
  114155. /* Mark off any ORDER BY term X that is a column in the table of
  114156. ** the current loop for which there is term in the WHERE
  114157. ** clause of the form X IS NULL or X=? that reference only outer
  114158. ** loops.
  114159. */
  114160. for(i=0; i<nOrderBy; i++){
  114161. if( MASKBIT(i) & obSat ) continue;
  114162. pOBExpr = sqlite3ExprSkipCollate(pOrderBy->a[i].pExpr);
  114163. if( pOBExpr->op!=TK_COLUMN ) continue;
  114164. if( pOBExpr->iTable!=iCur ) continue;
  114165. pTerm = findTerm(&pWInfo->sWC, iCur, pOBExpr->iColumn,
  114166. ~ready, WO_EQ|WO_ISNULL, 0);
  114167. if( pTerm==0 ) continue;
  114168. if( (pTerm->eOperator&WO_EQ)!=0 && pOBExpr->iColumn>=0 ){
  114169. const char *z1, *z2;
  114170. pColl = sqlite3ExprCollSeq(pWInfo->pParse, pOrderBy->a[i].pExpr);
  114171. if( !pColl ) pColl = db->pDfltColl;
  114172. z1 = pColl->zName;
  114173. pColl = sqlite3ExprCollSeq(pWInfo->pParse, pTerm->pExpr);
  114174. if( !pColl ) pColl = db->pDfltColl;
  114175. z2 = pColl->zName;
  114176. if( sqlite3StrICmp(z1, z2)!=0 ) continue;
  114177. }
  114178. obSat |= MASKBIT(i);
  114179. }
  114180. if( (pLoop->wsFlags & WHERE_ONEROW)==0 ){
  114181. if( pLoop->wsFlags & WHERE_IPK ){
  114182. pIndex = 0;
  114183. nKeyCol = 0;
  114184. nColumn = 1;
  114185. }else if( (pIndex = pLoop->u.btree.pIndex)==0 || pIndex->bUnordered ){
  114186. return 0;
  114187. }else{
  114188. nKeyCol = pIndex->nKeyCol;
  114189. nColumn = pIndex->nColumn;
  114190. assert( nColumn==nKeyCol+1 || !HasRowid(pIndex->pTable) );
  114191. assert( pIndex->aiColumn[nColumn-1]==(-1) || !HasRowid(pIndex->pTable));
  114192. isOrderDistinct = IsUniqueIndex(pIndex);
  114193. }
  114194. /* Loop through all columns of the index and deal with the ones
  114195. ** that are not constrained by == or IN.
  114196. */
  114197. rev = revSet = 0;
  114198. distinctColumns = 0;
  114199. for(j=0; j<nColumn; j++){
  114200. u8 bOnce; /* True to run the ORDER BY search loop */
  114201. /* Skip over == and IS NULL terms */
  114202. if( j<pLoop->u.btree.nEq
  114203. && pLoop->nSkip==0
  114204. && ((i = pLoop->aLTerm[j]->eOperator) & (WO_EQ|WO_ISNULL))!=0
  114205. ){
  114206. if( i & WO_ISNULL ){
  114207. testcase( isOrderDistinct );
  114208. isOrderDistinct = 0;
  114209. }
  114210. continue;
  114211. }
  114212. /* Get the column number in the table (iColumn) and sort order
  114213. ** (revIdx) for the j-th column of the index.
  114214. */
  114215. if( pIndex ){
  114216. iColumn = pIndex->aiColumn[j];
  114217. revIdx = pIndex->aSortOrder[j];
  114218. if( iColumn==pIndex->pTable->iPKey ) iColumn = -1;
  114219. }else{
  114220. iColumn = -1;
  114221. revIdx = 0;
  114222. }
  114223. /* An unconstrained column that might be NULL means that this
  114224. ** WhereLoop is not well-ordered
  114225. */
  114226. if( isOrderDistinct
  114227. && iColumn>=0
  114228. && j>=pLoop->u.btree.nEq
  114229. && pIndex->pTable->aCol[iColumn].notNull==0
  114230. ){
  114231. isOrderDistinct = 0;
  114232. }
  114233. /* Find the ORDER BY term that corresponds to the j-th column
  114234. ** of the index and mark that ORDER BY term off
  114235. */
  114236. bOnce = 1;
  114237. isMatch = 0;
  114238. for(i=0; bOnce && i<nOrderBy; i++){
  114239. if( MASKBIT(i) & obSat ) continue;
  114240. pOBExpr = sqlite3ExprSkipCollate(pOrderBy->a[i].pExpr);
  114241. testcase( wctrlFlags & WHERE_GROUPBY );
  114242. testcase( wctrlFlags & WHERE_DISTINCTBY );
  114243. if( (wctrlFlags & (WHERE_GROUPBY|WHERE_DISTINCTBY))==0 ) bOnce = 0;
  114244. if( pOBExpr->op!=TK_COLUMN ) continue;
  114245. if( pOBExpr->iTable!=iCur ) continue;
  114246. if( pOBExpr->iColumn!=iColumn ) continue;
  114247. if( iColumn>=0 ){
  114248. pColl = sqlite3ExprCollSeq(pWInfo->pParse, pOrderBy->a[i].pExpr);
  114249. if( !pColl ) pColl = db->pDfltColl;
  114250. if( sqlite3StrICmp(pColl->zName, pIndex->azColl[j])!=0 ) continue;
  114251. }
  114252. isMatch = 1;
  114253. break;
  114254. }
  114255. if( isMatch && (wctrlFlags & WHERE_GROUPBY)==0 ){
  114256. /* Make sure the sort order is compatible in an ORDER BY clause.
  114257. ** Sort order is irrelevant for a GROUP BY clause. */
  114258. if( revSet ){
  114259. if( (rev ^ revIdx)!=pOrderBy->a[i].sortOrder ) isMatch = 0;
  114260. }else{
  114261. rev = revIdx ^ pOrderBy->a[i].sortOrder;
  114262. if( rev ) *pRevMask |= MASKBIT(iLoop);
  114263. revSet = 1;
  114264. }
  114265. }
  114266. if( isMatch ){
  114267. if( iColumn<0 ){
  114268. testcase( distinctColumns==0 );
  114269. distinctColumns = 1;
  114270. }
  114271. obSat |= MASKBIT(i);
  114272. }else{
  114273. /* No match found */
  114274. if( j==0 || j<nKeyCol ){
  114275. testcase( isOrderDistinct!=0 );
  114276. isOrderDistinct = 0;
  114277. }
  114278. break;
  114279. }
  114280. } /* end Loop over all index columns */
  114281. if( distinctColumns ){
  114282. testcase( isOrderDistinct==0 );
  114283. isOrderDistinct = 1;
  114284. }
  114285. } /* end-if not one-row */
  114286. /* Mark off any other ORDER BY terms that reference pLoop */
  114287. if( isOrderDistinct ){
  114288. orderDistinctMask |= pLoop->maskSelf;
  114289. for(i=0; i<nOrderBy; i++){
  114290. Expr *p;
  114291. Bitmask mTerm;
  114292. if( MASKBIT(i) & obSat ) continue;
  114293. p = pOrderBy->a[i].pExpr;
  114294. mTerm = exprTableUsage(&pWInfo->sMaskSet,p);
  114295. if( mTerm==0 && !sqlite3ExprIsConstant(p) ) continue;
  114296. if( (mTerm&~orderDistinctMask)==0 ){
  114297. obSat |= MASKBIT(i);
  114298. }
  114299. }
  114300. }
  114301. } /* End the loop over all WhereLoops from outer-most down to inner-most */
  114302. if( obSat==obDone ) return (i8)nOrderBy;
  114303. if( !isOrderDistinct ){
  114304. for(i=nOrderBy-1; i>0; i--){
  114305. Bitmask m = MASKBIT(i) - 1;
  114306. if( (obSat&m)==m ) return i;
  114307. }
  114308. return 0;
  114309. }
  114310. return -1;
  114311. }
  114312. /*
  114313. ** If the WHERE_GROUPBY flag is set in the mask passed to sqlite3WhereBegin(),
  114314. ** the planner assumes that the specified pOrderBy list is actually a GROUP
  114315. ** BY clause - and so any order that groups rows as required satisfies the
  114316. ** request.
  114317. **
  114318. ** Normally, in this case it is not possible for the caller to determine
  114319. ** whether or not the rows are really being delivered in sorted order, or
  114320. ** just in some other order that provides the required grouping. However,
  114321. ** if the WHERE_SORTBYGROUP flag is also passed to sqlite3WhereBegin(), then
  114322. ** this function may be called on the returned WhereInfo object. It returns
  114323. ** true if the rows really will be sorted in the specified order, or false
  114324. ** otherwise.
  114325. **
  114326. ** For example, assuming:
  114327. **
  114328. ** CREATE INDEX i1 ON t1(x, Y);
  114329. **
  114330. ** then
  114331. **
  114332. ** SELECT * FROM t1 GROUP BY x,y ORDER BY x,y; -- IsSorted()==1
  114333. ** SELECT * FROM t1 GROUP BY y,x ORDER BY y,x; -- IsSorted()==0
  114334. */
  114335. SQLITE_PRIVATE int sqlite3WhereIsSorted(WhereInfo *pWInfo){
  114336. assert( pWInfo->wctrlFlags & WHERE_GROUPBY );
  114337. assert( pWInfo->wctrlFlags & WHERE_SORTBYGROUP );
  114338. return pWInfo->sorted;
  114339. }
  114340. #ifdef WHERETRACE_ENABLED
  114341. /* For debugging use only: */
  114342. static const char *wherePathName(WherePath *pPath, int nLoop, WhereLoop *pLast){
  114343. static char zName[65];
  114344. int i;
  114345. for(i=0; i<nLoop; i++){ zName[i] = pPath->aLoop[i]->cId; }
  114346. if( pLast ) zName[i++] = pLast->cId;
  114347. zName[i] = 0;
  114348. return zName;
  114349. }
  114350. #endif
  114351. /*
  114352. ** Return the cost of sorting nRow rows, assuming that the keys have
  114353. ** nOrderby columns and that the first nSorted columns are already in
  114354. ** order.
  114355. */
  114356. static LogEst whereSortingCost(
  114357. WhereInfo *pWInfo,
  114358. LogEst nRow,
  114359. int nOrderBy,
  114360. int nSorted
  114361. ){
  114362. /* TUNING: Estimated cost of a full external sort, where N is
  114363. ** the number of rows to sort is:
  114364. **
  114365. ** cost = (3.0 * N * log(N)).
  114366. **
  114367. ** Or, if the order-by clause has X terms but only the last Y
  114368. ** terms are out of order, then block-sorting will reduce the
  114369. ** sorting cost to:
  114370. **
  114371. ** cost = (3.0 * N * log(N)) * (Y/X)
  114372. **
  114373. ** The (Y/X) term is implemented using stack variable rScale
  114374. ** below. */
  114375. LogEst rScale, rSortCost;
  114376. assert( nOrderBy>0 && 66==sqlite3LogEst(100) );
  114377. rScale = sqlite3LogEst((nOrderBy-nSorted)*100/nOrderBy) - 66;
  114378. rSortCost = nRow + estLog(nRow) + rScale + 16;
  114379. /* TUNING: The cost of implementing DISTINCT using a B-TREE is
  114380. ** similar but with a larger constant of proportionality.
  114381. ** Multiply by an additional factor of 3.0. */
  114382. if( pWInfo->wctrlFlags & WHERE_WANT_DISTINCT ){
  114383. rSortCost += 16;
  114384. }
  114385. return rSortCost;
  114386. }
  114387. /*
  114388. ** Given the list of WhereLoop objects at pWInfo->pLoops, this routine
  114389. ** attempts to find the lowest cost path that visits each WhereLoop
  114390. ** once. This path is then loaded into the pWInfo->a[].pWLoop fields.
  114391. **
  114392. ** Assume that the total number of output rows that will need to be sorted
  114393. ** will be nRowEst (in the 10*log2 representation). Or, ignore sorting
  114394. ** costs if nRowEst==0.
  114395. **
  114396. ** Return SQLITE_OK on success or SQLITE_NOMEM of a memory allocation
  114397. ** error occurs.
  114398. */
  114399. static int wherePathSolver(WhereInfo *pWInfo, LogEst nRowEst){
  114400. int mxChoice; /* Maximum number of simultaneous paths tracked */
  114401. int nLoop; /* Number of terms in the join */
  114402. Parse *pParse; /* Parsing context */
  114403. sqlite3 *db; /* The database connection */
  114404. int iLoop; /* Loop counter over the terms of the join */
  114405. int ii, jj; /* Loop counters */
  114406. int mxI = 0; /* Index of next entry to replace */
  114407. int nOrderBy; /* Number of ORDER BY clause terms */
  114408. LogEst mxCost = 0; /* Maximum cost of a set of paths */
  114409. LogEst mxUnsorted = 0; /* Maximum unsorted cost of a set of path */
  114410. int nTo, nFrom; /* Number of valid entries in aTo[] and aFrom[] */
  114411. WherePath *aFrom; /* All nFrom paths at the previous level */
  114412. WherePath *aTo; /* The nTo best paths at the current level */
  114413. WherePath *pFrom; /* An element of aFrom[] that we are working on */
  114414. WherePath *pTo; /* An element of aTo[] that we are working on */
  114415. WhereLoop *pWLoop; /* One of the WhereLoop objects */
  114416. WhereLoop **pX; /* Used to divy up the pSpace memory */
  114417. LogEst *aSortCost = 0; /* Sorting and partial sorting costs */
  114418. char *pSpace; /* Temporary memory used by this routine */
  114419. int nSpace; /* Bytes of space allocated at pSpace */
  114420. pParse = pWInfo->pParse;
  114421. db = pParse->db;
  114422. nLoop = pWInfo->nLevel;
  114423. /* TUNING: For simple queries, only the best path is tracked.
  114424. ** For 2-way joins, the 5 best paths are followed.
  114425. ** For joins of 3 or more tables, track the 10 best paths */
  114426. mxChoice = (nLoop<=1) ? 1 : (nLoop==2 ? 5 : 10);
  114427. assert( nLoop<=pWInfo->pTabList->nSrc );
  114428. WHERETRACE(0x002, ("---- begin solver. (nRowEst=%d)\n", nRowEst));
  114429. /* If nRowEst is zero and there is an ORDER BY clause, ignore it. In this
  114430. ** case the purpose of this call is to estimate the number of rows returned
  114431. ** by the overall query. Once this estimate has been obtained, the caller
  114432. ** will invoke this function a second time, passing the estimate as the
  114433. ** nRowEst parameter. */
  114434. if( pWInfo->pOrderBy==0 || nRowEst==0 ){
  114435. nOrderBy = 0;
  114436. }else{
  114437. nOrderBy = pWInfo->pOrderBy->nExpr;
  114438. }
  114439. /* Allocate and initialize space for aTo, aFrom and aSortCost[] */
  114440. nSpace = (sizeof(WherePath)+sizeof(WhereLoop*)*nLoop)*mxChoice*2;
  114441. nSpace += sizeof(LogEst) * nOrderBy;
  114442. pSpace = sqlite3DbMallocRaw(db, nSpace);
  114443. if( pSpace==0 ) return SQLITE_NOMEM;
  114444. aTo = (WherePath*)pSpace;
  114445. aFrom = aTo+mxChoice;
  114446. memset(aFrom, 0, sizeof(aFrom[0]));
  114447. pX = (WhereLoop**)(aFrom+mxChoice);
  114448. for(ii=mxChoice*2, pFrom=aTo; ii>0; ii--, pFrom++, pX += nLoop){
  114449. pFrom->aLoop = pX;
  114450. }
  114451. if( nOrderBy ){
  114452. /* If there is an ORDER BY clause and it is not being ignored, set up
  114453. ** space for the aSortCost[] array. Each element of the aSortCost array
  114454. ** is either zero - meaning it has not yet been initialized - or the
  114455. ** cost of sorting nRowEst rows of data where the first X terms of
  114456. ** the ORDER BY clause are already in order, where X is the array
  114457. ** index. */
  114458. aSortCost = (LogEst*)pX;
  114459. memset(aSortCost, 0, sizeof(LogEst) * nOrderBy);
  114460. }
  114461. assert( aSortCost==0 || &pSpace[nSpace]==(char*)&aSortCost[nOrderBy] );
  114462. assert( aSortCost!=0 || &pSpace[nSpace]==(char*)pX );
  114463. /* Seed the search with a single WherePath containing zero WhereLoops.
  114464. **
  114465. ** TUNING: Do not let the number of iterations go above 28. If the cost
  114466. ** of computing an automatic index is not paid back within the first 28
  114467. ** rows, then do not use the automatic index. */
  114468. aFrom[0].nRow = MIN(pParse->nQueryLoop, 48); assert( 48==sqlite3LogEst(28) );
  114469. nFrom = 1;
  114470. assert( aFrom[0].isOrdered==0 );
  114471. if( nOrderBy ){
  114472. /* If nLoop is zero, then there are no FROM terms in the query. Since
  114473. ** in this case the query may return a maximum of one row, the results
  114474. ** are already in the requested order. Set isOrdered to nOrderBy to
  114475. ** indicate this. Or, if nLoop is greater than zero, set isOrdered to
  114476. ** -1, indicating that the result set may or may not be ordered,
  114477. ** depending on the loops added to the current plan. */
  114478. aFrom[0].isOrdered = nLoop>0 ? -1 : nOrderBy;
  114479. }
  114480. /* Compute successively longer WherePaths using the previous generation
  114481. ** of WherePaths as the basis for the next. Keep track of the mxChoice
  114482. ** best paths at each generation */
  114483. for(iLoop=0; iLoop<nLoop; iLoop++){
  114484. nTo = 0;
  114485. for(ii=0, pFrom=aFrom; ii<nFrom; ii++, pFrom++){
  114486. for(pWLoop=pWInfo->pLoops; pWLoop; pWLoop=pWLoop->pNextLoop){
  114487. LogEst nOut; /* Rows visited by (pFrom+pWLoop) */
  114488. LogEst rCost; /* Cost of path (pFrom+pWLoop) */
  114489. LogEst rUnsorted; /* Unsorted cost of (pFrom+pWLoop) */
  114490. i8 isOrdered = pFrom->isOrdered; /* isOrdered for (pFrom+pWLoop) */
  114491. Bitmask maskNew; /* Mask of src visited by (..) */
  114492. Bitmask revMask = 0; /* Mask of rev-order loops for (..) */
  114493. if( (pWLoop->prereq & ~pFrom->maskLoop)!=0 ) continue;
  114494. if( (pWLoop->maskSelf & pFrom->maskLoop)!=0 ) continue;
  114495. /* At this point, pWLoop is a candidate to be the next loop.
  114496. ** Compute its cost */
  114497. rUnsorted = sqlite3LogEstAdd(pWLoop->rSetup,pWLoop->rRun + pFrom->nRow);
  114498. rUnsorted = sqlite3LogEstAdd(rUnsorted, pFrom->rUnsorted);
  114499. nOut = pFrom->nRow + pWLoop->nOut;
  114500. maskNew = pFrom->maskLoop | pWLoop->maskSelf;
  114501. if( isOrdered<0 ){
  114502. isOrdered = wherePathSatisfiesOrderBy(pWInfo,
  114503. pWInfo->pOrderBy, pFrom, pWInfo->wctrlFlags,
  114504. iLoop, pWLoop, &revMask);
  114505. }else{
  114506. revMask = pFrom->revLoop;
  114507. }
  114508. if( isOrdered>=0 && isOrdered<nOrderBy ){
  114509. if( aSortCost[isOrdered]==0 ){
  114510. aSortCost[isOrdered] = whereSortingCost(
  114511. pWInfo, nRowEst, nOrderBy, isOrdered
  114512. );
  114513. }
  114514. rCost = sqlite3LogEstAdd(rUnsorted, aSortCost[isOrdered]);
  114515. WHERETRACE(0x002,
  114516. ("---- sort cost=%-3d (%d/%d) increases cost %3d to %-3d\n",
  114517. aSortCost[isOrdered], (nOrderBy-isOrdered), nOrderBy,
  114518. rUnsorted, rCost));
  114519. }else{
  114520. rCost = rUnsorted;
  114521. }
  114522. /* Check to see if pWLoop should be added to the set of
  114523. ** mxChoice best-so-far paths.
  114524. **
  114525. ** First look for an existing path among best-so-far paths
  114526. ** that covers the same set of loops and has the same isOrdered
  114527. ** setting as the current path candidate.
  114528. **
  114529. ** The term "((pTo->isOrdered^isOrdered)&0x80)==0" is equivalent
  114530. ** to (pTo->isOrdered==(-1))==(isOrdered==(-1))" for the range
  114531. ** of legal values for isOrdered, -1..64.
  114532. */
  114533. for(jj=0, pTo=aTo; jj<nTo; jj++, pTo++){
  114534. if( pTo->maskLoop==maskNew
  114535. && ((pTo->isOrdered^isOrdered)&0x80)==0
  114536. ){
  114537. testcase( jj==nTo-1 );
  114538. break;
  114539. }
  114540. }
  114541. if( jj>=nTo ){
  114542. /* None of the existing best-so-far paths match the candidate. */
  114543. if( nTo>=mxChoice
  114544. && (rCost>mxCost || (rCost==mxCost && rUnsorted>=mxUnsorted))
  114545. ){
  114546. /* The current candidate is no better than any of the mxChoice
  114547. ** paths currently in the best-so-far buffer. So discard
  114548. ** this candidate as not viable. */
  114549. #ifdef WHERETRACE_ENABLED /* 0x4 */
  114550. if( sqlite3WhereTrace&0x4 ){
  114551. sqlite3DebugPrintf("Skip %s cost=%-3d,%3d order=%c\n",
  114552. wherePathName(pFrom, iLoop, pWLoop), rCost, nOut,
  114553. isOrdered>=0 ? isOrdered+'0' : '?');
  114554. }
  114555. #endif
  114556. continue;
  114557. }
  114558. /* If we reach this points it means that the new candidate path
  114559. ** needs to be added to the set of best-so-far paths. */
  114560. if( nTo<mxChoice ){
  114561. /* Increase the size of the aTo set by one */
  114562. jj = nTo++;
  114563. }else{
  114564. /* New path replaces the prior worst to keep count below mxChoice */
  114565. jj = mxI;
  114566. }
  114567. pTo = &aTo[jj];
  114568. #ifdef WHERETRACE_ENABLED /* 0x4 */
  114569. if( sqlite3WhereTrace&0x4 ){
  114570. sqlite3DebugPrintf("New %s cost=%-3d,%3d order=%c\n",
  114571. wherePathName(pFrom, iLoop, pWLoop), rCost, nOut,
  114572. isOrdered>=0 ? isOrdered+'0' : '?');
  114573. }
  114574. #endif
  114575. }else{
  114576. /* Control reaches here if best-so-far path pTo=aTo[jj] covers the
  114577. ** same set of loops and has the sam isOrdered setting as the
  114578. ** candidate path. Check to see if the candidate should replace
  114579. ** pTo or if the candidate should be skipped */
  114580. if( pTo->rCost<rCost || (pTo->rCost==rCost && pTo->nRow<=nOut) ){
  114581. #ifdef WHERETRACE_ENABLED /* 0x4 */
  114582. if( sqlite3WhereTrace&0x4 ){
  114583. sqlite3DebugPrintf(
  114584. "Skip %s cost=%-3d,%3d order=%c",
  114585. wherePathName(pFrom, iLoop, pWLoop), rCost, nOut,
  114586. isOrdered>=0 ? isOrdered+'0' : '?');
  114587. sqlite3DebugPrintf(" vs %s cost=%-3d,%d order=%c\n",
  114588. wherePathName(pTo, iLoop+1, 0), pTo->rCost, pTo->nRow,
  114589. pTo->isOrdered>=0 ? pTo->isOrdered+'0' : '?');
  114590. }
  114591. #endif
  114592. /* Discard the candidate path from further consideration */
  114593. testcase( pTo->rCost==rCost );
  114594. continue;
  114595. }
  114596. testcase( pTo->rCost==rCost+1 );
  114597. /* Control reaches here if the candidate path is better than the
  114598. ** pTo path. Replace pTo with the candidate. */
  114599. #ifdef WHERETRACE_ENABLED /* 0x4 */
  114600. if( sqlite3WhereTrace&0x4 ){
  114601. sqlite3DebugPrintf(
  114602. "Update %s cost=%-3d,%3d order=%c",
  114603. wherePathName(pFrom, iLoop, pWLoop), rCost, nOut,
  114604. isOrdered>=0 ? isOrdered+'0' : '?');
  114605. sqlite3DebugPrintf(" was %s cost=%-3d,%3d order=%c\n",
  114606. wherePathName(pTo, iLoop+1, 0), pTo->rCost, pTo->nRow,
  114607. pTo->isOrdered>=0 ? pTo->isOrdered+'0' : '?');
  114608. }
  114609. #endif
  114610. }
  114611. /* pWLoop is a winner. Add it to the set of best so far */
  114612. pTo->maskLoop = pFrom->maskLoop | pWLoop->maskSelf;
  114613. pTo->revLoop = revMask;
  114614. pTo->nRow = nOut;
  114615. pTo->rCost = rCost;
  114616. pTo->rUnsorted = rUnsorted;
  114617. pTo->isOrdered = isOrdered;
  114618. memcpy(pTo->aLoop, pFrom->aLoop, sizeof(WhereLoop*)*iLoop);
  114619. pTo->aLoop[iLoop] = pWLoop;
  114620. if( nTo>=mxChoice ){
  114621. mxI = 0;
  114622. mxCost = aTo[0].rCost;
  114623. mxUnsorted = aTo[0].nRow;
  114624. for(jj=1, pTo=&aTo[1]; jj<mxChoice; jj++, pTo++){
  114625. if( pTo->rCost>mxCost
  114626. || (pTo->rCost==mxCost && pTo->rUnsorted>mxUnsorted)
  114627. ){
  114628. mxCost = pTo->rCost;
  114629. mxUnsorted = pTo->rUnsorted;
  114630. mxI = jj;
  114631. }
  114632. }
  114633. }
  114634. }
  114635. }
  114636. #ifdef WHERETRACE_ENABLED /* >=2 */
  114637. if( sqlite3WhereTrace & 0x02 ){
  114638. sqlite3DebugPrintf("---- after round %d ----\n", iLoop);
  114639. for(ii=0, pTo=aTo; ii<nTo; ii++, pTo++){
  114640. sqlite3DebugPrintf(" %s cost=%-3d nrow=%-3d order=%c",
  114641. wherePathName(pTo, iLoop+1, 0), pTo->rCost, pTo->nRow,
  114642. pTo->isOrdered>=0 ? (pTo->isOrdered+'0') : '?');
  114643. if( pTo->isOrdered>0 ){
  114644. sqlite3DebugPrintf(" rev=0x%llx\n", pTo->revLoop);
  114645. }else{
  114646. sqlite3DebugPrintf("\n");
  114647. }
  114648. }
  114649. }
  114650. #endif
  114651. /* Swap the roles of aFrom and aTo for the next generation */
  114652. pFrom = aTo;
  114653. aTo = aFrom;
  114654. aFrom = pFrom;
  114655. nFrom = nTo;
  114656. }
  114657. if( nFrom==0 ){
  114658. sqlite3ErrorMsg(pParse, "no query solution");
  114659. sqlite3DbFree(db, pSpace);
  114660. return SQLITE_ERROR;
  114661. }
  114662. /* Find the lowest cost path. pFrom will be left pointing to that path */
  114663. pFrom = aFrom;
  114664. for(ii=1; ii<nFrom; ii++){
  114665. if( pFrom->rCost>aFrom[ii].rCost ) pFrom = &aFrom[ii];
  114666. }
  114667. assert( pWInfo->nLevel==nLoop );
  114668. /* Load the lowest cost path into pWInfo */
  114669. for(iLoop=0; iLoop<nLoop; iLoop++){
  114670. WhereLevel *pLevel = pWInfo->a + iLoop;
  114671. pLevel->pWLoop = pWLoop = pFrom->aLoop[iLoop];
  114672. pLevel->iFrom = pWLoop->iTab;
  114673. pLevel->iTabCur = pWInfo->pTabList->a[pLevel->iFrom].iCursor;
  114674. }
  114675. if( (pWInfo->wctrlFlags & WHERE_WANT_DISTINCT)!=0
  114676. && (pWInfo->wctrlFlags & WHERE_DISTINCTBY)==0
  114677. && pWInfo->eDistinct==WHERE_DISTINCT_NOOP
  114678. && nRowEst
  114679. ){
  114680. Bitmask notUsed;
  114681. int rc = wherePathSatisfiesOrderBy(pWInfo, pWInfo->pResultSet, pFrom,
  114682. WHERE_DISTINCTBY, nLoop-1, pFrom->aLoop[nLoop-1], &notUsed);
  114683. if( rc==pWInfo->pResultSet->nExpr ){
  114684. pWInfo->eDistinct = WHERE_DISTINCT_ORDERED;
  114685. }
  114686. }
  114687. if( pWInfo->pOrderBy ){
  114688. if( pWInfo->wctrlFlags & WHERE_DISTINCTBY ){
  114689. if( pFrom->isOrdered==pWInfo->pOrderBy->nExpr ){
  114690. pWInfo->eDistinct = WHERE_DISTINCT_ORDERED;
  114691. }
  114692. }else{
  114693. pWInfo->nOBSat = pFrom->isOrdered;
  114694. if( pWInfo->nOBSat<0 ) pWInfo->nOBSat = 0;
  114695. pWInfo->revMask = pFrom->revLoop;
  114696. }
  114697. if( (pWInfo->wctrlFlags & WHERE_SORTBYGROUP)
  114698. && pWInfo->nOBSat==pWInfo->pOrderBy->nExpr && nLoop>0
  114699. ){
  114700. Bitmask revMask = 0;
  114701. int nOrder = wherePathSatisfiesOrderBy(pWInfo, pWInfo->pOrderBy,
  114702. pFrom, 0, nLoop-1, pFrom->aLoop[nLoop-1], &revMask
  114703. );
  114704. assert( pWInfo->sorted==0 );
  114705. if( nOrder==pWInfo->pOrderBy->nExpr ){
  114706. pWInfo->sorted = 1;
  114707. pWInfo->revMask = revMask;
  114708. }
  114709. }
  114710. }
  114711. pWInfo->nRowOut = pFrom->nRow;
  114712. /* Free temporary memory and return success */
  114713. sqlite3DbFree(db, pSpace);
  114714. return SQLITE_OK;
  114715. }
  114716. /*
  114717. ** Most queries use only a single table (they are not joins) and have
  114718. ** simple == constraints against indexed fields. This routine attempts
  114719. ** to plan those simple cases using much less ceremony than the
  114720. ** general-purpose query planner, and thereby yield faster sqlite3_prepare()
  114721. ** times for the common case.
  114722. **
  114723. ** Return non-zero on success, if this query can be handled by this
  114724. ** no-frills query planner. Return zero if this query needs the
  114725. ** general-purpose query planner.
  114726. */
  114727. static int whereShortCut(WhereLoopBuilder *pBuilder){
  114728. WhereInfo *pWInfo;
  114729. struct SrcList_item *pItem;
  114730. WhereClause *pWC;
  114731. WhereTerm *pTerm;
  114732. WhereLoop *pLoop;
  114733. int iCur;
  114734. int j;
  114735. Table *pTab;
  114736. Index *pIdx;
  114737. pWInfo = pBuilder->pWInfo;
  114738. if( pWInfo->wctrlFlags & WHERE_FORCE_TABLE ) return 0;
  114739. assert( pWInfo->pTabList->nSrc>=1 );
  114740. pItem = pWInfo->pTabList->a;
  114741. pTab = pItem->pTab;
  114742. if( IsVirtual(pTab) ) return 0;
  114743. if( pItem->zIndex ) return 0;
  114744. iCur = pItem->iCursor;
  114745. pWC = &pWInfo->sWC;
  114746. pLoop = pBuilder->pNew;
  114747. pLoop->wsFlags = 0;
  114748. pLoop->nSkip = 0;
  114749. pTerm = findTerm(pWC, iCur, -1, 0, WO_EQ, 0);
  114750. if( pTerm ){
  114751. pLoop->wsFlags = WHERE_COLUMN_EQ|WHERE_IPK|WHERE_ONEROW;
  114752. pLoop->aLTerm[0] = pTerm;
  114753. pLoop->nLTerm = 1;
  114754. pLoop->u.btree.nEq = 1;
  114755. /* TUNING: Cost of a rowid lookup is 10 */
  114756. pLoop->rRun = 33; /* 33==sqlite3LogEst(10) */
  114757. }else{
  114758. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  114759. assert( pLoop->aLTermSpace==pLoop->aLTerm );
  114760. if( !IsUniqueIndex(pIdx)
  114761. || pIdx->pPartIdxWhere!=0
  114762. || pIdx->nKeyCol>ArraySize(pLoop->aLTermSpace)
  114763. ) continue;
  114764. for(j=0; j<pIdx->nKeyCol; j++){
  114765. pTerm = findTerm(pWC, iCur, pIdx->aiColumn[j], 0, WO_EQ, pIdx);
  114766. if( pTerm==0 ) break;
  114767. pLoop->aLTerm[j] = pTerm;
  114768. }
  114769. if( j!=pIdx->nKeyCol ) continue;
  114770. pLoop->wsFlags = WHERE_COLUMN_EQ|WHERE_ONEROW|WHERE_INDEXED;
  114771. if( pIdx->isCovering || (pItem->colUsed & ~columnsInIndex(pIdx))==0 ){
  114772. pLoop->wsFlags |= WHERE_IDX_ONLY;
  114773. }
  114774. pLoop->nLTerm = j;
  114775. pLoop->u.btree.nEq = j;
  114776. pLoop->u.btree.pIndex = pIdx;
  114777. /* TUNING: Cost of a unique index lookup is 15 */
  114778. pLoop->rRun = 39; /* 39==sqlite3LogEst(15) */
  114779. break;
  114780. }
  114781. }
  114782. if( pLoop->wsFlags ){
  114783. pLoop->nOut = (LogEst)1;
  114784. pWInfo->a[0].pWLoop = pLoop;
  114785. pLoop->maskSelf = getMask(&pWInfo->sMaskSet, iCur);
  114786. pWInfo->a[0].iTabCur = iCur;
  114787. pWInfo->nRowOut = 1;
  114788. if( pWInfo->pOrderBy ) pWInfo->nOBSat = pWInfo->pOrderBy->nExpr;
  114789. if( pWInfo->wctrlFlags & WHERE_WANT_DISTINCT ){
  114790. pWInfo->eDistinct = WHERE_DISTINCT_UNIQUE;
  114791. }
  114792. #ifdef SQLITE_DEBUG
  114793. pLoop->cId = '0';
  114794. #endif
  114795. return 1;
  114796. }
  114797. return 0;
  114798. }
  114799. /*
  114800. ** Generate the beginning of the loop used for WHERE clause processing.
  114801. ** The return value is a pointer to an opaque structure that contains
  114802. ** information needed to terminate the loop. Later, the calling routine
  114803. ** should invoke sqlite3WhereEnd() with the return value of this function
  114804. ** in order to complete the WHERE clause processing.
  114805. **
  114806. ** If an error occurs, this routine returns NULL.
  114807. **
  114808. ** The basic idea is to do a nested loop, one loop for each table in
  114809. ** the FROM clause of a select. (INSERT and UPDATE statements are the
  114810. ** same as a SELECT with only a single table in the FROM clause.) For
  114811. ** example, if the SQL is this:
  114812. **
  114813. ** SELECT * FROM t1, t2, t3 WHERE ...;
  114814. **
  114815. ** Then the code generated is conceptually like the following:
  114816. **
  114817. ** foreach row1 in t1 do \ Code generated
  114818. ** foreach row2 in t2 do |-- by sqlite3WhereBegin()
  114819. ** foreach row3 in t3 do /
  114820. ** ...
  114821. ** end \ Code generated
  114822. ** end |-- by sqlite3WhereEnd()
  114823. ** end /
  114824. **
  114825. ** Note that the loops might not be nested in the order in which they
  114826. ** appear in the FROM clause if a different order is better able to make
  114827. ** use of indices. Note also that when the IN operator appears in
  114828. ** the WHERE clause, it might result in additional nested loops for
  114829. ** scanning through all values on the right-hand side of the IN.
  114830. **
  114831. ** There are Btree cursors associated with each table. t1 uses cursor
  114832. ** number pTabList->a[0].iCursor. t2 uses the cursor pTabList->a[1].iCursor.
  114833. ** And so forth. This routine generates code to open those VDBE cursors
  114834. ** and sqlite3WhereEnd() generates the code to close them.
  114835. **
  114836. ** The code that sqlite3WhereBegin() generates leaves the cursors named
  114837. ** in pTabList pointing at their appropriate entries. The [...] code
  114838. ** can use OP_Column and OP_Rowid opcodes on these cursors to extract
  114839. ** data from the various tables of the loop.
  114840. **
  114841. ** If the WHERE clause is empty, the foreach loops must each scan their
  114842. ** entire tables. Thus a three-way join is an O(N^3) operation. But if
  114843. ** the tables have indices and there are terms in the WHERE clause that
  114844. ** refer to those indices, a complete table scan can be avoided and the
  114845. ** code will run much faster. Most of the work of this routine is checking
  114846. ** to see if there are indices that can be used to speed up the loop.
  114847. **
  114848. ** Terms of the WHERE clause are also used to limit which rows actually
  114849. ** make it to the "..." in the middle of the loop. After each "foreach",
  114850. ** terms of the WHERE clause that use only terms in that loop and outer
  114851. ** loops are evaluated and if false a jump is made around all subsequent
  114852. ** inner loops (or around the "..." if the test occurs within the inner-
  114853. ** most loop)
  114854. **
  114855. ** OUTER JOINS
  114856. **
  114857. ** An outer join of tables t1 and t2 is conceptally coded as follows:
  114858. **
  114859. ** foreach row1 in t1 do
  114860. ** flag = 0
  114861. ** foreach row2 in t2 do
  114862. ** start:
  114863. ** ...
  114864. ** flag = 1
  114865. ** end
  114866. ** if flag==0 then
  114867. ** move the row2 cursor to a null row
  114868. ** goto start
  114869. ** fi
  114870. ** end
  114871. **
  114872. ** ORDER BY CLAUSE PROCESSING
  114873. **
  114874. ** pOrderBy is a pointer to the ORDER BY clause (or the GROUP BY clause
  114875. ** if the WHERE_GROUPBY flag is set in wctrlFlags) of a SELECT statement
  114876. ** if there is one. If there is no ORDER BY clause or if this routine
  114877. ** is called from an UPDATE or DELETE statement, then pOrderBy is NULL.
  114878. **
  114879. ** The iIdxCur parameter is the cursor number of an index. If
  114880. ** WHERE_ONETABLE_ONLY is set, iIdxCur is the cursor number of an index
  114881. ** to use for OR clause processing. The WHERE clause should use this
  114882. ** specific cursor. If WHERE_ONEPASS_DESIRED is set, then iIdxCur is
  114883. ** the first cursor in an array of cursors for all indices. iIdxCur should
  114884. ** be used to compute the appropriate cursor depending on which index is
  114885. ** used.
  114886. */
  114887. SQLITE_PRIVATE WhereInfo *sqlite3WhereBegin(
  114888. Parse *pParse, /* The parser context */
  114889. SrcList *pTabList, /* FROM clause: A list of all tables to be scanned */
  114890. Expr *pWhere, /* The WHERE clause */
  114891. ExprList *pOrderBy, /* An ORDER BY (or GROUP BY) clause, or NULL */
  114892. ExprList *pResultSet, /* Result set of the query */
  114893. u16 wctrlFlags, /* One of the WHERE_* flags defined in sqliteInt.h */
  114894. int iIdxCur /* If WHERE_ONETABLE_ONLY is set, index cursor number */
  114895. ){
  114896. int nByteWInfo; /* Num. bytes allocated for WhereInfo struct */
  114897. int nTabList; /* Number of elements in pTabList */
  114898. WhereInfo *pWInfo; /* Will become the return value of this function */
  114899. Vdbe *v = pParse->pVdbe; /* The virtual database engine */
  114900. Bitmask notReady; /* Cursors that are not yet positioned */
  114901. WhereLoopBuilder sWLB; /* The WhereLoop builder */
  114902. WhereMaskSet *pMaskSet; /* The expression mask set */
  114903. WhereLevel *pLevel; /* A single level in pWInfo->a[] */
  114904. WhereLoop *pLoop; /* Pointer to a single WhereLoop object */
  114905. int ii; /* Loop counter */
  114906. sqlite3 *db; /* Database connection */
  114907. int rc; /* Return code */
  114908. /* Variable initialization */
  114909. db = pParse->db;
  114910. memset(&sWLB, 0, sizeof(sWLB));
  114911. /* An ORDER/GROUP BY clause of more than 63 terms cannot be optimized */
  114912. testcase( pOrderBy && pOrderBy->nExpr==BMS-1 );
  114913. if( pOrderBy && pOrderBy->nExpr>=BMS ) pOrderBy = 0;
  114914. sWLB.pOrderBy = pOrderBy;
  114915. /* Disable the DISTINCT optimization if SQLITE_DistinctOpt is set via
  114916. ** sqlite3_test_ctrl(SQLITE_TESTCTRL_OPTIMIZATIONS,...) */
  114917. if( OptimizationDisabled(db, SQLITE_DistinctOpt) ){
  114918. wctrlFlags &= ~WHERE_WANT_DISTINCT;
  114919. }
  114920. /* The number of tables in the FROM clause is limited by the number of
  114921. ** bits in a Bitmask
  114922. */
  114923. testcase( pTabList->nSrc==BMS );
  114924. if( pTabList->nSrc>BMS ){
  114925. sqlite3ErrorMsg(pParse, "at most %d tables in a join", BMS);
  114926. return 0;
  114927. }
  114928. /* This function normally generates a nested loop for all tables in
  114929. ** pTabList. But if the WHERE_ONETABLE_ONLY flag is set, then we should
  114930. ** only generate code for the first table in pTabList and assume that
  114931. ** any cursors associated with subsequent tables are uninitialized.
  114932. */
  114933. nTabList = (wctrlFlags & WHERE_ONETABLE_ONLY) ? 1 : pTabList->nSrc;
  114934. /* Allocate and initialize the WhereInfo structure that will become the
  114935. ** return value. A single allocation is used to store the WhereInfo
  114936. ** struct, the contents of WhereInfo.a[], the WhereClause structure
  114937. ** and the WhereMaskSet structure. Since WhereClause contains an 8-byte
  114938. ** field (type Bitmask) it must be aligned on an 8-byte boundary on
  114939. ** some architectures. Hence the ROUND8() below.
  114940. */
  114941. nByteWInfo = ROUND8(sizeof(WhereInfo)+(nTabList-1)*sizeof(WhereLevel));
  114942. pWInfo = sqlite3DbMallocZero(db, nByteWInfo + sizeof(WhereLoop));
  114943. if( db->mallocFailed ){
  114944. sqlite3DbFree(db, pWInfo);
  114945. pWInfo = 0;
  114946. goto whereBeginError;
  114947. }
  114948. pWInfo->aiCurOnePass[0] = pWInfo->aiCurOnePass[1] = -1;
  114949. pWInfo->nLevel = nTabList;
  114950. pWInfo->pParse = pParse;
  114951. pWInfo->pTabList = pTabList;
  114952. pWInfo->pOrderBy = pOrderBy;
  114953. pWInfo->pResultSet = pResultSet;
  114954. pWInfo->iBreak = pWInfo->iContinue = sqlite3VdbeMakeLabel(v);
  114955. pWInfo->wctrlFlags = wctrlFlags;
  114956. pWInfo->savedNQueryLoop = pParse->nQueryLoop;
  114957. pMaskSet = &pWInfo->sMaskSet;
  114958. sWLB.pWInfo = pWInfo;
  114959. sWLB.pWC = &pWInfo->sWC;
  114960. sWLB.pNew = (WhereLoop*)(((char*)pWInfo)+nByteWInfo);
  114961. assert( EIGHT_BYTE_ALIGNMENT(sWLB.pNew) );
  114962. whereLoopInit(sWLB.pNew);
  114963. #ifdef SQLITE_DEBUG
  114964. sWLB.pNew->cId = '*';
  114965. #endif
  114966. /* Split the WHERE clause into separate subexpressions where each
  114967. ** subexpression is separated by an AND operator.
  114968. */
  114969. initMaskSet(pMaskSet);
  114970. whereClauseInit(&pWInfo->sWC, pWInfo);
  114971. whereSplit(&pWInfo->sWC, pWhere, TK_AND);
  114972. /* Special case: a WHERE clause that is constant. Evaluate the
  114973. ** expression and either jump over all of the code or fall thru.
  114974. */
  114975. for(ii=0; ii<sWLB.pWC->nTerm; ii++){
  114976. if( nTabList==0 || sqlite3ExprIsConstantNotJoin(sWLB.pWC->a[ii].pExpr) ){
  114977. sqlite3ExprIfFalse(pParse, sWLB.pWC->a[ii].pExpr, pWInfo->iBreak,
  114978. SQLITE_JUMPIFNULL);
  114979. sWLB.pWC->a[ii].wtFlags |= TERM_CODED;
  114980. }
  114981. }
  114982. /* Special case: No FROM clause
  114983. */
  114984. if( nTabList==0 ){
  114985. if( pOrderBy ) pWInfo->nOBSat = pOrderBy->nExpr;
  114986. if( wctrlFlags & WHERE_WANT_DISTINCT ){
  114987. pWInfo->eDistinct = WHERE_DISTINCT_UNIQUE;
  114988. }
  114989. }
  114990. /* Assign a bit from the bitmask to every term in the FROM clause.
  114991. **
  114992. ** When assigning bitmask values to FROM clause cursors, it must be
  114993. ** the case that if X is the bitmask for the N-th FROM clause term then
  114994. ** the bitmask for all FROM clause terms to the left of the N-th term
  114995. ** is (X-1). An expression from the ON clause of a LEFT JOIN can use
  114996. ** its Expr.iRightJoinTable value to find the bitmask of the right table
  114997. ** of the join. Subtracting one from the right table bitmask gives a
  114998. ** bitmask for all tables to the left of the join. Knowing the bitmask
  114999. ** for all tables to the left of a left join is important. Ticket #3015.
  115000. **
  115001. ** Note that bitmasks are created for all pTabList->nSrc tables in
  115002. ** pTabList, not just the first nTabList tables. nTabList is normally
  115003. ** equal to pTabList->nSrc but might be shortened to 1 if the
  115004. ** WHERE_ONETABLE_ONLY flag is set.
  115005. */
  115006. for(ii=0; ii<pTabList->nSrc; ii++){
  115007. createMask(pMaskSet, pTabList->a[ii].iCursor);
  115008. }
  115009. #ifndef NDEBUG
  115010. {
  115011. Bitmask toTheLeft = 0;
  115012. for(ii=0; ii<pTabList->nSrc; ii++){
  115013. Bitmask m = getMask(pMaskSet, pTabList->a[ii].iCursor);
  115014. assert( (m-1)==toTheLeft );
  115015. toTheLeft |= m;
  115016. }
  115017. }
  115018. #endif
  115019. /* Analyze all of the subexpressions. Note that exprAnalyze() might
  115020. ** add new virtual terms onto the end of the WHERE clause. We do not
  115021. ** want to analyze these virtual terms, so start analyzing at the end
  115022. ** and work forward so that the added virtual terms are never processed.
  115023. */
  115024. exprAnalyzeAll(pTabList, &pWInfo->sWC);
  115025. if( db->mallocFailed ){
  115026. goto whereBeginError;
  115027. }
  115028. if( wctrlFlags & WHERE_WANT_DISTINCT ){
  115029. if( isDistinctRedundant(pParse, pTabList, &pWInfo->sWC, pResultSet) ){
  115030. /* The DISTINCT marking is pointless. Ignore it. */
  115031. pWInfo->eDistinct = WHERE_DISTINCT_UNIQUE;
  115032. }else if( pOrderBy==0 ){
  115033. /* Try to ORDER BY the result set to make distinct processing easier */
  115034. pWInfo->wctrlFlags |= WHERE_DISTINCTBY;
  115035. pWInfo->pOrderBy = pResultSet;
  115036. }
  115037. }
  115038. /* Construct the WhereLoop objects */
  115039. WHERETRACE(0xffff,("*** Optimizer Start ***\n"));
  115040. #if defined(WHERETRACE_ENABLED)
  115041. /* Display all terms of the WHERE clause */
  115042. if( sqlite3WhereTrace & 0x100 ){
  115043. int i;
  115044. for(i=0; i<sWLB.pWC->nTerm; i++){
  115045. whereTermPrint(&sWLB.pWC->a[i], i);
  115046. }
  115047. }
  115048. #endif
  115049. if( nTabList!=1 || whereShortCut(&sWLB)==0 ){
  115050. rc = whereLoopAddAll(&sWLB);
  115051. if( rc ) goto whereBeginError;
  115052. /* Display all of the WhereLoop objects if wheretrace is enabled */
  115053. #ifdef WHERETRACE_ENABLED /* !=0 */
  115054. if( sqlite3WhereTrace ){
  115055. WhereLoop *p;
  115056. int i;
  115057. static char zLabel[] = "0123456789abcdefghijklmnopqrstuvwyxz"
  115058. "ABCDEFGHIJKLMNOPQRSTUVWYXZ";
  115059. for(p=pWInfo->pLoops, i=0; p; p=p->pNextLoop, i++){
  115060. p->cId = zLabel[i%sizeof(zLabel)];
  115061. whereLoopPrint(p, sWLB.pWC);
  115062. }
  115063. }
  115064. #endif
  115065. wherePathSolver(pWInfo, 0);
  115066. if( db->mallocFailed ) goto whereBeginError;
  115067. if( pWInfo->pOrderBy ){
  115068. wherePathSolver(pWInfo, pWInfo->nRowOut+1);
  115069. if( db->mallocFailed ) goto whereBeginError;
  115070. }
  115071. }
  115072. if( pWInfo->pOrderBy==0 && (db->flags & SQLITE_ReverseOrder)!=0 ){
  115073. pWInfo->revMask = (Bitmask)(-1);
  115074. }
  115075. if( pParse->nErr || NEVER(db->mallocFailed) ){
  115076. goto whereBeginError;
  115077. }
  115078. #ifdef WHERETRACE_ENABLED /* !=0 */
  115079. if( sqlite3WhereTrace ){
  115080. sqlite3DebugPrintf("---- Solution nRow=%d", pWInfo->nRowOut);
  115081. if( pWInfo->nOBSat>0 ){
  115082. sqlite3DebugPrintf(" ORDERBY=%d,0x%llx", pWInfo->nOBSat, pWInfo->revMask);
  115083. }
  115084. switch( pWInfo->eDistinct ){
  115085. case WHERE_DISTINCT_UNIQUE: {
  115086. sqlite3DebugPrintf(" DISTINCT=unique");
  115087. break;
  115088. }
  115089. case WHERE_DISTINCT_ORDERED: {
  115090. sqlite3DebugPrintf(" DISTINCT=ordered");
  115091. break;
  115092. }
  115093. case WHERE_DISTINCT_UNORDERED: {
  115094. sqlite3DebugPrintf(" DISTINCT=unordered");
  115095. break;
  115096. }
  115097. }
  115098. sqlite3DebugPrintf("\n");
  115099. for(ii=0; ii<pWInfo->nLevel; ii++){
  115100. whereLoopPrint(pWInfo->a[ii].pWLoop, sWLB.pWC);
  115101. }
  115102. }
  115103. #endif
  115104. /* Attempt to omit tables from the join that do not effect the result */
  115105. if( pWInfo->nLevel>=2
  115106. && pResultSet!=0
  115107. && OptimizationEnabled(db, SQLITE_OmitNoopJoin)
  115108. ){
  115109. Bitmask tabUsed = exprListTableUsage(pMaskSet, pResultSet);
  115110. if( sWLB.pOrderBy ) tabUsed |= exprListTableUsage(pMaskSet, sWLB.pOrderBy);
  115111. while( pWInfo->nLevel>=2 ){
  115112. WhereTerm *pTerm, *pEnd;
  115113. pLoop = pWInfo->a[pWInfo->nLevel-1].pWLoop;
  115114. if( (pWInfo->pTabList->a[pLoop->iTab].jointype & JT_LEFT)==0 ) break;
  115115. if( (wctrlFlags & WHERE_WANT_DISTINCT)==0
  115116. && (pLoop->wsFlags & WHERE_ONEROW)==0
  115117. ){
  115118. break;
  115119. }
  115120. if( (tabUsed & pLoop->maskSelf)!=0 ) break;
  115121. pEnd = sWLB.pWC->a + sWLB.pWC->nTerm;
  115122. for(pTerm=sWLB.pWC->a; pTerm<pEnd; pTerm++){
  115123. if( (pTerm->prereqAll & pLoop->maskSelf)!=0
  115124. && !ExprHasProperty(pTerm->pExpr, EP_FromJoin)
  115125. ){
  115126. break;
  115127. }
  115128. }
  115129. if( pTerm<pEnd ) break;
  115130. WHERETRACE(0xffff, ("-> drop loop %c not used\n", pLoop->cId));
  115131. pWInfo->nLevel--;
  115132. nTabList--;
  115133. }
  115134. }
  115135. WHERETRACE(0xffff,("*** Optimizer Finished ***\n"));
  115136. pWInfo->pParse->nQueryLoop += pWInfo->nRowOut;
  115137. /* If the caller is an UPDATE or DELETE statement that is requesting
  115138. ** to use a one-pass algorithm, determine if this is appropriate.
  115139. ** The one-pass algorithm only works if the WHERE clause constrains
  115140. ** the statement to update a single row.
  115141. */
  115142. assert( (wctrlFlags & WHERE_ONEPASS_DESIRED)==0 || pWInfo->nLevel==1 );
  115143. if( (wctrlFlags & WHERE_ONEPASS_DESIRED)!=0
  115144. && (pWInfo->a[0].pWLoop->wsFlags & WHERE_ONEROW)!=0 ){
  115145. pWInfo->okOnePass = 1;
  115146. if( HasRowid(pTabList->a[0].pTab) ){
  115147. pWInfo->a[0].pWLoop->wsFlags &= ~WHERE_IDX_ONLY;
  115148. }
  115149. }
  115150. /* Open all tables in the pTabList and any indices selected for
  115151. ** searching those tables.
  115152. */
  115153. notReady = ~(Bitmask)0;
  115154. for(ii=0, pLevel=pWInfo->a; ii<nTabList; ii++, pLevel++){
  115155. Table *pTab; /* Table to open */
  115156. int iDb; /* Index of database containing table/index */
  115157. struct SrcList_item *pTabItem;
  115158. pTabItem = &pTabList->a[pLevel->iFrom];
  115159. pTab = pTabItem->pTab;
  115160. iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  115161. pLoop = pLevel->pWLoop;
  115162. if( (pTab->tabFlags & TF_Ephemeral)!=0 || pTab->pSelect ){
  115163. /* Do nothing */
  115164. }else
  115165. #ifndef SQLITE_OMIT_VIRTUALTABLE
  115166. if( (pLoop->wsFlags & WHERE_VIRTUALTABLE)!=0 ){
  115167. const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
  115168. int iCur = pTabItem->iCursor;
  115169. sqlite3VdbeAddOp4(v, OP_VOpen, iCur, 0, 0, pVTab, P4_VTAB);
  115170. }else if( IsVirtual(pTab) ){
  115171. /* noop */
  115172. }else
  115173. #endif
  115174. if( (pLoop->wsFlags & WHERE_IDX_ONLY)==0
  115175. && (wctrlFlags & WHERE_OMIT_OPEN_CLOSE)==0 ){
  115176. int op = OP_OpenRead;
  115177. if( pWInfo->okOnePass ){
  115178. op = OP_OpenWrite;
  115179. pWInfo->aiCurOnePass[0] = pTabItem->iCursor;
  115180. };
  115181. sqlite3OpenTable(pParse, pTabItem->iCursor, iDb, pTab, op);
  115182. assert( pTabItem->iCursor==pLevel->iTabCur );
  115183. testcase( !pWInfo->okOnePass && pTab->nCol==BMS-1 );
  115184. testcase( !pWInfo->okOnePass && pTab->nCol==BMS );
  115185. if( !pWInfo->okOnePass && pTab->nCol<BMS && HasRowid(pTab) ){
  115186. Bitmask b = pTabItem->colUsed;
  115187. int n = 0;
  115188. for(; b; b=b>>1, n++){}
  115189. sqlite3VdbeChangeP4(v, sqlite3VdbeCurrentAddr(v)-1,
  115190. SQLITE_INT_TO_PTR(n), P4_INT32);
  115191. assert( n<=pTab->nCol );
  115192. }
  115193. }else{
  115194. sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
  115195. }
  115196. if( pLoop->wsFlags & WHERE_INDEXED ){
  115197. Index *pIx = pLoop->u.btree.pIndex;
  115198. int iIndexCur;
  115199. int op = OP_OpenRead;
  115200. /* iIdxCur is always set if to a positive value if ONEPASS is possible */
  115201. assert( iIdxCur!=0 || (pWInfo->wctrlFlags & WHERE_ONEPASS_DESIRED)==0 );
  115202. if( !HasRowid(pTab) && IsPrimaryKeyIndex(pIx)
  115203. && (wctrlFlags & WHERE_ONETABLE_ONLY)!=0
  115204. ){
  115205. /* This is one term of an OR-optimization using the PRIMARY KEY of a
  115206. ** WITHOUT ROWID table. No need for a separate index */
  115207. iIndexCur = pLevel->iTabCur;
  115208. op = 0;
  115209. }else if( pWInfo->okOnePass ){
  115210. Index *pJ = pTabItem->pTab->pIndex;
  115211. iIndexCur = iIdxCur;
  115212. assert( wctrlFlags & WHERE_ONEPASS_DESIRED );
  115213. while( ALWAYS(pJ) && pJ!=pIx ){
  115214. iIndexCur++;
  115215. pJ = pJ->pNext;
  115216. }
  115217. op = OP_OpenWrite;
  115218. pWInfo->aiCurOnePass[1] = iIndexCur;
  115219. }else if( iIdxCur && (wctrlFlags & WHERE_ONETABLE_ONLY)!=0 ){
  115220. iIndexCur = iIdxCur;
  115221. if( wctrlFlags & WHERE_REOPEN_IDX ) op = OP_ReopenIdx;
  115222. }else{
  115223. iIndexCur = pParse->nTab++;
  115224. }
  115225. pLevel->iIdxCur = iIndexCur;
  115226. assert( pIx->pSchema==pTab->pSchema );
  115227. assert( iIndexCur>=0 );
  115228. if( op ){
  115229. sqlite3VdbeAddOp3(v, op, iIndexCur, pIx->tnum, iDb);
  115230. sqlite3VdbeSetP4KeyInfo(pParse, pIx);
  115231. if( (pLoop->wsFlags & WHERE_CONSTRAINT)!=0
  115232. && (pLoop->wsFlags & (WHERE_COLUMN_RANGE|WHERE_SKIPSCAN))==0
  115233. && (pWInfo->wctrlFlags&WHERE_ORDERBY_MIN)==0
  115234. ){
  115235. sqlite3VdbeChangeP5(v, OPFLAG_SEEKEQ); /* Hint to COMDB2 */
  115236. }
  115237. VdbeComment((v, "%s", pIx->zName));
  115238. }
  115239. }
  115240. if( iDb>=0 ) sqlite3CodeVerifySchema(pParse, iDb);
  115241. notReady &= ~getMask(&pWInfo->sMaskSet, pTabItem->iCursor);
  115242. }
  115243. pWInfo->iTop = sqlite3VdbeCurrentAddr(v);
  115244. if( db->mallocFailed ) goto whereBeginError;
  115245. /* Generate the code to do the search. Each iteration of the for
  115246. ** loop below generates code for a single nested loop of the VM
  115247. ** program.
  115248. */
  115249. notReady = ~(Bitmask)0;
  115250. for(ii=0; ii<nTabList; ii++){
  115251. int addrExplain;
  115252. int wsFlags;
  115253. pLevel = &pWInfo->a[ii];
  115254. wsFlags = pLevel->pWLoop->wsFlags;
  115255. #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
  115256. if( (pLevel->pWLoop->wsFlags & WHERE_AUTO_INDEX)!=0 ){
  115257. constructAutomaticIndex(pParse, &pWInfo->sWC,
  115258. &pTabList->a[pLevel->iFrom], notReady, pLevel);
  115259. if( db->mallocFailed ) goto whereBeginError;
  115260. }
  115261. #endif
  115262. addrExplain = explainOneScan(
  115263. pParse, pTabList, pLevel, ii, pLevel->iFrom, wctrlFlags
  115264. );
  115265. pLevel->addrBody = sqlite3VdbeCurrentAddr(v);
  115266. notReady = codeOneLoopStart(pWInfo, ii, notReady);
  115267. pWInfo->iContinue = pLevel->addrCont;
  115268. if( (wsFlags&WHERE_MULTI_OR)==0 && (wctrlFlags&WHERE_ONETABLE_ONLY)==0 ){
  115269. addScanStatus(v, pTabList, pLevel, addrExplain);
  115270. }
  115271. }
  115272. /* Done. */
  115273. VdbeModuleComment((v, "Begin WHERE-core"));
  115274. return pWInfo;
  115275. /* Jump here if malloc fails */
  115276. whereBeginError:
  115277. if( pWInfo ){
  115278. pParse->nQueryLoop = pWInfo->savedNQueryLoop;
  115279. whereInfoFree(db, pWInfo);
  115280. }
  115281. return 0;
  115282. }
  115283. /*
  115284. ** Generate the end of the WHERE loop. See comments on
  115285. ** sqlite3WhereBegin() for additional information.
  115286. */
  115287. SQLITE_PRIVATE void sqlite3WhereEnd(WhereInfo *pWInfo){
  115288. Parse *pParse = pWInfo->pParse;
  115289. Vdbe *v = pParse->pVdbe;
  115290. int i;
  115291. WhereLevel *pLevel;
  115292. WhereLoop *pLoop;
  115293. SrcList *pTabList = pWInfo->pTabList;
  115294. sqlite3 *db = pParse->db;
  115295. /* Generate loop termination code.
  115296. */
  115297. VdbeModuleComment((v, "End WHERE-core"));
  115298. sqlite3ExprCacheClear(pParse);
  115299. for(i=pWInfo->nLevel-1; i>=0; i--){
  115300. int addr;
  115301. pLevel = &pWInfo->a[i];
  115302. pLoop = pLevel->pWLoop;
  115303. sqlite3VdbeResolveLabel(v, pLevel->addrCont);
  115304. if( pLevel->op!=OP_Noop ){
  115305. sqlite3VdbeAddOp3(v, pLevel->op, pLevel->p1, pLevel->p2, pLevel->p3);
  115306. sqlite3VdbeChangeP5(v, pLevel->p5);
  115307. VdbeCoverage(v);
  115308. VdbeCoverageIf(v, pLevel->op==OP_Next);
  115309. VdbeCoverageIf(v, pLevel->op==OP_Prev);
  115310. VdbeCoverageIf(v, pLevel->op==OP_VNext);
  115311. }
  115312. if( pLoop->wsFlags & WHERE_IN_ABLE && pLevel->u.in.nIn>0 ){
  115313. struct InLoop *pIn;
  115314. int j;
  115315. sqlite3VdbeResolveLabel(v, pLevel->addrNxt);
  115316. for(j=pLevel->u.in.nIn, pIn=&pLevel->u.in.aInLoop[j-1]; j>0; j--, pIn--){
  115317. sqlite3VdbeJumpHere(v, pIn->addrInTop+1);
  115318. sqlite3VdbeAddOp2(v, pIn->eEndLoopOp, pIn->iCur, pIn->addrInTop);
  115319. VdbeCoverage(v);
  115320. VdbeCoverageIf(v, pIn->eEndLoopOp==OP_PrevIfOpen);
  115321. VdbeCoverageIf(v, pIn->eEndLoopOp==OP_NextIfOpen);
  115322. sqlite3VdbeJumpHere(v, pIn->addrInTop-1);
  115323. }
  115324. }
  115325. sqlite3VdbeResolveLabel(v, pLevel->addrBrk);
  115326. if( pLevel->addrSkip ){
  115327. sqlite3VdbeAddOp2(v, OP_Goto, 0, pLevel->addrSkip);
  115328. VdbeComment((v, "next skip-scan on %s", pLoop->u.btree.pIndex->zName));
  115329. sqlite3VdbeJumpHere(v, pLevel->addrSkip);
  115330. sqlite3VdbeJumpHere(v, pLevel->addrSkip-2);
  115331. }
  115332. if( pLevel->addrLikeRep ){
  115333. int op;
  115334. if( sqlite3VdbeGetOp(v, pLevel->addrLikeRep-1)->p1 ){
  115335. op = OP_DecrJumpZero;
  115336. }else{
  115337. op = OP_JumpZeroIncr;
  115338. }
  115339. sqlite3VdbeAddOp2(v, op, pLevel->iLikeRepCntr, pLevel->addrLikeRep);
  115340. VdbeCoverage(v);
  115341. }
  115342. if( pLevel->iLeftJoin ){
  115343. addr = sqlite3VdbeAddOp1(v, OP_IfPos, pLevel->iLeftJoin); VdbeCoverage(v);
  115344. assert( (pLoop->wsFlags & WHERE_IDX_ONLY)==0
  115345. || (pLoop->wsFlags & WHERE_INDEXED)!=0 );
  115346. if( (pLoop->wsFlags & WHERE_IDX_ONLY)==0 ){
  115347. sqlite3VdbeAddOp1(v, OP_NullRow, pTabList->a[i].iCursor);
  115348. }
  115349. if( pLoop->wsFlags & WHERE_INDEXED ){
  115350. sqlite3VdbeAddOp1(v, OP_NullRow, pLevel->iIdxCur);
  115351. }
  115352. if( pLevel->op==OP_Return ){
  115353. sqlite3VdbeAddOp2(v, OP_Gosub, pLevel->p1, pLevel->addrFirst);
  115354. }else{
  115355. sqlite3VdbeAddOp2(v, OP_Goto, 0, pLevel->addrFirst);
  115356. }
  115357. sqlite3VdbeJumpHere(v, addr);
  115358. }
  115359. VdbeModuleComment((v, "End WHERE-loop%d: %s", i,
  115360. pWInfo->pTabList->a[pLevel->iFrom].pTab->zName));
  115361. }
  115362. /* The "break" point is here, just past the end of the outer loop.
  115363. ** Set it.
  115364. */
  115365. sqlite3VdbeResolveLabel(v, pWInfo->iBreak);
  115366. assert( pWInfo->nLevel<=pTabList->nSrc );
  115367. for(i=0, pLevel=pWInfo->a; i<pWInfo->nLevel; i++, pLevel++){
  115368. int k, last;
  115369. VdbeOp *pOp;
  115370. Index *pIdx = 0;
  115371. struct SrcList_item *pTabItem = &pTabList->a[pLevel->iFrom];
  115372. Table *pTab = pTabItem->pTab;
  115373. assert( pTab!=0 );
  115374. pLoop = pLevel->pWLoop;
  115375. /* For a co-routine, change all OP_Column references to the table of
  115376. ** the co-routine into OP_SCopy of result contained in a register.
  115377. ** OP_Rowid becomes OP_Null.
  115378. */
  115379. if( pTabItem->viaCoroutine && !db->mallocFailed ){
  115380. last = sqlite3VdbeCurrentAddr(v);
  115381. k = pLevel->addrBody;
  115382. pOp = sqlite3VdbeGetOp(v, k);
  115383. for(; k<last; k++, pOp++){
  115384. if( pOp->p1!=pLevel->iTabCur ) continue;
  115385. if( pOp->opcode==OP_Column ){
  115386. pOp->opcode = OP_Copy;
  115387. pOp->p1 = pOp->p2 + pTabItem->regResult;
  115388. pOp->p2 = pOp->p3;
  115389. pOp->p3 = 0;
  115390. }else if( pOp->opcode==OP_Rowid ){
  115391. pOp->opcode = OP_Null;
  115392. pOp->p1 = 0;
  115393. pOp->p3 = 0;
  115394. }
  115395. }
  115396. continue;
  115397. }
  115398. /* Close all of the cursors that were opened by sqlite3WhereBegin.
  115399. ** Except, do not close cursors that will be reused by the OR optimization
  115400. ** (WHERE_OMIT_OPEN_CLOSE). And do not close the OP_OpenWrite cursors
  115401. ** created for the ONEPASS optimization.
  115402. */
  115403. if( (pTab->tabFlags & TF_Ephemeral)==0
  115404. && pTab->pSelect==0
  115405. && (pWInfo->wctrlFlags & WHERE_OMIT_OPEN_CLOSE)==0
  115406. ){
  115407. int ws = pLoop->wsFlags;
  115408. if( !pWInfo->okOnePass && (ws & WHERE_IDX_ONLY)==0 ){
  115409. sqlite3VdbeAddOp1(v, OP_Close, pTabItem->iCursor);
  115410. }
  115411. if( (ws & WHERE_INDEXED)!=0
  115412. && (ws & (WHERE_IPK|WHERE_AUTO_INDEX))==0
  115413. && pLevel->iIdxCur!=pWInfo->aiCurOnePass[1]
  115414. ){
  115415. sqlite3VdbeAddOp1(v, OP_Close, pLevel->iIdxCur);
  115416. }
  115417. }
  115418. /* If this scan uses an index, make VDBE code substitutions to read data
  115419. ** from the index instead of from the table where possible. In some cases
  115420. ** this optimization prevents the table from ever being read, which can
  115421. ** yield a significant performance boost.
  115422. **
  115423. ** Calls to the code generator in between sqlite3WhereBegin and
  115424. ** sqlite3WhereEnd will have created code that references the table
  115425. ** directly. This loop scans all that code looking for opcodes
  115426. ** that reference the table and converts them into opcodes that
  115427. ** reference the index.
  115428. */
  115429. if( pLoop->wsFlags & (WHERE_INDEXED|WHERE_IDX_ONLY) ){
  115430. pIdx = pLoop->u.btree.pIndex;
  115431. }else if( pLoop->wsFlags & WHERE_MULTI_OR ){
  115432. pIdx = pLevel->u.pCovidx;
  115433. }
  115434. if( pIdx && !db->mallocFailed ){
  115435. last = sqlite3VdbeCurrentAddr(v);
  115436. k = pLevel->addrBody;
  115437. pOp = sqlite3VdbeGetOp(v, k);
  115438. for(; k<last; k++, pOp++){
  115439. if( pOp->p1!=pLevel->iTabCur ) continue;
  115440. if( pOp->opcode==OP_Column ){
  115441. int x = pOp->p2;
  115442. assert( pIdx->pTable==pTab );
  115443. if( !HasRowid(pTab) ){
  115444. Index *pPk = sqlite3PrimaryKeyIndex(pTab);
  115445. x = pPk->aiColumn[x];
  115446. }
  115447. x = sqlite3ColumnOfIndex(pIdx, x);
  115448. if( x>=0 ){
  115449. pOp->p2 = x;
  115450. pOp->p1 = pLevel->iIdxCur;
  115451. }
  115452. assert( (pLoop->wsFlags & WHERE_IDX_ONLY)==0 || x>=0 );
  115453. }else if( pOp->opcode==OP_Rowid ){
  115454. pOp->p1 = pLevel->iIdxCur;
  115455. pOp->opcode = OP_IdxRowid;
  115456. }
  115457. }
  115458. }
  115459. }
  115460. /* Final cleanup
  115461. */
  115462. pParse->nQueryLoop = pWInfo->savedNQueryLoop;
  115463. whereInfoFree(db, pWInfo);
  115464. return;
  115465. }
  115466. /************** End of where.c ***********************************************/
  115467. /************** Begin file parse.c *******************************************/
  115468. /* Driver template for the LEMON parser generator.
  115469. ** The author disclaims copyright to this source code.
  115470. **
  115471. ** This version of "lempar.c" is modified, slightly, for use by SQLite.
  115472. ** The only modifications are the addition of a couple of NEVER()
  115473. ** macros to disable tests that are needed in the case of a general
  115474. ** LALR(1) grammar but which are always false in the
  115475. ** specific grammar used by SQLite.
  115476. */
  115477. /* First off, code is included that follows the "include" declaration
  115478. ** in the input grammar file. */
  115479. /* #include <stdio.h> */
  115480. /*
  115481. ** Disable all error recovery processing in the parser push-down
  115482. ** automaton.
  115483. */
  115484. #define YYNOERRORRECOVERY 1
  115485. /*
  115486. ** Make yytestcase() the same as testcase()
  115487. */
  115488. #define yytestcase(X) testcase(X)
  115489. /*
  115490. ** An instance of this structure holds information about the
  115491. ** LIMIT clause of a SELECT statement.
  115492. */
  115493. struct LimitVal {
  115494. Expr *pLimit; /* The LIMIT expression. NULL if there is no limit */
  115495. Expr *pOffset; /* The OFFSET expression. NULL if there is none */
  115496. };
  115497. /*
  115498. ** An instance of this structure is used to store the LIKE,
  115499. ** GLOB, NOT LIKE, and NOT GLOB operators.
  115500. */
  115501. struct LikeOp {
  115502. Token eOperator; /* "like" or "glob" or "regexp" */
  115503. int bNot; /* True if the NOT keyword is present */
  115504. };
  115505. /*
  115506. ** An instance of the following structure describes the event of a
  115507. ** TRIGGER. "a" is the event type, one of TK_UPDATE, TK_INSERT,
  115508. ** TK_DELETE, or TK_INSTEAD. If the event is of the form
  115509. **
  115510. ** UPDATE ON (a,b,c)
  115511. **
  115512. ** Then the "b" IdList records the list "a,b,c".
  115513. */
  115514. struct TrigEvent { int a; IdList * b; };
  115515. /*
  115516. ** An instance of this structure holds the ATTACH key and the key type.
  115517. */
  115518. struct AttachKey { int type; Token key; };
  115519. /*
  115520. ** For a compound SELECT statement, make sure p->pPrior->pNext==p for
  115521. ** all elements in the list. And make sure list length does not exceed
  115522. ** SQLITE_LIMIT_COMPOUND_SELECT.
  115523. */
  115524. static void parserDoubleLinkSelect(Parse *pParse, Select *p){
  115525. if( p->pPrior ){
  115526. Select *pNext = 0, *pLoop;
  115527. int mxSelect, cnt = 0;
  115528. for(pLoop=p; pLoop; pNext=pLoop, pLoop=pLoop->pPrior, cnt++){
  115529. pLoop->pNext = pNext;
  115530. pLoop->selFlags |= SF_Compound;
  115531. }
  115532. if( (p->selFlags & SF_MultiValue)==0 &&
  115533. (mxSelect = pParse->db->aLimit[SQLITE_LIMIT_COMPOUND_SELECT])>0 &&
  115534. cnt>mxSelect
  115535. ){
  115536. sqlite3ErrorMsg(pParse, "too many terms in compound SELECT");
  115537. }
  115538. }
  115539. }
  115540. /* This is a utility routine used to set the ExprSpan.zStart and
  115541. ** ExprSpan.zEnd values of pOut so that the span covers the complete
  115542. ** range of text beginning with pStart and going to the end of pEnd.
  115543. */
  115544. static void spanSet(ExprSpan *pOut, Token *pStart, Token *pEnd){
  115545. pOut->zStart = pStart->z;
  115546. pOut->zEnd = &pEnd->z[pEnd->n];
  115547. }
  115548. /* Construct a new Expr object from a single identifier. Use the
  115549. ** new Expr to populate pOut. Set the span of pOut to be the identifier
  115550. ** that created the expression.
  115551. */
  115552. static void spanExpr(ExprSpan *pOut, Parse *pParse, int op, Token *pValue){
  115553. pOut->pExpr = sqlite3PExpr(pParse, op, 0, 0, pValue);
  115554. pOut->zStart = pValue->z;
  115555. pOut->zEnd = &pValue->z[pValue->n];
  115556. }
  115557. /* This routine constructs a binary expression node out of two ExprSpan
  115558. ** objects and uses the result to populate a new ExprSpan object.
  115559. */
  115560. static void spanBinaryExpr(
  115561. ExprSpan *pOut, /* Write the result here */
  115562. Parse *pParse, /* The parsing context. Errors accumulate here */
  115563. int op, /* The binary operation */
  115564. ExprSpan *pLeft, /* The left operand */
  115565. ExprSpan *pRight /* The right operand */
  115566. ){
  115567. pOut->pExpr = sqlite3PExpr(pParse, op, pLeft->pExpr, pRight->pExpr, 0);
  115568. pOut->zStart = pLeft->zStart;
  115569. pOut->zEnd = pRight->zEnd;
  115570. }
  115571. /* Construct an expression node for a unary postfix operator
  115572. */
  115573. static void spanUnaryPostfix(
  115574. ExprSpan *pOut, /* Write the new expression node here */
  115575. Parse *pParse, /* Parsing context to record errors */
  115576. int op, /* The operator */
  115577. ExprSpan *pOperand, /* The operand */
  115578. Token *pPostOp /* The operand token for setting the span */
  115579. ){
  115580. pOut->pExpr = sqlite3PExpr(pParse, op, pOperand->pExpr, 0, 0);
  115581. pOut->zStart = pOperand->zStart;
  115582. pOut->zEnd = &pPostOp->z[pPostOp->n];
  115583. }
  115584. /* A routine to convert a binary TK_IS or TK_ISNOT expression into a
  115585. ** unary TK_ISNULL or TK_NOTNULL expression. */
  115586. static void binaryToUnaryIfNull(Parse *pParse, Expr *pY, Expr *pA, int op){
  115587. sqlite3 *db = pParse->db;
  115588. if( pY && pA && pY->op==TK_NULL ){
  115589. pA->op = (u8)op;
  115590. sqlite3ExprDelete(db, pA->pRight);
  115591. pA->pRight = 0;
  115592. }
  115593. }
  115594. /* Construct an expression node for a unary prefix operator
  115595. */
  115596. static void spanUnaryPrefix(
  115597. ExprSpan *pOut, /* Write the new expression node here */
  115598. Parse *pParse, /* Parsing context to record errors */
  115599. int op, /* The operator */
  115600. ExprSpan *pOperand, /* The operand */
  115601. Token *pPreOp /* The operand token for setting the span */
  115602. ){
  115603. pOut->pExpr = sqlite3PExpr(pParse, op, pOperand->pExpr, 0, 0);
  115604. pOut->zStart = pPreOp->z;
  115605. pOut->zEnd = pOperand->zEnd;
  115606. }
  115607. /* Next is all token values, in a form suitable for use by makeheaders.
  115608. ** This section will be null unless lemon is run with the -m switch.
  115609. */
  115610. /*
  115611. ** These constants (all generated automatically by the parser generator)
  115612. ** specify the various kinds of tokens (terminals) that the parser
  115613. ** understands.
  115614. **
  115615. ** Each symbol here is a terminal symbol in the grammar.
  115616. */
  115617. /* Make sure the INTERFACE macro is defined.
  115618. */
  115619. #ifndef INTERFACE
  115620. # define INTERFACE 1
  115621. #endif
  115622. /* The next thing included is series of defines which control
  115623. ** various aspects of the generated parser.
  115624. ** YYCODETYPE is the data type used for storing terminal
  115625. ** and nonterminal numbers. "unsigned char" is
  115626. ** used if there are fewer than 250 terminals
  115627. ** and nonterminals. "int" is used otherwise.
  115628. ** YYNOCODE is a number of type YYCODETYPE which corresponds
  115629. ** to no legal terminal or nonterminal number. This
  115630. ** number is used to fill in empty slots of the hash
  115631. ** table.
  115632. ** YYFALLBACK If defined, this indicates that one or more tokens
  115633. ** have fall-back values which should be used if the
  115634. ** original value of the token will not parse.
  115635. ** YYACTIONTYPE is the data type used for storing terminal
  115636. ** and nonterminal numbers. "unsigned char" is
  115637. ** used if there are fewer than 250 rules and
  115638. ** states combined. "int" is used otherwise.
  115639. ** sqlite3ParserTOKENTYPE is the data type used for minor tokens given
  115640. ** directly to the parser from the tokenizer.
  115641. ** YYMINORTYPE is the data type used for all minor tokens.
  115642. ** This is typically a union of many types, one of
  115643. ** which is sqlite3ParserTOKENTYPE. The entry in the union
  115644. ** for base tokens is called "yy0".
  115645. ** YYSTACKDEPTH is the maximum depth of the parser's stack. If
  115646. ** zero the stack is dynamically sized using realloc()
  115647. ** sqlite3ParserARG_SDECL A static variable declaration for the %extra_argument
  115648. ** sqlite3ParserARG_PDECL A parameter declaration for the %extra_argument
  115649. ** sqlite3ParserARG_STORE Code to store %extra_argument into yypParser
  115650. ** sqlite3ParserARG_FETCH Code to extract %extra_argument from yypParser
  115651. ** YYNSTATE the combined number of states.
  115652. ** YYNRULE the number of rules in the grammar
  115653. ** YYERRORSYMBOL is the code number of the error symbol. If not
  115654. ** defined, then do no error processing.
  115655. */
  115656. #define YYCODETYPE unsigned char
  115657. #define YYNOCODE 254
  115658. #define YYACTIONTYPE unsigned short int
  115659. #define YYWILDCARD 70
  115660. #define sqlite3ParserTOKENTYPE Token
  115661. typedef union {
  115662. int yyinit;
  115663. sqlite3ParserTOKENTYPE yy0;
  115664. Select* yy3;
  115665. ExprList* yy14;
  115666. With* yy59;
  115667. SrcList* yy65;
  115668. struct LikeOp yy96;
  115669. Expr* yy132;
  115670. u8 yy186;
  115671. int yy328;
  115672. ExprSpan yy346;
  115673. struct TrigEvent yy378;
  115674. u16 yy381;
  115675. IdList* yy408;
  115676. struct {int value; int mask;} yy429;
  115677. TriggerStep* yy473;
  115678. struct LimitVal yy476;
  115679. } YYMINORTYPE;
  115680. #ifndef YYSTACKDEPTH
  115681. #define YYSTACKDEPTH 100
  115682. #endif
  115683. #define sqlite3ParserARG_SDECL Parse *pParse;
  115684. #define sqlite3ParserARG_PDECL ,Parse *pParse
  115685. #define sqlite3ParserARG_FETCH Parse *pParse = yypParser->pParse
  115686. #define sqlite3ParserARG_STORE yypParser->pParse = pParse
  115687. #define YYNSTATE 642
  115688. #define YYNRULE 327
  115689. #define YYFALLBACK 1
  115690. #define YY_NO_ACTION (YYNSTATE+YYNRULE+2)
  115691. #define YY_ACCEPT_ACTION (YYNSTATE+YYNRULE+1)
  115692. #define YY_ERROR_ACTION (YYNSTATE+YYNRULE)
  115693. /* The yyzerominor constant is used to initialize instances of
  115694. ** YYMINORTYPE objects to zero. */
  115695. static const YYMINORTYPE yyzerominor = { 0 };
  115696. /* Define the yytestcase() macro to be a no-op if is not already defined
  115697. ** otherwise.
  115698. **
  115699. ** Applications can choose to define yytestcase() in the %include section
  115700. ** to a macro that can assist in verifying code coverage. For production
  115701. ** code the yytestcase() macro should be turned off. But it is useful
  115702. ** for testing.
  115703. */
  115704. #ifndef yytestcase
  115705. # define yytestcase(X)
  115706. #endif
  115707. /* Next are the tables used to determine what action to take based on the
  115708. ** current state and lookahead token. These tables are used to implement
  115709. ** functions that take a state number and lookahead value and return an
  115710. ** action integer.
  115711. **
  115712. ** Suppose the action integer is N. Then the action is determined as
  115713. ** follows
  115714. **
  115715. ** 0 <= N < YYNSTATE Shift N. That is, push the lookahead
  115716. ** token onto the stack and goto state N.
  115717. **
  115718. ** YYNSTATE <= N < YYNSTATE+YYNRULE Reduce by rule N-YYNSTATE.
  115719. **
  115720. ** N == YYNSTATE+YYNRULE A syntax error has occurred.
  115721. **
  115722. ** N == YYNSTATE+YYNRULE+1 The parser accepts its input.
  115723. **
  115724. ** N == YYNSTATE+YYNRULE+2 No such action. Denotes unused
  115725. ** slots in the yy_action[] table.
  115726. **
  115727. ** The action table is constructed as a single large table named yy_action[].
  115728. ** Given state S and lookahead X, the action is computed as
  115729. **
  115730. ** yy_action[ yy_shift_ofst[S] + X ]
  115731. **
  115732. ** If the index value yy_shift_ofst[S]+X is out of range or if the value
  115733. ** yy_lookahead[yy_shift_ofst[S]+X] is not equal to X or if yy_shift_ofst[S]
  115734. ** is equal to YY_SHIFT_USE_DFLT, it means that the action is not in the table
  115735. ** and that yy_default[S] should be used instead.
  115736. **
  115737. ** The formula above is for computing the action when the lookahead is
  115738. ** a terminal symbol. If the lookahead is a non-terminal (as occurs after
  115739. ** a reduce action) then the yy_reduce_ofst[] array is used in place of
  115740. ** the yy_shift_ofst[] array and YY_REDUCE_USE_DFLT is used in place of
  115741. ** YY_SHIFT_USE_DFLT.
  115742. **
  115743. ** The following are the tables generated in this section:
  115744. **
  115745. ** yy_action[] A single table containing all actions.
  115746. ** yy_lookahead[] A table containing the lookahead for each entry in
  115747. ** yy_action. Used to detect hash collisions.
  115748. ** yy_shift_ofst[] For each state, the offset into yy_action for
  115749. ** shifting terminals.
  115750. ** yy_reduce_ofst[] For each state, the offset into yy_action for
  115751. ** shifting non-terminals after a reduce.
  115752. ** yy_default[] Default action for each state.
  115753. */
  115754. #define YY_ACTTAB_COUNT (1497)
  115755. static const YYACTIONTYPE yy_action[] = {
  115756. /* 0 */ 306, 212, 432, 955, 639, 191, 955, 295, 559, 88,
  115757. /* 10 */ 88, 88, 88, 81, 86, 86, 86, 86, 85, 85,
  115758. /* 20 */ 84, 84, 84, 83, 330, 185, 184, 183, 635, 635,
  115759. /* 30 */ 292, 606, 606, 88, 88, 88, 88, 683, 86, 86,
  115760. /* 40 */ 86, 86, 85, 85, 84, 84, 84, 83, 330, 16,
  115761. /* 50 */ 436, 597, 89, 90, 80, 600, 599, 601, 601, 87,
  115762. /* 60 */ 87, 88, 88, 88, 88, 684, 86, 86, 86, 86,
  115763. /* 70 */ 85, 85, 84, 84, 84, 83, 330, 306, 559, 84,
  115764. /* 80 */ 84, 84, 83, 330, 65, 86, 86, 86, 86, 85,
  115765. /* 90 */ 85, 84, 84, 84, 83, 330, 635, 635, 634, 633,
  115766. /* 100 */ 182, 682, 550, 379, 376, 375, 17, 322, 606, 606,
  115767. /* 110 */ 371, 198, 479, 91, 374, 82, 79, 165, 85, 85,
  115768. /* 120 */ 84, 84, 84, 83, 330, 598, 635, 635, 107, 89,
  115769. /* 130 */ 90, 80, 600, 599, 601, 601, 87, 87, 88, 88,
  115770. /* 140 */ 88, 88, 186, 86, 86, 86, 86, 85, 85, 84,
  115771. /* 150 */ 84, 84, 83, 330, 306, 594, 594, 142, 328, 327,
  115772. /* 160 */ 484, 249, 344, 238, 635, 635, 634, 633, 585, 448,
  115773. /* 170 */ 526, 525, 229, 388, 1, 394, 450, 584, 449, 635,
  115774. /* 180 */ 635, 635, 635, 319, 395, 606, 606, 199, 157, 273,
  115775. /* 190 */ 382, 268, 381, 187, 635, 635, 634, 633, 311, 555,
  115776. /* 200 */ 266, 593, 593, 266, 347, 588, 89, 90, 80, 600,
  115777. /* 210 */ 599, 601, 601, 87, 87, 88, 88, 88, 88, 478,
  115778. /* 220 */ 86, 86, 86, 86, 85, 85, 84, 84, 84, 83,
  115779. /* 230 */ 330, 306, 272, 536, 634, 633, 146, 610, 197, 310,
  115780. /* 240 */ 575, 182, 482, 271, 379, 376, 375, 506, 21, 634,
  115781. /* 250 */ 633, 634, 633, 635, 635, 374, 611, 574, 548, 440,
  115782. /* 260 */ 111, 563, 606, 606, 634, 633, 324, 479, 608, 608,
  115783. /* 270 */ 608, 300, 435, 573, 119, 407, 210, 162, 562, 883,
  115784. /* 280 */ 592, 592, 306, 89, 90, 80, 600, 599, 601, 601,
  115785. /* 290 */ 87, 87, 88, 88, 88, 88, 506, 86, 86, 86,
  115786. /* 300 */ 86, 85, 85, 84, 84, 84, 83, 330, 620, 111,
  115787. /* 310 */ 635, 635, 361, 606, 606, 358, 249, 349, 248, 433,
  115788. /* 320 */ 243, 479, 586, 634, 633, 195, 611, 93, 119, 221,
  115789. /* 330 */ 575, 497, 534, 534, 89, 90, 80, 600, 599, 601,
  115790. /* 340 */ 601, 87, 87, 88, 88, 88, 88, 574, 86, 86,
  115791. /* 350 */ 86, 86, 85, 85, 84, 84, 84, 83, 330, 306,
  115792. /* 360 */ 77, 429, 638, 573, 589, 530, 240, 230, 242, 105,
  115793. /* 370 */ 249, 349, 248, 515, 588, 208, 460, 529, 564, 173,
  115794. /* 380 */ 634, 633, 970, 144, 430, 2, 424, 228, 380, 557,
  115795. /* 390 */ 606, 606, 190, 153, 159, 158, 514, 51, 632, 631,
  115796. /* 400 */ 630, 71, 536, 432, 954, 196, 610, 954, 614, 45,
  115797. /* 410 */ 18, 89, 90, 80, 600, 599, 601, 601, 87, 87,
  115798. /* 420 */ 88, 88, 88, 88, 261, 86, 86, 86, 86, 85,
  115799. /* 430 */ 85, 84, 84, 84, 83, 330, 306, 608, 608, 608,
  115800. /* 440 */ 542, 424, 402, 385, 241, 506, 451, 320, 211, 543,
  115801. /* 450 */ 164, 436, 386, 293, 451, 587, 108, 496, 111, 334,
  115802. /* 460 */ 391, 591, 424, 614, 27, 452, 453, 606, 606, 72,
  115803. /* 470 */ 257, 70, 259, 452, 339, 342, 564, 582, 68, 415,
  115804. /* 480 */ 469, 328, 327, 62, 614, 45, 110, 393, 89, 90,
  115805. /* 490 */ 80, 600, 599, 601, 601, 87, 87, 88, 88, 88,
  115806. /* 500 */ 88, 152, 86, 86, 86, 86, 85, 85, 84, 84,
  115807. /* 510 */ 84, 83, 330, 306, 110, 499, 520, 538, 402, 389,
  115808. /* 520 */ 424, 110, 566, 500, 593, 593, 454, 82, 79, 165,
  115809. /* 530 */ 424, 591, 384, 564, 340, 615, 188, 162, 424, 350,
  115810. /* 540 */ 616, 424, 614, 44, 606, 606, 445, 582, 300, 434,
  115811. /* 550 */ 151, 19, 614, 9, 568, 580, 348, 615, 469, 567,
  115812. /* 560 */ 614, 26, 616, 614, 45, 89, 90, 80, 600, 599,
  115813. /* 570 */ 601, 601, 87, 87, 88, 88, 88, 88, 411, 86,
  115814. /* 580 */ 86, 86, 86, 85, 85, 84, 84, 84, 83, 330,
  115815. /* 590 */ 306, 579, 110, 578, 521, 282, 433, 398, 400, 255,
  115816. /* 600 */ 486, 82, 79, 165, 487, 164, 82, 79, 165, 488,
  115817. /* 610 */ 488, 364, 387, 424, 544, 544, 509, 350, 362, 155,
  115818. /* 620 */ 191, 606, 606, 559, 642, 640, 333, 82, 79, 165,
  115819. /* 630 */ 305, 564, 507, 312, 357, 614, 45, 329, 596, 595,
  115820. /* 640 */ 194, 337, 89, 90, 80, 600, 599, 601, 601, 87,
  115821. /* 650 */ 87, 88, 88, 88, 88, 424, 86, 86, 86, 86,
  115822. /* 660 */ 85, 85, 84, 84, 84, 83, 330, 306, 20, 323,
  115823. /* 670 */ 150, 263, 211, 543, 421, 596, 595, 614, 22, 424,
  115824. /* 680 */ 193, 424, 284, 424, 391, 424, 509, 424, 577, 424,
  115825. /* 690 */ 186, 335, 424, 559, 424, 313, 120, 546, 606, 606,
  115826. /* 700 */ 67, 614, 47, 614, 50, 614, 48, 614, 100, 614,
  115827. /* 710 */ 99, 614, 101, 576, 614, 102, 614, 109, 326, 89,
  115828. /* 720 */ 90, 80, 600, 599, 601, 601, 87, 87, 88, 88,
  115829. /* 730 */ 88, 88, 424, 86, 86, 86, 86, 85, 85, 84,
  115830. /* 740 */ 84, 84, 83, 330, 306, 424, 311, 424, 585, 54,
  115831. /* 750 */ 424, 516, 517, 590, 614, 112, 424, 584, 424, 572,
  115832. /* 760 */ 424, 195, 424, 571, 424, 67, 424, 614, 94, 614,
  115833. /* 770 */ 98, 424, 614, 97, 264, 606, 606, 195, 614, 46,
  115834. /* 780 */ 614, 96, 614, 30, 614, 49, 614, 115, 614, 114,
  115835. /* 790 */ 418, 229, 388, 614, 113, 306, 89, 90, 80, 600,
  115836. /* 800 */ 599, 601, 601, 87, 87, 88, 88, 88, 88, 424,
  115837. /* 810 */ 86, 86, 86, 86, 85, 85, 84, 84, 84, 83,
  115838. /* 820 */ 330, 119, 424, 590, 110, 372, 606, 606, 195, 53,
  115839. /* 830 */ 250, 614, 29, 195, 472, 438, 729, 190, 302, 498,
  115840. /* 840 */ 14, 523, 641, 2, 614, 43, 306, 89, 90, 80,
  115841. /* 850 */ 600, 599, 601, 601, 87, 87, 88, 88, 88, 88,
  115842. /* 860 */ 424, 86, 86, 86, 86, 85, 85, 84, 84, 84,
  115843. /* 870 */ 83, 330, 424, 613, 964, 964, 354, 606, 606, 420,
  115844. /* 880 */ 312, 64, 614, 42, 391, 355, 283, 437, 301, 255,
  115845. /* 890 */ 414, 410, 495, 492, 614, 28, 471, 306, 89, 90,
  115846. /* 900 */ 80, 600, 599, 601, 601, 87, 87, 88, 88, 88,
  115847. /* 910 */ 88, 424, 86, 86, 86, 86, 85, 85, 84, 84,
  115848. /* 920 */ 84, 83, 330, 424, 110, 110, 110, 110, 606, 606,
  115849. /* 930 */ 110, 254, 13, 614, 41, 532, 531, 283, 481, 531,
  115850. /* 940 */ 457, 284, 119, 561, 356, 614, 40, 284, 306, 89,
  115851. /* 950 */ 78, 80, 600, 599, 601, 601, 87, 87, 88, 88,
  115852. /* 960 */ 88, 88, 424, 86, 86, 86, 86, 85, 85, 84,
  115853. /* 970 */ 84, 84, 83, 330, 110, 424, 341, 220, 555, 606,
  115854. /* 980 */ 606, 351, 555, 318, 614, 95, 413, 255, 83, 330,
  115855. /* 990 */ 284, 284, 255, 640, 333, 356, 255, 614, 39, 306,
  115856. /* 1000 */ 356, 90, 80, 600, 599, 601, 601, 87, 87, 88,
  115857. /* 1010 */ 88, 88, 88, 424, 86, 86, 86, 86, 85, 85,
  115858. /* 1020 */ 84, 84, 84, 83, 330, 424, 317, 316, 141, 465,
  115859. /* 1030 */ 606, 606, 219, 619, 463, 614, 10, 417, 462, 255,
  115860. /* 1040 */ 189, 510, 553, 351, 207, 363, 161, 614, 38, 315,
  115861. /* 1050 */ 218, 255, 255, 80, 600, 599, 601, 601, 87, 87,
  115862. /* 1060 */ 88, 88, 88, 88, 424, 86, 86, 86, 86, 85,
  115863. /* 1070 */ 85, 84, 84, 84, 83, 330, 76, 419, 255, 3,
  115864. /* 1080 */ 878, 461, 424, 247, 331, 331, 614, 37, 217, 76,
  115865. /* 1090 */ 419, 390, 3, 216, 215, 422, 4, 331, 331, 424,
  115866. /* 1100 */ 547, 12, 424, 545, 614, 36, 424, 541, 422, 424,
  115867. /* 1110 */ 540, 424, 214, 424, 408, 424, 539, 403, 605, 605,
  115868. /* 1120 */ 237, 614, 25, 119, 614, 24, 588, 408, 614, 45,
  115869. /* 1130 */ 118, 614, 35, 614, 34, 614, 33, 614, 23, 588,
  115870. /* 1140 */ 60, 223, 603, 602, 513, 378, 73, 74, 140, 139,
  115871. /* 1150 */ 424, 110, 265, 75, 426, 425, 59, 424, 610, 73,
  115872. /* 1160 */ 74, 549, 402, 404, 424, 373, 75, 426, 425, 604,
  115873. /* 1170 */ 138, 610, 614, 11, 392, 76, 419, 181, 3, 614,
  115874. /* 1180 */ 32, 271, 369, 331, 331, 493, 614, 31, 149, 608,
  115875. /* 1190 */ 608, 608, 607, 15, 422, 365, 614, 8, 137, 489,
  115876. /* 1200 */ 136, 190, 608, 608, 608, 607, 15, 485, 176, 135,
  115877. /* 1210 */ 7, 252, 477, 408, 174, 133, 175, 474, 57, 56,
  115878. /* 1220 */ 132, 130, 119, 76, 419, 588, 3, 468, 245, 464,
  115879. /* 1230 */ 171, 331, 331, 125, 123, 456, 447, 122, 446, 104,
  115880. /* 1240 */ 336, 231, 422, 166, 154, 73, 74, 332, 116, 431,
  115881. /* 1250 */ 121, 309, 75, 426, 425, 222, 106, 610, 308, 637,
  115882. /* 1260 */ 204, 408, 629, 627, 628, 6, 200, 428, 427, 290,
  115883. /* 1270 */ 203, 622, 201, 588, 62, 63, 289, 66, 419, 399,
  115884. /* 1280 */ 3, 401, 288, 92, 143, 331, 331, 287, 608, 608,
  115885. /* 1290 */ 608, 607, 15, 73, 74, 227, 422, 325, 69, 416,
  115886. /* 1300 */ 75, 426, 425, 612, 412, 610, 192, 61, 569, 209,
  115887. /* 1310 */ 396, 226, 278, 225, 383, 408, 527, 558, 276, 533,
  115888. /* 1320 */ 552, 528, 321, 523, 370, 508, 180, 588, 494, 179,
  115889. /* 1330 */ 366, 117, 253, 269, 522, 503, 608, 608, 608, 607,
  115890. /* 1340 */ 15, 551, 502, 58, 274, 524, 178, 73, 74, 304,
  115891. /* 1350 */ 501, 368, 303, 206, 75, 426, 425, 491, 360, 610,
  115892. /* 1360 */ 213, 177, 483, 131, 345, 298, 297, 296, 202, 294,
  115893. /* 1370 */ 480, 490, 466, 134, 172, 129, 444, 346, 470, 128,
  115894. /* 1380 */ 314, 459, 103, 127, 126, 148, 124, 167, 443, 235,
  115895. /* 1390 */ 608, 608, 608, 607, 15, 442, 439, 623, 234, 299,
  115896. /* 1400 */ 145, 583, 291, 377, 581, 160, 119, 156, 270, 636,
  115897. /* 1410 */ 971, 169, 279, 626, 520, 625, 473, 624, 170, 621,
  115898. /* 1420 */ 618, 119, 168, 55, 409, 423, 537, 609, 286, 285,
  115899. /* 1430 */ 405, 570, 560, 556, 5, 52, 458, 554, 147, 267,
  115900. /* 1440 */ 519, 504, 518, 406, 262, 239, 260, 512, 343, 511,
  115901. /* 1450 */ 258, 353, 565, 256, 224, 251, 359, 277, 275, 476,
  115902. /* 1460 */ 475, 246, 352, 244, 467, 455, 236, 233, 232, 307,
  115903. /* 1470 */ 441, 281, 205, 163, 397, 280, 535, 505, 330, 617,
  115904. /* 1480 */ 971, 971, 971, 971, 367, 971, 971, 971, 971, 971,
  115905. /* 1490 */ 971, 971, 971, 971, 971, 971, 338,
  115906. };
  115907. static const YYCODETYPE yy_lookahead[] = {
  115908. /* 0 */ 19, 22, 22, 23, 1, 24, 26, 15, 27, 80,
  115909. /* 10 */ 81, 82, 83, 84, 85, 86, 87, 88, 89, 90,
  115910. /* 20 */ 91, 92, 93, 94, 95, 108, 109, 110, 27, 28,
  115911. /* 30 */ 23, 50, 51, 80, 81, 82, 83, 122, 85, 86,
  115912. /* 40 */ 87, 88, 89, 90, 91, 92, 93, 94, 95, 22,
  115913. /* 50 */ 70, 23, 71, 72, 73, 74, 75, 76, 77, 78,
  115914. /* 60 */ 79, 80, 81, 82, 83, 122, 85, 86, 87, 88,
  115915. /* 70 */ 89, 90, 91, 92, 93, 94, 95, 19, 97, 91,
  115916. /* 80 */ 92, 93, 94, 95, 26, 85, 86, 87, 88, 89,
  115917. /* 90 */ 90, 91, 92, 93, 94, 95, 27, 28, 97, 98,
  115918. /* 100 */ 99, 122, 211, 102, 103, 104, 79, 19, 50, 51,
  115919. /* 110 */ 19, 122, 59, 55, 113, 224, 225, 226, 89, 90,
  115920. /* 120 */ 91, 92, 93, 94, 95, 23, 27, 28, 26, 71,
  115921. /* 130 */ 72, 73, 74, 75, 76, 77, 78, 79, 80, 81,
  115922. /* 140 */ 82, 83, 51, 85, 86, 87, 88, 89, 90, 91,
  115923. /* 150 */ 92, 93, 94, 95, 19, 132, 133, 58, 89, 90,
  115924. /* 160 */ 21, 108, 109, 110, 27, 28, 97, 98, 33, 100,
  115925. /* 170 */ 7, 8, 119, 120, 22, 19, 107, 42, 109, 27,
  115926. /* 180 */ 28, 27, 28, 95, 28, 50, 51, 99, 100, 101,
  115927. /* 190 */ 102, 103, 104, 105, 27, 28, 97, 98, 107, 152,
  115928. /* 200 */ 112, 132, 133, 112, 65, 69, 71, 72, 73, 74,
  115929. /* 210 */ 75, 76, 77, 78, 79, 80, 81, 82, 83, 11,
  115930. /* 220 */ 85, 86, 87, 88, 89, 90, 91, 92, 93, 94,
  115931. /* 230 */ 95, 19, 101, 97, 97, 98, 24, 101, 122, 157,
  115932. /* 240 */ 12, 99, 103, 112, 102, 103, 104, 152, 22, 97,
  115933. /* 250 */ 98, 97, 98, 27, 28, 113, 27, 29, 91, 164,
  115934. /* 260 */ 165, 124, 50, 51, 97, 98, 219, 59, 132, 133,
  115935. /* 270 */ 134, 22, 23, 45, 66, 47, 212, 213, 124, 140,
  115936. /* 280 */ 132, 133, 19, 71, 72, 73, 74, 75, 76, 77,
  115937. /* 290 */ 78, 79, 80, 81, 82, 83, 152, 85, 86, 87,
  115938. /* 300 */ 88, 89, 90, 91, 92, 93, 94, 95, 164, 165,
  115939. /* 310 */ 27, 28, 230, 50, 51, 233, 108, 109, 110, 70,
  115940. /* 320 */ 16, 59, 23, 97, 98, 26, 97, 22, 66, 185,
  115941. /* 330 */ 12, 187, 27, 28, 71, 72, 73, 74, 75, 76,
  115942. /* 340 */ 77, 78, 79, 80, 81, 82, 83, 29, 85, 86,
  115943. /* 350 */ 87, 88, 89, 90, 91, 92, 93, 94, 95, 19,
  115944. /* 360 */ 22, 148, 149, 45, 23, 47, 62, 154, 64, 156,
  115945. /* 370 */ 108, 109, 110, 37, 69, 23, 163, 59, 26, 26,
  115946. /* 380 */ 97, 98, 144, 145, 146, 147, 152, 200, 52, 23,
  115947. /* 390 */ 50, 51, 26, 22, 89, 90, 60, 210, 7, 8,
  115948. /* 400 */ 9, 138, 97, 22, 23, 26, 101, 26, 174, 175,
  115949. /* 410 */ 197, 71, 72, 73, 74, 75, 76, 77, 78, 79,
  115950. /* 420 */ 80, 81, 82, 83, 16, 85, 86, 87, 88, 89,
  115951. /* 430 */ 90, 91, 92, 93, 94, 95, 19, 132, 133, 134,
  115952. /* 440 */ 23, 152, 208, 209, 140, 152, 152, 111, 195, 196,
  115953. /* 450 */ 98, 70, 163, 160, 152, 23, 22, 164, 165, 246,
  115954. /* 460 */ 207, 27, 152, 174, 175, 171, 172, 50, 51, 137,
  115955. /* 470 */ 62, 139, 64, 171, 172, 222, 124, 27, 138, 24,
  115956. /* 480 */ 163, 89, 90, 130, 174, 175, 197, 163, 71, 72,
  115957. /* 490 */ 73, 74, 75, 76, 77, 78, 79, 80, 81, 82,
  115958. /* 500 */ 83, 22, 85, 86, 87, 88, 89, 90, 91, 92,
  115959. /* 510 */ 93, 94, 95, 19, 197, 181, 182, 23, 208, 209,
  115960. /* 520 */ 152, 197, 26, 189, 132, 133, 232, 224, 225, 226,
  115961. /* 530 */ 152, 97, 91, 26, 232, 116, 212, 213, 152, 222,
  115962. /* 540 */ 121, 152, 174, 175, 50, 51, 243, 97, 22, 23,
  115963. /* 550 */ 22, 234, 174, 175, 177, 23, 239, 116, 163, 177,
  115964. /* 560 */ 174, 175, 121, 174, 175, 71, 72, 73, 74, 75,
  115965. /* 570 */ 76, 77, 78, 79, 80, 81, 82, 83, 24, 85,
  115966. /* 580 */ 86, 87, 88, 89, 90, 91, 92, 93, 94, 95,
  115967. /* 590 */ 19, 23, 197, 11, 23, 227, 70, 208, 220, 152,
  115968. /* 600 */ 31, 224, 225, 226, 35, 98, 224, 225, 226, 108,
  115969. /* 610 */ 109, 110, 115, 152, 117, 118, 27, 222, 49, 123,
  115970. /* 620 */ 24, 50, 51, 27, 0, 1, 2, 224, 225, 226,
  115971. /* 630 */ 166, 124, 168, 169, 239, 174, 175, 170, 171, 172,
  115972. /* 640 */ 22, 194, 71, 72, 73, 74, 75, 76, 77, 78,
  115973. /* 650 */ 79, 80, 81, 82, 83, 152, 85, 86, 87, 88,
  115974. /* 660 */ 89, 90, 91, 92, 93, 94, 95, 19, 22, 208,
  115975. /* 670 */ 24, 23, 195, 196, 170, 171, 172, 174, 175, 152,
  115976. /* 680 */ 26, 152, 152, 152, 207, 152, 97, 152, 23, 152,
  115977. /* 690 */ 51, 244, 152, 97, 152, 247, 248, 23, 50, 51,
  115978. /* 700 */ 26, 174, 175, 174, 175, 174, 175, 174, 175, 174,
  115979. /* 710 */ 175, 174, 175, 23, 174, 175, 174, 175, 188, 71,
  115980. /* 720 */ 72, 73, 74, 75, 76, 77, 78, 79, 80, 81,
  115981. /* 730 */ 82, 83, 152, 85, 86, 87, 88, 89, 90, 91,
  115982. /* 740 */ 92, 93, 94, 95, 19, 152, 107, 152, 33, 24,
  115983. /* 750 */ 152, 100, 101, 27, 174, 175, 152, 42, 152, 23,
  115984. /* 760 */ 152, 26, 152, 23, 152, 26, 152, 174, 175, 174,
  115985. /* 770 */ 175, 152, 174, 175, 23, 50, 51, 26, 174, 175,
  115986. /* 780 */ 174, 175, 174, 175, 174, 175, 174, 175, 174, 175,
  115987. /* 790 */ 163, 119, 120, 174, 175, 19, 71, 72, 73, 74,
  115988. /* 800 */ 75, 76, 77, 78, 79, 80, 81, 82, 83, 152,
  115989. /* 810 */ 85, 86, 87, 88, 89, 90, 91, 92, 93, 94,
  115990. /* 820 */ 95, 66, 152, 97, 197, 23, 50, 51, 26, 53,
  115991. /* 830 */ 23, 174, 175, 26, 23, 23, 23, 26, 26, 26,
  115992. /* 840 */ 36, 106, 146, 147, 174, 175, 19, 71, 72, 73,
  115993. /* 850 */ 74, 75, 76, 77, 78, 79, 80, 81, 82, 83,
  115994. /* 860 */ 152, 85, 86, 87, 88, 89, 90, 91, 92, 93,
  115995. /* 870 */ 94, 95, 152, 196, 119, 120, 19, 50, 51, 168,
  115996. /* 880 */ 169, 26, 174, 175, 207, 28, 152, 249, 250, 152,
  115997. /* 890 */ 163, 163, 163, 163, 174, 175, 163, 19, 71, 72,
  115998. /* 900 */ 73, 74, 75, 76, 77, 78, 79, 80, 81, 82,
  115999. /* 910 */ 83, 152, 85, 86, 87, 88, 89, 90, 91, 92,
  116000. /* 920 */ 93, 94, 95, 152, 197, 197, 197, 197, 50, 51,
  116001. /* 930 */ 197, 194, 36, 174, 175, 191, 192, 152, 191, 192,
  116002. /* 940 */ 163, 152, 66, 124, 152, 174, 175, 152, 19, 71,
  116003. /* 950 */ 72, 73, 74, 75, 76, 77, 78, 79, 80, 81,
  116004. /* 960 */ 82, 83, 152, 85, 86, 87, 88, 89, 90, 91,
  116005. /* 970 */ 92, 93, 94, 95, 197, 152, 100, 188, 152, 50,
  116006. /* 980 */ 51, 152, 152, 188, 174, 175, 252, 152, 94, 95,
  116007. /* 990 */ 152, 152, 152, 1, 2, 152, 152, 174, 175, 19,
  116008. /* 1000 */ 152, 72, 73, 74, 75, 76, 77, 78, 79, 80,
  116009. /* 1010 */ 81, 82, 83, 152, 85, 86, 87, 88, 89, 90,
  116010. /* 1020 */ 91, 92, 93, 94, 95, 152, 188, 188, 22, 194,
  116011. /* 1030 */ 50, 51, 240, 173, 194, 174, 175, 252, 194, 152,
  116012. /* 1040 */ 36, 181, 28, 152, 23, 219, 122, 174, 175, 219,
  116013. /* 1050 */ 221, 152, 152, 73, 74, 75, 76, 77, 78, 79,
  116014. /* 1060 */ 80, 81, 82, 83, 152, 85, 86, 87, 88, 89,
  116015. /* 1070 */ 90, 91, 92, 93, 94, 95, 19, 20, 152, 22,
  116016. /* 1080 */ 23, 194, 152, 240, 27, 28, 174, 175, 240, 19,
  116017. /* 1090 */ 20, 26, 22, 194, 194, 38, 22, 27, 28, 152,
  116018. /* 1100 */ 23, 22, 152, 116, 174, 175, 152, 23, 38, 152,
  116019. /* 1110 */ 23, 152, 221, 152, 57, 152, 23, 163, 50, 51,
  116020. /* 1120 */ 194, 174, 175, 66, 174, 175, 69, 57, 174, 175,
  116021. /* 1130 */ 40, 174, 175, 174, 175, 174, 175, 174, 175, 69,
  116022. /* 1140 */ 22, 53, 74, 75, 30, 53, 89, 90, 22, 22,
  116023. /* 1150 */ 152, 197, 23, 96, 97, 98, 22, 152, 101, 89,
  116024. /* 1160 */ 90, 91, 208, 209, 152, 53, 96, 97, 98, 101,
  116025. /* 1170 */ 22, 101, 174, 175, 152, 19, 20, 105, 22, 174,
  116026. /* 1180 */ 175, 112, 19, 27, 28, 20, 174, 175, 24, 132,
  116027. /* 1190 */ 133, 134, 135, 136, 38, 44, 174, 175, 107, 61,
  116028. /* 1200 */ 54, 26, 132, 133, 134, 135, 136, 54, 107, 22,
  116029. /* 1210 */ 5, 140, 1, 57, 36, 111, 122, 28, 79, 79,
  116030. /* 1220 */ 131, 123, 66, 19, 20, 69, 22, 1, 16, 20,
  116031. /* 1230 */ 125, 27, 28, 123, 111, 120, 23, 131, 23, 16,
  116032. /* 1240 */ 68, 142, 38, 15, 22, 89, 90, 3, 167, 4,
  116033. /* 1250 */ 248, 251, 96, 97, 98, 180, 180, 101, 251, 151,
  116034. /* 1260 */ 6, 57, 151, 13, 151, 26, 25, 151, 161, 202,
  116035. /* 1270 */ 153, 162, 153, 69, 130, 128, 203, 19, 20, 127,
  116036. /* 1280 */ 22, 126, 204, 129, 22, 27, 28, 205, 132, 133,
  116037. /* 1290 */ 134, 135, 136, 89, 90, 231, 38, 95, 137, 179,
  116038. /* 1300 */ 96, 97, 98, 206, 179, 101, 122, 107, 159, 159,
  116039. /* 1310 */ 125, 231, 216, 228, 107, 57, 184, 217, 216, 176,
  116040. /* 1320 */ 217, 176, 48, 106, 18, 184, 158, 69, 159, 158,
  116041. /* 1330 */ 46, 71, 237, 176, 176, 176, 132, 133, 134, 135,
  116042. /* 1340 */ 136, 217, 176, 137, 216, 178, 158, 89, 90, 179,
  116043. /* 1350 */ 176, 159, 179, 159, 96, 97, 98, 159, 159, 101,
  116044. /* 1360 */ 5, 158, 202, 22, 18, 10, 11, 12, 13, 14,
  116045. /* 1370 */ 190, 238, 17, 190, 158, 193, 41, 159, 202, 193,
  116046. /* 1380 */ 159, 202, 245, 193, 193, 223, 190, 32, 159, 34,
  116047. /* 1390 */ 132, 133, 134, 135, 136, 159, 39, 155, 43, 150,
  116048. /* 1400 */ 223, 177, 201, 178, 177, 186, 66, 199, 177, 152,
  116049. /* 1410 */ 253, 56, 215, 152, 182, 152, 202, 152, 63, 152,
  116050. /* 1420 */ 152, 66, 67, 242, 229, 152, 174, 152, 152, 152,
  116051. /* 1430 */ 152, 152, 152, 152, 199, 242, 202, 152, 198, 152,
  116052. /* 1440 */ 152, 152, 183, 192, 152, 215, 152, 183, 215, 183,
  116053. /* 1450 */ 152, 241, 214, 152, 211, 152, 152, 211, 211, 152,
  116054. /* 1460 */ 152, 241, 152, 152, 152, 152, 152, 152, 152, 114,
  116055. /* 1470 */ 152, 152, 235, 152, 152, 152, 174, 187, 95, 174,
  116056. /* 1480 */ 253, 253, 253, 253, 236, 253, 253, 253, 253, 253,
  116057. /* 1490 */ 253, 253, 253, 253, 253, 253, 141,
  116058. };
  116059. #define YY_SHIFT_USE_DFLT (-86)
  116060. #define YY_SHIFT_COUNT (429)
  116061. #define YY_SHIFT_MIN (-85)
  116062. #define YY_SHIFT_MAX (1383)
  116063. static const short yy_shift_ofst[] = {
  116064. /* 0 */ 992, 1057, 1355, 1156, 1204, 1204, 1, 262, -19, 135,
  116065. /* 10 */ 135, 776, 1204, 1204, 1204, 1204, 69, 69, 53, 208,
  116066. /* 20 */ 283, 755, 58, 725, 648, 571, 494, 417, 340, 263,
  116067. /* 30 */ 212, 827, 827, 827, 827, 827, 827, 827, 827, 827,
  116068. /* 40 */ 827, 827, 827, 827, 827, 827, 878, 827, 929, 980,
  116069. /* 50 */ 980, 1070, 1204, 1204, 1204, 1204, 1204, 1204, 1204, 1204,
  116070. /* 60 */ 1204, 1204, 1204, 1204, 1204, 1204, 1204, 1204, 1204, 1204,
  116071. /* 70 */ 1204, 1204, 1204, 1204, 1204, 1204, 1204, 1204, 1204, 1204,
  116072. /* 80 */ 1258, 1204, 1204, 1204, 1204, 1204, 1204, 1204, 1204, 1204,
  116073. /* 90 */ 1204, 1204, 1204, 1204, -71, -47, -47, -47, -47, -47,
  116074. /* 100 */ 0, 29, -12, 283, 283, 139, 91, 392, 392, 894,
  116075. /* 110 */ 672, 726, 1383, -86, -86, -86, 88, 318, 318, 99,
  116076. /* 120 */ 381, -20, 283, 283, 283, 283, 283, 283, 283, 283,
  116077. /* 130 */ 283, 283, 283, 283, 283, 283, 283, 283, 283, 283,
  116078. /* 140 */ 283, 283, 283, 283, 624, 876, 726, 672, 1340, 1340,
  116079. /* 150 */ 1340, 1340, 1340, 1340, -86, -86, -86, 305, 136, 136,
  116080. /* 160 */ 142, 167, 226, 154, 137, 152, 283, 283, 283, 283,
  116081. /* 170 */ 283, 283, 283, 283, 283, 283, 283, 283, 283, 283,
  116082. /* 180 */ 283, 283, 283, 336, 336, 336, 283, 283, 352, 283,
  116083. /* 190 */ 283, 283, 283, 283, 228, 283, 283, 283, 283, 283,
  116084. /* 200 */ 283, 283, 283, 283, 283, 501, 569, 596, 596, 596,
  116085. /* 210 */ 507, 497, 441, 391, 353, 156, 156, 857, 353, 857,
  116086. /* 220 */ 735, 813, 639, 715, 156, 332, 715, 715, 496, 419,
  116087. /* 230 */ 646, 1357, 1184, 1184, 1335, 1335, 1184, 1341, 1260, 1144,
  116088. /* 240 */ 1346, 1346, 1346, 1346, 1184, 1306, 1144, 1341, 1260, 1260,
  116089. /* 250 */ 1144, 1184, 1306, 1206, 1284, 1184, 1184, 1306, 1184, 1306,
  116090. /* 260 */ 1184, 1306, 1262, 1207, 1207, 1207, 1274, 1262, 1207, 1217,
  116091. /* 270 */ 1207, 1274, 1207, 1207, 1185, 1200, 1185, 1200, 1185, 1200,
  116092. /* 280 */ 1184, 1184, 1161, 1262, 1202, 1202, 1262, 1154, 1155, 1147,
  116093. /* 290 */ 1152, 1144, 1241, 1239, 1250, 1250, 1254, 1254, 1254, 1254,
  116094. /* 300 */ -86, -86, -86, -86, -86, -86, 1068, 304, 526, 249,
  116095. /* 310 */ 408, -83, 434, 812, 27, 811, 807, 802, 751, 589,
  116096. /* 320 */ 651, 163, 131, 674, 366, 450, 299, 148, 23, 102,
  116097. /* 330 */ 229, -21, 1245, 1244, 1222, 1099, 1228, 1172, 1223, 1215,
  116098. /* 340 */ 1213, 1115, 1106, 1123, 1110, 1209, 1105, 1212, 1226, 1098,
  116099. /* 350 */ 1089, 1140, 1139, 1104, 1189, 1178, 1094, 1211, 1205, 1187,
  116100. /* 360 */ 1101, 1071, 1153, 1175, 1146, 1138, 1151, 1091, 1164, 1165,
  116101. /* 370 */ 1163, 1069, 1072, 1148, 1112, 1134, 1127, 1129, 1126, 1092,
  116102. /* 380 */ 1114, 1118, 1088, 1090, 1093, 1087, 1084, 987, 1079, 1077,
  116103. /* 390 */ 1074, 1065, 924, 1021, 1014, 1004, 1006, 819, 739, 896,
  116104. /* 400 */ 855, 804, 739, 740, 736, 690, 654, 665, 618, 582,
  116105. /* 410 */ 568, 528, 554, 379, 532, 479, 455, 379, 432, 371,
  116106. /* 420 */ 341, 28, 338, 116, -11, -57, -85, 7, -8, 3,
  116107. };
  116108. #define YY_REDUCE_USE_DFLT (-110)
  116109. #define YY_REDUCE_COUNT (305)
  116110. #define YY_REDUCE_MIN (-109)
  116111. #define YY_REDUCE_MAX (1323)
  116112. static const short yy_reduce_ofst[] = {
  116113. /* 0 */ 238, 954, 213, 289, 310, 234, 144, 317, -109, 382,
  116114. /* 10 */ 377, 303, 461, 389, 378, 368, 302, 294, 253, 395,
  116115. /* 20 */ 293, 324, 403, 403, 403, 403, 403, 403, 403, 403,
  116116. /* 30 */ 403, 403, 403, 403, 403, 403, 403, 403, 403, 403,
  116117. /* 40 */ 403, 403, 403, 403, 403, 403, 403, 403, 403, 403,
  116118. /* 50 */ 403, 1022, 1012, 1005, 998, 963, 961, 959, 957, 950,
  116119. /* 60 */ 947, 930, 912, 873, 861, 823, 810, 771, 759, 720,
  116120. /* 70 */ 708, 670, 657, 619, 614, 612, 610, 608, 606, 604,
  116121. /* 80 */ 598, 595, 593, 580, 542, 540, 537, 535, 533, 531,
  116122. /* 90 */ 529, 527, 503, 386, 403, 403, 403, 403, 403, 403,
  116123. /* 100 */ 403, 403, 403, 95, 447, 82, 334, 504, 467, 403,
  116124. /* 110 */ 477, 464, 403, 403, 403, 403, 860, 747, 744, 785,
  116125. /* 120 */ 638, 638, 926, 891, 900, 899, 887, 844, 840, 835,
  116126. /* 130 */ 848, 830, 843, 829, 792, 839, 826, 737, 838, 795,
  116127. /* 140 */ 789, 47, 734, 530, 696, 777, 711, 677, 733, 730,
  116128. /* 150 */ 729, 728, 727, 627, 448, 64, 187, 1305, 1302, 1252,
  116129. /* 160 */ 1290, 1273, 1323, 1322, 1321, 1319, 1318, 1316, 1315, 1314,
  116130. /* 170 */ 1313, 1312, 1311, 1310, 1308, 1307, 1304, 1303, 1301, 1298,
  116131. /* 180 */ 1294, 1292, 1289, 1266, 1264, 1259, 1288, 1287, 1238, 1285,
  116132. /* 190 */ 1281, 1280, 1279, 1278, 1251, 1277, 1276, 1275, 1273, 1268,
  116133. /* 200 */ 1267, 1265, 1263, 1261, 1257, 1248, 1237, 1247, 1246, 1243,
  116134. /* 210 */ 1238, 1240, 1235, 1249, 1234, 1233, 1230, 1220, 1214, 1210,
  116135. /* 220 */ 1225, 1219, 1232, 1231, 1197, 1195, 1227, 1224, 1201, 1208,
  116136. /* 230 */ 1242, 1137, 1236, 1229, 1193, 1181, 1221, 1177, 1196, 1179,
  116137. /* 240 */ 1191, 1190, 1186, 1182, 1218, 1216, 1176, 1162, 1183, 1180,
  116138. /* 250 */ 1160, 1199, 1203, 1133, 1095, 1198, 1194, 1188, 1192, 1171,
  116139. /* 260 */ 1169, 1168, 1173, 1174, 1166, 1159, 1141, 1170, 1158, 1167,
  116140. /* 270 */ 1157, 1132, 1145, 1143, 1124, 1128, 1103, 1102, 1100, 1096,
  116141. /* 280 */ 1150, 1149, 1085, 1125, 1080, 1064, 1120, 1097, 1082, 1078,
  116142. /* 290 */ 1073, 1067, 1109, 1107, 1119, 1117, 1116, 1113, 1111, 1108,
  116143. /* 300 */ 1007, 1000, 1002, 1076, 1075, 1081,
  116144. };
  116145. static const YYACTIONTYPE yy_default[] = {
  116146. /* 0 */ 647, 964, 964, 964, 878, 878, 969, 964, 774, 802,
  116147. /* 10 */ 802, 938, 969, 969, 969, 876, 969, 969, 969, 964,
  116148. /* 20 */ 969, 778, 808, 969, 969, 969, 969, 969, 969, 969,
  116149. /* 30 */ 969, 937, 939, 816, 815, 918, 789, 813, 806, 810,
  116150. /* 40 */ 879, 872, 873, 871, 875, 880, 969, 809, 841, 856,
  116151. /* 50 */ 840, 969, 969, 969, 969, 969, 969, 969, 969, 969,
  116152. /* 60 */ 969, 969, 969, 969, 969, 969, 969, 969, 969, 969,
  116153. /* 70 */ 969, 969, 969, 969, 969, 969, 969, 969, 969, 969,
  116154. /* 80 */ 969, 969, 969, 969, 969, 969, 969, 969, 969, 969,
  116155. /* 90 */ 969, 969, 969, 969, 850, 855, 862, 854, 851, 843,
  116156. /* 100 */ 842, 844, 845, 969, 969, 673, 739, 969, 969, 846,
  116157. /* 110 */ 969, 685, 847, 859, 858, 857, 680, 969, 969, 969,
  116158. /* 120 */ 969, 969, 969, 969, 969, 969, 969, 969, 969, 969,
  116159. /* 130 */ 969, 969, 969, 969, 969, 969, 969, 969, 969, 969,
  116160. /* 140 */ 969, 969, 969, 969, 647, 964, 969, 969, 964, 964,
  116161. /* 150 */ 964, 964, 964, 964, 956, 778, 768, 969, 969, 969,
  116162. /* 160 */ 969, 969, 969, 969, 969, 969, 969, 944, 942, 969,
  116163. /* 170 */ 891, 969, 969, 969, 969, 969, 969, 969, 969, 969,
  116164. /* 180 */ 969, 969, 969, 969, 969, 969, 969, 969, 969, 969,
  116165. /* 190 */ 969, 969, 969, 969, 969, 969, 969, 969, 969, 969,
  116166. /* 200 */ 969, 969, 969, 969, 653, 969, 911, 774, 774, 774,
  116167. /* 210 */ 776, 754, 766, 655, 812, 791, 791, 923, 812, 923,
  116168. /* 220 */ 710, 733, 707, 802, 791, 874, 802, 802, 775, 766,
  116169. /* 230 */ 969, 949, 782, 782, 941, 941, 782, 821, 743, 812,
  116170. /* 240 */ 750, 750, 750, 750, 782, 670, 812, 821, 743, 743,
  116171. /* 250 */ 812, 782, 670, 917, 915, 782, 782, 670, 782, 670,
  116172. /* 260 */ 782, 670, 884, 741, 741, 741, 725, 884, 741, 710,
  116173. /* 270 */ 741, 725, 741, 741, 795, 790, 795, 790, 795, 790,
  116174. /* 280 */ 782, 782, 969, 884, 888, 888, 884, 807, 796, 805,
  116175. /* 290 */ 803, 812, 676, 728, 663, 663, 652, 652, 652, 652,
  116176. /* 300 */ 961, 961, 956, 712, 712, 695, 969, 969, 969, 969,
  116177. /* 310 */ 969, 969, 687, 969, 893, 969, 969, 969, 969, 969,
  116178. /* 320 */ 969, 969, 969, 969, 969, 969, 969, 969, 969, 969,
  116179. /* 330 */ 969, 828, 969, 648, 951, 969, 969, 948, 969, 969,
  116180. /* 340 */ 969, 969, 969, 969, 969, 969, 969, 969, 969, 969,
  116181. /* 350 */ 969, 969, 969, 969, 969, 969, 921, 969, 969, 969,
  116182. /* 360 */ 969, 969, 969, 914, 913, 969, 969, 969, 969, 969,
  116183. /* 370 */ 969, 969, 969, 969, 969, 969, 969, 969, 969, 969,
  116184. /* 380 */ 969, 969, 969, 969, 969, 969, 969, 757, 969, 969,
  116185. /* 390 */ 969, 761, 969, 969, 969, 969, 969, 969, 804, 969,
  116186. /* 400 */ 797, 969, 877, 969, 969, 969, 969, 969, 969, 969,
  116187. /* 410 */ 969, 969, 969, 966, 969, 969, 969, 965, 969, 969,
  116188. /* 420 */ 969, 969, 969, 830, 969, 829, 833, 969, 661, 969,
  116189. /* 430 */ 644, 649, 960, 963, 962, 959, 958, 957, 952, 950,
  116190. /* 440 */ 947, 946, 945, 943, 940, 936, 897, 895, 902, 901,
  116191. /* 450 */ 900, 899, 898, 896, 894, 892, 818, 817, 814, 811,
  116192. /* 460 */ 753, 935, 890, 752, 749, 748, 669, 953, 920, 929,
  116193. /* 470 */ 928, 927, 822, 926, 925, 924, 922, 919, 906, 820,
  116194. /* 480 */ 819, 744, 882, 881, 672, 910, 909, 908, 912, 916,
  116195. /* 490 */ 907, 784, 751, 671, 668, 675, 679, 731, 732, 740,
  116196. /* 500 */ 738, 737, 736, 735, 734, 730, 681, 686, 724, 709,
  116197. /* 510 */ 708, 717, 716, 722, 721, 720, 719, 718, 715, 714,
  116198. /* 520 */ 713, 706, 705, 711, 704, 727, 726, 723, 703, 747,
  116199. /* 530 */ 746, 745, 742, 702, 701, 700, 833, 699, 698, 838,
  116200. /* 540 */ 837, 866, 826, 755, 759, 758, 762, 763, 771, 770,
  116201. /* 550 */ 769, 780, 781, 793, 792, 824, 823, 794, 779, 773,
  116202. /* 560 */ 772, 788, 787, 786, 785, 777, 767, 799, 798, 868,
  116203. /* 570 */ 783, 867, 865, 934, 933, 932, 931, 930, 870, 967,
  116204. /* 580 */ 968, 887, 889, 886, 801, 800, 885, 869, 839, 836,
  116205. /* 590 */ 690, 691, 905, 904, 903, 693, 692, 689, 688, 863,
  116206. /* 600 */ 860, 852, 864, 861, 853, 849, 848, 834, 832, 831,
  116207. /* 610 */ 827, 835, 760, 756, 825, 765, 764, 697, 696, 694,
  116208. /* 620 */ 678, 677, 674, 667, 665, 664, 666, 662, 660, 659,
  116209. /* 630 */ 658, 657, 656, 684, 683, 682, 654, 651, 650, 646,
  116210. /* 640 */ 645, 643,
  116211. };
  116212. /* The next table maps tokens into fallback tokens. If a construct
  116213. ** like the following:
  116214. **
  116215. ** %fallback ID X Y Z.
  116216. **
  116217. ** appears in the grammar, then ID becomes a fallback token for X, Y,
  116218. ** and Z. Whenever one of the tokens X, Y, or Z is input to the parser
  116219. ** but it does not parse, the type of the token is changed to ID and
  116220. ** the parse is retried before an error is thrown.
  116221. */
  116222. #ifdef YYFALLBACK
  116223. static const YYCODETYPE yyFallback[] = {
  116224. 0, /* $ => nothing */
  116225. 0, /* SEMI => nothing */
  116226. 27, /* EXPLAIN => ID */
  116227. 27, /* QUERY => ID */
  116228. 27, /* PLAN => ID */
  116229. 27, /* BEGIN => ID */
  116230. 0, /* TRANSACTION => nothing */
  116231. 27, /* DEFERRED => ID */
  116232. 27, /* IMMEDIATE => ID */
  116233. 27, /* EXCLUSIVE => ID */
  116234. 0, /* COMMIT => nothing */
  116235. 27, /* END => ID */
  116236. 27, /* ROLLBACK => ID */
  116237. 27, /* SAVEPOINT => ID */
  116238. 27, /* RELEASE => ID */
  116239. 0, /* TO => nothing */
  116240. 0, /* TABLE => nothing */
  116241. 0, /* CREATE => nothing */
  116242. 27, /* IF => ID */
  116243. 0, /* NOT => nothing */
  116244. 0, /* EXISTS => nothing */
  116245. 27, /* TEMP => ID */
  116246. 0, /* LP => nothing */
  116247. 0, /* RP => nothing */
  116248. 0, /* AS => nothing */
  116249. 27, /* WITHOUT => ID */
  116250. 0, /* COMMA => nothing */
  116251. 0, /* ID => nothing */
  116252. 0, /* INDEXED => nothing */
  116253. 27, /* ABORT => ID */
  116254. 27, /* ACTION => ID */
  116255. 27, /* AFTER => ID */
  116256. 27, /* ANALYZE => ID */
  116257. 27, /* ASC => ID */
  116258. 27, /* ATTACH => ID */
  116259. 27, /* BEFORE => ID */
  116260. 27, /* BY => ID */
  116261. 27, /* CASCADE => ID */
  116262. 27, /* CAST => ID */
  116263. 27, /* COLUMNKW => ID */
  116264. 27, /* CONFLICT => ID */
  116265. 27, /* DATABASE => ID */
  116266. 27, /* DESC => ID */
  116267. 27, /* DETACH => ID */
  116268. 27, /* EACH => ID */
  116269. 27, /* FAIL => ID */
  116270. 27, /* FOR => ID */
  116271. 27, /* IGNORE => ID */
  116272. 27, /* INITIALLY => ID */
  116273. 27, /* INSTEAD => ID */
  116274. 27, /* LIKE_KW => ID */
  116275. 27, /* MATCH => ID */
  116276. 27, /* NO => ID */
  116277. 27, /* KEY => ID */
  116278. 27, /* OF => ID */
  116279. 27, /* OFFSET => ID */
  116280. 27, /* PRAGMA => ID */
  116281. 27, /* RAISE => ID */
  116282. 27, /* RECURSIVE => ID */
  116283. 27, /* REPLACE => ID */
  116284. 27, /* RESTRICT => ID */
  116285. 27, /* ROW => ID */
  116286. 27, /* TRIGGER => ID */
  116287. 27, /* VACUUM => ID */
  116288. 27, /* VIEW => ID */
  116289. 27, /* VIRTUAL => ID */
  116290. 27, /* WITH => ID */
  116291. 27, /* REINDEX => ID */
  116292. 27, /* RENAME => ID */
  116293. 27, /* CTIME_KW => ID */
  116294. };
  116295. #endif /* YYFALLBACK */
  116296. /* The following structure represents a single element of the
  116297. ** parser's stack. Information stored includes:
  116298. **
  116299. ** + The state number for the parser at this level of the stack.
  116300. **
  116301. ** + The value of the token stored at this level of the stack.
  116302. ** (In other words, the "major" token.)
  116303. **
  116304. ** + The semantic value stored at this level of the stack. This is
  116305. ** the information used by the action routines in the grammar.
  116306. ** It is sometimes called the "minor" token.
  116307. */
  116308. struct yyStackEntry {
  116309. YYACTIONTYPE stateno; /* The state-number */
  116310. YYCODETYPE major; /* The major token value. This is the code
  116311. ** number for the token at this stack level */
  116312. YYMINORTYPE minor; /* The user-supplied minor token value. This
  116313. ** is the value of the token */
  116314. };
  116315. typedef struct yyStackEntry yyStackEntry;
  116316. /* The state of the parser is completely contained in an instance of
  116317. ** the following structure */
  116318. struct yyParser {
  116319. int yyidx; /* Index of top element in stack */
  116320. #ifdef YYTRACKMAXSTACKDEPTH
  116321. int yyidxMax; /* Maximum value of yyidx */
  116322. #endif
  116323. int yyerrcnt; /* Shifts left before out of the error */
  116324. sqlite3ParserARG_SDECL /* A place to hold %extra_argument */
  116325. #if YYSTACKDEPTH<=0
  116326. int yystksz; /* Current side of the stack */
  116327. yyStackEntry *yystack; /* The parser's stack */
  116328. #else
  116329. yyStackEntry yystack[YYSTACKDEPTH]; /* The parser's stack */
  116330. #endif
  116331. };
  116332. typedef struct yyParser yyParser;
  116333. #ifndef NDEBUG
  116334. /* #include <stdio.h> */
  116335. static FILE *yyTraceFILE = 0;
  116336. static char *yyTracePrompt = 0;
  116337. #endif /* NDEBUG */
  116338. #ifndef NDEBUG
  116339. /*
  116340. ** Turn parser tracing on by giving a stream to which to write the trace
  116341. ** and a prompt to preface each trace message. Tracing is turned off
  116342. ** by making either argument NULL
  116343. **
  116344. ** Inputs:
  116345. ** <ul>
  116346. ** <li> A FILE* to which trace output should be written.
  116347. ** If NULL, then tracing is turned off.
  116348. ** <li> A prefix string written at the beginning of every
  116349. ** line of trace output. If NULL, then tracing is
  116350. ** turned off.
  116351. ** </ul>
  116352. **
  116353. ** Outputs:
  116354. ** None.
  116355. */
  116356. SQLITE_PRIVATE void sqlite3ParserTrace(FILE *TraceFILE, char *zTracePrompt){
  116357. yyTraceFILE = TraceFILE;
  116358. yyTracePrompt = zTracePrompt;
  116359. if( yyTraceFILE==0 ) yyTracePrompt = 0;
  116360. else if( yyTracePrompt==0 ) yyTraceFILE = 0;
  116361. }
  116362. #endif /* NDEBUG */
  116363. #ifndef NDEBUG
  116364. /* For tracing shifts, the names of all terminals and nonterminals
  116365. ** are required. The following table supplies these names */
  116366. static const char *const yyTokenName[] = {
  116367. "$", "SEMI", "EXPLAIN", "QUERY",
  116368. "PLAN", "BEGIN", "TRANSACTION", "DEFERRED",
  116369. "IMMEDIATE", "EXCLUSIVE", "COMMIT", "END",
  116370. "ROLLBACK", "SAVEPOINT", "RELEASE", "TO",
  116371. "TABLE", "CREATE", "IF", "NOT",
  116372. "EXISTS", "TEMP", "LP", "RP",
  116373. "AS", "WITHOUT", "COMMA", "ID",
  116374. "INDEXED", "ABORT", "ACTION", "AFTER",
  116375. "ANALYZE", "ASC", "ATTACH", "BEFORE",
  116376. "BY", "CASCADE", "CAST", "COLUMNKW",
  116377. "CONFLICT", "DATABASE", "DESC", "DETACH",
  116378. "EACH", "FAIL", "FOR", "IGNORE",
  116379. "INITIALLY", "INSTEAD", "LIKE_KW", "MATCH",
  116380. "NO", "KEY", "OF", "OFFSET",
  116381. "PRAGMA", "RAISE", "RECURSIVE", "REPLACE",
  116382. "RESTRICT", "ROW", "TRIGGER", "VACUUM",
  116383. "VIEW", "VIRTUAL", "WITH", "REINDEX",
  116384. "RENAME", "CTIME_KW", "ANY", "OR",
  116385. "AND", "IS", "BETWEEN", "IN",
  116386. "ISNULL", "NOTNULL", "NE", "EQ",
  116387. "GT", "LE", "LT", "GE",
  116388. "ESCAPE", "BITAND", "BITOR", "LSHIFT",
  116389. "RSHIFT", "PLUS", "MINUS", "STAR",
  116390. "SLASH", "REM", "CONCAT", "COLLATE",
  116391. "BITNOT", "STRING", "JOIN_KW", "CONSTRAINT",
  116392. "DEFAULT", "NULL", "PRIMARY", "UNIQUE",
  116393. "CHECK", "REFERENCES", "AUTOINCR", "ON",
  116394. "INSERT", "DELETE", "UPDATE", "SET",
  116395. "DEFERRABLE", "FOREIGN", "DROP", "UNION",
  116396. "ALL", "EXCEPT", "INTERSECT", "SELECT",
  116397. "VALUES", "DISTINCT", "DOT", "FROM",
  116398. "JOIN", "USING", "ORDER", "GROUP",
  116399. "HAVING", "LIMIT", "WHERE", "INTO",
  116400. "INTEGER", "FLOAT", "BLOB", "VARIABLE",
  116401. "CASE", "WHEN", "THEN", "ELSE",
  116402. "INDEX", "ALTER", "ADD", "error",
  116403. "input", "cmdlist", "ecmd", "explain",
  116404. "cmdx", "cmd", "transtype", "trans_opt",
  116405. "nm", "savepoint_opt", "create_table", "create_table_args",
  116406. "createkw", "temp", "ifnotexists", "dbnm",
  116407. "columnlist", "conslist_opt", "table_options", "select",
  116408. "column", "columnid", "type", "carglist",
  116409. "typetoken", "typename", "signed", "plus_num",
  116410. "minus_num", "ccons", "term", "expr",
  116411. "onconf", "sortorder", "autoinc", "idxlist_opt",
  116412. "refargs", "defer_subclause", "refarg", "refact",
  116413. "init_deferred_pred_opt", "conslist", "tconscomma", "tcons",
  116414. "idxlist", "defer_subclause_opt", "orconf", "resolvetype",
  116415. "raisetype", "ifexists", "fullname", "selectnowith",
  116416. "oneselect", "with", "multiselect_op", "distinct",
  116417. "selcollist", "from", "where_opt", "groupby_opt",
  116418. "having_opt", "orderby_opt", "limit_opt", "values",
  116419. "nexprlist", "exprlist", "sclp", "as",
  116420. "seltablist", "stl_prefix", "joinop", "indexed_opt",
  116421. "on_opt", "using_opt", "joinop2", "idlist",
  116422. "sortlist", "setlist", "insert_cmd", "inscollist_opt",
  116423. "likeop", "between_op", "in_op", "case_operand",
  116424. "case_exprlist", "case_else", "uniqueflag", "collate",
  116425. "nmnum", "trigger_decl", "trigger_cmd_list", "trigger_time",
  116426. "trigger_event", "foreach_clause", "when_clause", "trigger_cmd",
  116427. "trnm", "tridxby", "database_kw_opt", "key_opt",
  116428. "add_column_fullname", "kwcolumn_opt", "create_vtab", "vtabarglist",
  116429. "vtabarg", "vtabargtoken", "lp", "anylist",
  116430. "wqlist",
  116431. };
  116432. #endif /* NDEBUG */
  116433. #ifndef NDEBUG
  116434. /* For tracing reduce actions, the names of all rules are required.
  116435. */
  116436. static const char *const yyRuleName[] = {
  116437. /* 0 */ "input ::= cmdlist",
  116438. /* 1 */ "cmdlist ::= cmdlist ecmd",
  116439. /* 2 */ "cmdlist ::= ecmd",
  116440. /* 3 */ "ecmd ::= SEMI",
  116441. /* 4 */ "ecmd ::= explain cmdx SEMI",
  116442. /* 5 */ "explain ::=",
  116443. /* 6 */ "explain ::= EXPLAIN",
  116444. /* 7 */ "explain ::= EXPLAIN QUERY PLAN",
  116445. /* 8 */ "cmdx ::= cmd",
  116446. /* 9 */ "cmd ::= BEGIN transtype trans_opt",
  116447. /* 10 */ "trans_opt ::=",
  116448. /* 11 */ "trans_opt ::= TRANSACTION",
  116449. /* 12 */ "trans_opt ::= TRANSACTION nm",
  116450. /* 13 */ "transtype ::=",
  116451. /* 14 */ "transtype ::= DEFERRED",
  116452. /* 15 */ "transtype ::= IMMEDIATE",
  116453. /* 16 */ "transtype ::= EXCLUSIVE",
  116454. /* 17 */ "cmd ::= COMMIT trans_opt",
  116455. /* 18 */ "cmd ::= END trans_opt",
  116456. /* 19 */ "cmd ::= ROLLBACK trans_opt",
  116457. /* 20 */ "savepoint_opt ::= SAVEPOINT",
  116458. /* 21 */ "savepoint_opt ::=",
  116459. /* 22 */ "cmd ::= SAVEPOINT nm",
  116460. /* 23 */ "cmd ::= RELEASE savepoint_opt nm",
  116461. /* 24 */ "cmd ::= ROLLBACK trans_opt TO savepoint_opt nm",
  116462. /* 25 */ "cmd ::= create_table create_table_args",
  116463. /* 26 */ "create_table ::= createkw temp TABLE ifnotexists nm dbnm",
  116464. /* 27 */ "createkw ::= CREATE",
  116465. /* 28 */ "ifnotexists ::=",
  116466. /* 29 */ "ifnotexists ::= IF NOT EXISTS",
  116467. /* 30 */ "temp ::= TEMP",
  116468. /* 31 */ "temp ::=",
  116469. /* 32 */ "create_table_args ::= LP columnlist conslist_opt RP table_options",
  116470. /* 33 */ "create_table_args ::= AS select",
  116471. /* 34 */ "table_options ::=",
  116472. /* 35 */ "table_options ::= WITHOUT nm",
  116473. /* 36 */ "columnlist ::= columnlist COMMA column",
  116474. /* 37 */ "columnlist ::= column",
  116475. /* 38 */ "column ::= columnid type carglist",
  116476. /* 39 */ "columnid ::= nm",
  116477. /* 40 */ "nm ::= ID|INDEXED",
  116478. /* 41 */ "nm ::= STRING",
  116479. /* 42 */ "nm ::= JOIN_KW",
  116480. /* 43 */ "type ::=",
  116481. /* 44 */ "type ::= typetoken",
  116482. /* 45 */ "typetoken ::= typename",
  116483. /* 46 */ "typetoken ::= typename LP signed RP",
  116484. /* 47 */ "typetoken ::= typename LP signed COMMA signed RP",
  116485. /* 48 */ "typename ::= ID|STRING",
  116486. /* 49 */ "typename ::= typename ID|STRING",
  116487. /* 50 */ "signed ::= plus_num",
  116488. /* 51 */ "signed ::= minus_num",
  116489. /* 52 */ "carglist ::= carglist ccons",
  116490. /* 53 */ "carglist ::=",
  116491. /* 54 */ "ccons ::= CONSTRAINT nm",
  116492. /* 55 */ "ccons ::= DEFAULT term",
  116493. /* 56 */ "ccons ::= DEFAULT LP expr RP",
  116494. /* 57 */ "ccons ::= DEFAULT PLUS term",
  116495. /* 58 */ "ccons ::= DEFAULT MINUS term",
  116496. /* 59 */ "ccons ::= DEFAULT ID|INDEXED",
  116497. /* 60 */ "ccons ::= NULL onconf",
  116498. /* 61 */ "ccons ::= NOT NULL onconf",
  116499. /* 62 */ "ccons ::= PRIMARY KEY sortorder onconf autoinc",
  116500. /* 63 */ "ccons ::= UNIQUE onconf",
  116501. /* 64 */ "ccons ::= CHECK LP expr RP",
  116502. /* 65 */ "ccons ::= REFERENCES nm idxlist_opt refargs",
  116503. /* 66 */ "ccons ::= defer_subclause",
  116504. /* 67 */ "ccons ::= COLLATE ID|STRING",
  116505. /* 68 */ "autoinc ::=",
  116506. /* 69 */ "autoinc ::= AUTOINCR",
  116507. /* 70 */ "refargs ::=",
  116508. /* 71 */ "refargs ::= refargs refarg",
  116509. /* 72 */ "refarg ::= MATCH nm",
  116510. /* 73 */ "refarg ::= ON INSERT refact",
  116511. /* 74 */ "refarg ::= ON DELETE refact",
  116512. /* 75 */ "refarg ::= ON UPDATE refact",
  116513. /* 76 */ "refact ::= SET NULL",
  116514. /* 77 */ "refact ::= SET DEFAULT",
  116515. /* 78 */ "refact ::= CASCADE",
  116516. /* 79 */ "refact ::= RESTRICT",
  116517. /* 80 */ "refact ::= NO ACTION",
  116518. /* 81 */ "defer_subclause ::= NOT DEFERRABLE init_deferred_pred_opt",
  116519. /* 82 */ "defer_subclause ::= DEFERRABLE init_deferred_pred_opt",
  116520. /* 83 */ "init_deferred_pred_opt ::=",
  116521. /* 84 */ "init_deferred_pred_opt ::= INITIALLY DEFERRED",
  116522. /* 85 */ "init_deferred_pred_opt ::= INITIALLY IMMEDIATE",
  116523. /* 86 */ "conslist_opt ::=",
  116524. /* 87 */ "conslist_opt ::= COMMA conslist",
  116525. /* 88 */ "conslist ::= conslist tconscomma tcons",
  116526. /* 89 */ "conslist ::= tcons",
  116527. /* 90 */ "tconscomma ::= COMMA",
  116528. /* 91 */ "tconscomma ::=",
  116529. /* 92 */ "tcons ::= CONSTRAINT nm",
  116530. /* 93 */ "tcons ::= PRIMARY KEY LP idxlist autoinc RP onconf",
  116531. /* 94 */ "tcons ::= UNIQUE LP idxlist RP onconf",
  116532. /* 95 */ "tcons ::= CHECK LP expr RP onconf",
  116533. /* 96 */ "tcons ::= FOREIGN KEY LP idxlist RP REFERENCES nm idxlist_opt refargs defer_subclause_opt",
  116534. /* 97 */ "defer_subclause_opt ::=",
  116535. /* 98 */ "defer_subclause_opt ::= defer_subclause",
  116536. /* 99 */ "onconf ::=",
  116537. /* 100 */ "onconf ::= ON CONFLICT resolvetype",
  116538. /* 101 */ "orconf ::=",
  116539. /* 102 */ "orconf ::= OR resolvetype",
  116540. /* 103 */ "resolvetype ::= raisetype",
  116541. /* 104 */ "resolvetype ::= IGNORE",
  116542. /* 105 */ "resolvetype ::= REPLACE",
  116543. /* 106 */ "cmd ::= DROP TABLE ifexists fullname",
  116544. /* 107 */ "ifexists ::= IF EXISTS",
  116545. /* 108 */ "ifexists ::=",
  116546. /* 109 */ "cmd ::= createkw temp VIEW ifnotexists nm dbnm AS select",
  116547. /* 110 */ "cmd ::= DROP VIEW ifexists fullname",
  116548. /* 111 */ "cmd ::= select",
  116549. /* 112 */ "select ::= with selectnowith",
  116550. /* 113 */ "selectnowith ::= oneselect",
  116551. /* 114 */ "selectnowith ::= selectnowith multiselect_op oneselect",
  116552. /* 115 */ "multiselect_op ::= UNION",
  116553. /* 116 */ "multiselect_op ::= UNION ALL",
  116554. /* 117 */ "multiselect_op ::= EXCEPT|INTERSECT",
  116555. /* 118 */ "oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt orderby_opt limit_opt",
  116556. /* 119 */ "oneselect ::= values",
  116557. /* 120 */ "values ::= VALUES LP nexprlist RP",
  116558. /* 121 */ "values ::= values COMMA LP exprlist RP",
  116559. /* 122 */ "distinct ::= DISTINCT",
  116560. /* 123 */ "distinct ::= ALL",
  116561. /* 124 */ "distinct ::=",
  116562. /* 125 */ "sclp ::= selcollist COMMA",
  116563. /* 126 */ "sclp ::=",
  116564. /* 127 */ "selcollist ::= sclp expr as",
  116565. /* 128 */ "selcollist ::= sclp STAR",
  116566. /* 129 */ "selcollist ::= sclp nm DOT STAR",
  116567. /* 130 */ "as ::= AS nm",
  116568. /* 131 */ "as ::= ID|STRING",
  116569. /* 132 */ "as ::=",
  116570. /* 133 */ "from ::=",
  116571. /* 134 */ "from ::= FROM seltablist",
  116572. /* 135 */ "stl_prefix ::= seltablist joinop",
  116573. /* 136 */ "stl_prefix ::=",
  116574. /* 137 */ "seltablist ::= stl_prefix nm dbnm as indexed_opt on_opt using_opt",
  116575. /* 138 */ "seltablist ::= stl_prefix LP select RP as on_opt using_opt",
  116576. /* 139 */ "seltablist ::= stl_prefix LP seltablist RP as on_opt using_opt",
  116577. /* 140 */ "dbnm ::=",
  116578. /* 141 */ "dbnm ::= DOT nm",
  116579. /* 142 */ "fullname ::= nm dbnm",
  116580. /* 143 */ "joinop ::= COMMA|JOIN",
  116581. /* 144 */ "joinop ::= JOIN_KW JOIN",
  116582. /* 145 */ "joinop ::= JOIN_KW nm JOIN",
  116583. /* 146 */ "joinop ::= JOIN_KW nm nm JOIN",
  116584. /* 147 */ "on_opt ::= ON expr",
  116585. /* 148 */ "on_opt ::=",
  116586. /* 149 */ "indexed_opt ::=",
  116587. /* 150 */ "indexed_opt ::= INDEXED BY nm",
  116588. /* 151 */ "indexed_opt ::= NOT INDEXED",
  116589. /* 152 */ "using_opt ::= USING LP idlist RP",
  116590. /* 153 */ "using_opt ::=",
  116591. /* 154 */ "orderby_opt ::=",
  116592. /* 155 */ "orderby_opt ::= ORDER BY sortlist",
  116593. /* 156 */ "sortlist ::= sortlist COMMA expr sortorder",
  116594. /* 157 */ "sortlist ::= expr sortorder",
  116595. /* 158 */ "sortorder ::= ASC",
  116596. /* 159 */ "sortorder ::= DESC",
  116597. /* 160 */ "sortorder ::=",
  116598. /* 161 */ "groupby_opt ::=",
  116599. /* 162 */ "groupby_opt ::= GROUP BY nexprlist",
  116600. /* 163 */ "having_opt ::=",
  116601. /* 164 */ "having_opt ::= HAVING expr",
  116602. /* 165 */ "limit_opt ::=",
  116603. /* 166 */ "limit_opt ::= LIMIT expr",
  116604. /* 167 */ "limit_opt ::= LIMIT expr OFFSET expr",
  116605. /* 168 */ "limit_opt ::= LIMIT expr COMMA expr",
  116606. /* 169 */ "cmd ::= with DELETE FROM fullname indexed_opt where_opt",
  116607. /* 170 */ "where_opt ::=",
  116608. /* 171 */ "where_opt ::= WHERE expr",
  116609. /* 172 */ "cmd ::= with UPDATE orconf fullname indexed_opt SET setlist where_opt",
  116610. /* 173 */ "setlist ::= setlist COMMA nm EQ expr",
  116611. /* 174 */ "setlist ::= nm EQ expr",
  116612. /* 175 */ "cmd ::= with insert_cmd INTO fullname inscollist_opt select",
  116613. /* 176 */ "cmd ::= with insert_cmd INTO fullname inscollist_opt DEFAULT VALUES",
  116614. /* 177 */ "insert_cmd ::= INSERT orconf",
  116615. /* 178 */ "insert_cmd ::= REPLACE",
  116616. /* 179 */ "inscollist_opt ::=",
  116617. /* 180 */ "inscollist_opt ::= LP idlist RP",
  116618. /* 181 */ "idlist ::= idlist COMMA nm",
  116619. /* 182 */ "idlist ::= nm",
  116620. /* 183 */ "expr ::= term",
  116621. /* 184 */ "expr ::= LP expr RP",
  116622. /* 185 */ "term ::= NULL",
  116623. /* 186 */ "expr ::= ID|INDEXED",
  116624. /* 187 */ "expr ::= JOIN_KW",
  116625. /* 188 */ "expr ::= nm DOT nm",
  116626. /* 189 */ "expr ::= nm DOT nm DOT nm",
  116627. /* 190 */ "term ::= INTEGER|FLOAT|BLOB",
  116628. /* 191 */ "term ::= STRING",
  116629. /* 192 */ "expr ::= VARIABLE",
  116630. /* 193 */ "expr ::= expr COLLATE ID|STRING",
  116631. /* 194 */ "expr ::= CAST LP expr AS typetoken RP",
  116632. /* 195 */ "expr ::= ID|INDEXED LP distinct exprlist RP",
  116633. /* 196 */ "expr ::= ID|INDEXED LP STAR RP",
  116634. /* 197 */ "term ::= CTIME_KW",
  116635. /* 198 */ "expr ::= expr AND expr",
  116636. /* 199 */ "expr ::= expr OR expr",
  116637. /* 200 */ "expr ::= expr LT|GT|GE|LE expr",
  116638. /* 201 */ "expr ::= expr EQ|NE expr",
  116639. /* 202 */ "expr ::= expr BITAND|BITOR|LSHIFT|RSHIFT expr",
  116640. /* 203 */ "expr ::= expr PLUS|MINUS expr",
  116641. /* 204 */ "expr ::= expr STAR|SLASH|REM expr",
  116642. /* 205 */ "expr ::= expr CONCAT expr",
  116643. /* 206 */ "likeop ::= LIKE_KW|MATCH",
  116644. /* 207 */ "likeop ::= NOT LIKE_KW|MATCH",
  116645. /* 208 */ "expr ::= expr likeop expr",
  116646. /* 209 */ "expr ::= expr likeop expr ESCAPE expr",
  116647. /* 210 */ "expr ::= expr ISNULL|NOTNULL",
  116648. /* 211 */ "expr ::= expr NOT NULL",
  116649. /* 212 */ "expr ::= expr IS expr",
  116650. /* 213 */ "expr ::= expr IS NOT expr",
  116651. /* 214 */ "expr ::= NOT expr",
  116652. /* 215 */ "expr ::= BITNOT expr",
  116653. /* 216 */ "expr ::= MINUS expr",
  116654. /* 217 */ "expr ::= PLUS expr",
  116655. /* 218 */ "between_op ::= BETWEEN",
  116656. /* 219 */ "between_op ::= NOT BETWEEN",
  116657. /* 220 */ "expr ::= expr between_op expr AND expr",
  116658. /* 221 */ "in_op ::= IN",
  116659. /* 222 */ "in_op ::= NOT IN",
  116660. /* 223 */ "expr ::= expr in_op LP exprlist RP",
  116661. /* 224 */ "expr ::= LP select RP",
  116662. /* 225 */ "expr ::= expr in_op LP select RP",
  116663. /* 226 */ "expr ::= expr in_op nm dbnm",
  116664. /* 227 */ "expr ::= EXISTS LP select RP",
  116665. /* 228 */ "expr ::= CASE case_operand case_exprlist case_else END",
  116666. /* 229 */ "case_exprlist ::= case_exprlist WHEN expr THEN expr",
  116667. /* 230 */ "case_exprlist ::= WHEN expr THEN expr",
  116668. /* 231 */ "case_else ::= ELSE expr",
  116669. /* 232 */ "case_else ::=",
  116670. /* 233 */ "case_operand ::= expr",
  116671. /* 234 */ "case_operand ::=",
  116672. /* 235 */ "exprlist ::= nexprlist",
  116673. /* 236 */ "exprlist ::=",
  116674. /* 237 */ "nexprlist ::= nexprlist COMMA expr",
  116675. /* 238 */ "nexprlist ::= expr",
  116676. /* 239 */ "cmd ::= createkw uniqueflag INDEX ifnotexists nm dbnm ON nm LP idxlist RP where_opt",
  116677. /* 240 */ "uniqueflag ::= UNIQUE",
  116678. /* 241 */ "uniqueflag ::=",
  116679. /* 242 */ "idxlist_opt ::=",
  116680. /* 243 */ "idxlist_opt ::= LP idxlist RP",
  116681. /* 244 */ "idxlist ::= idxlist COMMA nm collate sortorder",
  116682. /* 245 */ "idxlist ::= nm collate sortorder",
  116683. /* 246 */ "collate ::=",
  116684. /* 247 */ "collate ::= COLLATE ID|STRING",
  116685. /* 248 */ "cmd ::= DROP INDEX ifexists fullname",
  116686. /* 249 */ "cmd ::= VACUUM",
  116687. /* 250 */ "cmd ::= VACUUM nm",
  116688. /* 251 */ "cmd ::= PRAGMA nm dbnm",
  116689. /* 252 */ "cmd ::= PRAGMA nm dbnm EQ nmnum",
  116690. /* 253 */ "cmd ::= PRAGMA nm dbnm LP nmnum RP",
  116691. /* 254 */ "cmd ::= PRAGMA nm dbnm EQ minus_num",
  116692. /* 255 */ "cmd ::= PRAGMA nm dbnm LP minus_num RP",
  116693. /* 256 */ "nmnum ::= plus_num",
  116694. /* 257 */ "nmnum ::= nm",
  116695. /* 258 */ "nmnum ::= ON",
  116696. /* 259 */ "nmnum ::= DELETE",
  116697. /* 260 */ "nmnum ::= DEFAULT",
  116698. /* 261 */ "plus_num ::= PLUS INTEGER|FLOAT",
  116699. /* 262 */ "plus_num ::= INTEGER|FLOAT",
  116700. /* 263 */ "minus_num ::= MINUS INTEGER|FLOAT",
  116701. /* 264 */ "cmd ::= createkw trigger_decl BEGIN trigger_cmd_list END",
  116702. /* 265 */ "trigger_decl ::= temp TRIGGER ifnotexists nm dbnm trigger_time trigger_event ON fullname foreach_clause when_clause",
  116703. /* 266 */ "trigger_time ::= BEFORE",
  116704. /* 267 */ "trigger_time ::= AFTER",
  116705. /* 268 */ "trigger_time ::= INSTEAD OF",
  116706. /* 269 */ "trigger_time ::=",
  116707. /* 270 */ "trigger_event ::= DELETE|INSERT",
  116708. /* 271 */ "trigger_event ::= UPDATE",
  116709. /* 272 */ "trigger_event ::= UPDATE OF idlist",
  116710. /* 273 */ "foreach_clause ::=",
  116711. /* 274 */ "foreach_clause ::= FOR EACH ROW",
  116712. /* 275 */ "when_clause ::=",
  116713. /* 276 */ "when_clause ::= WHEN expr",
  116714. /* 277 */ "trigger_cmd_list ::= trigger_cmd_list trigger_cmd SEMI",
  116715. /* 278 */ "trigger_cmd_list ::= trigger_cmd SEMI",
  116716. /* 279 */ "trnm ::= nm",
  116717. /* 280 */ "trnm ::= nm DOT nm",
  116718. /* 281 */ "tridxby ::=",
  116719. /* 282 */ "tridxby ::= INDEXED BY nm",
  116720. /* 283 */ "tridxby ::= NOT INDEXED",
  116721. /* 284 */ "trigger_cmd ::= UPDATE orconf trnm tridxby SET setlist where_opt",
  116722. /* 285 */ "trigger_cmd ::= insert_cmd INTO trnm inscollist_opt select",
  116723. /* 286 */ "trigger_cmd ::= DELETE FROM trnm tridxby where_opt",
  116724. /* 287 */ "trigger_cmd ::= select",
  116725. /* 288 */ "expr ::= RAISE LP IGNORE RP",
  116726. /* 289 */ "expr ::= RAISE LP raisetype COMMA nm RP",
  116727. /* 290 */ "raisetype ::= ROLLBACK",
  116728. /* 291 */ "raisetype ::= ABORT",
  116729. /* 292 */ "raisetype ::= FAIL",
  116730. /* 293 */ "cmd ::= DROP TRIGGER ifexists fullname",
  116731. /* 294 */ "cmd ::= ATTACH database_kw_opt expr AS expr key_opt",
  116732. /* 295 */ "cmd ::= DETACH database_kw_opt expr",
  116733. /* 296 */ "key_opt ::=",
  116734. /* 297 */ "key_opt ::= KEY expr",
  116735. /* 298 */ "database_kw_opt ::= DATABASE",
  116736. /* 299 */ "database_kw_opt ::=",
  116737. /* 300 */ "cmd ::= REINDEX",
  116738. /* 301 */ "cmd ::= REINDEX nm dbnm",
  116739. /* 302 */ "cmd ::= ANALYZE",
  116740. /* 303 */ "cmd ::= ANALYZE nm dbnm",
  116741. /* 304 */ "cmd ::= ALTER TABLE fullname RENAME TO nm",
  116742. /* 305 */ "cmd ::= ALTER TABLE add_column_fullname ADD kwcolumn_opt column",
  116743. /* 306 */ "add_column_fullname ::= fullname",
  116744. /* 307 */ "kwcolumn_opt ::=",
  116745. /* 308 */ "kwcolumn_opt ::= COLUMNKW",
  116746. /* 309 */ "cmd ::= create_vtab",
  116747. /* 310 */ "cmd ::= create_vtab LP vtabarglist RP",
  116748. /* 311 */ "create_vtab ::= createkw VIRTUAL TABLE ifnotexists nm dbnm USING nm",
  116749. /* 312 */ "vtabarglist ::= vtabarg",
  116750. /* 313 */ "vtabarglist ::= vtabarglist COMMA vtabarg",
  116751. /* 314 */ "vtabarg ::=",
  116752. /* 315 */ "vtabarg ::= vtabarg vtabargtoken",
  116753. /* 316 */ "vtabargtoken ::= ANY",
  116754. /* 317 */ "vtabargtoken ::= lp anylist RP",
  116755. /* 318 */ "lp ::= LP",
  116756. /* 319 */ "anylist ::=",
  116757. /* 320 */ "anylist ::= anylist LP anylist RP",
  116758. /* 321 */ "anylist ::= anylist ANY",
  116759. /* 322 */ "with ::=",
  116760. /* 323 */ "with ::= WITH wqlist",
  116761. /* 324 */ "with ::= WITH RECURSIVE wqlist",
  116762. /* 325 */ "wqlist ::= nm idxlist_opt AS LP select RP",
  116763. /* 326 */ "wqlist ::= wqlist COMMA nm idxlist_opt AS LP select RP",
  116764. };
  116765. #endif /* NDEBUG */
  116766. #if YYSTACKDEPTH<=0
  116767. /*
  116768. ** Try to increase the size of the parser stack.
  116769. */
  116770. static void yyGrowStack(yyParser *p){
  116771. int newSize;
  116772. yyStackEntry *pNew;
  116773. newSize = p->yystksz*2 + 100;
  116774. pNew = realloc(p->yystack, newSize*sizeof(pNew[0]));
  116775. if( pNew ){
  116776. p->yystack = pNew;
  116777. p->yystksz = newSize;
  116778. #ifndef NDEBUG
  116779. if( yyTraceFILE ){
  116780. fprintf(yyTraceFILE,"%sStack grows to %d entries!\n",
  116781. yyTracePrompt, p->yystksz);
  116782. }
  116783. #endif
  116784. }
  116785. }
  116786. #endif
  116787. /*
  116788. ** This function allocates a new parser.
  116789. ** The only argument is a pointer to a function which works like
  116790. ** malloc.
  116791. **
  116792. ** Inputs:
  116793. ** A pointer to the function used to allocate memory.
  116794. **
  116795. ** Outputs:
  116796. ** A pointer to a parser. This pointer is used in subsequent calls
  116797. ** to sqlite3Parser and sqlite3ParserFree.
  116798. */
  116799. SQLITE_PRIVATE void *sqlite3ParserAlloc(void *(*mallocProc)(u64)){
  116800. yyParser *pParser;
  116801. pParser = (yyParser*)(*mallocProc)( (u64)sizeof(yyParser) );
  116802. if( pParser ){
  116803. pParser->yyidx = -1;
  116804. #ifdef YYTRACKMAXSTACKDEPTH
  116805. pParser->yyidxMax = 0;
  116806. #endif
  116807. #if YYSTACKDEPTH<=0
  116808. pParser->yystack = NULL;
  116809. pParser->yystksz = 0;
  116810. yyGrowStack(pParser);
  116811. #endif
  116812. }
  116813. return pParser;
  116814. }
  116815. /* The following function deletes the value associated with a
  116816. ** symbol. The symbol can be either a terminal or nonterminal.
  116817. ** "yymajor" is the symbol code, and "yypminor" is a pointer to
  116818. ** the value.
  116819. */
  116820. static void yy_destructor(
  116821. yyParser *yypParser, /* The parser */
  116822. YYCODETYPE yymajor, /* Type code for object to destroy */
  116823. YYMINORTYPE *yypminor /* The object to be destroyed */
  116824. ){
  116825. sqlite3ParserARG_FETCH;
  116826. switch( yymajor ){
  116827. /* Here is inserted the actions which take place when a
  116828. ** terminal or non-terminal is destroyed. This can happen
  116829. ** when the symbol is popped from the stack during a
  116830. ** reduce or during error processing or when a parser is
  116831. ** being destroyed before it is finished parsing.
  116832. **
  116833. ** Note: during a reduce, the only symbols destroyed are those
  116834. ** which appear on the RHS of the rule, but which are not used
  116835. ** inside the C code.
  116836. */
  116837. case 163: /* select */
  116838. case 195: /* selectnowith */
  116839. case 196: /* oneselect */
  116840. case 207: /* values */
  116841. {
  116842. sqlite3SelectDelete(pParse->db, (yypminor->yy3));
  116843. }
  116844. break;
  116845. case 174: /* term */
  116846. case 175: /* expr */
  116847. {
  116848. sqlite3ExprDelete(pParse->db, (yypminor->yy346).pExpr);
  116849. }
  116850. break;
  116851. case 179: /* idxlist_opt */
  116852. case 188: /* idxlist */
  116853. case 200: /* selcollist */
  116854. case 203: /* groupby_opt */
  116855. case 205: /* orderby_opt */
  116856. case 208: /* nexprlist */
  116857. case 209: /* exprlist */
  116858. case 210: /* sclp */
  116859. case 220: /* sortlist */
  116860. case 221: /* setlist */
  116861. case 228: /* case_exprlist */
  116862. {
  116863. sqlite3ExprListDelete(pParse->db, (yypminor->yy14));
  116864. }
  116865. break;
  116866. case 194: /* fullname */
  116867. case 201: /* from */
  116868. case 212: /* seltablist */
  116869. case 213: /* stl_prefix */
  116870. {
  116871. sqlite3SrcListDelete(pParse->db, (yypminor->yy65));
  116872. }
  116873. break;
  116874. case 197: /* with */
  116875. case 252: /* wqlist */
  116876. {
  116877. sqlite3WithDelete(pParse->db, (yypminor->yy59));
  116878. }
  116879. break;
  116880. case 202: /* where_opt */
  116881. case 204: /* having_opt */
  116882. case 216: /* on_opt */
  116883. case 227: /* case_operand */
  116884. case 229: /* case_else */
  116885. case 238: /* when_clause */
  116886. case 243: /* key_opt */
  116887. {
  116888. sqlite3ExprDelete(pParse->db, (yypminor->yy132));
  116889. }
  116890. break;
  116891. case 217: /* using_opt */
  116892. case 219: /* idlist */
  116893. case 223: /* inscollist_opt */
  116894. {
  116895. sqlite3IdListDelete(pParse->db, (yypminor->yy408));
  116896. }
  116897. break;
  116898. case 234: /* trigger_cmd_list */
  116899. case 239: /* trigger_cmd */
  116900. {
  116901. sqlite3DeleteTriggerStep(pParse->db, (yypminor->yy473));
  116902. }
  116903. break;
  116904. case 236: /* trigger_event */
  116905. {
  116906. sqlite3IdListDelete(pParse->db, (yypminor->yy378).b);
  116907. }
  116908. break;
  116909. default: break; /* If no destructor action specified: do nothing */
  116910. }
  116911. }
  116912. /*
  116913. ** Pop the parser's stack once.
  116914. **
  116915. ** If there is a destructor routine associated with the token which
  116916. ** is popped from the stack, then call it.
  116917. **
  116918. ** Return the major token number for the symbol popped.
  116919. */
  116920. static int yy_pop_parser_stack(yyParser *pParser){
  116921. YYCODETYPE yymajor;
  116922. yyStackEntry *yytos = &pParser->yystack[pParser->yyidx];
  116923. /* There is no mechanism by which the parser stack can be popped below
  116924. ** empty in SQLite. */
  116925. if( NEVER(pParser->yyidx<0) ) return 0;
  116926. #ifndef NDEBUG
  116927. if( yyTraceFILE && pParser->yyidx>=0 ){
  116928. fprintf(yyTraceFILE,"%sPopping %s\n",
  116929. yyTracePrompt,
  116930. yyTokenName[yytos->major]);
  116931. }
  116932. #endif
  116933. yymajor = yytos->major;
  116934. yy_destructor(pParser, yymajor, &yytos->minor);
  116935. pParser->yyidx--;
  116936. return yymajor;
  116937. }
  116938. /*
  116939. ** Deallocate and destroy a parser. Destructors are all called for
  116940. ** all stack elements before shutting the parser down.
  116941. **
  116942. ** Inputs:
  116943. ** <ul>
  116944. ** <li> A pointer to the parser. This should be a pointer
  116945. ** obtained from sqlite3ParserAlloc.
  116946. ** <li> A pointer to a function used to reclaim memory obtained
  116947. ** from malloc.
  116948. ** </ul>
  116949. */
  116950. SQLITE_PRIVATE void sqlite3ParserFree(
  116951. void *p, /* The parser to be deleted */
  116952. void (*freeProc)(void*) /* Function used to reclaim memory */
  116953. ){
  116954. yyParser *pParser = (yyParser*)p;
  116955. /* In SQLite, we never try to destroy a parser that was not successfully
  116956. ** created in the first place. */
  116957. if( NEVER(pParser==0) ) return;
  116958. while( pParser->yyidx>=0 ) yy_pop_parser_stack(pParser);
  116959. #if YYSTACKDEPTH<=0
  116960. free(pParser->yystack);
  116961. #endif
  116962. (*freeProc)((void*)pParser);
  116963. }
  116964. /*
  116965. ** Return the peak depth of the stack for a parser.
  116966. */
  116967. #ifdef YYTRACKMAXSTACKDEPTH
  116968. SQLITE_PRIVATE int sqlite3ParserStackPeak(void *p){
  116969. yyParser *pParser = (yyParser*)p;
  116970. return pParser->yyidxMax;
  116971. }
  116972. #endif
  116973. /*
  116974. ** Find the appropriate action for a parser given the terminal
  116975. ** look-ahead token iLookAhead.
  116976. **
  116977. ** If the look-ahead token is YYNOCODE, then check to see if the action is
  116978. ** independent of the look-ahead. If it is, return the action, otherwise
  116979. ** return YY_NO_ACTION.
  116980. */
  116981. static int yy_find_shift_action(
  116982. yyParser *pParser, /* The parser */
  116983. YYCODETYPE iLookAhead /* The look-ahead token */
  116984. ){
  116985. int i;
  116986. int stateno = pParser->yystack[pParser->yyidx].stateno;
  116987. if( stateno>YY_SHIFT_COUNT
  116988. || (i = yy_shift_ofst[stateno])==YY_SHIFT_USE_DFLT ){
  116989. return yy_default[stateno];
  116990. }
  116991. assert( iLookAhead!=YYNOCODE );
  116992. i += iLookAhead;
  116993. if( i<0 || i>=YY_ACTTAB_COUNT || yy_lookahead[i]!=iLookAhead ){
  116994. if( iLookAhead>0 ){
  116995. #ifdef YYFALLBACK
  116996. YYCODETYPE iFallback; /* Fallback token */
  116997. if( iLookAhead<sizeof(yyFallback)/sizeof(yyFallback[0])
  116998. && (iFallback = yyFallback[iLookAhead])!=0 ){
  116999. #ifndef NDEBUG
  117000. if( yyTraceFILE ){
  117001. fprintf(yyTraceFILE, "%sFALLBACK %s => %s\n",
  117002. yyTracePrompt, yyTokenName[iLookAhead], yyTokenName[iFallback]);
  117003. }
  117004. #endif
  117005. return yy_find_shift_action(pParser, iFallback);
  117006. }
  117007. #endif
  117008. #ifdef YYWILDCARD
  117009. {
  117010. int j = i - iLookAhead + YYWILDCARD;
  117011. if(
  117012. #if YY_SHIFT_MIN+YYWILDCARD<0
  117013. j>=0 &&
  117014. #endif
  117015. #if YY_SHIFT_MAX+YYWILDCARD>=YY_ACTTAB_COUNT
  117016. j<YY_ACTTAB_COUNT &&
  117017. #endif
  117018. yy_lookahead[j]==YYWILDCARD
  117019. ){
  117020. #ifndef NDEBUG
  117021. if( yyTraceFILE ){
  117022. fprintf(yyTraceFILE, "%sWILDCARD %s => %s\n",
  117023. yyTracePrompt, yyTokenName[iLookAhead], yyTokenName[YYWILDCARD]);
  117024. }
  117025. #endif /* NDEBUG */
  117026. return yy_action[j];
  117027. }
  117028. }
  117029. #endif /* YYWILDCARD */
  117030. }
  117031. return yy_default[stateno];
  117032. }else{
  117033. return yy_action[i];
  117034. }
  117035. }
  117036. /*
  117037. ** Find the appropriate action for a parser given the non-terminal
  117038. ** look-ahead token iLookAhead.
  117039. **
  117040. ** If the look-ahead token is YYNOCODE, then check to see if the action is
  117041. ** independent of the look-ahead. If it is, return the action, otherwise
  117042. ** return YY_NO_ACTION.
  117043. */
  117044. static int yy_find_reduce_action(
  117045. int stateno, /* Current state number */
  117046. YYCODETYPE iLookAhead /* The look-ahead token */
  117047. ){
  117048. int i;
  117049. #ifdef YYERRORSYMBOL
  117050. if( stateno>YY_REDUCE_COUNT ){
  117051. return yy_default[stateno];
  117052. }
  117053. #else
  117054. assert( stateno<=YY_REDUCE_COUNT );
  117055. #endif
  117056. i = yy_reduce_ofst[stateno];
  117057. assert( i!=YY_REDUCE_USE_DFLT );
  117058. assert( iLookAhead!=YYNOCODE );
  117059. i += iLookAhead;
  117060. #ifdef YYERRORSYMBOL
  117061. if( i<0 || i>=YY_ACTTAB_COUNT || yy_lookahead[i]!=iLookAhead ){
  117062. return yy_default[stateno];
  117063. }
  117064. #else
  117065. assert( i>=0 && i<YY_ACTTAB_COUNT );
  117066. assert( yy_lookahead[i]==iLookAhead );
  117067. #endif
  117068. return yy_action[i];
  117069. }
  117070. /*
  117071. ** The following routine is called if the stack overflows.
  117072. */
  117073. static void yyStackOverflow(yyParser *yypParser, YYMINORTYPE *yypMinor){
  117074. sqlite3ParserARG_FETCH;
  117075. yypParser->yyidx--;
  117076. #ifndef NDEBUG
  117077. if( yyTraceFILE ){
  117078. fprintf(yyTraceFILE,"%sStack Overflow!\n",yyTracePrompt);
  117079. }
  117080. #endif
  117081. while( yypParser->yyidx>=0 ) yy_pop_parser_stack(yypParser);
  117082. /* Here code is inserted which will execute if the parser
  117083. ** stack every overflows */
  117084. UNUSED_PARAMETER(yypMinor); /* Silence some compiler warnings */
  117085. sqlite3ErrorMsg(pParse, "parser stack overflow");
  117086. sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument var */
  117087. }
  117088. /*
  117089. ** Perform a shift action.
  117090. */
  117091. static void yy_shift(
  117092. yyParser *yypParser, /* The parser to be shifted */
  117093. int yyNewState, /* The new state to shift in */
  117094. int yyMajor, /* The major token to shift in */
  117095. YYMINORTYPE *yypMinor /* Pointer to the minor token to shift in */
  117096. ){
  117097. yyStackEntry *yytos;
  117098. yypParser->yyidx++;
  117099. #ifdef YYTRACKMAXSTACKDEPTH
  117100. if( yypParser->yyidx>yypParser->yyidxMax ){
  117101. yypParser->yyidxMax = yypParser->yyidx;
  117102. }
  117103. #endif
  117104. #if YYSTACKDEPTH>0
  117105. if( yypParser->yyidx>=YYSTACKDEPTH ){
  117106. yyStackOverflow(yypParser, yypMinor);
  117107. return;
  117108. }
  117109. #else
  117110. if( yypParser->yyidx>=yypParser->yystksz ){
  117111. yyGrowStack(yypParser);
  117112. if( yypParser->yyidx>=yypParser->yystksz ){
  117113. yyStackOverflow(yypParser, yypMinor);
  117114. return;
  117115. }
  117116. }
  117117. #endif
  117118. yytos = &yypParser->yystack[yypParser->yyidx];
  117119. yytos->stateno = (YYACTIONTYPE)yyNewState;
  117120. yytos->major = (YYCODETYPE)yyMajor;
  117121. yytos->minor = *yypMinor;
  117122. #ifndef NDEBUG
  117123. if( yyTraceFILE && yypParser->yyidx>0 ){
  117124. int i;
  117125. fprintf(yyTraceFILE,"%sShift %d\n",yyTracePrompt,yyNewState);
  117126. fprintf(yyTraceFILE,"%sStack:",yyTracePrompt);
  117127. for(i=1; i<=yypParser->yyidx; i++)
  117128. fprintf(yyTraceFILE," %s",yyTokenName[yypParser->yystack[i].major]);
  117129. fprintf(yyTraceFILE,"\n");
  117130. }
  117131. #endif
  117132. }
  117133. /* The following table contains information about every rule that
  117134. ** is used during the reduce.
  117135. */
  117136. static const struct {
  117137. YYCODETYPE lhs; /* Symbol on the left-hand side of the rule */
  117138. unsigned char nrhs; /* Number of right-hand side symbols in the rule */
  117139. } yyRuleInfo[] = {
  117140. { 144, 1 },
  117141. { 145, 2 },
  117142. { 145, 1 },
  117143. { 146, 1 },
  117144. { 146, 3 },
  117145. { 147, 0 },
  117146. { 147, 1 },
  117147. { 147, 3 },
  117148. { 148, 1 },
  117149. { 149, 3 },
  117150. { 151, 0 },
  117151. { 151, 1 },
  117152. { 151, 2 },
  117153. { 150, 0 },
  117154. { 150, 1 },
  117155. { 150, 1 },
  117156. { 150, 1 },
  117157. { 149, 2 },
  117158. { 149, 2 },
  117159. { 149, 2 },
  117160. { 153, 1 },
  117161. { 153, 0 },
  117162. { 149, 2 },
  117163. { 149, 3 },
  117164. { 149, 5 },
  117165. { 149, 2 },
  117166. { 154, 6 },
  117167. { 156, 1 },
  117168. { 158, 0 },
  117169. { 158, 3 },
  117170. { 157, 1 },
  117171. { 157, 0 },
  117172. { 155, 5 },
  117173. { 155, 2 },
  117174. { 162, 0 },
  117175. { 162, 2 },
  117176. { 160, 3 },
  117177. { 160, 1 },
  117178. { 164, 3 },
  117179. { 165, 1 },
  117180. { 152, 1 },
  117181. { 152, 1 },
  117182. { 152, 1 },
  117183. { 166, 0 },
  117184. { 166, 1 },
  117185. { 168, 1 },
  117186. { 168, 4 },
  117187. { 168, 6 },
  117188. { 169, 1 },
  117189. { 169, 2 },
  117190. { 170, 1 },
  117191. { 170, 1 },
  117192. { 167, 2 },
  117193. { 167, 0 },
  117194. { 173, 2 },
  117195. { 173, 2 },
  117196. { 173, 4 },
  117197. { 173, 3 },
  117198. { 173, 3 },
  117199. { 173, 2 },
  117200. { 173, 2 },
  117201. { 173, 3 },
  117202. { 173, 5 },
  117203. { 173, 2 },
  117204. { 173, 4 },
  117205. { 173, 4 },
  117206. { 173, 1 },
  117207. { 173, 2 },
  117208. { 178, 0 },
  117209. { 178, 1 },
  117210. { 180, 0 },
  117211. { 180, 2 },
  117212. { 182, 2 },
  117213. { 182, 3 },
  117214. { 182, 3 },
  117215. { 182, 3 },
  117216. { 183, 2 },
  117217. { 183, 2 },
  117218. { 183, 1 },
  117219. { 183, 1 },
  117220. { 183, 2 },
  117221. { 181, 3 },
  117222. { 181, 2 },
  117223. { 184, 0 },
  117224. { 184, 2 },
  117225. { 184, 2 },
  117226. { 161, 0 },
  117227. { 161, 2 },
  117228. { 185, 3 },
  117229. { 185, 1 },
  117230. { 186, 1 },
  117231. { 186, 0 },
  117232. { 187, 2 },
  117233. { 187, 7 },
  117234. { 187, 5 },
  117235. { 187, 5 },
  117236. { 187, 10 },
  117237. { 189, 0 },
  117238. { 189, 1 },
  117239. { 176, 0 },
  117240. { 176, 3 },
  117241. { 190, 0 },
  117242. { 190, 2 },
  117243. { 191, 1 },
  117244. { 191, 1 },
  117245. { 191, 1 },
  117246. { 149, 4 },
  117247. { 193, 2 },
  117248. { 193, 0 },
  117249. { 149, 8 },
  117250. { 149, 4 },
  117251. { 149, 1 },
  117252. { 163, 2 },
  117253. { 195, 1 },
  117254. { 195, 3 },
  117255. { 198, 1 },
  117256. { 198, 2 },
  117257. { 198, 1 },
  117258. { 196, 9 },
  117259. { 196, 1 },
  117260. { 207, 4 },
  117261. { 207, 5 },
  117262. { 199, 1 },
  117263. { 199, 1 },
  117264. { 199, 0 },
  117265. { 210, 2 },
  117266. { 210, 0 },
  117267. { 200, 3 },
  117268. { 200, 2 },
  117269. { 200, 4 },
  117270. { 211, 2 },
  117271. { 211, 1 },
  117272. { 211, 0 },
  117273. { 201, 0 },
  117274. { 201, 2 },
  117275. { 213, 2 },
  117276. { 213, 0 },
  117277. { 212, 7 },
  117278. { 212, 7 },
  117279. { 212, 7 },
  117280. { 159, 0 },
  117281. { 159, 2 },
  117282. { 194, 2 },
  117283. { 214, 1 },
  117284. { 214, 2 },
  117285. { 214, 3 },
  117286. { 214, 4 },
  117287. { 216, 2 },
  117288. { 216, 0 },
  117289. { 215, 0 },
  117290. { 215, 3 },
  117291. { 215, 2 },
  117292. { 217, 4 },
  117293. { 217, 0 },
  117294. { 205, 0 },
  117295. { 205, 3 },
  117296. { 220, 4 },
  117297. { 220, 2 },
  117298. { 177, 1 },
  117299. { 177, 1 },
  117300. { 177, 0 },
  117301. { 203, 0 },
  117302. { 203, 3 },
  117303. { 204, 0 },
  117304. { 204, 2 },
  117305. { 206, 0 },
  117306. { 206, 2 },
  117307. { 206, 4 },
  117308. { 206, 4 },
  117309. { 149, 6 },
  117310. { 202, 0 },
  117311. { 202, 2 },
  117312. { 149, 8 },
  117313. { 221, 5 },
  117314. { 221, 3 },
  117315. { 149, 6 },
  117316. { 149, 7 },
  117317. { 222, 2 },
  117318. { 222, 1 },
  117319. { 223, 0 },
  117320. { 223, 3 },
  117321. { 219, 3 },
  117322. { 219, 1 },
  117323. { 175, 1 },
  117324. { 175, 3 },
  117325. { 174, 1 },
  117326. { 175, 1 },
  117327. { 175, 1 },
  117328. { 175, 3 },
  117329. { 175, 5 },
  117330. { 174, 1 },
  117331. { 174, 1 },
  117332. { 175, 1 },
  117333. { 175, 3 },
  117334. { 175, 6 },
  117335. { 175, 5 },
  117336. { 175, 4 },
  117337. { 174, 1 },
  117338. { 175, 3 },
  117339. { 175, 3 },
  117340. { 175, 3 },
  117341. { 175, 3 },
  117342. { 175, 3 },
  117343. { 175, 3 },
  117344. { 175, 3 },
  117345. { 175, 3 },
  117346. { 224, 1 },
  117347. { 224, 2 },
  117348. { 175, 3 },
  117349. { 175, 5 },
  117350. { 175, 2 },
  117351. { 175, 3 },
  117352. { 175, 3 },
  117353. { 175, 4 },
  117354. { 175, 2 },
  117355. { 175, 2 },
  117356. { 175, 2 },
  117357. { 175, 2 },
  117358. { 225, 1 },
  117359. { 225, 2 },
  117360. { 175, 5 },
  117361. { 226, 1 },
  117362. { 226, 2 },
  117363. { 175, 5 },
  117364. { 175, 3 },
  117365. { 175, 5 },
  117366. { 175, 4 },
  117367. { 175, 4 },
  117368. { 175, 5 },
  117369. { 228, 5 },
  117370. { 228, 4 },
  117371. { 229, 2 },
  117372. { 229, 0 },
  117373. { 227, 1 },
  117374. { 227, 0 },
  117375. { 209, 1 },
  117376. { 209, 0 },
  117377. { 208, 3 },
  117378. { 208, 1 },
  117379. { 149, 12 },
  117380. { 230, 1 },
  117381. { 230, 0 },
  117382. { 179, 0 },
  117383. { 179, 3 },
  117384. { 188, 5 },
  117385. { 188, 3 },
  117386. { 231, 0 },
  117387. { 231, 2 },
  117388. { 149, 4 },
  117389. { 149, 1 },
  117390. { 149, 2 },
  117391. { 149, 3 },
  117392. { 149, 5 },
  117393. { 149, 6 },
  117394. { 149, 5 },
  117395. { 149, 6 },
  117396. { 232, 1 },
  117397. { 232, 1 },
  117398. { 232, 1 },
  117399. { 232, 1 },
  117400. { 232, 1 },
  117401. { 171, 2 },
  117402. { 171, 1 },
  117403. { 172, 2 },
  117404. { 149, 5 },
  117405. { 233, 11 },
  117406. { 235, 1 },
  117407. { 235, 1 },
  117408. { 235, 2 },
  117409. { 235, 0 },
  117410. { 236, 1 },
  117411. { 236, 1 },
  117412. { 236, 3 },
  117413. { 237, 0 },
  117414. { 237, 3 },
  117415. { 238, 0 },
  117416. { 238, 2 },
  117417. { 234, 3 },
  117418. { 234, 2 },
  117419. { 240, 1 },
  117420. { 240, 3 },
  117421. { 241, 0 },
  117422. { 241, 3 },
  117423. { 241, 2 },
  117424. { 239, 7 },
  117425. { 239, 5 },
  117426. { 239, 5 },
  117427. { 239, 1 },
  117428. { 175, 4 },
  117429. { 175, 6 },
  117430. { 192, 1 },
  117431. { 192, 1 },
  117432. { 192, 1 },
  117433. { 149, 4 },
  117434. { 149, 6 },
  117435. { 149, 3 },
  117436. { 243, 0 },
  117437. { 243, 2 },
  117438. { 242, 1 },
  117439. { 242, 0 },
  117440. { 149, 1 },
  117441. { 149, 3 },
  117442. { 149, 1 },
  117443. { 149, 3 },
  117444. { 149, 6 },
  117445. { 149, 6 },
  117446. { 244, 1 },
  117447. { 245, 0 },
  117448. { 245, 1 },
  117449. { 149, 1 },
  117450. { 149, 4 },
  117451. { 246, 8 },
  117452. { 247, 1 },
  117453. { 247, 3 },
  117454. { 248, 0 },
  117455. { 248, 2 },
  117456. { 249, 1 },
  117457. { 249, 3 },
  117458. { 250, 1 },
  117459. { 251, 0 },
  117460. { 251, 4 },
  117461. { 251, 2 },
  117462. { 197, 0 },
  117463. { 197, 2 },
  117464. { 197, 3 },
  117465. { 252, 6 },
  117466. { 252, 8 },
  117467. };
  117468. static void yy_accept(yyParser*); /* Forward Declaration */
  117469. /*
  117470. ** Perform a reduce action and the shift that must immediately
  117471. ** follow the reduce.
  117472. */
  117473. static void yy_reduce(
  117474. yyParser *yypParser, /* The parser */
  117475. int yyruleno /* Number of the rule by which to reduce */
  117476. ){
  117477. int yygoto; /* The next state */
  117478. int yyact; /* The next action */
  117479. YYMINORTYPE yygotominor; /* The LHS of the rule reduced */
  117480. yyStackEntry *yymsp; /* The top of the parser's stack */
  117481. int yysize; /* Amount to pop the stack */
  117482. sqlite3ParserARG_FETCH;
  117483. yymsp = &yypParser->yystack[yypParser->yyidx];
  117484. #ifndef NDEBUG
  117485. if( yyTraceFILE && yyruleno>=0
  117486. && yyruleno<(int)(sizeof(yyRuleName)/sizeof(yyRuleName[0])) ){
  117487. fprintf(yyTraceFILE, "%sReduce [%s].\n", yyTracePrompt,
  117488. yyRuleName[yyruleno]);
  117489. }
  117490. #endif /* NDEBUG */
  117491. /* Silence complaints from purify about yygotominor being uninitialized
  117492. ** in some cases when it is copied into the stack after the following
  117493. ** switch. yygotominor is uninitialized when a rule reduces that does
  117494. ** not set the value of its left-hand side nonterminal. Leaving the
  117495. ** value of the nonterminal uninitialized is utterly harmless as long
  117496. ** as the value is never used. So really the only thing this code
  117497. ** accomplishes is to quieten purify.
  117498. **
  117499. ** 2007-01-16: The wireshark project (www.wireshark.org) reports that
  117500. ** without this code, their parser segfaults. I'm not sure what there
  117501. ** parser is doing to make this happen. This is the second bug report
  117502. ** from wireshark this week. Clearly they are stressing Lemon in ways
  117503. ** that it has not been previously stressed... (SQLite ticket #2172)
  117504. */
  117505. /*memset(&yygotominor, 0, sizeof(yygotominor));*/
  117506. yygotominor = yyzerominor;
  117507. switch( yyruleno ){
  117508. /* Beginning here are the reduction cases. A typical example
  117509. ** follows:
  117510. ** case 0:
  117511. ** #line <lineno> <grammarfile>
  117512. ** { ... } // User supplied code
  117513. ** #line <lineno> <thisfile>
  117514. ** break;
  117515. */
  117516. case 5: /* explain ::= */
  117517. { sqlite3BeginParse(pParse, 0); }
  117518. break;
  117519. case 6: /* explain ::= EXPLAIN */
  117520. { sqlite3BeginParse(pParse, 1); }
  117521. break;
  117522. case 7: /* explain ::= EXPLAIN QUERY PLAN */
  117523. { sqlite3BeginParse(pParse, 2); }
  117524. break;
  117525. case 8: /* cmdx ::= cmd */
  117526. { sqlite3FinishCoding(pParse); }
  117527. break;
  117528. case 9: /* cmd ::= BEGIN transtype trans_opt */
  117529. {sqlite3BeginTransaction(pParse, yymsp[-1].minor.yy328);}
  117530. break;
  117531. case 13: /* transtype ::= */
  117532. {yygotominor.yy328 = TK_DEFERRED;}
  117533. break;
  117534. case 14: /* transtype ::= DEFERRED */
  117535. case 15: /* transtype ::= IMMEDIATE */ yytestcase(yyruleno==15);
  117536. case 16: /* transtype ::= EXCLUSIVE */ yytestcase(yyruleno==16);
  117537. case 115: /* multiselect_op ::= UNION */ yytestcase(yyruleno==115);
  117538. case 117: /* multiselect_op ::= EXCEPT|INTERSECT */ yytestcase(yyruleno==117);
  117539. {yygotominor.yy328 = yymsp[0].major;}
  117540. break;
  117541. case 17: /* cmd ::= COMMIT trans_opt */
  117542. case 18: /* cmd ::= END trans_opt */ yytestcase(yyruleno==18);
  117543. {sqlite3CommitTransaction(pParse);}
  117544. break;
  117545. case 19: /* cmd ::= ROLLBACK trans_opt */
  117546. {sqlite3RollbackTransaction(pParse);}
  117547. break;
  117548. case 22: /* cmd ::= SAVEPOINT nm */
  117549. {
  117550. sqlite3Savepoint(pParse, SAVEPOINT_BEGIN, &yymsp[0].minor.yy0);
  117551. }
  117552. break;
  117553. case 23: /* cmd ::= RELEASE savepoint_opt nm */
  117554. {
  117555. sqlite3Savepoint(pParse, SAVEPOINT_RELEASE, &yymsp[0].minor.yy0);
  117556. }
  117557. break;
  117558. case 24: /* cmd ::= ROLLBACK trans_opt TO savepoint_opt nm */
  117559. {
  117560. sqlite3Savepoint(pParse, SAVEPOINT_ROLLBACK, &yymsp[0].minor.yy0);
  117561. }
  117562. break;
  117563. case 26: /* create_table ::= createkw temp TABLE ifnotexists nm dbnm */
  117564. {
  117565. sqlite3StartTable(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0,yymsp[-4].minor.yy328,0,0,yymsp[-2].minor.yy328);
  117566. }
  117567. break;
  117568. case 27: /* createkw ::= CREATE */
  117569. {
  117570. pParse->db->lookaside.bEnabled = 0;
  117571. yygotominor.yy0 = yymsp[0].minor.yy0;
  117572. }
  117573. break;
  117574. case 28: /* ifnotexists ::= */
  117575. case 31: /* temp ::= */ yytestcase(yyruleno==31);
  117576. case 68: /* autoinc ::= */ yytestcase(yyruleno==68);
  117577. case 81: /* defer_subclause ::= NOT DEFERRABLE init_deferred_pred_opt */ yytestcase(yyruleno==81);
  117578. case 83: /* init_deferred_pred_opt ::= */ yytestcase(yyruleno==83);
  117579. case 85: /* init_deferred_pred_opt ::= INITIALLY IMMEDIATE */ yytestcase(yyruleno==85);
  117580. case 97: /* defer_subclause_opt ::= */ yytestcase(yyruleno==97);
  117581. case 108: /* ifexists ::= */ yytestcase(yyruleno==108);
  117582. case 218: /* between_op ::= BETWEEN */ yytestcase(yyruleno==218);
  117583. case 221: /* in_op ::= IN */ yytestcase(yyruleno==221);
  117584. {yygotominor.yy328 = 0;}
  117585. break;
  117586. case 29: /* ifnotexists ::= IF NOT EXISTS */
  117587. case 30: /* temp ::= TEMP */ yytestcase(yyruleno==30);
  117588. case 69: /* autoinc ::= AUTOINCR */ yytestcase(yyruleno==69);
  117589. case 84: /* init_deferred_pred_opt ::= INITIALLY DEFERRED */ yytestcase(yyruleno==84);
  117590. case 107: /* ifexists ::= IF EXISTS */ yytestcase(yyruleno==107);
  117591. case 219: /* between_op ::= NOT BETWEEN */ yytestcase(yyruleno==219);
  117592. case 222: /* in_op ::= NOT IN */ yytestcase(yyruleno==222);
  117593. {yygotominor.yy328 = 1;}
  117594. break;
  117595. case 32: /* create_table_args ::= LP columnlist conslist_opt RP table_options */
  117596. {
  117597. sqlite3EndTable(pParse,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0,yymsp[0].minor.yy186,0);
  117598. }
  117599. break;
  117600. case 33: /* create_table_args ::= AS select */
  117601. {
  117602. sqlite3EndTable(pParse,0,0,0,yymsp[0].minor.yy3);
  117603. sqlite3SelectDelete(pParse->db, yymsp[0].minor.yy3);
  117604. }
  117605. break;
  117606. case 34: /* table_options ::= */
  117607. {yygotominor.yy186 = 0;}
  117608. break;
  117609. case 35: /* table_options ::= WITHOUT nm */
  117610. {
  117611. if( yymsp[0].minor.yy0.n==5 && sqlite3_strnicmp(yymsp[0].minor.yy0.z,"rowid",5)==0 ){
  117612. yygotominor.yy186 = TF_WithoutRowid;
  117613. }else{
  117614. yygotominor.yy186 = 0;
  117615. sqlite3ErrorMsg(pParse, "unknown table option: %.*s", yymsp[0].minor.yy0.n, yymsp[0].minor.yy0.z);
  117616. }
  117617. }
  117618. break;
  117619. case 38: /* column ::= columnid type carglist */
  117620. {
  117621. yygotominor.yy0.z = yymsp[-2].minor.yy0.z;
  117622. yygotominor.yy0.n = (int)(pParse->sLastToken.z-yymsp[-2].minor.yy0.z) + pParse->sLastToken.n;
  117623. }
  117624. break;
  117625. case 39: /* columnid ::= nm */
  117626. {
  117627. sqlite3AddColumn(pParse,&yymsp[0].minor.yy0);
  117628. yygotominor.yy0 = yymsp[0].minor.yy0;
  117629. pParse->constraintName.n = 0;
  117630. }
  117631. break;
  117632. case 40: /* nm ::= ID|INDEXED */
  117633. case 41: /* nm ::= STRING */ yytestcase(yyruleno==41);
  117634. case 42: /* nm ::= JOIN_KW */ yytestcase(yyruleno==42);
  117635. case 45: /* typetoken ::= typename */ yytestcase(yyruleno==45);
  117636. case 48: /* typename ::= ID|STRING */ yytestcase(yyruleno==48);
  117637. case 130: /* as ::= AS nm */ yytestcase(yyruleno==130);
  117638. case 131: /* as ::= ID|STRING */ yytestcase(yyruleno==131);
  117639. case 141: /* dbnm ::= DOT nm */ yytestcase(yyruleno==141);
  117640. case 150: /* indexed_opt ::= INDEXED BY nm */ yytestcase(yyruleno==150);
  117641. case 247: /* collate ::= COLLATE ID|STRING */ yytestcase(yyruleno==247);
  117642. case 256: /* nmnum ::= plus_num */ yytestcase(yyruleno==256);
  117643. case 257: /* nmnum ::= nm */ yytestcase(yyruleno==257);
  117644. case 258: /* nmnum ::= ON */ yytestcase(yyruleno==258);
  117645. case 259: /* nmnum ::= DELETE */ yytestcase(yyruleno==259);
  117646. case 260: /* nmnum ::= DEFAULT */ yytestcase(yyruleno==260);
  117647. case 261: /* plus_num ::= PLUS INTEGER|FLOAT */ yytestcase(yyruleno==261);
  117648. case 262: /* plus_num ::= INTEGER|FLOAT */ yytestcase(yyruleno==262);
  117649. case 263: /* minus_num ::= MINUS INTEGER|FLOAT */ yytestcase(yyruleno==263);
  117650. case 279: /* trnm ::= nm */ yytestcase(yyruleno==279);
  117651. {yygotominor.yy0 = yymsp[0].minor.yy0;}
  117652. break;
  117653. case 44: /* type ::= typetoken */
  117654. {sqlite3AddColumnType(pParse,&yymsp[0].minor.yy0);}
  117655. break;
  117656. case 46: /* typetoken ::= typename LP signed RP */
  117657. {
  117658. yygotominor.yy0.z = yymsp[-3].minor.yy0.z;
  117659. yygotominor.yy0.n = (int)(&yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n] - yymsp[-3].minor.yy0.z);
  117660. }
  117661. break;
  117662. case 47: /* typetoken ::= typename LP signed COMMA signed RP */
  117663. {
  117664. yygotominor.yy0.z = yymsp[-5].minor.yy0.z;
  117665. yygotominor.yy0.n = (int)(&yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n] - yymsp[-5].minor.yy0.z);
  117666. }
  117667. break;
  117668. case 49: /* typename ::= typename ID|STRING */
  117669. {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);}
  117670. break;
  117671. case 54: /* ccons ::= CONSTRAINT nm */
  117672. case 92: /* tcons ::= CONSTRAINT nm */ yytestcase(yyruleno==92);
  117673. {pParse->constraintName = yymsp[0].minor.yy0;}
  117674. break;
  117675. case 55: /* ccons ::= DEFAULT term */
  117676. case 57: /* ccons ::= DEFAULT PLUS term */ yytestcase(yyruleno==57);
  117677. {sqlite3AddDefaultValue(pParse,&yymsp[0].minor.yy346);}
  117678. break;
  117679. case 56: /* ccons ::= DEFAULT LP expr RP */
  117680. {sqlite3AddDefaultValue(pParse,&yymsp[-1].minor.yy346);}
  117681. break;
  117682. case 58: /* ccons ::= DEFAULT MINUS term */
  117683. {
  117684. ExprSpan v;
  117685. v.pExpr = sqlite3PExpr(pParse, TK_UMINUS, yymsp[0].minor.yy346.pExpr, 0, 0);
  117686. v.zStart = yymsp[-1].minor.yy0.z;
  117687. v.zEnd = yymsp[0].minor.yy346.zEnd;
  117688. sqlite3AddDefaultValue(pParse,&v);
  117689. }
  117690. break;
  117691. case 59: /* ccons ::= DEFAULT ID|INDEXED */
  117692. {
  117693. ExprSpan v;
  117694. spanExpr(&v, pParse, TK_STRING, &yymsp[0].minor.yy0);
  117695. sqlite3AddDefaultValue(pParse,&v);
  117696. }
  117697. break;
  117698. case 61: /* ccons ::= NOT NULL onconf */
  117699. {sqlite3AddNotNull(pParse, yymsp[0].minor.yy328);}
  117700. break;
  117701. case 62: /* ccons ::= PRIMARY KEY sortorder onconf autoinc */
  117702. {sqlite3AddPrimaryKey(pParse,0,yymsp[-1].minor.yy328,yymsp[0].minor.yy328,yymsp[-2].minor.yy328);}
  117703. break;
  117704. case 63: /* ccons ::= UNIQUE onconf */
  117705. {sqlite3CreateIndex(pParse,0,0,0,0,yymsp[0].minor.yy328,0,0,0,0);}
  117706. break;
  117707. case 64: /* ccons ::= CHECK LP expr RP */
  117708. {sqlite3AddCheckConstraint(pParse,yymsp[-1].minor.yy346.pExpr);}
  117709. break;
  117710. case 65: /* ccons ::= REFERENCES nm idxlist_opt refargs */
  117711. {sqlite3CreateForeignKey(pParse,0,&yymsp[-2].minor.yy0,yymsp[-1].minor.yy14,yymsp[0].minor.yy328);}
  117712. break;
  117713. case 66: /* ccons ::= defer_subclause */
  117714. {sqlite3DeferForeignKey(pParse,yymsp[0].minor.yy328);}
  117715. break;
  117716. case 67: /* ccons ::= COLLATE ID|STRING */
  117717. {sqlite3AddCollateType(pParse, &yymsp[0].minor.yy0);}
  117718. break;
  117719. case 70: /* refargs ::= */
  117720. { yygotominor.yy328 = OE_None*0x0101; /* EV: R-19803-45884 */}
  117721. break;
  117722. case 71: /* refargs ::= refargs refarg */
  117723. { yygotominor.yy328 = (yymsp[-1].minor.yy328 & ~yymsp[0].minor.yy429.mask) | yymsp[0].minor.yy429.value; }
  117724. break;
  117725. case 72: /* refarg ::= MATCH nm */
  117726. case 73: /* refarg ::= ON INSERT refact */ yytestcase(yyruleno==73);
  117727. { yygotominor.yy429.value = 0; yygotominor.yy429.mask = 0x000000; }
  117728. break;
  117729. case 74: /* refarg ::= ON DELETE refact */
  117730. { yygotominor.yy429.value = yymsp[0].minor.yy328; yygotominor.yy429.mask = 0x0000ff; }
  117731. break;
  117732. case 75: /* refarg ::= ON UPDATE refact */
  117733. { yygotominor.yy429.value = yymsp[0].minor.yy328<<8; yygotominor.yy429.mask = 0x00ff00; }
  117734. break;
  117735. case 76: /* refact ::= SET NULL */
  117736. { yygotominor.yy328 = OE_SetNull; /* EV: R-33326-45252 */}
  117737. break;
  117738. case 77: /* refact ::= SET DEFAULT */
  117739. { yygotominor.yy328 = OE_SetDflt; /* EV: R-33326-45252 */}
  117740. break;
  117741. case 78: /* refact ::= CASCADE */
  117742. { yygotominor.yy328 = OE_Cascade; /* EV: R-33326-45252 */}
  117743. break;
  117744. case 79: /* refact ::= RESTRICT */
  117745. { yygotominor.yy328 = OE_Restrict; /* EV: R-33326-45252 */}
  117746. break;
  117747. case 80: /* refact ::= NO ACTION */
  117748. { yygotominor.yy328 = OE_None; /* EV: R-33326-45252 */}
  117749. break;
  117750. case 82: /* defer_subclause ::= DEFERRABLE init_deferred_pred_opt */
  117751. case 98: /* defer_subclause_opt ::= defer_subclause */ yytestcase(yyruleno==98);
  117752. case 100: /* onconf ::= ON CONFLICT resolvetype */ yytestcase(yyruleno==100);
  117753. case 103: /* resolvetype ::= raisetype */ yytestcase(yyruleno==103);
  117754. {yygotominor.yy328 = yymsp[0].minor.yy328;}
  117755. break;
  117756. case 86: /* conslist_opt ::= */
  117757. {yygotominor.yy0.n = 0; yygotominor.yy0.z = 0;}
  117758. break;
  117759. case 87: /* conslist_opt ::= COMMA conslist */
  117760. {yygotominor.yy0 = yymsp[-1].minor.yy0;}
  117761. break;
  117762. case 90: /* tconscomma ::= COMMA */
  117763. {pParse->constraintName.n = 0;}
  117764. break;
  117765. case 93: /* tcons ::= PRIMARY KEY LP idxlist autoinc RP onconf */
  117766. {sqlite3AddPrimaryKey(pParse,yymsp[-3].minor.yy14,yymsp[0].minor.yy328,yymsp[-2].minor.yy328,0);}
  117767. break;
  117768. case 94: /* tcons ::= UNIQUE LP idxlist RP onconf */
  117769. {sqlite3CreateIndex(pParse,0,0,0,yymsp[-2].minor.yy14,yymsp[0].minor.yy328,0,0,0,0);}
  117770. break;
  117771. case 95: /* tcons ::= CHECK LP expr RP onconf */
  117772. {sqlite3AddCheckConstraint(pParse,yymsp[-2].minor.yy346.pExpr);}
  117773. break;
  117774. case 96: /* tcons ::= FOREIGN KEY LP idxlist RP REFERENCES nm idxlist_opt refargs defer_subclause_opt */
  117775. {
  117776. sqlite3CreateForeignKey(pParse, yymsp[-6].minor.yy14, &yymsp[-3].minor.yy0, yymsp[-2].minor.yy14, yymsp[-1].minor.yy328);
  117777. sqlite3DeferForeignKey(pParse, yymsp[0].minor.yy328);
  117778. }
  117779. break;
  117780. case 99: /* onconf ::= */
  117781. {yygotominor.yy328 = OE_Default;}
  117782. break;
  117783. case 101: /* orconf ::= */
  117784. {yygotominor.yy186 = OE_Default;}
  117785. break;
  117786. case 102: /* orconf ::= OR resolvetype */
  117787. {yygotominor.yy186 = (u8)yymsp[0].minor.yy328;}
  117788. break;
  117789. case 104: /* resolvetype ::= IGNORE */
  117790. {yygotominor.yy328 = OE_Ignore;}
  117791. break;
  117792. case 105: /* resolvetype ::= REPLACE */
  117793. {yygotominor.yy328 = OE_Replace;}
  117794. break;
  117795. case 106: /* cmd ::= DROP TABLE ifexists fullname */
  117796. {
  117797. sqlite3DropTable(pParse, yymsp[0].minor.yy65, 0, yymsp[-1].minor.yy328);
  117798. }
  117799. break;
  117800. case 109: /* cmd ::= createkw temp VIEW ifnotexists nm dbnm AS select */
  117801. {
  117802. 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);
  117803. }
  117804. break;
  117805. case 110: /* cmd ::= DROP VIEW ifexists fullname */
  117806. {
  117807. sqlite3DropTable(pParse, yymsp[0].minor.yy65, 1, yymsp[-1].minor.yy328);
  117808. }
  117809. break;
  117810. case 111: /* cmd ::= select */
  117811. {
  117812. SelectDest dest = {SRT_Output, 0, 0, 0, 0, 0};
  117813. sqlite3Select(pParse, yymsp[0].minor.yy3, &dest);
  117814. sqlite3SelectDelete(pParse->db, yymsp[0].minor.yy3);
  117815. }
  117816. break;
  117817. case 112: /* select ::= with selectnowith */
  117818. {
  117819. Select *p = yymsp[0].minor.yy3;
  117820. if( p ){
  117821. p->pWith = yymsp[-1].minor.yy59;
  117822. parserDoubleLinkSelect(pParse, p);
  117823. }else{
  117824. sqlite3WithDelete(pParse->db, yymsp[-1].minor.yy59);
  117825. }
  117826. yygotominor.yy3 = p;
  117827. }
  117828. break;
  117829. case 113: /* selectnowith ::= oneselect */
  117830. case 119: /* oneselect ::= values */ yytestcase(yyruleno==119);
  117831. {yygotominor.yy3 = yymsp[0].minor.yy3;}
  117832. break;
  117833. case 114: /* selectnowith ::= selectnowith multiselect_op oneselect */
  117834. {
  117835. Select *pRhs = yymsp[0].minor.yy3;
  117836. if( pRhs && pRhs->pPrior ){
  117837. SrcList *pFrom;
  117838. Token x;
  117839. x.n = 0;
  117840. parserDoubleLinkSelect(pParse, pRhs);
  117841. pFrom = sqlite3SrcListAppendFromTerm(pParse,0,0,0,&x,pRhs,0,0);
  117842. pRhs = sqlite3SelectNew(pParse,0,pFrom,0,0,0,0,0,0,0);
  117843. }
  117844. if( pRhs ){
  117845. pRhs->op = (u8)yymsp[-1].minor.yy328;
  117846. pRhs->pPrior = yymsp[-2].minor.yy3;
  117847. pRhs->selFlags &= ~SF_MultiValue;
  117848. if( yymsp[-1].minor.yy328!=TK_ALL ) pParse->hasCompound = 1;
  117849. }else{
  117850. sqlite3SelectDelete(pParse->db, yymsp[-2].minor.yy3);
  117851. }
  117852. yygotominor.yy3 = pRhs;
  117853. }
  117854. break;
  117855. case 116: /* multiselect_op ::= UNION ALL */
  117856. {yygotominor.yy328 = TK_ALL;}
  117857. break;
  117858. case 118: /* oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt orderby_opt limit_opt */
  117859. {
  117860. 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);
  117861. #if SELECTTRACE_ENABLED
  117862. /* Populate the Select.zSelName[] string that is used to help with
  117863. ** query planner debugging, to differentiate between multiple Select
  117864. ** objects in a complex query.
  117865. **
  117866. ** If the SELECT keyword is immediately followed by a C-style comment
  117867. ** then extract the first few alphanumeric characters from within that
  117868. ** comment to be the zSelName value. Otherwise, the label is #N where
  117869. ** is an integer that is incremented with each SELECT statement seen.
  117870. */
  117871. if( yygotominor.yy3!=0 ){
  117872. const char *z = yymsp[-8].minor.yy0.z+6;
  117873. int i;
  117874. sqlite3_snprintf(sizeof(yygotominor.yy3->zSelName), yygotominor.yy3->zSelName, "#%d",
  117875. ++pParse->nSelect);
  117876. while( z[0]==' ' ) z++;
  117877. if( z[0]=='/' && z[1]=='*' ){
  117878. z += 2;
  117879. while( z[0]==' ' ) z++;
  117880. for(i=0; sqlite3Isalnum(z[i]); i++){}
  117881. sqlite3_snprintf(sizeof(yygotominor.yy3->zSelName), yygotominor.yy3->zSelName, "%.*s", i, z);
  117882. }
  117883. }
  117884. #endif /* SELECTRACE_ENABLED */
  117885. }
  117886. break;
  117887. case 120: /* values ::= VALUES LP nexprlist RP */
  117888. {
  117889. yygotominor.yy3 = sqlite3SelectNew(pParse,yymsp[-1].minor.yy14,0,0,0,0,0,SF_Values,0,0);
  117890. }
  117891. break;
  117892. case 121: /* values ::= values COMMA LP exprlist RP */
  117893. {
  117894. Select *pRight, *pLeft = yymsp[-4].minor.yy3;
  117895. pRight = sqlite3SelectNew(pParse,yymsp[-1].minor.yy14,0,0,0,0,0,SF_Values|SF_MultiValue,0,0);
  117896. if( ALWAYS(pLeft) ) pLeft->selFlags &= ~SF_MultiValue;
  117897. if( pRight ){
  117898. pRight->op = TK_ALL;
  117899. pLeft = yymsp[-4].minor.yy3;
  117900. pRight->pPrior = pLeft;
  117901. yygotominor.yy3 = pRight;
  117902. }else{
  117903. yygotominor.yy3 = pLeft;
  117904. }
  117905. }
  117906. break;
  117907. case 122: /* distinct ::= DISTINCT */
  117908. {yygotominor.yy381 = SF_Distinct;}
  117909. break;
  117910. case 123: /* distinct ::= ALL */
  117911. case 124: /* distinct ::= */ yytestcase(yyruleno==124);
  117912. {yygotominor.yy381 = 0;}
  117913. break;
  117914. case 125: /* sclp ::= selcollist COMMA */
  117915. case 243: /* idxlist_opt ::= LP idxlist RP */ yytestcase(yyruleno==243);
  117916. {yygotominor.yy14 = yymsp[-1].minor.yy14;}
  117917. break;
  117918. case 126: /* sclp ::= */
  117919. case 154: /* orderby_opt ::= */ yytestcase(yyruleno==154);
  117920. case 161: /* groupby_opt ::= */ yytestcase(yyruleno==161);
  117921. case 236: /* exprlist ::= */ yytestcase(yyruleno==236);
  117922. case 242: /* idxlist_opt ::= */ yytestcase(yyruleno==242);
  117923. {yygotominor.yy14 = 0;}
  117924. break;
  117925. case 127: /* selcollist ::= sclp expr as */
  117926. {
  117927. yygotominor.yy14 = sqlite3ExprListAppend(pParse, yymsp[-2].minor.yy14, yymsp[-1].minor.yy346.pExpr);
  117928. if( yymsp[0].minor.yy0.n>0 ) sqlite3ExprListSetName(pParse, yygotominor.yy14, &yymsp[0].minor.yy0, 1);
  117929. sqlite3ExprListSetSpan(pParse,yygotominor.yy14,&yymsp[-1].minor.yy346);
  117930. }
  117931. break;
  117932. case 128: /* selcollist ::= sclp STAR */
  117933. {
  117934. Expr *p = sqlite3Expr(pParse->db, TK_ALL, 0);
  117935. yygotominor.yy14 = sqlite3ExprListAppend(pParse, yymsp[-1].minor.yy14, p);
  117936. }
  117937. break;
  117938. case 129: /* selcollist ::= sclp nm DOT STAR */
  117939. {
  117940. Expr *pRight = sqlite3PExpr(pParse, TK_ALL, 0, 0, &yymsp[0].minor.yy0);
  117941. Expr *pLeft = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-2].minor.yy0);
  117942. Expr *pDot = sqlite3PExpr(pParse, TK_DOT, pLeft, pRight, 0);
  117943. yygotominor.yy14 = sqlite3ExprListAppend(pParse,yymsp[-3].minor.yy14, pDot);
  117944. }
  117945. break;
  117946. case 132: /* as ::= */
  117947. {yygotominor.yy0.n = 0;}
  117948. break;
  117949. case 133: /* from ::= */
  117950. {yygotominor.yy65 = sqlite3DbMallocZero(pParse->db, sizeof(*yygotominor.yy65));}
  117951. break;
  117952. case 134: /* from ::= FROM seltablist */
  117953. {
  117954. yygotominor.yy65 = yymsp[0].minor.yy65;
  117955. sqlite3SrcListShiftJoinType(yygotominor.yy65);
  117956. }
  117957. break;
  117958. case 135: /* stl_prefix ::= seltablist joinop */
  117959. {
  117960. yygotominor.yy65 = yymsp[-1].minor.yy65;
  117961. if( ALWAYS(yygotominor.yy65 && yygotominor.yy65->nSrc>0) ) yygotominor.yy65->a[yygotominor.yy65->nSrc-1].jointype = (u8)yymsp[0].minor.yy328;
  117962. }
  117963. break;
  117964. case 136: /* stl_prefix ::= */
  117965. {yygotominor.yy65 = 0;}
  117966. break;
  117967. case 137: /* seltablist ::= stl_prefix nm dbnm as indexed_opt on_opt using_opt */
  117968. {
  117969. 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);
  117970. sqlite3SrcListIndexedBy(pParse, yygotominor.yy65, &yymsp[-2].minor.yy0);
  117971. }
  117972. break;
  117973. case 138: /* seltablist ::= stl_prefix LP select RP as on_opt using_opt */
  117974. {
  117975. 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);
  117976. }
  117977. break;
  117978. case 139: /* seltablist ::= stl_prefix LP seltablist RP as on_opt using_opt */
  117979. {
  117980. if( yymsp[-6].minor.yy65==0 && yymsp[-2].minor.yy0.n==0 && yymsp[-1].minor.yy132==0 && yymsp[0].minor.yy408==0 ){
  117981. yygotominor.yy65 = yymsp[-4].minor.yy65;
  117982. }else if( yymsp[-4].minor.yy65->nSrc==1 ){
  117983. yygotominor.yy65 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-6].minor.yy65,0,0,&yymsp[-2].minor.yy0,0,yymsp[-1].minor.yy132,yymsp[0].minor.yy408);
  117984. if( yygotominor.yy65 ){
  117985. struct SrcList_item *pNew = &yygotominor.yy65->a[yygotominor.yy65->nSrc-1];
  117986. struct SrcList_item *pOld = yymsp[-4].minor.yy65->a;
  117987. pNew->zName = pOld->zName;
  117988. pNew->zDatabase = pOld->zDatabase;
  117989. pNew->pSelect = pOld->pSelect;
  117990. pOld->zName = pOld->zDatabase = 0;
  117991. pOld->pSelect = 0;
  117992. }
  117993. sqlite3SrcListDelete(pParse->db, yymsp[-4].minor.yy65);
  117994. }else{
  117995. Select *pSubquery;
  117996. sqlite3SrcListShiftJoinType(yymsp[-4].minor.yy65);
  117997. pSubquery = sqlite3SelectNew(pParse,0,yymsp[-4].minor.yy65,0,0,0,0,SF_NestedFrom,0,0);
  117998. yygotominor.yy65 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-6].minor.yy65,0,0,&yymsp[-2].minor.yy0,pSubquery,yymsp[-1].minor.yy132,yymsp[0].minor.yy408);
  117999. }
  118000. }
  118001. break;
  118002. case 140: /* dbnm ::= */
  118003. case 149: /* indexed_opt ::= */ yytestcase(yyruleno==149);
  118004. {yygotominor.yy0.z=0; yygotominor.yy0.n=0;}
  118005. break;
  118006. case 142: /* fullname ::= nm dbnm */
  118007. {yygotominor.yy65 = sqlite3SrcListAppend(pParse->db,0,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0);}
  118008. break;
  118009. case 143: /* joinop ::= COMMA|JOIN */
  118010. { yygotominor.yy328 = JT_INNER; }
  118011. break;
  118012. case 144: /* joinop ::= JOIN_KW JOIN */
  118013. { yygotominor.yy328 = sqlite3JoinType(pParse,&yymsp[-1].minor.yy0,0,0); }
  118014. break;
  118015. case 145: /* joinop ::= JOIN_KW nm JOIN */
  118016. { yygotominor.yy328 = sqlite3JoinType(pParse,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0,0); }
  118017. break;
  118018. case 146: /* joinop ::= JOIN_KW nm nm JOIN */
  118019. { yygotominor.yy328 = sqlite3JoinType(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0); }
  118020. break;
  118021. case 147: /* on_opt ::= ON expr */
  118022. case 164: /* having_opt ::= HAVING expr */ yytestcase(yyruleno==164);
  118023. case 171: /* where_opt ::= WHERE expr */ yytestcase(yyruleno==171);
  118024. case 231: /* case_else ::= ELSE expr */ yytestcase(yyruleno==231);
  118025. case 233: /* case_operand ::= expr */ yytestcase(yyruleno==233);
  118026. {yygotominor.yy132 = yymsp[0].minor.yy346.pExpr;}
  118027. break;
  118028. case 148: /* on_opt ::= */
  118029. case 163: /* having_opt ::= */ yytestcase(yyruleno==163);
  118030. case 170: /* where_opt ::= */ yytestcase(yyruleno==170);
  118031. case 232: /* case_else ::= */ yytestcase(yyruleno==232);
  118032. case 234: /* case_operand ::= */ yytestcase(yyruleno==234);
  118033. {yygotominor.yy132 = 0;}
  118034. break;
  118035. case 151: /* indexed_opt ::= NOT INDEXED */
  118036. {yygotominor.yy0.z=0; yygotominor.yy0.n=1;}
  118037. break;
  118038. case 152: /* using_opt ::= USING LP idlist RP */
  118039. case 180: /* inscollist_opt ::= LP idlist RP */ yytestcase(yyruleno==180);
  118040. {yygotominor.yy408 = yymsp[-1].minor.yy408;}
  118041. break;
  118042. case 153: /* using_opt ::= */
  118043. case 179: /* inscollist_opt ::= */ yytestcase(yyruleno==179);
  118044. {yygotominor.yy408 = 0;}
  118045. break;
  118046. case 155: /* orderby_opt ::= ORDER BY sortlist */
  118047. case 162: /* groupby_opt ::= GROUP BY nexprlist */ yytestcase(yyruleno==162);
  118048. case 235: /* exprlist ::= nexprlist */ yytestcase(yyruleno==235);
  118049. {yygotominor.yy14 = yymsp[0].minor.yy14;}
  118050. break;
  118051. case 156: /* sortlist ::= sortlist COMMA expr sortorder */
  118052. {
  118053. yygotominor.yy14 = sqlite3ExprListAppend(pParse,yymsp[-3].minor.yy14,yymsp[-1].minor.yy346.pExpr);
  118054. if( yygotominor.yy14 ) yygotominor.yy14->a[yygotominor.yy14->nExpr-1].sortOrder = (u8)yymsp[0].minor.yy328;
  118055. }
  118056. break;
  118057. case 157: /* sortlist ::= expr sortorder */
  118058. {
  118059. yygotominor.yy14 = sqlite3ExprListAppend(pParse,0,yymsp[-1].minor.yy346.pExpr);
  118060. if( yygotominor.yy14 && ALWAYS(yygotominor.yy14->a) ) yygotominor.yy14->a[0].sortOrder = (u8)yymsp[0].minor.yy328;
  118061. }
  118062. break;
  118063. case 158: /* sortorder ::= ASC */
  118064. case 160: /* sortorder ::= */ yytestcase(yyruleno==160);
  118065. {yygotominor.yy328 = SQLITE_SO_ASC;}
  118066. break;
  118067. case 159: /* sortorder ::= DESC */
  118068. {yygotominor.yy328 = SQLITE_SO_DESC;}
  118069. break;
  118070. case 165: /* limit_opt ::= */
  118071. {yygotominor.yy476.pLimit = 0; yygotominor.yy476.pOffset = 0;}
  118072. break;
  118073. case 166: /* limit_opt ::= LIMIT expr */
  118074. {yygotominor.yy476.pLimit = yymsp[0].minor.yy346.pExpr; yygotominor.yy476.pOffset = 0;}
  118075. break;
  118076. case 167: /* limit_opt ::= LIMIT expr OFFSET expr */
  118077. {yygotominor.yy476.pLimit = yymsp[-2].minor.yy346.pExpr; yygotominor.yy476.pOffset = yymsp[0].minor.yy346.pExpr;}
  118078. break;
  118079. case 168: /* limit_opt ::= LIMIT expr COMMA expr */
  118080. {yygotominor.yy476.pOffset = yymsp[-2].minor.yy346.pExpr; yygotominor.yy476.pLimit = yymsp[0].minor.yy346.pExpr;}
  118081. break;
  118082. case 169: /* cmd ::= with DELETE FROM fullname indexed_opt where_opt */
  118083. {
  118084. sqlite3WithPush(pParse, yymsp[-5].minor.yy59, 1);
  118085. sqlite3SrcListIndexedBy(pParse, yymsp[-2].minor.yy65, &yymsp[-1].minor.yy0);
  118086. sqlite3DeleteFrom(pParse,yymsp[-2].minor.yy65,yymsp[0].minor.yy132);
  118087. }
  118088. break;
  118089. case 172: /* cmd ::= with UPDATE orconf fullname indexed_opt SET setlist where_opt */
  118090. {
  118091. sqlite3WithPush(pParse, yymsp[-7].minor.yy59, 1);
  118092. sqlite3SrcListIndexedBy(pParse, yymsp[-4].minor.yy65, &yymsp[-3].minor.yy0);
  118093. sqlite3ExprListCheckLength(pParse,yymsp[-1].minor.yy14,"set list");
  118094. sqlite3Update(pParse,yymsp[-4].minor.yy65,yymsp[-1].minor.yy14,yymsp[0].minor.yy132,yymsp[-5].minor.yy186);
  118095. }
  118096. break;
  118097. case 173: /* setlist ::= setlist COMMA nm EQ expr */
  118098. {
  118099. yygotominor.yy14 = sqlite3ExprListAppend(pParse, yymsp[-4].minor.yy14, yymsp[0].minor.yy346.pExpr);
  118100. sqlite3ExprListSetName(pParse, yygotominor.yy14, &yymsp[-2].minor.yy0, 1);
  118101. }
  118102. break;
  118103. case 174: /* setlist ::= nm EQ expr */
  118104. {
  118105. yygotominor.yy14 = sqlite3ExprListAppend(pParse, 0, yymsp[0].minor.yy346.pExpr);
  118106. sqlite3ExprListSetName(pParse, yygotominor.yy14, &yymsp[-2].minor.yy0, 1);
  118107. }
  118108. break;
  118109. case 175: /* cmd ::= with insert_cmd INTO fullname inscollist_opt select */
  118110. {
  118111. sqlite3WithPush(pParse, yymsp[-5].minor.yy59, 1);
  118112. sqlite3Insert(pParse, yymsp[-2].minor.yy65, yymsp[0].minor.yy3, yymsp[-1].minor.yy408, yymsp[-4].minor.yy186);
  118113. }
  118114. break;
  118115. case 176: /* cmd ::= with insert_cmd INTO fullname inscollist_opt DEFAULT VALUES */
  118116. {
  118117. sqlite3WithPush(pParse, yymsp[-6].minor.yy59, 1);
  118118. sqlite3Insert(pParse, yymsp[-3].minor.yy65, 0, yymsp[-2].minor.yy408, yymsp[-5].minor.yy186);
  118119. }
  118120. break;
  118121. case 177: /* insert_cmd ::= INSERT orconf */
  118122. {yygotominor.yy186 = yymsp[0].minor.yy186;}
  118123. break;
  118124. case 178: /* insert_cmd ::= REPLACE */
  118125. {yygotominor.yy186 = OE_Replace;}
  118126. break;
  118127. case 181: /* idlist ::= idlist COMMA nm */
  118128. {yygotominor.yy408 = sqlite3IdListAppend(pParse->db,yymsp[-2].minor.yy408,&yymsp[0].minor.yy0);}
  118129. break;
  118130. case 182: /* idlist ::= nm */
  118131. {yygotominor.yy408 = sqlite3IdListAppend(pParse->db,0,&yymsp[0].minor.yy0);}
  118132. break;
  118133. case 183: /* expr ::= term */
  118134. {yygotominor.yy346 = yymsp[0].minor.yy346;}
  118135. break;
  118136. case 184: /* expr ::= LP expr RP */
  118137. {yygotominor.yy346.pExpr = yymsp[-1].minor.yy346.pExpr; spanSet(&yygotominor.yy346,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0);}
  118138. break;
  118139. case 185: /* term ::= NULL */
  118140. case 190: /* term ::= INTEGER|FLOAT|BLOB */ yytestcase(yyruleno==190);
  118141. case 191: /* term ::= STRING */ yytestcase(yyruleno==191);
  118142. {spanExpr(&yygotominor.yy346, pParse, yymsp[0].major, &yymsp[0].minor.yy0);}
  118143. break;
  118144. case 186: /* expr ::= ID|INDEXED */
  118145. case 187: /* expr ::= JOIN_KW */ yytestcase(yyruleno==187);
  118146. {spanExpr(&yygotominor.yy346, pParse, TK_ID, &yymsp[0].minor.yy0);}
  118147. break;
  118148. case 188: /* expr ::= nm DOT nm */
  118149. {
  118150. Expr *temp1 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-2].minor.yy0);
  118151. Expr *temp2 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[0].minor.yy0);
  118152. yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_DOT, temp1, temp2, 0);
  118153. spanSet(&yygotominor.yy346,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0);
  118154. }
  118155. break;
  118156. case 189: /* expr ::= nm DOT nm DOT nm */
  118157. {
  118158. Expr *temp1 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-4].minor.yy0);
  118159. Expr *temp2 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-2].minor.yy0);
  118160. Expr *temp3 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[0].minor.yy0);
  118161. Expr *temp4 = sqlite3PExpr(pParse, TK_DOT, temp2, temp3, 0);
  118162. yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_DOT, temp1, temp4, 0);
  118163. spanSet(&yygotominor.yy346,&yymsp[-4].minor.yy0,&yymsp[0].minor.yy0);
  118164. }
  118165. break;
  118166. case 192: /* expr ::= VARIABLE */
  118167. {
  118168. if( yymsp[0].minor.yy0.n>=2 && yymsp[0].minor.yy0.z[0]=='#' && sqlite3Isdigit(yymsp[0].minor.yy0.z[1]) ){
  118169. /* When doing a nested parse, one can include terms in an expression
  118170. ** that look like this: #1 #2 ... These terms refer to registers
  118171. ** in the virtual machine. #N is the N-th register. */
  118172. if( pParse->nested==0 ){
  118173. sqlite3ErrorMsg(pParse, "near \"%T\": syntax error", &yymsp[0].minor.yy0);
  118174. yygotominor.yy346.pExpr = 0;
  118175. }else{
  118176. yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_REGISTER, 0, 0, &yymsp[0].minor.yy0);
  118177. if( yygotominor.yy346.pExpr ) sqlite3GetInt32(&yymsp[0].minor.yy0.z[1], &yygotominor.yy346.pExpr->iTable);
  118178. }
  118179. }else{
  118180. spanExpr(&yygotominor.yy346, pParse, TK_VARIABLE, &yymsp[0].minor.yy0);
  118181. sqlite3ExprAssignVarNumber(pParse, yygotominor.yy346.pExpr);
  118182. }
  118183. spanSet(&yygotominor.yy346, &yymsp[0].minor.yy0, &yymsp[0].minor.yy0);
  118184. }
  118185. break;
  118186. case 193: /* expr ::= expr COLLATE ID|STRING */
  118187. {
  118188. yygotominor.yy346.pExpr = sqlite3ExprAddCollateToken(pParse, yymsp[-2].minor.yy346.pExpr, &yymsp[0].minor.yy0, 1);
  118189. yygotominor.yy346.zStart = yymsp[-2].minor.yy346.zStart;
  118190. yygotominor.yy346.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
  118191. }
  118192. break;
  118193. case 194: /* expr ::= CAST LP expr AS typetoken RP */
  118194. {
  118195. yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_CAST, yymsp[-3].minor.yy346.pExpr, 0, &yymsp[-1].minor.yy0);
  118196. spanSet(&yygotominor.yy346,&yymsp[-5].minor.yy0,&yymsp[0].minor.yy0);
  118197. }
  118198. break;
  118199. case 195: /* expr ::= ID|INDEXED LP distinct exprlist RP */
  118200. {
  118201. if( yymsp[-1].minor.yy14 && yymsp[-1].minor.yy14->nExpr>pParse->db->aLimit[SQLITE_LIMIT_FUNCTION_ARG] ){
  118202. sqlite3ErrorMsg(pParse, "too many arguments on function %T", &yymsp[-4].minor.yy0);
  118203. }
  118204. yygotominor.yy346.pExpr = sqlite3ExprFunction(pParse, yymsp[-1].minor.yy14, &yymsp[-4].minor.yy0);
  118205. spanSet(&yygotominor.yy346,&yymsp[-4].minor.yy0,&yymsp[0].minor.yy0);
  118206. if( yymsp[-2].minor.yy381 && yygotominor.yy346.pExpr ){
  118207. yygotominor.yy346.pExpr->flags |= EP_Distinct;
  118208. }
  118209. }
  118210. break;
  118211. case 196: /* expr ::= ID|INDEXED LP STAR RP */
  118212. {
  118213. yygotominor.yy346.pExpr = sqlite3ExprFunction(pParse, 0, &yymsp[-3].minor.yy0);
  118214. spanSet(&yygotominor.yy346,&yymsp[-3].minor.yy0,&yymsp[0].minor.yy0);
  118215. }
  118216. break;
  118217. case 197: /* term ::= CTIME_KW */
  118218. {
  118219. yygotominor.yy346.pExpr = sqlite3ExprFunction(pParse, 0, &yymsp[0].minor.yy0);
  118220. spanSet(&yygotominor.yy346, &yymsp[0].minor.yy0, &yymsp[0].minor.yy0);
  118221. }
  118222. break;
  118223. case 198: /* expr ::= expr AND expr */
  118224. case 199: /* expr ::= expr OR expr */ yytestcase(yyruleno==199);
  118225. case 200: /* expr ::= expr LT|GT|GE|LE expr */ yytestcase(yyruleno==200);
  118226. case 201: /* expr ::= expr EQ|NE expr */ yytestcase(yyruleno==201);
  118227. case 202: /* expr ::= expr BITAND|BITOR|LSHIFT|RSHIFT expr */ yytestcase(yyruleno==202);
  118228. case 203: /* expr ::= expr PLUS|MINUS expr */ yytestcase(yyruleno==203);
  118229. case 204: /* expr ::= expr STAR|SLASH|REM expr */ yytestcase(yyruleno==204);
  118230. case 205: /* expr ::= expr CONCAT expr */ yytestcase(yyruleno==205);
  118231. {spanBinaryExpr(&yygotominor.yy346,pParse,yymsp[-1].major,&yymsp[-2].minor.yy346,&yymsp[0].minor.yy346);}
  118232. break;
  118233. case 206: /* likeop ::= LIKE_KW|MATCH */
  118234. {yygotominor.yy96.eOperator = yymsp[0].minor.yy0; yygotominor.yy96.bNot = 0;}
  118235. break;
  118236. case 207: /* likeop ::= NOT LIKE_KW|MATCH */
  118237. {yygotominor.yy96.eOperator = yymsp[0].minor.yy0; yygotominor.yy96.bNot = 1;}
  118238. break;
  118239. case 208: /* expr ::= expr likeop expr */
  118240. {
  118241. ExprList *pList;
  118242. pList = sqlite3ExprListAppend(pParse,0, yymsp[0].minor.yy346.pExpr);
  118243. pList = sqlite3ExprListAppend(pParse,pList, yymsp[-2].minor.yy346.pExpr);
  118244. yygotominor.yy346.pExpr = sqlite3ExprFunction(pParse, pList, &yymsp[-1].minor.yy96.eOperator);
  118245. if( yymsp[-1].minor.yy96.bNot ) yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy346.pExpr, 0, 0);
  118246. yygotominor.yy346.zStart = yymsp[-2].minor.yy346.zStart;
  118247. yygotominor.yy346.zEnd = yymsp[0].minor.yy346.zEnd;
  118248. if( yygotominor.yy346.pExpr ) yygotominor.yy346.pExpr->flags |= EP_InfixFunc;
  118249. }
  118250. break;
  118251. case 209: /* expr ::= expr likeop expr ESCAPE expr */
  118252. {
  118253. ExprList *pList;
  118254. pList = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy346.pExpr);
  118255. pList = sqlite3ExprListAppend(pParse,pList, yymsp[-4].minor.yy346.pExpr);
  118256. pList = sqlite3ExprListAppend(pParse,pList, yymsp[0].minor.yy346.pExpr);
  118257. yygotominor.yy346.pExpr = sqlite3ExprFunction(pParse, pList, &yymsp[-3].minor.yy96.eOperator);
  118258. if( yymsp[-3].minor.yy96.bNot ) yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy346.pExpr, 0, 0);
  118259. yygotominor.yy346.zStart = yymsp[-4].minor.yy346.zStart;
  118260. yygotominor.yy346.zEnd = yymsp[0].minor.yy346.zEnd;
  118261. if( yygotominor.yy346.pExpr ) yygotominor.yy346.pExpr->flags |= EP_InfixFunc;
  118262. }
  118263. break;
  118264. case 210: /* expr ::= expr ISNULL|NOTNULL */
  118265. {spanUnaryPostfix(&yygotominor.yy346,pParse,yymsp[0].major,&yymsp[-1].minor.yy346,&yymsp[0].minor.yy0);}
  118266. break;
  118267. case 211: /* expr ::= expr NOT NULL */
  118268. {spanUnaryPostfix(&yygotominor.yy346,pParse,TK_NOTNULL,&yymsp[-2].minor.yy346,&yymsp[0].minor.yy0);}
  118269. break;
  118270. case 212: /* expr ::= expr IS expr */
  118271. {
  118272. spanBinaryExpr(&yygotominor.yy346,pParse,TK_IS,&yymsp[-2].minor.yy346,&yymsp[0].minor.yy346);
  118273. binaryToUnaryIfNull(pParse, yymsp[0].minor.yy346.pExpr, yygotominor.yy346.pExpr, TK_ISNULL);
  118274. }
  118275. break;
  118276. case 213: /* expr ::= expr IS NOT expr */
  118277. {
  118278. spanBinaryExpr(&yygotominor.yy346,pParse,TK_ISNOT,&yymsp[-3].minor.yy346,&yymsp[0].minor.yy346);
  118279. binaryToUnaryIfNull(pParse, yymsp[0].minor.yy346.pExpr, yygotominor.yy346.pExpr, TK_NOTNULL);
  118280. }
  118281. break;
  118282. case 214: /* expr ::= NOT expr */
  118283. case 215: /* expr ::= BITNOT expr */ yytestcase(yyruleno==215);
  118284. {spanUnaryPrefix(&yygotominor.yy346,pParse,yymsp[-1].major,&yymsp[0].minor.yy346,&yymsp[-1].minor.yy0);}
  118285. break;
  118286. case 216: /* expr ::= MINUS expr */
  118287. {spanUnaryPrefix(&yygotominor.yy346,pParse,TK_UMINUS,&yymsp[0].minor.yy346,&yymsp[-1].minor.yy0);}
  118288. break;
  118289. case 217: /* expr ::= PLUS expr */
  118290. {spanUnaryPrefix(&yygotominor.yy346,pParse,TK_UPLUS,&yymsp[0].minor.yy346,&yymsp[-1].minor.yy0);}
  118291. break;
  118292. case 220: /* expr ::= expr between_op expr AND expr */
  118293. {
  118294. ExprList *pList = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy346.pExpr);
  118295. pList = sqlite3ExprListAppend(pParse,pList, yymsp[0].minor.yy346.pExpr);
  118296. yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_BETWEEN, yymsp[-4].minor.yy346.pExpr, 0, 0);
  118297. if( yygotominor.yy346.pExpr ){
  118298. yygotominor.yy346.pExpr->x.pList = pList;
  118299. }else{
  118300. sqlite3ExprListDelete(pParse->db, pList);
  118301. }
  118302. if( yymsp[-3].minor.yy328 ) yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy346.pExpr, 0, 0);
  118303. yygotominor.yy346.zStart = yymsp[-4].minor.yy346.zStart;
  118304. yygotominor.yy346.zEnd = yymsp[0].minor.yy346.zEnd;
  118305. }
  118306. break;
  118307. case 223: /* expr ::= expr in_op LP exprlist RP */
  118308. {
  118309. if( yymsp[-1].minor.yy14==0 ){
  118310. /* Expressions of the form
  118311. **
  118312. ** expr1 IN ()
  118313. ** expr1 NOT IN ()
  118314. **
  118315. ** simplify to constants 0 (false) and 1 (true), respectively,
  118316. ** regardless of the value of expr1.
  118317. */
  118318. yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_INTEGER, 0, 0, &sqlite3IntTokens[yymsp[-3].minor.yy328]);
  118319. sqlite3ExprDelete(pParse->db, yymsp[-4].minor.yy346.pExpr);
  118320. }else if( yymsp[-1].minor.yy14->nExpr==1 ){
  118321. /* Expressions of the form:
  118322. **
  118323. ** expr1 IN (?1)
  118324. ** expr1 NOT IN (?2)
  118325. **
  118326. ** with exactly one value on the RHS can be simplified to something
  118327. ** like this:
  118328. **
  118329. ** expr1 == ?1
  118330. ** expr1 <> ?2
  118331. **
  118332. ** But, the RHS of the == or <> is marked with the EP_Generic flag
  118333. ** so that it may not contribute to the computation of comparison
  118334. ** affinity or the collating sequence to use for comparison. Otherwise,
  118335. ** the semantics would be subtly different from IN or NOT IN.
  118336. */
  118337. Expr *pRHS = yymsp[-1].minor.yy14->a[0].pExpr;
  118338. yymsp[-1].minor.yy14->a[0].pExpr = 0;
  118339. sqlite3ExprListDelete(pParse->db, yymsp[-1].minor.yy14);
  118340. /* pRHS cannot be NULL because a malloc error would have been detected
  118341. ** before now and control would have never reached this point */
  118342. if( ALWAYS(pRHS) ){
  118343. pRHS->flags &= ~EP_Collate;
  118344. pRHS->flags |= EP_Generic;
  118345. }
  118346. yygotominor.yy346.pExpr = sqlite3PExpr(pParse, yymsp[-3].minor.yy328 ? TK_NE : TK_EQ, yymsp[-4].minor.yy346.pExpr, pRHS, 0);
  118347. }else{
  118348. yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_IN, yymsp[-4].minor.yy346.pExpr, 0, 0);
  118349. if( yygotominor.yy346.pExpr ){
  118350. yygotominor.yy346.pExpr->x.pList = yymsp[-1].minor.yy14;
  118351. sqlite3ExprSetHeightAndFlags(pParse, yygotominor.yy346.pExpr);
  118352. }else{
  118353. sqlite3ExprListDelete(pParse->db, yymsp[-1].minor.yy14);
  118354. }
  118355. if( yymsp[-3].minor.yy328 ) yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy346.pExpr, 0, 0);
  118356. }
  118357. yygotominor.yy346.zStart = yymsp[-4].minor.yy346.zStart;
  118358. yygotominor.yy346.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
  118359. }
  118360. break;
  118361. case 224: /* expr ::= LP select RP */
  118362. {
  118363. yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_SELECT, 0, 0, 0);
  118364. if( yygotominor.yy346.pExpr ){
  118365. yygotominor.yy346.pExpr->x.pSelect = yymsp[-1].minor.yy3;
  118366. ExprSetProperty(yygotominor.yy346.pExpr, EP_xIsSelect|EP_Subquery);
  118367. sqlite3ExprSetHeightAndFlags(pParse, yygotominor.yy346.pExpr);
  118368. }else{
  118369. sqlite3SelectDelete(pParse->db, yymsp[-1].minor.yy3);
  118370. }
  118371. yygotominor.yy346.zStart = yymsp[-2].minor.yy0.z;
  118372. yygotominor.yy346.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
  118373. }
  118374. break;
  118375. case 225: /* expr ::= expr in_op LP select RP */
  118376. {
  118377. yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_IN, yymsp[-4].minor.yy346.pExpr, 0, 0);
  118378. if( yygotominor.yy346.pExpr ){
  118379. yygotominor.yy346.pExpr->x.pSelect = yymsp[-1].minor.yy3;
  118380. ExprSetProperty(yygotominor.yy346.pExpr, EP_xIsSelect|EP_Subquery);
  118381. sqlite3ExprSetHeightAndFlags(pParse, yygotominor.yy346.pExpr);
  118382. }else{
  118383. sqlite3SelectDelete(pParse->db, yymsp[-1].minor.yy3);
  118384. }
  118385. if( yymsp[-3].minor.yy328 ) yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy346.pExpr, 0, 0);
  118386. yygotominor.yy346.zStart = yymsp[-4].minor.yy346.zStart;
  118387. yygotominor.yy346.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
  118388. }
  118389. break;
  118390. case 226: /* expr ::= expr in_op nm dbnm */
  118391. {
  118392. SrcList *pSrc = sqlite3SrcListAppend(pParse->db, 0,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0);
  118393. yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_IN, yymsp[-3].minor.yy346.pExpr, 0, 0);
  118394. if( yygotominor.yy346.pExpr ){
  118395. yygotominor.yy346.pExpr->x.pSelect = sqlite3SelectNew(pParse, 0,pSrc,0,0,0,0,0,0,0);
  118396. ExprSetProperty(yygotominor.yy346.pExpr, EP_xIsSelect|EP_Subquery);
  118397. sqlite3ExprSetHeightAndFlags(pParse, yygotominor.yy346.pExpr);
  118398. }else{
  118399. sqlite3SrcListDelete(pParse->db, pSrc);
  118400. }
  118401. if( yymsp[-2].minor.yy328 ) yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy346.pExpr, 0, 0);
  118402. yygotominor.yy346.zStart = yymsp[-3].minor.yy346.zStart;
  118403. 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];
  118404. }
  118405. break;
  118406. case 227: /* expr ::= EXISTS LP select RP */
  118407. {
  118408. Expr *p = yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_EXISTS, 0, 0, 0);
  118409. if( p ){
  118410. p->x.pSelect = yymsp[-1].minor.yy3;
  118411. ExprSetProperty(p, EP_xIsSelect|EP_Subquery);
  118412. sqlite3ExprSetHeightAndFlags(pParse, p);
  118413. }else{
  118414. sqlite3SelectDelete(pParse->db, yymsp[-1].minor.yy3);
  118415. }
  118416. yygotominor.yy346.zStart = yymsp[-3].minor.yy0.z;
  118417. yygotominor.yy346.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
  118418. }
  118419. break;
  118420. case 228: /* expr ::= CASE case_operand case_exprlist case_else END */
  118421. {
  118422. yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_CASE, yymsp[-3].minor.yy132, 0, 0);
  118423. if( yygotominor.yy346.pExpr ){
  118424. yygotominor.yy346.pExpr->x.pList = yymsp[-1].minor.yy132 ? sqlite3ExprListAppend(pParse,yymsp[-2].minor.yy14,yymsp[-1].minor.yy132) : yymsp[-2].minor.yy14;
  118425. sqlite3ExprSetHeightAndFlags(pParse, yygotominor.yy346.pExpr);
  118426. }else{
  118427. sqlite3ExprListDelete(pParse->db, yymsp[-2].minor.yy14);
  118428. sqlite3ExprDelete(pParse->db, yymsp[-1].minor.yy132);
  118429. }
  118430. yygotominor.yy346.zStart = yymsp[-4].minor.yy0.z;
  118431. yygotominor.yy346.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
  118432. }
  118433. break;
  118434. case 229: /* case_exprlist ::= case_exprlist WHEN expr THEN expr */
  118435. {
  118436. yygotominor.yy14 = sqlite3ExprListAppend(pParse,yymsp[-4].minor.yy14, yymsp[-2].minor.yy346.pExpr);
  118437. yygotominor.yy14 = sqlite3ExprListAppend(pParse,yygotominor.yy14, yymsp[0].minor.yy346.pExpr);
  118438. }
  118439. break;
  118440. case 230: /* case_exprlist ::= WHEN expr THEN expr */
  118441. {
  118442. yygotominor.yy14 = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy346.pExpr);
  118443. yygotominor.yy14 = sqlite3ExprListAppend(pParse,yygotominor.yy14, yymsp[0].minor.yy346.pExpr);
  118444. }
  118445. break;
  118446. case 237: /* nexprlist ::= nexprlist COMMA expr */
  118447. {yygotominor.yy14 = sqlite3ExprListAppend(pParse,yymsp[-2].minor.yy14,yymsp[0].minor.yy346.pExpr);}
  118448. break;
  118449. case 238: /* nexprlist ::= expr */
  118450. {yygotominor.yy14 = sqlite3ExprListAppend(pParse,0,yymsp[0].minor.yy346.pExpr);}
  118451. break;
  118452. case 239: /* cmd ::= createkw uniqueflag INDEX ifnotexists nm dbnm ON nm LP idxlist RP where_opt */
  118453. {
  118454. sqlite3CreateIndex(pParse, &yymsp[-7].minor.yy0, &yymsp[-6].minor.yy0,
  118455. sqlite3SrcListAppend(pParse->db,0,&yymsp[-4].minor.yy0,0), yymsp[-2].minor.yy14, yymsp[-10].minor.yy328,
  118456. &yymsp[-11].minor.yy0, yymsp[0].minor.yy132, SQLITE_SO_ASC, yymsp[-8].minor.yy328);
  118457. }
  118458. break;
  118459. case 240: /* uniqueflag ::= UNIQUE */
  118460. case 291: /* raisetype ::= ABORT */ yytestcase(yyruleno==291);
  118461. {yygotominor.yy328 = OE_Abort;}
  118462. break;
  118463. case 241: /* uniqueflag ::= */
  118464. {yygotominor.yy328 = OE_None;}
  118465. break;
  118466. case 244: /* idxlist ::= idxlist COMMA nm collate sortorder */
  118467. {
  118468. Expr *p = sqlite3ExprAddCollateToken(pParse, 0, &yymsp[-1].minor.yy0, 1);
  118469. yygotominor.yy14 = sqlite3ExprListAppend(pParse,yymsp[-4].minor.yy14, p);
  118470. sqlite3ExprListSetName(pParse,yygotominor.yy14,&yymsp[-2].minor.yy0,1);
  118471. sqlite3ExprListCheckLength(pParse, yygotominor.yy14, "index");
  118472. if( yygotominor.yy14 ) yygotominor.yy14->a[yygotominor.yy14->nExpr-1].sortOrder = (u8)yymsp[0].minor.yy328;
  118473. }
  118474. break;
  118475. case 245: /* idxlist ::= nm collate sortorder */
  118476. {
  118477. Expr *p = sqlite3ExprAddCollateToken(pParse, 0, &yymsp[-1].minor.yy0, 1);
  118478. yygotominor.yy14 = sqlite3ExprListAppend(pParse,0, p);
  118479. sqlite3ExprListSetName(pParse, yygotominor.yy14, &yymsp[-2].minor.yy0, 1);
  118480. sqlite3ExprListCheckLength(pParse, yygotominor.yy14, "index");
  118481. if( yygotominor.yy14 ) yygotominor.yy14->a[yygotominor.yy14->nExpr-1].sortOrder = (u8)yymsp[0].minor.yy328;
  118482. }
  118483. break;
  118484. case 246: /* collate ::= */
  118485. {yygotominor.yy0.z = 0; yygotominor.yy0.n = 0;}
  118486. break;
  118487. case 248: /* cmd ::= DROP INDEX ifexists fullname */
  118488. {sqlite3DropIndex(pParse, yymsp[0].minor.yy65, yymsp[-1].minor.yy328);}
  118489. break;
  118490. case 249: /* cmd ::= VACUUM */
  118491. case 250: /* cmd ::= VACUUM nm */ yytestcase(yyruleno==250);
  118492. {sqlite3Vacuum(pParse);}
  118493. break;
  118494. case 251: /* cmd ::= PRAGMA nm dbnm */
  118495. {sqlite3Pragma(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0,0,0);}
  118496. break;
  118497. case 252: /* cmd ::= PRAGMA nm dbnm EQ nmnum */
  118498. {sqlite3Pragma(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0,0);}
  118499. break;
  118500. case 253: /* cmd ::= PRAGMA nm dbnm LP nmnum RP */
  118501. {sqlite3Pragma(pParse,&yymsp[-4].minor.yy0,&yymsp[-3].minor.yy0,&yymsp[-1].minor.yy0,0);}
  118502. break;
  118503. case 254: /* cmd ::= PRAGMA nm dbnm EQ minus_num */
  118504. {sqlite3Pragma(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0,1);}
  118505. break;
  118506. case 255: /* cmd ::= PRAGMA nm dbnm LP minus_num RP */
  118507. {sqlite3Pragma(pParse,&yymsp[-4].minor.yy0,&yymsp[-3].minor.yy0,&yymsp[-1].minor.yy0,1);}
  118508. break;
  118509. case 264: /* cmd ::= createkw trigger_decl BEGIN trigger_cmd_list END */
  118510. {
  118511. Token all;
  118512. all.z = yymsp[-3].minor.yy0.z;
  118513. all.n = (int)(yymsp[0].minor.yy0.z - yymsp[-3].minor.yy0.z) + yymsp[0].minor.yy0.n;
  118514. sqlite3FinishTrigger(pParse, yymsp[-1].minor.yy473, &all);
  118515. }
  118516. break;
  118517. case 265: /* trigger_decl ::= temp TRIGGER ifnotexists nm dbnm trigger_time trigger_event ON fullname foreach_clause when_clause */
  118518. {
  118519. 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);
  118520. yygotominor.yy0 = (yymsp[-6].minor.yy0.n==0?yymsp[-7].minor.yy0:yymsp[-6].minor.yy0);
  118521. }
  118522. break;
  118523. case 266: /* trigger_time ::= BEFORE */
  118524. case 269: /* trigger_time ::= */ yytestcase(yyruleno==269);
  118525. { yygotominor.yy328 = TK_BEFORE; }
  118526. break;
  118527. case 267: /* trigger_time ::= AFTER */
  118528. { yygotominor.yy328 = TK_AFTER; }
  118529. break;
  118530. case 268: /* trigger_time ::= INSTEAD OF */
  118531. { yygotominor.yy328 = TK_INSTEAD;}
  118532. break;
  118533. case 270: /* trigger_event ::= DELETE|INSERT */
  118534. case 271: /* trigger_event ::= UPDATE */ yytestcase(yyruleno==271);
  118535. {yygotominor.yy378.a = yymsp[0].major; yygotominor.yy378.b = 0;}
  118536. break;
  118537. case 272: /* trigger_event ::= UPDATE OF idlist */
  118538. {yygotominor.yy378.a = TK_UPDATE; yygotominor.yy378.b = yymsp[0].minor.yy408;}
  118539. break;
  118540. case 275: /* when_clause ::= */
  118541. case 296: /* key_opt ::= */ yytestcase(yyruleno==296);
  118542. { yygotominor.yy132 = 0; }
  118543. break;
  118544. case 276: /* when_clause ::= WHEN expr */
  118545. case 297: /* key_opt ::= KEY expr */ yytestcase(yyruleno==297);
  118546. { yygotominor.yy132 = yymsp[0].minor.yy346.pExpr; }
  118547. break;
  118548. case 277: /* trigger_cmd_list ::= trigger_cmd_list trigger_cmd SEMI */
  118549. {
  118550. assert( yymsp[-2].minor.yy473!=0 );
  118551. yymsp[-2].minor.yy473->pLast->pNext = yymsp[-1].minor.yy473;
  118552. yymsp[-2].minor.yy473->pLast = yymsp[-1].minor.yy473;
  118553. yygotominor.yy473 = yymsp[-2].minor.yy473;
  118554. }
  118555. break;
  118556. case 278: /* trigger_cmd_list ::= trigger_cmd SEMI */
  118557. {
  118558. assert( yymsp[-1].minor.yy473!=0 );
  118559. yymsp[-1].minor.yy473->pLast = yymsp[-1].minor.yy473;
  118560. yygotominor.yy473 = yymsp[-1].minor.yy473;
  118561. }
  118562. break;
  118563. case 280: /* trnm ::= nm DOT nm */
  118564. {
  118565. yygotominor.yy0 = yymsp[0].minor.yy0;
  118566. sqlite3ErrorMsg(pParse,
  118567. "qualified table names are not allowed on INSERT, UPDATE, and DELETE "
  118568. "statements within triggers");
  118569. }
  118570. break;
  118571. case 282: /* tridxby ::= INDEXED BY nm */
  118572. {
  118573. sqlite3ErrorMsg(pParse,
  118574. "the INDEXED BY clause is not allowed on UPDATE or DELETE statements "
  118575. "within triggers");
  118576. }
  118577. break;
  118578. case 283: /* tridxby ::= NOT INDEXED */
  118579. {
  118580. sqlite3ErrorMsg(pParse,
  118581. "the NOT INDEXED clause is not allowed on UPDATE or DELETE statements "
  118582. "within triggers");
  118583. }
  118584. break;
  118585. case 284: /* trigger_cmd ::= UPDATE orconf trnm tridxby SET setlist where_opt */
  118586. { yygotominor.yy473 = sqlite3TriggerUpdateStep(pParse->db, &yymsp[-4].minor.yy0, yymsp[-1].minor.yy14, yymsp[0].minor.yy132, yymsp[-5].minor.yy186); }
  118587. break;
  118588. case 285: /* trigger_cmd ::= insert_cmd INTO trnm inscollist_opt select */
  118589. {yygotominor.yy473 = sqlite3TriggerInsertStep(pParse->db, &yymsp[-2].minor.yy0, yymsp[-1].minor.yy408, yymsp[0].minor.yy3, yymsp[-4].minor.yy186);}
  118590. break;
  118591. case 286: /* trigger_cmd ::= DELETE FROM trnm tridxby where_opt */
  118592. {yygotominor.yy473 = sqlite3TriggerDeleteStep(pParse->db, &yymsp[-2].minor.yy0, yymsp[0].minor.yy132);}
  118593. break;
  118594. case 287: /* trigger_cmd ::= select */
  118595. {yygotominor.yy473 = sqlite3TriggerSelectStep(pParse->db, yymsp[0].minor.yy3); }
  118596. break;
  118597. case 288: /* expr ::= RAISE LP IGNORE RP */
  118598. {
  118599. yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_RAISE, 0, 0, 0);
  118600. if( yygotominor.yy346.pExpr ){
  118601. yygotominor.yy346.pExpr->affinity = OE_Ignore;
  118602. }
  118603. yygotominor.yy346.zStart = yymsp[-3].minor.yy0.z;
  118604. yygotominor.yy346.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
  118605. }
  118606. break;
  118607. case 289: /* expr ::= RAISE LP raisetype COMMA nm RP */
  118608. {
  118609. yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_RAISE, 0, 0, &yymsp[-1].minor.yy0);
  118610. if( yygotominor.yy346.pExpr ) {
  118611. yygotominor.yy346.pExpr->affinity = (char)yymsp[-3].minor.yy328;
  118612. }
  118613. yygotominor.yy346.zStart = yymsp[-5].minor.yy0.z;
  118614. yygotominor.yy346.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
  118615. }
  118616. break;
  118617. case 290: /* raisetype ::= ROLLBACK */
  118618. {yygotominor.yy328 = OE_Rollback;}
  118619. break;
  118620. case 292: /* raisetype ::= FAIL */
  118621. {yygotominor.yy328 = OE_Fail;}
  118622. break;
  118623. case 293: /* cmd ::= DROP TRIGGER ifexists fullname */
  118624. {
  118625. sqlite3DropTrigger(pParse,yymsp[0].minor.yy65,yymsp[-1].minor.yy328);
  118626. }
  118627. break;
  118628. case 294: /* cmd ::= ATTACH database_kw_opt expr AS expr key_opt */
  118629. {
  118630. sqlite3Attach(pParse, yymsp[-3].minor.yy346.pExpr, yymsp[-1].minor.yy346.pExpr, yymsp[0].minor.yy132);
  118631. }
  118632. break;
  118633. case 295: /* cmd ::= DETACH database_kw_opt expr */
  118634. {
  118635. sqlite3Detach(pParse, yymsp[0].minor.yy346.pExpr);
  118636. }
  118637. break;
  118638. case 300: /* cmd ::= REINDEX */
  118639. {sqlite3Reindex(pParse, 0, 0);}
  118640. break;
  118641. case 301: /* cmd ::= REINDEX nm dbnm */
  118642. {sqlite3Reindex(pParse, &yymsp[-1].minor.yy0, &yymsp[0].minor.yy0);}
  118643. break;
  118644. case 302: /* cmd ::= ANALYZE */
  118645. {sqlite3Analyze(pParse, 0, 0);}
  118646. break;
  118647. case 303: /* cmd ::= ANALYZE nm dbnm */
  118648. {sqlite3Analyze(pParse, &yymsp[-1].minor.yy0, &yymsp[0].minor.yy0);}
  118649. break;
  118650. case 304: /* cmd ::= ALTER TABLE fullname RENAME TO nm */
  118651. {
  118652. sqlite3AlterRenameTable(pParse,yymsp[-3].minor.yy65,&yymsp[0].minor.yy0);
  118653. }
  118654. break;
  118655. case 305: /* cmd ::= ALTER TABLE add_column_fullname ADD kwcolumn_opt column */
  118656. {
  118657. sqlite3AlterFinishAddColumn(pParse, &yymsp[0].minor.yy0);
  118658. }
  118659. break;
  118660. case 306: /* add_column_fullname ::= fullname */
  118661. {
  118662. pParse->db->lookaside.bEnabled = 0;
  118663. sqlite3AlterBeginAddColumn(pParse, yymsp[0].minor.yy65);
  118664. }
  118665. break;
  118666. case 309: /* cmd ::= create_vtab */
  118667. {sqlite3VtabFinishParse(pParse,0);}
  118668. break;
  118669. case 310: /* cmd ::= create_vtab LP vtabarglist RP */
  118670. {sqlite3VtabFinishParse(pParse,&yymsp[0].minor.yy0);}
  118671. break;
  118672. case 311: /* create_vtab ::= createkw VIRTUAL TABLE ifnotexists nm dbnm USING nm */
  118673. {
  118674. sqlite3VtabBeginParse(pParse, &yymsp[-3].minor.yy0, &yymsp[-2].minor.yy0, &yymsp[0].minor.yy0, yymsp[-4].minor.yy328);
  118675. }
  118676. break;
  118677. case 314: /* vtabarg ::= */
  118678. {sqlite3VtabArgInit(pParse);}
  118679. break;
  118680. case 316: /* vtabargtoken ::= ANY */
  118681. case 317: /* vtabargtoken ::= lp anylist RP */ yytestcase(yyruleno==317);
  118682. case 318: /* lp ::= LP */ yytestcase(yyruleno==318);
  118683. {sqlite3VtabArgExtend(pParse,&yymsp[0].minor.yy0);}
  118684. break;
  118685. case 322: /* with ::= */
  118686. {yygotominor.yy59 = 0;}
  118687. break;
  118688. case 323: /* with ::= WITH wqlist */
  118689. case 324: /* with ::= WITH RECURSIVE wqlist */ yytestcase(yyruleno==324);
  118690. { yygotominor.yy59 = yymsp[0].minor.yy59; }
  118691. break;
  118692. case 325: /* wqlist ::= nm idxlist_opt AS LP select RP */
  118693. {
  118694. yygotominor.yy59 = sqlite3WithAdd(pParse, 0, &yymsp[-5].minor.yy0, yymsp[-4].minor.yy14, yymsp[-1].minor.yy3);
  118695. }
  118696. break;
  118697. case 326: /* wqlist ::= wqlist COMMA nm idxlist_opt AS LP select RP */
  118698. {
  118699. yygotominor.yy59 = sqlite3WithAdd(pParse, yymsp[-7].minor.yy59, &yymsp[-5].minor.yy0, yymsp[-4].minor.yy14, yymsp[-1].minor.yy3);
  118700. }
  118701. break;
  118702. default:
  118703. /* (0) input ::= cmdlist */ yytestcase(yyruleno==0);
  118704. /* (1) cmdlist ::= cmdlist ecmd */ yytestcase(yyruleno==1);
  118705. /* (2) cmdlist ::= ecmd */ yytestcase(yyruleno==2);
  118706. /* (3) ecmd ::= SEMI */ yytestcase(yyruleno==3);
  118707. /* (4) ecmd ::= explain cmdx SEMI */ yytestcase(yyruleno==4);
  118708. /* (10) trans_opt ::= */ yytestcase(yyruleno==10);
  118709. /* (11) trans_opt ::= TRANSACTION */ yytestcase(yyruleno==11);
  118710. /* (12) trans_opt ::= TRANSACTION nm */ yytestcase(yyruleno==12);
  118711. /* (20) savepoint_opt ::= SAVEPOINT */ yytestcase(yyruleno==20);
  118712. /* (21) savepoint_opt ::= */ yytestcase(yyruleno==21);
  118713. /* (25) cmd ::= create_table create_table_args */ yytestcase(yyruleno==25);
  118714. /* (36) columnlist ::= columnlist COMMA column */ yytestcase(yyruleno==36);
  118715. /* (37) columnlist ::= column */ yytestcase(yyruleno==37);
  118716. /* (43) type ::= */ yytestcase(yyruleno==43);
  118717. /* (50) signed ::= plus_num */ yytestcase(yyruleno==50);
  118718. /* (51) signed ::= minus_num */ yytestcase(yyruleno==51);
  118719. /* (52) carglist ::= carglist ccons */ yytestcase(yyruleno==52);
  118720. /* (53) carglist ::= */ yytestcase(yyruleno==53);
  118721. /* (60) ccons ::= NULL onconf */ yytestcase(yyruleno==60);
  118722. /* (88) conslist ::= conslist tconscomma tcons */ yytestcase(yyruleno==88);
  118723. /* (89) conslist ::= tcons */ yytestcase(yyruleno==89);
  118724. /* (91) tconscomma ::= */ yytestcase(yyruleno==91);
  118725. /* (273) foreach_clause ::= */ yytestcase(yyruleno==273);
  118726. /* (274) foreach_clause ::= FOR EACH ROW */ yytestcase(yyruleno==274);
  118727. /* (281) tridxby ::= */ yytestcase(yyruleno==281);
  118728. /* (298) database_kw_opt ::= DATABASE */ yytestcase(yyruleno==298);
  118729. /* (299) database_kw_opt ::= */ yytestcase(yyruleno==299);
  118730. /* (307) kwcolumn_opt ::= */ yytestcase(yyruleno==307);
  118731. /* (308) kwcolumn_opt ::= COLUMNKW */ yytestcase(yyruleno==308);
  118732. /* (312) vtabarglist ::= vtabarg */ yytestcase(yyruleno==312);
  118733. /* (313) vtabarglist ::= vtabarglist COMMA vtabarg */ yytestcase(yyruleno==313);
  118734. /* (315) vtabarg ::= vtabarg vtabargtoken */ yytestcase(yyruleno==315);
  118735. /* (319) anylist ::= */ yytestcase(yyruleno==319);
  118736. /* (320) anylist ::= anylist LP anylist RP */ yytestcase(yyruleno==320);
  118737. /* (321) anylist ::= anylist ANY */ yytestcase(yyruleno==321);
  118738. break;
  118739. };
  118740. assert( yyruleno>=0 && yyruleno<sizeof(yyRuleInfo)/sizeof(yyRuleInfo[0]) );
  118741. yygoto = yyRuleInfo[yyruleno].lhs;
  118742. yysize = yyRuleInfo[yyruleno].nrhs;
  118743. yypParser->yyidx -= yysize;
  118744. yyact = yy_find_reduce_action(yymsp[-yysize].stateno,(YYCODETYPE)yygoto);
  118745. if( yyact < YYNSTATE ){
  118746. #ifdef NDEBUG
  118747. /* If we are not debugging and the reduce action popped at least
  118748. ** one element off the stack, then we can push the new element back
  118749. ** onto the stack here, and skip the stack overflow test in yy_shift().
  118750. ** That gives a significant speed improvement. */
  118751. if( yysize ){
  118752. yypParser->yyidx++;
  118753. yymsp -= yysize-1;
  118754. yymsp->stateno = (YYACTIONTYPE)yyact;
  118755. yymsp->major = (YYCODETYPE)yygoto;
  118756. yymsp->minor = yygotominor;
  118757. }else
  118758. #endif
  118759. {
  118760. yy_shift(yypParser,yyact,yygoto,&yygotominor);
  118761. }
  118762. }else{
  118763. assert( yyact == YYNSTATE + YYNRULE + 1 );
  118764. yy_accept(yypParser);
  118765. }
  118766. }
  118767. /*
  118768. ** The following code executes when the parse fails
  118769. */
  118770. #ifndef YYNOERRORRECOVERY
  118771. static void yy_parse_failed(
  118772. yyParser *yypParser /* The parser */
  118773. ){
  118774. sqlite3ParserARG_FETCH;
  118775. #ifndef NDEBUG
  118776. if( yyTraceFILE ){
  118777. fprintf(yyTraceFILE,"%sFail!\n",yyTracePrompt);
  118778. }
  118779. #endif
  118780. while( yypParser->yyidx>=0 ) yy_pop_parser_stack(yypParser);
  118781. /* Here code is inserted which will be executed whenever the
  118782. ** parser fails */
  118783. sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
  118784. }
  118785. #endif /* YYNOERRORRECOVERY */
  118786. /*
  118787. ** The following code executes when a syntax error first occurs.
  118788. */
  118789. static void yy_syntax_error(
  118790. yyParser *yypParser, /* The parser */
  118791. int yymajor, /* The major type of the error token */
  118792. YYMINORTYPE yyminor /* The minor type of the error token */
  118793. ){
  118794. sqlite3ParserARG_FETCH;
  118795. #define TOKEN (yyminor.yy0)
  118796. UNUSED_PARAMETER(yymajor); /* Silence some compiler warnings */
  118797. assert( TOKEN.z[0] ); /* The tokenizer always gives us a token */
  118798. sqlite3ErrorMsg(pParse, "near \"%T\": syntax error", &TOKEN);
  118799. sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
  118800. }
  118801. /*
  118802. ** The following is executed when the parser accepts
  118803. */
  118804. static void yy_accept(
  118805. yyParser *yypParser /* The parser */
  118806. ){
  118807. sqlite3ParserARG_FETCH;
  118808. #ifndef NDEBUG
  118809. if( yyTraceFILE ){
  118810. fprintf(yyTraceFILE,"%sAccept!\n",yyTracePrompt);
  118811. }
  118812. #endif
  118813. while( yypParser->yyidx>=0 ) yy_pop_parser_stack(yypParser);
  118814. /* Here code is inserted which will be executed whenever the
  118815. ** parser accepts */
  118816. sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
  118817. }
  118818. /* The main parser program.
  118819. ** The first argument is a pointer to a structure obtained from
  118820. ** "sqlite3ParserAlloc" which describes the current state of the parser.
  118821. ** The second argument is the major token number. The third is
  118822. ** the minor token. The fourth optional argument is whatever the
  118823. ** user wants (and specified in the grammar) and is available for
  118824. ** use by the action routines.
  118825. **
  118826. ** Inputs:
  118827. ** <ul>
  118828. ** <li> A pointer to the parser (an opaque structure.)
  118829. ** <li> The major token number.
  118830. ** <li> The minor token number.
  118831. ** <li> An option argument of a grammar-specified type.
  118832. ** </ul>
  118833. **
  118834. ** Outputs:
  118835. ** None.
  118836. */
  118837. SQLITE_PRIVATE void sqlite3Parser(
  118838. void *yyp, /* The parser */
  118839. int yymajor, /* The major token code number */
  118840. sqlite3ParserTOKENTYPE yyminor /* The value for the token */
  118841. sqlite3ParserARG_PDECL /* Optional %extra_argument parameter */
  118842. ){
  118843. YYMINORTYPE yyminorunion;
  118844. int yyact; /* The parser action. */
  118845. #if !defined(YYERRORSYMBOL) && !defined(YYNOERRORRECOVERY)
  118846. int yyendofinput; /* True if we are at the end of input */
  118847. #endif
  118848. #ifdef YYERRORSYMBOL
  118849. int yyerrorhit = 0; /* True if yymajor has invoked an error */
  118850. #endif
  118851. yyParser *yypParser; /* The parser */
  118852. /* (re)initialize the parser, if necessary */
  118853. yypParser = (yyParser*)yyp;
  118854. if( yypParser->yyidx<0 ){
  118855. #if YYSTACKDEPTH<=0
  118856. if( yypParser->yystksz <=0 ){
  118857. /*memset(&yyminorunion, 0, sizeof(yyminorunion));*/
  118858. yyminorunion = yyzerominor;
  118859. yyStackOverflow(yypParser, &yyminorunion);
  118860. return;
  118861. }
  118862. #endif
  118863. yypParser->yyidx = 0;
  118864. yypParser->yyerrcnt = -1;
  118865. yypParser->yystack[0].stateno = 0;
  118866. yypParser->yystack[0].major = 0;
  118867. }
  118868. yyminorunion.yy0 = yyminor;
  118869. #if !defined(YYERRORSYMBOL) && !defined(YYNOERRORRECOVERY)
  118870. yyendofinput = (yymajor==0);
  118871. #endif
  118872. sqlite3ParserARG_STORE;
  118873. #ifndef NDEBUG
  118874. if( yyTraceFILE ){
  118875. fprintf(yyTraceFILE,"%sInput %s\n",yyTracePrompt,yyTokenName[yymajor]);
  118876. }
  118877. #endif
  118878. do{
  118879. yyact = yy_find_shift_action(yypParser,(YYCODETYPE)yymajor);
  118880. if( yyact<YYNSTATE ){
  118881. yy_shift(yypParser,yyact,yymajor,&yyminorunion);
  118882. yypParser->yyerrcnt--;
  118883. yymajor = YYNOCODE;
  118884. }else if( yyact < YYNSTATE + YYNRULE ){
  118885. yy_reduce(yypParser,yyact-YYNSTATE);
  118886. }else{
  118887. assert( yyact == YY_ERROR_ACTION );
  118888. #ifdef YYERRORSYMBOL
  118889. int yymx;
  118890. #endif
  118891. #ifndef NDEBUG
  118892. if( yyTraceFILE ){
  118893. fprintf(yyTraceFILE,"%sSyntax Error!\n",yyTracePrompt);
  118894. }
  118895. #endif
  118896. #ifdef YYERRORSYMBOL
  118897. /* A syntax error has occurred.
  118898. ** The response to an error depends upon whether or not the
  118899. ** grammar defines an error token "ERROR".
  118900. **
  118901. ** This is what we do if the grammar does define ERROR:
  118902. **
  118903. ** * Call the %syntax_error function.
  118904. **
  118905. ** * Begin popping the stack until we enter a state where
  118906. ** it is legal to shift the error symbol, then shift
  118907. ** the error symbol.
  118908. **
  118909. ** * Set the error count to three.
  118910. **
  118911. ** * Begin accepting and shifting new tokens. No new error
  118912. ** processing will occur until three tokens have been
  118913. ** shifted successfully.
  118914. **
  118915. */
  118916. if( yypParser->yyerrcnt<0 ){
  118917. yy_syntax_error(yypParser,yymajor,yyminorunion);
  118918. }
  118919. yymx = yypParser->yystack[yypParser->yyidx].major;
  118920. if( yymx==YYERRORSYMBOL || yyerrorhit ){
  118921. #ifndef NDEBUG
  118922. if( yyTraceFILE ){
  118923. fprintf(yyTraceFILE,"%sDiscard input token %s\n",
  118924. yyTracePrompt,yyTokenName[yymajor]);
  118925. }
  118926. #endif
  118927. yy_destructor(yypParser, (YYCODETYPE)yymajor,&yyminorunion);
  118928. yymajor = YYNOCODE;
  118929. }else{
  118930. while(
  118931. yypParser->yyidx >= 0 &&
  118932. yymx != YYERRORSYMBOL &&
  118933. (yyact = yy_find_reduce_action(
  118934. yypParser->yystack[yypParser->yyidx].stateno,
  118935. YYERRORSYMBOL)) >= YYNSTATE
  118936. ){
  118937. yy_pop_parser_stack(yypParser);
  118938. }
  118939. if( yypParser->yyidx < 0 || yymajor==0 ){
  118940. yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion);
  118941. yy_parse_failed(yypParser);
  118942. yymajor = YYNOCODE;
  118943. }else if( yymx!=YYERRORSYMBOL ){
  118944. YYMINORTYPE u2;
  118945. u2.YYERRSYMDT = 0;
  118946. yy_shift(yypParser,yyact,YYERRORSYMBOL,&u2);
  118947. }
  118948. }
  118949. yypParser->yyerrcnt = 3;
  118950. yyerrorhit = 1;
  118951. #elif defined(YYNOERRORRECOVERY)
  118952. /* If the YYNOERRORRECOVERY macro is defined, then do not attempt to
  118953. ** do any kind of error recovery. Instead, simply invoke the syntax
  118954. ** error routine and continue going as if nothing had happened.
  118955. **
  118956. ** Applications can set this macro (for example inside %include) if
  118957. ** they intend to abandon the parse upon the first syntax error seen.
  118958. */
  118959. yy_syntax_error(yypParser,yymajor,yyminorunion);
  118960. yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion);
  118961. yymajor = YYNOCODE;
  118962. #else /* YYERRORSYMBOL is not defined */
  118963. /* This is what we do if the grammar does not define ERROR:
  118964. **
  118965. ** * Report an error message, and throw away the input token.
  118966. **
  118967. ** * If the input token is $, then fail the parse.
  118968. **
  118969. ** As before, subsequent error messages are suppressed until
  118970. ** three input tokens have been successfully shifted.
  118971. */
  118972. if( yypParser->yyerrcnt<=0 ){
  118973. yy_syntax_error(yypParser,yymajor,yyminorunion);
  118974. }
  118975. yypParser->yyerrcnt = 3;
  118976. yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion);
  118977. if( yyendofinput ){
  118978. yy_parse_failed(yypParser);
  118979. }
  118980. yymajor = YYNOCODE;
  118981. #endif
  118982. }
  118983. }while( yymajor!=YYNOCODE && yypParser->yyidx>=0 );
  118984. return;
  118985. }
  118986. /************** End of parse.c ***********************************************/
  118987. /************** Begin file tokenize.c ****************************************/
  118988. /*
  118989. ** 2001 September 15
  118990. **
  118991. ** The author disclaims copyright to this source code. In place of
  118992. ** a legal notice, here is a blessing:
  118993. **
  118994. ** May you do good and not evil.
  118995. ** May you find forgiveness for yourself and forgive others.
  118996. ** May you share freely, never taking more than you give.
  118997. **
  118998. *************************************************************************
  118999. ** An tokenizer for SQL
  119000. **
  119001. ** This file contains C code that splits an SQL input string up into
  119002. ** individual tokens and sends those tokens one-by-one over to the
  119003. ** parser for analysis.
  119004. */
  119005. /* #include <stdlib.h> */
  119006. /*
  119007. ** The charMap() macro maps alphabetic characters into their
  119008. ** lower-case ASCII equivalent. On ASCII machines, this is just
  119009. ** an upper-to-lower case map. On EBCDIC machines we also need
  119010. ** to adjust the encoding. Only alphabetic characters and underscores
  119011. ** need to be translated.
  119012. */
  119013. #ifdef SQLITE_ASCII
  119014. # define charMap(X) sqlite3UpperToLower[(unsigned char)X]
  119015. #endif
  119016. #ifdef SQLITE_EBCDIC
  119017. # define charMap(X) ebcdicToAscii[(unsigned char)X]
  119018. const unsigned char ebcdicToAscii[] = {
  119019. /* 0 1 2 3 4 5 6 7 8 9 A B C D E F */
  119020. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0x */
  119021. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 1x */
  119022. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 2x */
  119023. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 3x */
  119024. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 4x */
  119025. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 5x */
  119026. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 95, 0, 0, /* 6x */
  119027. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 7x */
  119028. 0, 97, 98, 99,100,101,102,103,104,105, 0, 0, 0, 0, 0, 0, /* 8x */
  119029. 0,106,107,108,109,110,111,112,113,114, 0, 0, 0, 0, 0, 0, /* 9x */
  119030. 0, 0,115,116,117,118,119,120,121,122, 0, 0, 0, 0, 0, 0, /* Ax */
  119031. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Bx */
  119032. 0, 97, 98, 99,100,101,102,103,104,105, 0, 0, 0, 0, 0, 0, /* Cx */
  119033. 0,106,107,108,109,110,111,112,113,114, 0, 0, 0, 0, 0, 0, /* Dx */
  119034. 0, 0,115,116,117,118,119,120,121,122, 0, 0, 0, 0, 0, 0, /* Ex */
  119035. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Fx */
  119036. };
  119037. #endif
  119038. /*
  119039. ** The sqlite3KeywordCode function looks up an identifier to determine if
  119040. ** it is a keyword. If it is a keyword, the token code of that keyword is
  119041. ** returned. If the input is not a keyword, TK_ID is returned.
  119042. **
  119043. ** The implementation of this routine was generated by a program,
  119044. ** mkkeywordhash.h, located in the tool subdirectory of the distribution.
  119045. ** The output of the mkkeywordhash.c program is written into a file
  119046. ** named keywordhash.h and then included into this source file by
  119047. ** the #include below.
  119048. */
  119049. /************** Include keywordhash.h in the middle of tokenize.c ************/
  119050. /************** Begin file keywordhash.h *************************************/
  119051. /***** This file contains automatically generated code ******
  119052. **
  119053. ** The code in this file has been automatically generated by
  119054. **
  119055. ** sqlite/tool/mkkeywordhash.c
  119056. **
  119057. ** The code in this file implements a function that determines whether
  119058. ** or not a given identifier is really an SQL keyword. The same thing
  119059. ** might be implemented more directly using a hand-written hash table.
  119060. ** But by using this automatically generated code, the size of the code
  119061. ** is substantially reduced. This is important for embedded applications
  119062. ** on platforms with limited memory.
  119063. */
  119064. /* Hash score: 182 */
  119065. static int keywordCode(const char *z, int n){
  119066. /* zText[] encodes 834 bytes of keywords in 554 bytes */
  119067. /* REINDEXEDESCAPEACHECKEYBEFOREIGNOREGEXPLAINSTEADDATABASELECT */
  119068. /* ABLEFTHENDEFERRABLELSEXCEPTRANSACTIONATURALTERAISEXCLUSIVE */
  119069. /* XISTSAVEPOINTERSECTRIGGEREFERENCESCONSTRAINTOFFSETEMPORARY */
  119070. /* UNIQUERYWITHOUTERELEASEATTACHAVINGROUPDATEBEGINNERECURSIVE */
  119071. /* BETWEENOTNULLIKECASCADELETECASECOLLATECREATECURRENT_DATEDETACH */
  119072. /* IMMEDIATEJOINSERTMATCHPLANALYZEPRAGMABORTVALUESVIRTUALIMITWHEN */
  119073. /* WHERENAMEAFTEREPLACEANDEFAULTAUTOINCREMENTCASTCOLUMNCOMMIT */
  119074. /* CONFLICTCROSSCURRENT_TIMESTAMPRIMARYDEFERREDISTINCTDROPFAIL */
  119075. /* FROMFULLGLOBYIFISNULLORDERESTRICTRIGHTROLLBACKROWUNIONUSING */
  119076. /* VACUUMVIEWINITIALLY */
  119077. static const char zText[553] = {
  119078. 'R','E','I','N','D','E','X','E','D','E','S','C','A','P','E','A','C','H',
  119079. 'E','C','K','E','Y','B','E','F','O','R','E','I','G','N','O','R','E','G',
  119080. 'E','X','P','L','A','I','N','S','T','E','A','D','D','A','T','A','B','A',
  119081. 'S','E','L','E','C','T','A','B','L','E','F','T','H','E','N','D','E','F',
  119082. 'E','R','R','A','B','L','E','L','S','E','X','C','E','P','T','R','A','N',
  119083. 'S','A','C','T','I','O','N','A','T','U','R','A','L','T','E','R','A','I',
  119084. 'S','E','X','C','L','U','S','I','V','E','X','I','S','T','S','A','V','E',
  119085. 'P','O','I','N','T','E','R','S','E','C','T','R','I','G','G','E','R','E',
  119086. 'F','E','R','E','N','C','E','S','C','O','N','S','T','R','A','I','N','T',
  119087. 'O','F','F','S','E','T','E','M','P','O','R','A','R','Y','U','N','I','Q',
  119088. 'U','E','R','Y','W','I','T','H','O','U','T','E','R','E','L','E','A','S',
  119089. 'E','A','T','T','A','C','H','A','V','I','N','G','R','O','U','P','D','A',
  119090. 'T','E','B','E','G','I','N','N','E','R','E','C','U','R','S','I','V','E',
  119091. 'B','E','T','W','E','E','N','O','T','N','U','L','L','I','K','E','C','A',
  119092. 'S','C','A','D','E','L','E','T','E','C','A','S','E','C','O','L','L','A',
  119093. 'T','E','C','R','E','A','T','E','C','U','R','R','E','N','T','_','D','A',
  119094. 'T','E','D','E','T','A','C','H','I','M','M','E','D','I','A','T','E','J',
  119095. 'O','I','N','S','E','R','T','M','A','T','C','H','P','L','A','N','A','L',
  119096. 'Y','Z','E','P','R','A','G','M','A','B','O','R','T','V','A','L','U','E',
  119097. 'S','V','I','R','T','U','A','L','I','M','I','T','W','H','E','N','W','H',
  119098. 'E','R','E','N','A','M','E','A','F','T','E','R','E','P','L','A','C','E',
  119099. 'A','N','D','E','F','A','U','L','T','A','U','T','O','I','N','C','R','E',
  119100. 'M','E','N','T','C','A','S','T','C','O','L','U','M','N','C','O','M','M',
  119101. 'I','T','C','O','N','F','L','I','C','T','C','R','O','S','S','C','U','R',
  119102. 'R','E','N','T','_','T','I','M','E','S','T','A','M','P','R','I','M','A',
  119103. 'R','Y','D','E','F','E','R','R','E','D','I','S','T','I','N','C','T','D',
  119104. 'R','O','P','F','A','I','L','F','R','O','M','F','U','L','L','G','L','O',
  119105. 'B','Y','I','F','I','S','N','U','L','L','O','R','D','E','R','E','S','T',
  119106. 'R','I','C','T','R','I','G','H','T','R','O','L','L','B','A','C','K','R',
  119107. 'O','W','U','N','I','O','N','U','S','I','N','G','V','A','C','U','U','M',
  119108. 'V','I','E','W','I','N','I','T','I','A','L','L','Y',
  119109. };
  119110. static const unsigned char aHash[127] = {
  119111. 76, 105, 117, 74, 0, 45, 0, 0, 82, 0, 77, 0, 0,
  119112. 42, 12, 78, 15, 0, 116, 85, 54, 112, 0, 19, 0, 0,
  119113. 121, 0, 119, 115, 0, 22, 93, 0, 9, 0, 0, 70, 71,
  119114. 0, 69, 6, 0, 48, 90, 102, 0, 118, 101, 0, 0, 44,
  119115. 0, 103, 24, 0, 17, 0, 122, 53, 23, 0, 5, 110, 25,
  119116. 96, 0, 0, 124, 106, 60, 123, 57, 28, 55, 0, 91, 0,
  119117. 100, 26, 0, 99, 0, 0, 0, 95, 92, 97, 88, 109, 14,
  119118. 39, 108, 0, 81, 0, 18, 89, 111, 32, 0, 120, 80, 113,
  119119. 62, 46, 84, 0, 0, 94, 40, 59, 114, 0, 36, 0, 0,
  119120. 29, 0, 86, 63, 64, 0, 20, 61, 0, 56,
  119121. };
  119122. static const unsigned char aNext[124] = {
  119123. 0, 0, 0, 0, 4, 0, 0, 0, 0, 0, 0, 0, 0,
  119124. 0, 2, 0, 0, 0, 0, 0, 0, 13, 0, 0, 0, 0,
  119125. 0, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119126. 0, 0, 0, 0, 33, 0, 21, 0, 0, 0, 0, 0, 50,
  119127. 0, 43, 3, 47, 0, 0, 0, 0, 30, 0, 58, 0, 38,
  119128. 0, 0, 0, 1, 66, 0, 0, 67, 0, 41, 0, 0, 0,
  119129. 0, 0, 0, 49, 65, 0, 0, 0, 0, 31, 52, 16, 34,
  119130. 10, 0, 0, 0, 0, 0, 0, 0, 11, 72, 79, 0, 8,
  119131. 0, 104, 98, 0, 107, 0, 87, 0, 75, 51, 0, 27, 37,
  119132. 73, 83, 0, 35, 68, 0, 0,
  119133. };
  119134. static const unsigned char aLen[124] = {
  119135. 7, 7, 5, 4, 6, 4, 5, 3, 6, 7, 3, 6, 6,
  119136. 7, 7, 3, 8, 2, 6, 5, 4, 4, 3, 10, 4, 6,
  119137. 11, 6, 2, 7, 5, 5, 9, 6, 9, 9, 7, 10, 10,
  119138. 4, 6, 2, 3, 9, 4, 2, 6, 5, 7, 4, 5, 7,
  119139. 6, 6, 5, 6, 5, 5, 9, 7, 7, 3, 2, 4, 4,
  119140. 7, 3, 6, 4, 7, 6, 12, 6, 9, 4, 6, 5, 4,
  119141. 7, 6, 5, 6, 7, 5, 4, 5, 6, 5, 7, 3, 7,
  119142. 13, 2, 2, 4, 6, 6, 8, 5, 17, 12, 7, 8, 8,
  119143. 2, 4, 4, 4, 4, 4, 2, 2, 6, 5, 8, 5, 8,
  119144. 3, 5, 5, 6, 4, 9, 3,
  119145. };
  119146. static const unsigned short int aOffset[124] = {
  119147. 0, 2, 2, 8, 9, 14, 16, 20, 23, 25, 25, 29, 33,
  119148. 36, 41, 46, 48, 53, 54, 59, 62, 65, 67, 69, 78, 81,
  119149. 86, 91, 95, 96, 101, 105, 109, 117, 122, 128, 136, 142, 152,
  119150. 159, 162, 162, 165, 167, 167, 171, 176, 179, 184, 184, 188, 192,
  119151. 199, 204, 209, 212, 218, 221, 225, 234, 240, 240, 240, 243, 246,
  119152. 250, 251, 255, 261, 265, 272, 278, 290, 296, 305, 307, 313, 318,
  119153. 320, 327, 332, 337, 343, 349, 354, 358, 361, 367, 371, 378, 380,
  119154. 387, 389, 391, 400, 404, 410, 416, 424, 429, 429, 445, 452, 459,
  119155. 460, 467, 471, 475, 479, 483, 486, 488, 490, 496, 500, 508, 513,
  119156. 521, 524, 529, 534, 540, 544, 549,
  119157. };
  119158. static const unsigned char aCode[124] = {
  119159. TK_REINDEX, TK_INDEXED, TK_INDEX, TK_DESC, TK_ESCAPE,
  119160. TK_EACH, TK_CHECK, TK_KEY, TK_BEFORE, TK_FOREIGN,
  119161. TK_FOR, TK_IGNORE, TK_LIKE_KW, TK_EXPLAIN, TK_INSTEAD,
  119162. TK_ADD, TK_DATABASE, TK_AS, TK_SELECT, TK_TABLE,
  119163. TK_JOIN_KW, TK_THEN, TK_END, TK_DEFERRABLE, TK_ELSE,
  119164. TK_EXCEPT, TK_TRANSACTION,TK_ACTION, TK_ON, TK_JOIN_KW,
  119165. TK_ALTER, TK_RAISE, TK_EXCLUSIVE, TK_EXISTS, TK_SAVEPOINT,
  119166. TK_INTERSECT, TK_TRIGGER, TK_REFERENCES, TK_CONSTRAINT, TK_INTO,
  119167. TK_OFFSET, TK_OF, TK_SET, TK_TEMP, TK_TEMP,
  119168. TK_OR, TK_UNIQUE, TK_QUERY, TK_WITHOUT, TK_WITH,
  119169. TK_JOIN_KW, TK_RELEASE, TK_ATTACH, TK_HAVING, TK_GROUP,
  119170. TK_UPDATE, TK_BEGIN, TK_JOIN_KW, TK_RECURSIVE, TK_BETWEEN,
  119171. TK_NOTNULL, TK_NOT, TK_NO, TK_NULL, TK_LIKE_KW,
  119172. TK_CASCADE, TK_ASC, TK_DELETE, TK_CASE, TK_COLLATE,
  119173. TK_CREATE, TK_CTIME_KW, TK_DETACH, TK_IMMEDIATE, TK_JOIN,
  119174. TK_INSERT, TK_MATCH, TK_PLAN, TK_ANALYZE, TK_PRAGMA,
  119175. TK_ABORT, TK_VALUES, TK_VIRTUAL, TK_LIMIT, TK_WHEN,
  119176. TK_WHERE, TK_RENAME, TK_AFTER, TK_REPLACE, TK_AND,
  119177. TK_DEFAULT, TK_AUTOINCR, TK_TO, TK_IN, TK_CAST,
  119178. TK_COLUMNKW, TK_COMMIT, TK_CONFLICT, TK_JOIN_KW, TK_CTIME_KW,
  119179. TK_CTIME_KW, TK_PRIMARY, TK_DEFERRED, TK_DISTINCT, TK_IS,
  119180. TK_DROP, TK_FAIL, TK_FROM, TK_JOIN_KW, TK_LIKE_KW,
  119181. TK_BY, TK_IF, TK_ISNULL, TK_ORDER, TK_RESTRICT,
  119182. TK_JOIN_KW, TK_ROLLBACK, TK_ROW, TK_UNION, TK_USING,
  119183. TK_VACUUM, TK_VIEW, TK_INITIALLY, TK_ALL,
  119184. };
  119185. int h, i;
  119186. if( n<2 ) return TK_ID;
  119187. h = ((charMap(z[0])*4) ^
  119188. (charMap(z[n-1])*3) ^
  119189. n) % 127;
  119190. for(i=((int)aHash[h])-1; i>=0; i=((int)aNext[i])-1){
  119191. if( aLen[i]==n && sqlite3StrNICmp(&zText[aOffset[i]],z,n)==0 ){
  119192. testcase( i==0 ); /* REINDEX */
  119193. testcase( i==1 ); /* INDEXED */
  119194. testcase( i==2 ); /* INDEX */
  119195. testcase( i==3 ); /* DESC */
  119196. testcase( i==4 ); /* ESCAPE */
  119197. testcase( i==5 ); /* EACH */
  119198. testcase( i==6 ); /* CHECK */
  119199. testcase( i==7 ); /* KEY */
  119200. testcase( i==8 ); /* BEFORE */
  119201. testcase( i==9 ); /* FOREIGN */
  119202. testcase( i==10 ); /* FOR */
  119203. testcase( i==11 ); /* IGNORE */
  119204. testcase( i==12 ); /* REGEXP */
  119205. testcase( i==13 ); /* EXPLAIN */
  119206. testcase( i==14 ); /* INSTEAD */
  119207. testcase( i==15 ); /* ADD */
  119208. testcase( i==16 ); /* DATABASE */
  119209. testcase( i==17 ); /* AS */
  119210. testcase( i==18 ); /* SELECT */
  119211. testcase( i==19 ); /* TABLE */
  119212. testcase( i==20 ); /* LEFT */
  119213. testcase( i==21 ); /* THEN */
  119214. testcase( i==22 ); /* END */
  119215. testcase( i==23 ); /* DEFERRABLE */
  119216. testcase( i==24 ); /* ELSE */
  119217. testcase( i==25 ); /* EXCEPT */
  119218. testcase( i==26 ); /* TRANSACTION */
  119219. testcase( i==27 ); /* ACTION */
  119220. testcase( i==28 ); /* ON */
  119221. testcase( i==29 ); /* NATURAL */
  119222. testcase( i==30 ); /* ALTER */
  119223. testcase( i==31 ); /* RAISE */
  119224. testcase( i==32 ); /* EXCLUSIVE */
  119225. testcase( i==33 ); /* EXISTS */
  119226. testcase( i==34 ); /* SAVEPOINT */
  119227. testcase( i==35 ); /* INTERSECT */
  119228. testcase( i==36 ); /* TRIGGER */
  119229. testcase( i==37 ); /* REFERENCES */
  119230. testcase( i==38 ); /* CONSTRAINT */
  119231. testcase( i==39 ); /* INTO */
  119232. testcase( i==40 ); /* OFFSET */
  119233. testcase( i==41 ); /* OF */
  119234. testcase( i==42 ); /* SET */
  119235. testcase( i==43 ); /* TEMPORARY */
  119236. testcase( i==44 ); /* TEMP */
  119237. testcase( i==45 ); /* OR */
  119238. testcase( i==46 ); /* UNIQUE */
  119239. testcase( i==47 ); /* QUERY */
  119240. testcase( i==48 ); /* WITHOUT */
  119241. testcase( i==49 ); /* WITH */
  119242. testcase( i==50 ); /* OUTER */
  119243. testcase( i==51 ); /* RELEASE */
  119244. testcase( i==52 ); /* ATTACH */
  119245. testcase( i==53 ); /* HAVING */
  119246. testcase( i==54 ); /* GROUP */
  119247. testcase( i==55 ); /* UPDATE */
  119248. testcase( i==56 ); /* BEGIN */
  119249. testcase( i==57 ); /* INNER */
  119250. testcase( i==58 ); /* RECURSIVE */
  119251. testcase( i==59 ); /* BETWEEN */
  119252. testcase( i==60 ); /* NOTNULL */
  119253. testcase( i==61 ); /* NOT */
  119254. testcase( i==62 ); /* NO */
  119255. testcase( i==63 ); /* NULL */
  119256. testcase( i==64 ); /* LIKE */
  119257. testcase( i==65 ); /* CASCADE */
  119258. testcase( i==66 ); /* ASC */
  119259. testcase( i==67 ); /* DELETE */
  119260. testcase( i==68 ); /* CASE */
  119261. testcase( i==69 ); /* COLLATE */
  119262. testcase( i==70 ); /* CREATE */
  119263. testcase( i==71 ); /* CURRENT_DATE */
  119264. testcase( i==72 ); /* DETACH */
  119265. testcase( i==73 ); /* IMMEDIATE */
  119266. testcase( i==74 ); /* JOIN */
  119267. testcase( i==75 ); /* INSERT */
  119268. testcase( i==76 ); /* MATCH */
  119269. testcase( i==77 ); /* PLAN */
  119270. testcase( i==78 ); /* ANALYZE */
  119271. testcase( i==79 ); /* PRAGMA */
  119272. testcase( i==80 ); /* ABORT */
  119273. testcase( i==81 ); /* VALUES */
  119274. testcase( i==82 ); /* VIRTUAL */
  119275. testcase( i==83 ); /* LIMIT */
  119276. testcase( i==84 ); /* WHEN */
  119277. testcase( i==85 ); /* WHERE */
  119278. testcase( i==86 ); /* RENAME */
  119279. testcase( i==87 ); /* AFTER */
  119280. testcase( i==88 ); /* REPLACE */
  119281. testcase( i==89 ); /* AND */
  119282. testcase( i==90 ); /* DEFAULT */
  119283. testcase( i==91 ); /* AUTOINCREMENT */
  119284. testcase( i==92 ); /* TO */
  119285. testcase( i==93 ); /* IN */
  119286. testcase( i==94 ); /* CAST */
  119287. testcase( i==95 ); /* COLUMN */
  119288. testcase( i==96 ); /* COMMIT */
  119289. testcase( i==97 ); /* CONFLICT */
  119290. testcase( i==98 ); /* CROSS */
  119291. testcase( i==99 ); /* CURRENT_TIMESTAMP */
  119292. testcase( i==100 ); /* CURRENT_TIME */
  119293. testcase( i==101 ); /* PRIMARY */
  119294. testcase( i==102 ); /* DEFERRED */
  119295. testcase( i==103 ); /* DISTINCT */
  119296. testcase( i==104 ); /* IS */
  119297. testcase( i==105 ); /* DROP */
  119298. testcase( i==106 ); /* FAIL */
  119299. testcase( i==107 ); /* FROM */
  119300. testcase( i==108 ); /* FULL */
  119301. testcase( i==109 ); /* GLOB */
  119302. testcase( i==110 ); /* BY */
  119303. testcase( i==111 ); /* IF */
  119304. testcase( i==112 ); /* ISNULL */
  119305. testcase( i==113 ); /* ORDER */
  119306. testcase( i==114 ); /* RESTRICT */
  119307. testcase( i==115 ); /* RIGHT */
  119308. testcase( i==116 ); /* ROLLBACK */
  119309. testcase( i==117 ); /* ROW */
  119310. testcase( i==118 ); /* UNION */
  119311. testcase( i==119 ); /* USING */
  119312. testcase( i==120 ); /* VACUUM */
  119313. testcase( i==121 ); /* VIEW */
  119314. testcase( i==122 ); /* INITIALLY */
  119315. testcase( i==123 ); /* ALL */
  119316. return aCode[i];
  119317. }
  119318. }
  119319. return TK_ID;
  119320. }
  119321. SQLITE_PRIVATE int sqlite3KeywordCode(const unsigned char *z, int n){
  119322. return keywordCode((char*)z, n);
  119323. }
  119324. #define SQLITE_N_KEYWORD 124
  119325. /************** End of keywordhash.h *****************************************/
  119326. /************** Continuing where we left off in tokenize.c *******************/
  119327. /*
  119328. ** If X is a character that can be used in an identifier then
  119329. ** IdChar(X) will be true. Otherwise it is false.
  119330. **
  119331. ** For ASCII, any character with the high-order bit set is
  119332. ** allowed in an identifier. For 7-bit characters,
  119333. ** sqlite3IsIdChar[X] must be 1.
  119334. **
  119335. ** For EBCDIC, the rules are more complex but have the same
  119336. ** end result.
  119337. **
  119338. ** Ticket #1066. the SQL standard does not allow '$' in the
  119339. ** middle of identifiers. But many SQL implementations do.
  119340. ** SQLite will allow '$' in identifiers for compatibility.
  119341. ** But the feature is undocumented.
  119342. */
  119343. #ifdef SQLITE_ASCII
  119344. #define IdChar(C) ((sqlite3CtypeMap[(unsigned char)C]&0x46)!=0)
  119345. #endif
  119346. #ifdef SQLITE_EBCDIC
  119347. SQLITE_PRIVATE const char sqlite3IsEbcdicIdChar[] = {
  119348. /* x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 xA xB xC xD xE xF */
  119349. 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, /* 4x */
  119350. 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 0, 0, 0, /* 5x */
  119351. 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0, /* 6x */
  119352. 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, /* 7x */
  119353. 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 0, /* 8x */
  119354. 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 0, 1, 0, /* 9x */
  119355. 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 0, /* Ax */
  119356. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Bx */
  119357. 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, /* Cx */
  119358. 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, /* Dx */
  119359. 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, /* Ex */
  119360. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 0, /* Fx */
  119361. };
  119362. #define IdChar(C) (((c=C)>=0x42 && sqlite3IsEbcdicIdChar[c-0x40]))
  119363. #endif
  119364. SQLITE_PRIVATE int sqlite3IsIdChar(u8 c){ return IdChar(c); }
  119365. /*
  119366. ** Return the length of the token that begins at z[0].
  119367. ** Store the token type in *tokenType before returning.
  119368. */
  119369. SQLITE_PRIVATE int sqlite3GetToken(const unsigned char *z, int *tokenType){
  119370. int i, c;
  119371. switch( *z ){
  119372. case ' ': case '\t': case '\n': case '\f': case '\r': {
  119373. testcase( z[0]==' ' );
  119374. testcase( z[0]=='\t' );
  119375. testcase( z[0]=='\n' );
  119376. testcase( z[0]=='\f' );
  119377. testcase( z[0]=='\r' );
  119378. for(i=1; sqlite3Isspace(z[i]); i++){}
  119379. *tokenType = TK_SPACE;
  119380. return i;
  119381. }
  119382. case '-': {
  119383. if( z[1]=='-' ){
  119384. for(i=2; (c=z[i])!=0 && c!='\n'; i++){}
  119385. *tokenType = TK_SPACE; /* IMP: R-22934-25134 */
  119386. return i;
  119387. }
  119388. *tokenType = TK_MINUS;
  119389. return 1;
  119390. }
  119391. case '(': {
  119392. *tokenType = TK_LP;
  119393. return 1;
  119394. }
  119395. case ')': {
  119396. *tokenType = TK_RP;
  119397. return 1;
  119398. }
  119399. case ';': {
  119400. *tokenType = TK_SEMI;
  119401. return 1;
  119402. }
  119403. case '+': {
  119404. *tokenType = TK_PLUS;
  119405. return 1;
  119406. }
  119407. case '*': {
  119408. *tokenType = TK_STAR;
  119409. return 1;
  119410. }
  119411. case '/': {
  119412. if( z[1]!='*' || z[2]==0 ){
  119413. *tokenType = TK_SLASH;
  119414. return 1;
  119415. }
  119416. for(i=3, c=z[2]; (c!='*' || z[i]!='/') && (c=z[i])!=0; i++){}
  119417. if( c ) i++;
  119418. *tokenType = TK_SPACE; /* IMP: R-22934-25134 */
  119419. return i;
  119420. }
  119421. case '%': {
  119422. *tokenType = TK_REM;
  119423. return 1;
  119424. }
  119425. case '=': {
  119426. *tokenType = TK_EQ;
  119427. return 1 + (z[1]=='=');
  119428. }
  119429. case '<': {
  119430. if( (c=z[1])=='=' ){
  119431. *tokenType = TK_LE;
  119432. return 2;
  119433. }else if( c=='>' ){
  119434. *tokenType = TK_NE;
  119435. return 2;
  119436. }else if( c=='<' ){
  119437. *tokenType = TK_LSHIFT;
  119438. return 2;
  119439. }else{
  119440. *tokenType = TK_LT;
  119441. return 1;
  119442. }
  119443. }
  119444. case '>': {
  119445. if( (c=z[1])=='=' ){
  119446. *tokenType = TK_GE;
  119447. return 2;
  119448. }else if( c=='>' ){
  119449. *tokenType = TK_RSHIFT;
  119450. return 2;
  119451. }else{
  119452. *tokenType = TK_GT;
  119453. return 1;
  119454. }
  119455. }
  119456. case '!': {
  119457. if( z[1]!='=' ){
  119458. *tokenType = TK_ILLEGAL;
  119459. return 2;
  119460. }else{
  119461. *tokenType = TK_NE;
  119462. return 2;
  119463. }
  119464. }
  119465. case '|': {
  119466. if( z[1]!='|' ){
  119467. *tokenType = TK_BITOR;
  119468. return 1;
  119469. }else{
  119470. *tokenType = TK_CONCAT;
  119471. return 2;
  119472. }
  119473. }
  119474. case ',': {
  119475. *tokenType = TK_COMMA;
  119476. return 1;
  119477. }
  119478. case '&': {
  119479. *tokenType = TK_BITAND;
  119480. return 1;
  119481. }
  119482. case '~': {
  119483. *tokenType = TK_BITNOT;
  119484. return 1;
  119485. }
  119486. case '`':
  119487. case '\'':
  119488. case '"': {
  119489. int delim = z[0];
  119490. testcase( delim=='`' );
  119491. testcase( delim=='\'' );
  119492. testcase( delim=='"' );
  119493. for(i=1; (c=z[i])!=0; i++){
  119494. if( c==delim ){
  119495. if( z[i+1]==delim ){
  119496. i++;
  119497. }else{
  119498. break;
  119499. }
  119500. }
  119501. }
  119502. if( c=='\'' ){
  119503. *tokenType = TK_STRING;
  119504. return i+1;
  119505. }else if( c!=0 ){
  119506. *tokenType = TK_ID;
  119507. return i+1;
  119508. }else{
  119509. *tokenType = TK_ILLEGAL;
  119510. return i;
  119511. }
  119512. }
  119513. case '.': {
  119514. #ifndef SQLITE_OMIT_FLOATING_POINT
  119515. if( !sqlite3Isdigit(z[1]) )
  119516. #endif
  119517. {
  119518. *tokenType = TK_DOT;
  119519. return 1;
  119520. }
  119521. /* If the next character is a digit, this is a floating point
  119522. ** number that begins with ".". Fall thru into the next case */
  119523. }
  119524. case '0': case '1': case '2': case '3': case '4':
  119525. case '5': case '6': case '7': case '8': case '9': {
  119526. testcase( z[0]=='0' ); testcase( z[0]=='1' ); testcase( z[0]=='2' );
  119527. testcase( z[0]=='3' ); testcase( z[0]=='4' ); testcase( z[0]=='5' );
  119528. testcase( z[0]=='6' ); testcase( z[0]=='7' ); testcase( z[0]=='8' );
  119529. testcase( z[0]=='9' );
  119530. *tokenType = TK_INTEGER;
  119531. #ifndef SQLITE_OMIT_HEX_INTEGER
  119532. if( z[0]=='0' && (z[1]=='x' || z[1]=='X') && sqlite3Isxdigit(z[2]) ){
  119533. for(i=3; sqlite3Isxdigit(z[i]); i++){}
  119534. return i;
  119535. }
  119536. #endif
  119537. for(i=0; sqlite3Isdigit(z[i]); i++){}
  119538. #ifndef SQLITE_OMIT_FLOATING_POINT
  119539. if( z[i]=='.' ){
  119540. i++;
  119541. while( sqlite3Isdigit(z[i]) ){ i++; }
  119542. *tokenType = TK_FLOAT;
  119543. }
  119544. if( (z[i]=='e' || z[i]=='E') &&
  119545. ( sqlite3Isdigit(z[i+1])
  119546. || ((z[i+1]=='+' || z[i+1]=='-') && sqlite3Isdigit(z[i+2]))
  119547. )
  119548. ){
  119549. i += 2;
  119550. while( sqlite3Isdigit(z[i]) ){ i++; }
  119551. *tokenType = TK_FLOAT;
  119552. }
  119553. #endif
  119554. while( IdChar(z[i]) ){
  119555. *tokenType = TK_ILLEGAL;
  119556. i++;
  119557. }
  119558. return i;
  119559. }
  119560. case '[': {
  119561. for(i=1, c=z[0]; c!=']' && (c=z[i])!=0; i++){}
  119562. *tokenType = c==']' ? TK_ID : TK_ILLEGAL;
  119563. return i;
  119564. }
  119565. case '?': {
  119566. *tokenType = TK_VARIABLE;
  119567. for(i=1; sqlite3Isdigit(z[i]); i++){}
  119568. return i;
  119569. }
  119570. #ifndef SQLITE_OMIT_TCL_VARIABLE
  119571. case '$':
  119572. #endif
  119573. case '@': /* For compatibility with MS SQL Server */
  119574. case '#':
  119575. case ':': {
  119576. int n = 0;
  119577. testcase( z[0]=='$' ); testcase( z[0]=='@' );
  119578. testcase( z[0]==':' ); testcase( z[0]=='#' );
  119579. *tokenType = TK_VARIABLE;
  119580. for(i=1; (c=z[i])!=0; i++){
  119581. if( IdChar(c) ){
  119582. n++;
  119583. #ifndef SQLITE_OMIT_TCL_VARIABLE
  119584. }else if( c=='(' && n>0 ){
  119585. do{
  119586. i++;
  119587. }while( (c=z[i])!=0 && !sqlite3Isspace(c) && c!=')' );
  119588. if( c==')' ){
  119589. i++;
  119590. }else{
  119591. *tokenType = TK_ILLEGAL;
  119592. }
  119593. break;
  119594. }else if( c==':' && z[i+1]==':' ){
  119595. i++;
  119596. #endif
  119597. }else{
  119598. break;
  119599. }
  119600. }
  119601. if( n==0 ) *tokenType = TK_ILLEGAL;
  119602. return i;
  119603. }
  119604. #ifndef SQLITE_OMIT_BLOB_LITERAL
  119605. case 'x': case 'X': {
  119606. testcase( z[0]=='x' ); testcase( z[0]=='X' );
  119607. if( z[1]=='\'' ){
  119608. *tokenType = TK_BLOB;
  119609. for(i=2; sqlite3Isxdigit(z[i]); i++){}
  119610. if( z[i]!='\'' || i%2 ){
  119611. *tokenType = TK_ILLEGAL;
  119612. while( z[i] && z[i]!='\'' ){ i++; }
  119613. }
  119614. if( z[i] ) i++;
  119615. return i;
  119616. }
  119617. /* Otherwise fall through to the next case */
  119618. }
  119619. #endif
  119620. default: {
  119621. if( !IdChar(*z) ){
  119622. break;
  119623. }
  119624. for(i=1; IdChar(z[i]); i++){}
  119625. *tokenType = keywordCode((char*)z, i);
  119626. return i;
  119627. }
  119628. }
  119629. *tokenType = TK_ILLEGAL;
  119630. return 1;
  119631. }
  119632. /*
  119633. ** Run the parser on the given SQL string. The parser structure is
  119634. ** passed in. An SQLITE_ status code is returned. If an error occurs
  119635. ** then an and attempt is made to write an error message into
  119636. ** memory obtained from sqlite3_malloc() and to make *pzErrMsg point to that
  119637. ** error message.
  119638. */
  119639. SQLITE_PRIVATE int sqlite3RunParser(Parse *pParse, const char *zSql, char **pzErrMsg){
  119640. int nErr = 0; /* Number of errors encountered */
  119641. int i; /* Loop counter */
  119642. void *pEngine; /* The LEMON-generated LALR(1) parser */
  119643. int tokenType; /* type of the next token */
  119644. int lastTokenParsed = -1; /* type of the previous token */
  119645. u8 enableLookaside; /* Saved value of db->lookaside.bEnabled */
  119646. sqlite3 *db = pParse->db; /* The database connection */
  119647. int mxSqlLen; /* Max length of an SQL string */
  119648. assert( zSql!=0 );
  119649. mxSqlLen = db->aLimit[SQLITE_LIMIT_SQL_LENGTH];
  119650. if( db->nVdbeActive==0 ){
  119651. db->u1.isInterrupted = 0;
  119652. }
  119653. pParse->rc = SQLITE_OK;
  119654. pParse->zTail = zSql;
  119655. i = 0;
  119656. assert( pzErrMsg!=0 );
  119657. pEngine = sqlite3ParserAlloc(sqlite3Malloc);
  119658. if( pEngine==0 ){
  119659. db->mallocFailed = 1;
  119660. return SQLITE_NOMEM;
  119661. }
  119662. assert( pParse->pNewTable==0 );
  119663. assert( pParse->pNewTrigger==0 );
  119664. assert( pParse->nVar==0 );
  119665. assert( pParse->nzVar==0 );
  119666. assert( pParse->azVar==0 );
  119667. enableLookaside = db->lookaside.bEnabled;
  119668. if( db->lookaside.pStart ) db->lookaside.bEnabled = 1;
  119669. while( !db->mallocFailed && zSql[i]!=0 ){
  119670. assert( i>=0 );
  119671. pParse->sLastToken.z = &zSql[i];
  119672. pParse->sLastToken.n = sqlite3GetToken((unsigned char*)&zSql[i],&tokenType);
  119673. i += pParse->sLastToken.n;
  119674. if( i>mxSqlLen ){
  119675. pParse->rc = SQLITE_TOOBIG;
  119676. break;
  119677. }
  119678. switch( tokenType ){
  119679. case TK_SPACE: {
  119680. if( db->u1.isInterrupted ){
  119681. sqlite3ErrorMsg(pParse, "interrupt");
  119682. pParse->rc = SQLITE_INTERRUPT;
  119683. goto abort_parse;
  119684. }
  119685. break;
  119686. }
  119687. case TK_ILLEGAL: {
  119688. sqlite3ErrorMsg(pParse, "unrecognized token: \"%T\"",
  119689. &pParse->sLastToken);
  119690. goto abort_parse;
  119691. }
  119692. case TK_SEMI: {
  119693. pParse->zTail = &zSql[i];
  119694. /* Fall thru into the default case */
  119695. }
  119696. default: {
  119697. sqlite3Parser(pEngine, tokenType, pParse->sLastToken, pParse);
  119698. lastTokenParsed = tokenType;
  119699. if( pParse->rc!=SQLITE_OK ){
  119700. goto abort_parse;
  119701. }
  119702. break;
  119703. }
  119704. }
  119705. }
  119706. abort_parse:
  119707. assert( nErr==0 );
  119708. if( zSql[i]==0 && pParse->rc==SQLITE_OK && db->mallocFailed==0 ){
  119709. if( lastTokenParsed!=TK_SEMI ){
  119710. sqlite3Parser(pEngine, TK_SEMI, pParse->sLastToken, pParse);
  119711. pParse->zTail = &zSql[i];
  119712. }
  119713. if( pParse->rc==SQLITE_OK && db->mallocFailed==0 ){
  119714. sqlite3Parser(pEngine, 0, pParse->sLastToken, pParse);
  119715. }
  119716. }
  119717. #ifdef YYTRACKMAXSTACKDEPTH
  119718. sqlite3_mutex_enter(sqlite3MallocMutex());
  119719. sqlite3StatusSet(SQLITE_STATUS_PARSER_STACK,
  119720. sqlite3ParserStackPeak(pEngine)
  119721. );
  119722. sqlite3_mutex_leave(sqlite3MallocMutex());
  119723. #endif /* YYDEBUG */
  119724. sqlite3ParserFree(pEngine, sqlite3_free);
  119725. db->lookaside.bEnabled = enableLookaside;
  119726. if( db->mallocFailed ){
  119727. pParse->rc = SQLITE_NOMEM;
  119728. }
  119729. if( pParse->rc!=SQLITE_OK && pParse->rc!=SQLITE_DONE && pParse->zErrMsg==0 ){
  119730. sqlite3SetString(&pParse->zErrMsg, db, "%s", sqlite3ErrStr(pParse->rc));
  119731. }
  119732. assert( pzErrMsg!=0 );
  119733. if( pParse->zErrMsg ){
  119734. *pzErrMsg = pParse->zErrMsg;
  119735. sqlite3_log(pParse->rc, "%s", *pzErrMsg);
  119736. pParse->zErrMsg = 0;
  119737. nErr++;
  119738. }
  119739. if( pParse->pVdbe && pParse->nErr>0 && pParse->nested==0 ){
  119740. sqlite3VdbeDelete(pParse->pVdbe);
  119741. pParse->pVdbe = 0;
  119742. }
  119743. #ifndef SQLITE_OMIT_SHARED_CACHE
  119744. if( pParse->nested==0 ){
  119745. sqlite3DbFree(db, pParse->aTableLock);
  119746. pParse->aTableLock = 0;
  119747. pParse->nTableLock = 0;
  119748. }
  119749. #endif
  119750. #ifndef SQLITE_OMIT_VIRTUALTABLE
  119751. sqlite3_free(pParse->apVtabLock);
  119752. #endif
  119753. if( !IN_DECLARE_VTAB ){
  119754. /* If the pParse->declareVtab flag is set, do not delete any table
  119755. ** structure built up in pParse->pNewTable. The calling code (see vtab.c)
  119756. ** will take responsibility for freeing the Table structure.
  119757. */
  119758. sqlite3DeleteTable(db, pParse->pNewTable);
  119759. }
  119760. if( pParse->bFreeWith ) sqlite3WithDelete(db, pParse->pWith);
  119761. sqlite3DeleteTrigger(db, pParse->pNewTrigger);
  119762. for(i=pParse->nzVar-1; i>=0; i--) sqlite3DbFree(db, pParse->azVar[i]);
  119763. sqlite3DbFree(db, pParse->azVar);
  119764. while( pParse->pAinc ){
  119765. AutoincInfo *p = pParse->pAinc;
  119766. pParse->pAinc = p->pNext;
  119767. sqlite3DbFree(db, p);
  119768. }
  119769. while( pParse->pZombieTab ){
  119770. Table *p = pParse->pZombieTab;
  119771. pParse->pZombieTab = p->pNextZombie;
  119772. sqlite3DeleteTable(db, p);
  119773. }
  119774. assert( nErr==0 || pParse->rc!=SQLITE_OK );
  119775. return nErr;
  119776. }
  119777. /************** End of tokenize.c ********************************************/
  119778. /************** Begin file complete.c ****************************************/
  119779. /*
  119780. ** 2001 September 15
  119781. **
  119782. ** The author disclaims copyright to this source code. In place of
  119783. ** a legal notice, here is a blessing:
  119784. **
  119785. ** May you do good and not evil.
  119786. ** May you find forgiveness for yourself and forgive others.
  119787. ** May you share freely, never taking more than you give.
  119788. **
  119789. *************************************************************************
  119790. ** An tokenizer for SQL
  119791. **
  119792. ** This file contains C code that implements the sqlite3_complete() API.
  119793. ** This code used to be part of the tokenizer.c source file. But by
  119794. ** separating it out, the code will be automatically omitted from
  119795. ** static links that do not use it.
  119796. */
  119797. #ifndef SQLITE_OMIT_COMPLETE
  119798. /*
  119799. ** This is defined in tokenize.c. We just have to import the definition.
  119800. */
  119801. #ifndef SQLITE_AMALGAMATION
  119802. #ifdef SQLITE_ASCII
  119803. #define IdChar(C) ((sqlite3CtypeMap[(unsigned char)C]&0x46)!=0)
  119804. #endif
  119805. #ifdef SQLITE_EBCDIC
  119806. SQLITE_PRIVATE const char sqlite3IsEbcdicIdChar[];
  119807. #define IdChar(C) (((c=C)>=0x42 && sqlite3IsEbcdicIdChar[c-0x40]))
  119808. #endif
  119809. #endif /* SQLITE_AMALGAMATION */
  119810. /*
  119811. ** Token types used by the sqlite3_complete() routine. See the header
  119812. ** comments on that procedure for additional information.
  119813. */
  119814. #define tkSEMI 0
  119815. #define tkWS 1
  119816. #define tkOTHER 2
  119817. #ifndef SQLITE_OMIT_TRIGGER
  119818. #define tkEXPLAIN 3
  119819. #define tkCREATE 4
  119820. #define tkTEMP 5
  119821. #define tkTRIGGER 6
  119822. #define tkEND 7
  119823. #endif
  119824. /*
  119825. ** Return TRUE if the given SQL string ends in a semicolon.
  119826. **
  119827. ** Special handling is require for CREATE TRIGGER statements.
  119828. ** Whenever the CREATE TRIGGER keywords are seen, the statement
  119829. ** must end with ";END;".
  119830. **
  119831. ** This implementation uses a state machine with 8 states:
  119832. **
  119833. ** (0) INVALID We have not yet seen a non-whitespace character.
  119834. **
  119835. ** (1) START At the beginning or end of an SQL statement. This routine
  119836. ** returns 1 if it ends in the START state and 0 if it ends
  119837. ** in any other state.
  119838. **
  119839. ** (2) NORMAL We are in the middle of statement which ends with a single
  119840. ** semicolon.
  119841. **
  119842. ** (3) EXPLAIN The keyword EXPLAIN has been seen at the beginning of
  119843. ** a statement.
  119844. **
  119845. ** (4) CREATE The keyword CREATE has been seen at the beginning of a
  119846. ** statement, possibly preceded by EXPLAIN and/or followed by
  119847. ** TEMP or TEMPORARY
  119848. **
  119849. ** (5) TRIGGER We are in the middle of a trigger definition that must be
  119850. ** ended by a semicolon, the keyword END, and another semicolon.
  119851. **
  119852. ** (6) SEMI We've seen the first semicolon in the ";END;" that occurs at
  119853. ** the end of a trigger definition.
  119854. **
  119855. ** (7) END We've seen the ";END" of the ";END;" that occurs at the end
  119856. ** of a trigger definition.
  119857. **
  119858. ** Transitions between states above are determined by tokens extracted
  119859. ** from the input. The following tokens are significant:
  119860. **
  119861. ** (0) tkSEMI A semicolon.
  119862. ** (1) tkWS Whitespace.
  119863. ** (2) tkOTHER Any other SQL token.
  119864. ** (3) tkEXPLAIN The "explain" keyword.
  119865. ** (4) tkCREATE The "create" keyword.
  119866. ** (5) tkTEMP The "temp" or "temporary" keyword.
  119867. ** (6) tkTRIGGER The "trigger" keyword.
  119868. ** (7) tkEND The "end" keyword.
  119869. **
  119870. ** Whitespace never causes a state transition and is always ignored.
  119871. ** This means that a SQL string of all whitespace is invalid.
  119872. **
  119873. ** If we compile with SQLITE_OMIT_TRIGGER, all of the computation needed
  119874. ** to recognize the end of a trigger can be omitted. All we have to do
  119875. ** is look for a semicolon that is not part of an string or comment.
  119876. */
  119877. SQLITE_API int SQLITE_STDCALL sqlite3_complete(const char *zSql){
  119878. u8 state = 0; /* Current state, using numbers defined in header comment */
  119879. u8 token; /* Value of the next token */
  119880. #ifndef SQLITE_OMIT_TRIGGER
  119881. /* A complex statement machine used to detect the end of a CREATE TRIGGER
  119882. ** statement. This is the normal case.
  119883. */
  119884. static const u8 trans[8][8] = {
  119885. /* Token: */
  119886. /* State: ** SEMI WS OTHER EXPLAIN CREATE TEMP TRIGGER END */
  119887. /* 0 INVALID: */ { 1, 0, 2, 3, 4, 2, 2, 2, },
  119888. /* 1 START: */ { 1, 1, 2, 3, 4, 2, 2, 2, },
  119889. /* 2 NORMAL: */ { 1, 2, 2, 2, 2, 2, 2, 2, },
  119890. /* 3 EXPLAIN: */ { 1, 3, 3, 2, 4, 2, 2, 2, },
  119891. /* 4 CREATE: */ { 1, 4, 2, 2, 2, 4, 5, 2, },
  119892. /* 5 TRIGGER: */ { 6, 5, 5, 5, 5, 5, 5, 5, },
  119893. /* 6 SEMI: */ { 6, 6, 5, 5, 5, 5, 5, 7, },
  119894. /* 7 END: */ { 1, 7, 5, 5, 5, 5, 5, 5, },
  119895. };
  119896. #else
  119897. /* If triggers are not supported by this compile then the statement machine
  119898. ** used to detect the end of a statement is much simpler
  119899. */
  119900. static const u8 trans[3][3] = {
  119901. /* Token: */
  119902. /* State: ** SEMI WS OTHER */
  119903. /* 0 INVALID: */ { 1, 0, 2, },
  119904. /* 1 START: */ { 1, 1, 2, },
  119905. /* 2 NORMAL: */ { 1, 2, 2, },
  119906. };
  119907. #endif /* SQLITE_OMIT_TRIGGER */
  119908. #ifdef SQLITE_ENABLE_API_ARMOR
  119909. if( zSql==0 ){
  119910. (void)SQLITE_MISUSE_BKPT;
  119911. return 0;
  119912. }
  119913. #endif
  119914. while( *zSql ){
  119915. switch( *zSql ){
  119916. case ';': { /* A semicolon */
  119917. token = tkSEMI;
  119918. break;
  119919. }
  119920. case ' ':
  119921. case '\r':
  119922. case '\t':
  119923. case '\n':
  119924. case '\f': { /* White space is ignored */
  119925. token = tkWS;
  119926. break;
  119927. }
  119928. case '/': { /* C-style comments */
  119929. if( zSql[1]!='*' ){
  119930. token = tkOTHER;
  119931. break;
  119932. }
  119933. zSql += 2;
  119934. while( zSql[0] && (zSql[0]!='*' || zSql[1]!='/') ){ zSql++; }
  119935. if( zSql[0]==0 ) return 0;
  119936. zSql++;
  119937. token = tkWS;
  119938. break;
  119939. }
  119940. case '-': { /* SQL-style comments from "--" to end of line */
  119941. if( zSql[1]!='-' ){
  119942. token = tkOTHER;
  119943. break;
  119944. }
  119945. while( *zSql && *zSql!='\n' ){ zSql++; }
  119946. if( *zSql==0 ) return state==1;
  119947. token = tkWS;
  119948. break;
  119949. }
  119950. case '[': { /* Microsoft-style identifiers in [...] */
  119951. zSql++;
  119952. while( *zSql && *zSql!=']' ){ zSql++; }
  119953. if( *zSql==0 ) return 0;
  119954. token = tkOTHER;
  119955. break;
  119956. }
  119957. case '`': /* Grave-accent quoted symbols used by MySQL */
  119958. case '"': /* single- and double-quoted strings */
  119959. case '\'': {
  119960. int c = *zSql;
  119961. zSql++;
  119962. while( *zSql && *zSql!=c ){ zSql++; }
  119963. if( *zSql==0 ) return 0;
  119964. token = tkOTHER;
  119965. break;
  119966. }
  119967. default: {
  119968. #ifdef SQLITE_EBCDIC
  119969. unsigned char c;
  119970. #endif
  119971. if( IdChar((u8)*zSql) ){
  119972. /* Keywords and unquoted identifiers */
  119973. int nId;
  119974. for(nId=1; IdChar(zSql[nId]); nId++){}
  119975. #ifdef SQLITE_OMIT_TRIGGER
  119976. token = tkOTHER;
  119977. #else
  119978. switch( *zSql ){
  119979. case 'c': case 'C': {
  119980. if( nId==6 && sqlite3StrNICmp(zSql, "create", 6)==0 ){
  119981. token = tkCREATE;
  119982. }else{
  119983. token = tkOTHER;
  119984. }
  119985. break;
  119986. }
  119987. case 't': case 'T': {
  119988. if( nId==7 && sqlite3StrNICmp(zSql, "trigger", 7)==0 ){
  119989. token = tkTRIGGER;
  119990. }else if( nId==4 && sqlite3StrNICmp(zSql, "temp", 4)==0 ){
  119991. token = tkTEMP;
  119992. }else if( nId==9 && sqlite3StrNICmp(zSql, "temporary", 9)==0 ){
  119993. token = tkTEMP;
  119994. }else{
  119995. token = tkOTHER;
  119996. }
  119997. break;
  119998. }
  119999. case 'e': case 'E': {
  120000. if( nId==3 && sqlite3StrNICmp(zSql, "end", 3)==0 ){
  120001. token = tkEND;
  120002. }else
  120003. #ifndef SQLITE_OMIT_EXPLAIN
  120004. if( nId==7 && sqlite3StrNICmp(zSql, "explain", 7)==0 ){
  120005. token = tkEXPLAIN;
  120006. }else
  120007. #endif
  120008. {
  120009. token = tkOTHER;
  120010. }
  120011. break;
  120012. }
  120013. default: {
  120014. token = tkOTHER;
  120015. break;
  120016. }
  120017. }
  120018. #endif /* SQLITE_OMIT_TRIGGER */
  120019. zSql += nId-1;
  120020. }else{
  120021. /* Operators and special symbols */
  120022. token = tkOTHER;
  120023. }
  120024. break;
  120025. }
  120026. }
  120027. state = trans[state][token];
  120028. zSql++;
  120029. }
  120030. return state==1;
  120031. }
  120032. #ifndef SQLITE_OMIT_UTF16
  120033. /*
  120034. ** This routine is the same as the sqlite3_complete() routine described
  120035. ** above, except that the parameter is required to be UTF-16 encoded, not
  120036. ** UTF-8.
  120037. */
  120038. SQLITE_API int SQLITE_STDCALL sqlite3_complete16(const void *zSql){
  120039. sqlite3_value *pVal;
  120040. char const *zSql8;
  120041. int rc;
  120042. #ifndef SQLITE_OMIT_AUTOINIT
  120043. rc = sqlite3_initialize();
  120044. if( rc ) return rc;
  120045. #endif
  120046. pVal = sqlite3ValueNew(0);
  120047. sqlite3ValueSetStr(pVal, -1, zSql, SQLITE_UTF16NATIVE, SQLITE_STATIC);
  120048. zSql8 = sqlite3ValueText(pVal, SQLITE_UTF8);
  120049. if( zSql8 ){
  120050. rc = sqlite3_complete(zSql8);
  120051. }else{
  120052. rc = SQLITE_NOMEM;
  120053. }
  120054. sqlite3ValueFree(pVal);
  120055. return sqlite3ApiExit(0, rc);
  120056. }
  120057. #endif /* SQLITE_OMIT_UTF16 */
  120058. #endif /* SQLITE_OMIT_COMPLETE */
  120059. /************** End of complete.c ********************************************/
  120060. /************** Begin file main.c ********************************************/
  120061. /*
  120062. ** 2001 September 15
  120063. **
  120064. ** The author disclaims copyright to this source code. In place of
  120065. ** a legal notice, here is a blessing:
  120066. **
  120067. ** May you do good and not evil.
  120068. ** May you find forgiveness for yourself and forgive others.
  120069. ** May you share freely, never taking more than you give.
  120070. **
  120071. *************************************************************************
  120072. ** Main file for the SQLite library. The routines in this file
  120073. ** implement the programmer interface to the library. Routines in
  120074. ** other files are for internal use by SQLite and should not be
  120075. ** accessed by users of the library.
  120076. */
  120077. #ifdef SQLITE_ENABLE_FTS3
  120078. /************** Include fts3.h in the middle of main.c ***********************/
  120079. /************** Begin file fts3.h ********************************************/
  120080. /*
  120081. ** 2006 Oct 10
  120082. **
  120083. ** The author disclaims copyright to this source code. In place of
  120084. ** a legal notice, here is a blessing:
  120085. **
  120086. ** May you do good and not evil.
  120087. ** May you find forgiveness for yourself and forgive others.
  120088. ** May you share freely, never taking more than you give.
  120089. **
  120090. ******************************************************************************
  120091. **
  120092. ** This header file is used by programs that want to link against the
  120093. ** FTS3 library. All it does is declare the sqlite3Fts3Init() interface.
  120094. */
  120095. #if 0
  120096. extern "C" {
  120097. #endif /* __cplusplus */
  120098. SQLITE_PRIVATE int sqlite3Fts3Init(sqlite3 *db);
  120099. #if 0
  120100. } /* extern "C" */
  120101. #endif /* __cplusplus */
  120102. /************** End of fts3.h ************************************************/
  120103. /************** Continuing where we left off in main.c ***********************/
  120104. #endif
  120105. #ifdef SQLITE_ENABLE_RTREE
  120106. /************** Include rtree.h in the middle of main.c **********************/
  120107. /************** Begin file rtree.h *******************************************/
  120108. /*
  120109. ** 2008 May 26
  120110. **
  120111. ** The author disclaims copyright to this source code. In place of
  120112. ** a legal notice, here is a blessing:
  120113. **
  120114. ** May you do good and not evil.
  120115. ** May you find forgiveness for yourself and forgive others.
  120116. ** May you share freely, never taking more than you give.
  120117. **
  120118. ******************************************************************************
  120119. **
  120120. ** This header file is used by programs that want to link against the
  120121. ** RTREE library. All it does is declare the sqlite3RtreeInit() interface.
  120122. */
  120123. #if 0
  120124. extern "C" {
  120125. #endif /* __cplusplus */
  120126. SQLITE_PRIVATE int sqlite3RtreeInit(sqlite3 *db);
  120127. #if 0
  120128. } /* extern "C" */
  120129. #endif /* __cplusplus */
  120130. /************** End of rtree.h ***********************************************/
  120131. /************** Continuing where we left off in main.c ***********************/
  120132. #endif
  120133. #ifdef SQLITE_ENABLE_ICU
  120134. /************** Include sqliteicu.h in the middle of main.c ******************/
  120135. /************** Begin file sqliteicu.h ***************************************/
  120136. /*
  120137. ** 2008 May 26
  120138. **
  120139. ** The author disclaims copyright to this source code. In place of
  120140. ** a legal notice, here is a blessing:
  120141. **
  120142. ** May you do good and not evil.
  120143. ** May you find forgiveness for yourself and forgive others.
  120144. ** May you share freely, never taking more than you give.
  120145. **
  120146. ******************************************************************************
  120147. **
  120148. ** This header file is used by programs that want to link against the
  120149. ** ICU extension. All it does is declare the sqlite3IcuInit() interface.
  120150. */
  120151. #if 0
  120152. extern "C" {
  120153. #endif /* __cplusplus */
  120154. SQLITE_PRIVATE int sqlite3IcuInit(sqlite3 *db);
  120155. #if 0
  120156. } /* extern "C" */
  120157. #endif /* __cplusplus */
  120158. /************** End of sqliteicu.h *******************************************/
  120159. /************** Continuing where we left off in main.c ***********************/
  120160. #endif
  120161. #ifndef SQLITE_AMALGAMATION
  120162. /* IMPLEMENTATION-OF: R-46656-45156 The sqlite3_version[] string constant
  120163. ** contains the text of SQLITE_VERSION macro.
  120164. */
  120165. SQLITE_API const char sqlite3_version[] = SQLITE_VERSION;
  120166. #endif
  120167. /* IMPLEMENTATION-OF: R-53536-42575 The sqlite3_libversion() function returns
  120168. ** a pointer to the to the sqlite3_version[] string constant.
  120169. */
  120170. SQLITE_API const char *SQLITE_STDCALL sqlite3_libversion(void){ return sqlite3_version; }
  120171. /* IMPLEMENTATION-OF: R-63124-39300 The sqlite3_sourceid() function returns a
  120172. ** pointer to a string constant whose value is the same as the
  120173. ** SQLITE_SOURCE_ID C preprocessor macro.
  120174. */
  120175. SQLITE_API const char *SQLITE_STDCALL sqlite3_sourceid(void){ return SQLITE_SOURCE_ID; }
  120176. /* IMPLEMENTATION-OF: R-35210-63508 The sqlite3_libversion_number() function
  120177. ** returns an integer equal to SQLITE_VERSION_NUMBER.
  120178. */
  120179. SQLITE_API int SQLITE_STDCALL sqlite3_libversion_number(void){ return SQLITE_VERSION_NUMBER; }
  120180. /* IMPLEMENTATION-OF: R-20790-14025 The sqlite3_threadsafe() function returns
  120181. ** zero if and only if SQLite was compiled with mutexing code omitted due to
  120182. ** the SQLITE_THREADSAFE compile-time option being set to 0.
  120183. */
  120184. SQLITE_API int SQLITE_STDCALL sqlite3_threadsafe(void){ return SQLITE_THREADSAFE; }
  120185. /*
  120186. ** When compiling the test fixture or with debugging enabled (on Win32),
  120187. ** this variable being set to non-zero will cause OSTRACE macros to emit
  120188. ** extra diagnostic information.
  120189. */
  120190. #ifdef SQLITE_HAVE_OS_TRACE
  120191. # ifndef SQLITE_DEBUG_OS_TRACE
  120192. # define SQLITE_DEBUG_OS_TRACE 0
  120193. # endif
  120194. int sqlite3OSTrace = SQLITE_DEBUG_OS_TRACE;
  120195. #endif
  120196. #if !defined(SQLITE_OMIT_TRACE) && defined(SQLITE_ENABLE_IOTRACE)
  120197. /*
  120198. ** If the following function pointer is not NULL and if
  120199. ** SQLITE_ENABLE_IOTRACE is enabled, then messages describing
  120200. ** I/O active are written using this function. These messages
  120201. ** are intended for debugging activity only.
  120202. */
  120203. SQLITE_API void (SQLITE_CDECL *sqlite3IoTrace)(const char*, ...) = 0;
  120204. #endif
  120205. /*
  120206. ** If the following global variable points to a string which is the
  120207. ** name of a directory, then that directory will be used to store
  120208. ** temporary files.
  120209. **
  120210. ** See also the "PRAGMA temp_store_directory" SQL command.
  120211. */
  120212. SQLITE_API char *sqlite3_temp_directory = 0;
  120213. /*
  120214. ** If the following global variable points to a string which is the
  120215. ** name of a directory, then that directory will be used to store
  120216. ** all database files specified with a relative pathname.
  120217. **
  120218. ** See also the "PRAGMA data_store_directory" SQL command.
  120219. */
  120220. SQLITE_API char *sqlite3_data_directory = 0;
  120221. /*
  120222. ** Initialize SQLite.
  120223. **
  120224. ** This routine must be called to initialize the memory allocation,
  120225. ** VFS, and mutex subsystems prior to doing any serious work with
  120226. ** SQLite. But as long as you do not compile with SQLITE_OMIT_AUTOINIT
  120227. ** this routine will be called automatically by key routines such as
  120228. ** sqlite3_open().
  120229. **
  120230. ** This routine is a no-op except on its very first call for the process,
  120231. ** or for the first call after a call to sqlite3_shutdown.
  120232. **
  120233. ** The first thread to call this routine runs the initialization to
  120234. ** completion. If subsequent threads call this routine before the first
  120235. ** thread has finished the initialization process, then the subsequent
  120236. ** threads must block until the first thread finishes with the initialization.
  120237. **
  120238. ** The first thread might call this routine recursively. Recursive
  120239. ** calls to this routine should not block, of course. Otherwise the
  120240. ** initialization process would never complete.
  120241. **
  120242. ** Let X be the first thread to enter this routine. Let Y be some other
  120243. ** thread. Then while the initial invocation of this routine by X is
  120244. ** incomplete, it is required that:
  120245. **
  120246. ** * Calls to this routine from Y must block until the outer-most
  120247. ** call by X completes.
  120248. **
  120249. ** * Recursive calls to this routine from thread X return immediately
  120250. ** without blocking.
  120251. */
  120252. SQLITE_API int SQLITE_STDCALL sqlite3_initialize(void){
  120253. MUTEX_LOGIC( sqlite3_mutex *pMaster; ) /* The main static mutex */
  120254. int rc; /* Result code */
  120255. #ifdef SQLITE_EXTRA_INIT
  120256. int bRunExtraInit = 0; /* Extra initialization needed */
  120257. #endif
  120258. #ifdef SQLITE_OMIT_WSD
  120259. rc = sqlite3_wsd_init(4096, 24);
  120260. if( rc!=SQLITE_OK ){
  120261. return rc;
  120262. }
  120263. #endif
  120264. /* If the following assert() fails on some obscure processor/compiler
  120265. ** combination, the work-around is to set the correct pointer
  120266. ** size at compile-time using -DSQLITE_PTRSIZE=n compile-time option */
  120267. assert( SQLITE_PTRSIZE==sizeof(char*) );
  120268. /* If SQLite is already completely initialized, then this call
  120269. ** to sqlite3_initialize() should be a no-op. But the initialization
  120270. ** must be complete. So isInit must not be set until the very end
  120271. ** of this routine.
  120272. */
  120273. if( sqlite3GlobalConfig.isInit ) return SQLITE_OK;
  120274. /* Make sure the mutex subsystem is initialized. If unable to
  120275. ** initialize the mutex subsystem, return early with the error.
  120276. ** If the system is so sick that we are unable to allocate a mutex,
  120277. ** there is not much SQLite is going to be able to do.
  120278. **
  120279. ** The mutex subsystem must take care of serializing its own
  120280. ** initialization.
  120281. */
  120282. rc = sqlite3MutexInit();
  120283. if( rc ) return rc;
  120284. /* Initialize the malloc() system and the recursive pInitMutex mutex.
  120285. ** This operation is protected by the STATIC_MASTER mutex. Note that
  120286. ** MutexAlloc() is called for a static mutex prior to initializing the
  120287. ** malloc subsystem - this implies that the allocation of a static
  120288. ** mutex must not require support from the malloc subsystem.
  120289. */
  120290. MUTEX_LOGIC( pMaster = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); )
  120291. sqlite3_mutex_enter(pMaster);
  120292. sqlite3GlobalConfig.isMutexInit = 1;
  120293. if( !sqlite3GlobalConfig.isMallocInit ){
  120294. rc = sqlite3MallocInit();
  120295. }
  120296. if( rc==SQLITE_OK ){
  120297. sqlite3GlobalConfig.isMallocInit = 1;
  120298. if( !sqlite3GlobalConfig.pInitMutex ){
  120299. sqlite3GlobalConfig.pInitMutex =
  120300. sqlite3MutexAlloc(SQLITE_MUTEX_RECURSIVE);
  120301. if( sqlite3GlobalConfig.bCoreMutex && !sqlite3GlobalConfig.pInitMutex ){
  120302. rc = SQLITE_NOMEM;
  120303. }
  120304. }
  120305. }
  120306. if( rc==SQLITE_OK ){
  120307. sqlite3GlobalConfig.nRefInitMutex++;
  120308. }
  120309. sqlite3_mutex_leave(pMaster);
  120310. /* If rc is not SQLITE_OK at this point, then either the malloc
  120311. ** subsystem could not be initialized or the system failed to allocate
  120312. ** the pInitMutex mutex. Return an error in either case. */
  120313. if( rc!=SQLITE_OK ){
  120314. return rc;
  120315. }
  120316. /* Do the rest of the initialization under the recursive mutex so
  120317. ** that we will be able to handle recursive calls into
  120318. ** sqlite3_initialize(). The recursive calls normally come through
  120319. ** sqlite3_os_init() when it invokes sqlite3_vfs_register(), but other
  120320. ** recursive calls might also be possible.
  120321. **
  120322. ** IMPLEMENTATION-OF: R-00140-37445 SQLite automatically serializes calls
  120323. ** to the xInit method, so the xInit method need not be threadsafe.
  120324. **
  120325. ** The following mutex is what serializes access to the appdef pcache xInit
  120326. ** methods. The sqlite3_pcache_methods.xInit() all is embedded in the
  120327. ** call to sqlite3PcacheInitialize().
  120328. */
  120329. sqlite3_mutex_enter(sqlite3GlobalConfig.pInitMutex);
  120330. if( sqlite3GlobalConfig.isInit==0 && sqlite3GlobalConfig.inProgress==0 ){
  120331. FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
  120332. sqlite3GlobalConfig.inProgress = 1;
  120333. memset(pHash, 0, sizeof(sqlite3GlobalFunctions));
  120334. sqlite3RegisterGlobalFunctions();
  120335. if( sqlite3GlobalConfig.isPCacheInit==0 ){
  120336. rc = sqlite3PcacheInitialize();
  120337. }
  120338. if( rc==SQLITE_OK ){
  120339. sqlite3GlobalConfig.isPCacheInit = 1;
  120340. rc = sqlite3OsInit();
  120341. }
  120342. if( rc==SQLITE_OK ){
  120343. sqlite3PCacheBufferSetup( sqlite3GlobalConfig.pPage,
  120344. sqlite3GlobalConfig.szPage, sqlite3GlobalConfig.nPage);
  120345. sqlite3GlobalConfig.isInit = 1;
  120346. #ifdef SQLITE_EXTRA_INIT
  120347. bRunExtraInit = 1;
  120348. #endif
  120349. }
  120350. sqlite3GlobalConfig.inProgress = 0;
  120351. }
  120352. sqlite3_mutex_leave(sqlite3GlobalConfig.pInitMutex);
  120353. /* Go back under the static mutex and clean up the recursive
  120354. ** mutex to prevent a resource leak.
  120355. */
  120356. sqlite3_mutex_enter(pMaster);
  120357. sqlite3GlobalConfig.nRefInitMutex--;
  120358. if( sqlite3GlobalConfig.nRefInitMutex<=0 ){
  120359. assert( sqlite3GlobalConfig.nRefInitMutex==0 );
  120360. sqlite3_mutex_free(sqlite3GlobalConfig.pInitMutex);
  120361. sqlite3GlobalConfig.pInitMutex = 0;
  120362. }
  120363. sqlite3_mutex_leave(pMaster);
  120364. /* The following is just a sanity check to make sure SQLite has
  120365. ** been compiled correctly. It is important to run this code, but
  120366. ** we don't want to run it too often and soak up CPU cycles for no
  120367. ** reason. So we run it once during initialization.
  120368. */
  120369. #ifndef NDEBUG
  120370. #ifndef SQLITE_OMIT_FLOATING_POINT
  120371. /* This section of code's only "output" is via assert() statements. */
  120372. if ( rc==SQLITE_OK ){
  120373. u64 x = (((u64)1)<<63)-1;
  120374. double y;
  120375. assert(sizeof(x)==8);
  120376. assert(sizeof(x)==sizeof(y));
  120377. memcpy(&y, &x, 8);
  120378. assert( sqlite3IsNaN(y) );
  120379. }
  120380. #endif
  120381. #endif
  120382. /* Do extra initialization steps requested by the SQLITE_EXTRA_INIT
  120383. ** compile-time option.
  120384. */
  120385. #ifdef SQLITE_EXTRA_INIT
  120386. if( bRunExtraInit ){
  120387. int SQLITE_EXTRA_INIT(const char*);
  120388. rc = SQLITE_EXTRA_INIT(0);
  120389. }
  120390. #endif
  120391. return rc;
  120392. }
  120393. /*
  120394. ** Undo the effects of sqlite3_initialize(). Must not be called while
  120395. ** there are outstanding database connections or memory allocations or
  120396. ** while any part of SQLite is otherwise in use in any thread. This
  120397. ** routine is not threadsafe. But it is safe to invoke this routine
  120398. ** on when SQLite is already shut down. If SQLite is already shut down
  120399. ** when this routine is invoked, then this routine is a harmless no-op.
  120400. */
  120401. SQLITE_API int SQLITE_STDCALL sqlite3_shutdown(void){
  120402. #ifdef SQLITE_OMIT_WSD
  120403. int rc = sqlite3_wsd_init(4096, 24);
  120404. if( rc!=SQLITE_OK ){
  120405. return rc;
  120406. }
  120407. #endif
  120408. if( sqlite3GlobalConfig.isInit ){
  120409. #ifdef SQLITE_EXTRA_SHUTDOWN
  120410. void SQLITE_EXTRA_SHUTDOWN(void);
  120411. SQLITE_EXTRA_SHUTDOWN();
  120412. #endif
  120413. sqlite3_os_end();
  120414. sqlite3_reset_auto_extension();
  120415. sqlite3GlobalConfig.isInit = 0;
  120416. }
  120417. if( sqlite3GlobalConfig.isPCacheInit ){
  120418. sqlite3PcacheShutdown();
  120419. sqlite3GlobalConfig.isPCacheInit = 0;
  120420. }
  120421. if( sqlite3GlobalConfig.isMallocInit ){
  120422. sqlite3MallocEnd();
  120423. sqlite3GlobalConfig.isMallocInit = 0;
  120424. #ifndef SQLITE_OMIT_SHUTDOWN_DIRECTORIES
  120425. /* The heap subsystem has now been shutdown and these values are supposed
  120426. ** to be NULL or point to memory that was obtained from sqlite3_malloc(),
  120427. ** which would rely on that heap subsystem; therefore, make sure these
  120428. ** values cannot refer to heap memory that was just invalidated when the
  120429. ** heap subsystem was shutdown. This is only done if the current call to
  120430. ** this function resulted in the heap subsystem actually being shutdown.
  120431. */
  120432. sqlite3_data_directory = 0;
  120433. sqlite3_temp_directory = 0;
  120434. #endif
  120435. }
  120436. if( sqlite3GlobalConfig.isMutexInit ){
  120437. sqlite3MutexEnd();
  120438. sqlite3GlobalConfig.isMutexInit = 0;
  120439. }
  120440. return SQLITE_OK;
  120441. }
  120442. /*
  120443. ** This API allows applications to modify the global configuration of
  120444. ** the SQLite library at run-time.
  120445. **
  120446. ** This routine should only be called when there are no outstanding
  120447. ** database connections or memory allocations. This routine is not
  120448. ** threadsafe. Failure to heed these warnings can lead to unpredictable
  120449. ** behavior.
  120450. */
  120451. SQLITE_API int SQLITE_CDECL sqlite3_config(int op, ...){
  120452. va_list ap;
  120453. int rc = SQLITE_OK;
  120454. /* sqlite3_config() shall return SQLITE_MISUSE if it is invoked while
  120455. ** the SQLite library is in use. */
  120456. if( sqlite3GlobalConfig.isInit ) return SQLITE_MISUSE_BKPT;
  120457. va_start(ap, op);
  120458. switch( op ){
  120459. /* Mutex configuration options are only available in a threadsafe
  120460. ** compile.
  120461. */
  120462. #if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0 /* IMP: R-54466-46756 */
  120463. case SQLITE_CONFIG_SINGLETHREAD: {
  120464. /* EVIDENCE-OF: R-02748-19096 This option sets the threading mode to
  120465. ** Single-thread. */
  120466. sqlite3GlobalConfig.bCoreMutex = 0; /* Disable mutex on core */
  120467. sqlite3GlobalConfig.bFullMutex = 0; /* Disable mutex on connections */
  120468. break;
  120469. }
  120470. #endif
  120471. #if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0 /* IMP: R-20520-54086 */
  120472. case SQLITE_CONFIG_MULTITHREAD: {
  120473. /* EVIDENCE-OF: R-14374-42468 This option sets the threading mode to
  120474. ** Multi-thread. */
  120475. sqlite3GlobalConfig.bCoreMutex = 1; /* Enable mutex on core */
  120476. sqlite3GlobalConfig.bFullMutex = 0; /* Disable mutex on connections */
  120477. break;
  120478. }
  120479. #endif
  120480. #if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0 /* IMP: R-59593-21810 */
  120481. case SQLITE_CONFIG_SERIALIZED: {
  120482. /* EVIDENCE-OF: R-41220-51800 This option sets the threading mode to
  120483. ** Serialized. */
  120484. sqlite3GlobalConfig.bCoreMutex = 1; /* Enable mutex on core */
  120485. sqlite3GlobalConfig.bFullMutex = 1; /* Enable mutex on connections */
  120486. break;
  120487. }
  120488. #endif
  120489. #if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0 /* IMP: R-63666-48755 */
  120490. case SQLITE_CONFIG_MUTEX: {
  120491. /* Specify an alternative mutex implementation */
  120492. sqlite3GlobalConfig.mutex = *va_arg(ap, sqlite3_mutex_methods*);
  120493. break;
  120494. }
  120495. #endif
  120496. #if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0 /* IMP: R-14450-37597 */
  120497. case SQLITE_CONFIG_GETMUTEX: {
  120498. /* Retrieve the current mutex implementation */
  120499. *va_arg(ap, sqlite3_mutex_methods*) = sqlite3GlobalConfig.mutex;
  120500. break;
  120501. }
  120502. #endif
  120503. case SQLITE_CONFIG_MALLOC: {
  120504. /* EVIDENCE-OF: R-55594-21030 The SQLITE_CONFIG_MALLOC option takes a
  120505. ** single argument which is a pointer to an instance of the
  120506. ** sqlite3_mem_methods structure. The argument specifies alternative
  120507. ** low-level memory allocation routines to be used in place of the memory
  120508. ** allocation routines built into SQLite. */
  120509. sqlite3GlobalConfig.m = *va_arg(ap, sqlite3_mem_methods*);
  120510. break;
  120511. }
  120512. case SQLITE_CONFIG_GETMALLOC: {
  120513. /* EVIDENCE-OF: R-51213-46414 The SQLITE_CONFIG_GETMALLOC option takes a
  120514. ** single argument which is a pointer to an instance of the
  120515. ** sqlite3_mem_methods structure. The sqlite3_mem_methods structure is
  120516. ** filled with the currently defined memory allocation routines. */
  120517. if( sqlite3GlobalConfig.m.xMalloc==0 ) sqlite3MemSetDefault();
  120518. *va_arg(ap, sqlite3_mem_methods*) = sqlite3GlobalConfig.m;
  120519. break;
  120520. }
  120521. case SQLITE_CONFIG_MEMSTATUS: {
  120522. /* EVIDENCE-OF: R-61275-35157 The SQLITE_CONFIG_MEMSTATUS option takes
  120523. ** single argument of type int, interpreted as a boolean, which enables
  120524. ** or disables the collection of memory allocation statistics. */
  120525. sqlite3GlobalConfig.bMemstat = va_arg(ap, int);
  120526. break;
  120527. }
  120528. case SQLITE_CONFIG_SCRATCH: {
  120529. /* EVIDENCE-OF: R-08404-60887 There are three arguments to
  120530. ** SQLITE_CONFIG_SCRATCH: A pointer an 8-byte aligned memory buffer from
  120531. ** which the scratch allocations will be drawn, the size of each scratch
  120532. ** allocation (sz), and the maximum number of scratch allocations (N). */
  120533. sqlite3GlobalConfig.pScratch = va_arg(ap, void*);
  120534. sqlite3GlobalConfig.szScratch = va_arg(ap, int);
  120535. sqlite3GlobalConfig.nScratch = va_arg(ap, int);
  120536. break;
  120537. }
  120538. case SQLITE_CONFIG_PAGECACHE: {
  120539. /* EVIDENCE-OF: R-31408-40510 There are three arguments to
  120540. ** SQLITE_CONFIG_PAGECACHE: A pointer to 8-byte aligned memory, the size
  120541. ** of each page buffer (sz), and the number of pages (N). */
  120542. sqlite3GlobalConfig.pPage = va_arg(ap, void*);
  120543. sqlite3GlobalConfig.szPage = va_arg(ap, int);
  120544. sqlite3GlobalConfig.nPage = va_arg(ap, int);
  120545. break;
  120546. }
  120547. case SQLITE_CONFIG_PCACHE_HDRSZ: {
  120548. /* EVIDENCE-OF: R-39100-27317 The SQLITE_CONFIG_PCACHE_HDRSZ option takes
  120549. ** a single parameter which is a pointer to an integer and writes into
  120550. ** that integer the number of extra bytes per page required for each page
  120551. ** in SQLITE_CONFIG_PAGECACHE. */
  120552. *va_arg(ap, int*) =
  120553. sqlite3HeaderSizeBtree() +
  120554. sqlite3HeaderSizePcache() +
  120555. sqlite3HeaderSizePcache1();
  120556. break;
  120557. }
  120558. case SQLITE_CONFIG_PCACHE: {
  120559. /* no-op */
  120560. break;
  120561. }
  120562. case SQLITE_CONFIG_GETPCACHE: {
  120563. /* now an error */
  120564. rc = SQLITE_ERROR;
  120565. break;
  120566. }
  120567. case SQLITE_CONFIG_PCACHE2: {
  120568. /* EVIDENCE-OF: R-63325-48378 The SQLITE_CONFIG_PCACHE2 option takes a
  120569. ** single argument which is a pointer to an sqlite3_pcache_methods2
  120570. ** object. This object specifies the interface to a custom page cache
  120571. ** implementation. */
  120572. sqlite3GlobalConfig.pcache2 = *va_arg(ap, sqlite3_pcache_methods2*);
  120573. break;
  120574. }
  120575. case SQLITE_CONFIG_GETPCACHE2: {
  120576. /* EVIDENCE-OF: R-22035-46182 The SQLITE_CONFIG_GETPCACHE2 option takes a
  120577. ** single argument which is a pointer to an sqlite3_pcache_methods2
  120578. ** object. SQLite copies of the current page cache implementation into
  120579. ** that object. */
  120580. if( sqlite3GlobalConfig.pcache2.xInit==0 ){
  120581. sqlite3PCacheSetDefault();
  120582. }
  120583. *va_arg(ap, sqlite3_pcache_methods2*) = sqlite3GlobalConfig.pcache2;
  120584. break;
  120585. }
  120586. /* EVIDENCE-OF: R-06626-12911 The SQLITE_CONFIG_HEAP option is only
  120587. ** available if SQLite is compiled with either SQLITE_ENABLE_MEMSYS3 or
  120588. ** SQLITE_ENABLE_MEMSYS5 and returns SQLITE_ERROR if invoked otherwise. */
  120589. #if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
  120590. case SQLITE_CONFIG_HEAP: {
  120591. /* EVIDENCE-OF: R-19854-42126 There are three arguments to
  120592. ** SQLITE_CONFIG_HEAP: An 8-byte aligned pointer to the memory, the
  120593. ** number of bytes in the memory buffer, and the minimum allocation size.
  120594. */
  120595. sqlite3GlobalConfig.pHeap = va_arg(ap, void*);
  120596. sqlite3GlobalConfig.nHeap = va_arg(ap, int);
  120597. sqlite3GlobalConfig.mnReq = va_arg(ap, int);
  120598. if( sqlite3GlobalConfig.mnReq<1 ){
  120599. sqlite3GlobalConfig.mnReq = 1;
  120600. }else if( sqlite3GlobalConfig.mnReq>(1<<12) ){
  120601. /* cap min request size at 2^12 */
  120602. sqlite3GlobalConfig.mnReq = (1<<12);
  120603. }
  120604. if( sqlite3GlobalConfig.pHeap==0 ){
  120605. /* EVIDENCE-OF: R-49920-60189 If the first pointer (the memory pointer)
  120606. ** is NULL, then SQLite reverts to using its default memory allocator
  120607. ** (the system malloc() implementation), undoing any prior invocation of
  120608. ** SQLITE_CONFIG_MALLOC.
  120609. **
  120610. ** Setting sqlite3GlobalConfig.m to all zeros will cause malloc to
  120611. ** revert to its default implementation when sqlite3_initialize() is run
  120612. */
  120613. memset(&sqlite3GlobalConfig.m, 0, sizeof(sqlite3GlobalConfig.m));
  120614. }else{
  120615. /* EVIDENCE-OF: R-61006-08918 If the memory pointer is not NULL then the
  120616. ** alternative memory allocator is engaged to handle all of SQLites
  120617. ** memory allocation needs. */
  120618. #ifdef SQLITE_ENABLE_MEMSYS3
  120619. sqlite3GlobalConfig.m = *sqlite3MemGetMemsys3();
  120620. #endif
  120621. #ifdef SQLITE_ENABLE_MEMSYS5
  120622. sqlite3GlobalConfig.m = *sqlite3MemGetMemsys5();
  120623. #endif
  120624. }
  120625. break;
  120626. }
  120627. #endif
  120628. case SQLITE_CONFIG_LOOKASIDE: {
  120629. sqlite3GlobalConfig.szLookaside = va_arg(ap, int);
  120630. sqlite3GlobalConfig.nLookaside = va_arg(ap, int);
  120631. break;
  120632. }
  120633. /* Record a pointer to the logger function and its first argument.
  120634. ** The default is NULL. Logging is disabled if the function pointer is
  120635. ** NULL.
  120636. */
  120637. case SQLITE_CONFIG_LOG: {
  120638. /* MSVC is picky about pulling func ptrs from va lists.
  120639. ** http://support.microsoft.com/kb/47961
  120640. ** sqlite3GlobalConfig.xLog = va_arg(ap, void(*)(void*,int,const char*));
  120641. */
  120642. typedef void(*LOGFUNC_t)(void*,int,const char*);
  120643. sqlite3GlobalConfig.xLog = va_arg(ap, LOGFUNC_t);
  120644. sqlite3GlobalConfig.pLogArg = va_arg(ap, void*);
  120645. break;
  120646. }
  120647. /* EVIDENCE-OF: R-55548-33817 The compile-time setting for URI filenames
  120648. ** can be changed at start-time using the
  120649. ** sqlite3_config(SQLITE_CONFIG_URI,1) or
  120650. ** sqlite3_config(SQLITE_CONFIG_URI,0) configuration calls.
  120651. */
  120652. case SQLITE_CONFIG_URI: {
  120653. /* EVIDENCE-OF: R-25451-61125 The SQLITE_CONFIG_URI option takes a single
  120654. ** argument of type int. If non-zero, then URI handling is globally
  120655. ** enabled. If the parameter is zero, then URI handling is globally
  120656. ** disabled. */
  120657. sqlite3GlobalConfig.bOpenUri = va_arg(ap, int);
  120658. break;
  120659. }
  120660. case SQLITE_CONFIG_COVERING_INDEX_SCAN: {
  120661. /* EVIDENCE-OF: R-36592-02772 The SQLITE_CONFIG_COVERING_INDEX_SCAN
  120662. ** option takes a single integer argument which is interpreted as a
  120663. ** boolean in order to enable or disable the use of covering indices for
  120664. ** full table scans in the query optimizer. */
  120665. sqlite3GlobalConfig.bUseCis = va_arg(ap, int);
  120666. break;
  120667. }
  120668. #ifdef SQLITE_ENABLE_SQLLOG
  120669. case SQLITE_CONFIG_SQLLOG: {
  120670. typedef void(*SQLLOGFUNC_t)(void*, sqlite3*, const char*, int);
  120671. sqlite3GlobalConfig.xSqllog = va_arg(ap, SQLLOGFUNC_t);
  120672. sqlite3GlobalConfig.pSqllogArg = va_arg(ap, void *);
  120673. break;
  120674. }
  120675. #endif
  120676. case SQLITE_CONFIG_MMAP_SIZE: {
  120677. /* EVIDENCE-OF: R-58063-38258 SQLITE_CONFIG_MMAP_SIZE takes two 64-bit
  120678. ** integer (sqlite3_int64) values that are the default mmap size limit
  120679. ** (the default setting for PRAGMA mmap_size) and the maximum allowed
  120680. ** mmap size limit. */
  120681. sqlite3_int64 szMmap = va_arg(ap, sqlite3_int64);
  120682. sqlite3_int64 mxMmap = va_arg(ap, sqlite3_int64);
  120683. /* EVIDENCE-OF: R-53367-43190 If either argument to this option is
  120684. ** negative, then that argument is changed to its compile-time default.
  120685. **
  120686. ** EVIDENCE-OF: R-34993-45031 The maximum allowed mmap size will be
  120687. ** silently truncated if necessary so that it does not exceed the
  120688. ** compile-time maximum mmap size set by the SQLITE_MAX_MMAP_SIZE
  120689. ** compile-time option.
  120690. */
  120691. if( mxMmap<0 || mxMmap>SQLITE_MAX_MMAP_SIZE ){
  120692. mxMmap = SQLITE_MAX_MMAP_SIZE;
  120693. }
  120694. if( szMmap<0 ) szMmap = SQLITE_DEFAULT_MMAP_SIZE;
  120695. if( szMmap>mxMmap) szMmap = mxMmap;
  120696. sqlite3GlobalConfig.mxMmap = mxMmap;
  120697. sqlite3GlobalConfig.szMmap = szMmap;
  120698. break;
  120699. }
  120700. #if SQLITE_OS_WIN && defined(SQLITE_WIN32_MALLOC) /* IMP: R-04780-55815 */
  120701. case SQLITE_CONFIG_WIN32_HEAPSIZE: {
  120702. /* EVIDENCE-OF: R-34926-03360 SQLITE_CONFIG_WIN32_HEAPSIZE takes a 32-bit
  120703. ** unsigned integer value that specifies the maximum size of the created
  120704. ** heap. */
  120705. sqlite3GlobalConfig.nHeap = va_arg(ap, int);
  120706. break;
  120707. }
  120708. #endif
  120709. case SQLITE_CONFIG_PMASZ: {
  120710. sqlite3GlobalConfig.szPma = va_arg(ap, unsigned int);
  120711. break;
  120712. }
  120713. default: {
  120714. rc = SQLITE_ERROR;
  120715. break;
  120716. }
  120717. }
  120718. va_end(ap);
  120719. return rc;
  120720. }
  120721. /*
  120722. ** Set up the lookaside buffers for a database connection.
  120723. ** Return SQLITE_OK on success.
  120724. ** If lookaside is already active, return SQLITE_BUSY.
  120725. **
  120726. ** The sz parameter is the number of bytes in each lookaside slot.
  120727. ** The cnt parameter is the number of slots. If pStart is NULL the
  120728. ** space for the lookaside memory is obtained from sqlite3_malloc().
  120729. ** If pStart is not NULL then it is sz*cnt bytes of memory to use for
  120730. ** the lookaside memory.
  120731. */
  120732. static int setupLookaside(sqlite3 *db, void *pBuf, int sz, int cnt){
  120733. void *pStart;
  120734. if( db->lookaside.nOut ){
  120735. return SQLITE_BUSY;
  120736. }
  120737. /* Free any existing lookaside buffer for this handle before
  120738. ** allocating a new one so we don't have to have space for
  120739. ** both at the same time.
  120740. */
  120741. if( db->lookaside.bMalloced ){
  120742. sqlite3_free(db->lookaside.pStart);
  120743. }
  120744. /* The size of a lookaside slot after ROUNDDOWN8 needs to be larger
  120745. ** than a pointer to be useful.
  120746. */
  120747. sz = ROUNDDOWN8(sz); /* IMP: R-33038-09382 */
  120748. if( sz<=(int)sizeof(LookasideSlot*) ) sz = 0;
  120749. if( cnt<0 ) cnt = 0;
  120750. if( sz==0 || cnt==0 ){
  120751. sz = 0;
  120752. pStart = 0;
  120753. }else if( pBuf==0 ){
  120754. sqlite3BeginBenignMalloc();
  120755. pStart = sqlite3Malloc( sz*cnt ); /* IMP: R-61949-35727 */
  120756. sqlite3EndBenignMalloc();
  120757. if( pStart ) cnt = sqlite3MallocSize(pStart)/sz;
  120758. }else{
  120759. pStart = pBuf;
  120760. }
  120761. db->lookaside.pStart = pStart;
  120762. db->lookaside.pFree = 0;
  120763. db->lookaside.sz = (u16)sz;
  120764. if( pStart ){
  120765. int i;
  120766. LookasideSlot *p;
  120767. assert( sz > (int)sizeof(LookasideSlot*) );
  120768. p = (LookasideSlot*)pStart;
  120769. for(i=cnt-1; i>=0; i--){
  120770. p->pNext = db->lookaside.pFree;
  120771. db->lookaside.pFree = p;
  120772. p = (LookasideSlot*)&((u8*)p)[sz];
  120773. }
  120774. db->lookaside.pEnd = p;
  120775. db->lookaside.bEnabled = 1;
  120776. db->lookaside.bMalloced = pBuf==0 ?1:0;
  120777. }else{
  120778. db->lookaside.pStart = db;
  120779. db->lookaside.pEnd = db;
  120780. db->lookaside.bEnabled = 0;
  120781. db->lookaside.bMalloced = 0;
  120782. }
  120783. return SQLITE_OK;
  120784. }
  120785. /*
  120786. ** Return the mutex associated with a database connection.
  120787. */
  120788. SQLITE_API sqlite3_mutex *SQLITE_STDCALL sqlite3_db_mutex(sqlite3 *db){
  120789. #ifdef SQLITE_ENABLE_API_ARMOR
  120790. if( !sqlite3SafetyCheckOk(db) ){
  120791. (void)SQLITE_MISUSE_BKPT;
  120792. return 0;
  120793. }
  120794. #endif
  120795. return db->mutex;
  120796. }
  120797. /*
  120798. ** Free up as much memory as we can from the given database
  120799. ** connection.
  120800. */
  120801. SQLITE_API int SQLITE_STDCALL sqlite3_db_release_memory(sqlite3 *db){
  120802. int i;
  120803. #ifdef SQLITE_ENABLE_API_ARMOR
  120804. if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
  120805. #endif
  120806. sqlite3_mutex_enter(db->mutex);
  120807. sqlite3BtreeEnterAll(db);
  120808. for(i=0; i<db->nDb; i++){
  120809. Btree *pBt = db->aDb[i].pBt;
  120810. if( pBt ){
  120811. Pager *pPager = sqlite3BtreePager(pBt);
  120812. sqlite3PagerShrink(pPager);
  120813. }
  120814. }
  120815. sqlite3BtreeLeaveAll(db);
  120816. sqlite3_mutex_leave(db->mutex);
  120817. return SQLITE_OK;
  120818. }
  120819. /*
  120820. ** Configuration settings for an individual database connection
  120821. */
  120822. SQLITE_API int SQLITE_CDECL sqlite3_db_config(sqlite3 *db, int op, ...){
  120823. va_list ap;
  120824. int rc;
  120825. va_start(ap, op);
  120826. switch( op ){
  120827. case SQLITE_DBCONFIG_LOOKASIDE: {
  120828. void *pBuf = va_arg(ap, void*); /* IMP: R-26835-10964 */
  120829. int sz = va_arg(ap, int); /* IMP: R-47871-25994 */
  120830. int cnt = va_arg(ap, int); /* IMP: R-04460-53386 */
  120831. rc = setupLookaside(db, pBuf, sz, cnt);
  120832. break;
  120833. }
  120834. default: {
  120835. static const struct {
  120836. int op; /* The opcode */
  120837. u32 mask; /* Mask of the bit in sqlite3.flags to set/clear */
  120838. } aFlagOp[] = {
  120839. { SQLITE_DBCONFIG_ENABLE_FKEY, SQLITE_ForeignKeys },
  120840. { SQLITE_DBCONFIG_ENABLE_TRIGGER, SQLITE_EnableTrigger },
  120841. };
  120842. unsigned int i;
  120843. rc = SQLITE_ERROR; /* IMP: R-42790-23372 */
  120844. for(i=0; i<ArraySize(aFlagOp); i++){
  120845. if( aFlagOp[i].op==op ){
  120846. int onoff = va_arg(ap, int);
  120847. int *pRes = va_arg(ap, int*);
  120848. int oldFlags = db->flags;
  120849. if( onoff>0 ){
  120850. db->flags |= aFlagOp[i].mask;
  120851. }else if( onoff==0 ){
  120852. db->flags &= ~aFlagOp[i].mask;
  120853. }
  120854. if( oldFlags!=db->flags ){
  120855. sqlite3ExpirePreparedStatements(db);
  120856. }
  120857. if( pRes ){
  120858. *pRes = (db->flags & aFlagOp[i].mask)!=0;
  120859. }
  120860. rc = SQLITE_OK;
  120861. break;
  120862. }
  120863. }
  120864. break;
  120865. }
  120866. }
  120867. va_end(ap);
  120868. return rc;
  120869. }
  120870. /*
  120871. ** Return true if the buffer z[0..n-1] contains all spaces.
  120872. */
  120873. static int allSpaces(const char *z, int n){
  120874. while( n>0 && z[n-1]==' ' ){ n--; }
  120875. return n==0;
  120876. }
  120877. /*
  120878. ** This is the default collating function named "BINARY" which is always
  120879. ** available.
  120880. **
  120881. ** If the padFlag argument is not NULL then space padding at the end
  120882. ** of strings is ignored. This implements the RTRIM collation.
  120883. */
  120884. static int binCollFunc(
  120885. void *padFlag,
  120886. int nKey1, const void *pKey1,
  120887. int nKey2, const void *pKey2
  120888. ){
  120889. int rc, n;
  120890. n = nKey1<nKey2 ? nKey1 : nKey2;
  120891. /* EVIDENCE-OF: R-65033-28449 The built-in BINARY collation compares
  120892. ** strings byte by byte using the memcmp() function from the standard C
  120893. ** library. */
  120894. rc = memcmp(pKey1, pKey2, n);
  120895. if( rc==0 ){
  120896. if( padFlag
  120897. && allSpaces(((char*)pKey1)+n, nKey1-n)
  120898. && allSpaces(((char*)pKey2)+n, nKey2-n)
  120899. ){
  120900. /* EVIDENCE-OF: R-31624-24737 RTRIM is like BINARY except that extra
  120901. ** spaces at the end of either string do not change the result. In other
  120902. ** words, strings will compare equal to one another as long as they
  120903. ** differ only in the number of spaces at the end.
  120904. */
  120905. }else{
  120906. rc = nKey1 - nKey2;
  120907. }
  120908. }
  120909. return rc;
  120910. }
  120911. /*
  120912. ** Another built-in collating sequence: NOCASE.
  120913. **
  120914. ** This collating sequence is intended to be used for "case independent
  120915. ** comparison". SQLite's knowledge of upper and lower case equivalents
  120916. ** extends only to the 26 characters used in the English language.
  120917. **
  120918. ** At the moment there is only a UTF-8 implementation.
  120919. */
  120920. static int nocaseCollatingFunc(
  120921. void *NotUsed,
  120922. int nKey1, const void *pKey1,
  120923. int nKey2, const void *pKey2
  120924. ){
  120925. int r = sqlite3StrNICmp(
  120926. (const char *)pKey1, (const char *)pKey2, (nKey1<nKey2)?nKey1:nKey2);
  120927. UNUSED_PARAMETER(NotUsed);
  120928. if( 0==r ){
  120929. r = nKey1-nKey2;
  120930. }
  120931. return r;
  120932. }
  120933. /*
  120934. ** Return the ROWID of the most recent insert
  120935. */
  120936. SQLITE_API sqlite_int64 SQLITE_STDCALL sqlite3_last_insert_rowid(sqlite3 *db){
  120937. #ifdef SQLITE_ENABLE_API_ARMOR
  120938. if( !sqlite3SafetyCheckOk(db) ){
  120939. (void)SQLITE_MISUSE_BKPT;
  120940. return 0;
  120941. }
  120942. #endif
  120943. return db->lastRowid;
  120944. }
  120945. /*
  120946. ** Return the number of changes in the most recent call to sqlite3_exec().
  120947. */
  120948. SQLITE_API int SQLITE_STDCALL sqlite3_changes(sqlite3 *db){
  120949. #ifdef SQLITE_ENABLE_API_ARMOR
  120950. if( !sqlite3SafetyCheckOk(db) ){
  120951. (void)SQLITE_MISUSE_BKPT;
  120952. return 0;
  120953. }
  120954. #endif
  120955. return db->nChange;
  120956. }
  120957. /*
  120958. ** Return the number of changes since the database handle was opened.
  120959. */
  120960. SQLITE_API int SQLITE_STDCALL sqlite3_total_changes(sqlite3 *db){
  120961. #ifdef SQLITE_ENABLE_API_ARMOR
  120962. if( !sqlite3SafetyCheckOk(db) ){
  120963. (void)SQLITE_MISUSE_BKPT;
  120964. return 0;
  120965. }
  120966. #endif
  120967. return db->nTotalChange;
  120968. }
  120969. /*
  120970. ** Close all open savepoints. This function only manipulates fields of the
  120971. ** database handle object, it does not close any savepoints that may be open
  120972. ** at the b-tree/pager level.
  120973. */
  120974. SQLITE_PRIVATE void sqlite3CloseSavepoints(sqlite3 *db){
  120975. while( db->pSavepoint ){
  120976. Savepoint *pTmp = db->pSavepoint;
  120977. db->pSavepoint = pTmp->pNext;
  120978. sqlite3DbFree(db, pTmp);
  120979. }
  120980. db->nSavepoint = 0;
  120981. db->nStatement = 0;
  120982. db->isTransactionSavepoint = 0;
  120983. }
  120984. /*
  120985. ** Invoke the destructor function associated with FuncDef p, if any. Except,
  120986. ** if this is not the last copy of the function, do not invoke it. Multiple
  120987. ** copies of a single function are created when create_function() is called
  120988. ** with SQLITE_ANY as the encoding.
  120989. */
  120990. static void functionDestroy(sqlite3 *db, FuncDef *p){
  120991. FuncDestructor *pDestructor = p->pDestructor;
  120992. if( pDestructor ){
  120993. pDestructor->nRef--;
  120994. if( pDestructor->nRef==0 ){
  120995. pDestructor->xDestroy(pDestructor->pUserData);
  120996. sqlite3DbFree(db, pDestructor);
  120997. }
  120998. }
  120999. }
  121000. /*
  121001. ** Disconnect all sqlite3_vtab objects that belong to database connection
  121002. ** db. This is called when db is being closed.
  121003. */
  121004. static void disconnectAllVtab(sqlite3 *db){
  121005. #ifndef SQLITE_OMIT_VIRTUALTABLE
  121006. int i;
  121007. sqlite3BtreeEnterAll(db);
  121008. for(i=0; i<db->nDb; i++){
  121009. Schema *pSchema = db->aDb[i].pSchema;
  121010. if( db->aDb[i].pSchema ){
  121011. HashElem *p;
  121012. for(p=sqliteHashFirst(&pSchema->tblHash); p; p=sqliteHashNext(p)){
  121013. Table *pTab = (Table *)sqliteHashData(p);
  121014. if( IsVirtual(pTab) ) sqlite3VtabDisconnect(db, pTab);
  121015. }
  121016. }
  121017. }
  121018. sqlite3VtabUnlockList(db);
  121019. sqlite3BtreeLeaveAll(db);
  121020. #else
  121021. UNUSED_PARAMETER(db);
  121022. #endif
  121023. }
  121024. /*
  121025. ** Return TRUE if database connection db has unfinalized prepared
  121026. ** statements or unfinished sqlite3_backup objects.
  121027. */
  121028. static int connectionIsBusy(sqlite3 *db){
  121029. int j;
  121030. assert( sqlite3_mutex_held(db->mutex) );
  121031. if( db->pVdbe ) return 1;
  121032. for(j=0; j<db->nDb; j++){
  121033. Btree *pBt = db->aDb[j].pBt;
  121034. if( pBt && sqlite3BtreeIsInBackup(pBt) ) return 1;
  121035. }
  121036. return 0;
  121037. }
  121038. /*
  121039. ** Close an existing SQLite database
  121040. */
  121041. static int sqlite3Close(sqlite3 *db, int forceZombie){
  121042. if( !db ){
  121043. /* EVIDENCE-OF: R-63257-11740 Calling sqlite3_close() or
  121044. ** sqlite3_close_v2() with a NULL pointer argument is a harmless no-op. */
  121045. return SQLITE_OK;
  121046. }
  121047. if( !sqlite3SafetyCheckSickOrOk(db) ){
  121048. return SQLITE_MISUSE_BKPT;
  121049. }
  121050. sqlite3_mutex_enter(db->mutex);
  121051. /* Force xDisconnect calls on all virtual tables */
  121052. disconnectAllVtab(db);
  121053. /* If a transaction is open, the disconnectAllVtab() call above
  121054. ** will not have called the xDisconnect() method on any virtual
  121055. ** tables in the db->aVTrans[] array. The following sqlite3VtabRollback()
  121056. ** call will do so. We need to do this before the check for active
  121057. ** SQL statements below, as the v-table implementation may be storing
  121058. ** some prepared statements internally.
  121059. */
  121060. sqlite3VtabRollback(db);
  121061. /* Legacy behavior (sqlite3_close() behavior) is to return
  121062. ** SQLITE_BUSY if the connection can not be closed immediately.
  121063. */
  121064. if( !forceZombie && connectionIsBusy(db) ){
  121065. sqlite3ErrorWithMsg(db, SQLITE_BUSY, "unable to close due to unfinalized "
  121066. "statements or unfinished backups");
  121067. sqlite3_mutex_leave(db->mutex);
  121068. return SQLITE_BUSY;
  121069. }
  121070. #ifdef SQLITE_ENABLE_SQLLOG
  121071. if( sqlite3GlobalConfig.xSqllog ){
  121072. /* Closing the handle. Fourth parameter is passed the value 2. */
  121073. sqlite3GlobalConfig.xSqllog(sqlite3GlobalConfig.pSqllogArg, db, 0, 2);
  121074. }
  121075. #endif
  121076. /* Convert the connection into a zombie and then close it.
  121077. */
  121078. db->magic = SQLITE_MAGIC_ZOMBIE;
  121079. sqlite3LeaveMutexAndCloseZombie(db);
  121080. return SQLITE_OK;
  121081. }
  121082. /*
  121083. ** Two variations on the public interface for closing a database
  121084. ** connection. The sqlite3_close() version returns SQLITE_BUSY and
  121085. ** leaves the connection option if there are unfinalized prepared
  121086. ** statements or unfinished sqlite3_backups. The sqlite3_close_v2()
  121087. ** version forces the connection to become a zombie if there are
  121088. ** unclosed resources, and arranges for deallocation when the last
  121089. ** prepare statement or sqlite3_backup closes.
  121090. */
  121091. SQLITE_API int SQLITE_STDCALL sqlite3_close(sqlite3 *db){ return sqlite3Close(db,0); }
  121092. SQLITE_API int SQLITE_STDCALL sqlite3_close_v2(sqlite3 *db){ return sqlite3Close(db,1); }
  121093. /*
  121094. ** Close the mutex on database connection db.
  121095. **
  121096. ** Furthermore, if database connection db is a zombie (meaning that there
  121097. ** has been a prior call to sqlite3_close(db) or sqlite3_close_v2(db)) and
  121098. ** every sqlite3_stmt has now been finalized and every sqlite3_backup has
  121099. ** finished, then free all resources.
  121100. */
  121101. SQLITE_PRIVATE void sqlite3LeaveMutexAndCloseZombie(sqlite3 *db){
  121102. HashElem *i; /* Hash table iterator */
  121103. int j;
  121104. /* If there are outstanding sqlite3_stmt or sqlite3_backup objects
  121105. ** or if the connection has not yet been closed by sqlite3_close_v2(),
  121106. ** then just leave the mutex and return.
  121107. */
  121108. if( db->magic!=SQLITE_MAGIC_ZOMBIE || connectionIsBusy(db) ){
  121109. sqlite3_mutex_leave(db->mutex);
  121110. return;
  121111. }
  121112. /* If we reach this point, it means that the database connection has
  121113. ** closed all sqlite3_stmt and sqlite3_backup objects and has been
  121114. ** passed to sqlite3_close (meaning that it is a zombie). Therefore,
  121115. ** go ahead and free all resources.
  121116. */
  121117. /* If a transaction is open, roll it back. This also ensures that if
  121118. ** any database schemas have been modified by an uncommitted transaction
  121119. ** they are reset. And that the required b-tree mutex is held to make
  121120. ** the pager rollback and schema reset an atomic operation. */
  121121. sqlite3RollbackAll(db, SQLITE_OK);
  121122. /* Free any outstanding Savepoint structures. */
  121123. sqlite3CloseSavepoints(db);
  121124. /* Close all database connections */
  121125. for(j=0; j<db->nDb; j++){
  121126. struct Db *pDb = &db->aDb[j];
  121127. if( pDb->pBt ){
  121128. sqlite3BtreeClose(pDb->pBt);
  121129. pDb->pBt = 0;
  121130. if( j!=1 ){
  121131. pDb->pSchema = 0;
  121132. }
  121133. }
  121134. }
  121135. /* Clear the TEMP schema separately and last */
  121136. if( db->aDb[1].pSchema ){
  121137. sqlite3SchemaClear(db->aDb[1].pSchema);
  121138. }
  121139. sqlite3VtabUnlockList(db);
  121140. /* Free up the array of auxiliary databases */
  121141. sqlite3CollapseDatabaseArray(db);
  121142. assert( db->nDb<=2 );
  121143. assert( db->aDb==db->aDbStatic );
  121144. /* Tell the code in notify.c that the connection no longer holds any
  121145. ** locks and does not require any further unlock-notify callbacks.
  121146. */
  121147. sqlite3ConnectionClosed(db);
  121148. for(j=0; j<ArraySize(db->aFunc.a); j++){
  121149. FuncDef *pNext, *pHash, *p;
  121150. for(p=db->aFunc.a[j]; p; p=pHash){
  121151. pHash = p->pHash;
  121152. while( p ){
  121153. functionDestroy(db, p);
  121154. pNext = p->pNext;
  121155. sqlite3DbFree(db, p);
  121156. p = pNext;
  121157. }
  121158. }
  121159. }
  121160. for(i=sqliteHashFirst(&db->aCollSeq); i; i=sqliteHashNext(i)){
  121161. CollSeq *pColl = (CollSeq *)sqliteHashData(i);
  121162. /* Invoke any destructors registered for collation sequence user data. */
  121163. for(j=0; j<3; j++){
  121164. if( pColl[j].xDel ){
  121165. pColl[j].xDel(pColl[j].pUser);
  121166. }
  121167. }
  121168. sqlite3DbFree(db, pColl);
  121169. }
  121170. sqlite3HashClear(&db->aCollSeq);
  121171. #ifndef SQLITE_OMIT_VIRTUALTABLE
  121172. for(i=sqliteHashFirst(&db->aModule); i; i=sqliteHashNext(i)){
  121173. Module *pMod = (Module *)sqliteHashData(i);
  121174. if( pMod->xDestroy ){
  121175. pMod->xDestroy(pMod->pAux);
  121176. }
  121177. sqlite3DbFree(db, pMod);
  121178. }
  121179. sqlite3HashClear(&db->aModule);
  121180. #endif
  121181. sqlite3Error(db, SQLITE_OK); /* Deallocates any cached error strings. */
  121182. sqlite3ValueFree(db->pErr);
  121183. sqlite3CloseExtensions(db);
  121184. #if SQLITE_USER_AUTHENTICATION
  121185. sqlite3_free(db->auth.zAuthUser);
  121186. sqlite3_free(db->auth.zAuthPW);
  121187. #endif
  121188. db->magic = SQLITE_MAGIC_ERROR;
  121189. /* The temp-database schema is allocated differently from the other schema
  121190. ** objects (using sqliteMalloc() directly, instead of sqlite3BtreeSchema()).
  121191. ** So it needs to be freed here. Todo: Why not roll the temp schema into
  121192. ** the same sqliteMalloc() as the one that allocates the database
  121193. ** structure?
  121194. */
  121195. sqlite3DbFree(db, db->aDb[1].pSchema);
  121196. sqlite3_mutex_leave(db->mutex);
  121197. db->magic = SQLITE_MAGIC_CLOSED;
  121198. sqlite3_mutex_free(db->mutex);
  121199. assert( db->lookaside.nOut==0 ); /* Fails on a lookaside memory leak */
  121200. if( db->lookaside.bMalloced ){
  121201. sqlite3_free(db->lookaside.pStart);
  121202. }
  121203. sqlite3_free(db);
  121204. }
  121205. /*
  121206. ** Rollback all database files. If tripCode is not SQLITE_OK, then
  121207. ** any write cursors are invalidated ("tripped" - as in "tripping a circuit
  121208. ** breaker") and made to return tripCode if there are any further
  121209. ** attempts to use that cursor. Read cursors remain open and valid
  121210. ** but are "saved" in case the table pages are moved around.
  121211. */
  121212. SQLITE_PRIVATE void sqlite3RollbackAll(sqlite3 *db, int tripCode){
  121213. int i;
  121214. int inTrans = 0;
  121215. int schemaChange;
  121216. assert( sqlite3_mutex_held(db->mutex) );
  121217. sqlite3BeginBenignMalloc();
  121218. /* Obtain all b-tree mutexes before making any calls to BtreeRollback().
  121219. ** This is important in case the transaction being rolled back has
  121220. ** modified the database schema. If the b-tree mutexes are not taken
  121221. ** here, then another shared-cache connection might sneak in between
  121222. ** the database rollback and schema reset, which can cause false
  121223. ** corruption reports in some cases. */
  121224. sqlite3BtreeEnterAll(db);
  121225. schemaChange = (db->flags & SQLITE_InternChanges)!=0 && db->init.busy==0;
  121226. for(i=0; i<db->nDb; i++){
  121227. Btree *p = db->aDb[i].pBt;
  121228. if( p ){
  121229. if( sqlite3BtreeIsInTrans(p) ){
  121230. inTrans = 1;
  121231. }
  121232. sqlite3BtreeRollback(p, tripCode, !schemaChange);
  121233. }
  121234. }
  121235. sqlite3VtabRollback(db);
  121236. sqlite3EndBenignMalloc();
  121237. if( (db->flags&SQLITE_InternChanges)!=0 && db->init.busy==0 ){
  121238. sqlite3ExpirePreparedStatements(db);
  121239. sqlite3ResetAllSchemasOfConnection(db);
  121240. }
  121241. sqlite3BtreeLeaveAll(db);
  121242. /* Any deferred constraint violations have now been resolved. */
  121243. db->nDeferredCons = 0;
  121244. db->nDeferredImmCons = 0;
  121245. db->flags &= ~SQLITE_DeferFKs;
  121246. /* If one has been configured, invoke the rollback-hook callback */
  121247. if( db->xRollbackCallback && (inTrans || !db->autoCommit) ){
  121248. db->xRollbackCallback(db->pRollbackArg);
  121249. }
  121250. }
  121251. /*
  121252. ** Return a static string containing the name corresponding to the error code
  121253. ** specified in the argument.
  121254. */
  121255. #if defined(SQLITE_NEED_ERR_NAME)
  121256. SQLITE_PRIVATE const char *sqlite3ErrName(int rc){
  121257. const char *zName = 0;
  121258. int i, origRc = rc;
  121259. for(i=0; i<2 && zName==0; i++, rc &= 0xff){
  121260. switch( rc ){
  121261. case SQLITE_OK: zName = "SQLITE_OK"; break;
  121262. case SQLITE_ERROR: zName = "SQLITE_ERROR"; break;
  121263. case SQLITE_INTERNAL: zName = "SQLITE_INTERNAL"; break;
  121264. case SQLITE_PERM: zName = "SQLITE_PERM"; break;
  121265. case SQLITE_ABORT: zName = "SQLITE_ABORT"; break;
  121266. case SQLITE_ABORT_ROLLBACK: zName = "SQLITE_ABORT_ROLLBACK"; break;
  121267. case SQLITE_BUSY: zName = "SQLITE_BUSY"; break;
  121268. case SQLITE_BUSY_RECOVERY: zName = "SQLITE_BUSY_RECOVERY"; break;
  121269. case SQLITE_BUSY_SNAPSHOT: zName = "SQLITE_BUSY_SNAPSHOT"; break;
  121270. case SQLITE_LOCKED: zName = "SQLITE_LOCKED"; break;
  121271. case SQLITE_LOCKED_SHAREDCACHE: zName = "SQLITE_LOCKED_SHAREDCACHE";break;
  121272. case SQLITE_NOMEM: zName = "SQLITE_NOMEM"; break;
  121273. case SQLITE_READONLY: zName = "SQLITE_READONLY"; break;
  121274. case SQLITE_READONLY_RECOVERY: zName = "SQLITE_READONLY_RECOVERY"; break;
  121275. case SQLITE_READONLY_CANTLOCK: zName = "SQLITE_READONLY_CANTLOCK"; break;
  121276. case SQLITE_READONLY_ROLLBACK: zName = "SQLITE_READONLY_ROLLBACK"; break;
  121277. case SQLITE_READONLY_DBMOVED: zName = "SQLITE_READONLY_DBMOVED"; break;
  121278. case SQLITE_INTERRUPT: zName = "SQLITE_INTERRUPT"; break;
  121279. case SQLITE_IOERR: zName = "SQLITE_IOERR"; break;
  121280. case SQLITE_IOERR_READ: zName = "SQLITE_IOERR_READ"; break;
  121281. case SQLITE_IOERR_SHORT_READ: zName = "SQLITE_IOERR_SHORT_READ"; break;
  121282. case SQLITE_IOERR_WRITE: zName = "SQLITE_IOERR_WRITE"; break;
  121283. case SQLITE_IOERR_FSYNC: zName = "SQLITE_IOERR_FSYNC"; break;
  121284. case SQLITE_IOERR_DIR_FSYNC: zName = "SQLITE_IOERR_DIR_FSYNC"; break;
  121285. case SQLITE_IOERR_TRUNCATE: zName = "SQLITE_IOERR_TRUNCATE"; break;
  121286. case SQLITE_IOERR_FSTAT: zName = "SQLITE_IOERR_FSTAT"; break;
  121287. case SQLITE_IOERR_UNLOCK: zName = "SQLITE_IOERR_UNLOCK"; break;
  121288. case SQLITE_IOERR_RDLOCK: zName = "SQLITE_IOERR_RDLOCK"; break;
  121289. case SQLITE_IOERR_DELETE: zName = "SQLITE_IOERR_DELETE"; break;
  121290. case SQLITE_IOERR_NOMEM: zName = "SQLITE_IOERR_NOMEM"; break;
  121291. case SQLITE_IOERR_ACCESS: zName = "SQLITE_IOERR_ACCESS"; break;
  121292. case SQLITE_IOERR_CHECKRESERVEDLOCK:
  121293. zName = "SQLITE_IOERR_CHECKRESERVEDLOCK"; break;
  121294. case SQLITE_IOERR_LOCK: zName = "SQLITE_IOERR_LOCK"; break;
  121295. case SQLITE_IOERR_CLOSE: zName = "SQLITE_IOERR_CLOSE"; break;
  121296. case SQLITE_IOERR_DIR_CLOSE: zName = "SQLITE_IOERR_DIR_CLOSE"; break;
  121297. case SQLITE_IOERR_SHMOPEN: zName = "SQLITE_IOERR_SHMOPEN"; break;
  121298. case SQLITE_IOERR_SHMSIZE: zName = "SQLITE_IOERR_SHMSIZE"; break;
  121299. case SQLITE_IOERR_SHMLOCK: zName = "SQLITE_IOERR_SHMLOCK"; break;
  121300. case SQLITE_IOERR_SHMMAP: zName = "SQLITE_IOERR_SHMMAP"; break;
  121301. case SQLITE_IOERR_SEEK: zName = "SQLITE_IOERR_SEEK"; break;
  121302. case SQLITE_IOERR_DELETE_NOENT: zName = "SQLITE_IOERR_DELETE_NOENT";break;
  121303. case SQLITE_IOERR_MMAP: zName = "SQLITE_IOERR_MMAP"; break;
  121304. case SQLITE_IOERR_GETTEMPPATH: zName = "SQLITE_IOERR_GETTEMPPATH"; break;
  121305. case SQLITE_IOERR_CONVPATH: zName = "SQLITE_IOERR_CONVPATH"; break;
  121306. case SQLITE_CORRUPT: zName = "SQLITE_CORRUPT"; break;
  121307. case SQLITE_CORRUPT_VTAB: zName = "SQLITE_CORRUPT_VTAB"; break;
  121308. case SQLITE_NOTFOUND: zName = "SQLITE_NOTFOUND"; break;
  121309. case SQLITE_FULL: zName = "SQLITE_FULL"; break;
  121310. case SQLITE_CANTOPEN: zName = "SQLITE_CANTOPEN"; break;
  121311. case SQLITE_CANTOPEN_NOTEMPDIR: zName = "SQLITE_CANTOPEN_NOTEMPDIR";break;
  121312. case SQLITE_CANTOPEN_ISDIR: zName = "SQLITE_CANTOPEN_ISDIR"; break;
  121313. case SQLITE_CANTOPEN_FULLPATH: zName = "SQLITE_CANTOPEN_FULLPATH"; break;
  121314. case SQLITE_CANTOPEN_CONVPATH: zName = "SQLITE_CANTOPEN_CONVPATH"; break;
  121315. case SQLITE_PROTOCOL: zName = "SQLITE_PROTOCOL"; break;
  121316. case SQLITE_EMPTY: zName = "SQLITE_EMPTY"; break;
  121317. case SQLITE_SCHEMA: zName = "SQLITE_SCHEMA"; break;
  121318. case SQLITE_TOOBIG: zName = "SQLITE_TOOBIG"; break;
  121319. case SQLITE_CONSTRAINT: zName = "SQLITE_CONSTRAINT"; break;
  121320. case SQLITE_CONSTRAINT_UNIQUE: zName = "SQLITE_CONSTRAINT_UNIQUE"; break;
  121321. case SQLITE_CONSTRAINT_TRIGGER: zName = "SQLITE_CONSTRAINT_TRIGGER";break;
  121322. case SQLITE_CONSTRAINT_FOREIGNKEY:
  121323. zName = "SQLITE_CONSTRAINT_FOREIGNKEY"; break;
  121324. case SQLITE_CONSTRAINT_CHECK: zName = "SQLITE_CONSTRAINT_CHECK"; break;
  121325. case SQLITE_CONSTRAINT_PRIMARYKEY:
  121326. zName = "SQLITE_CONSTRAINT_PRIMARYKEY"; break;
  121327. case SQLITE_CONSTRAINT_NOTNULL: zName = "SQLITE_CONSTRAINT_NOTNULL";break;
  121328. case SQLITE_CONSTRAINT_COMMITHOOK:
  121329. zName = "SQLITE_CONSTRAINT_COMMITHOOK"; break;
  121330. case SQLITE_CONSTRAINT_VTAB: zName = "SQLITE_CONSTRAINT_VTAB"; break;
  121331. case SQLITE_CONSTRAINT_FUNCTION:
  121332. zName = "SQLITE_CONSTRAINT_FUNCTION"; break;
  121333. case SQLITE_CONSTRAINT_ROWID: zName = "SQLITE_CONSTRAINT_ROWID"; break;
  121334. case SQLITE_MISMATCH: zName = "SQLITE_MISMATCH"; break;
  121335. case SQLITE_MISUSE: zName = "SQLITE_MISUSE"; break;
  121336. case SQLITE_NOLFS: zName = "SQLITE_NOLFS"; break;
  121337. case SQLITE_AUTH: zName = "SQLITE_AUTH"; break;
  121338. case SQLITE_FORMAT: zName = "SQLITE_FORMAT"; break;
  121339. case SQLITE_RANGE: zName = "SQLITE_RANGE"; break;
  121340. case SQLITE_NOTADB: zName = "SQLITE_NOTADB"; break;
  121341. case SQLITE_ROW: zName = "SQLITE_ROW"; break;
  121342. case SQLITE_NOTICE: zName = "SQLITE_NOTICE"; break;
  121343. case SQLITE_NOTICE_RECOVER_WAL: zName = "SQLITE_NOTICE_RECOVER_WAL";break;
  121344. case SQLITE_NOTICE_RECOVER_ROLLBACK:
  121345. zName = "SQLITE_NOTICE_RECOVER_ROLLBACK"; break;
  121346. case SQLITE_WARNING: zName = "SQLITE_WARNING"; break;
  121347. case SQLITE_WARNING_AUTOINDEX: zName = "SQLITE_WARNING_AUTOINDEX"; break;
  121348. case SQLITE_DONE: zName = "SQLITE_DONE"; break;
  121349. }
  121350. }
  121351. if( zName==0 ){
  121352. static char zBuf[50];
  121353. sqlite3_snprintf(sizeof(zBuf), zBuf, "SQLITE_UNKNOWN(%d)", origRc);
  121354. zName = zBuf;
  121355. }
  121356. return zName;
  121357. }
  121358. #endif
  121359. /*
  121360. ** Return a static string that describes the kind of error specified in the
  121361. ** argument.
  121362. */
  121363. SQLITE_PRIVATE const char *sqlite3ErrStr(int rc){
  121364. static const char* const aMsg[] = {
  121365. /* SQLITE_OK */ "not an error",
  121366. /* SQLITE_ERROR */ "SQL logic error or missing database",
  121367. /* SQLITE_INTERNAL */ 0,
  121368. /* SQLITE_PERM */ "access permission denied",
  121369. /* SQLITE_ABORT */ "callback requested query abort",
  121370. /* SQLITE_BUSY */ "database is locked",
  121371. /* SQLITE_LOCKED */ "database table is locked",
  121372. /* SQLITE_NOMEM */ "out of memory",
  121373. /* SQLITE_READONLY */ "attempt to write a readonly database",
  121374. /* SQLITE_INTERRUPT */ "interrupted",
  121375. /* SQLITE_IOERR */ "disk I/O error",
  121376. /* SQLITE_CORRUPT */ "database disk image is malformed",
  121377. /* SQLITE_NOTFOUND */ "unknown operation",
  121378. /* SQLITE_FULL */ "database or disk is full",
  121379. /* SQLITE_CANTOPEN */ "unable to open database file",
  121380. /* SQLITE_PROTOCOL */ "locking protocol",
  121381. /* SQLITE_EMPTY */ "table contains no data",
  121382. /* SQLITE_SCHEMA */ "database schema has changed",
  121383. /* SQLITE_TOOBIG */ "string or blob too big",
  121384. /* SQLITE_CONSTRAINT */ "constraint failed",
  121385. /* SQLITE_MISMATCH */ "datatype mismatch",
  121386. /* SQLITE_MISUSE */ "library routine called out of sequence",
  121387. /* SQLITE_NOLFS */ "large file support is disabled",
  121388. /* SQLITE_AUTH */ "authorization denied",
  121389. /* SQLITE_FORMAT */ "auxiliary database format error",
  121390. /* SQLITE_RANGE */ "bind or column index out of range",
  121391. /* SQLITE_NOTADB */ "file is encrypted or is not a database",
  121392. };
  121393. const char *zErr = "unknown error";
  121394. switch( rc ){
  121395. case SQLITE_ABORT_ROLLBACK: {
  121396. zErr = "abort due to ROLLBACK";
  121397. break;
  121398. }
  121399. default: {
  121400. rc &= 0xff;
  121401. if( ALWAYS(rc>=0) && rc<ArraySize(aMsg) && aMsg[rc]!=0 ){
  121402. zErr = aMsg[rc];
  121403. }
  121404. break;
  121405. }
  121406. }
  121407. return zErr;
  121408. }
  121409. /*
  121410. ** This routine implements a busy callback that sleeps and tries
  121411. ** again until a timeout value is reached. The timeout value is
  121412. ** an integer number of milliseconds passed in as the first
  121413. ** argument.
  121414. */
  121415. static int sqliteDefaultBusyCallback(
  121416. void *ptr, /* Database connection */
  121417. int count /* Number of times table has been busy */
  121418. ){
  121419. #if SQLITE_OS_WIN || HAVE_USLEEP
  121420. static const u8 delays[] =
  121421. { 1, 2, 5, 10, 15, 20, 25, 25, 25, 50, 50, 100 };
  121422. static const u8 totals[] =
  121423. { 0, 1, 3, 8, 18, 33, 53, 78, 103, 128, 178, 228 };
  121424. # define NDELAY ArraySize(delays)
  121425. sqlite3 *db = (sqlite3 *)ptr;
  121426. int timeout = db->busyTimeout;
  121427. int delay, prior;
  121428. assert( count>=0 );
  121429. if( count < NDELAY ){
  121430. delay = delays[count];
  121431. prior = totals[count];
  121432. }else{
  121433. delay = delays[NDELAY-1];
  121434. prior = totals[NDELAY-1] + delay*(count-(NDELAY-1));
  121435. }
  121436. if( prior + delay > timeout ){
  121437. delay = timeout - prior;
  121438. if( delay<=0 ) return 0;
  121439. }
  121440. sqlite3OsSleep(db->pVfs, delay*1000);
  121441. return 1;
  121442. #else
  121443. sqlite3 *db = (sqlite3 *)ptr;
  121444. int timeout = ((sqlite3 *)ptr)->busyTimeout;
  121445. if( (count+1)*1000 > timeout ){
  121446. return 0;
  121447. }
  121448. sqlite3OsSleep(db->pVfs, 1000000);
  121449. return 1;
  121450. #endif
  121451. }
  121452. /*
  121453. ** Invoke the given busy handler.
  121454. **
  121455. ** This routine is called when an operation failed with a lock.
  121456. ** If this routine returns non-zero, the lock is retried. If it
  121457. ** returns 0, the operation aborts with an SQLITE_BUSY error.
  121458. */
  121459. SQLITE_PRIVATE int sqlite3InvokeBusyHandler(BusyHandler *p){
  121460. int rc;
  121461. if( NEVER(p==0) || p->xFunc==0 || p->nBusy<0 ) return 0;
  121462. rc = p->xFunc(p->pArg, p->nBusy);
  121463. if( rc==0 ){
  121464. p->nBusy = -1;
  121465. }else{
  121466. p->nBusy++;
  121467. }
  121468. return rc;
  121469. }
  121470. /*
  121471. ** This routine sets the busy callback for an Sqlite database to the
  121472. ** given callback function with the given argument.
  121473. */
  121474. SQLITE_API int SQLITE_STDCALL sqlite3_busy_handler(
  121475. sqlite3 *db,
  121476. int (*xBusy)(void*,int),
  121477. void *pArg
  121478. ){
  121479. #ifdef SQLITE_ENABLE_API_ARMOR
  121480. if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
  121481. #endif
  121482. sqlite3_mutex_enter(db->mutex);
  121483. db->busyHandler.xFunc = xBusy;
  121484. db->busyHandler.pArg = pArg;
  121485. db->busyHandler.nBusy = 0;
  121486. db->busyTimeout = 0;
  121487. sqlite3_mutex_leave(db->mutex);
  121488. return SQLITE_OK;
  121489. }
  121490. #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
  121491. /*
  121492. ** This routine sets the progress callback for an Sqlite database to the
  121493. ** given callback function with the given argument. The progress callback will
  121494. ** be invoked every nOps opcodes.
  121495. */
  121496. SQLITE_API void SQLITE_STDCALL sqlite3_progress_handler(
  121497. sqlite3 *db,
  121498. int nOps,
  121499. int (*xProgress)(void*),
  121500. void *pArg
  121501. ){
  121502. #ifdef SQLITE_ENABLE_API_ARMOR
  121503. if( !sqlite3SafetyCheckOk(db) ){
  121504. (void)SQLITE_MISUSE_BKPT;
  121505. return;
  121506. }
  121507. #endif
  121508. sqlite3_mutex_enter(db->mutex);
  121509. if( nOps>0 ){
  121510. db->xProgress = xProgress;
  121511. db->nProgressOps = (unsigned)nOps;
  121512. db->pProgressArg = pArg;
  121513. }else{
  121514. db->xProgress = 0;
  121515. db->nProgressOps = 0;
  121516. db->pProgressArg = 0;
  121517. }
  121518. sqlite3_mutex_leave(db->mutex);
  121519. }
  121520. #endif
  121521. /*
  121522. ** This routine installs a default busy handler that waits for the
  121523. ** specified number of milliseconds before returning 0.
  121524. */
  121525. SQLITE_API int SQLITE_STDCALL sqlite3_busy_timeout(sqlite3 *db, int ms){
  121526. #ifdef SQLITE_ENABLE_API_ARMOR
  121527. if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
  121528. #endif
  121529. if( ms>0 ){
  121530. sqlite3_busy_handler(db, sqliteDefaultBusyCallback, (void*)db);
  121531. db->busyTimeout = ms;
  121532. }else{
  121533. sqlite3_busy_handler(db, 0, 0);
  121534. }
  121535. return SQLITE_OK;
  121536. }
  121537. /*
  121538. ** Cause any pending operation to stop at its earliest opportunity.
  121539. */
  121540. SQLITE_API void SQLITE_STDCALL sqlite3_interrupt(sqlite3 *db){
  121541. #ifdef SQLITE_ENABLE_API_ARMOR
  121542. if( !sqlite3SafetyCheckOk(db) ){
  121543. (void)SQLITE_MISUSE_BKPT;
  121544. return;
  121545. }
  121546. #endif
  121547. db->u1.isInterrupted = 1;
  121548. }
  121549. /*
  121550. ** This function is exactly the same as sqlite3_create_function(), except
  121551. ** that it is designed to be called by internal code. The difference is
  121552. ** that if a malloc() fails in sqlite3_create_function(), an error code
  121553. ** is returned and the mallocFailed flag cleared.
  121554. */
  121555. SQLITE_PRIVATE int sqlite3CreateFunc(
  121556. sqlite3 *db,
  121557. const char *zFunctionName,
  121558. int nArg,
  121559. int enc,
  121560. void *pUserData,
  121561. void (*xFunc)(sqlite3_context*,int,sqlite3_value **),
  121562. void (*xStep)(sqlite3_context*,int,sqlite3_value **),
  121563. void (*xFinal)(sqlite3_context*),
  121564. FuncDestructor *pDestructor
  121565. ){
  121566. FuncDef *p;
  121567. int nName;
  121568. int extraFlags;
  121569. assert( sqlite3_mutex_held(db->mutex) );
  121570. if( zFunctionName==0 ||
  121571. (xFunc && (xFinal || xStep)) ||
  121572. (!xFunc && (xFinal && !xStep)) ||
  121573. (!xFunc && (!xFinal && xStep)) ||
  121574. (nArg<-1 || nArg>SQLITE_MAX_FUNCTION_ARG) ||
  121575. (255<(nName = sqlite3Strlen30( zFunctionName))) ){
  121576. return SQLITE_MISUSE_BKPT;
  121577. }
  121578. assert( SQLITE_FUNC_CONSTANT==SQLITE_DETERMINISTIC );
  121579. extraFlags = enc & SQLITE_DETERMINISTIC;
  121580. enc &= (SQLITE_FUNC_ENCMASK|SQLITE_ANY);
  121581. #ifndef SQLITE_OMIT_UTF16
  121582. /* If SQLITE_UTF16 is specified as the encoding type, transform this
  121583. ** to one of SQLITE_UTF16LE or SQLITE_UTF16BE using the
  121584. ** SQLITE_UTF16NATIVE macro. SQLITE_UTF16 is not used internally.
  121585. **
  121586. ** If SQLITE_ANY is specified, add three versions of the function
  121587. ** to the hash table.
  121588. */
  121589. if( enc==SQLITE_UTF16 ){
  121590. enc = SQLITE_UTF16NATIVE;
  121591. }else if( enc==SQLITE_ANY ){
  121592. int rc;
  121593. rc = sqlite3CreateFunc(db, zFunctionName, nArg, SQLITE_UTF8|extraFlags,
  121594. pUserData, xFunc, xStep, xFinal, pDestructor);
  121595. if( rc==SQLITE_OK ){
  121596. rc = sqlite3CreateFunc(db, zFunctionName, nArg, SQLITE_UTF16LE|extraFlags,
  121597. pUserData, xFunc, xStep, xFinal, pDestructor);
  121598. }
  121599. if( rc!=SQLITE_OK ){
  121600. return rc;
  121601. }
  121602. enc = SQLITE_UTF16BE;
  121603. }
  121604. #else
  121605. enc = SQLITE_UTF8;
  121606. #endif
  121607. /* Check if an existing function is being overridden or deleted. If so,
  121608. ** and there are active VMs, then return SQLITE_BUSY. If a function
  121609. ** is being overridden/deleted but there are no active VMs, allow the
  121610. ** operation to continue but invalidate all precompiled statements.
  121611. */
  121612. p = sqlite3FindFunction(db, zFunctionName, nName, nArg, (u8)enc, 0);
  121613. if( p && (p->funcFlags & SQLITE_FUNC_ENCMASK)==enc && p->nArg==nArg ){
  121614. if( db->nVdbeActive ){
  121615. sqlite3ErrorWithMsg(db, SQLITE_BUSY,
  121616. "unable to delete/modify user-function due to active statements");
  121617. assert( !db->mallocFailed );
  121618. return SQLITE_BUSY;
  121619. }else{
  121620. sqlite3ExpirePreparedStatements(db);
  121621. }
  121622. }
  121623. p = sqlite3FindFunction(db, zFunctionName, nName, nArg, (u8)enc, 1);
  121624. assert(p || db->mallocFailed);
  121625. if( !p ){
  121626. return SQLITE_NOMEM;
  121627. }
  121628. /* If an older version of the function with a configured destructor is
  121629. ** being replaced invoke the destructor function here. */
  121630. functionDestroy(db, p);
  121631. if( pDestructor ){
  121632. pDestructor->nRef++;
  121633. }
  121634. p->pDestructor = pDestructor;
  121635. p->funcFlags = (p->funcFlags & SQLITE_FUNC_ENCMASK) | extraFlags;
  121636. testcase( p->funcFlags & SQLITE_DETERMINISTIC );
  121637. p->xFunc = xFunc;
  121638. p->xStep = xStep;
  121639. p->xFinalize = xFinal;
  121640. p->pUserData = pUserData;
  121641. p->nArg = (u16)nArg;
  121642. return SQLITE_OK;
  121643. }
  121644. /*
  121645. ** Create new user functions.
  121646. */
  121647. SQLITE_API int SQLITE_STDCALL sqlite3_create_function(
  121648. sqlite3 *db,
  121649. const char *zFunc,
  121650. int nArg,
  121651. int enc,
  121652. void *p,
  121653. void (*xFunc)(sqlite3_context*,int,sqlite3_value **),
  121654. void (*xStep)(sqlite3_context*,int,sqlite3_value **),
  121655. void (*xFinal)(sqlite3_context*)
  121656. ){
  121657. return sqlite3_create_function_v2(db, zFunc, nArg, enc, p, xFunc, xStep,
  121658. xFinal, 0);
  121659. }
  121660. SQLITE_API int SQLITE_STDCALL sqlite3_create_function_v2(
  121661. sqlite3 *db,
  121662. const char *zFunc,
  121663. int nArg,
  121664. int enc,
  121665. void *p,
  121666. void (*xFunc)(sqlite3_context*,int,sqlite3_value **),
  121667. void (*xStep)(sqlite3_context*,int,sqlite3_value **),
  121668. void (*xFinal)(sqlite3_context*),
  121669. void (*xDestroy)(void *)
  121670. ){
  121671. int rc = SQLITE_ERROR;
  121672. FuncDestructor *pArg = 0;
  121673. #ifdef SQLITE_ENABLE_API_ARMOR
  121674. if( !sqlite3SafetyCheckOk(db) ){
  121675. return SQLITE_MISUSE_BKPT;
  121676. }
  121677. #endif
  121678. sqlite3_mutex_enter(db->mutex);
  121679. if( xDestroy ){
  121680. pArg = (FuncDestructor *)sqlite3DbMallocZero(db, sizeof(FuncDestructor));
  121681. if( !pArg ){
  121682. xDestroy(p);
  121683. goto out;
  121684. }
  121685. pArg->xDestroy = xDestroy;
  121686. pArg->pUserData = p;
  121687. }
  121688. rc = sqlite3CreateFunc(db, zFunc, nArg, enc, p, xFunc, xStep, xFinal, pArg);
  121689. if( pArg && pArg->nRef==0 ){
  121690. assert( rc!=SQLITE_OK );
  121691. xDestroy(p);
  121692. sqlite3DbFree(db, pArg);
  121693. }
  121694. out:
  121695. rc = sqlite3ApiExit(db, rc);
  121696. sqlite3_mutex_leave(db->mutex);
  121697. return rc;
  121698. }
  121699. #ifndef SQLITE_OMIT_UTF16
  121700. SQLITE_API int SQLITE_STDCALL sqlite3_create_function16(
  121701. sqlite3 *db,
  121702. const void *zFunctionName,
  121703. int nArg,
  121704. int eTextRep,
  121705. void *p,
  121706. void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
  121707. void (*xStep)(sqlite3_context*,int,sqlite3_value**),
  121708. void (*xFinal)(sqlite3_context*)
  121709. ){
  121710. int rc;
  121711. char *zFunc8;
  121712. #ifdef SQLITE_ENABLE_API_ARMOR
  121713. if( !sqlite3SafetyCheckOk(db) || zFunctionName==0 ) return SQLITE_MISUSE_BKPT;
  121714. #endif
  121715. sqlite3_mutex_enter(db->mutex);
  121716. assert( !db->mallocFailed );
  121717. zFunc8 = sqlite3Utf16to8(db, zFunctionName, -1, SQLITE_UTF16NATIVE);
  121718. rc = sqlite3CreateFunc(db, zFunc8, nArg, eTextRep, p, xFunc, xStep, xFinal,0);
  121719. sqlite3DbFree(db, zFunc8);
  121720. rc = sqlite3ApiExit(db, rc);
  121721. sqlite3_mutex_leave(db->mutex);
  121722. return rc;
  121723. }
  121724. #endif
  121725. /*
  121726. ** Declare that a function has been overloaded by a virtual table.
  121727. **
  121728. ** If the function already exists as a regular global function, then
  121729. ** this routine is a no-op. If the function does not exist, then create
  121730. ** a new one that always throws a run-time error.
  121731. **
  121732. ** When virtual tables intend to provide an overloaded function, they
  121733. ** should call this routine to make sure the global function exists.
  121734. ** A global function must exist in order for name resolution to work
  121735. ** properly.
  121736. */
  121737. SQLITE_API int SQLITE_STDCALL sqlite3_overload_function(
  121738. sqlite3 *db,
  121739. const char *zName,
  121740. int nArg
  121741. ){
  121742. int nName = sqlite3Strlen30(zName);
  121743. int rc = SQLITE_OK;
  121744. #ifdef SQLITE_ENABLE_API_ARMOR
  121745. if( !sqlite3SafetyCheckOk(db) || zName==0 || nArg<-2 ){
  121746. return SQLITE_MISUSE_BKPT;
  121747. }
  121748. #endif
  121749. sqlite3_mutex_enter(db->mutex);
  121750. if( sqlite3FindFunction(db, zName, nName, nArg, SQLITE_UTF8, 0)==0 ){
  121751. rc = sqlite3CreateFunc(db, zName, nArg, SQLITE_UTF8,
  121752. 0, sqlite3InvalidFunction, 0, 0, 0);
  121753. }
  121754. rc = sqlite3ApiExit(db, rc);
  121755. sqlite3_mutex_leave(db->mutex);
  121756. return rc;
  121757. }
  121758. #ifndef SQLITE_OMIT_TRACE
  121759. /*
  121760. ** Register a trace function. The pArg from the previously registered trace
  121761. ** is returned.
  121762. **
  121763. ** A NULL trace function means that no tracing is executes. A non-NULL
  121764. ** trace is a pointer to a function that is invoked at the start of each
  121765. ** SQL statement.
  121766. */
  121767. SQLITE_API void *SQLITE_STDCALL sqlite3_trace(sqlite3 *db, void (*xTrace)(void*,const char*), void *pArg){
  121768. void *pOld;
  121769. #ifdef SQLITE_ENABLE_API_ARMOR
  121770. if( !sqlite3SafetyCheckOk(db) ){
  121771. (void)SQLITE_MISUSE_BKPT;
  121772. return 0;
  121773. }
  121774. #endif
  121775. sqlite3_mutex_enter(db->mutex);
  121776. pOld = db->pTraceArg;
  121777. db->xTrace = xTrace;
  121778. db->pTraceArg = pArg;
  121779. sqlite3_mutex_leave(db->mutex);
  121780. return pOld;
  121781. }
  121782. /*
  121783. ** Register a profile function. The pArg from the previously registered
  121784. ** profile function is returned.
  121785. **
  121786. ** A NULL profile function means that no profiling is executes. A non-NULL
  121787. ** profile is a pointer to a function that is invoked at the conclusion of
  121788. ** each SQL statement that is run.
  121789. */
  121790. SQLITE_API void *SQLITE_STDCALL sqlite3_profile(
  121791. sqlite3 *db,
  121792. void (*xProfile)(void*,const char*,sqlite_uint64),
  121793. void *pArg
  121794. ){
  121795. void *pOld;
  121796. #ifdef SQLITE_ENABLE_API_ARMOR
  121797. if( !sqlite3SafetyCheckOk(db) ){
  121798. (void)SQLITE_MISUSE_BKPT;
  121799. return 0;
  121800. }
  121801. #endif
  121802. sqlite3_mutex_enter(db->mutex);
  121803. pOld = db->pProfileArg;
  121804. db->xProfile = xProfile;
  121805. db->pProfileArg = pArg;
  121806. sqlite3_mutex_leave(db->mutex);
  121807. return pOld;
  121808. }
  121809. #endif /* SQLITE_OMIT_TRACE */
  121810. /*
  121811. ** Register a function to be invoked when a transaction commits.
  121812. ** If the invoked function returns non-zero, then the commit becomes a
  121813. ** rollback.
  121814. */
  121815. SQLITE_API void *SQLITE_STDCALL sqlite3_commit_hook(
  121816. sqlite3 *db, /* Attach the hook to this database */
  121817. int (*xCallback)(void*), /* Function to invoke on each commit */
  121818. void *pArg /* Argument to the function */
  121819. ){
  121820. void *pOld;
  121821. #ifdef SQLITE_ENABLE_API_ARMOR
  121822. if( !sqlite3SafetyCheckOk(db) ){
  121823. (void)SQLITE_MISUSE_BKPT;
  121824. return 0;
  121825. }
  121826. #endif
  121827. sqlite3_mutex_enter(db->mutex);
  121828. pOld = db->pCommitArg;
  121829. db->xCommitCallback = xCallback;
  121830. db->pCommitArg = pArg;
  121831. sqlite3_mutex_leave(db->mutex);
  121832. return pOld;
  121833. }
  121834. /*
  121835. ** Register a callback to be invoked each time a row is updated,
  121836. ** inserted or deleted using this database connection.
  121837. */
  121838. SQLITE_API void *SQLITE_STDCALL sqlite3_update_hook(
  121839. sqlite3 *db, /* Attach the hook to this database */
  121840. void (*xCallback)(void*,int,char const *,char const *,sqlite_int64),
  121841. void *pArg /* Argument to the function */
  121842. ){
  121843. void *pRet;
  121844. #ifdef SQLITE_ENABLE_API_ARMOR
  121845. if( !sqlite3SafetyCheckOk(db) ){
  121846. (void)SQLITE_MISUSE_BKPT;
  121847. return 0;
  121848. }
  121849. #endif
  121850. sqlite3_mutex_enter(db->mutex);
  121851. pRet = db->pUpdateArg;
  121852. db->xUpdateCallback = xCallback;
  121853. db->pUpdateArg = pArg;
  121854. sqlite3_mutex_leave(db->mutex);
  121855. return pRet;
  121856. }
  121857. /*
  121858. ** Register a callback to be invoked each time a transaction is rolled
  121859. ** back by this database connection.
  121860. */
  121861. SQLITE_API void *SQLITE_STDCALL sqlite3_rollback_hook(
  121862. sqlite3 *db, /* Attach the hook to this database */
  121863. void (*xCallback)(void*), /* Callback function */
  121864. void *pArg /* Argument to the function */
  121865. ){
  121866. void *pRet;
  121867. #ifdef SQLITE_ENABLE_API_ARMOR
  121868. if( !sqlite3SafetyCheckOk(db) ){
  121869. (void)SQLITE_MISUSE_BKPT;
  121870. return 0;
  121871. }
  121872. #endif
  121873. sqlite3_mutex_enter(db->mutex);
  121874. pRet = db->pRollbackArg;
  121875. db->xRollbackCallback = xCallback;
  121876. db->pRollbackArg = pArg;
  121877. sqlite3_mutex_leave(db->mutex);
  121878. return pRet;
  121879. }
  121880. #ifndef SQLITE_OMIT_WAL
  121881. /*
  121882. ** The sqlite3_wal_hook() callback registered by sqlite3_wal_autocheckpoint().
  121883. ** Invoke sqlite3_wal_checkpoint if the number of frames in the log file
  121884. ** is greater than sqlite3.pWalArg cast to an integer (the value configured by
  121885. ** wal_autocheckpoint()).
  121886. */
  121887. SQLITE_PRIVATE int sqlite3WalDefaultHook(
  121888. void *pClientData, /* Argument */
  121889. sqlite3 *db, /* Connection */
  121890. const char *zDb, /* Database */
  121891. int nFrame /* Size of WAL */
  121892. ){
  121893. if( nFrame>=SQLITE_PTR_TO_INT(pClientData) ){
  121894. sqlite3BeginBenignMalloc();
  121895. sqlite3_wal_checkpoint(db, zDb);
  121896. sqlite3EndBenignMalloc();
  121897. }
  121898. return SQLITE_OK;
  121899. }
  121900. #endif /* SQLITE_OMIT_WAL */
  121901. /*
  121902. ** Configure an sqlite3_wal_hook() callback to automatically checkpoint
  121903. ** a database after committing a transaction if there are nFrame or
  121904. ** more frames in the log file. Passing zero or a negative value as the
  121905. ** nFrame parameter disables automatic checkpoints entirely.
  121906. **
  121907. ** The callback registered by this function replaces any existing callback
  121908. ** registered using sqlite3_wal_hook(). Likewise, registering a callback
  121909. ** using sqlite3_wal_hook() disables the automatic checkpoint mechanism
  121910. ** configured by this function.
  121911. */
  121912. SQLITE_API int SQLITE_STDCALL sqlite3_wal_autocheckpoint(sqlite3 *db, int nFrame){
  121913. #ifdef SQLITE_OMIT_WAL
  121914. UNUSED_PARAMETER(db);
  121915. UNUSED_PARAMETER(nFrame);
  121916. #else
  121917. #ifdef SQLITE_ENABLE_API_ARMOR
  121918. if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
  121919. #endif
  121920. if( nFrame>0 ){
  121921. sqlite3_wal_hook(db, sqlite3WalDefaultHook, SQLITE_INT_TO_PTR(nFrame));
  121922. }else{
  121923. sqlite3_wal_hook(db, 0, 0);
  121924. }
  121925. #endif
  121926. return SQLITE_OK;
  121927. }
  121928. /*
  121929. ** Register a callback to be invoked each time a transaction is written
  121930. ** into the write-ahead-log by this database connection.
  121931. */
  121932. SQLITE_API void *SQLITE_STDCALL sqlite3_wal_hook(
  121933. sqlite3 *db, /* Attach the hook to this db handle */
  121934. int(*xCallback)(void *, sqlite3*, const char*, int),
  121935. void *pArg /* First argument passed to xCallback() */
  121936. ){
  121937. #ifndef SQLITE_OMIT_WAL
  121938. void *pRet;
  121939. #ifdef SQLITE_ENABLE_API_ARMOR
  121940. if( !sqlite3SafetyCheckOk(db) ){
  121941. (void)SQLITE_MISUSE_BKPT;
  121942. return 0;
  121943. }
  121944. #endif
  121945. sqlite3_mutex_enter(db->mutex);
  121946. pRet = db->pWalArg;
  121947. db->xWalCallback = xCallback;
  121948. db->pWalArg = pArg;
  121949. sqlite3_mutex_leave(db->mutex);
  121950. return pRet;
  121951. #else
  121952. return 0;
  121953. #endif
  121954. }
  121955. /*
  121956. ** Checkpoint database zDb.
  121957. */
  121958. SQLITE_API int SQLITE_STDCALL sqlite3_wal_checkpoint_v2(
  121959. sqlite3 *db, /* Database handle */
  121960. const char *zDb, /* Name of attached database (or NULL) */
  121961. int eMode, /* SQLITE_CHECKPOINT_* value */
  121962. int *pnLog, /* OUT: Size of WAL log in frames */
  121963. int *pnCkpt /* OUT: Total number of frames checkpointed */
  121964. ){
  121965. #ifdef SQLITE_OMIT_WAL
  121966. return SQLITE_OK;
  121967. #else
  121968. int rc; /* Return code */
  121969. int iDb = SQLITE_MAX_ATTACHED; /* sqlite3.aDb[] index of db to checkpoint */
  121970. #ifdef SQLITE_ENABLE_API_ARMOR
  121971. if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
  121972. #endif
  121973. /* Initialize the output variables to -1 in case an error occurs. */
  121974. if( pnLog ) *pnLog = -1;
  121975. if( pnCkpt ) *pnCkpt = -1;
  121976. assert( SQLITE_CHECKPOINT_PASSIVE==0 );
  121977. assert( SQLITE_CHECKPOINT_FULL==1 );
  121978. assert( SQLITE_CHECKPOINT_RESTART==2 );
  121979. assert( SQLITE_CHECKPOINT_TRUNCATE==3 );
  121980. if( eMode<SQLITE_CHECKPOINT_PASSIVE || eMode>SQLITE_CHECKPOINT_TRUNCATE ){
  121981. /* EVIDENCE-OF: R-03996-12088 The M parameter must be a valid checkpoint
  121982. ** mode: */
  121983. return SQLITE_MISUSE;
  121984. }
  121985. sqlite3_mutex_enter(db->mutex);
  121986. if( zDb && zDb[0] ){
  121987. iDb = sqlite3FindDbName(db, zDb);
  121988. }
  121989. if( iDb<0 ){
  121990. rc = SQLITE_ERROR;
  121991. sqlite3ErrorWithMsg(db, SQLITE_ERROR, "unknown database: %s", zDb);
  121992. }else{
  121993. db->busyHandler.nBusy = 0;
  121994. rc = sqlite3Checkpoint(db, iDb, eMode, pnLog, pnCkpt);
  121995. sqlite3Error(db, rc);
  121996. }
  121997. rc = sqlite3ApiExit(db, rc);
  121998. sqlite3_mutex_leave(db->mutex);
  121999. return rc;
  122000. #endif
  122001. }
  122002. /*
  122003. ** Checkpoint database zDb. If zDb is NULL, or if the buffer zDb points
  122004. ** to contains a zero-length string, all attached databases are
  122005. ** checkpointed.
  122006. */
  122007. SQLITE_API int SQLITE_STDCALL sqlite3_wal_checkpoint(sqlite3 *db, const char *zDb){
  122008. /* EVIDENCE-OF: R-41613-20553 The sqlite3_wal_checkpoint(D,X) is equivalent to
  122009. ** sqlite3_wal_checkpoint_v2(D,X,SQLITE_CHECKPOINT_PASSIVE,0,0). */
  122010. return sqlite3_wal_checkpoint_v2(db,zDb,SQLITE_CHECKPOINT_PASSIVE,0,0);
  122011. }
  122012. #ifndef SQLITE_OMIT_WAL
  122013. /*
  122014. ** Run a checkpoint on database iDb. This is a no-op if database iDb is
  122015. ** not currently open in WAL mode.
  122016. **
  122017. ** If a transaction is open on the database being checkpointed, this
  122018. ** function returns SQLITE_LOCKED and a checkpoint is not attempted. If
  122019. ** an error occurs while running the checkpoint, an SQLite error code is
  122020. ** returned (i.e. SQLITE_IOERR). Otherwise, SQLITE_OK.
  122021. **
  122022. ** The mutex on database handle db should be held by the caller. The mutex
  122023. ** associated with the specific b-tree being checkpointed is taken by
  122024. ** this function while the checkpoint is running.
  122025. **
  122026. ** If iDb is passed SQLITE_MAX_ATTACHED, then all attached databases are
  122027. ** checkpointed. If an error is encountered it is returned immediately -
  122028. ** no attempt is made to checkpoint any remaining databases.
  122029. **
  122030. ** Parameter eMode is one of SQLITE_CHECKPOINT_PASSIVE, FULL or RESTART.
  122031. */
  122032. SQLITE_PRIVATE int sqlite3Checkpoint(sqlite3 *db, int iDb, int eMode, int *pnLog, int *pnCkpt){
  122033. int rc = SQLITE_OK; /* Return code */
  122034. int i; /* Used to iterate through attached dbs */
  122035. int bBusy = 0; /* True if SQLITE_BUSY has been encountered */
  122036. assert( sqlite3_mutex_held(db->mutex) );
  122037. assert( !pnLog || *pnLog==-1 );
  122038. assert( !pnCkpt || *pnCkpt==-1 );
  122039. for(i=0; i<db->nDb && rc==SQLITE_OK; i++){
  122040. if( i==iDb || iDb==SQLITE_MAX_ATTACHED ){
  122041. rc = sqlite3BtreeCheckpoint(db->aDb[i].pBt, eMode, pnLog, pnCkpt);
  122042. pnLog = 0;
  122043. pnCkpt = 0;
  122044. if( rc==SQLITE_BUSY ){
  122045. bBusy = 1;
  122046. rc = SQLITE_OK;
  122047. }
  122048. }
  122049. }
  122050. return (rc==SQLITE_OK && bBusy) ? SQLITE_BUSY : rc;
  122051. }
  122052. #endif /* SQLITE_OMIT_WAL */
  122053. /*
  122054. ** This function returns true if main-memory should be used instead of
  122055. ** a temporary file for transient pager files and statement journals.
  122056. ** The value returned depends on the value of db->temp_store (runtime
  122057. ** parameter) and the compile time value of SQLITE_TEMP_STORE. The
  122058. ** following table describes the relationship between these two values
  122059. ** and this functions return value.
  122060. **
  122061. ** SQLITE_TEMP_STORE db->temp_store Location of temporary database
  122062. ** ----------------- -------------- ------------------------------
  122063. ** 0 any file (return 0)
  122064. ** 1 1 file (return 0)
  122065. ** 1 2 memory (return 1)
  122066. ** 1 0 file (return 0)
  122067. ** 2 1 file (return 0)
  122068. ** 2 2 memory (return 1)
  122069. ** 2 0 memory (return 1)
  122070. ** 3 any memory (return 1)
  122071. */
  122072. SQLITE_PRIVATE int sqlite3TempInMemory(const sqlite3 *db){
  122073. #if SQLITE_TEMP_STORE==1
  122074. return ( db->temp_store==2 );
  122075. #endif
  122076. #if SQLITE_TEMP_STORE==2
  122077. return ( db->temp_store!=1 );
  122078. #endif
  122079. #if SQLITE_TEMP_STORE==3
  122080. return 1;
  122081. #endif
  122082. #if SQLITE_TEMP_STORE<1 || SQLITE_TEMP_STORE>3
  122083. return 0;
  122084. #endif
  122085. }
  122086. /*
  122087. ** Return UTF-8 encoded English language explanation of the most recent
  122088. ** error.
  122089. */
  122090. SQLITE_API const char *SQLITE_STDCALL sqlite3_errmsg(sqlite3 *db){
  122091. const char *z;
  122092. if( !db ){
  122093. return sqlite3ErrStr(SQLITE_NOMEM);
  122094. }
  122095. if( !sqlite3SafetyCheckSickOrOk(db) ){
  122096. return sqlite3ErrStr(SQLITE_MISUSE_BKPT);
  122097. }
  122098. sqlite3_mutex_enter(db->mutex);
  122099. if( db->mallocFailed ){
  122100. z = sqlite3ErrStr(SQLITE_NOMEM);
  122101. }else{
  122102. testcase( db->pErr==0 );
  122103. z = (char*)sqlite3_value_text(db->pErr);
  122104. assert( !db->mallocFailed );
  122105. if( z==0 ){
  122106. z = sqlite3ErrStr(db->errCode);
  122107. }
  122108. }
  122109. sqlite3_mutex_leave(db->mutex);
  122110. return z;
  122111. }
  122112. #ifndef SQLITE_OMIT_UTF16
  122113. /*
  122114. ** Return UTF-16 encoded English language explanation of the most recent
  122115. ** error.
  122116. */
  122117. SQLITE_API const void *SQLITE_STDCALL sqlite3_errmsg16(sqlite3 *db){
  122118. static const u16 outOfMem[] = {
  122119. 'o', 'u', 't', ' ', 'o', 'f', ' ', 'm', 'e', 'm', 'o', 'r', 'y', 0
  122120. };
  122121. static const u16 misuse[] = {
  122122. 'l', 'i', 'b', 'r', 'a', 'r', 'y', ' ',
  122123. 'r', 'o', 'u', 't', 'i', 'n', 'e', ' ',
  122124. 'c', 'a', 'l', 'l', 'e', 'd', ' ',
  122125. 'o', 'u', 't', ' ',
  122126. 'o', 'f', ' ',
  122127. 's', 'e', 'q', 'u', 'e', 'n', 'c', 'e', 0
  122128. };
  122129. const void *z;
  122130. if( !db ){
  122131. return (void *)outOfMem;
  122132. }
  122133. if( !sqlite3SafetyCheckSickOrOk(db) ){
  122134. return (void *)misuse;
  122135. }
  122136. sqlite3_mutex_enter(db->mutex);
  122137. if( db->mallocFailed ){
  122138. z = (void *)outOfMem;
  122139. }else{
  122140. z = sqlite3_value_text16(db->pErr);
  122141. if( z==0 ){
  122142. sqlite3ErrorWithMsg(db, db->errCode, sqlite3ErrStr(db->errCode));
  122143. z = sqlite3_value_text16(db->pErr);
  122144. }
  122145. /* A malloc() may have failed within the call to sqlite3_value_text16()
  122146. ** above. If this is the case, then the db->mallocFailed flag needs to
  122147. ** be cleared before returning. Do this directly, instead of via
  122148. ** sqlite3ApiExit(), to avoid setting the database handle error message.
  122149. */
  122150. db->mallocFailed = 0;
  122151. }
  122152. sqlite3_mutex_leave(db->mutex);
  122153. return z;
  122154. }
  122155. #endif /* SQLITE_OMIT_UTF16 */
  122156. /*
  122157. ** Return the most recent error code generated by an SQLite routine. If NULL is
  122158. ** passed to this function, we assume a malloc() failed during sqlite3_open().
  122159. */
  122160. SQLITE_API int SQLITE_STDCALL sqlite3_errcode(sqlite3 *db){
  122161. if( db && !sqlite3SafetyCheckSickOrOk(db) ){
  122162. return SQLITE_MISUSE_BKPT;
  122163. }
  122164. if( !db || db->mallocFailed ){
  122165. return SQLITE_NOMEM;
  122166. }
  122167. return db->errCode & db->errMask;
  122168. }
  122169. SQLITE_API int SQLITE_STDCALL sqlite3_extended_errcode(sqlite3 *db){
  122170. if( db && !sqlite3SafetyCheckSickOrOk(db) ){
  122171. return SQLITE_MISUSE_BKPT;
  122172. }
  122173. if( !db || db->mallocFailed ){
  122174. return SQLITE_NOMEM;
  122175. }
  122176. return db->errCode;
  122177. }
  122178. /*
  122179. ** Return a string that describes the kind of error specified in the
  122180. ** argument. For now, this simply calls the internal sqlite3ErrStr()
  122181. ** function.
  122182. */
  122183. SQLITE_API const char *SQLITE_STDCALL sqlite3_errstr(int rc){
  122184. return sqlite3ErrStr(rc);
  122185. }
  122186. /*
  122187. ** Create a new collating function for database "db". The name is zName
  122188. ** and the encoding is enc.
  122189. */
  122190. static int createCollation(
  122191. sqlite3* db,
  122192. const char *zName,
  122193. u8 enc,
  122194. void* pCtx,
  122195. int(*xCompare)(void*,int,const void*,int,const void*),
  122196. void(*xDel)(void*)
  122197. ){
  122198. CollSeq *pColl;
  122199. int enc2;
  122200. assert( sqlite3_mutex_held(db->mutex) );
  122201. /* If SQLITE_UTF16 is specified as the encoding type, transform this
  122202. ** to one of SQLITE_UTF16LE or SQLITE_UTF16BE using the
  122203. ** SQLITE_UTF16NATIVE macro. SQLITE_UTF16 is not used internally.
  122204. */
  122205. enc2 = enc;
  122206. testcase( enc2==SQLITE_UTF16 );
  122207. testcase( enc2==SQLITE_UTF16_ALIGNED );
  122208. if( enc2==SQLITE_UTF16 || enc2==SQLITE_UTF16_ALIGNED ){
  122209. enc2 = SQLITE_UTF16NATIVE;
  122210. }
  122211. if( enc2<SQLITE_UTF8 || enc2>SQLITE_UTF16BE ){
  122212. return SQLITE_MISUSE_BKPT;
  122213. }
  122214. /* Check if this call is removing or replacing an existing collation
  122215. ** sequence. If so, and there are active VMs, return busy. If there
  122216. ** are no active VMs, invalidate any pre-compiled statements.
  122217. */
  122218. pColl = sqlite3FindCollSeq(db, (u8)enc2, zName, 0);
  122219. if( pColl && pColl->xCmp ){
  122220. if( db->nVdbeActive ){
  122221. sqlite3ErrorWithMsg(db, SQLITE_BUSY,
  122222. "unable to delete/modify collation sequence due to active statements");
  122223. return SQLITE_BUSY;
  122224. }
  122225. sqlite3ExpirePreparedStatements(db);
  122226. /* If collation sequence pColl was created directly by a call to
  122227. ** sqlite3_create_collation, and not generated by synthCollSeq(),
  122228. ** then any copies made by synthCollSeq() need to be invalidated.
  122229. ** Also, collation destructor - CollSeq.xDel() - function may need
  122230. ** to be called.
  122231. */
  122232. if( (pColl->enc & ~SQLITE_UTF16_ALIGNED)==enc2 ){
  122233. CollSeq *aColl = sqlite3HashFind(&db->aCollSeq, zName);
  122234. int j;
  122235. for(j=0; j<3; j++){
  122236. CollSeq *p = &aColl[j];
  122237. if( p->enc==pColl->enc ){
  122238. if( p->xDel ){
  122239. p->xDel(p->pUser);
  122240. }
  122241. p->xCmp = 0;
  122242. }
  122243. }
  122244. }
  122245. }
  122246. pColl = sqlite3FindCollSeq(db, (u8)enc2, zName, 1);
  122247. if( pColl==0 ) return SQLITE_NOMEM;
  122248. pColl->xCmp = xCompare;
  122249. pColl->pUser = pCtx;
  122250. pColl->xDel = xDel;
  122251. pColl->enc = (u8)(enc2 | (enc & SQLITE_UTF16_ALIGNED));
  122252. sqlite3Error(db, SQLITE_OK);
  122253. return SQLITE_OK;
  122254. }
  122255. /*
  122256. ** This array defines hard upper bounds on limit values. The
  122257. ** initializer must be kept in sync with the SQLITE_LIMIT_*
  122258. ** #defines in sqlite3.h.
  122259. */
  122260. static const int aHardLimit[] = {
  122261. SQLITE_MAX_LENGTH,
  122262. SQLITE_MAX_SQL_LENGTH,
  122263. SQLITE_MAX_COLUMN,
  122264. SQLITE_MAX_EXPR_DEPTH,
  122265. SQLITE_MAX_COMPOUND_SELECT,
  122266. SQLITE_MAX_VDBE_OP,
  122267. SQLITE_MAX_FUNCTION_ARG,
  122268. SQLITE_MAX_ATTACHED,
  122269. SQLITE_MAX_LIKE_PATTERN_LENGTH,
  122270. SQLITE_MAX_VARIABLE_NUMBER, /* IMP: R-38091-32352 */
  122271. SQLITE_MAX_TRIGGER_DEPTH,
  122272. SQLITE_MAX_WORKER_THREADS,
  122273. };
  122274. /*
  122275. ** Make sure the hard limits are set to reasonable values
  122276. */
  122277. #if SQLITE_MAX_LENGTH<100
  122278. # error SQLITE_MAX_LENGTH must be at least 100
  122279. #endif
  122280. #if SQLITE_MAX_SQL_LENGTH<100
  122281. # error SQLITE_MAX_SQL_LENGTH must be at least 100
  122282. #endif
  122283. #if SQLITE_MAX_SQL_LENGTH>SQLITE_MAX_LENGTH
  122284. # error SQLITE_MAX_SQL_LENGTH must not be greater than SQLITE_MAX_LENGTH
  122285. #endif
  122286. #if SQLITE_MAX_COMPOUND_SELECT<2
  122287. # error SQLITE_MAX_COMPOUND_SELECT must be at least 2
  122288. #endif
  122289. #if SQLITE_MAX_VDBE_OP<40
  122290. # error SQLITE_MAX_VDBE_OP must be at least 40
  122291. #endif
  122292. #if SQLITE_MAX_FUNCTION_ARG<0 || SQLITE_MAX_FUNCTION_ARG>1000
  122293. # error SQLITE_MAX_FUNCTION_ARG must be between 0 and 1000
  122294. #endif
  122295. #if SQLITE_MAX_ATTACHED<0 || SQLITE_MAX_ATTACHED>125
  122296. # error SQLITE_MAX_ATTACHED must be between 0 and 125
  122297. #endif
  122298. #if SQLITE_MAX_LIKE_PATTERN_LENGTH<1
  122299. # error SQLITE_MAX_LIKE_PATTERN_LENGTH must be at least 1
  122300. #endif
  122301. #if SQLITE_MAX_COLUMN>32767
  122302. # error SQLITE_MAX_COLUMN must not exceed 32767
  122303. #endif
  122304. #if SQLITE_MAX_TRIGGER_DEPTH<1
  122305. # error SQLITE_MAX_TRIGGER_DEPTH must be at least 1
  122306. #endif
  122307. #if SQLITE_MAX_WORKER_THREADS<0 || SQLITE_MAX_WORKER_THREADS>50
  122308. # error SQLITE_MAX_WORKER_THREADS must be between 0 and 50
  122309. #endif
  122310. /*
  122311. ** Change the value of a limit. Report the old value.
  122312. ** If an invalid limit index is supplied, report -1.
  122313. ** Make no changes but still report the old value if the
  122314. ** new limit is negative.
  122315. **
  122316. ** A new lower limit does not shrink existing constructs.
  122317. ** It merely prevents new constructs that exceed the limit
  122318. ** from forming.
  122319. */
  122320. SQLITE_API int SQLITE_STDCALL sqlite3_limit(sqlite3 *db, int limitId, int newLimit){
  122321. int oldLimit;
  122322. #ifdef SQLITE_ENABLE_API_ARMOR
  122323. if( !sqlite3SafetyCheckOk(db) ){
  122324. (void)SQLITE_MISUSE_BKPT;
  122325. return -1;
  122326. }
  122327. #endif
  122328. /* EVIDENCE-OF: R-30189-54097 For each limit category SQLITE_LIMIT_NAME
  122329. ** there is a hard upper bound set at compile-time by a C preprocessor
  122330. ** macro called SQLITE_MAX_NAME. (The "_LIMIT_" in the name is changed to
  122331. ** "_MAX_".)
  122332. */
  122333. assert( aHardLimit[SQLITE_LIMIT_LENGTH]==SQLITE_MAX_LENGTH );
  122334. assert( aHardLimit[SQLITE_LIMIT_SQL_LENGTH]==SQLITE_MAX_SQL_LENGTH );
  122335. assert( aHardLimit[SQLITE_LIMIT_COLUMN]==SQLITE_MAX_COLUMN );
  122336. assert( aHardLimit[SQLITE_LIMIT_EXPR_DEPTH]==SQLITE_MAX_EXPR_DEPTH );
  122337. assert( aHardLimit[SQLITE_LIMIT_COMPOUND_SELECT]==SQLITE_MAX_COMPOUND_SELECT);
  122338. assert( aHardLimit[SQLITE_LIMIT_VDBE_OP]==SQLITE_MAX_VDBE_OP );
  122339. assert( aHardLimit[SQLITE_LIMIT_FUNCTION_ARG]==SQLITE_MAX_FUNCTION_ARG );
  122340. assert( aHardLimit[SQLITE_LIMIT_ATTACHED]==SQLITE_MAX_ATTACHED );
  122341. assert( aHardLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH]==
  122342. SQLITE_MAX_LIKE_PATTERN_LENGTH );
  122343. assert( aHardLimit[SQLITE_LIMIT_VARIABLE_NUMBER]==SQLITE_MAX_VARIABLE_NUMBER);
  122344. assert( aHardLimit[SQLITE_LIMIT_TRIGGER_DEPTH]==SQLITE_MAX_TRIGGER_DEPTH );
  122345. assert( aHardLimit[SQLITE_LIMIT_WORKER_THREADS]==SQLITE_MAX_WORKER_THREADS );
  122346. assert( SQLITE_LIMIT_WORKER_THREADS==(SQLITE_N_LIMIT-1) );
  122347. if( limitId<0 || limitId>=SQLITE_N_LIMIT ){
  122348. return -1;
  122349. }
  122350. oldLimit = db->aLimit[limitId];
  122351. if( newLimit>=0 ){ /* IMP: R-52476-28732 */
  122352. if( newLimit>aHardLimit[limitId] ){
  122353. newLimit = aHardLimit[limitId]; /* IMP: R-51463-25634 */
  122354. }
  122355. db->aLimit[limitId] = newLimit;
  122356. }
  122357. return oldLimit; /* IMP: R-53341-35419 */
  122358. }
  122359. /*
  122360. ** This function is used to parse both URIs and non-URI filenames passed by the
  122361. ** user to API functions sqlite3_open() or sqlite3_open_v2(), and for database
  122362. ** URIs specified as part of ATTACH statements.
  122363. **
  122364. ** The first argument to this function is the name of the VFS to use (or
  122365. ** a NULL to signify the default VFS) if the URI does not contain a "vfs=xxx"
  122366. ** query parameter. The second argument contains the URI (or non-URI filename)
  122367. ** itself. When this function is called the *pFlags variable should contain
  122368. ** the default flags to open the database handle with. The value stored in
  122369. ** *pFlags may be updated before returning if the URI filename contains
  122370. ** "cache=xxx" or "mode=xxx" query parameters.
  122371. **
  122372. ** If successful, SQLITE_OK is returned. In this case *ppVfs is set to point to
  122373. ** the VFS that should be used to open the database file. *pzFile is set to
  122374. ** point to a buffer containing the name of the file to open. It is the
  122375. ** responsibility of the caller to eventually call sqlite3_free() to release
  122376. ** this buffer.
  122377. **
  122378. ** If an error occurs, then an SQLite error code is returned and *pzErrMsg
  122379. ** may be set to point to a buffer containing an English language error
  122380. ** message. It is the responsibility of the caller to eventually release
  122381. ** this buffer by calling sqlite3_free().
  122382. */
  122383. SQLITE_PRIVATE int sqlite3ParseUri(
  122384. const char *zDefaultVfs, /* VFS to use if no "vfs=xxx" query option */
  122385. const char *zUri, /* Nul-terminated URI to parse */
  122386. unsigned int *pFlags, /* IN/OUT: SQLITE_OPEN_XXX flags */
  122387. sqlite3_vfs **ppVfs, /* OUT: VFS to use */
  122388. char **pzFile, /* OUT: Filename component of URI */
  122389. char **pzErrMsg /* OUT: Error message (if rc!=SQLITE_OK) */
  122390. ){
  122391. int rc = SQLITE_OK;
  122392. unsigned int flags = *pFlags;
  122393. const char *zVfs = zDefaultVfs;
  122394. char *zFile;
  122395. char c;
  122396. int nUri = sqlite3Strlen30(zUri);
  122397. assert( *pzErrMsg==0 );
  122398. if( ((flags & SQLITE_OPEN_URI) /* IMP: R-48725-32206 */
  122399. || sqlite3GlobalConfig.bOpenUri) /* IMP: R-51689-46548 */
  122400. && nUri>=5 && memcmp(zUri, "file:", 5)==0 /* IMP: R-57884-37496 */
  122401. ){
  122402. char *zOpt;
  122403. int eState; /* Parser state when parsing URI */
  122404. int iIn; /* Input character index */
  122405. int iOut = 0; /* Output character index */
  122406. u64 nByte = nUri+2; /* Bytes of space to allocate */
  122407. /* Make sure the SQLITE_OPEN_URI flag is set to indicate to the VFS xOpen
  122408. ** method that there may be extra parameters following the file-name. */
  122409. flags |= SQLITE_OPEN_URI;
  122410. for(iIn=0; iIn<nUri; iIn++) nByte += (zUri[iIn]=='&');
  122411. zFile = sqlite3_malloc64(nByte);
  122412. if( !zFile ) return SQLITE_NOMEM;
  122413. iIn = 5;
  122414. #ifdef SQLITE_ALLOW_URI_AUTHORITY
  122415. if( strncmp(zUri+5, "///", 3)==0 ){
  122416. iIn = 7;
  122417. /* The following condition causes URIs with five leading / characters
  122418. ** like file://///host/path to be converted into UNCs like //host/path.
  122419. ** The correct URI for that UNC has only two or four leading / characters
  122420. ** file://host/path or file:////host/path. But 5 leading slashes is a
  122421. ** common error, we are told, so we handle it as a special case. */
  122422. if( strncmp(zUri+7, "///", 3)==0 ){ iIn++; }
  122423. }else if( strncmp(zUri+5, "//localhost/", 12)==0 ){
  122424. iIn = 16;
  122425. }
  122426. #else
  122427. /* Discard the scheme and authority segments of the URI. */
  122428. if( zUri[5]=='/' && zUri[6]=='/' ){
  122429. iIn = 7;
  122430. while( zUri[iIn] && zUri[iIn]!='/' ) iIn++;
  122431. if( iIn!=7 && (iIn!=16 || memcmp("localhost", &zUri[7], 9)) ){
  122432. *pzErrMsg = sqlite3_mprintf("invalid uri authority: %.*s",
  122433. iIn-7, &zUri[7]);
  122434. rc = SQLITE_ERROR;
  122435. goto parse_uri_out;
  122436. }
  122437. }
  122438. #endif
  122439. /* Copy the filename and any query parameters into the zFile buffer.
  122440. ** Decode %HH escape codes along the way.
  122441. **
  122442. ** Within this loop, variable eState may be set to 0, 1 or 2, depending
  122443. ** on the parsing context. As follows:
  122444. **
  122445. ** 0: Parsing file-name.
  122446. ** 1: Parsing name section of a name=value query parameter.
  122447. ** 2: Parsing value section of a name=value query parameter.
  122448. */
  122449. eState = 0;
  122450. while( (c = zUri[iIn])!=0 && c!='#' ){
  122451. iIn++;
  122452. if( c=='%'
  122453. && sqlite3Isxdigit(zUri[iIn])
  122454. && sqlite3Isxdigit(zUri[iIn+1])
  122455. ){
  122456. int octet = (sqlite3HexToInt(zUri[iIn++]) << 4);
  122457. octet += sqlite3HexToInt(zUri[iIn++]);
  122458. assert( octet>=0 && octet<256 );
  122459. if( octet==0 ){
  122460. /* This branch is taken when "%00" appears within the URI. In this
  122461. ** case we ignore all text in the remainder of the path, name or
  122462. ** value currently being parsed. So ignore the current character
  122463. ** and skip to the next "?", "=" or "&", as appropriate. */
  122464. while( (c = zUri[iIn])!=0 && c!='#'
  122465. && (eState!=0 || c!='?')
  122466. && (eState!=1 || (c!='=' && c!='&'))
  122467. && (eState!=2 || c!='&')
  122468. ){
  122469. iIn++;
  122470. }
  122471. continue;
  122472. }
  122473. c = octet;
  122474. }else if( eState==1 && (c=='&' || c=='=') ){
  122475. if( zFile[iOut-1]==0 ){
  122476. /* An empty option name. Ignore this option altogether. */
  122477. while( zUri[iIn] && zUri[iIn]!='#' && zUri[iIn-1]!='&' ) iIn++;
  122478. continue;
  122479. }
  122480. if( c=='&' ){
  122481. zFile[iOut++] = '\0';
  122482. }else{
  122483. eState = 2;
  122484. }
  122485. c = 0;
  122486. }else if( (eState==0 && c=='?') || (eState==2 && c=='&') ){
  122487. c = 0;
  122488. eState = 1;
  122489. }
  122490. zFile[iOut++] = c;
  122491. }
  122492. if( eState==1 ) zFile[iOut++] = '\0';
  122493. zFile[iOut++] = '\0';
  122494. zFile[iOut++] = '\0';
  122495. /* Check if there were any options specified that should be interpreted
  122496. ** here. Options that are interpreted here include "vfs" and those that
  122497. ** correspond to flags that may be passed to the sqlite3_open_v2()
  122498. ** method. */
  122499. zOpt = &zFile[sqlite3Strlen30(zFile)+1];
  122500. while( zOpt[0] ){
  122501. int nOpt = sqlite3Strlen30(zOpt);
  122502. char *zVal = &zOpt[nOpt+1];
  122503. int nVal = sqlite3Strlen30(zVal);
  122504. if( nOpt==3 && memcmp("vfs", zOpt, 3)==0 ){
  122505. zVfs = zVal;
  122506. }else{
  122507. struct OpenMode {
  122508. const char *z;
  122509. int mode;
  122510. } *aMode = 0;
  122511. char *zModeType = 0;
  122512. int mask = 0;
  122513. int limit = 0;
  122514. if( nOpt==5 && memcmp("cache", zOpt, 5)==0 ){
  122515. static struct OpenMode aCacheMode[] = {
  122516. { "shared", SQLITE_OPEN_SHAREDCACHE },
  122517. { "private", SQLITE_OPEN_PRIVATECACHE },
  122518. { 0, 0 }
  122519. };
  122520. mask = SQLITE_OPEN_SHAREDCACHE|SQLITE_OPEN_PRIVATECACHE;
  122521. aMode = aCacheMode;
  122522. limit = mask;
  122523. zModeType = "cache";
  122524. }
  122525. if( nOpt==4 && memcmp("mode", zOpt, 4)==0 ){
  122526. static struct OpenMode aOpenMode[] = {
  122527. { "ro", SQLITE_OPEN_READONLY },
  122528. { "rw", SQLITE_OPEN_READWRITE },
  122529. { "rwc", SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE },
  122530. { "memory", SQLITE_OPEN_MEMORY },
  122531. { 0, 0 }
  122532. };
  122533. mask = SQLITE_OPEN_READONLY | SQLITE_OPEN_READWRITE
  122534. | SQLITE_OPEN_CREATE | SQLITE_OPEN_MEMORY;
  122535. aMode = aOpenMode;
  122536. limit = mask & flags;
  122537. zModeType = "access";
  122538. }
  122539. if( aMode ){
  122540. int i;
  122541. int mode = 0;
  122542. for(i=0; aMode[i].z; i++){
  122543. const char *z = aMode[i].z;
  122544. if( nVal==sqlite3Strlen30(z) && 0==memcmp(zVal, z, nVal) ){
  122545. mode = aMode[i].mode;
  122546. break;
  122547. }
  122548. }
  122549. if( mode==0 ){
  122550. *pzErrMsg = sqlite3_mprintf("no such %s mode: %s", zModeType, zVal);
  122551. rc = SQLITE_ERROR;
  122552. goto parse_uri_out;
  122553. }
  122554. if( (mode & ~SQLITE_OPEN_MEMORY)>limit ){
  122555. *pzErrMsg = sqlite3_mprintf("%s mode not allowed: %s",
  122556. zModeType, zVal);
  122557. rc = SQLITE_PERM;
  122558. goto parse_uri_out;
  122559. }
  122560. flags = (flags & ~mask) | mode;
  122561. }
  122562. }
  122563. zOpt = &zVal[nVal+1];
  122564. }
  122565. }else{
  122566. zFile = sqlite3_malloc64(nUri+2);
  122567. if( !zFile ) return SQLITE_NOMEM;
  122568. memcpy(zFile, zUri, nUri);
  122569. zFile[nUri] = '\0';
  122570. zFile[nUri+1] = '\0';
  122571. flags &= ~SQLITE_OPEN_URI;
  122572. }
  122573. *ppVfs = sqlite3_vfs_find(zVfs);
  122574. if( *ppVfs==0 ){
  122575. *pzErrMsg = sqlite3_mprintf("no such vfs: %s", zVfs);
  122576. rc = SQLITE_ERROR;
  122577. }
  122578. parse_uri_out:
  122579. if( rc!=SQLITE_OK ){
  122580. sqlite3_free(zFile);
  122581. zFile = 0;
  122582. }
  122583. *pFlags = flags;
  122584. *pzFile = zFile;
  122585. return rc;
  122586. }
  122587. /*
  122588. ** This routine does the work of opening a database on behalf of
  122589. ** sqlite3_open() and sqlite3_open16(). The database filename "zFilename"
  122590. ** is UTF-8 encoded.
  122591. */
  122592. static int openDatabase(
  122593. const char *zFilename, /* Database filename UTF-8 encoded */
  122594. sqlite3 **ppDb, /* OUT: Returned database handle */
  122595. unsigned int flags, /* Operational flags */
  122596. const char *zVfs /* Name of the VFS to use */
  122597. ){
  122598. sqlite3 *db; /* Store allocated handle here */
  122599. int rc; /* Return code */
  122600. int isThreadsafe; /* True for threadsafe connections */
  122601. char *zOpen = 0; /* Filename argument to pass to BtreeOpen() */
  122602. char *zErrMsg = 0; /* Error message from sqlite3ParseUri() */
  122603. #ifdef SQLITE_ENABLE_API_ARMOR
  122604. if( ppDb==0 ) return SQLITE_MISUSE_BKPT;
  122605. #endif
  122606. *ppDb = 0;
  122607. #ifndef SQLITE_OMIT_AUTOINIT
  122608. rc = sqlite3_initialize();
  122609. if( rc ) return rc;
  122610. #endif
  122611. /* Only allow sensible combinations of bits in the flags argument.
  122612. ** Throw an error if any non-sense combination is used. If we
  122613. ** do not block illegal combinations here, it could trigger
  122614. ** assert() statements in deeper layers. Sensible combinations
  122615. ** are:
  122616. **
  122617. ** 1: SQLITE_OPEN_READONLY
  122618. ** 2: SQLITE_OPEN_READWRITE
  122619. ** 6: SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE
  122620. */
  122621. assert( SQLITE_OPEN_READONLY == 0x01 );
  122622. assert( SQLITE_OPEN_READWRITE == 0x02 );
  122623. assert( SQLITE_OPEN_CREATE == 0x04 );
  122624. testcase( (1<<(flags&7))==0x02 ); /* READONLY */
  122625. testcase( (1<<(flags&7))==0x04 ); /* READWRITE */
  122626. testcase( (1<<(flags&7))==0x40 ); /* READWRITE | CREATE */
  122627. if( ((1<<(flags&7)) & 0x46)==0 ){
  122628. return SQLITE_MISUSE_BKPT; /* IMP: R-65497-44594 */
  122629. }
  122630. if( sqlite3GlobalConfig.bCoreMutex==0 ){
  122631. isThreadsafe = 0;
  122632. }else if( flags & SQLITE_OPEN_NOMUTEX ){
  122633. isThreadsafe = 0;
  122634. }else if( flags & SQLITE_OPEN_FULLMUTEX ){
  122635. isThreadsafe = 1;
  122636. }else{
  122637. isThreadsafe = sqlite3GlobalConfig.bFullMutex;
  122638. }
  122639. if( flags & SQLITE_OPEN_PRIVATECACHE ){
  122640. flags &= ~SQLITE_OPEN_SHAREDCACHE;
  122641. }else if( sqlite3GlobalConfig.sharedCacheEnabled ){
  122642. flags |= SQLITE_OPEN_SHAREDCACHE;
  122643. }
  122644. /* Remove harmful bits from the flags parameter
  122645. **
  122646. ** The SQLITE_OPEN_NOMUTEX and SQLITE_OPEN_FULLMUTEX flags were
  122647. ** dealt with in the previous code block. Besides these, the only
  122648. ** valid input flags for sqlite3_open_v2() are SQLITE_OPEN_READONLY,
  122649. ** SQLITE_OPEN_READWRITE, SQLITE_OPEN_CREATE, SQLITE_OPEN_SHAREDCACHE,
  122650. ** SQLITE_OPEN_PRIVATECACHE, and some reserved bits. Silently mask
  122651. ** off all other flags.
  122652. */
  122653. flags &= ~( SQLITE_OPEN_DELETEONCLOSE |
  122654. SQLITE_OPEN_EXCLUSIVE |
  122655. SQLITE_OPEN_MAIN_DB |
  122656. SQLITE_OPEN_TEMP_DB |
  122657. SQLITE_OPEN_TRANSIENT_DB |
  122658. SQLITE_OPEN_MAIN_JOURNAL |
  122659. SQLITE_OPEN_TEMP_JOURNAL |
  122660. SQLITE_OPEN_SUBJOURNAL |
  122661. SQLITE_OPEN_MASTER_JOURNAL |
  122662. SQLITE_OPEN_NOMUTEX |
  122663. SQLITE_OPEN_FULLMUTEX |
  122664. SQLITE_OPEN_WAL
  122665. );
  122666. /* Allocate the sqlite data structure */
  122667. db = sqlite3MallocZero( sizeof(sqlite3) );
  122668. if( db==0 ) goto opendb_out;
  122669. if( isThreadsafe ){
  122670. db->mutex = sqlite3MutexAlloc(SQLITE_MUTEX_RECURSIVE);
  122671. if( db->mutex==0 ){
  122672. sqlite3_free(db);
  122673. db = 0;
  122674. goto opendb_out;
  122675. }
  122676. }
  122677. sqlite3_mutex_enter(db->mutex);
  122678. db->errMask = 0xff;
  122679. db->nDb = 2;
  122680. db->magic = SQLITE_MAGIC_BUSY;
  122681. db->aDb = db->aDbStatic;
  122682. assert( sizeof(db->aLimit)==sizeof(aHardLimit) );
  122683. memcpy(db->aLimit, aHardLimit, sizeof(db->aLimit));
  122684. db->aLimit[SQLITE_LIMIT_WORKER_THREADS] = SQLITE_DEFAULT_WORKER_THREADS;
  122685. db->autoCommit = 1;
  122686. db->nextAutovac = -1;
  122687. db->szMmap = sqlite3GlobalConfig.szMmap;
  122688. db->nextPagesize = 0;
  122689. db->nMaxSorterMmap = 0x7FFFFFFF;
  122690. db->flags |= SQLITE_ShortColNames | SQLITE_EnableTrigger | SQLITE_CacheSpill
  122691. #if !defined(SQLITE_DEFAULT_AUTOMATIC_INDEX) || SQLITE_DEFAULT_AUTOMATIC_INDEX
  122692. | SQLITE_AutoIndex
  122693. #endif
  122694. #if SQLITE_DEFAULT_CKPTFULLFSYNC
  122695. | SQLITE_CkptFullFSync
  122696. #endif
  122697. #if SQLITE_DEFAULT_FILE_FORMAT<4
  122698. | SQLITE_LegacyFileFmt
  122699. #endif
  122700. #ifdef SQLITE_ENABLE_LOAD_EXTENSION
  122701. | SQLITE_LoadExtension
  122702. #endif
  122703. #if SQLITE_DEFAULT_RECURSIVE_TRIGGERS
  122704. | SQLITE_RecTriggers
  122705. #endif
  122706. #if defined(SQLITE_DEFAULT_FOREIGN_KEYS) && SQLITE_DEFAULT_FOREIGN_KEYS
  122707. | SQLITE_ForeignKeys
  122708. #endif
  122709. #if defined(SQLITE_REVERSE_UNORDERED_SELECTS)
  122710. | SQLITE_ReverseOrder
  122711. #endif
  122712. ;
  122713. sqlite3HashInit(&db->aCollSeq);
  122714. #ifndef SQLITE_OMIT_VIRTUALTABLE
  122715. sqlite3HashInit(&db->aModule);
  122716. #endif
  122717. /* Add the default collation sequence BINARY. BINARY works for both UTF-8
  122718. ** and UTF-16, so add a version for each to avoid any unnecessary
  122719. ** conversions. The only error that can occur here is a malloc() failure.
  122720. **
  122721. ** EVIDENCE-OF: R-52786-44878 SQLite defines three built-in collating
  122722. ** functions:
  122723. */
  122724. createCollation(db, "BINARY", SQLITE_UTF8, 0, binCollFunc, 0);
  122725. createCollation(db, "BINARY", SQLITE_UTF16BE, 0, binCollFunc, 0);
  122726. createCollation(db, "BINARY", SQLITE_UTF16LE, 0, binCollFunc, 0);
  122727. createCollation(db, "NOCASE", SQLITE_UTF8, 0, nocaseCollatingFunc, 0);
  122728. createCollation(db, "RTRIM", SQLITE_UTF8, (void*)1, binCollFunc, 0);
  122729. if( db->mallocFailed ){
  122730. goto opendb_out;
  122731. }
  122732. /* EVIDENCE-OF: R-08308-17224 The default collating function for all
  122733. ** strings is BINARY.
  122734. */
  122735. db->pDfltColl = sqlite3FindCollSeq(db, SQLITE_UTF8, "BINARY", 0);
  122736. assert( db->pDfltColl!=0 );
  122737. /* Parse the filename/URI argument. */
  122738. db->openFlags = flags;
  122739. rc = sqlite3ParseUri(zVfs, zFilename, &flags, &db->pVfs, &zOpen, &zErrMsg);
  122740. if( rc!=SQLITE_OK ){
  122741. if( rc==SQLITE_NOMEM ) db->mallocFailed = 1;
  122742. sqlite3ErrorWithMsg(db, rc, zErrMsg ? "%s" : 0, zErrMsg);
  122743. sqlite3_free(zErrMsg);
  122744. goto opendb_out;
  122745. }
  122746. /* Open the backend database driver */
  122747. rc = sqlite3BtreeOpen(db->pVfs, zOpen, db, &db->aDb[0].pBt, 0,
  122748. flags | SQLITE_OPEN_MAIN_DB);
  122749. if( rc!=SQLITE_OK ){
  122750. if( rc==SQLITE_IOERR_NOMEM ){
  122751. rc = SQLITE_NOMEM;
  122752. }
  122753. sqlite3Error(db, rc);
  122754. goto opendb_out;
  122755. }
  122756. sqlite3BtreeEnter(db->aDb[0].pBt);
  122757. db->aDb[0].pSchema = sqlite3SchemaGet(db, db->aDb[0].pBt);
  122758. if( !db->mallocFailed ) ENC(db) = SCHEMA_ENC(db);
  122759. sqlite3BtreeLeave(db->aDb[0].pBt);
  122760. db->aDb[1].pSchema = sqlite3SchemaGet(db, 0);
  122761. /* The default safety_level for the main database is 'full'; for the temp
  122762. ** database it is 'NONE'. This matches the pager layer defaults.
  122763. */
  122764. db->aDb[0].zName = "main";
  122765. db->aDb[0].safety_level = 3;
  122766. db->aDb[1].zName = "temp";
  122767. db->aDb[1].safety_level = 1;
  122768. db->magic = SQLITE_MAGIC_OPEN;
  122769. if( db->mallocFailed ){
  122770. goto opendb_out;
  122771. }
  122772. /* Register all built-in functions, but do not attempt to read the
  122773. ** database schema yet. This is delayed until the first time the database
  122774. ** is accessed.
  122775. */
  122776. sqlite3Error(db, SQLITE_OK);
  122777. sqlite3RegisterBuiltinFunctions(db);
  122778. /* Load automatic extensions - extensions that have been registered
  122779. ** using the sqlite3_automatic_extension() API.
  122780. */
  122781. rc = sqlite3_errcode(db);
  122782. if( rc==SQLITE_OK ){
  122783. sqlite3AutoLoadExtensions(db);
  122784. rc = sqlite3_errcode(db);
  122785. if( rc!=SQLITE_OK ){
  122786. goto opendb_out;
  122787. }
  122788. }
  122789. #ifdef SQLITE_ENABLE_FTS1
  122790. if( !db->mallocFailed ){
  122791. extern int sqlite3Fts1Init(sqlite3*);
  122792. rc = sqlite3Fts1Init(db);
  122793. }
  122794. #endif
  122795. #ifdef SQLITE_ENABLE_FTS2
  122796. if( !db->mallocFailed && rc==SQLITE_OK ){
  122797. extern int sqlite3Fts2Init(sqlite3*);
  122798. rc = sqlite3Fts2Init(db);
  122799. }
  122800. #endif
  122801. #ifdef SQLITE_ENABLE_FTS3
  122802. if( !db->mallocFailed && rc==SQLITE_OK ){
  122803. rc = sqlite3Fts3Init(db);
  122804. }
  122805. #endif
  122806. #ifdef SQLITE_ENABLE_ICU
  122807. if( !db->mallocFailed && rc==SQLITE_OK ){
  122808. rc = sqlite3IcuInit(db);
  122809. }
  122810. #endif
  122811. #ifdef SQLITE_ENABLE_RTREE
  122812. if( !db->mallocFailed && rc==SQLITE_OK){
  122813. rc = sqlite3RtreeInit(db);
  122814. }
  122815. #endif
  122816. #ifdef SQLITE_ENABLE_DBSTAT_VTAB
  122817. if( !db->mallocFailed && rc==SQLITE_OK){
  122818. int sqlite3_dbstat_register(sqlite3*);
  122819. rc = sqlite3_dbstat_register(db);
  122820. }
  122821. #endif
  122822. /* -DSQLITE_DEFAULT_LOCKING_MODE=1 makes EXCLUSIVE the default locking
  122823. ** mode. -DSQLITE_DEFAULT_LOCKING_MODE=0 make NORMAL the default locking
  122824. ** mode. Doing nothing at all also makes NORMAL the default.
  122825. */
  122826. #ifdef SQLITE_DEFAULT_LOCKING_MODE
  122827. db->dfltLockMode = SQLITE_DEFAULT_LOCKING_MODE;
  122828. sqlite3PagerLockingMode(sqlite3BtreePager(db->aDb[0].pBt),
  122829. SQLITE_DEFAULT_LOCKING_MODE);
  122830. #endif
  122831. if( rc ) sqlite3Error(db, rc);
  122832. /* Enable the lookaside-malloc subsystem */
  122833. setupLookaside(db, 0, sqlite3GlobalConfig.szLookaside,
  122834. sqlite3GlobalConfig.nLookaside);
  122835. sqlite3_wal_autocheckpoint(db, SQLITE_DEFAULT_WAL_AUTOCHECKPOINT);
  122836. opendb_out:
  122837. sqlite3_free(zOpen);
  122838. if( db ){
  122839. assert( db->mutex!=0 || isThreadsafe==0
  122840. || sqlite3GlobalConfig.bFullMutex==0 );
  122841. sqlite3_mutex_leave(db->mutex);
  122842. }
  122843. rc = sqlite3_errcode(db);
  122844. assert( db!=0 || rc==SQLITE_NOMEM );
  122845. if( rc==SQLITE_NOMEM ){
  122846. sqlite3_close(db);
  122847. db = 0;
  122848. }else if( rc!=SQLITE_OK ){
  122849. db->magic = SQLITE_MAGIC_SICK;
  122850. }
  122851. *ppDb = db;
  122852. #ifdef SQLITE_ENABLE_SQLLOG
  122853. if( sqlite3GlobalConfig.xSqllog ){
  122854. /* Opening a db handle. Fourth parameter is passed 0. */
  122855. void *pArg = sqlite3GlobalConfig.pSqllogArg;
  122856. sqlite3GlobalConfig.xSqllog(pArg, db, zFilename, 0);
  122857. }
  122858. #endif
  122859. return sqlite3ApiExit(0, rc);
  122860. }
  122861. /*
  122862. ** Open a new database handle.
  122863. */
  122864. SQLITE_API int SQLITE_STDCALL sqlite3_open(
  122865. const char *zFilename,
  122866. sqlite3 **ppDb
  122867. ){
  122868. return openDatabase(zFilename, ppDb,
  122869. SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, 0);
  122870. }
  122871. SQLITE_API int SQLITE_STDCALL sqlite3_open_v2(
  122872. const char *filename, /* Database filename (UTF-8) */
  122873. sqlite3 **ppDb, /* OUT: SQLite db handle */
  122874. int flags, /* Flags */
  122875. const char *zVfs /* Name of VFS module to use */
  122876. ){
  122877. return openDatabase(filename, ppDb, (unsigned int)flags, zVfs);
  122878. }
  122879. #ifndef SQLITE_OMIT_UTF16
  122880. /*
  122881. ** Open a new database handle.
  122882. */
  122883. SQLITE_API int SQLITE_STDCALL sqlite3_open16(
  122884. const void *zFilename,
  122885. sqlite3 **ppDb
  122886. ){
  122887. char const *zFilename8; /* zFilename encoded in UTF-8 instead of UTF-16 */
  122888. sqlite3_value *pVal;
  122889. int rc;
  122890. #ifdef SQLITE_ENABLE_API_ARMOR
  122891. if( ppDb==0 ) return SQLITE_MISUSE_BKPT;
  122892. #endif
  122893. *ppDb = 0;
  122894. #ifndef SQLITE_OMIT_AUTOINIT
  122895. rc = sqlite3_initialize();
  122896. if( rc ) return rc;
  122897. #endif
  122898. if( zFilename==0 ) zFilename = "\000\000";
  122899. pVal = sqlite3ValueNew(0);
  122900. sqlite3ValueSetStr(pVal, -1, zFilename, SQLITE_UTF16NATIVE, SQLITE_STATIC);
  122901. zFilename8 = sqlite3ValueText(pVal, SQLITE_UTF8);
  122902. if( zFilename8 ){
  122903. rc = openDatabase(zFilename8, ppDb,
  122904. SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, 0);
  122905. assert( *ppDb || rc==SQLITE_NOMEM );
  122906. if( rc==SQLITE_OK && !DbHasProperty(*ppDb, 0, DB_SchemaLoaded) ){
  122907. SCHEMA_ENC(*ppDb) = ENC(*ppDb) = SQLITE_UTF16NATIVE;
  122908. }
  122909. }else{
  122910. rc = SQLITE_NOMEM;
  122911. }
  122912. sqlite3ValueFree(pVal);
  122913. return sqlite3ApiExit(0, rc);
  122914. }
  122915. #endif /* SQLITE_OMIT_UTF16 */
  122916. /*
  122917. ** Register a new collation sequence with the database handle db.
  122918. */
  122919. SQLITE_API int SQLITE_STDCALL sqlite3_create_collation(
  122920. sqlite3* db,
  122921. const char *zName,
  122922. int enc,
  122923. void* pCtx,
  122924. int(*xCompare)(void*,int,const void*,int,const void*)
  122925. ){
  122926. return sqlite3_create_collation_v2(db, zName, enc, pCtx, xCompare, 0);
  122927. }
  122928. /*
  122929. ** Register a new collation sequence with the database handle db.
  122930. */
  122931. SQLITE_API int SQLITE_STDCALL sqlite3_create_collation_v2(
  122932. sqlite3* db,
  122933. const char *zName,
  122934. int enc,
  122935. void* pCtx,
  122936. int(*xCompare)(void*,int,const void*,int,const void*),
  122937. void(*xDel)(void*)
  122938. ){
  122939. int rc;
  122940. #ifdef SQLITE_ENABLE_API_ARMOR
  122941. if( !sqlite3SafetyCheckOk(db) || zName==0 ) return SQLITE_MISUSE_BKPT;
  122942. #endif
  122943. sqlite3_mutex_enter(db->mutex);
  122944. assert( !db->mallocFailed );
  122945. rc = createCollation(db, zName, (u8)enc, pCtx, xCompare, xDel);
  122946. rc = sqlite3ApiExit(db, rc);
  122947. sqlite3_mutex_leave(db->mutex);
  122948. return rc;
  122949. }
  122950. #ifndef SQLITE_OMIT_UTF16
  122951. /*
  122952. ** Register a new collation sequence with the database handle db.
  122953. */
  122954. SQLITE_API int SQLITE_STDCALL sqlite3_create_collation16(
  122955. sqlite3* db,
  122956. const void *zName,
  122957. int enc,
  122958. void* pCtx,
  122959. int(*xCompare)(void*,int,const void*,int,const void*)
  122960. ){
  122961. int rc = SQLITE_OK;
  122962. char *zName8;
  122963. #ifdef SQLITE_ENABLE_API_ARMOR
  122964. if( !sqlite3SafetyCheckOk(db) || zName==0 ) return SQLITE_MISUSE_BKPT;
  122965. #endif
  122966. sqlite3_mutex_enter(db->mutex);
  122967. assert( !db->mallocFailed );
  122968. zName8 = sqlite3Utf16to8(db, zName, -1, SQLITE_UTF16NATIVE);
  122969. if( zName8 ){
  122970. rc = createCollation(db, zName8, (u8)enc, pCtx, xCompare, 0);
  122971. sqlite3DbFree(db, zName8);
  122972. }
  122973. rc = sqlite3ApiExit(db, rc);
  122974. sqlite3_mutex_leave(db->mutex);
  122975. return rc;
  122976. }
  122977. #endif /* SQLITE_OMIT_UTF16 */
  122978. /*
  122979. ** Register a collation sequence factory callback with the database handle
  122980. ** db. Replace any previously installed collation sequence factory.
  122981. */
  122982. SQLITE_API int SQLITE_STDCALL sqlite3_collation_needed(
  122983. sqlite3 *db,
  122984. void *pCollNeededArg,
  122985. void(*xCollNeeded)(void*,sqlite3*,int eTextRep,const char*)
  122986. ){
  122987. #ifdef SQLITE_ENABLE_API_ARMOR
  122988. if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
  122989. #endif
  122990. sqlite3_mutex_enter(db->mutex);
  122991. db->xCollNeeded = xCollNeeded;
  122992. db->xCollNeeded16 = 0;
  122993. db->pCollNeededArg = pCollNeededArg;
  122994. sqlite3_mutex_leave(db->mutex);
  122995. return SQLITE_OK;
  122996. }
  122997. #ifndef SQLITE_OMIT_UTF16
  122998. /*
  122999. ** Register a collation sequence factory callback with the database handle
  123000. ** db. Replace any previously installed collation sequence factory.
  123001. */
  123002. SQLITE_API int SQLITE_STDCALL sqlite3_collation_needed16(
  123003. sqlite3 *db,
  123004. void *pCollNeededArg,
  123005. void(*xCollNeeded16)(void*,sqlite3*,int eTextRep,const void*)
  123006. ){
  123007. #ifdef SQLITE_ENABLE_API_ARMOR
  123008. if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
  123009. #endif
  123010. sqlite3_mutex_enter(db->mutex);
  123011. db->xCollNeeded = 0;
  123012. db->xCollNeeded16 = xCollNeeded16;
  123013. db->pCollNeededArg = pCollNeededArg;
  123014. sqlite3_mutex_leave(db->mutex);
  123015. return SQLITE_OK;
  123016. }
  123017. #endif /* SQLITE_OMIT_UTF16 */
  123018. #ifndef SQLITE_OMIT_DEPRECATED
  123019. /*
  123020. ** This function is now an anachronism. It used to be used to recover from a
  123021. ** malloc() failure, but SQLite now does this automatically.
  123022. */
  123023. SQLITE_API int SQLITE_STDCALL sqlite3_global_recover(void){
  123024. return SQLITE_OK;
  123025. }
  123026. #endif
  123027. /*
  123028. ** Test to see whether or not the database connection is in autocommit
  123029. ** mode. Return TRUE if it is and FALSE if not. Autocommit mode is on
  123030. ** by default. Autocommit is disabled by a BEGIN statement and reenabled
  123031. ** by the next COMMIT or ROLLBACK.
  123032. */
  123033. SQLITE_API int SQLITE_STDCALL sqlite3_get_autocommit(sqlite3 *db){
  123034. #ifdef SQLITE_ENABLE_API_ARMOR
  123035. if( !sqlite3SafetyCheckOk(db) ){
  123036. (void)SQLITE_MISUSE_BKPT;
  123037. return 0;
  123038. }
  123039. #endif
  123040. return db->autoCommit;
  123041. }
  123042. /*
  123043. ** The following routines are substitutes for constants SQLITE_CORRUPT,
  123044. ** SQLITE_MISUSE, SQLITE_CANTOPEN, SQLITE_IOERR and possibly other error
  123045. ** constants. They serve two purposes:
  123046. **
  123047. ** 1. Serve as a convenient place to set a breakpoint in a debugger
  123048. ** to detect when version error conditions occurs.
  123049. **
  123050. ** 2. Invoke sqlite3_log() to provide the source code location where
  123051. ** a low-level error is first detected.
  123052. */
  123053. SQLITE_PRIVATE int sqlite3CorruptError(int lineno){
  123054. testcase( sqlite3GlobalConfig.xLog!=0 );
  123055. sqlite3_log(SQLITE_CORRUPT,
  123056. "database corruption at line %d of [%.10s]",
  123057. lineno, 20+sqlite3_sourceid());
  123058. return SQLITE_CORRUPT;
  123059. }
  123060. SQLITE_PRIVATE int sqlite3MisuseError(int lineno){
  123061. testcase( sqlite3GlobalConfig.xLog!=0 );
  123062. sqlite3_log(SQLITE_MISUSE,
  123063. "misuse at line %d of [%.10s]",
  123064. lineno, 20+sqlite3_sourceid());
  123065. return SQLITE_MISUSE;
  123066. }
  123067. SQLITE_PRIVATE int sqlite3CantopenError(int lineno){
  123068. testcase( sqlite3GlobalConfig.xLog!=0 );
  123069. sqlite3_log(SQLITE_CANTOPEN,
  123070. "cannot open file at line %d of [%.10s]",
  123071. lineno, 20+sqlite3_sourceid());
  123072. return SQLITE_CANTOPEN;
  123073. }
  123074. #ifndef SQLITE_OMIT_DEPRECATED
  123075. /*
  123076. ** This is a convenience routine that makes sure that all thread-specific
  123077. ** data for this thread has been deallocated.
  123078. **
  123079. ** SQLite no longer uses thread-specific data so this routine is now a
  123080. ** no-op. It is retained for historical compatibility.
  123081. */
  123082. SQLITE_API void SQLITE_STDCALL sqlite3_thread_cleanup(void){
  123083. }
  123084. #endif
  123085. /*
  123086. ** Return meta information about a specific column of a database table.
  123087. ** See comment in sqlite3.h (sqlite.h.in) for details.
  123088. */
  123089. SQLITE_API int SQLITE_STDCALL sqlite3_table_column_metadata(
  123090. sqlite3 *db, /* Connection handle */
  123091. const char *zDbName, /* Database name or NULL */
  123092. const char *zTableName, /* Table name */
  123093. const char *zColumnName, /* Column name */
  123094. char const **pzDataType, /* OUTPUT: Declared data type */
  123095. char const **pzCollSeq, /* OUTPUT: Collation sequence name */
  123096. int *pNotNull, /* OUTPUT: True if NOT NULL constraint exists */
  123097. int *pPrimaryKey, /* OUTPUT: True if column part of PK */
  123098. int *pAutoinc /* OUTPUT: True if column is auto-increment */
  123099. ){
  123100. int rc;
  123101. char *zErrMsg = 0;
  123102. Table *pTab = 0;
  123103. Column *pCol = 0;
  123104. int iCol = 0;
  123105. char const *zDataType = 0;
  123106. char const *zCollSeq = 0;
  123107. int notnull = 0;
  123108. int primarykey = 0;
  123109. int autoinc = 0;
  123110. #ifdef SQLITE_ENABLE_API_ARMOR
  123111. if( !sqlite3SafetyCheckOk(db) || zTableName==0 ){
  123112. return SQLITE_MISUSE_BKPT;
  123113. }
  123114. #endif
  123115. /* Ensure the database schema has been loaded */
  123116. sqlite3_mutex_enter(db->mutex);
  123117. sqlite3BtreeEnterAll(db);
  123118. rc = sqlite3Init(db, &zErrMsg);
  123119. if( SQLITE_OK!=rc ){
  123120. goto error_out;
  123121. }
  123122. /* Locate the table in question */
  123123. pTab = sqlite3FindTable(db, zTableName, zDbName);
  123124. if( !pTab || pTab->pSelect ){
  123125. pTab = 0;
  123126. goto error_out;
  123127. }
  123128. /* Find the column for which info is requested */
  123129. if( zColumnName==0 ){
  123130. /* Query for existance of table only */
  123131. }else{
  123132. for(iCol=0; iCol<pTab->nCol; iCol++){
  123133. pCol = &pTab->aCol[iCol];
  123134. if( 0==sqlite3StrICmp(pCol->zName, zColumnName) ){
  123135. break;
  123136. }
  123137. }
  123138. if( iCol==pTab->nCol ){
  123139. if( HasRowid(pTab) && sqlite3IsRowid(zColumnName) ){
  123140. iCol = pTab->iPKey;
  123141. pCol = iCol>=0 ? &pTab->aCol[iCol] : 0;
  123142. }else{
  123143. pTab = 0;
  123144. goto error_out;
  123145. }
  123146. }
  123147. }
  123148. /* The following block stores the meta information that will be returned
  123149. ** to the caller in local variables zDataType, zCollSeq, notnull, primarykey
  123150. ** and autoinc. At this point there are two possibilities:
  123151. **
  123152. ** 1. The specified column name was rowid", "oid" or "_rowid_"
  123153. ** and there is no explicitly declared IPK column.
  123154. **
  123155. ** 2. The table is not a view and the column name identified an
  123156. ** explicitly declared column. Copy meta information from *pCol.
  123157. */
  123158. if( pCol ){
  123159. zDataType = pCol->zType;
  123160. zCollSeq = pCol->zColl;
  123161. notnull = pCol->notNull!=0;
  123162. primarykey = (pCol->colFlags & COLFLAG_PRIMKEY)!=0;
  123163. autoinc = pTab->iPKey==iCol && (pTab->tabFlags & TF_Autoincrement)!=0;
  123164. }else{
  123165. zDataType = "INTEGER";
  123166. primarykey = 1;
  123167. }
  123168. if( !zCollSeq ){
  123169. zCollSeq = "BINARY";
  123170. }
  123171. error_out:
  123172. sqlite3BtreeLeaveAll(db);
  123173. /* Whether the function call succeeded or failed, set the output parameters
  123174. ** to whatever their local counterparts contain. If an error did occur,
  123175. ** this has the effect of zeroing all output parameters.
  123176. */
  123177. if( pzDataType ) *pzDataType = zDataType;
  123178. if( pzCollSeq ) *pzCollSeq = zCollSeq;
  123179. if( pNotNull ) *pNotNull = notnull;
  123180. if( pPrimaryKey ) *pPrimaryKey = primarykey;
  123181. if( pAutoinc ) *pAutoinc = autoinc;
  123182. if( SQLITE_OK==rc && !pTab ){
  123183. sqlite3DbFree(db, zErrMsg);
  123184. zErrMsg = sqlite3MPrintf(db, "no such table column: %s.%s", zTableName,
  123185. zColumnName);
  123186. rc = SQLITE_ERROR;
  123187. }
  123188. sqlite3ErrorWithMsg(db, rc, (zErrMsg?"%s":0), zErrMsg);
  123189. sqlite3DbFree(db, zErrMsg);
  123190. rc = sqlite3ApiExit(db, rc);
  123191. sqlite3_mutex_leave(db->mutex);
  123192. return rc;
  123193. }
  123194. /*
  123195. ** Sleep for a little while. Return the amount of time slept.
  123196. */
  123197. SQLITE_API int SQLITE_STDCALL sqlite3_sleep(int ms){
  123198. sqlite3_vfs *pVfs;
  123199. int rc;
  123200. pVfs = sqlite3_vfs_find(0);
  123201. if( pVfs==0 ) return 0;
  123202. /* This function works in milliseconds, but the underlying OsSleep()
  123203. ** API uses microseconds. Hence the 1000's.
  123204. */
  123205. rc = (sqlite3OsSleep(pVfs, 1000*ms)/1000);
  123206. return rc;
  123207. }
  123208. /*
  123209. ** Enable or disable the extended result codes.
  123210. */
  123211. SQLITE_API int SQLITE_STDCALL sqlite3_extended_result_codes(sqlite3 *db, int onoff){
  123212. #ifdef SQLITE_ENABLE_API_ARMOR
  123213. if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
  123214. #endif
  123215. sqlite3_mutex_enter(db->mutex);
  123216. db->errMask = onoff ? 0xffffffff : 0xff;
  123217. sqlite3_mutex_leave(db->mutex);
  123218. return SQLITE_OK;
  123219. }
  123220. /*
  123221. ** Invoke the xFileControl method on a particular database.
  123222. */
  123223. SQLITE_API int SQLITE_STDCALL sqlite3_file_control(sqlite3 *db, const char *zDbName, int op, void *pArg){
  123224. int rc = SQLITE_ERROR;
  123225. Btree *pBtree;
  123226. #ifdef SQLITE_ENABLE_API_ARMOR
  123227. if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
  123228. #endif
  123229. sqlite3_mutex_enter(db->mutex);
  123230. pBtree = sqlite3DbNameToBtree(db, zDbName);
  123231. if( pBtree ){
  123232. Pager *pPager;
  123233. sqlite3_file *fd;
  123234. sqlite3BtreeEnter(pBtree);
  123235. pPager = sqlite3BtreePager(pBtree);
  123236. assert( pPager!=0 );
  123237. fd = sqlite3PagerFile(pPager);
  123238. assert( fd!=0 );
  123239. if( op==SQLITE_FCNTL_FILE_POINTER ){
  123240. *(sqlite3_file**)pArg = fd;
  123241. rc = SQLITE_OK;
  123242. }else if( fd->pMethods ){
  123243. rc = sqlite3OsFileControl(fd, op, pArg);
  123244. }else{
  123245. rc = SQLITE_NOTFOUND;
  123246. }
  123247. sqlite3BtreeLeave(pBtree);
  123248. }
  123249. sqlite3_mutex_leave(db->mutex);
  123250. return rc;
  123251. }
  123252. /*
  123253. ** Interface to the testing logic.
  123254. */
  123255. SQLITE_API int SQLITE_CDECL sqlite3_test_control(int op, ...){
  123256. int rc = 0;
  123257. #ifndef SQLITE_OMIT_BUILTIN_TEST
  123258. va_list ap;
  123259. va_start(ap, op);
  123260. switch( op ){
  123261. /*
  123262. ** Save the current state of the PRNG.
  123263. */
  123264. case SQLITE_TESTCTRL_PRNG_SAVE: {
  123265. sqlite3PrngSaveState();
  123266. break;
  123267. }
  123268. /*
  123269. ** Restore the state of the PRNG to the last state saved using
  123270. ** PRNG_SAVE. If PRNG_SAVE has never before been called, then
  123271. ** this verb acts like PRNG_RESET.
  123272. */
  123273. case SQLITE_TESTCTRL_PRNG_RESTORE: {
  123274. sqlite3PrngRestoreState();
  123275. break;
  123276. }
  123277. /*
  123278. ** Reset the PRNG back to its uninitialized state. The next call
  123279. ** to sqlite3_randomness() will reseed the PRNG using a single call
  123280. ** to the xRandomness method of the default VFS.
  123281. */
  123282. case SQLITE_TESTCTRL_PRNG_RESET: {
  123283. sqlite3_randomness(0,0);
  123284. break;
  123285. }
  123286. /*
  123287. ** sqlite3_test_control(BITVEC_TEST, size, program)
  123288. **
  123289. ** Run a test against a Bitvec object of size. The program argument
  123290. ** is an array of integers that defines the test. Return -1 on a
  123291. ** memory allocation error, 0 on success, or non-zero for an error.
  123292. ** See the sqlite3BitvecBuiltinTest() for additional information.
  123293. */
  123294. case SQLITE_TESTCTRL_BITVEC_TEST: {
  123295. int sz = va_arg(ap, int);
  123296. int *aProg = va_arg(ap, int*);
  123297. rc = sqlite3BitvecBuiltinTest(sz, aProg);
  123298. break;
  123299. }
  123300. /*
  123301. ** sqlite3_test_control(FAULT_INSTALL, xCallback)
  123302. **
  123303. ** Arrange to invoke xCallback() whenever sqlite3FaultSim() is called,
  123304. ** if xCallback is not NULL.
  123305. **
  123306. ** As a test of the fault simulator mechanism itself, sqlite3FaultSim(0)
  123307. ** is called immediately after installing the new callback and the return
  123308. ** value from sqlite3FaultSim(0) becomes the return from
  123309. ** sqlite3_test_control().
  123310. */
  123311. case SQLITE_TESTCTRL_FAULT_INSTALL: {
  123312. /* MSVC is picky about pulling func ptrs from va lists.
  123313. ** http://support.microsoft.com/kb/47961
  123314. ** sqlite3GlobalConfig.xTestCallback = va_arg(ap, int(*)(int));
  123315. */
  123316. typedef int(*TESTCALLBACKFUNC_t)(int);
  123317. sqlite3GlobalConfig.xTestCallback = va_arg(ap, TESTCALLBACKFUNC_t);
  123318. rc = sqlite3FaultSim(0);
  123319. break;
  123320. }
  123321. /*
  123322. ** sqlite3_test_control(BENIGN_MALLOC_HOOKS, xBegin, xEnd)
  123323. **
  123324. ** Register hooks to call to indicate which malloc() failures
  123325. ** are benign.
  123326. */
  123327. case SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS: {
  123328. typedef void (*void_function)(void);
  123329. void_function xBenignBegin;
  123330. void_function xBenignEnd;
  123331. xBenignBegin = va_arg(ap, void_function);
  123332. xBenignEnd = va_arg(ap, void_function);
  123333. sqlite3BenignMallocHooks(xBenignBegin, xBenignEnd);
  123334. break;
  123335. }
  123336. /*
  123337. ** sqlite3_test_control(SQLITE_TESTCTRL_PENDING_BYTE, unsigned int X)
  123338. **
  123339. ** Set the PENDING byte to the value in the argument, if X>0.
  123340. ** Make no changes if X==0. Return the value of the pending byte
  123341. ** as it existing before this routine was called.
  123342. **
  123343. ** IMPORTANT: Changing the PENDING byte from 0x40000000 results in
  123344. ** an incompatible database file format. Changing the PENDING byte
  123345. ** while any database connection is open results in undefined and
  123346. ** deleterious behavior.
  123347. */
  123348. case SQLITE_TESTCTRL_PENDING_BYTE: {
  123349. rc = PENDING_BYTE;
  123350. #ifndef SQLITE_OMIT_WSD
  123351. {
  123352. unsigned int newVal = va_arg(ap, unsigned int);
  123353. if( newVal ) sqlite3PendingByte = newVal;
  123354. }
  123355. #endif
  123356. break;
  123357. }
  123358. /*
  123359. ** sqlite3_test_control(SQLITE_TESTCTRL_ASSERT, int X)
  123360. **
  123361. ** This action provides a run-time test to see whether or not
  123362. ** assert() was enabled at compile-time. If X is true and assert()
  123363. ** is enabled, then the return value is true. If X is true and
  123364. ** assert() is disabled, then the return value is zero. If X is
  123365. ** false and assert() is enabled, then the assertion fires and the
  123366. ** process aborts. If X is false and assert() is disabled, then the
  123367. ** return value is zero.
  123368. */
  123369. case SQLITE_TESTCTRL_ASSERT: {
  123370. volatile int x = 0;
  123371. assert( (x = va_arg(ap,int))!=0 );
  123372. rc = x;
  123373. break;
  123374. }
  123375. /*
  123376. ** sqlite3_test_control(SQLITE_TESTCTRL_ALWAYS, int X)
  123377. **
  123378. ** This action provides a run-time test to see how the ALWAYS and
  123379. ** NEVER macros were defined at compile-time.
  123380. **
  123381. ** The return value is ALWAYS(X).
  123382. **
  123383. ** The recommended test is X==2. If the return value is 2, that means
  123384. ** ALWAYS() and NEVER() are both no-op pass-through macros, which is the
  123385. ** default setting. If the return value is 1, then ALWAYS() is either
  123386. ** hard-coded to true or else it asserts if its argument is false.
  123387. ** The first behavior (hard-coded to true) is the case if
  123388. ** SQLITE_TESTCTRL_ASSERT shows that assert() is disabled and the second
  123389. ** behavior (assert if the argument to ALWAYS() is false) is the case if
  123390. ** SQLITE_TESTCTRL_ASSERT shows that assert() is enabled.
  123391. **
  123392. ** The run-time test procedure might look something like this:
  123393. **
  123394. ** if( sqlite3_test_control(SQLITE_TESTCTRL_ALWAYS, 2)==2 ){
  123395. ** // ALWAYS() and NEVER() are no-op pass-through macros
  123396. ** }else if( sqlite3_test_control(SQLITE_TESTCTRL_ASSERT, 1) ){
  123397. ** // ALWAYS(x) asserts that x is true. NEVER(x) asserts x is false.
  123398. ** }else{
  123399. ** // ALWAYS(x) is a constant 1. NEVER(x) is a constant 0.
  123400. ** }
  123401. */
  123402. case SQLITE_TESTCTRL_ALWAYS: {
  123403. int x = va_arg(ap,int);
  123404. rc = ALWAYS(x);
  123405. break;
  123406. }
  123407. /*
  123408. ** sqlite3_test_control(SQLITE_TESTCTRL_BYTEORDER);
  123409. **
  123410. ** The integer returned reveals the byte-order of the computer on which
  123411. ** SQLite is running:
  123412. **
  123413. ** 1 big-endian, determined at run-time
  123414. ** 10 little-endian, determined at run-time
  123415. ** 432101 big-endian, determined at compile-time
  123416. ** 123410 little-endian, determined at compile-time
  123417. */
  123418. case SQLITE_TESTCTRL_BYTEORDER: {
  123419. rc = SQLITE_BYTEORDER*100 + SQLITE_LITTLEENDIAN*10 + SQLITE_BIGENDIAN;
  123420. break;
  123421. }
  123422. /* sqlite3_test_control(SQLITE_TESTCTRL_RESERVE, sqlite3 *db, int N)
  123423. **
  123424. ** Set the nReserve size to N for the main database on the database
  123425. ** connection db.
  123426. */
  123427. case SQLITE_TESTCTRL_RESERVE: {
  123428. sqlite3 *db = va_arg(ap, sqlite3*);
  123429. int x = va_arg(ap,int);
  123430. sqlite3_mutex_enter(db->mutex);
  123431. sqlite3BtreeSetPageSize(db->aDb[0].pBt, 0, x, 0);
  123432. sqlite3_mutex_leave(db->mutex);
  123433. break;
  123434. }
  123435. /* sqlite3_test_control(SQLITE_TESTCTRL_OPTIMIZATIONS, sqlite3 *db, int N)
  123436. **
  123437. ** Enable or disable various optimizations for testing purposes. The
  123438. ** argument N is a bitmask of optimizations to be disabled. For normal
  123439. ** operation N should be 0. The idea is that a test program (like the
  123440. ** SQL Logic Test or SLT test module) can run the same SQL multiple times
  123441. ** with various optimizations disabled to verify that the same answer
  123442. ** is obtained in every case.
  123443. */
  123444. case SQLITE_TESTCTRL_OPTIMIZATIONS: {
  123445. sqlite3 *db = va_arg(ap, sqlite3*);
  123446. db->dbOptFlags = (u16)(va_arg(ap, int) & 0xffff);
  123447. break;
  123448. }
  123449. #ifdef SQLITE_N_KEYWORD
  123450. /* sqlite3_test_control(SQLITE_TESTCTRL_ISKEYWORD, const char *zWord)
  123451. **
  123452. ** If zWord is a keyword recognized by the parser, then return the
  123453. ** number of keywords. Or if zWord is not a keyword, return 0.
  123454. **
  123455. ** This test feature is only available in the amalgamation since
  123456. ** the SQLITE_N_KEYWORD macro is not defined in this file if SQLite
  123457. ** is built using separate source files.
  123458. */
  123459. case SQLITE_TESTCTRL_ISKEYWORD: {
  123460. const char *zWord = va_arg(ap, const char*);
  123461. int n = sqlite3Strlen30(zWord);
  123462. rc = (sqlite3KeywordCode((u8*)zWord, n)!=TK_ID) ? SQLITE_N_KEYWORD : 0;
  123463. break;
  123464. }
  123465. #endif
  123466. /* sqlite3_test_control(SQLITE_TESTCTRL_SCRATCHMALLOC, sz, &pNew, pFree);
  123467. **
  123468. ** Pass pFree into sqlite3ScratchFree().
  123469. ** If sz>0 then allocate a scratch buffer into pNew.
  123470. */
  123471. case SQLITE_TESTCTRL_SCRATCHMALLOC: {
  123472. void *pFree, **ppNew;
  123473. int sz;
  123474. sz = va_arg(ap, int);
  123475. ppNew = va_arg(ap, void**);
  123476. pFree = va_arg(ap, void*);
  123477. if( sz ) *ppNew = sqlite3ScratchMalloc(sz);
  123478. sqlite3ScratchFree(pFree);
  123479. break;
  123480. }
  123481. /* sqlite3_test_control(SQLITE_TESTCTRL_LOCALTIME_FAULT, int onoff);
  123482. **
  123483. ** If parameter onoff is non-zero, configure the wrappers so that all
  123484. ** subsequent calls to localtime() and variants fail. If onoff is zero,
  123485. ** undo this setting.
  123486. */
  123487. case SQLITE_TESTCTRL_LOCALTIME_FAULT: {
  123488. sqlite3GlobalConfig.bLocaltimeFault = va_arg(ap, int);
  123489. break;
  123490. }
  123491. /* sqlite3_test_control(SQLITE_TESTCTRL_NEVER_CORRUPT, int);
  123492. **
  123493. ** Set or clear a flag that indicates that the database file is always well-
  123494. ** formed and never corrupt. This flag is clear by default, indicating that
  123495. ** database files might have arbitrary corruption. Setting the flag during
  123496. ** testing causes certain assert() statements in the code to be activated
  123497. ** that demonstrat invariants on well-formed database files.
  123498. */
  123499. case SQLITE_TESTCTRL_NEVER_CORRUPT: {
  123500. sqlite3GlobalConfig.neverCorrupt = va_arg(ap, int);
  123501. break;
  123502. }
  123503. /* sqlite3_test_control(SQLITE_TESTCTRL_VDBE_COVERAGE, xCallback, ptr);
  123504. **
  123505. ** Set the VDBE coverage callback function to xCallback with context
  123506. ** pointer ptr.
  123507. */
  123508. case SQLITE_TESTCTRL_VDBE_COVERAGE: {
  123509. #ifdef SQLITE_VDBE_COVERAGE
  123510. typedef void (*branch_callback)(void*,int,u8,u8);
  123511. sqlite3GlobalConfig.xVdbeBranch = va_arg(ap,branch_callback);
  123512. sqlite3GlobalConfig.pVdbeBranchArg = va_arg(ap,void*);
  123513. #endif
  123514. break;
  123515. }
  123516. /* sqlite3_test_control(SQLITE_TESTCTRL_SORTER_MMAP, db, nMax); */
  123517. case SQLITE_TESTCTRL_SORTER_MMAP: {
  123518. sqlite3 *db = va_arg(ap, sqlite3*);
  123519. db->nMaxSorterMmap = va_arg(ap, int);
  123520. break;
  123521. }
  123522. /* sqlite3_test_control(SQLITE_TESTCTRL_ISINIT);
  123523. **
  123524. ** Return SQLITE_OK if SQLite has been initialized and SQLITE_ERROR if
  123525. ** not.
  123526. */
  123527. case SQLITE_TESTCTRL_ISINIT: {
  123528. if( sqlite3GlobalConfig.isInit==0 ) rc = SQLITE_ERROR;
  123529. break;
  123530. }
  123531. /* sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, db, dbName, onOff, tnum);
  123532. **
  123533. ** This test control is used to create imposter tables. "db" is a pointer
  123534. ** to the database connection. dbName is the database name (ex: "main" or
  123535. ** "temp") which will receive the imposter. "onOff" turns imposter mode on
  123536. ** or off. "tnum" is the root page of the b-tree to which the imposter
  123537. ** table should connect.
  123538. **
  123539. ** Enable imposter mode only when the schema has already been parsed. Then
  123540. ** run a single CREATE TABLE statement to construct the imposter table in
  123541. ** the parsed schema. Then turn imposter mode back off again.
  123542. **
  123543. ** If onOff==0 and tnum>0 then reset the schema for all databases, causing
  123544. ** the schema to be reparsed the next time it is needed. This has the
  123545. ** effect of erasing all imposter tables.
  123546. */
  123547. case SQLITE_TESTCTRL_IMPOSTER: {
  123548. sqlite3 *db = va_arg(ap, sqlite3*);
  123549. sqlite3_mutex_enter(db->mutex);
  123550. db->init.iDb = sqlite3FindDbName(db, va_arg(ap,const char*));
  123551. db->init.busy = db->init.imposterTable = va_arg(ap,int);
  123552. db->init.newTnum = va_arg(ap,int);
  123553. if( db->init.busy==0 && db->init.newTnum>0 ){
  123554. sqlite3ResetAllSchemasOfConnection(db);
  123555. }
  123556. sqlite3_mutex_leave(db->mutex);
  123557. break;
  123558. }
  123559. }
  123560. va_end(ap);
  123561. #endif /* SQLITE_OMIT_BUILTIN_TEST */
  123562. return rc;
  123563. }
  123564. /*
  123565. ** This is a utility routine, useful to VFS implementations, that checks
  123566. ** to see if a database file was a URI that contained a specific query
  123567. ** parameter, and if so obtains the value of the query parameter.
  123568. **
  123569. ** The zFilename argument is the filename pointer passed into the xOpen()
  123570. ** method of a VFS implementation. The zParam argument is the name of the
  123571. ** query parameter we seek. This routine returns the value of the zParam
  123572. ** parameter if it exists. If the parameter does not exist, this routine
  123573. ** returns a NULL pointer.
  123574. */
  123575. SQLITE_API const char *SQLITE_STDCALL sqlite3_uri_parameter(const char *zFilename, const char *zParam){
  123576. if( zFilename==0 || zParam==0 ) return 0;
  123577. zFilename += sqlite3Strlen30(zFilename) + 1;
  123578. while( zFilename[0] ){
  123579. int x = strcmp(zFilename, zParam);
  123580. zFilename += sqlite3Strlen30(zFilename) + 1;
  123581. if( x==0 ) return zFilename;
  123582. zFilename += sqlite3Strlen30(zFilename) + 1;
  123583. }
  123584. return 0;
  123585. }
  123586. /*
  123587. ** Return a boolean value for a query parameter.
  123588. */
  123589. SQLITE_API int SQLITE_STDCALL sqlite3_uri_boolean(const char *zFilename, const char *zParam, int bDflt){
  123590. const char *z = sqlite3_uri_parameter(zFilename, zParam);
  123591. bDflt = bDflt!=0;
  123592. return z ? sqlite3GetBoolean(z, bDflt) : bDflt;
  123593. }
  123594. /*
  123595. ** Return a 64-bit integer value for a query parameter.
  123596. */
  123597. SQLITE_API sqlite3_int64 SQLITE_STDCALL sqlite3_uri_int64(
  123598. const char *zFilename, /* Filename as passed to xOpen */
  123599. const char *zParam, /* URI parameter sought */
  123600. sqlite3_int64 bDflt /* return if parameter is missing */
  123601. ){
  123602. const char *z = sqlite3_uri_parameter(zFilename, zParam);
  123603. sqlite3_int64 v;
  123604. if( z && sqlite3DecOrHexToI64(z, &v)==SQLITE_OK ){
  123605. bDflt = v;
  123606. }
  123607. return bDflt;
  123608. }
  123609. /*
  123610. ** Return the Btree pointer identified by zDbName. Return NULL if not found.
  123611. */
  123612. SQLITE_PRIVATE Btree *sqlite3DbNameToBtree(sqlite3 *db, const char *zDbName){
  123613. int i;
  123614. for(i=0; i<db->nDb; i++){
  123615. if( db->aDb[i].pBt
  123616. && (zDbName==0 || sqlite3StrICmp(zDbName, db->aDb[i].zName)==0)
  123617. ){
  123618. return db->aDb[i].pBt;
  123619. }
  123620. }
  123621. return 0;
  123622. }
  123623. /*
  123624. ** Return the filename of the database associated with a database
  123625. ** connection.
  123626. */
  123627. SQLITE_API const char *SQLITE_STDCALL sqlite3_db_filename(sqlite3 *db, const char *zDbName){
  123628. Btree *pBt;
  123629. #ifdef SQLITE_ENABLE_API_ARMOR
  123630. if( !sqlite3SafetyCheckOk(db) ){
  123631. (void)SQLITE_MISUSE_BKPT;
  123632. return 0;
  123633. }
  123634. #endif
  123635. pBt = sqlite3DbNameToBtree(db, zDbName);
  123636. return pBt ? sqlite3BtreeGetFilename(pBt) : 0;
  123637. }
  123638. /*
  123639. ** Return 1 if database is read-only or 0 if read/write. Return -1 if
  123640. ** no such database exists.
  123641. */
  123642. SQLITE_API int SQLITE_STDCALL sqlite3_db_readonly(sqlite3 *db, const char *zDbName){
  123643. Btree *pBt;
  123644. #ifdef SQLITE_ENABLE_API_ARMOR
  123645. if( !sqlite3SafetyCheckOk(db) ){
  123646. (void)SQLITE_MISUSE_BKPT;
  123647. return -1;
  123648. }
  123649. #endif
  123650. pBt = sqlite3DbNameToBtree(db, zDbName);
  123651. return pBt ? sqlite3BtreeIsReadonly(pBt) : -1;
  123652. }
  123653. /************** End of main.c ************************************************/
  123654. /************** Begin file notify.c ******************************************/
  123655. /*
  123656. ** 2009 March 3
  123657. **
  123658. ** The author disclaims copyright to this source code. In place of
  123659. ** a legal notice, here is a blessing:
  123660. **
  123661. ** May you do good and not evil.
  123662. ** May you find forgiveness for yourself and forgive others.
  123663. ** May you share freely, never taking more than you give.
  123664. **
  123665. *************************************************************************
  123666. **
  123667. ** This file contains the implementation of the sqlite3_unlock_notify()
  123668. ** API method and its associated functionality.
  123669. */
  123670. /* Omit this entire file if SQLITE_ENABLE_UNLOCK_NOTIFY is not defined. */
  123671. #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
  123672. /*
  123673. ** Public interfaces:
  123674. **
  123675. ** sqlite3ConnectionBlocked()
  123676. ** sqlite3ConnectionUnlocked()
  123677. ** sqlite3ConnectionClosed()
  123678. ** sqlite3_unlock_notify()
  123679. */
  123680. #define assertMutexHeld() \
  123681. assert( sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER)) )
  123682. /*
  123683. ** Head of a linked list of all sqlite3 objects created by this process
  123684. ** for which either sqlite3.pBlockingConnection or sqlite3.pUnlockConnection
  123685. ** is not NULL. This variable may only accessed while the STATIC_MASTER
  123686. ** mutex is held.
  123687. */
  123688. static sqlite3 *SQLITE_WSD sqlite3BlockedList = 0;
  123689. #ifndef NDEBUG
  123690. /*
  123691. ** This function is a complex assert() that verifies the following
  123692. ** properties of the blocked connections list:
  123693. **
  123694. ** 1) Each entry in the list has a non-NULL value for either
  123695. ** pUnlockConnection or pBlockingConnection, or both.
  123696. **
  123697. ** 2) All entries in the list that share a common value for
  123698. ** xUnlockNotify are grouped together.
  123699. **
  123700. ** 3) If the argument db is not NULL, then none of the entries in the
  123701. ** blocked connections list have pUnlockConnection or pBlockingConnection
  123702. ** set to db. This is used when closing connection db.
  123703. */
  123704. static void checkListProperties(sqlite3 *db){
  123705. sqlite3 *p;
  123706. for(p=sqlite3BlockedList; p; p=p->pNextBlocked){
  123707. int seen = 0;
  123708. sqlite3 *p2;
  123709. /* Verify property (1) */
  123710. assert( p->pUnlockConnection || p->pBlockingConnection );
  123711. /* Verify property (2) */
  123712. for(p2=sqlite3BlockedList; p2!=p; p2=p2->pNextBlocked){
  123713. if( p2->xUnlockNotify==p->xUnlockNotify ) seen = 1;
  123714. assert( p2->xUnlockNotify==p->xUnlockNotify || !seen );
  123715. assert( db==0 || p->pUnlockConnection!=db );
  123716. assert( db==0 || p->pBlockingConnection!=db );
  123717. }
  123718. }
  123719. }
  123720. #else
  123721. # define checkListProperties(x)
  123722. #endif
  123723. /*
  123724. ** Remove connection db from the blocked connections list. If connection
  123725. ** db is not currently a part of the list, this function is a no-op.
  123726. */
  123727. static void removeFromBlockedList(sqlite3 *db){
  123728. sqlite3 **pp;
  123729. assertMutexHeld();
  123730. for(pp=&sqlite3BlockedList; *pp; pp = &(*pp)->pNextBlocked){
  123731. if( *pp==db ){
  123732. *pp = (*pp)->pNextBlocked;
  123733. break;
  123734. }
  123735. }
  123736. }
  123737. /*
  123738. ** Add connection db to the blocked connections list. It is assumed
  123739. ** that it is not already a part of the list.
  123740. */
  123741. static void addToBlockedList(sqlite3 *db){
  123742. sqlite3 **pp;
  123743. assertMutexHeld();
  123744. for(
  123745. pp=&sqlite3BlockedList;
  123746. *pp && (*pp)->xUnlockNotify!=db->xUnlockNotify;
  123747. pp=&(*pp)->pNextBlocked
  123748. );
  123749. db->pNextBlocked = *pp;
  123750. *pp = db;
  123751. }
  123752. /*
  123753. ** Obtain the STATIC_MASTER mutex.
  123754. */
  123755. static void enterMutex(void){
  123756. sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
  123757. checkListProperties(0);
  123758. }
  123759. /*
  123760. ** Release the STATIC_MASTER mutex.
  123761. */
  123762. static void leaveMutex(void){
  123763. assertMutexHeld();
  123764. checkListProperties(0);
  123765. sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
  123766. }
  123767. /*
  123768. ** Register an unlock-notify callback.
  123769. **
  123770. ** This is called after connection "db" has attempted some operation
  123771. ** but has received an SQLITE_LOCKED error because another connection
  123772. ** (call it pOther) in the same process was busy using the same shared
  123773. ** cache. pOther is found by looking at db->pBlockingConnection.
  123774. **
  123775. ** If there is no blocking connection, the callback is invoked immediately,
  123776. ** before this routine returns.
  123777. **
  123778. ** If pOther is already blocked on db, then report SQLITE_LOCKED, to indicate
  123779. ** a deadlock.
  123780. **
  123781. ** Otherwise, make arrangements to invoke xNotify when pOther drops
  123782. ** its locks.
  123783. **
  123784. ** Each call to this routine overrides any prior callbacks registered
  123785. ** on the same "db". If xNotify==0 then any prior callbacks are immediately
  123786. ** cancelled.
  123787. */
  123788. SQLITE_API int SQLITE_STDCALL sqlite3_unlock_notify(
  123789. sqlite3 *db,
  123790. void (*xNotify)(void **, int),
  123791. void *pArg
  123792. ){
  123793. int rc = SQLITE_OK;
  123794. sqlite3_mutex_enter(db->mutex);
  123795. enterMutex();
  123796. if( xNotify==0 ){
  123797. removeFromBlockedList(db);
  123798. db->pBlockingConnection = 0;
  123799. db->pUnlockConnection = 0;
  123800. db->xUnlockNotify = 0;
  123801. db->pUnlockArg = 0;
  123802. }else if( 0==db->pBlockingConnection ){
  123803. /* The blocking transaction has been concluded. Or there never was a
  123804. ** blocking transaction. In either case, invoke the notify callback
  123805. ** immediately.
  123806. */
  123807. xNotify(&pArg, 1);
  123808. }else{
  123809. sqlite3 *p;
  123810. for(p=db->pBlockingConnection; p && p!=db; p=p->pUnlockConnection){}
  123811. if( p ){
  123812. rc = SQLITE_LOCKED; /* Deadlock detected. */
  123813. }else{
  123814. db->pUnlockConnection = db->pBlockingConnection;
  123815. db->xUnlockNotify = xNotify;
  123816. db->pUnlockArg = pArg;
  123817. removeFromBlockedList(db);
  123818. addToBlockedList(db);
  123819. }
  123820. }
  123821. leaveMutex();
  123822. assert( !db->mallocFailed );
  123823. sqlite3ErrorWithMsg(db, rc, (rc?"database is deadlocked":0));
  123824. sqlite3_mutex_leave(db->mutex);
  123825. return rc;
  123826. }
  123827. /*
  123828. ** This function is called while stepping or preparing a statement
  123829. ** associated with connection db. The operation will return SQLITE_LOCKED
  123830. ** to the user because it requires a lock that will not be available
  123831. ** until connection pBlocker concludes its current transaction.
  123832. */
  123833. SQLITE_PRIVATE void sqlite3ConnectionBlocked(sqlite3 *db, sqlite3 *pBlocker){
  123834. enterMutex();
  123835. if( db->pBlockingConnection==0 && db->pUnlockConnection==0 ){
  123836. addToBlockedList(db);
  123837. }
  123838. db->pBlockingConnection = pBlocker;
  123839. leaveMutex();
  123840. }
  123841. /*
  123842. ** This function is called when
  123843. ** the transaction opened by database db has just finished. Locks held
  123844. ** by database connection db have been released.
  123845. **
  123846. ** This function loops through each entry in the blocked connections
  123847. ** list and does the following:
  123848. **
  123849. ** 1) If the sqlite3.pBlockingConnection member of a list entry is
  123850. ** set to db, then set pBlockingConnection=0.
  123851. **
  123852. ** 2) If the sqlite3.pUnlockConnection member of a list entry is
  123853. ** set to db, then invoke the configured unlock-notify callback and
  123854. ** set pUnlockConnection=0.
  123855. **
  123856. ** 3) If the two steps above mean that pBlockingConnection==0 and
  123857. ** pUnlockConnection==0, remove the entry from the blocked connections
  123858. ** list.
  123859. */
  123860. SQLITE_PRIVATE void sqlite3ConnectionUnlocked(sqlite3 *db){
  123861. void (*xUnlockNotify)(void **, int) = 0; /* Unlock-notify cb to invoke */
  123862. int nArg = 0; /* Number of entries in aArg[] */
  123863. sqlite3 **pp; /* Iterator variable */
  123864. void **aArg; /* Arguments to the unlock callback */
  123865. void **aDyn = 0; /* Dynamically allocated space for aArg[] */
  123866. void *aStatic[16]; /* Starter space for aArg[]. No malloc required */
  123867. aArg = aStatic;
  123868. enterMutex(); /* Enter STATIC_MASTER mutex */
  123869. /* This loop runs once for each entry in the blocked-connections list. */
  123870. for(pp=&sqlite3BlockedList; *pp; /* no-op */ ){
  123871. sqlite3 *p = *pp;
  123872. /* Step 1. */
  123873. if( p->pBlockingConnection==db ){
  123874. p->pBlockingConnection = 0;
  123875. }
  123876. /* Step 2. */
  123877. if( p->pUnlockConnection==db ){
  123878. assert( p->xUnlockNotify );
  123879. if( p->xUnlockNotify!=xUnlockNotify && nArg!=0 ){
  123880. xUnlockNotify(aArg, nArg);
  123881. nArg = 0;
  123882. }
  123883. sqlite3BeginBenignMalloc();
  123884. assert( aArg==aDyn || (aDyn==0 && aArg==aStatic) );
  123885. assert( nArg<=(int)ArraySize(aStatic) || aArg==aDyn );
  123886. if( (!aDyn && nArg==(int)ArraySize(aStatic))
  123887. || (aDyn && nArg==(int)(sqlite3MallocSize(aDyn)/sizeof(void*)))
  123888. ){
  123889. /* The aArg[] array needs to grow. */
  123890. void **pNew = (void **)sqlite3Malloc(nArg*sizeof(void *)*2);
  123891. if( pNew ){
  123892. memcpy(pNew, aArg, nArg*sizeof(void *));
  123893. sqlite3_free(aDyn);
  123894. aDyn = aArg = pNew;
  123895. }else{
  123896. /* This occurs when the array of context pointers that need to
  123897. ** be passed to the unlock-notify callback is larger than the
  123898. ** aStatic[] array allocated on the stack and the attempt to
  123899. ** allocate a larger array from the heap has failed.
  123900. **
  123901. ** This is a difficult situation to handle. Returning an error
  123902. ** code to the caller is insufficient, as even if an error code
  123903. ** is returned the transaction on connection db will still be
  123904. ** closed and the unlock-notify callbacks on blocked connections
  123905. ** will go unissued. This might cause the application to wait
  123906. ** indefinitely for an unlock-notify callback that will never
  123907. ** arrive.
  123908. **
  123909. ** Instead, invoke the unlock-notify callback with the context
  123910. ** array already accumulated. We can then clear the array and
  123911. ** begin accumulating any further context pointers without
  123912. ** requiring any dynamic allocation. This is sub-optimal because
  123913. ** it means that instead of one callback with a large array of
  123914. ** context pointers the application will receive two or more
  123915. ** callbacks with smaller arrays of context pointers, which will
  123916. ** reduce the applications ability to prioritize multiple
  123917. ** connections. But it is the best that can be done under the
  123918. ** circumstances.
  123919. */
  123920. xUnlockNotify(aArg, nArg);
  123921. nArg = 0;
  123922. }
  123923. }
  123924. sqlite3EndBenignMalloc();
  123925. aArg[nArg++] = p->pUnlockArg;
  123926. xUnlockNotify = p->xUnlockNotify;
  123927. p->pUnlockConnection = 0;
  123928. p->xUnlockNotify = 0;
  123929. p->pUnlockArg = 0;
  123930. }
  123931. /* Step 3. */
  123932. if( p->pBlockingConnection==0 && p->pUnlockConnection==0 ){
  123933. /* Remove connection p from the blocked connections list. */
  123934. *pp = p->pNextBlocked;
  123935. p->pNextBlocked = 0;
  123936. }else{
  123937. pp = &p->pNextBlocked;
  123938. }
  123939. }
  123940. if( nArg!=0 ){
  123941. xUnlockNotify(aArg, nArg);
  123942. }
  123943. sqlite3_free(aDyn);
  123944. leaveMutex(); /* Leave STATIC_MASTER mutex */
  123945. }
  123946. /*
  123947. ** This is called when the database connection passed as an argument is
  123948. ** being closed. The connection is removed from the blocked list.
  123949. */
  123950. SQLITE_PRIVATE void sqlite3ConnectionClosed(sqlite3 *db){
  123951. sqlite3ConnectionUnlocked(db);
  123952. enterMutex();
  123953. removeFromBlockedList(db);
  123954. checkListProperties(db);
  123955. leaveMutex();
  123956. }
  123957. #endif
  123958. /************** End of notify.c **********************************************/
  123959. /************** Begin file fts3.c ********************************************/
  123960. /*
  123961. ** 2006 Oct 10
  123962. **
  123963. ** The author disclaims copyright to this source code. In place of
  123964. ** a legal notice, here is a blessing:
  123965. **
  123966. ** May you do good and not evil.
  123967. ** May you find forgiveness for yourself and forgive others.
  123968. ** May you share freely, never taking more than you give.
  123969. **
  123970. ******************************************************************************
  123971. **
  123972. ** This is an SQLite module implementing full-text search.
  123973. */
  123974. /*
  123975. ** The code in this file is only compiled if:
  123976. **
  123977. ** * The FTS3 module is being built as an extension
  123978. ** (in which case SQLITE_CORE is not defined), or
  123979. **
  123980. ** * The FTS3 module is being built into the core of
  123981. ** SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
  123982. */
  123983. /* The full-text index is stored in a series of b+tree (-like)
  123984. ** structures called segments which map terms to doclists. The
  123985. ** structures are like b+trees in layout, but are constructed from the
  123986. ** bottom up in optimal fashion and are not updatable. Since trees
  123987. ** are built from the bottom up, things will be described from the
  123988. ** bottom up.
  123989. **
  123990. **
  123991. **** Varints ****
  123992. ** The basic unit of encoding is a variable-length integer called a
  123993. ** varint. We encode variable-length integers in little-endian order
  123994. ** using seven bits * per byte as follows:
  123995. **
  123996. ** KEY:
  123997. ** A = 0xxxxxxx 7 bits of data and one flag bit
  123998. ** B = 1xxxxxxx 7 bits of data and one flag bit
  123999. **
  124000. ** 7 bits - A
  124001. ** 14 bits - BA
  124002. ** 21 bits - BBA
  124003. ** and so on.
  124004. **
  124005. ** This is similar in concept to how sqlite encodes "varints" but
  124006. ** the encoding is not the same. SQLite varints are big-endian
  124007. ** are are limited to 9 bytes in length whereas FTS3 varints are
  124008. ** little-endian and can be up to 10 bytes in length (in theory).
  124009. **
  124010. ** Example encodings:
  124011. **
  124012. ** 1: 0x01
  124013. ** 127: 0x7f
  124014. ** 128: 0x81 0x00
  124015. **
  124016. **
  124017. **** Document lists ****
  124018. ** A doclist (document list) holds a docid-sorted list of hits for a
  124019. ** given term. Doclists hold docids and associated token positions.
  124020. ** A docid is the unique integer identifier for a single document.
  124021. ** A position is the index of a word within the document. The first
  124022. ** word of the document has a position of 0.
  124023. **
  124024. ** FTS3 used to optionally store character offsets using a compile-time
  124025. ** option. But that functionality is no longer supported.
  124026. **
  124027. ** A doclist is stored like this:
  124028. **
  124029. ** array {
  124030. ** varint docid; (delta from previous doclist)
  124031. ** array { (position list for column 0)
  124032. ** varint position; (2 more than the delta from previous position)
  124033. ** }
  124034. ** array {
  124035. ** varint POS_COLUMN; (marks start of position list for new column)
  124036. ** varint column; (index of new column)
  124037. ** array {
  124038. ** varint position; (2 more than the delta from previous position)
  124039. ** }
  124040. ** }
  124041. ** varint POS_END; (marks end of positions for this document.
  124042. ** }
  124043. **
  124044. ** Here, array { X } means zero or more occurrences of X, adjacent in
  124045. ** memory. A "position" is an index of a token in the token stream
  124046. ** generated by the tokenizer. Note that POS_END and POS_COLUMN occur
  124047. ** in the same logical place as the position element, and act as sentinals
  124048. ** ending a position list array. POS_END is 0. POS_COLUMN is 1.
  124049. ** The positions numbers are not stored literally but rather as two more
  124050. ** than the difference from the prior position, or the just the position plus
  124051. ** 2 for the first position. Example:
  124052. **
  124053. ** label: A B C D E F G H I J K
  124054. ** value: 123 5 9 1 1 14 35 0 234 72 0
  124055. **
  124056. ** The 123 value is the first docid. For column zero in this document
  124057. ** there are two matches at positions 3 and 10 (5-2 and 9-2+3). The 1
  124058. ** at D signals the start of a new column; the 1 at E indicates that the
  124059. ** new column is column number 1. There are two positions at 12 and 45
  124060. ** (14-2 and 35-2+12). The 0 at H indicate the end-of-document. The
  124061. ** 234 at I is the delta to next docid (357). It has one position 70
  124062. ** (72-2) and then terminates with the 0 at K.
  124063. **
  124064. ** A "position-list" is the list of positions for multiple columns for
  124065. ** a single docid. A "column-list" is the set of positions for a single
  124066. ** column. Hence, a position-list consists of one or more column-lists,
  124067. ** a document record consists of a docid followed by a position-list and
  124068. ** a doclist consists of one or more document records.
  124069. **
  124070. ** A bare doclist omits the position information, becoming an
  124071. ** array of varint-encoded docids.
  124072. **
  124073. **** Segment leaf nodes ****
  124074. ** Segment leaf nodes store terms and doclists, ordered by term. Leaf
  124075. ** nodes are written using LeafWriter, and read using LeafReader (to
  124076. ** iterate through a single leaf node's data) and LeavesReader (to
  124077. ** iterate through a segment's entire leaf layer). Leaf nodes have
  124078. ** the format:
  124079. **
  124080. ** varint iHeight; (height from leaf level, always 0)
  124081. ** varint nTerm; (length of first term)
  124082. ** char pTerm[nTerm]; (content of first term)
  124083. ** varint nDoclist; (length of term's associated doclist)
  124084. ** char pDoclist[nDoclist]; (content of doclist)
  124085. ** array {
  124086. ** (further terms are delta-encoded)
  124087. ** varint nPrefix; (length of prefix shared with previous term)
  124088. ** varint nSuffix; (length of unshared suffix)
  124089. ** char pTermSuffix[nSuffix];(unshared suffix of next term)
  124090. ** varint nDoclist; (length of term's associated doclist)
  124091. ** char pDoclist[nDoclist]; (content of doclist)
  124092. ** }
  124093. **
  124094. ** Here, array { X } means zero or more occurrences of X, adjacent in
  124095. ** memory.
  124096. **
  124097. ** Leaf nodes are broken into blocks which are stored contiguously in
  124098. ** the %_segments table in sorted order. This means that when the end
  124099. ** of a node is reached, the next term is in the node with the next
  124100. ** greater node id.
  124101. **
  124102. ** New data is spilled to a new leaf node when the current node
  124103. ** exceeds LEAF_MAX bytes (default 2048). New data which itself is
  124104. ** larger than STANDALONE_MIN (default 1024) is placed in a standalone
  124105. ** node (a leaf node with a single term and doclist). The goal of
  124106. ** these settings is to pack together groups of small doclists while
  124107. ** making it efficient to directly access large doclists. The
  124108. ** assumption is that large doclists represent terms which are more
  124109. ** likely to be query targets.
  124110. **
  124111. ** TODO(shess) It may be useful for blocking decisions to be more
  124112. ** dynamic. For instance, it may make more sense to have a 2.5k leaf
  124113. ** node rather than splitting into 2k and .5k nodes. My intuition is
  124114. ** that this might extend through 2x or 4x the pagesize.
  124115. **
  124116. **
  124117. **** Segment interior nodes ****
  124118. ** Segment interior nodes store blockids for subtree nodes and terms
  124119. ** to describe what data is stored by the each subtree. Interior
  124120. ** nodes are written using InteriorWriter, and read using
  124121. ** InteriorReader. InteriorWriters are created as needed when
  124122. ** SegmentWriter creates new leaf nodes, or when an interior node
  124123. ** itself grows too big and must be split. The format of interior
  124124. ** nodes:
  124125. **
  124126. ** varint iHeight; (height from leaf level, always >0)
  124127. ** varint iBlockid; (block id of node's leftmost subtree)
  124128. ** optional {
  124129. ** varint nTerm; (length of first term)
  124130. ** char pTerm[nTerm]; (content of first term)
  124131. ** array {
  124132. ** (further terms are delta-encoded)
  124133. ** varint nPrefix; (length of shared prefix with previous term)
  124134. ** varint nSuffix; (length of unshared suffix)
  124135. ** char pTermSuffix[nSuffix]; (unshared suffix of next term)
  124136. ** }
  124137. ** }
  124138. **
  124139. ** Here, optional { X } means an optional element, while array { X }
  124140. ** means zero or more occurrences of X, adjacent in memory.
  124141. **
  124142. ** An interior node encodes n terms separating n+1 subtrees. The
  124143. ** subtree blocks are contiguous, so only the first subtree's blockid
  124144. ** is encoded. The subtree at iBlockid will contain all terms less
  124145. ** than the first term encoded (or all terms if no term is encoded).
  124146. ** Otherwise, for terms greater than or equal to pTerm[i] but less
  124147. ** than pTerm[i+1], the subtree for that term will be rooted at
  124148. ** iBlockid+i. Interior nodes only store enough term data to
  124149. ** distinguish adjacent children (if the rightmost term of the left
  124150. ** child is "something", and the leftmost term of the right child is
  124151. ** "wicked", only "w" is stored).
  124152. **
  124153. ** New data is spilled to a new interior node at the same height when
  124154. ** the current node exceeds INTERIOR_MAX bytes (default 2048).
  124155. ** INTERIOR_MIN_TERMS (default 7) keeps large terms from monopolizing
  124156. ** interior nodes and making the tree too skinny. The interior nodes
  124157. ** at a given height are naturally tracked by interior nodes at
  124158. ** height+1, and so on.
  124159. **
  124160. **
  124161. **** Segment directory ****
  124162. ** The segment directory in table %_segdir stores meta-information for
  124163. ** merging and deleting segments, and also the root node of the
  124164. ** segment's tree.
  124165. **
  124166. ** The root node is the top node of the segment's tree after encoding
  124167. ** the entire segment, restricted to ROOT_MAX bytes (default 1024).
  124168. ** This could be either a leaf node or an interior node. If the top
  124169. ** node requires more than ROOT_MAX bytes, it is flushed to %_segments
  124170. ** and a new root interior node is generated (which should always fit
  124171. ** within ROOT_MAX because it only needs space for 2 varints, the
  124172. ** height and the blockid of the previous root).
  124173. **
  124174. ** The meta-information in the segment directory is:
  124175. ** level - segment level (see below)
  124176. ** idx - index within level
  124177. ** - (level,idx uniquely identify a segment)
  124178. ** start_block - first leaf node
  124179. ** leaves_end_block - last leaf node
  124180. ** end_block - last block (including interior nodes)
  124181. ** root - contents of root node
  124182. **
  124183. ** If the root node is a leaf node, then start_block,
  124184. ** leaves_end_block, and end_block are all 0.
  124185. **
  124186. **
  124187. **** Segment merging ****
  124188. ** To amortize update costs, segments are grouped into levels and
  124189. ** merged in batches. Each increase in level represents exponentially
  124190. ** more documents.
  124191. **
  124192. ** New documents (actually, document updates) are tokenized and
  124193. ** written individually (using LeafWriter) to a level 0 segment, with
  124194. ** incrementing idx. When idx reaches MERGE_COUNT (default 16), all
  124195. ** level 0 segments are merged into a single level 1 segment. Level 1
  124196. ** is populated like level 0, and eventually MERGE_COUNT level 1
  124197. ** segments are merged to a single level 2 segment (representing
  124198. ** MERGE_COUNT^2 updates), and so on.
  124199. **
  124200. ** A segment merge traverses all segments at a given level in
  124201. ** parallel, performing a straightforward sorted merge. Since segment
  124202. ** leaf nodes are written in to the %_segments table in order, this
  124203. ** merge traverses the underlying sqlite disk structures efficiently.
  124204. ** After the merge, all segment blocks from the merged level are
  124205. ** deleted.
  124206. **
  124207. ** MERGE_COUNT controls how often we merge segments. 16 seems to be
  124208. ** somewhat of a sweet spot for insertion performance. 32 and 64 show
  124209. ** very similar performance numbers to 16 on insertion, though they're
  124210. ** a tiny bit slower (perhaps due to more overhead in merge-time
  124211. ** sorting). 8 is about 20% slower than 16, 4 about 50% slower than
  124212. ** 16, 2 about 66% slower than 16.
  124213. **
  124214. ** At query time, high MERGE_COUNT increases the number of segments
  124215. ** which need to be scanned and merged. For instance, with 100k docs
  124216. ** inserted:
  124217. **
  124218. ** MERGE_COUNT segments
  124219. ** 16 25
  124220. ** 8 12
  124221. ** 4 10
  124222. ** 2 6
  124223. **
  124224. ** This appears to have only a moderate impact on queries for very
  124225. ** frequent terms (which are somewhat dominated by segment merge
  124226. ** costs), and infrequent and non-existent terms still seem to be fast
  124227. ** even with many segments.
  124228. **
  124229. ** TODO(shess) That said, it would be nice to have a better query-side
  124230. ** argument for MERGE_COUNT of 16. Also, it is possible/likely that
  124231. ** optimizations to things like doclist merging will swing the sweet
  124232. ** spot around.
  124233. **
  124234. **
  124235. **
  124236. **** Handling of deletions and updates ****
  124237. ** Since we're using a segmented structure, with no docid-oriented
  124238. ** index into the term index, we clearly cannot simply update the term
  124239. ** index when a document is deleted or updated. For deletions, we
  124240. ** write an empty doclist (varint(docid) varint(POS_END)), for updates
  124241. ** we simply write the new doclist. Segment merges overwrite older
  124242. ** data for a particular docid with newer data, so deletes or updates
  124243. ** will eventually overtake the earlier data and knock it out. The
  124244. ** query logic likewise merges doclists so that newer data knocks out
  124245. ** older data.
  124246. */
  124247. /************** Include fts3Int.h in the middle of fts3.c ********************/
  124248. /************** Begin file fts3Int.h *****************************************/
  124249. /*
  124250. ** 2009 Nov 12
  124251. **
  124252. ** The author disclaims copyright to this source code. In place of
  124253. ** a legal notice, here is a blessing:
  124254. **
  124255. ** May you do good and not evil.
  124256. ** May you find forgiveness for yourself and forgive others.
  124257. ** May you share freely, never taking more than you give.
  124258. **
  124259. ******************************************************************************
  124260. **
  124261. */
  124262. #ifndef _FTSINT_H
  124263. #define _FTSINT_H
  124264. #if !defined(NDEBUG) && !defined(SQLITE_DEBUG)
  124265. # define NDEBUG 1
  124266. #endif
  124267. /*
  124268. ** FTS4 is really an extension for FTS3. It is enabled using the
  124269. ** SQLITE_ENABLE_FTS3 macro. But to avoid confusion we also all
  124270. ** the SQLITE_ENABLE_FTS4 macro to serve as an alisse for SQLITE_ENABLE_FTS3.
  124271. */
  124272. #if defined(SQLITE_ENABLE_FTS4) && !defined(SQLITE_ENABLE_FTS3)
  124273. # define SQLITE_ENABLE_FTS3
  124274. #endif
  124275. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  124276. /* If not building as part of the core, include sqlite3ext.h. */
  124277. #ifndef SQLITE_CORE
  124278. SQLITE_EXTENSION_INIT3
  124279. #endif
  124280. /************** Include fts3_tokenizer.h in the middle of fts3Int.h **********/
  124281. /************** Begin file fts3_tokenizer.h **********************************/
  124282. /*
  124283. ** 2006 July 10
  124284. **
  124285. ** The author disclaims copyright to this source code.
  124286. **
  124287. *************************************************************************
  124288. ** Defines the interface to tokenizers used by fulltext-search. There
  124289. ** are three basic components:
  124290. **
  124291. ** sqlite3_tokenizer_module is a singleton defining the tokenizer
  124292. ** interface functions. This is essentially the class structure for
  124293. ** tokenizers.
  124294. **
  124295. ** sqlite3_tokenizer is used to define a particular tokenizer, perhaps
  124296. ** including customization information defined at creation time.
  124297. **
  124298. ** sqlite3_tokenizer_cursor is generated by a tokenizer to generate
  124299. ** tokens from a particular input.
  124300. */
  124301. #ifndef _FTS3_TOKENIZER_H_
  124302. #define _FTS3_TOKENIZER_H_
  124303. /* TODO(shess) Only used for SQLITE_OK and SQLITE_DONE at this time.
  124304. ** If tokenizers are to be allowed to call sqlite3_*() functions, then
  124305. ** we will need a way to register the API consistently.
  124306. */
  124307. /*
  124308. ** Structures used by the tokenizer interface. When a new tokenizer
  124309. ** implementation is registered, the caller provides a pointer to
  124310. ** an sqlite3_tokenizer_module containing pointers to the callback
  124311. ** functions that make up an implementation.
  124312. **
  124313. ** When an fts3 table is created, it passes any arguments passed to
  124314. ** the tokenizer clause of the CREATE VIRTUAL TABLE statement to the
  124315. ** sqlite3_tokenizer_module.xCreate() function of the requested tokenizer
  124316. ** implementation. The xCreate() function in turn returns an
  124317. ** sqlite3_tokenizer structure representing the specific tokenizer to
  124318. ** be used for the fts3 table (customized by the tokenizer clause arguments).
  124319. **
  124320. ** To tokenize an input buffer, the sqlite3_tokenizer_module.xOpen()
  124321. ** method is called. It returns an sqlite3_tokenizer_cursor object
  124322. ** that may be used to tokenize a specific input buffer based on
  124323. ** the tokenization rules supplied by a specific sqlite3_tokenizer
  124324. ** object.
  124325. */
  124326. typedef struct sqlite3_tokenizer_module sqlite3_tokenizer_module;
  124327. typedef struct sqlite3_tokenizer sqlite3_tokenizer;
  124328. typedef struct sqlite3_tokenizer_cursor sqlite3_tokenizer_cursor;
  124329. struct sqlite3_tokenizer_module {
  124330. /*
  124331. ** Structure version. Should always be set to 0 or 1.
  124332. */
  124333. int iVersion;
  124334. /*
  124335. ** Create a new tokenizer. The values in the argv[] array are the
  124336. ** arguments passed to the "tokenizer" clause of the CREATE VIRTUAL
  124337. ** TABLE statement that created the fts3 table. For example, if
  124338. ** the following SQL is executed:
  124339. **
  124340. ** CREATE .. USING fts3( ... , tokenizer <tokenizer-name> arg1 arg2)
  124341. **
  124342. ** then argc is set to 2, and the argv[] array contains pointers
  124343. ** to the strings "arg1" and "arg2".
  124344. **
  124345. ** This method should return either SQLITE_OK (0), or an SQLite error
  124346. ** code. If SQLITE_OK is returned, then *ppTokenizer should be set
  124347. ** to point at the newly created tokenizer structure. The generic
  124348. ** sqlite3_tokenizer.pModule variable should not be initialized by
  124349. ** this callback. The caller will do so.
  124350. */
  124351. int (*xCreate)(
  124352. int argc, /* Size of argv array */
  124353. const char *const*argv, /* Tokenizer argument strings */
  124354. sqlite3_tokenizer **ppTokenizer /* OUT: Created tokenizer */
  124355. );
  124356. /*
  124357. ** Destroy an existing tokenizer. The fts3 module calls this method
  124358. ** exactly once for each successful call to xCreate().
  124359. */
  124360. int (*xDestroy)(sqlite3_tokenizer *pTokenizer);
  124361. /*
  124362. ** Create a tokenizer cursor to tokenize an input buffer. The caller
  124363. ** is responsible for ensuring that the input buffer remains valid
  124364. ** until the cursor is closed (using the xClose() method).
  124365. */
  124366. int (*xOpen)(
  124367. sqlite3_tokenizer *pTokenizer, /* Tokenizer object */
  124368. const char *pInput, int nBytes, /* Input buffer */
  124369. sqlite3_tokenizer_cursor **ppCursor /* OUT: Created tokenizer cursor */
  124370. );
  124371. /*
  124372. ** Destroy an existing tokenizer cursor. The fts3 module calls this
  124373. ** method exactly once for each successful call to xOpen().
  124374. */
  124375. int (*xClose)(sqlite3_tokenizer_cursor *pCursor);
  124376. /*
  124377. ** Retrieve the next token from the tokenizer cursor pCursor. This
  124378. ** method should either return SQLITE_OK and set the values of the
  124379. ** "OUT" variables identified below, or SQLITE_DONE to indicate that
  124380. ** the end of the buffer has been reached, or an SQLite error code.
  124381. **
  124382. ** *ppToken should be set to point at a buffer containing the
  124383. ** normalized version of the token (i.e. after any case-folding and/or
  124384. ** stemming has been performed). *pnBytes should be set to the length
  124385. ** of this buffer in bytes. The input text that generated the token is
  124386. ** identified by the byte offsets returned in *piStartOffset and
  124387. ** *piEndOffset. *piStartOffset should be set to the index of the first
  124388. ** byte of the token in the input buffer. *piEndOffset should be set
  124389. ** to the index of the first byte just past the end of the token in
  124390. ** the input buffer.
  124391. **
  124392. ** The buffer *ppToken is set to point at is managed by the tokenizer
  124393. ** implementation. It is only required to be valid until the next call
  124394. ** to xNext() or xClose().
  124395. */
  124396. /* TODO(shess) current implementation requires pInput to be
  124397. ** nul-terminated. This should either be fixed, or pInput/nBytes
  124398. ** should be converted to zInput.
  124399. */
  124400. int (*xNext)(
  124401. sqlite3_tokenizer_cursor *pCursor, /* Tokenizer cursor */
  124402. const char **ppToken, int *pnBytes, /* OUT: Normalized text for token */
  124403. int *piStartOffset, /* OUT: Byte offset of token in input buffer */
  124404. int *piEndOffset, /* OUT: Byte offset of end of token in input buffer */
  124405. int *piPosition /* OUT: Number of tokens returned before this one */
  124406. );
  124407. /***********************************************************************
  124408. ** Methods below this point are only available if iVersion>=1.
  124409. */
  124410. /*
  124411. ** Configure the language id of a tokenizer cursor.
  124412. */
  124413. int (*xLanguageid)(sqlite3_tokenizer_cursor *pCsr, int iLangid);
  124414. };
  124415. struct sqlite3_tokenizer {
  124416. const sqlite3_tokenizer_module *pModule; /* The module for this tokenizer */
  124417. /* Tokenizer implementations will typically add additional fields */
  124418. };
  124419. struct sqlite3_tokenizer_cursor {
  124420. sqlite3_tokenizer *pTokenizer; /* Tokenizer for this cursor. */
  124421. /* Tokenizer implementations will typically add additional fields */
  124422. };
  124423. int fts3_global_term_cnt(int iTerm, int iCol);
  124424. int fts3_term_cnt(int iTerm, int iCol);
  124425. #endif /* _FTS3_TOKENIZER_H_ */
  124426. /************** End of fts3_tokenizer.h **************************************/
  124427. /************** Continuing where we left off in fts3Int.h ********************/
  124428. /************** Include fts3_hash.h in the middle of fts3Int.h ***************/
  124429. /************** Begin file fts3_hash.h ***************************************/
  124430. /*
  124431. ** 2001 September 22
  124432. **
  124433. ** The author disclaims copyright to this source code. In place of
  124434. ** a legal notice, here is a blessing:
  124435. **
  124436. ** May you do good and not evil.
  124437. ** May you find forgiveness for yourself and forgive others.
  124438. ** May you share freely, never taking more than you give.
  124439. **
  124440. *************************************************************************
  124441. ** This is the header file for the generic hash-table implementation
  124442. ** used in SQLite. We've modified it slightly to serve as a standalone
  124443. ** hash table implementation for the full-text indexing module.
  124444. **
  124445. */
  124446. #ifndef _FTS3_HASH_H_
  124447. #define _FTS3_HASH_H_
  124448. /* Forward declarations of structures. */
  124449. typedef struct Fts3Hash Fts3Hash;
  124450. typedef struct Fts3HashElem Fts3HashElem;
  124451. /* A complete hash table is an instance of the following structure.
  124452. ** The internals of this structure are intended to be opaque -- client
  124453. ** code should not attempt to access or modify the fields of this structure
  124454. ** directly. Change this structure only by using the routines below.
  124455. ** However, many of the "procedures" and "functions" for modifying and
  124456. ** accessing this structure are really macros, so we can't really make
  124457. ** this structure opaque.
  124458. */
  124459. struct Fts3Hash {
  124460. char keyClass; /* HASH_INT, _POINTER, _STRING, _BINARY */
  124461. char copyKey; /* True if copy of key made on insert */
  124462. int count; /* Number of entries in this table */
  124463. Fts3HashElem *first; /* The first element of the array */
  124464. int htsize; /* Number of buckets in the hash table */
  124465. struct _fts3ht { /* the hash table */
  124466. int count; /* Number of entries with this hash */
  124467. Fts3HashElem *chain; /* Pointer to first entry with this hash */
  124468. } *ht;
  124469. };
  124470. /* Each element in the hash table is an instance of the following
  124471. ** structure. All elements are stored on a single doubly-linked list.
  124472. **
  124473. ** Again, this structure is intended to be opaque, but it can't really
  124474. ** be opaque because it is used by macros.
  124475. */
  124476. struct Fts3HashElem {
  124477. Fts3HashElem *next, *prev; /* Next and previous elements in the table */
  124478. void *data; /* Data associated with this element */
  124479. void *pKey; int nKey; /* Key associated with this element */
  124480. };
  124481. /*
  124482. ** There are 2 different modes of operation for a hash table:
  124483. **
  124484. ** FTS3_HASH_STRING pKey points to a string that is nKey bytes long
  124485. ** (including the null-terminator, if any). Case
  124486. ** is respected in comparisons.
  124487. **
  124488. ** FTS3_HASH_BINARY pKey points to binary data nKey bytes long.
  124489. ** memcmp() is used to compare keys.
  124490. **
  124491. ** A copy of the key is made if the copyKey parameter to fts3HashInit is 1.
  124492. */
  124493. #define FTS3_HASH_STRING 1
  124494. #define FTS3_HASH_BINARY 2
  124495. /*
  124496. ** Access routines. To delete, insert a NULL pointer.
  124497. */
  124498. SQLITE_PRIVATE void sqlite3Fts3HashInit(Fts3Hash *pNew, char keyClass, char copyKey);
  124499. SQLITE_PRIVATE void *sqlite3Fts3HashInsert(Fts3Hash*, const void *pKey, int nKey, void *pData);
  124500. SQLITE_PRIVATE void *sqlite3Fts3HashFind(const Fts3Hash*, const void *pKey, int nKey);
  124501. SQLITE_PRIVATE void sqlite3Fts3HashClear(Fts3Hash*);
  124502. SQLITE_PRIVATE Fts3HashElem *sqlite3Fts3HashFindElem(const Fts3Hash *, const void *, int);
  124503. /*
  124504. ** Shorthand for the functions above
  124505. */
  124506. #define fts3HashInit sqlite3Fts3HashInit
  124507. #define fts3HashInsert sqlite3Fts3HashInsert
  124508. #define fts3HashFind sqlite3Fts3HashFind
  124509. #define fts3HashClear sqlite3Fts3HashClear
  124510. #define fts3HashFindElem sqlite3Fts3HashFindElem
  124511. /*
  124512. ** Macros for looping over all elements of a hash table. The idiom is
  124513. ** like this:
  124514. **
  124515. ** Fts3Hash h;
  124516. ** Fts3HashElem *p;
  124517. ** ...
  124518. ** for(p=fts3HashFirst(&h); p; p=fts3HashNext(p)){
  124519. ** SomeStructure *pData = fts3HashData(p);
  124520. ** // do something with pData
  124521. ** }
  124522. */
  124523. #define fts3HashFirst(H) ((H)->first)
  124524. #define fts3HashNext(E) ((E)->next)
  124525. #define fts3HashData(E) ((E)->data)
  124526. #define fts3HashKey(E) ((E)->pKey)
  124527. #define fts3HashKeysize(E) ((E)->nKey)
  124528. /*
  124529. ** Number of entries in a hash table
  124530. */
  124531. #define fts3HashCount(H) ((H)->count)
  124532. #endif /* _FTS3_HASH_H_ */
  124533. /************** End of fts3_hash.h *******************************************/
  124534. /************** Continuing where we left off in fts3Int.h ********************/
  124535. /*
  124536. ** This constant determines the maximum depth of an FTS expression tree
  124537. ** that the library will create and use. FTS uses recursion to perform
  124538. ** various operations on the query tree, so the disadvantage of a large
  124539. ** limit is that it may allow very large queries to use large amounts
  124540. ** of stack space (perhaps causing a stack overflow).
  124541. */
  124542. #ifndef SQLITE_FTS3_MAX_EXPR_DEPTH
  124543. # define SQLITE_FTS3_MAX_EXPR_DEPTH 12
  124544. #endif
  124545. /*
  124546. ** This constant controls how often segments are merged. Once there are
  124547. ** FTS3_MERGE_COUNT segments of level N, they are merged into a single
  124548. ** segment of level N+1.
  124549. */
  124550. #define FTS3_MERGE_COUNT 16
  124551. /*
  124552. ** This is the maximum amount of data (in bytes) to store in the
  124553. ** Fts3Table.pendingTerms hash table. Normally, the hash table is
  124554. ** populated as documents are inserted/updated/deleted in a transaction
  124555. ** and used to create a new segment when the transaction is committed.
  124556. ** However if this limit is reached midway through a transaction, a new
  124557. ** segment is created and the hash table cleared immediately.
  124558. */
  124559. #define FTS3_MAX_PENDING_DATA (1*1024*1024)
  124560. /*
  124561. ** Macro to return the number of elements in an array. SQLite has a
  124562. ** similar macro called ArraySize(). Use a different name to avoid
  124563. ** a collision when building an amalgamation with built-in FTS3.
  124564. */
  124565. #define SizeofArray(X) ((int)(sizeof(X)/sizeof(X[0])))
  124566. #ifndef MIN
  124567. # define MIN(x,y) ((x)<(y)?(x):(y))
  124568. #endif
  124569. #ifndef MAX
  124570. # define MAX(x,y) ((x)>(y)?(x):(y))
  124571. #endif
  124572. /*
  124573. ** Maximum length of a varint encoded integer. The varint format is different
  124574. ** from that used by SQLite, so the maximum length is 10, not 9.
  124575. */
  124576. #define FTS3_VARINT_MAX 10
  124577. /*
  124578. ** FTS4 virtual tables may maintain multiple indexes - one index of all terms
  124579. ** in the document set and zero or more prefix indexes. All indexes are stored
  124580. ** as one or more b+-trees in the %_segments and %_segdir tables.
  124581. **
  124582. ** It is possible to determine which index a b+-tree belongs to based on the
  124583. ** value stored in the "%_segdir.level" column. Given this value L, the index
  124584. ** that the b+-tree belongs to is (L<<10). In other words, all b+-trees with
  124585. ** level values between 0 and 1023 (inclusive) belong to index 0, all levels
  124586. ** between 1024 and 2047 to index 1, and so on.
  124587. **
  124588. ** It is considered impossible for an index to use more than 1024 levels. In
  124589. ** theory though this may happen, but only after at least
  124590. ** (FTS3_MERGE_COUNT^1024) separate flushes of the pending-terms tables.
  124591. */
  124592. #define FTS3_SEGDIR_MAXLEVEL 1024
  124593. #define FTS3_SEGDIR_MAXLEVEL_STR "1024"
  124594. /*
  124595. ** The testcase() macro is only used by the amalgamation. If undefined,
  124596. ** make it a no-op.
  124597. */
  124598. #ifndef testcase
  124599. # define testcase(X)
  124600. #endif
  124601. /*
  124602. ** Terminator values for position-lists and column-lists.
  124603. */
  124604. #define POS_COLUMN (1) /* Column-list terminator */
  124605. #define POS_END (0) /* Position-list terminator */
  124606. /*
  124607. ** This section provides definitions to allow the
  124608. ** FTS3 extension to be compiled outside of the
  124609. ** amalgamation.
  124610. */
  124611. #ifndef SQLITE_AMALGAMATION
  124612. /*
  124613. ** Macros indicating that conditional expressions are always true or
  124614. ** false.
  124615. */
  124616. #ifdef SQLITE_COVERAGE_TEST
  124617. # define ALWAYS(x) (1)
  124618. # define NEVER(X) (0)
  124619. #elif defined(SQLITE_DEBUG)
  124620. # define ALWAYS(x) sqlite3Fts3Always((x)!=0)
  124621. # define NEVER(x) sqlite3Fts3Never((x)!=0)
  124622. SQLITE_PRIVATE int sqlite3Fts3Always(int b);
  124623. SQLITE_PRIVATE int sqlite3Fts3Never(int b);
  124624. #else
  124625. # define ALWAYS(x) (x)
  124626. # define NEVER(x) (x)
  124627. #endif
  124628. /*
  124629. ** Internal types used by SQLite.
  124630. */
  124631. typedef unsigned char u8; /* 1-byte (or larger) unsigned integer */
  124632. typedef short int i16; /* 2-byte (or larger) signed integer */
  124633. typedef unsigned int u32; /* 4-byte unsigned integer */
  124634. typedef sqlite3_uint64 u64; /* 8-byte unsigned integer */
  124635. typedef sqlite3_int64 i64; /* 8-byte signed integer */
  124636. /*
  124637. ** Macro used to suppress compiler warnings for unused parameters.
  124638. */
  124639. #define UNUSED_PARAMETER(x) (void)(x)
  124640. /*
  124641. ** Activate assert() only if SQLITE_TEST is enabled.
  124642. */
  124643. #if !defined(NDEBUG) && !defined(SQLITE_DEBUG)
  124644. # define NDEBUG 1
  124645. #endif
  124646. /*
  124647. ** The TESTONLY macro is used to enclose variable declarations or
  124648. ** other bits of code that are needed to support the arguments
  124649. ** within testcase() and assert() macros.
  124650. */
  124651. #if defined(SQLITE_DEBUG) || defined(SQLITE_COVERAGE_TEST)
  124652. # define TESTONLY(X) X
  124653. #else
  124654. # define TESTONLY(X)
  124655. #endif
  124656. #endif /* SQLITE_AMALGAMATION */
  124657. #ifdef SQLITE_DEBUG
  124658. SQLITE_PRIVATE int sqlite3Fts3Corrupt(void);
  124659. # define FTS_CORRUPT_VTAB sqlite3Fts3Corrupt()
  124660. #else
  124661. # define FTS_CORRUPT_VTAB SQLITE_CORRUPT_VTAB
  124662. #endif
  124663. typedef struct Fts3Table Fts3Table;
  124664. typedef struct Fts3Cursor Fts3Cursor;
  124665. typedef struct Fts3Expr Fts3Expr;
  124666. typedef struct Fts3Phrase Fts3Phrase;
  124667. typedef struct Fts3PhraseToken Fts3PhraseToken;
  124668. typedef struct Fts3Doclist Fts3Doclist;
  124669. typedef struct Fts3SegFilter Fts3SegFilter;
  124670. typedef struct Fts3DeferredToken Fts3DeferredToken;
  124671. typedef struct Fts3SegReader Fts3SegReader;
  124672. typedef struct Fts3MultiSegReader Fts3MultiSegReader;
  124673. /*
  124674. ** A connection to a fulltext index is an instance of the following
  124675. ** structure. The xCreate and xConnect methods create an instance
  124676. ** of this structure and xDestroy and xDisconnect free that instance.
  124677. ** All other methods receive a pointer to the structure as one of their
  124678. ** arguments.
  124679. */
  124680. struct Fts3Table {
  124681. sqlite3_vtab base; /* Base class used by SQLite core */
  124682. sqlite3 *db; /* The database connection */
  124683. const char *zDb; /* logical database name */
  124684. const char *zName; /* virtual table name */
  124685. int nColumn; /* number of named columns in virtual table */
  124686. char **azColumn; /* column names. malloced */
  124687. u8 *abNotindexed; /* True for 'notindexed' columns */
  124688. sqlite3_tokenizer *pTokenizer; /* tokenizer for inserts and queries */
  124689. char *zContentTbl; /* content=xxx option, or NULL */
  124690. char *zLanguageid; /* languageid=xxx option, or NULL */
  124691. int nAutoincrmerge; /* Value configured by 'automerge' */
  124692. u32 nLeafAdd; /* Number of leaf blocks added this trans */
  124693. /* Precompiled statements used by the implementation. Each of these
  124694. ** statements is run and reset within a single virtual table API call.
  124695. */
  124696. sqlite3_stmt *aStmt[40];
  124697. char *zReadExprlist;
  124698. char *zWriteExprlist;
  124699. int nNodeSize; /* Soft limit for node size */
  124700. u8 bFts4; /* True for FTS4, false for FTS3 */
  124701. u8 bHasStat; /* True if %_stat table exists (2==unknown) */
  124702. u8 bHasDocsize; /* True if %_docsize table exists */
  124703. u8 bDescIdx; /* True if doclists are in reverse order */
  124704. u8 bIgnoreSavepoint; /* True to ignore xSavepoint invocations */
  124705. int nPgsz; /* Page size for host database */
  124706. char *zSegmentsTbl; /* Name of %_segments table */
  124707. sqlite3_blob *pSegments; /* Blob handle open on %_segments table */
  124708. /*
  124709. ** The following array of hash tables is used to buffer pending index
  124710. ** updates during transactions. All pending updates buffered at any one
  124711. ** time must share a common language-id (see the FTS4 langid= feature).
  124712. ** The current language id is stored in variable iPrevLangid.
  124713. **
  124714. ** A single FTS4 table may have multiple full-text indexes. For each index
  124715. ** there is an entry in the aIndex[] array. Index 0 is an index of all the
  124716. ** terms that appear in the document set. Each subsequent index in aIndex[]
  124717. ** is an index of prefixes of a specific length.
  124718. **
  124719. ** Variable nPendingData contains an estimate the memory consumed by the
  124720. ** pending data structures, including hash table overhead, but not including
  124721. ** malloc overhead. When nPendingData exceeds nMaxPendingData, all hash
  124722. ** tables are flushed to disk. Variable iPrevDocid is the docid of the most
  124723. ** recently inserted record.
  124724. */
  124725. int nIndex; /* Size of aIndex[] */
  124726. struct Fts3Index {
  124727. int nPrefix; /* Prefix length (0 for main terms index) */
  124728. Fts3Hash hPending; /* Pending terms table for this index */
  124729. } *aIndex;
  124730. int nMaxPendingData; /* Max pending data before flush to disk */
  124731. int nPendingData; /* Current bytes of pending data */
  124732. sqlite_int64 iPrevDocid; /* Docid of most recently inserted document */
  124733. int iPrevLangid; /* Langid of recently inserted document */
  124734. #if defined(SQLITE_DEBUG) || defined(SQLITE_COVERAGE_TEST)
  124735. /* State variables used for validating that the transaction control
  124736. ** methods of the virtual table are called at appropriate times. These
  124737. ** values do not contribute to FTS functionality; they are used for
  124738. ** verifying the operation of the SQLite core.
  124739. */
  124740. int inTransaction; /* True after xBegin but before xCommit/xRollback */
  124741. int mxSavepoint; /* Largest valid xSavepoint integer */
  124742. #endif
  124743. #ifdef SQLITE_TEST
  124744. /* True to disable the incremental doclist optimization. This is controled
  124745. ** by special insert command 'test-no-incr-doclist'. */
  124746. int bNoIncrDoclist;
  124747. #endif
  124748. };
  124749. /*
  124750. ** When the core wants to read from the virtual table, it creates a
  124751. ** virtual table cursor (an instance of the following structure) using
  124752. ** the xOpen method. Cursors are destroyed using the xClose method.
  124753. */
  124754. struct Fts3Cursor {
  124755. sqlite3_vtab_cursor base; /* Base class used by SQLite core */
  124756. i16 eSearch; /* Search strategy (see below) */
  124757. u8 isEof; /* True if at End Of Results */
  124758. u8 isRequireSeek; /* True if must seek pStmt to %_content row */
  124759. sqlite3_stmt *pStmt; /* Prepared statement in use by the cursor */
  124760. Fts3Expr *pExpr; /* Parsed MATCH query string */
  124761. int iLangid; /* Language being queried for */
  124762. int nPhrase; /* Number of matchable phrases in query */
  124763. Fts3DeferredToken *pDeferred; /* Deferred search tokens, if any */
  124764. sqlite3_int64 iPrevId; /* Previous id read from aDoclist */
  124765. char *pNextId; /* Pointer into the body of aDoclist */
  124766. char *aDoclist; /* List of docids for full-text queries */
  124767. int nDoclist; /* Size of buffer at aDoclist */
  124768. u8 bDesc; /* True to sort in descending order */
  124769. int eEvalmode; /* An FTS3_EVAL_XX constant */
  124770. int nRowAvg; /* Average size of database rows, in pages */
  124771. sqlite3_int64 nDoc; /* Documents in table */
  124772. i64 iMinDocid; /* Minimum docid to return */
  124773. i64 iMaxDocid; /* Maximum docid to return */
  124774. int isMatchinfoNeeded; /* True when aMatchinfo[] needs filling in */
  124775. u32 *aMatchinfo; /* Information about most recent match */
  124776. int nMatchinfo; /* Number of elements in aMatchinfo[] */
  124777. char *zMatchinfo; /* Matchinfo specification */
  124778. };
  124779. #define FTS3_EVAL_FILTER 0
  124780. #define FTS3_EVAL_NEXT 1
  124781. #define FTS3_EVAL_MATCHINFO 2
  124782. /*
  124783. ** The Fts3Cursor.eSearch member is always set to one of the following.
  124784. ** Actualy, Fts3Cursor.eSearch can be greater than or equal to
  124785. ** FTS3_FULLTEXT_SEARCH. If so, then Fts3Cursor.eSearch - 2 is the index
  124786. ** of the column to be searched. For example, in
  124787. **
  124788. ** CREATE VIRTUAL TABLE ex1 USING fts3(a,b,c,d);
  124789. ** SELECT docid FROM ex1 WHERE b MATCH 'one two three';
  124790. **
  124791. ** Because the LHS of the MATCH operator is 2nd column "b",
  124792. ** Fts3Cursor.eSearch will be set to FTS3_FULLTEXT_SEARCH+1. (+0 for a,
  124793. ** +1 for b, +2 for c, +3 for d.) If the LHS of MATCH were "ex1"
  124794. ** indicating that all columns should be searched,
  124795. ** then eSearch would be set to FTS3_FULLTEXT_SEARCH+4.
  124796. */
  124797. #define FTS3_FULLSCAN_SEARCH 0 /* Linear scan of %_content table */
  124798. #define FTS3_DOCID_SEARCH 1 /* Lookup by rowid on %_content table */
  124799. #define FTS3_FULLTEXT_SEARCH 2 /* Full-text index search */
  124800. /*
  124801. ** The lower 16-bits of the sqlite3_index_info.idxNum value set by
  124802. ** the xBestIndex() method contains the Fts3Cursor.eSearch value described
  124803. ** above. The upper 16-bits contain a combination of the following
  124804. ** bits, used to describe extra constraints on full-text searches.
  124805. */
  124806. #define FTS3_HAVE_LANGID 0x00010000 /* languageid=? */
  124807. #define FTS3_HAVE_DOCID_GE 0x00020000 /* docid>=? */
  124808. #define FTS3_HAVE_DOCID_LE 0x00040000 /* docid<=? */
  124809. struct Fts3Doclist {
  124810. char *aAll; /* Array containing doclist (or NULL) */
  124811. int nAll; /* Size of a[] in bytes */
  124812. char *pNextDocid; /* Pointer to next docid */
  124813. sqlite3_int64 iDocid; /* Current docid (if pList!=0) */
  124814. int bFreeList; /* True if pList should be sqlite3_free()d */
  124815. char *pList; /* Pointer to position list following iDocid */
  124816. int nList; /* Length of position list */
  124817. };
  124818. /*
  124819. ** A "phrase" is a sequence of one or more tokens that must match in
  124820. ** sequence. A single token is the base case and the most common case.
  124821. ** For a sequence of tokens contained in double-quotes (i.e. "one two three")
  124822. ** nToken will be the number of tokens in the string.
  124823. */
  124824. struct Fts3PhraseToken {
  124825. char *z; /* Text of the token */
  124826. int n; /* Number of bytes in buffer z */
  124827. int isPrefix; /* True if token ends with a "*" character */
  124828. int bFirst; /* True if token must appear at position 0 */
  124829. /* Variables above this point are populated when the expression is
  124830. ** parsed (by code in fts3_expr.c). Below this point the variables are
  124831. ** used when evaluating the expression. */
  124832. Fts3DeferredToken *pDeferred; /* Deferred token object for this token */
  124833. Fts3MultiSegReader *pSegcsr; /* Segment-reader for this token */
  124834. };
  124835. struct Fts3Phrase {
  124836. /* Cache of doclist for this phrase. */
  124837. Fts3Doclist doclist;
  124838. int bIncr; /* True if doclist is loaded incrementally */
  124839. int iDoclistToken;
  124840. /* Used by sqlite3Fts3EvalPhrasePoslist() if this is a descendent of an
  124841. ** OR condition. */
  124842. char *pOrPoslist;
  124843. i64 iOrDocid;
  124844. /* Variables below this point are populated by fts3_expr.c when parsing
  124845. ** a MATCH expression. Everything above is part of the evaluation phase.
  124846. */
  124847. int nToken; /* Number of tokens in the phrase */
  124848. int iColumn; /* Index of column this phrase must match */
  124849. Fts3PhraseToken aToken[1]; /* One entry for each token in the phrase */
  124850. };
  124851. /*
  124852. ** A tree of these objects forms the RHS of a MATCH operator.
  124853. **
  124854. ** If Fts3Expr.eType is FTSQUERY_PHRASE and isLoaded is true, then aDoclist
  124855. ** points to a malloced buffer, size nDoclist bytes, containing the results
  124856. ** of this phrase query in FTS3 doclist format. As usual, the initial
  124857. ** "Length" field found in doclists stored on disk is omitted from this
  124858. ** buffer.
  124859. **
  124860. ** Variable aMI is used only for FTSQUERY_NEAR nodes to store the global
  124861. ** matchinfo data. If it is not NULL, it points to an array of size nCol*3,
  124862. ** where nCol is the number of columns in the queried FTS table. The array
  124863. ** is populated as follows:
  124864. **
  124865. ** aMI[iCol*3 + 0] = Undefined
  124866. ** aMI[iCol*3 + 1] = Number of occurrences
  124867. ** aMI[iCol*3 + 2] = Number of rows containing at least one instance
  124868. **
  124869. ** The aMI array is allocated using sqlite3_malloc(). It should be freed
  124870. ** when the expression node is.
  124871. */
  124872. struct Fts3Expr {
  124873. int eType; /* One of the FTSQUERY_XXX values defined below */
  124874. int nNear; /* Valid if eType==FTSQUERY_NEAR */
  124875. Fts3Expr *pParent; /* pParent->pLeft==this or pParent->pRight==this */
  124876. Fts3Expr *pLeft; /* Left operand */
  124877. Fts3Expr *pRight; /* Right operand */
  124878. Fts3Phrase *pPhrase; /* Valid if eType==FTSQUERY_PHRASE */
  124879. /* The following are used by the fts3_eval.c module. */
  124880. sqlite3_int64 iDocid; /* Current docid */
  124881. u8 bEof; /* True this expression is at EOF already */
  124882. u8 bStart; /* True if iDocid is valid */
  124883. u8 bDeferred; /* True if this expression is entirely deferred */
  124884. u32 *aMI;
  124885. };
  124886. /*
  124887. ** Candidate values for Fts3Query.eType. Note that the order of the first
  124888. ** four values is in order of precedence when parsing expressions. For
  124889. ** example, the following:
  124890. **
  124891. ** "a OR b AND c NOT d NEAR e"
  124892. **
  124893. ** is equivalent to:
  124894. **
  124895. ** "a OR (b AND (c NOT (d NEAR e)))"
  124896. */
  124897. #define FTSQUERY_NEAR 1
  124898. #define FTSQUERY_NOT 2
  124899. #define FTSQUERY_AND 3
  124900. #define FTSQUERY_OR 4
  124901. #define FTSQUERY_PHRASE 5
  124902. /* fts3_write.c */
  124903. SQLITE_PRIVATE int sqlite3Fts3UpdateMethod(sqlite3_vtab*,int,sqlite3_value**,sqlite3_int64*);
  124904. SQLITE_PRIVATE int sqlite3Fts3PendingTermsFlush(Fts3Table *);
  124905. SQLITE_PRIVATE void sqlite3Fts3PendingTermsClear(Fts3Table *);
  124906. SQLITE_PRIVATE int sqlite3Fts3Optimize(Fts3Table *);
  124907. SQLITE_PRIVATE int sqlite3Fts3SegReaderNew(int, int, sqlite3_int64,
  124908. sqlite3_int64, sqlite3_int64, const char *, int, Fts3SegReader**);
  124909. SQLITE_PRIVATE int sqlite3Fts3SegReaderPending(
  124910. Fts3Table*,int,const char*,int,int,Fts3SegReader**);
  124911. SQLITE_PRIVATE void sqlite3Fts3SegReaderFree(Fts3SegReader *);
  124912. SQLITE_PRIVATE int sqlite3Fts3AllSegdirs(Fts3Table*, int, int, int, sqlite3_stmt **);
  124913. SQLITE_PRIVATE int sqlite3Fts3ReadBlock(Fts3Table*, sqlite3_int64, char **, int*, int*);
  124914. SQLITE_PRIVATE int sqlite3Fts3SelectDoctotal(Fts3Table *, sqlite3_stmt **);
  124915. SQLITE_PRIVATE int sqlite3Fts3SelectDocsize(Fts3Table *, sqlite3_int64, sqlite3_stmt **);
  124916. #ifndef SQLITE_DISABLE_FTS4_DEFERRED
  124917. SQLITE_PRIVATE void sqlite3Fts3FreeDeferredTokens(Fts3Cursor *);
  124918. SQLITE_PRIVATE int sqlite3Fts3DeferToken(Fts3Cursor *, Fts3PhraseToken *, int);
  124919. SQLITE_PRIVATE int sqlite3Fts3CacheDeferredDoclists(Fts3Cursor *);
  124920. SQLITE_PRIVATE void sqlite3Fts3FreeDeferredDoclists(Fts3Cursor *);
  124921. SQLITE_PRIVATE int sqlite3Fts3DeferredTokenList(Fts3DeferredToken *, char **, int *);
  124922. #else
  124923. # define sqlite3Fts3FreeDeferredTokens(x)
  124924. # define sqlite3Fts3DeferToken(x,y,z) SQLITE_OK
  124925. # define sqlite3Fts3CacheDeferredDoclists(x) SQLITE_OK
  124926. # define sqlite3Fts3FreeDeferredDoclists(x)
  124927. # define sqlite3Fts3DeferredTokenList(x,y,z) SQLITE_OK
  124928. #endif
  124929. SQLITE_PRIVATE void sqlite3Fts3SegmentsClose(Fts3Table *);
  124930. SQLITE_PRIVATE int sqlite3Fts3MaxLevel(Fts3Table *, int *);
  124931. /* Special values interpreted by sqlite3SegReaderCursor() */
  124932. #define FTS3_SEGCURSOR_PENDING -1
  124933. #define FTS3_SEGCURSOR_ALL -2
  124934. SQLITE_PRIVATE int sqlite3Fts3SegReaderStart(Fts3Table*, Fts3MultiSegReader*, Fts3SegFilter*);
  124935. SQLITE_PRIVATE int sqlite3Fts3SegReaderStep(Fts3Table *, Fts3MultiSegReader *);
  124936. SQLITE_PRIVATE void sqlite3Fts3SegReaderFinish(Fts3MultiSegReader *);
  124937. SQLITE_PRIVATE int sqlite3Fts3SegReaderCursor(Fts3Table *,
  124938. int, int, int, const char *, int, int, int, Fts3MultiSegReader *);
  124939. /* Flags allowed as part of the 4th argument to SegmentReaderIterate() */
  124940. #define FTS3_SEGMENT_REQUIRE_POS 0x00000001
  124941. #define FTS3_SEGMENT_IGNORE_EMPTY 0x00000002
  124942. #define FTS3_SEGMENT_COLUMN_FILTER 0x00000004
  124943. #define FTS3_SEGMENT_PREFIX 0x00000008
  124944. #define FTS3_SEGMENT_SCAN 0x00000010
  124945. #define FTS3_SEGMENT_FIRST 0x00000020
  124946. /* Type passed as 4th argument to SegmentReaderIterate() */
  124947. struct Fts3SegFilter {
  124948. const char *zTerm;
  124949. int nTerm;
  124950. int iCol;
  124951. int flags;
  124952. };
  124953. struct Fts3MultiSegReader {
  124954. /* Used internally by sqlite3Fts3SegReaderXXX() calls */
  124955. Fts3SegReader **apSegment; /* Array of Fts3SegReader objects */
  124956. int nSegment; /* Size of apSegment array */
  124957. int nAdvance; /* How many seg-readers to advance */
  124958. Fts3SegFilter *pFilter; /* Pointer to filter object */
  124959. char *aBuffer; /* Buffer to merge doclists in */
  124960. int nBuffer; /* Allocated size of aBuffer[] in bytes */
  124961. int iColFilter; /* If >=0, filter for this column */
  124962. int bRestart;
  124963. /* Used by fts3.c only. */
  124964. int nCost; /* Cost of running iterator */
  124965. int bLookup; /* True if a lookup of a single entry. */
  124966. /* Output values. Valid only after Fts3SegReaderStep() returns SQLITE_ROW. */
  124967. char *zTerm; /* Pointer to term buffer */
  124968. int nTerm; /* Size of zTerm in bytes */
  124969. char *aDoclist; /* Pointer to doclist buffer */
  124970. int nDoclist; /* Size of aDoclist[] in bytes */
  124971. };
  124972. SQLITE_PRIVATE int sqlite3Fts3Incrmerge(Fts3Table*,int,int);
  124973. #define fts3GetVarint32(p, piVal) ( \
  124974. (*(u8*)(p)&0x80) ? sqlite3Fts3GetVarint32(p, piVal) : (*piVal=*(u8*)(p), 1) \
  124975. )
  124976. /* fts3.c */
  124977. SQLITE_PRIVATE void sqlite3Fts3ErrMsg(char**,const char*,...);
  124978. SQLITE_PRIVATE int sqlite3Fts3PutVarint(char *, sqlite3_int64);
  124979. SQLITE_PRIVATE int sqlite3Fts3GetVarint(const char *, sqlite_int64 *);
  124980. SQLITE_PRIVATE int sqlite3Fts3GetVarint32(const char *, int *);
  124981. SQLITE_PRIVATE int sqlite3Fts3VarintLen(sqlite3_uint64);
  124982. SQLITE_PRIVATE void sqlite3Fts3Dequote(char *);
  124983. SQLITE_PRIVATE void sqlite3Fts3DoclistPrev(int,char*,int,char**,sqlite3_int64*,int*,u8*);
  124984. SQLITE_PRIVATE int sqlite3Fts3EvalPhraseStats(Fts3Cursor *, Fts3Expr *, u32 *);
  124985. SQLITE_PRIVATE int sqlite3Fts3FirstFilter(sqlite3_int64, char *, int, char *);
  124986. SQLITE_PRIVATE void sqlite3Fts3CreateStatTable(int*, Fts3Table*);
  124987. /* fts3_tokenizer.c */
  124988. SQLITE_PRIVATE const char *sqlite3Fts3NextToken(const char *, int *);
  124989. SQLITE_PRIVATE int sqlite3Fts3InitHashTable(sqlite3 *, Fts3Hash *, const char *);
  124990. SQLITE_PRIVATE int sqlite3Fts3InitTokenizer(Fts3Hash *pHash, const char *,
  124991. sqlite3_tokenizer **, char **
  124992. );
  124993. SQLITE_PRIVATE int sqlite3Fts3IsIdChar(char);
  124994. /* fts3_snippet.c */
  124995. SQLITE_PRIVATE void sqlite3Fts3Offsets(sqlite3_context*, Fts3Cursor*);
  124996. SQLITE_PRIVATE void sqlite3Fts3Snippet(sqlite3_context *, Fts3Cursor *, const char *,
  124997. const char *, const char *, int, int
  124998. );
  124999. SQLITE_PRIVATE void sqlite3Fts3Matchinfo(sqlite3_context *, Fts3Cursor *, const char *);
  125000. /* fts3_expr.c */
  125001. SQLITE_PRIVATE int sqlite3Fts3ExprParse(sqlite3_tokenizer *, int,
  125002. char **, int, int, int, const char *, int, Fts3Expr **, char **
  125003. );
  125004. SQLITE_PRIVATE void sqlite3Fts3ExprFree(Fts3Expr *);
  125005. #ifdef SQLITE_TEST
  125006. SQLITE_PRIVATE int sqlite3Fts3ExprInitTestInterface(sqlite3 *db);
  125007. SQLITE_PRIVATE int sqlite3Fts3InitTerm(sqlite3 *db);
  125008. #endif
  125009. SQLITE_PRIVATE int sqlite3Fts3OpenTokenizer(sqlite3_tokenizer *, int, const char *, int,
  125010. sqlite3_tokenizer_cursor **
  125011. );
  125012. /* fts3_aux.c */
  125013. SQLITE_PRIVATE int sqlite3Fts3InitAux(sqlite3 *db);
  125014. SQLITE_PRIVATE void sqlite3Fts3EvalPhraseCleanup(Fts3Phrase *);
  125015. SQLITE_PRIVATE int sqlite3Fts3MsrIncrStart(
  125016. Fts3Table*, Fts3MultiSegReader*, int, const char*, int);
  125017. SQLITE_PRIVATE int sqlite3Fts3MsrIncrNext(
  125018. Fts3Table *, Fts3MultiSegReader *, sqlite3_int64 *, char **, int *);
  125019. SQLITE_PRIVATE int sqlite3Fts3EvalPhrasePoslist(Fts3Cursor *, Fts3Expr *, int iCol, char **);
  125020. SQLITE_PRIVATE int sqlite3Fts3MsrOvfl(Fts3Cursor *, Fts3MultiSegReader *, int *);
  125021. SQLITE_PRIVATE int sqlite3Fts3MsrIncrRestart(Fts3MultiSegReader *pCsr);
  125022. /* fts3_tokenize_vtab.c */
  125023. SQLITE_PRIVATE int sqlite3Fts3InitTok(sqlite3*, Fts3Hash *);
  125024. /* fts3_unicode2.c (functions generated by parsing unicode text files) */
  125025. #ifndef SQLITE_DISABLE_FTS3_UNICODE
  125026. SQLITE_PRIVATE int sqlite3FtsUnicodeFold(int, int);
  125027. SQLITE_PRIVATE int sqlite3FtsUnicodeIsalnum(int);
  125028. SQLITE_PRIVATE int sqlite3FtsUnicodeIsdiacritic(int);
  125029. #endif
  125030. #endif /* !SQLITE_CORE || SQLITE_ENABLE_FTS3 */
  125031. #endif /* _FTSINT_H */
  125032. /************** End of fts3Int.h *********************************************/
  125033. /************** Continuing where we left off in fts3.c ***********************/
  125034. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  125035. #if defined(SQLITE_ENABLE_FTS3) && !defined(SQLITE_CORE)
  125036. # define SQLITE_CORE 1
  125037. #endif
  125038. /* #include <assert.h> */
  125039. /* #include <stdlib.h> */
  125040. /* #include <stddef.h> */
  125041. /* #include <stdio.h> */
  125042. /* #include <string.h> */
  125043. /* #include <stdarg.h> */
  125044. #ifndef SQLITE_CORE
  125045. SQLITE_EXTENSION_INIT1
  125046. #endif
  125047. static int fts3EvalNext(Fts3Cursor *pCsr);
  125048. static int fts3EvalStart(Fts3Cursor *pCsr);
  125049. static int fts3TermSegReaderCursor(
  125050. Fts3Cursor *, const char *, int, int, Fts3MultiSegReader **);
  125051. #ifndef SQLITE_AMALGAMATION
  125052. # if defined(SQLITE_DEBUG)
  125053. SQLITE_PRIVATE int sqlite3Fts3Always(int b) { assert( b ); return b; }
  125054. SQLITE_PRIVATE int sqlite3Fts3Never(int b) { assert( !b ); return b; }
  125055. # endif
  125056. #endif
  125057. /*
  125058. ** Write a 64-bit variable-length integer to memory starting at p[0].
  125059. ** The length of data written will be between 1 and FTS3_VARINT_MAX bytes.
  125060. ** The number of bytes written is returned.
  125061. */
  125062. SQLITE_PRIVATE int sqlite3Fts3PutVarint(char *p, sqlite_int64 v){
  125063. unsigned char *q = (unsigned char *) p;
  125064. sqlite_uint64 vu = v;
  125065. do{
  125066. *q++ = (unsigned char) ((vu & 0x7f) | 0x80);
  125067. vu >>= 7;
  125068. }while( vu!=0 );
  125069. q[-1] &= 0x7f; /* turn off high bit in final byte */
  125070. assert( q - (unsigned char *)p <= FTS3_VARINT_MAX );
  125071. return (int) (q - (unsigned char *)p);
  125072. }
  125073. #define GETVARINT_STEP(v, ptr, shift, mask1, mask2, var, ret) \
  125074. v = (v & mask1) | ( (*ptr++) << shift ); \
  125075. if( (v & mask2)==0 ){ var = v; return ret; }
  125076. #define GETVARINT_INIT(v, ptr, shift, mask1, mask2, var, ret) \
  125077. v = (*ptr++); \
  125078. if( (v & mask2)==0 ){ var = v; return ret; }
  125079. /*
  125080. ** Read a 64-bit variable-length integer from memory starting at p[0].
  125081. ** Return the number of bytes read, or 0 on error.
  125082. ** The value is stored in *v.
  125083. */
  125084. SQLITE_PRIVATE int sqlite3Fts3GetVarint(const char *p, sqlite_int64 *v){
  125085. const char *pStart = p;
  125086. u32 a;
  125087. u64 b;
  125088. int shift;
  125089. GETVARINT_INIT(a, p, 0, 0x00, 0x80, *v, 1);
  125090. GETVARINT_STEP(a, p, 7, 0x7F, 0x4000, *v, 2);
  125091. GETVARINT_STEP(a, p, 14, 0x3FFF, 0x200000, *v, 3);
  125092. GETVARINT_STEP(a, p, 21, 0x1FFFFF, 0x10000000, *v, 4);
  125093. b = (a & 0x0FFFFFFF );
  125094. for(shift=28; shift<=63; shift+=7){
  125095. u64 c = *p++;
  125096. b += (c&0x7F) << shift;
  125097. if( (c & 0x80)==0 ) break;
  125098. }
  125099. *v = b;
  125100. return (int)(p - pStart);
  125101. }
  125102. /*
  125103. ** Similar to sqlite3Fts3GetVarint(), except that the output is truncated to a
  125104. ** 32-bit integer before it is returned.
  125105. */
  125106. SQLITE_PRIVATE int sqlite3Fts3GetVarint32(const char *p, int *pi){
  125107. u32 a;
  125108. #ifndef fts3GetVarint32
  125109. GETVARINT_INIT(a, p, 0, 0x00, 0x80, *pi, 1);
  125110. #else
  125111. a = (*p++);
  125112. assert( a & 0x80 );
  125113. #endif
  125114. GETVARINT_STEP(a, p, 7, 0x7F, 0x4000, *pi, 2);
  125115. GETVARINT_STEP(a, p, 14, 0x3FFF, 0x200000, *pi, 3);
  125116. GETVARINT_STEP(a, p, 21, 0x1FFFFF, 0x10000000, *pi, 4);
  125117. a = (a & 0x0FFFFFFF );
  125118. *pi = (int)(a | ((u32)(*p & 0x0F) << 28));
  125119. return 5;
  125120. }
  125121. /*
  125122. ** Return the number of bytes required to encode v as a varint
  125123. */
  125124. SQLITE_PRIVATE int sqlite3Fts3VarintLen(sqlite3_uint64 v){
  125125. int i = 0;
  125126. do{
  125127. i++;
  125128. v >>= 7;
  125129. }while( v!=0 );
  125130. return i;
  125131. }
  125132. /*
  125133. ** Convert an SQL-style quoted string into a normal string by removing
  125134. ** the quote characters. The conversion is done in-place. If the
  125135. ** input does not begin with a quote character, then this routine
  125136. ** is a no-op.
  125137. **
  125138. ** Examples:
  125139. **
  125140. ** "abc" becomes abc
  125141. ** 'xyz' becomes xyz
  125142. ** [pqr] becomes pqr
  125143. ** `mno` becomes mno
  125144. **
  125145. */
  125146. SQLITE_PRIVATE void sqlite3Fts3Dequote(char *z){
  125147. char quote; /* Quote character (if any ) */
  125148. quote = z[0];
  125149. if( quote=='[' || quote=='\'' || quote=='"' || quote=='`' ){
  125150. int iIn = 1; /* Index of next byte to read from input */
  125151. int iOut = 0; /* Index of next byte to write to output */
  125152. /* If the first byte was a '[', then the close-quote character is a ']' */
  125153. if( quote=='[' ) quote = ']';
  125154. while( z[iIn] ){
  125155. if( z[iIn]==quote ){
  125156. if( z[iIn+1]!=quote ) break;
  125157. z[iOut++] = quote;
  125158. iIn += 2;
  125159. }else{
  125160. z[iOut++] = z[iIn++];
  125161. }
  125162. }
  125163. z[iOut] = '\0';
  125164. }
  125165. }
  125166. /*
  125167. ** Read a single varint from the doclist at *pp and advance *pp to point
  125168. ** to the first byte past the end of the varint. Add the value of the varint
  125169. ** to *pVal.
  125170. */
  125171. static void fts3GetDeltaVarint(char **pp, sqlite3_int64 *pVal){
  125172. sqlite3_int64 iVal;
  125173. *pp += sqlite3Fts3GetVarint(*pp, &iVal);
  125174. *pVal += iVal;
  125175. }
  125176. /*
  125177. ** When this function is called, *pp points to the first byte following a
  125178. ** varint that is part of a doclist (or position-list, or any other list
  125179. ** of varints). This function moves *pp to point to the start of that varint,
  125180. ** and sets *pVal by the varint value.
  125181. **
  125182. ** Argument pStart points to the first byte of the doclist that the
  125183. ** varint is part of.
  125184. */
  125185. static void fts3GetReverseVarint(
  125186. char **pp,
  125187. char *pStart,
  125188. sqlite3_int64 *pVal
  125189. ){
  125190. sqlite3_int64 iVal;
  125191. char *p;
  125192. /* Pointer p now points at the first byte past the varint we are
  125193. ** interested in. So, unless the doclist is corrupt, the 0x80 bit is
  125194. ** clear on character p[-1]. */
  125195. for(p = (*pp)-2; p>=pStart && *p&0x80; p--);
  125196. p++;
  125197. *pp = p;
  125198. sqlite3Fts3GetVarint(p, &iVal);
  125199. *pVal = iVal;
  125200. }
  125201. /*
  125202. ** The xDisconnect() virtual table method.
  125203. */
  125204. static int fts3DisconnectMethod(sqlite3_vtab *pVtab){
  125205. Fts3Table *p = (Fts3Table *)pVtab;
  125206. int i;
  125207. assert( p->nPendingData==0 );
  125208. assert( p->pSegments==0 );
  125209. /* Free any prepared statements held */
  125210. for(i=0; i<SizeofArray(p->aStmt); i++){
  125211. sqlite3_finalize(p->aStmt[i]);
  125212. }
  125213. sqlite3_free(p->zSegmentsTbl);
  125214. sqlite3_free(p->zReadExprlist);
  125215. sqlite3_free(p->zWriteExprlist);
  125216. sqlite3_free(p->zContentTbl);
  125217. sqlite3_free(p->zLanguageid);
  125218. /* Invoke the tokenizer destructor to free the tokenizer. */
  125219. p->pTokenizer->pModule->xDestroy(p->pTokenizer);
  125220. sqlite3_free(p);
  125221. return SQLITE_OK;
  125222. }
  125223. /*
  125224. ** Write an error message into *pzErr
  125225. */
  125226. SQLITE_PRIVATE void sqlite3Fts3ErrMsg(char **pzErr, const char *zFormat, ...){
  125227. va_list ap;
  125228. sqlite3_free(*pzErr);
  125229. va_start(ap, zFormat);
  125230. *pzErr = sqlite3_vmprintf(zFormat, ap);
  125231. va_end(ap);
  125232. }
  125233. /*
  125234. ** Construct one or more SQL statements from the format string given
  125235. ** and then evaluate those statements. The success code is written
  125236. ** into *pRc.
  125237. **
  125238. ** If *pRc is initially non-zero then this routine is a no-op.
  125239. */
  125240. static void fts3DbExec(
  125241. int *pRc, /* Success code */
  125242. sqlite3 *db, /* Database in which to run SQL */
  125243. const char *zFormat, /* Format string for SQL */
  125244. ... /* Arguments to the format string */
  125245. ){
  125246. va_list ap;
  125247. char *zSql;
  125248. if( *pRc ) return;
  125249. va_start(ap, zFormat);
  125250. zSql = sqlite3_vmprintf(zFormat, ap);
  125251. va_end(ap);
  125252. if( zSql==0 ){
  125253. *pRc = SQLITE_NOMEM;
  125254. }else{
  125255. *pRc = sqlite3_exec(db, zSql, 0, 0, 0);
  125256. sqlite3_free(zSql);
  125257. }
  125258. }
  125259. /*
  125260. ** The xDestroy() virtual table method.
  125261. */
  125262. static int fts3DestroyMethod(sqlite3_vtab *pVtab){
  125263. Fts3Table *p = (Fts3Table *)pVtab;
  125264. int rc = SQLITE_OK; /* Return code */
  125265. const char *zDb = p->zDb; /* Name of database (e.g. "main", "temp") */
  125266. sqlite3 *db = p->db; /* Database handle */
  125267. /* Drop the shadow tables */
  125268. if( p->zContentTbl==0 ){
  125269. fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_content'", zDb, p->zName);
  125270. }
  125271. fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_segments'", zDb,p->zName);
  125272. fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_segdir'", zDb, p->zName);
  125273. fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_docsize'", zDb, p->zName);
  125274. fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_stat'", zDb, p->zName);
  125275. /* If everything has worked, invoke fts3DisconnectMethod() to free the
  125276. ** memory associated with the Fts3Table structure and return SQLITE_OK.
  125277. ** Otherwise, return an SQLite error code.
  125278. */
  125279. return (rc==SQLITE_OK ? fts3DisconnectMethod(pVtab) : rc);
  125280. }
  125281. /*
  125282. ** Invoke sqlite3_declare_vtab() to declare the schema for the FTS3 table
  125283. ** passed as the first argument. This is done as part of the xConnect()
  125284. ** and xCreate() methods.
  125285. **
  125286. ** If *pRc is non-zero when this function is called, it is a no-op.
  125287. ** Otherwise, if an error occurs, an SQLite error code is stored in *pRc
  125288. ** before returning.
  125289. */
  125290. static void fts3DeclareVtab(int *pRc, Fts3Table *p){
  125291. if( *pRc==SQLITE_OK ){
  125292. int i; /* Iterator variable */
  125293. int rc; /* Return code */
  125294. char *zSql; /* SQL statement passed to declare_vtab() */
  125295. char *zCols; /* List of user defined columns */
  125296. const char *zLanguageid;
  125297. zLanguageid = (p->zLanguageid ? p->zLanguageid : "__langid");
  125298. sqlite3_vtab_config(p->db, SQLITE_VTAB_CONSTRAINT_SUPPORT, 1);
  125299. /* Create a list of user columns for the virtual table */
  125300. zCols = sqlite3_mprintf("%Q, ", p->azColumn[0]);
  125301. for(i=1; zCols && i<p->nColumn; i++){
  125302. zCols = sqlite3_mprintf("%z%Q, ", zCols, p->azColumn[i]);
  125303. }
  125304. /* Create the whole "CREATE TABLE" statement to pass to SQLite */
  125305. zSql = sqlite3_mprintf(
  125306. "CREATE TABLE x(%s %Q HIDDEN, docid HIDDEN, %Q HIDDEN)",
  125307. zCols, p->zName, zLanguageid
  125308. );
  125309. if( !zCols || !zSql ){
  125310. rc = SQLITE_NOMEM;
  125311. }else{
  125312. rc = sqlite3_declare_vtab(p->db, zSql);
  125313. }
  125314. sqlite3_free(zSql);
  125315. sqlite3_free(zCols);
  125316. *pRc = rc;
  125317. }
  125318. }
  125319. /*
  125320. ** Create the %_stat table if it does not already exist.
  125321. */
  125322. SQLITE_PRIVATE void sqlite3Fts3CreateStatTable(int *pRc, Fts3Table *p){
  125323. fts3DbExec(pRc, p->db,
  125324. "CREATE TABLE IF NOT EXISTS %Q.'%q_stat'"
  125325. "(id INTEGER PRIMARY KEY, value BLOB);",
  125326. p->zDb, p->zName
  125327. );
  125328. if( (*pRc)==SQLITE_OK ) p->bHasStat = 1;
  125329. }
  125330. /*
  125331. ** Create the backing store tables (%_content, %_segments and %_segdir)
  125332. ** required by the FTS3 table passed as the only argument. This is done
  125333. ** as part of the vtab xCreate() method.
  125334. **
  125335. ** If the p->bHasDocsize boolean is true (indicating that this is an
  125336. ** FTS4 table, not an FTS3 table) then also create the %_docsize and
  125337. ** %_stat tables required by FTS4.
  125338. */
  125339. static int fts3CreateTables(Fts3Table *p){
  125340. int rc = SQLITE_OK; /* Return code */
  125341. int i; /* Iterator variable */
  125342. sqlite3 *db = p->db; /* The database connection */
  125343. if( p->zContentTbl==0 ){
  125344. const char *zLanguageid = p->zLanguageid;
  125345. char *zContentCols; /* Columns of %_content table */
  125346. /* Create a list of user columns for the content table */
  125347. zContentCols = sqlite3_mprintf("docid INTEGER PRIMARY KEY");
  125348. for(i=0; zContentCols && i<p->nColumn; i++){
  125349. char *z = p->azColumn[i];
  125350. zContentCols = sqlite3_mprintf("%z, 'c%d%q'", zContentCols, i, z);
  125351. }
  125352. if( zLanguageid && zContentCols ){
  125353. zContentCols = sqlite3_mprintf("%z, langid", zContentCols, zLanguageid);
  125354. }
  125355. if( zContentCols==0 ) rc = SQLITE_NOMEM;
  125356. /* Create the content table */
  125357. fts3DbExec(&rc, db,
  125358. "CREATE TABLE %Q.'%q_content'(%s)",
  125359. p->zDb, p->zName, zContentCols
  125360. );
  125361. sqlite3_free(zContentCols);
  125362. }
  125363. /* Create other tables */
  125364. fts3DbExec(&rc, db,
  125365. "CREATE TABLE %Q.'%q_segments'(blockid INTEGER PRIMARY KEY, block BLOB);",
  125366. p->zDb, p->zName
  125367. );
  125368. fts3DbExec(&rc, db,
  125369. "CREATE TABLE %Q.'%q_segdir'("
  125370. "level INTEGER,"
  125371. "idx INTEGER,"
  125372. "start_block INTEGER,"
  125373. "leaves_end_block INTEGER,"
  125374. "end_block INTEGER,"
  125375. "root BLOB,"
  125376. "PRIMARY KEY(level, idx)"
  125377. ");",
  125378. p->zDb, p->zName
  125379. );
  125380. if( p->bHasDocsize ){
  125381. fts3DbExec(&rc, db,
  125382. "CREATE TABLE %Q.'%q_docsize'(docid INTEGER PRIMARY KEY, size BLOB);",
  125383. p->zDb, p->zName
  125384. );
  125385. }
  125386. assert( p->bHasStat==p->bFts4 );
  125387. if( p->bHasStat ){
  125388. sqlite3Fts3CreateStatTable(&rc, p);
  125389. }
  125390. return rc;
  125391. }
  125392. /*
  125393. ** Store the current database page-size in bytes in p->nPgsz.
  125394. **
  125395. ** If *pRc is non-zero when this function is called, it is a no-op.
  125396. ** Otherwise, if an error occurs, an SQLite error code is stored in *pRc
  125397. ** before returning.
  125398. */
  125399. static void fts3DatabasePageSize(int *pRc, Fts3Table *p){
  125400. if( *pRc==SQLITE_OK ){
  125401. int rc; /* Return code */
  125402. char *zSql; /* SQL text "PRAGMA %Q.page_size" */
  125403. sqlite3_stmt *pStmt; /* Compiled "PRAGMA %Q.page_size" statement */
  125404. zSql = sqlite3_mprintf("PRAGMA %Q.page_size", p->zDb);
  125405. if( !zSql ){
  125406. rc = SQLITE_NOMEM;
  125407. }else{
  125408. rc = sqlite3_prepare(p->db, zSql, -1, &pStmt, 0);
  125409. if( rc==SQLITE_OK ){
  125410. sqlite3_step(pStmt);
  125411. p->nPgsz = sqlite3_column_int(pStmt, 0);
  125412. rc = sqlite3_finalize(pStmt);
  125413. }else if( rc==SQLITE_AUTH ){
  125414. p->nPgsz = 1024;
  125415. rc = SQLITE_OK;
  125416. }
  125417. }
  125418. assert( p->nPgsz>0 || rc!=SQLITE_OK );
  125419. sqlite3_free(zSql);
  125420. *pRc = rc;
  125421. }
  125422. }
  125423. /*
  125424. ** "Special" FTS4 arguments are column specifications of the following form:
  125425. **
  125426. ** <key> = <value>
  125427. **
  125428. ** There may not be whitespace surrounding the "=" character. The <value>
  125429. ** term may be quoted, but the <key> may not.
  125430. */
  125431. static int fts3IsSpecialColumn(
  125432. const char *z,
  125433. int *pnKey,
  125434. char **pzValue
  125435. ){
  125436. char *zValue;
  125437. const char *zCsr = z;
  125438. while( *zCsr!='=' ){
  125439. if( *zCsr=='\0' ) return 0;
  125440. zCsr++;
  125441. }
  125442. *pnKey = (int)(zCsr-z);
  125443. zValue = sqlite3_mprintf("%s", &zCsr[1]);
  125444. if( zValue ){
  125445. sqlite3Fts3Dequote(zValue);
  125446. }
  125447. *pzValue = zValue;
  125448. return 1;
  125449. }
  125450. /*
  125451. ** Append the output of a printf() style formatting to an existing string.
  125452. */
  125453. static void fts3Appendf(
  125454. int *pRc, /* IN/OUT: Error code */
  125455. char **pz, /* IN/OUT: Pointer to string buffer */
  125456. const char *zFormat, /* Printf format string to append */
  125457. ... /* Arguments for printf format string */
  125458. ){
  125459. if( *pRc==SQLITE_OK ){
  125460. va_list ap;
  125461. char *z;
  125462. va_start(ap, zFormat);
  125463. z = sqlite3_vmprintf(zFormat, ap);
  125464. va_end(ap);
  125465. if( z && *pz ){
  125466. char *z2 = sqlite3_mprintf("%s%s", *pz, z);
  125467. sqlite3_free(z);
  125468. z = z2;
  125469. }
  125470. if( z==0 ) *pRc = SQLITE_NOMEM;
  125471. sqlite3_free(*pz);
  125472. *pz = z;
  125473. }
  125474. }
  125475. /*
  125476. ** Return a copy of input string zInput enclosed in double-quotes (") and
  125477. ** with all double quote characters escaped. For example:
  125478. **
  125479. ** fts3QuoteId("un \"zip\"") -> "un \"\"zip\"\""
  125480. **
  125481. ** The pointer returned points to memory obtained from sqlite3_malloc(). It
  125482. ** is the callers responsibility to call sqlite3_free() to release this
  125483. ** memory.
  125484. */
  125485. static char *fts3QuoteId(char const *zInput){
  125486. int nRet;
  125487. char *zRet;
  125488. nRet = 2 + (int)strlen(zInput)*2 + 1;
  125489. zRet = sqlite3_malloc(nRet);
  125490. if( zRet ){
  125491. int i;
  125492. char *z = zRet;
  125493. *(z++) = '"';
  125494. for(i=0; zInput[i]; i++){
  125495. if( zInput[i]=='"' ) *(z++) = '"';
  125496. *(z++) = zInput[i];
  125497. }
  125498. *(z++) = '"';
  125499. *(z++) = '\0';
  125500. }
  125501. return zRet;
  125502. }
  125503. /*
  125504. ** Return a list of comma separated SQL expressions and a FROM clause that
  125505. ** could be used in a SELECT statement such as the following:
  125506. **
  125507. ** SELECT <list of expressions> FROM %_content AS x ...
  125508. **
  125509. ** to return the docid, followed by each column of text data in order
  125510. ** from left to write. If parameter zFunc is not NULL, then instead of
  125511. ** being returned directly each column of text data is passed to an SQL
  125512. ** function named zFunc first. For example, if zFunc is "unzip" and the
  125513. ** table has the three user-defined columns "a", "b", and "c", the following
  125514. ** string is returned:
  125515. **
  125516. ** "docid, unzip(x.'a'), unzip(x.'b'), unzip(x.'c') FROM %_content AS x"
  125517. **
  125518. ** The pointer returned points to a buffer allocated by sqlite3_malloc(). It
  125519. ** is the responsibility of the caller to eventually free it.
  125520. **
  125521. ** If *pRc is not SQLITE_OK when this function is called, it is a no-op (and
  125522. ** a NULL pointer is returned). Otherwise, if an OOM error is encountered
  125523. ** by this function, NULL is returned and *pRc is set to SQLITE_NOMEM. If
  125524. ** no error occurs, *pRc is left unmodified.
  125525. */
  125526. static char *fts3ReadExprList(Fts3Table *p, const char *zFunc, int *pRc){
  125527. char *zRet = 0;
  125528. char *zFree = 0;
  125529. char *zFunction;
  125530. int i;
  125531. if( p->zContentTbl==0 ){
  125532. if( !zFunc ){
  125533. zFunction = "";
  125534. }else{
  125535. zFree = zFunction = fts3QuoteId(zFunc);
  125536. }
  125537. fts3Appendf(pRc, &zRet, "docid");
  125538. for(i=0; i<p->nColumn; i++){
  125539. fts3Appendf(pRc, &zRet, ",%s(x.'c%d%q')", zFunction, i, p->azColumn[i]);
  125540. }
  125541. if( p->zLanguageid ){
  125542. fts3Appendf(pRc, &zRet, ", x.%Q", "langid");
  125543. }
  125544. sqlite3_free(zFree);
  125545. }else{
  125546. fts3Appendf(pRc, &zRet, "rowid");
  125547. for(i=0; i<p->nColumn; i++){
  125548. fts3Appendf(pRc, &zRet, ", x.'%q'", p->azColumn[i]);
  125549. }
  125550. if( p->zLanguageid ){
  125551. fts3Appendf(pRc, &zRet, ", x.%Q", p->zLanguageid);
  125552. }
  125553. }
  125554. fts3Appendf(pRc, &zRet, " FROM '%q'.'%q%s' AS x",
  125555. p->zDb,
  125556. (p->zContentTbl ? p->zContentTbl : p->zName),
  125557. (p->zContentTbl ? "" : "_content")
  125558. );
  125559. return zRet;
  125560. }
  125561. /*
  125562. ** Return a list of N comma separated question marks, where N is the number
  125563. ** of columns in the %_content table (one for the docid plus one for each
  125564. ** user-defined text column).
  125565. **
  125566. ** If argument zFunc is not NULL, then all but the first question mark
  125567. ** is preceded by zFunc and an open bracket, and followed by a closed
  125568. ** bracket. For example, if zFunc is "zip" and the FTS3 table has three
  125569. ** user-defined text columns, the following string is returned:
  125570. **
  125571. ** "?, zip(?), zip(?), zip(?)"
  125572. **
  125573. ** The pointer returned points to a buffer allocated by sqlite3_malloc(). It
  125574. ** is the responsibility of the caller to eventually free it.
  125575. **
  125576. ** If *pRc is not SQLITE_OK when this function is called, it is a no-op (and
  125577. ** a NULL pointer is returned). Otherwise, if an OOM error is encountered
  125578. ** by this function, NULL is returned and *pRc is set to SQLITE_NOMEM. If
  125579. ** no error occurs, *pRc is left unmodified.
  125580. */
  125581. static char *fts3WriteExprList(Fts3Table *p, const char *zFunc, int *pRc){
  125582. char *zRet = 0;
  125583. char *zFree = 0;
  125584. char *zFunction;
  125585. int i;
  125586. if( !zFunc ){
  125587. zFunction = "";
  125588. }else{
  125589. zFree = zFunction = fts3QuoteId(zFunc);
  125590. }
  125591. fts3Appendf(pRc, &zRet, "?");
  125592. for(i=0; i<p->nColumn; i++){
  125593. fts3Appendf(pRc, &zRet, ",%s(?)", zFunction);
  125594. }
  125595. if( p->zLanguageid ){
  125596. fts3Appendf(pRc, &zRet, ", ?");
  125597. }
  125598. sqlite3_free(zFree);
  125599. return zRet;
  125600. }
  125601. /*
  125602. ** This function interprets the string at (*pp) as a non-negative integer
  125603. ** value. It reads the integer and sets *pnOut to the value read, then
  125604. ** sets *pp to point to the byte immediately following the last byte of
  125605. ** the integer value.
  125606. **
  125607. ** Only decimal digits ('0'..'9') may be part of an integer value.
  125608. **
  125609. ** If *pp does not being with a decimal digit SQLITE_ERROR is returned and
  125610. ** the output value undefined. Otherwise SQLITE_OK is returned.
  125611. **
  125612. ** This function is used when parsing the "prefix=" FTS4 parameter.
  125613. */
  125614. static int fts3GobbleInt(const char **pp, int *pnOut){
  125615. const int MAX_NPREFIX = 10000000;
  125616. const char *p; /* Iterator pointer */
  125617. int nInt = 0; /* Output value */
  125618. for(p=*pp; p[0]>='0' && p[0]<='9'; p++){
  125619. nInt = nInt * 10 + (p[0] - '0');
  125620. if( nInt>MAX_NPREFIX ){
  125621. nInt = 0;
  125622. break;
  125623. }
  125624. }
  125625. if( p==*pp ) return SQLITE_ERROR;
  125626. *pnOut = nInt;
  125627. *pp = p;
  125628. return SQLITE_OK;
  125629. }
  125630. /*
  125631. ** This function is called to allocate an array of Fts3Index structures
  125632. ** representing the indexes maintained by the current FTS table. FTS tables
  125633. ** always maintain the main "terms" index, but may also maintain one or
  125634. ** more "prefix" indexes, depending on the value of the "prefix=" parameter
  125635. ** (if any) specified as part of the CREATE VIRTUAL TABLE statement.
  125636. **
  125637. ** Argument zParam is passed the value of the "prefix=" option if one was
  125638. ** specified, or NULL otherwise.
  125639. **
  125640. ** If no error occurs, SQLITE_OK is returned and *apIndex set to point to
  125641. ** the allocated array. *pnIndex is set to the number of elements in the
  125642. ** array. If an error does occur, an SQLite error code is returned.
  125643. **
  125644. ** Regardless of whether or not an error is returned, it is the responsibility
  125645. ** of the caller to call sqlite3_free() on the output array to free it.
  125646. */
  125647. static int fts3PrefixParameter(
  125648. const char *zParam, /* ABC in prefix=ABC parameter to parse */
  125649. int *pnIndex, /* OUT: size of *apIndex[] array */
  125650. struct Fts3Index **apIndex /* OUT: Array of indexes for this table */
  125651. ){
  125652. struct Fts3Index *aIndex; /* Allocated array */
  125653. int nIndex = 1; /* Number of entries in array */
  125654. if( zParam && zParam[0] ){
  125655. const char *p;
  125656. nIndex++;
  125657. for(p=zParam; *p; p++){
  125658. if( *p==',' ) nIndex++;
  125659. }
  125660. }
  125661. aIndex = sqlite3_malloc(sizeof(struct Fts3Index) * nIndex);
  125662. *apIndex = aIndex;
  125663. if( !aIndex ){
  125664. return SQLITE_NOMEM;
  125665. }
  125666. memset(aIndex, 0, sizeof(struct Fts3Index) * nIndex);
  125667. if( zParam ){
  125668. const char *p = zParam;
  125669. int i;
  125670. for(i=1; i<nIndex; i++){
  125671. int nPrefix = 0;
  125672. if( fts3GobbleInt(&p, &nPrefix) ) return SQLITE_ERROR;
  125673. assert( nPrefix>=0 );
  125674. if( nPrefix==0 ){
  125675. nIndex--;
  125676. i--;
  125677. }else{
  125678. aIndex[i].nPrefix = nPrefix;
  125679. }
  125680. p++;
  125681. }
  125682. }
  125683. *pnIndex = nIndex;
  125684. return SQLITE_OK;
  125685. }
  125686. /*
  125687. ** This function is called when initializing an FTS4 table that uses the
  125688. ** content=xxx option. It determines the number of and names of the columns
  125689. ** of the new FTS4 table.
  125690. **
  125691. ** The third argument passed to this function is the value passed to the
  125692. ** config=xxx option (i.e. "xxx"). This function queries the database for
  125693. ** a table of that name. If found, the output variables are populated
  125694. ** as follows:
  125695. **
  125696. ** *pnCol: Set to the number of columns table xxx has,
  125697. **
  125698. ** *pnStr: Set to the total amount of space required to store a copy
  125699. ** of each columns name, including the nul-terminator.
  125700. **
  125701. ** *pazCol: Set to point to an array of *pnCol strings. Each string is
  125702. ** the name of the corresponding column in table xxx. The array
  125703. ** and its contents are allocated using a single allocation. It
  125704. ** is the responsibility of the caller to free this allocation
  125705. ** by eventually passing the *pazCol value to sqlite3_free().
  125706. **
  125707. ** If the table cannot be found, an error code is returned and the output
  125708. ** variables are undefined. Or, if an OOM is encountered, SQLITE_NOMEM is
  125709. ** returned (and the output variables are undefined).
  125710. */
  125711. static int fts3ContentColumns(
  125712. sqlite3 *db, /* Database handle */
  125713. const char *zDb, /* Name of db (i.e. "main", "temp" etc.) */
  125714. const char *zTbl, /* Name of content table */
  125715. const char ***pazCol, /* OUT: Malloc'd array of column names */
  125716. int *pnCol, /* OUT: Size of array *pazCol */
  125717. int *pnStr, /* OUT: Bytes of string content */
  125718. char **pzErr /* OUT: error message */
  125719. ){
  125720. int rc = SQLITE_OK; /* Return code */
  125721. char *zSql; /* "SELECT *" statement on zTbl */
  125722. sqlite3_stmt *pStmt = 0; /* Compiled version of zSql */
  125723. zSql = sqlite3_mprintf("SELECT * FROM %Q.%Q", zDb, zTbl);
  125724. if( !zSql ){
  125725. rc = SQLITE_NOMEM;
  125726. }else{
  125727. rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
  125728. if( rc!=SQLITE_OK ){
  125729. sqlite3Fts3ErrMsg(pzErr, "%s", sqlite3_errmsg(db));
  125730. }
  125731. }
  125732. sqlite3_free(zSql);
  125733. if( rc==SQLITE_OK ){
  125734. const char **azCol; /* Output array */
  125735. int nStr = 0; /* Size of all column names (incl. 0x00) */
  125736. int nCol; /* Number of table columns */
  125737. int i; /* Used to iterate through columns */
  125738. /* Loop through the returned columns. Set nStr to the number of bytes of
  125739. ** space required to store a copy of each column name, including the
  125740. ** nul-terminator byte. */
  125741. nCol = sqlite3_column_count(pStmt);
  125742. for(i=0; i<nCol; i++){
  125743. const char *zCol = sqlite3_column_name(pStmt, i);
  125744. nStr += (int)strlen(zCol) + 1;
  125745. }
  125746. /* Allocate and populate the array to return. */
  125747. azCol = (const char **)sqlite3_malloc(sizeof(char *) * nCol + nStr);
  125748. if( azCol==0 ){
  125749. rc = SQLITE_NOMEM;
  125750. }else{
  125751. char *p = (char *)&azCol[nCol];
  125752. for(i=0; i<nCol; i++){
  125753. const char *zCol = sqlite3_column_name(pStmt, i);
  125754. int n = (int)strlen(zCol)+1;
  125755. memcpy(p, zCol, n);
  125756. azCol[i] = p;
  125757. p += n;
  125758. }
  125759. }
  125760. sqlite3_finalize(pStmt);
  125761. /* Set the output variables. */
  125762. *pnCol = nCol;
  125763. *pnStr = nStr;
  125764. *pazCol = azCol;
  125765. }
  125766. return rc;
  125767. }
  125768. /*
  125769. ** This function is the implementation of both the xConnect and xCreate
  125770. ** methods of the FTS3 virtual table.
  125771. **
  125772. ** The argv[] array contains the following:
  125773. **
  125774. ** argv[0] -> module name ("fts3" or "fts4")
  125775. ** argv[1] -> database name
  125776. ** argv[2] -> table name
  125777. ** argv[...] -> "column name" and other module argument fields.
  125778. */
  125779. static int fts3InitVtab(
  125780. int isCreate, /* True for xCreate, false for xConnect */
  125781. sqlite3 *db, /* The SQLite database connection */
  125782. void *pAux, /* Hash table containing tokenizers */
  125783. int argc, /* Number of elements in argv array */
  125784. const char * const *argv, /* xCreate/xConnect argument array */
  125785. sqlite3_vtab **ppVTab, /* Write the resulting vtab structure here */
  125786. char **pzErr /* Write any error message here */
  125787. ){
  125788. Fts3Hash *pHash = (Fts3Hash *)pAux;
  125789. Fts3Table *p = 0; /* Pointer to allocated vtab */
  125790. int rc = SQLITE_OK; /* Return code */
  125791. int i; /* Iterator variable */
  125792. int nByte; /* Size of allocation used for *p */
  125793. int iCol; /* Column index */
  125794. int nString = 0; /* Bytes required to hold all column names */
  125795. int nCol = 0; /* Number of columns in the FTS table */
  125796. char *zCsr; /* Space for holding column names */
  125797. int nDb; /* Bytes required to hold database name */
  125798. int nName; /* Bytes required to hold table name */
  125799. int isFts4 = (argv[0][3]=='4'); /* True for FTS4, false for FTS3 */
  125800. const char **aCol; /* Array of column names */
  125801. sqlite3_tokenizer *pTokenizer = 0; /* Tokenizer for this table */
  125802. int nIndex = 0; /* Size of aIndex[] array */
  125803. struct Fts3Index *aIndex = 0; /* Array of indexes for this table */
  125804. /* The results of parsing supported FTS4 key=value options: */
  125805. int bNoDocsize = 0; /* True to omit %_docsize table */
  125806. int bDescIdx = 0; /* True to store descending indexes */
  125807. char *zPrefix = 0; /* Prefix parameter value (or NULL) */
  125808. char *zCompress = 0; /* compress=? parameter (or NULL) */
  125809. char *zUncompress = 0; /* uncompress=? parameter (or NULL) */
  125810. char *zContent = 0; /* content=? parameter (or NULL) */
  125811. char *zLanguageid = 0; /* languageid=? parameter (or NULL) */
  125812. char **azNotindexed = 0; /* The set of notindexed= columns */
  125813. int nNotindexed = 0; /* Size of azNotindexed[] array */
  125814. assert( strlen(argv[0])==4 );
  125815. assert( (sqlite3_strnicmp(argv[0], "fts4", 4)==0 && isFts4)
  125816. || (sqlite3_strnicmp(argv[0], "fts3", 4)==0 && !isFts4)
  125817. );
  125818. nDb = (int)strlen(argv[1]) + 1;
  125819. nName = (int)strlen(argv[2]) + 1;
  125820. nByte = sizeof(const char *) * (argc-2);
  125821. aCol = (const char **)sqlite3_malloc(nByte);
  125822. if( aCol ){
  125823. memset((void*)aCol, 0, nByte);
  125824. azNotindexed = (char **)sqlite3_malloc(nByte);
  125825. }
  125826. if( azNotindexed ){
  125827. memset(azNotindexed, 0, nByte);
  125828. }
  125829. if( !aCol || !azNotindexed ){
  125830. rc = SQLITE_NOMEM;
  125831. goto fts3_init_out;
  125832. }
  125833. /* Loop through all of the arguments passed by the user to the FTS3/4
  125834. ** module (i.e. all the column names and special arguments). This loop
  125835. ** does the following:
  125836. **
  125837. ** + Figures out the number of columns the FTSX table will have, and
  125838. ** the number of bytes of space that must be allocated to store copies
  125839. ** of the column names.
  125840. **
  125841. ** + If there is a tokenizer specification included in the arguments,
  125842. ** initializes the tokenizer pTokenizer.
  125843. */
  125844. for(i=3; rc==SQLITE_OK && i<argc; i++){
  125845. char const *z = argv[i];
  125846. int nKey;
  125847. char *zVal;
  125848. /* Check if this is a tokenizer specification */
  125849. if( !pTokenizer
  125850. && strlen(z)>8
  125851. && 0==sqlite3_strnicmp(z, "tokenize", 8)
  125852. && 0==sqlite3Fts3IsIdChar(z[8])
  125853. ){
  125854. rc = sqlite3Fts3InitTokenizer(pHash, &z[9], &pTokenizer, pzErr);
  125855. }
  125856. /* Check if it is an FTS4 special argument. */
  125857. else if( isFts4 && fts3IsSpecialColumn(z, &nKey, &zVal) ){
  125858. struct Fts4Option {
  125859. const char *zOpt;
  125860. int nOpt;
  125861. } aFts4Opt[] = {
  125862. { "matchinfo", 9 }, /* 0 -> MATCHINFO */
  125863. { "prefix", 6 }, /* 1 -> PREFIX */
  125864. { "compress", 8 }, /* 2 -> COMPRESS */
  125865. { "uncompress", 10 }, /* 3 -> UNCOMPRESS */
  125866. { "order", 5 }, /* 4 -> ORDER */
  125867. { "content", 7 }, /* 5 -> CONTENT */
  125868. { "languageid", 10 }, /* 6 -> LANGUAGEID */
  125869. { "notindexed", 10 } /* 7 -> NOTINDEXED */
  125870. };
  125871. int iOpt;
  125872. if( !zVal ){
  125873. rc = SQLITE_NOMEM;
  125874. }else{
  125875. for(iOpt=0; iOpt<SizeofArray(aFts4Opt); iOpt++){
  125876. struct Fts4Option *pOp = &aFts4Opt[iOpt];
  125877. if( nKey==pOp->nOpt && !sqlite3_strnicmp(z, pOp->zOpt, pOp->nOpt) ){
  125878. break;
  125879. }
  125880. }
  125881. if( iOpt==SizeofArray(aFts4Opt) ){
  125882. sqlite3Fts3ErrMsg(pzErr, "unrecognized parameter: %s", z);
  125883. rc = SQLITE_ERROR;
  125884. }else{
  125885. switch( iOpt ){
  125886. case 0: /* MATCHINFO */
  125887. if( strlen(zVal)!=4 || sqlite3_strnicmp(zVal, "fts3", 4) ){
  125888. sqlite3Fts3ErrMsg(pzErr, "unrecognized matchinfo: %s", zVal);
  125889. rc = SQLITE_ERROR;
  125890. }
  125891. bNoDocsize = 1;
  125892. break;
  125893. case 1: /* PREFIX */
  125894. sqlite3_free(zPrefix);
  125895. zPrefix = zVal;
  125896. zVal = 0;
  125897. break;
  125898. case 2: /* COMPRESS */
  125899. sqlite3_free(zCompress);
  125900. zCompress = zVal;
  125901. zVal = 0;
  125902. break;
  125903. case 3: /* UNCOMPRESS */
  125904. sqlite3_free(zUncompress);
  125905. zUncompress = zVal;
  125906. zVal = 0;
  125907. break;
  125908. case 4: /* ORDER */
  125909. if( (strlen(zVal)!=3 || sqlite3_strnicmp(zVal, "asc", 3))
  125910. && (strlen(zVal)!=4 || sqlite3_strnicmp(zVal, "desc", 4))
  125911. ){
  125912. sqlite3Fts3ErrMsg(pzErr, "unrecognized order: %s", zVal);
  125913. rc = SQLITE_ERROR;
  125914. }
  125915. bDescIdx = (zVal[0]=='d' || zVal[0]=='D');
  125916. break;
  125917. case 5: /* CONTENT */
  125918. sqlite3_free(zContent);
  125919. zContent = zVal;
  125920. zVal = 0;
  125921. break;
  125922. case 6: /* LANGUAGEID */
  125923. assert( iOpt==6 );
  125924. sqlite3_free(zLanguageid);
  125925. zLanguageid = zVal;
  125926. zVal = 0;
  125927. break;
  125928. case 7: /* NOTINDEXED */
  125929. azNotindexed[nNotindexed++] = zVal;
  125930. zVal = 0;
  125931. break;
  125932. }
  125933. }
  125934. sqlite3_free(zVal);
  125935. }
  125936. }
  125937. /* Otherwise, the argument is a column name. */
  125938. else {
  125939. nString += (int)(strlen(z) + 1);
  125940. aCol[nCol++] = z;
  125941. }
  125942. }
  125943. /* If a content=xxx option was specified, the following:
  125944. **
  125945. ** 1. Ignore any compress= and uncompress= options.
  125946. **
  125947. ** 2. If no column names were specified as part of the CREATE VIRTUAL
  125948. ** TABLE statement, use all columns from the content table.
  125949. */
  125950. if( rc==SQLITE_OK && zContent ){
  125951. sqlite3_free(zCompress);
  125952. sqlite3_free(zUncompress);
  125953. zCompress = 0;
  125954. zUncompress = 0;
  125955. if( nCol==0 ){
  125956. sqlite3_free((void*)aCol);
  125957. aCol = 0;
  125958. rc = fts3ContentColumns(db, argv[1], zContent,&aCol,&nCol,&nString,pzErr);
  125959. /* If a languageid= option was specified, remove the language id
  125960. ** column from the aCol[] array. */
  125961. if( rc==SQLITE_OK && zLanguageid ){
  125962. int j;
  125963. for(j=0; j<nCol; j++){
  125964. if( sqlite3_stricmp(zLanguageid, aCol[j])==0 ){
  125965. int k;
  125966. for(k=j; k<nCol; k++) aCol[k] = aCol[k+1];
  125967. nCol--;
  125968. break;
  125969. }
  125970. }
  125971. }
  125972. }
  125973. }
  125974. if( rc!=SQLITE_OK ) goto fts3_init_out;
  125975. if( nCol==0 ){
  125976. assert( nString==0 );
  125977. aCol[0] = "content";
  125978. nString = 8;
  125979. nCol = 1;
  125980. }
  125981. if( pTokenizer==0 ){
  125982. rc = sqlite3Fts3InitTokenizer(pHash, "simple", &pTokenizer, pzErr);
  125983. if( rc!=SQLITE_OK ) goto fts3_init_out;
  125984. }
  125985. assert( pTokenizer );
  125986. rc = fts3PrefixParameter(zPrefix, &nIndex, &aIndex);
  125987. if( rc==SQLITE_ERROR ){
  125988. assert( zPrefix );
  125989. sqlite3Fts3ErrMsg(pzErr, "error parsing prefix parameter: %s", zPrefix);
  125990. }
  125991. if( rc!=SQLITE_OK ) goto fts3_init_out;
  125992. /* Allocate and populate the Fts3Table structure. */
  125993. nByte = sizeof(Fts3Table) + /* Fts3Table */
  125994. nCol * sizeof(char *) + /* azColumn */
  125995. nIndex * sizeof(struct Fts3Index) + /* aIndex */
  125996. nCol * sizeof(u8) + /* abNotindexed */
  125997. nName + /* zName */
  125998. nDb + /* zDb */
  125999. nString; /* Space for azColumn strings */
  126000. p = (Fts3Table*)sqlite3_malloc(nByte);
  126001. if( p==0 ){
  126002. rc = SQLITE_NOMEM;
  126003. goto fts3_init_out;
  126004. }
  126005. memset(p, 0, nByte);
  126006. p->db = db;
  126007. p->nColumn = nCol;
  126008. p->nPendingData = 0;
  126009. p->azColumn = (char **)&p[1];
  126010. p->pTokenizer = pTokenizer;
  126011. p->nMaxPendingData = FTS3_MAX_PENDING_DATA;
  126012. p->bHasDocsize = (isFts4 && bNoDocsize==0);
  126013. p->bHasStat = isFts4;
  126014. p->bFts4 = isFts4;
  126015. p->bDescIdx = bDescIdx;
  126016. p->nAutoincrmerge = 0xff; /* 0xff means setting unknown */
  126017. p->zContentTbl = zContent;
  126018. p->zLanguageid = zLanguageid;
  126019. zContent = 0;
  126020. zLanguageid = 0;
  126021. TESTONLY( p->inTransaction = -1 );
  126022. TESTONLY( p->mxSavepoint = -1 );
  126023. p->aIndex = (struct Fts3Index *)&p->azColumn[nCol];
  126024. memcpy(p->aIndex, aIndex, sizeof(struct Fts3Index) * nIndex);
  126025. p->nIndex = nIndex;
  126026. for(i=0; i<nIndex; i++){
  126027. fts3HashInit(&p->aIndex[i].hPending, FTS3_HASH_STRING, 1);
  126028. }
  126029. p->abNotindexed = (u8 *)&p->aIndex[nIndex];
  126030. /* Fill in the zName and zDb fields of the vtab structure. */
  126031. zCsr = (char *)&p->abNotindexed[nCol];
  126032. p->zName = zCsr;
  126033. memcpy(zCsr, argv[2], nName);
  126034. zCsr += nName;
  126035. p->zDb = zCsr;
  126036. memcpy(zCsr, argv[1], nDb);
  126037. zCsr += nDb;
  126038. /* Fill in the azColumn array */
  126039. for(iCol=0; iCol<nCol; iCol++){
  126040. char *z;
  126041. int n = 0;
  126042. z = (char *)sqlite3Fts3NextToken(aCol[iCol], &n);
  126043. memcpy(zCsr, z, n);
  126044. zCsr[n] = '\0';
  126045. sqlite3Fts3Dequote(zCsr);
  126046. p->azColumn[iCol] = zCsr;
  126047. zCsr += n+1;
  126048. assert( zCsr <= &((char *)p)[nByte] );
  126049. }
  126050. /* Fill in the abNotindexed array */
  126051. for(iCol=0; iCol<nCol; iCol++){
  126052. int n = (int)strlen(p->azColumn[iCol]);
  126053. for(i=0; i<nNotindexed; i++){
  126054. char *zNot = azNotindexed[i];
  126055. if( zNot && n==(int)strlen(zNot)
  126056. && 0==sqlite3_strnicmp(p->azColumn[iCol], zNot, n)
  126057. ){
  126058. p->abNotindexed[iCol] = 1;
  126059. sqlite3_free(zNot);
  126060. azNotindexed[i] = 0;
  126061. }
  126062. }
  126063. }
  126064. for(i=0; i<nNotindexed; i++){
  126065. if( azNotindexed[i] ){
  126066. sqlite3Fts3ErrMsg(pzErr, "no such column: %s", azNotindexed[i]);
  126067. rc = SQLITE_ERROR;
  126068. }
  126069. }
  126070. if( rc==SQLITE_OK && (zCompress==0)!=(zUncompress==0) ){
  126071. char const *zMiss = (zCompress==0 ? "compress" : "uncompress");
  126072. rc = SQLITE_ERROR;
  126073. sqlite3Fts3ErrMsg(pzErr, "missing %s parameter in fts4 constructor", zMiss);
  126074. }
  126075. p->zReadExprlist = fts3ReadExprList(p, zUncompress, &rc);
  126076. p->zWriteExprlist = fts3WriteExprList(p, zCompress, &rc);
  126077. if( rc!=SQLITE_OK ) goto fts3_init_out;
  126078. /* If this is an xCreate call, create the underlying tables in the
  126079. ** database. TODO: For xConnect(), it could verify that said tables exist.
  126080. */
  126081. if( isCreate ){
  126082. rc = fts3CreateTables(p);
  126083. }
  126084. /* Check to see if a legacy fts3 table has been "upgraded" by the
  126085. ** addition of a %_stat table so that it can use incremental merge.
  126086. */
  126087. if( !isFts4 && !isCreate ){
  126088. p->bHasStat = 2;
  126089. }
  126090. /* Figure out the page-size for the database. This is required in order to
  126091. ** estimate the cost of loading large doclists from the database. */
  126092. fts3DatabasePageSize(&rc, p);
  126093. p->nNodeSize = p->nPgsz-35;
  126094. /* Declare the table schema to SQLite. */
  126095. fts3DeclareVtab(&rc, p);
  126096. fts3_init_out:
  126097. sqlite3_free(zPrefix);
  126098. sqlite3_free(aIndex);
  126099. sqlite3_free(zCompress);
  126100. sqlite3_free(zUncompress);
  126101. sqlite3_free(zContent);
  126102. sqlite3_free(zLanguageid);
  126103. for(i=0; i<nNotindexed; i++) sqlite3_free(azNotindexed[i]);
  126104. sqlite3_free((void *)aCol);
  126105. sqlite3_free((void *)azNotindexed);
  126106. if( rc!=SQLITE_OK ){
  126107. if( p ){
  126108. fts3DisconnectMethod((sqlite3_vtab *)p);
  126109. }else if( pTokenizer ){
  126110. pTokenizer->pModule->xDestroy(pTokenizer);
  126111. }
  126112. }else{
  126113. assert( p->pSegments==0 );
  126114. *ppVTab = &p->base;
  126115. }
  126116. return rc;
  126117. }
  126118. /*
  126119. ** The xConnect() and xCreate() methods for the virtual table. All the
  126120. ** work is done in function fts3InitVtab().
  126121. */
  126122. static int fts3ConnectMethod(
  126123. sqlite3 *db, /* Database connection */
  126124. void *pAux, /* Pointer to tokenizer hash table */
  126125. int argc, /* Number of elements in argv array */
  126126. const char * const *argv, /* xCreate/xConnect argument array */
  126127. sqlite3_vtab **ppVtab, /* OUT: New sqlite3_vtab object */
  126128. char **pzErr /* OUT: sqlite3_malloc'd error message */
  126129. ){
  126130. return fts3InitVtab(0, db, pAux, argc, argv, ppVtab, pzErr);
  126131. }
  126132. static int fts3CreateMethod(
  126133. sqlite3 *db, /* Database connection */
  126134. void *pAux, /* Pointer to tokenizer hash table */
  126135. int argc, /* Number of elements in argv array */
  126136. const char * const *argv, /* xCreate/xConnect argument array */
  126137. sqlite3_vtab **ppVtab, /* OUT: New sqlite3_vtab object */
  126138. char **pzErr /* OUT: sqlite3_malloc'd error message */
  126139. ){
  126140. return fts3InitVtab(1, db, pAux, argc, argv, ppVtab, pzErr);
  126141. }
  126142. /*
  126143. ** Set the pIdxInfo->estimatedRows variable to nRow. Unless this
  126144. ** extension is currently being used by a version of SQLite too old to
  126145. ** support estimatedRows. In that case this function is a no-op.
  126146. */
  126147. static void fts3SetEstimatedRows(sqlite3_index_info *pIdxInfo, i64 nRow){
  126148. #if SQLITE_VERSION_NUMBER>=3008002
  126149. if( sqlite3_libversion_number()>=3008002 ){
  126150. pIdxInfo->estimatedRows = nRow;
  126151. }
  126152. #endif
  126153. }
  126154. /*
  126155. ** Implementation of the xBestIndex method for FTS3 tables. There
  126156. ** are three possible strategies, in order of preference:
  126157. **
  126158. ** 1. Direct lookup by rowid or docid.
  126159. ** 2. Full-text search using a MATCH operator on a non-docid column.
  126160. ** 3. Linear scan of %_content table.
  126161. */
  126162. static int fts3BestIndexMethod(sqlite3_vtab *pVTab, sqlite3_index_info *pInfo){
  126163. Fts3Table *p = (Fts3Table *)pVTab;
  126164. int i; /* Iterator variable */
  126165. int iCons = -1; /* Index of constraint to use */
  126166. int iLangidCons = -1; /* Index of langid=x constraint, if present */
  126167. int iDocidGe = -1; /* Index of docid>=x constraint, if present */
  126168. int iDocidLe = -1; /* Index of docid<=x constraint, if present */
  126169. int iIdx;
  126170. /* By default use a full table scan. This is an expensive option,
  126171. ** so search through the constraints to see if a more efficient
  126172. ** strategy is possible.
  126173. */
  126174. pInfo->idxNum = FTS3_FULLSCAN_SEARCH;
  126175. pInfo->estimatedCost = 5000000;
  126176. for(i=0; i<pInfo->nConstraint; i++){
  126177. int bDocid; /* True if this constraint is on docid */
  126178. struct sqlite3_index_constraint *pCons = &pInfo->aConstraint[i];
  126179. if( pCons->usable==0 ){
  126180. if( pCons->op==SQLITE_INDEX_CONSTRAINT_MATCH ){
  126181. /* There exists an unusable MATCH constraint. This means that if
  126182. ** the planner does elect to use the results of this call as part
  126183. ** of the overall query plan the user will see an "unable to use
  126184. ** function MATCH in the requested context" error. To discourage
  126185. ** this, return a very high cost here. */
  126186. pInfo->idxNum = FTS3_FULLSCAN_SEARCH;
  126187. pInfo->estimatedCost = 1e50;
  126188. fts3SetEstimatedRows(pInfo, ((sqlite3_int64)1) << 50);
  126189. return SQLITE_OK;
  126190. }
  126191. continue;
  126192. }
  126193. bDocid = (pCons->iColumn<0 || pCons->iColumn==p->nColumn+1);
  126194. /* A direct lookup on the rowid or docid column. Assign a cost of 1.0. */
  126195. if( iCons<0 && pCons->op==SQLITE_INDEX_CONSTRAINT_EQ && bDocid ){
  126196. pInfo->idxNum = FTS3_DOCID_SEARCH;
  126197. pInfo->estimatedCost = 1.0;
  126198. iCons = i;
  126199. }
  126200. /* A MATCH constraint. Use a full-text search.
  126201. **
  126202. ** If there is more than one MATCH constraint available, use the first
  126203. ** one encountered. If there is both a MATCH constraint and a direct
  126204. ** rowid/docid lookup, prefer the MATCH strategy. This is done even
  126205. ** though the rowid/docid lookup is faster than a MATCH query, selecting
  126206. ** it would lead to an "unable to use function MATCH in the requested
  126207. ** context" error.
  126208. */
  126209. if( pCons->op==SQLITE_INDEX_CONSTRAINT_MATCH
  126210. && pCons->iColumn>=0 && pCons->iColumn<=p->nColumn
  126211. ){
  126212. pInfo->idxNum = FTS3_FULLTEXT_SEARCH + pCons->iColumn;
  126213. pInfo->estimatedCost = 2.0;
  126214. iCons = i;
  126215. }
  126216. /* Equality constraint on the langid column */
  126217. if( pCons->op==SQLITE_INDEX_CONSTRAINT_EQ
  126218. && pCons->iColumn==p->nColumn + 2
  126219. ){
  126220. iLangidCons = i;
  126221. }
  126222. if( bDocid ){
  126223. switch( pCons->op ){
  126224. case SQLITE_INDEX_CONSTRAINT_GE:
  126225. case SQLITE_INDEX_CONSTRAINT_GT:
  126226. iDocidGe = i;
  126227. break;
  126228. case SQLITE_INDEX_CONSTRAINT_LE:
  126229. case SQLITE_INDEX_CONSTRAINT_LT:
  126230. iDocidLe = i;
  126231. break;
  126232. }
  126233. }
  126234. }
  126235. iIdx = 1;
  126236. if( iCons>=0 ){
  126237. pInfo->aConstraintUsage[iCons].argvIndex = iIdx++;
  126238. pInfo->aConstraintUsage[iCons].omit = 1;
  126239. }
  126240. if( iLangidCons>=0 ){
  126241. pInfo->idxNum |= FTS3_HAVE_LANGID;
  126242. pInfo->aConstraintUsage[iLangidCons].argvIndex = iIdx++;
  126243. }
  126244. if( iDocidGe>=0 ){
  126245. pInfo->idxNum |= FTS3_HAVE_DOCID_GE;
  126246. pInfo->aConstraintUsage[iDocidGe].argvIndex = iIdx++;
  126247. }
  126248. if( iDocidLe>=0 ){
  126249. pInfo->idxNum |= FTS3_HAVE_DOCID_LE;
  126250. pInfo->aConstraintUsage[iDocidLe].argvIndex = iIdx++;
  126251. }
  126252. /* Regardless of the strategy selected, FTS can deliver rows in rowid (or
  126253. ** docid) order. Both ascending and descending are possible.
  126254. */
  126255. if( pInfo->nOrderBy==1 ){
  126256. struct sqlite3_index_orderby *pOrder = &pInfo->aOrderBy[0];
  126257. if( pOrder->iColumn<0 || pOrder->iColumn==p->nColumn+1 ){
  126258. if( pOrder->desc ){
  126259. pInfo->idxStr = "DESC";
  126260. }else{
  126261. pInfo->idxStr = "ASC";
  126262. }
  126263. pInfo->orderByConsumed = 1;
  126264. }
  126265. }
  126266. assert( p->pSegments==0 );
  126267. return SQLITE_OK;
  126268. }
  126269. /*
  126270. ** Implementation of xOpen method.
  126271. */
  126272. static int fts3OpenMethod(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCsr){
  126273. sqlite3_vtab_cursor *pCsr; /* Allocated cursor */
  126274. UNUSED_PARAMETER(pVTab);
  126275. /* Allocate a buffer large enough for an Fts3Cursor structure. If the
  126276. ** allocation succeeds, zero it and return SQLITE_OK. Otherwise,
  126277. ** if the allocation fails, return SQLITE_NOMEM.
  126278. */
  126279. *ppCsr = pCsr = (sqlite3_vtab_cursor *)sqlite3_malloc(sizeof(Fts3Cursor));
  126280. if( !pCsr ){
  126281. return SQLITE_NOMEM;
  126282. }
  126283. memset(pCsr, 0, sizeof(Fts3Cursor));
  126284. return SQLITE_OK;
  126285. }
  126286. /*
  126287. ** Close the cursor. For additional information see the documentation
  126288. ** on the xClose method of the virtual table interface.
  126289. */
  126290. static int fts3CloseMethod(sqlite3_vtab_cursor *pCursor){
  126291. Fts3Cursor *pCsr = (Fts3Cursor *)pCursor;
  126292. assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 );
  126293. sqlite3_finalize(pCsr->pStmt);
  126294. sqlite3Fts3ExprFree(pCsr->pExpr);
  126295. sqlite3Fts3FreeDeferredTokens(pCsr);
  126296. sqlite3_free(pCsr->aDoclist);
  126297. sqlite3_free(pCsr->aMatchinfo);
  126298. assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 );
  126299. sqlite3_free(pCsr);
  126300. return SQLITE_OK;
  126301. }
  126302. /*
  126303. ** If pCsr->pStmt has not been prepared (i.e. if pCsr->pStmt==0), then
  126304. ** compose and prepare an SQL statement of the form:
  126305. **
  126306. ** "SELECT <columns> FROM %_content WHERE rowid = ?"
  126307. **
  126308. ** (or the equivalent for a content=xxx table) and set pCsr->pStmt to
  126309. ** it. If an error occurs, return an SQLite error code.
  126310. **
  126311. ** Otherwise, set *ppStmt to point to pCsr->pStmt and return SQLITE_OK.
  126312. */
  126313. static int fts3CursorSeekStmt(Fts3Cursor *pCsr, sqlite3_stmt **ppStmt){
  126314. int rc = SQLITE_OK;
  126315. if( pCsr->pStmt==0 ){
  126316. Fts3Table *p = (Fts3Table *)pCsr->base.pVtab;
  126317. char *zSql;
  126318. zSql = sqlite3_mprintf("SELECT %s WHERE rowid = ?", p->zReadExprlist);
  126319. if( !zSql ) return SQLITE_NOMEM;
  126320. rc = sqlite3_prepare_v2(p->db, zSql, -1, &pCsr->pStmt, 0);
  126321. sqlite3_free(zSql);
  126322. }
  126323. *ppStmt = pCsr->pStmt;
  126324. return rc;
  126325. }
  126326. /*
  126327. ** Position the pCsr->pStmt statement so that it is on the row
  126328. ** of the %_content table that contains the last match. Return
  126329. ** SQLITE_OK on success.
  126330. */
  126331. static int fts3CursorSeek(sqlite3_context *pContext, Fts3Cursor *pCsr){
  126332. int rc = SQLITE_OK;
  126333. if( pCsr->isRequireSeek ){
  126334. sqlite3_stmt *pStmt = 0;
  126335. rc = fts3CursorSeekStmt(pCsr, &pStmt);
  126336. if( rc==SQLITE_OK ){
  126337. sqlite3_bind_int64(pCsr->pStmt, 1, pCsr->iPrevId);
  126338. pCsr->isRequireSeek = 0;
  126339. if( SQLITE_ROW==sqlite3_step(pCsr->pStmt) ){
  126340. return SQLITE_OK;
  126341. }else{
  126342. rc = sqlite3_reset(pCsr->pStmt);
  126343. if( rc==SQLITE_OK && ((Fts3Table *)pCsr->base.pVtab)->zContentTbl==0 ){
  126344. /* If no row was found and no error has occurred, then the %_content
  126345. ** table is missing a row that is present in the full-text index.
  126346. ** The data structures are corrupt. */
  126347. rc = FTS_CORRUPT_VTAB;
  126348. pCsr->isEof = 1;
  126349. }
  126350. }
  126351. }
  126352. }
  126353. if( rc!=SQLITE_OK && pContext ){
  126354. sqlite3_result_error_code(pContext, rc);
  126355. }
  126356. return rc;
  126357. }
  126358. /*
  126359. ** This function is used to process a single interior node when searching
  126360. ** a b-tree for a term or term prefix. The node data is passed to this
  126361. ** function via the zNode/nNode parameters. The term to search for is
  126362. ** passed in zTerm/nTerm.
  126363. **
  126364. ** If piFirst is not NULL, then this function sets *piFirst to the blockid
  126365. ** of the child node that heads the sub-tree that may contain the term.
  126366. **
  126367. ** If piLast is not NULL, then *piLast is set to the right-most child node
  126368. ** that heads a sub-tree that may contain a term for which zTerm/nTerm is
  126369. ** a prefix.
  126370. **
  126371. ** If an OOM error occurs, SQLITE_NOMEM is returned. Otherwise, SQLITE_OK.
  126372. */
  126373. static int fts3ScanInteriorNode(
  126374. const char *zTerm, /* Term to select leaves for */
  126375. int nTerm, /* Size of term zTerm in bytes */
  126376. const char *zNode, /* Buffer containing segment interior node */
  126377. int nNode, /* Size of buffer at zNode */
  126378. sqlite3_int64 *piFirst, /* OUT: Selected child node */
  126379. sqlite3_int64 *piLast /* OUT: Selected child node */
  126380. ){
  126381. int rc = SQLITE_OK; /* Return code */
  126382. const char *zCsr = zNode; /* Cursor to iterate through node */
  126383. const char *zEnd = &zCsr[nNode];/* End of interior node buffer */
  126384. char *zBuffer = 0; /* Buffer to load terms into */
  126385. int nAlloc = 0; /* Size of allocated buffer */
  126386. int isFirstTerm = 1; /* True when processing first term on page */
  126387. sqlite3_int64 iChild; /* Block id of child node to descend to */
  126388. /* Skip over the 'height' varint that occurs at the start of every
  126389. ** interior node. Then load the blockid of the left-child of the b-tree
  126390. ** node into variable iChild.
  126391. **
  126392. ** Even if the data structure on disk is corrupted, this (reading two
  126393. ** varints from the buffer) does not risk an overread. If zNode is a
  126394. ** root node, then the buffer comes from a SELECT statement. SQLite does
  126395. ** not make this guarantee explicitly, but in practice there are always
  126396. ** either more than 20 bytes of allocated space following the nNode bytes of
  126397. ** contents, or two zero bytes. Or, if the node is read from the %_segments
  126398. ** table, then there are always 20 bytes of zeroed padding following the
  126399. ** nNode bytes of content (see sqlite3Fts3ReadBlock() for details).
  126400. */
  126401. zCsr += sqlite3Fts3GetVarint(zCsr, &iChild);
  126402. zCsr += sqlite3Fts3GetVarint(zCsr, &iChild);
  126403. if( zCsr>zEnd ){
  126404. return FTS_CORRUPT_VTAB;
  126405. }
  126406. while( zCsr<zEnd && (piFirst || piLast) ){
  126407. int cmp; /* memcmp() result */
  126408. int nSuffix; /* Size of term suffix */
  126409. int nPrefix = 0; /* Size of term prefix */
  126410. int nBuffer; /* Total term size */
  126411. /* Load the next term on the node into zBuffer. Use realloc() to expand
  126412. ** the size of zBuffer if required. */
  126413. if( !isFirstTerm ){
  126414. zCsr += fts3GetVarint32(zCsr, &nPrefix);
  126415. }
  126416. isFirstTerm = 0;
  126417. zCsr += fts3GetVarint32(zCsr, &nSuffix);
  126418. if( nPrefix<0 || nSuffix<0 || &zCsr[nSuffix]>zEnd ){
  126419. rc = FTS_CORRUPT_VTAB;
  126420. goto finish_scan;
  126421. }
  126422. if( nPrefix+nSuffix>nAlloc ){
  126423. char *zNew;
  126424. nAlloc = (nPrefix+nSuffix) * 2;
  126425. zNew = (char *)sqlite3_realloc(zBuffer, nAlloc);
  126426. if( !zNew ){
  126427. rc = SQLITE_NOMEM;
  126428. goto finish_scan;
  126429. }
  126430. zBuffer = zNew;
  126431. }
  126432. assert( zBuffer );
  126433. memcpy(&zBuffer[nPrefix], zCsr, nSuffix);
  126434. nBuffer = nPrefix + nSuffix;
  126435. zCsr += nSuffix;
  126436. /* Compare the term we are searching for with the term just loaded from
  126437. ** the interior node. If the specified term is greater than or equal
  126438. ** to the term from the interior node, then all terms on the sub-tree
  126439. ** headed by node iChild are smaller than zTerm. No need to search
  126440. ** iChild.
  126441. **
  126442. ** If the interior node term is larger than the specified term, then
  126443. ** the tree headed by iChild may contain the specified term.
  126444. */
  126445. cmp = memcmp(zTerm, zBuffer, (nBuffer>nTerm ? nTerm : nBuffer));
  126446. if( piFirst && (cmp<0 || (cmp==0 && nBuffer>nTerm)) ){
  126447. *piFirst = iChild;
  126448. piFirst = 0;
  126449. }
  126450. if( piLast && cmp<0 ){
  126451. *piLast = iChild;
  126452. piLast = 0;
  126453. }
  126454. iChild++;
  126455. };
  126456. if( piFirst ) *piFirst = iChild;
  126457. if( piLast ) *piLast = iChild;
  126458. finish_scan:
  126459. sqlite3_free(zBuffer);
  126460. return rc;
  126461. }
  126462. /*
  126463. ** The buffer pointed to by argument zNode (size nNode bytes) contains an
  126464. ** interior node of a b-tree segment. The zTerm buffer (size nTerm bytes)
  126465. ** contains a term. This function searches the sub-tree headed by the zNode
  126466. ** node for the range of leaf nodes that may contain the specified term
  126467. ** or terms for which the specified term is a prefix.
  126468. **
  126469. ** If piLeaf is not NULL, then *piLeaf is set to the blockid of the
  126470. ** left-most leaf node in the tree that may contain the specified term.
  126471. ** If piLeaf2 is not NULL, then *piLeaf2 is set to the blockid of the
  126472. ** right-most leaf node that may contain a term for which the specified
  126473. ** term is a prefix.
  126474. **
  126475. ** It is possible that the range of returned leaf nodes does not contain
  126476. ** the specified term or any terms for which it is a prefix. However, if the
  126477. ** segment does contain any such terms, they are stored within the identified
  126478. ** range. Because this function only inspects interior segment nodes (and
  126479. ** never loads leaf nodes into memory), it is not possible to be sure.
  126480. **
  126481. ** If an error occurs, an error code other than SQLITE_OK is returned.
  126482. */
  126483. static int fts3SelectLeaf(
  126484. Fts3Table *p, /* Virtual table handle */
  126485. const char *zTerm, /* Term to select leaves for */
  126486. int nTerm, /* Size of term zTerm in bytes */
  126487. const char *zNode, /* Buffer containing segment interior node */
  126488. int nNode, /* Size of buffer at zNode */
  126489. sqlite3_int64 *piLeaf, /* Selected leaf node */
  126490. sqlite3_int64 *piLeaf2 /* Selected leaf node */
  126491. ){
  126492. int rc = SQLITE_OK; /* Return code */
  126493. int iHeight; /* Height of this node in tree */
  126494. assert( piLeaf || piLeaf2 );
  126495. fts3GetVarint32(zNode, &iHeight);
  126496. rc = fts3ScanInteriorNode(zTerm, nTerm, zNode, nNode, piLeaf, piLeaf2);
  126497. assert( !piLeaf2 || !piLeaf || rc!=SQLITE_OK || (*piLeaf<=*piLeaf2) );
  126498. if( rc==SQLITE_OK && iHeight>1 ){
  126499. char *zBlob = 0; /* Blob read from %_segments table */
  126500. int nBlob = 0; /* Size of zBlob in bytes */
  126501. if( piLeaf && piLeaf2 && (*piLeaf!=*piLeaf2) ){
  126502. rc = sqlite3Fts3ReadBlock(p, *piLeaf, &zBlob, &nBlob, 0);
  126503. if( rc==SQLITE_OK ){
  126504. rc = fts3SelectLeaf(p, zTerm, nTerm, zBlob, nBlob, piLeaf, 0);
  126505. }
  126506. sqlite3_free(zBlob);
  126507. piLeaf = 0;
  126508. zBlob = 0;
  126509. }
  126510. if( rc==SQLITE_OK ){
  126511. rc = sqlite3Fts3ReadBlock(p, piLeaf?*piLeaf:*piLeaf2, &zBlob, &nBlob, 0);
  126512. }
  126513. if( rc==SQLITE_OK ){
  126514. rc = fts3SelectLeaf(p, zTerm, nTerm, zBlob, nBlob, piLeaf, piLeaf2);
  126515. }
  126516. sqlite3_free(zBlob);
  126517. }
  126518. return rc;
  126519. }
  126520. /*
  126521. ** This function is used to create delta-encoded serialized lists of FTS3
  126522. ** varints. Each call to this function appends a single varint to a list.
  126523. */
  126524. static void fts3PutDeltaVarint(
  126525. char **pp, /* IN/OUT: Output pointer */
  126526. sqlite3_int64 *piPrev, /* IN/OUT: Previous value written to list */
  126527. sqlite3_int64 iVal /* Write this value to the list */
  126528. ){
  126529. assert( iVal-*piPrev > 0 || (*piPrev==0 && iVal==0) );
  126530. *pp += sqlite3Fts3PutVarint(*pp, iVal-*piPrev);
  126531. *piPrev = iVal;
  126532. }
  126533. /*
  126534. ** When this function is called, *ppPoslist is assumed to point to the
  126535. ** start of a position-list. After it returns, *ppPoslist points to the
  126536. ** first byte after the position-list.
  126537. **
  126538. ** A position list is list of positions (delta encoded) and columns for
  126539. ** a single document record of a doclist. So, in other words, this
  126540. ** routine advances *ppPoslist so that it points to the next docid in
  126541. ** the doclist, or to the first byte past the end of the doclist.
  126542. **
  126543. ** If pp is not NULL, then the contents of the position list are copied
  126544. ** to *pp. *pp is set to point to the first byte past the last byte copied
  126545. ** before this function returns.
  126546. */
  126547. static void fts3PoslistCopy(char **pp, char **ppPoslist){
  126548. char *pEnd = *ppPoslist;
  126549. char c = 0;
  126550. /* The end of a position list is marked by a zero encoded as an FTS3
  126551. ** varint. A single POS_END (0) byte. Except, if the 0 byte is preceded by
  126552. ** a byte with the 0x80 bit set, then it is not a varint 0, but the tail
  126553. ** of some other, multi-byte, value.
  126554. **
  126555. ** The following while-loop moves pEnd to point to the first byte that is not
  126556. ** immediately preceded by a byte with the 0x80 bit set. Then increments
  126557. ** pEnd once more so that it points to the byte immediately following the
  126558. ** last byte in the position-list.
  126559. */
  126560. while( *pEnd | c ){
  126561. c = *pEnd++ & 0x80;
  126562. testcase( c!=0 && (*pEnd)==0 );
  126563. }
  126564. pEnd++; /* Advance past the POS_END terminator byte */
  126565. if( pp ){
  126566. int n = (int)(pEnd - *ppPoslist);
  126567. char *p = *pp;
  126568. memcpy(p, *ppPoslist, n);
  126569. p += n;
  126570. *pp = p;
  126571. }
  126572. *ppPoslist = pEnd;
  126573. }
  126574. /*
  126575. ** When this function is called, *ppPoslist is assumed to point to the
  126576. ** start of a column-list. After it returns, *ppPoslist points to the
  126577. ** to the terminator (POS_COLUMN or POS_END) byte of the column-list.
  126578. **
  126579. ** A column-list is list of delta-encoded positions for a single column
  126580. ** within a single document within a doclist.
  126581. **
  126582. ** The column-list is terminated either by a POS_COLUMN varint (1) or
  126583. ** a POS_END varint (0). This routine leaves *ppPoslist pointing to
  126584. ** the POS_COLUMN or POS_END that terminates the column-list.
  126585. **
  126586. ** If pp is not NULL, then the contents of the column-list are copied
  126587. ** to *pp. *pp is set to point to the first byte past the last byte copied
  126588. ** before this function returns. The POS_COLUMN or POS_END terminator
  126589. ** is not copied into *pp.
  126590. */
  126591. static void fts3ColumnlistCopy(char **pp, char **ppPoslist){
  126592. char *pEnd = *ppPoslist;
  126593. char c = 0;
  126594. /* A column-list is terminated by either a 0x01 or 0x00 byte that is
  126595. ** not part of a multi-byte varint.
  126596. */
  126597. while( 0xFE & (*pEnd | c) ){
  126598. c = *pEnd++ & 0x80;
  126599. testcase( c!=0 && ((*pEnd)&0xfe)==0 );
  126600. }
  126601. if( pp ){
  126602. int n = (int)(pEnd - *ppPoslist);
  126603. char *p = *pp;
  126604. memcpy(p, *ppPoslist, n);
  126605. p += n;
  126606. *pp = p;
  126607. }
  126608. *ppPoslist = pEnd;
  126609. }
  126610. /*
  126611. ** Value used to signify the end of an position-list. This is safe because
  126612. ** it is not possible to have a document with 2^31 terms.
  126613. */
  126614. #define POSITION_LIST_END 0x7fffffff
  126615. /*
  126616. ** This function is used to help parse position-lists. When this function is
  126617. ** called, *pp may point to the start of the next varint in the position-list
  126618. ** being parsed, or it may point to 1 byte past the end of the position-list
  126619. ** (in which case **pp will be a terminator bytes POS_END (0) or
  126620. ** (1)).
  126621. **
  126622. ** If *pp points past the end of the current position-list, set *pi to
  126623. ** POSITION_LIST_END and return. Otherwise, read the next varint from *pp,
  126624. ** increment the current value of *pi by the value read, and set *pp to
  126625. ** point to the next value before returning.
  126626. **
  126627. ** Before calling this routine *pi must be initialized to the value of
  126628. ** the previous position, or zero if we are reading the first position
  126629. ** in the position-list. Because positions are delta-encoded, the value
  126630. ** of the previous position is needed in order to compute the value of
  126631. ** the next position.
  126632. */
  126633. static void fts3ReadNextPos(
  126634. char **pp, /* IN/OUT: Pointer into position-list buffer */
  126635. sqlite3_int64 *pi /* IN/OUT: Value read from position-list */
  126636. ){
  126637. if( (**pp)&0xFE ){
  126638. fts3GetDeltaVarint(pp, pi);
  126639. *pi -= 2;
  126640. }else{
  126641. *pi = POSITION_LIST_END;
  126642. }
  126643. }
  126644. /*
  126645. ** If parameter iCol is not 0, write an POS_COLUMN (1) byte followed by
  126646. ** the value of iCol encoded as a varint to *pp. This will start a new
  126647. ** column list.
  126648. **
  126649. ** Set *pp to point to the byte just after the last byte written before
  126650. ** returning (do not modify it if iCol==0). Return the total number of bytes
  126651. ** written (0 if iCol==0).
  126652. */
  126653. static int fts3PutColNumber(char **pp, int iCol){
  126654. int n = 0; /* Number of bytes written */
  126655. if( iCol ){
  126656. char *p = *pp; /* Output pointer */
  126657. n = 1 + sqlite3Fts3PutVarint(&p[1], iCol);
  126658. *p = 0x01;
  126659. *pp = &p[n];
  126660. }
  126661. return n;
  126662. }
  126663. /*
  126664. ** Compute the union of two position lists. The output written
  126665. ** into *pp contains all positions of both *pp1 and *pp2 in sorted
  126666. ** order and with any duplicates removed. All pointers are
  126667. ** updated appropriately. The caller is responsible for insuring
  126668. ** that there is enough space in *pp to hold the complete output.
  126669. */
  126670. static void fts3PoslistMerge(
  126671. char **pp, /* Output buffer */
  126672. char **pp1, /* Left input list */
  126673. char **pp2 /* Right input list */
  126674. ){
  126675. char *p = *pp;
  126676. char *p1 = *pp1;
  126677. char *p2 = *pp2;
  126678. while( *p1 || *p2 ){
  126679. int iCol1; /* The current column index in pp1 */
  126680. int iCol2; /* The current column index in pp2 */
  126681. if( *p1==POS_COLUMN ) fts3GetVarint32(&p1[1], &iCol1);
  126682. else if( *p1==POS_END ) iCol1 = POSITION_LIST_END;
  126683. else iCol1 = 0;
  126684. if( *p2==POS_COLUMN ) fts3GetVarint32(&p2[1], &iCol2);
  126685. else if( *p2==POS_END ) iCol2 = POSITION_LIST_END;
  126686. else iCol2 = 0;
  126687. if( iCol1==iCol2 ){
  126688. sqlite3_int64 i1 = 0; /* Last position from pp1 */
  126689. sqlite3_int64 i2 = 0; /* Last position from pp2 */
  126690. sqlite3_int64 iPrev = 0;
  126691. int n = fts3PutColNumber(&p, iCol1);
  126692. p1 += n;
  126693. p2 += n;
  126694. /* At this point, both p1 and p2 point to the start of column-lists
  126695. ** for the same column (the column with index iCol1 and iCol2).
  126696. ** A column-list is a list of non-negative delta-encoded varints, each
  126697. ** incremented by 2 before being stored. Each list is terminated by a
  126698. ** POS_END (0) or POS_COLUMN (1). The following block merges the two lists
  126699. ** and writes the results to buffer p. p is left pointing to the byte
  126700. ** after the list written. No terminator (POS_END or POS_COLUMN) is
  126701. ** written to the output.
  126702. */
  126703. fts3GetDeltaVarint(&p1, &i1);
  126704. fts3GetDeltaVarint(&p2, &i2);
  126705. do {
  126706. fts3PutDeltaVarint(&p, &iPrev, (i1<i2) ? i1 : i2);
  126707. iPrev -= 2;
  126708. if( i1==i2 ){
  126709. fts3ReadNextPos(&p1, &i1);
  126710. fts3ReadNextPos(&p2, &i2);
  126711. }else if( i1<i2 ){
  126712. fts3ReadNextPos(&p1, &i1);
  126713. }else{
  126714. fts3ReadNextPos(&p2, &i2);
  126715. }
  126716. }while( i1!=POSITION_LIST_END || i2!=POSITION_LIST_END );
  126717. }else if( iCol1<iCol2 ){
  126718. p1 += fts3PutColNumber(&p, iCol1);
  126719. fts3ColumnlistCopy(&p, &p1);
  126720. }else{
  126721. p2 += fts3PutColNumber(&p, iCol2);
  126722. fts3ColumnlistCopy(&p, &p2);
  126723. }
  126724. }
  126725. *p++ = POS_END;
  126726. *pp = p;
  126727. *pp1 = p1 + 1;
  126728. *pp2 = p2 + 1;
  126729. }
  126730. /*
  126731. ** This function is used to merge two position lists into one. When it is
  126732. ** called, *pp1 and *pp2 must both point to position lists. A position-list is
  126733. ** the part of a doclist that follows each document id. For example, if a row
  126734. ** contains:
  126735. **
  126736. ** 'a b c'|'x y z'|'a b b a'
  126737. **
  126738. ** Then the position list for this row for token 'b' would consist of:
  126739. **
  126740. ** 0x02 0x01 0x02 0x03 0x03 0x00
  126741. **
  126742. ** When this function returns, both *pp1 and *pp2 are left pointing to the
  126743. ** byte following the 0x00 terminator of their respective position lists.
  126744. **
  126745. ** If isSaveLeft is 0, an entry is added to the output position list for
  126746. ** each position in *pp2 for which there exists one or more positions in
  126747. ** *pp1 so that (pos(*pp2)>pos(*pp1) && pos(*pp2)-pos(*pp1)<=nToken). i.e.
  126748. ** when the *pp1 token appears before the *pp2 token, but not more than nToken
  126749. ** slots before it.
  126750. **
  126751. ** e.g. nToken==1 searches for adjacent positions.
  126752. */
  126753. static int fts3PoslistPhraseMerge(
  126754. char **pp, /* IN/OUT: Preallocated output buffer */
  126755. int nToken, /* Maximum difference in token positions */
  126756. int isSaveLeft, /* Save the left position */
  126757. int isExact, /* If *pp1 is exactly nTokens before *pp2 */
  126758. char **pp1, /* IN/OUT: Left input list */
  126759. char **pp2 /* IN/OUT: Right input list */
  126760. ){
  126761. char *p = *pp;
  126762. char *p1 = *pp1;
  126763. char *p2 = *pp2;
  126764. int iCol1 = 0;
  126765. int iCol2 = 0;
  126766. /* Never set both isSaveLeft and isExact for the same invocation. */
  126767. assert( isSaveLeft==0 || isExact==0 );
  126768. assert( p!=0 && *p1!=0 && *p2!=0 );
  126769. if( *p1==POS_COLUMN ){
  126770. p1++;
  126771. p1 += fts3GetVarint32(p1, &iCol1);
  126772. }
  126773. if( *p2==POS_COLUMN ){
  126774. p2++;
  126775. p2 += fts3GetVarint32(p2, &iCol2);
  126776. }
  126777. while( 1 ){
  126778. if( iCol1==iCol2 ){
  126779. char *pSave = p;
  126780. sqlite3_int64 iPrev = 0;
  126781. sqlite3_int64 iPos1 = 0;
  126782. sqlite3_int64 iPos2 = 0;
  126783. if( iCol1 ){
  126784. *p++ = POS_COLUMN;
  126785. p += sqlite3Fts3PutVarint(p, iCol1);
  126786. }
  126787. assert( *p1!=POS_END && *p1!=POS_COLUMN );
  126788. assert( *p2!=POS_END && *p2!=POS_COLUMN );
  126789. fts3GetDeltaVarint(&p1, &iPos1); iPos1 -= 2;
  126790. fts3GetDeltaVarint(&p2, &iPos2); iPos2 -= 2;
  126791. while( 1 ){
  126792. if( iPos2==iPos1+nToken
  126793. || (isExact==0 && iPos2>iPos1 && iPos2<=iPos1+nToken)
  126794. ){
  126795. sqlite3_int64 iSave;
  126796. iSave = isSaveLeft ? iPos1 : iPos2;
  126797. fts3PutDeltaVarint(&p, &iPrev, iSave+2); iPrev -= 2;
  126798. pSave = 0;
  126799. assert( p );
  126800. }
  126801. if( (!isSaveLeft && iPos2<=(iPos1+nToken)) || iPos2<=iPos1 ){
  126802. if( (*p2&0xFE)==0 ) break;
  126803. fts3GetDeltaVarint(&p2, &iPos2); iPos2 -= 2;
  126804. }else{
  126805. if( (*p1&0xFE)==0 ) break;
  126806. fts3GetDeltaVarint(&p1, &iPos1); iPos1 -= 2;
  126807. }
  126808. }
  126809. if( pSave ){
  126810. assert( pp && p );
  126811. p = pSave;
  126812. }
  126813. fts3ColumnlistCopy(0, &p1);
  126814. fts3ColumnlistCopy(0, &p2);
  126815. assert( (*p1&0xFE)==0 && (*p2&0xFE)==0 );
  126816. if( 0==*p1 || 0==*p2 ) break;
  126817. p1++;
  126818. p1 += fts3GetVarint32(p1, &iCol1);
  126819. p2++;
  126820. p2 += fts3GetVarint32(p2, &iCol2);
  126821. }
  126822. /* Advance pointer p1 or p2 (whichever corresponds to the smaller of
  126823. ** iCol1 and iCol2) so that it points to either the 0x00 that marks the
  126824. ** end of the position list, or the 0x01 that precedes the next
  126825. ** column-number in the position list.
  126826. */
  126827. else if( iCol1<iCol2 ){
  126828. fts3ColumnlistCopy(0, &p1);
  126829. if( 0==*p1 ) break;
  126830. p1++;
  126831. p1 += fts3GetVarint32(p1, &iCol1);
  126832. }else{
  126833. fts3ColumnlistCopy(0, &p2);
  126834. if( 0==*p2 ) break;
  126835. p2++;
  126836. p2 += fts3GetVarint32(p2, &iCol2);
  126837. }
  126838. }
  126839. fts3PoslistCopy(0, &p2);
  126840. fts3PoslistCopy(0, &p1);
  126841. *pp1 = p1;
  126842. *pp2 = p2;
  126843. if( *pp==p ){
  126844. return 0;
  126845. }
  126846. *p++ = 0x00;
  126847. *pp = p;
  126848. return 1;
  126849. }
  126850. /*
  126851. ** Merge two position-lists as required by the NEAR operator. The argument
  126852. ** position lists correspond to the left and right phrases of an expression
  126853. ** like:
  126854. **
  126855. ** "phrase 1" NEAR "phrase number 2"
  126856. **
  126857. ** Position list *pp1 corresponds to the left-hand side of the NEAR
  126858. ** expression and *pp2 to the right. As usual, the indexes in the position
  126859. ** lists are the offsets of the last token in each phrase (tokens "1" and "2"
  126860. ** in the example above).
  126861. **
  126862. ** The output position list - written to *pp - is a copy of *pp2 with those
  126863. ** entries that are not sufficiently NEAR entries in *pp1 removed.
  126864. */
  126865. static int fts3PoslistNearMerge(
  126866. char **pp, /* Output buffer */
  126867. char *aTmp, /* Temporary buffer space */
  126868. int nRight, /* Maximum difference in token positions */
  126869. int nLeft, /* Maximum difference in token positions */
  126870. char **pp1, /* IN/OUT: Left input list */
  126871. char **pp2 /* IN/OUT: Right input list */
  126872. ){
  126873. char *p1 = *pp1;
  126874. char *p2 = *pp2;
  126875. char *pTmp1 = aTmp;
  126876. char *pTmp2;
  126877. char *aTmp2;
  126878. int res = 1;
  126879. fts3PoslistPhraseMerge(&pTmp1, nRight, 0, 0, pp1, pp2);
  126880. aTmp2 = pTmp2 = pTmp1;
  126881. *pp1 = p1;
  126882. *pp2 = p2;
  126883. fts3PoslistPhraseMerge(&pTmp2, nLeft, 1, 0, pp2, pp1);
  126884. if( pTmp1!=aTmp && pTmp2!=aTmp2 ){
  126885. fts3PoslistMerge(pp, &aTmp, &aTmp2);
  126886. }else if( pTmp1!=aTmp ){
  126887. fts3PoslistCopy(pp, &aTmp);
  126888. }else if( pTmp2!=aTmp2 ){
  126889. fts3PoslistCopy(pp, &aTmp2);
  126890. }else{
  126891. res = 0;
  126892. }
  126893. return res;
  126894. }
  126895. /*
  126896. ** An instance of this function is used to merge together the (potentially
  126897. ** large number of) doclists for each term that matches a prefix query.
  126898. ** See function fts3TermSelectMerge() for details.
  126899. */
  126900. typedef struct TermSelect TermSelect;
  126901. struct TermSelect {
  126902. char *aaOutput[16]; /* Malloc'd output buffers */
  126903. int anOutput[16]; /* Size each output buffer in bytes */
  126904. };
  126905. /*
  126906. ** This function is used to read a single varint from a buffer. Parameter
  126907. ** pEnd points 1 byte past the end of the buffer. When this function is
  126908. ** called, if *pp points to pEnd or greater, then the end of the buffer
  126909. ** has been reached. In this case *pp is set to 0 and the function returns.
  126910. **
  126911. ** If *pp does not point to or past pEnd, then a single varint is read
  126912. ** from *pp. *pp is then set to point 1 byte past the end of the read varint.
  126913. **
  126914. ** If bDescIdx is false, the value read is added to *pVal before returning.
  126915. ** If it is true, the value read is subtracted from *pVal before this
  126916. ** function returns.
  126917. */
  126918. static void fts3GetDeltaVarint3(
  126919. char **pp, /* IN/OUT: Point to read varint from */
  126920. char *pEnd, /* End of buffer */
  126921. int bDescIdx, /* True if docids are descending */
  126922. sqlite3_int64 *pVal /* IN/OUT: Integer value */
  126923. ){
  126924. if( *pp>=pEnd ){
  126925. *pp = 0;
  126926. }else{
  126927. sqlite3_int64 iVal;
  126928. *pp += sqlite3Fts3GetVarint(*pp, &iVal);
  126929. if( bDescIdx ){
  126930. *pVal -= iVal;
  126931. }else{
  126932. *pVal += iVal;
  126933. }
  126934. }
  126935. }
  126936. /*
  126937. ** This function is used to write a single varint to a buffer. The varint
  126938. ** is written to *pp. Before returning, *pp is set to point 1 byte past the
  126939. ** end of the value written.
  126940. **
  126941. ** If *pbFirst is zero when this function is called, the value written to
  126942. ** the buffer is that of parameter iVal.
  126943. **
  126944. ** If *pbFirst is non-zero when this function is called, then the value
  126945. ** written is either (iVal-*piPrev) (if bDescIdx is zero) or (*piPrev-iVal)
  126946. ** (if bDescIdx is non-zero).
  126947. **
  126948. ** Before returning, this function always sets *pbFirst to 1 and *piPrev
  126949. ** to the value of parameter iVal.
  126950. */
  126951. static void fts3PutDeltaVarint3(
  126952. char **pp, /* IN/OUT: Output pointer */
  126953. int bDescIdx, /* True for descending docids */
  126954. sqlite3_int64 *piPrev, /* IN/OUT: Previous value written to list */
  126955. int *pbFirst, /* IN/OUT: True after first int written */
  126956. sqlite3_int64 iVal /* Write this value to the list */
  126957. ){
  126958. sqlite3_int64 iWrite;
  126959. if( bDescIdx==0 || *pbFirst==0 ){
  126960. iWrite = iVal - *piPrev;
  126961. }else{
  126962. iWrite = *piPrev - iVal;
  126963. }
  126964. assert( *pbFirst || *piPrev==0 );
  126965. assert( *pbFirst==0 || iWrite>0 );
  126966. *pp += sqlite3Fts3PutVarint(*pp, iWrite);
  126967. *piPrev = iVal;
  126968. *pbFirst = 1;
  126969. }
  126970. /*
  126971. ** This macro is used by various functions that merge doclists. The two
  126972. ** arguments are 64-bit docid values. If the value of the stack variable
  126973. ** bDescDoclist is 0 when this macro is invoked, then it returns (i1-i2).
  126974. ** Otherwise, (i2-i1).
  126975. **
  126976. ** Using this makes it easier to write code that can merge doclists that are
  126977. ** sorted in either ascending or descending order.
  126978. */
  126979. #define DOCID_CMP(i1, i2) ((bDescDoclist?-1:1) * (i1-i2))
  126980. /*
  126981. ** This function does an "OR" merge of two doclists (output contains all
  126982. ** positions contained in either argument doclist). If the docids in the
  126983. ** input doclists are sorted in ascending order, parameter bDescDoclist
  126984. ** should be false. If they are sorted in ascending order, it should be
  126985. ** passed a non-zero value.
  126986. **
  126987. ** If no error occurs, *paOut is set to point at an sqlite3_malloc'd buffer
  126988. ** containing the output doclist and SQLITE_OK is returned. In this case
  126989. ** *pnOut is set to the number of bytes in the output doclist.
  126990. **
  126991. ** If an error occurs, an SQLite error code is returned. The output values
  126992. ** are undefined in this case.
  126993. */
  126994. static int fts3DoclistOrMerge(
  126995. int bDescDoclist, /* True if arguments are desc */
  126996. char *a1, int n1, /* First doclist */
  126997. char *a2, int n2, /* Second doclist */
  126998. char **paOut, int *pnOut /* OUT: Malloc'd doclist */
  126999. ){
  127000. sqlite3_int64 i1 = 0;
  127001. sqlite3_int64 i2 = 0;
  127002. sqlite3_int64 iPrev = 0;
  127003. char *pEnd1 = &a1[n1];
  127004. char *pEnd2 = &a2[n2];
  127005. char *p1 = a1;
  127006. char *p2 = a2;
  127007. char *p;
  127008. char *aOut;
  127009. int bFirstOut = 0;
  127010. *paOut = 0;
  127011. *pnOut = 0;
  127012. /* Allocate space for the output. Both the input and output doclists
  127013. ** are delta encoded. If they are in ascending order (bDescDoclist==0),
  127014. ** then the first docid in each list is simply encoded as a varint. For
  127015. ** each subsequent docid, the varint stored is the difference between the
  127016. ** current and previous docid (a positive number - since the list is in
  127017. ** ascending order).
  127018. **
  127019. ** The first docid written to the output is therefore encoded using the
  127020. ** same number of bytes as it is in whichever of the input lists it is
  127021. ** read from. And each subsequent docid read from the same input list
  127022. ** consumes either the same or less bytes as it did in the input (since
  127023. ** the difference between it and the previous value in the output must
  127024. ** be a positive value less than or equal to the delta value read from
  127025. ** the input list). The same argument applies to all but the first docid
  127026. ** read from the 'other' list. And to the contents of all position lists
  127027. ** that will be copied and merged from the input to the output.
  127028. **
  127029. ** However, if the first docid copied to the output is a negative number,
  127030. ** then the encoding of the first docid from the 'other' input list may
  127031. ** be larger in the output than it was in the input (since the delta value
  127032. ** may be a larger positive integer than the actual docid).
  127033. **
  127034. ** The space required to store the output is therefore the sum of the
  127035. ** sizes of the two inputs, plus enough space for exactly one of the input
  127036. ** docids to grow.
  127037. **
  127038. ** A symetric argument may be made if the doclists are in descending
  127039. ** order.
  127040. */
  127041. aOut = sqlite3_malloc(n1+n2+FTS3_VARINT_MAX-1);
  127042. if( !aOut ) return SQLITE_NOMEM;
  127043. p = aOut;
  127044. fts3GetDeltaVarint3(&p1, pEnd1, 0, &i1);
  127045. fts3GetDeltaVarint3(&p2, pEnd2, 0, &i2);
  127046. while( p1 || p2 ){
  127047. sqlite3_int64 iDiff = DOCID_CMP(i1, i2);
  127048. if( p2 && p1 && iDiff==0 ){
  127049. fts3PutDeltaVarint3(&p, bDescDoclist, &iPrev, &bFirstOut, i1);
  127050. fts3PoslistMerge(&p, &p1, &p2);
  127051. fts3GetDeltaVarint3(&p1, pEnd1, bDescDoclist, &i1);
  127052. fts3GetDeltaVarint3(&p2, pEnd2, bDescDoclist, &i2);
  127053. }else if( !p2 || (p1 && iDiff<0) ){
  127054. fts3PutDeltaVarint3(&p, bDescDoclist, &iPrev, &bFirstOut, i1);
  127055. fts3PoslistCopy(&p, &p1);
  127056. fts3GetDeltaVarint3(&p1, pEnd1, bDescDoclist, &i1);
  127057. }else{
  127058. fts3PutDeltaVarint3(&p, bDescDoclist, &iPrev, &bFirstOut, i2);
  127059. fts3PoslistCopy(&p, &p2);
  127060. fts3GetDeltaVarint3(&p2, pEnd2, bDescDoclist, &i2);
  127061. }
  127062. }
  127063. *paOut = aOut;
  127064. *pnOut = (int)(p-aOut);
  127065. assert( *pnOut<=n1+n2+FTS3_VARINT_MAX-1 );
  127066. return SQLITE_OK;
  127067. }
  127068. /*
  127069. ** This function does a "phrase" merge of two doclists. In a phrase merge,
  127070. ** the output contains a copy of each position from the right-hand input
  127071. ** doclist for which there is a position in the left-hand input doclist
  127072. ** exactly nDist tokens before it.
  127073. **
  127074. ** If the docids in the input doclists are sorted in ascending order,
  127075. ** parameter bDescDoclist should be false. If they are sorted in ascending
  127076. ** order, it should be passed a non-zero value.
  127077. **
  127078. ** The right-hand input doclist is overwritten by this function.
  127079. */
  127080. static int fts3DoclistPhraseMerge(
  127081. int bDescDoclist, /* True if arguments are desc */
  127082. int nDist, /* Distance from left to right (1=adjacent) */
  127083. char *aLeft, int nLeft, /* Left doclist */
  127084. char **paRight, int *pnRight /* IN/OUT: Right/output doclist */
  127085. ){
  127086. sqlite3_int64 i1 = 0;
  127087. sqlite3_int64 i2 = 0;
  127088. sqlite3_int64 iPrev = 0;
  127089. char *aRight = *paRight;
  127090. char *pEnd1 = &aLeft[nLeft];
  127091. char *pEnd2 = &aRight[*pnRight];
  127092. char *p1 = aLeft;
  127093. char *p2 = aRight;
  127094. char *p;
  127095. int bFirstOut = 0;
  127096. char *aOut;
  127097. assert( nDist>0 );
  127098. if( bDescDoclist ){
  127099. aOut = sqlite3_malloc(*pnRight + FTS3_VARINT_MAX);
  127100. if( aOut==0 ) return SQLITE_NOMEM;
  127101. }else{
  127102. aOut = aRight;
  127103. }
  127104. p = aOut;
  127105. fts3GetDeltaVarint3(&p1, pEnd1, 0, &i1);
  127106. fts3GetDeltaVarint3(&p2, pEnd2, 0, &i2);
  127107. while( p1 && p2 ){
  127108. sqlite3_int64 iDiff = DOCID_CMP(i1, i2);
  127109. if( iDiff==0 ){
  127110. char *pSave = p;
  127111. sqlite3_int64 iPrevSave = iPrev;
  127112. int bFirstOutSave = bFirstOut;
  127113. fts3PutDeltaVarint3(&p, bDescDoclist, &iPrev, &bFirstOut, i1);
  127114. if( 0==fts3PoslistPhraseMerge(&p, nDist, 0, 1, &p1, &p2) ){
  127115. p = pSave;
  127116. iPrev = iPrevSave;
  127117. bFirstOut = bFirstOutSave;
  127118. }
  127119. fts3GetDeltaVarint3(&p1, pEnd1, bDescDoclist, &i1);
  127120. fts3GetDeltaVarint3(&p2, pEnd2, bDescDoclist, &i2);
  127121. }else if( iDiff<0 ){
  127122. fts3PoslistCopy(0, &p1);
  127123. fts3GetDeltaVarint3(&p1, pEnd1, bDescDoclist, &i1);
  127124. }else{
  127125. fts3PoslistCopy(0, &p2);
  127126. fts3GetDeltaVarint3(&p2, pEnd2, bDescDoclist, &i2);
  127127. }
  127128. }
  127129. *pnRight = (int)(p - aOut);
  127130. if( bDescDoclist ){
  127131. sqlite3_free(aRight);
  127132. *paRight = aOut;
  127133. }
  127134. return SQLITE_OK;
  127135. }
  127136. /*
  127137. ** Argument pList points to a position list nList bytes in size. This
  127138. ** function checks to see if the position list contains any entries for
  127139. ** a token in position 0 (of any column). If so, it writes argument iDelta
  127140. ** to the output buffer pOut, followed by a position list consisting only
  127141. ** of the entries from pList at position 0, and terminated by an 0x00 byte.
  127142. ** The value returned is the number of bytes written to pOut (if any).
  127143. */
  127144. SQLITE_PRIVATE int sqlite3Fts3FirstFilter(
  127145. sqlite3_int64 iDelta, /* Varint that may be written to pOut */
  127146. char *pList, /* Position list (no 0x00 term) */
  127147. int nList, /* Size of pList in bytes */
  127148. char *pOut /* Write output here */
  127149. ){
  127150. int nOut = 0;
  127151. int bWritten = 0; /* True once iDelta has been written */
  127152. char *p = pList;
  127153. char *pEnd = &pList[nList];
  127154. if( *p!=0x01 ){
  127155. if( *p==0x02 ){
  127156. nOut += sqlite3Fts3PutVarint(&pOut[nOut], iDelta);
  127157. pOut[nOut++] = 0x02;
  127158. bWritten = 1;
  127159. }
  127160. fts3ColumnlistCopy(0, &p);
  127161. }
  127162. while( p<pEnd && *p==0x01 ){
  127163. sqlite3_int64 iCol;
  127164. p++;
  127165. p += sqlite3Fts3GetVarint(p, &iCol);
  127166. if( *p==0x02 ){
  127167. if( bWritten==0 ){
  127168. nOut += sqlite3Fts3PutVarint(&pOut[nOut], iDelta);
  127169. bWritten = 1;
  127170. }
  127171. pOut[nOut++] = 0x01;
  127172. nOut += sqlite3Fts3PutVarint(&pOut[nOut], iCol);
  127173. pOut[nOut++] = 0x02;
  127174. }
  127175. fts3ColumnlistCopy(0, &p);
  127176. }
  127177. if( bWritten ){
  127178. pOut[nOut++] = 0x00;
  127179. }
  127180. return nOut;
  127181. }
  127182. /*
  127183. ** Merge all doclists in the TermSelect.aaOutput[] array into a single
  127184. ** doclist stored in TermSelect.aaOutput[0]. If successful, delete all
  127185. ** other doclists (except the aaOutput[0] one) and return SQLITE_OK.
  127186. **
  127187. ** If an OOM error occurs, return SQLITE_NOMEM. In this case it is
  127188. ** the responsibility of the caller to free any doclists left in the
  127189. ** TermSelect.aaOutput[] array.
  127190. */
  127191. static int fts3TermSelectFinishMerge(Fts3Table *p, TermSelect *pTS){
  127192. char *aOut = 0;
  127193. int nOut = 0;
  127194. int i;
  127195. /* Loop through the doclists in the aaOutput[] array. Merge them all
  127196. ** into a single doclist.
  127197. */
  127198. for(i=0; i<SizeofArray(pTS->aaOutput); i++){
  127199. if( pTS->aaOutput[i] ){
  127200. if( !aOut ){
  127201. aOut = pTS->aaOutput[i];
  127202. nOut = pTS->anOutput[i];
  127203. pTS->aaOutput[i] = 0;
  127204. }else{
  127205. int nNew;
  127206. char *aNew;
  127207. int rc = fts3DoclistOrMerge(p->bDescIdx,
  127208. pTS->aaOutput[i], pTS->anOutput[i], aOut, nOut, &aNew, &nNew
  127209. );
  127210. if( rc!=SQLITE_OK ){
  127211. sqlite3_free(aOut);
  127212. return rc;
  127213. }
  127214. sqlite3_free(pTS->aaOutput[i]);
  127215. sqlite3_free(aOut);
  127216. pTS->aaOutput[i] = 0;
  127217. aOut = aNew;
  127218. nOut = nNew;
  127219. }
  127220. }
  127221. }
  127222. pTS->aaOutput[0] = aOut;
  127223. pTS->anOutput[0] = nOut;
  127224. return SQLITE_OK;
  127225. }
  127226. /*
  127227. ** Merge the doclist aDoclist/nDoclist into the TermSelect object passed
  127228. ** as the first argument. The merge is an "OR" merge (see function
  127229. ** fts3DoclistOrMerge() for details).
  127230. **
  127231. ** This function is called with the doclist for each term that matches
  127232. ** a queried prefix. It merges all these doclists into one, the doclist
  127233. ** for the specified prefix. Since there can be a very large number of
  127234. ** doclists to merge, the merging is done pair-wise using the TermSelect
  127235. ** object.
  127236. **
  127237. ** This function returns SQLITE_OK if the merge is successful, or an
  127238. ** SQLite error code (SQLITE_NOMEM) if an error occurs.
  127239. */
  127240. static int fts3TermSelectMerge(
  127241. Fts3Table *p, /* FTS table handle */
  127242. TermSelect *pTS, /* TermSelect object to merge into */
  127243. char *aDoclist, /* Pointer to doclist */
  127244. int nDoclist /* Size of aDoclist in bytes */
  127245. ){
  127246. if( pTS->aaOutput[0]==0 ){
  127247. /* If this is the first term selected, copy the doclist to the output
  127248. ** buffer using memcpy().
  127249. **
  127250. ** Add FTS3_VARINT_MAX bytes of unused space to the end of the
  127251. ** allocation. This is so as to ensure that the buffer is big enough
  127252. ** to hold the current doclist AND'd with any other doclist. If the
  127253. ** doclists are stored in order=ASC order, this padding would not be
  127254. ** required (since the size of [doclistA AND doclistB] is always less
  127255. ** than or equal to the size of [doclistA] in that case). But this is
  127256. ** not true for order=DESC. For example, a doclist containing (1, -1)
  127257. ** may be smaller than (-1), as in the first example the -1 may be stored
  127258. ** as a single-byte delta, whereas in the second it must be stored as a
  127259. ** FTS3_VARINT_MAX byte varint.
  127260. **
  127261. ** Similar padding is added in the fts3DoclistOrMerge() function.
  127262. */
  127263. pTS->aaOutput[0] = sqlite3_malloc(nDoclist + FTS3_VARINT_MAX + 1);
  127264. pTS->anOutput[0] = nDoclist;
  127265. if( pTS->aaOutput[0] ){
  127266. memcpy(pTS->aaOutput[0], aDoclist, nDoclist);
  127267. }else{
  127268. return SQLITE_NOMEM;
  127269. }
  127270. }else{
  127271. char *aMerge = aDoclist;
  127272. int nMerge = nDoclist;
  127273. int iOut;
  127274. for(iOut=0; iOut<SizeofArray(pTS->aaOutput); iOut++){
  127275. if( pTS->aaOutput[iOut]==0 ){
  127276. assert( iOut>0 );
  127277. pTS->aaOutput[iOut] = aMerge;
  127278. pTS->anOutput[iOut] = nMerge;
  127279. break;
  127280. }else{
  127281. char *aNew;
  127282. int nNew;
  127283. int rc = fts3DoclistOrMerge(p->bDescIdx, aMerge, nMerge,
  127284. pTS->aaOutput[iOut], pTS->anOutput[iOut], &aNew, &nNew
  127285. );
  127286. if( rc!=SQLITE_OK ){
  127287. if( aMerge!=aDoclist ) sqlite3_free(aMerge);
  127288. return rc;
  127289. }
  127290. if( aMerge!=aDoclist ) sqlite3_free(aMerge);
  127291. sqlite3_free(pTS->aaOutput[iOut]);
  127292. pTS->aaOutput[iOut] = 0;
  127293. aMerge = aNew;
  127294. nMerge = nNew;
  127295. if( (iOut+1)==SizeofArray(pTS->aaOutput) ){
  127296. pTS->aaOutput[iOut] = aMerge;
  127297. pTS->anOutput[iOut] = nMerge;
  127298. }
  127299. }
  127300. }
  127301. }
  127302. return SQLITE_OK;
  127303. }
  127304. /*
  127305. ** Append SegReader object pNew to the end of the pCsr->apSegment[] array.
  127306. */
  127307. static int fts3SegReaderCursorAppend(
  127308. Fts3MultiSegReader *pCsr,
  127309. Fts3SegReader *pNew
  127310. ){
  127311. if( (pCsr->nSegment%16)==0 ){
  127312. Fts3SegReader **apNew;
  127313. int nByte = (pCsr->nSegment + 16)*sizeof(Fts3SegReader*);
  127314. apNew = (Fts3SegReader **)sqlite3_realloc(pCsr->apSegment, nByte);
  127315. if( !apNew ){
  127316. sqlite3Fts3SegReaderFree(pNew);
  127317. return SQLITE_NOMEM;
  127318. }
  127319. pCsr->apSegment = apNew;
  127320. }
  127321. pCsr->apSegment[pCsr->nSegment++] = pNew;
  127322. return SQLITE_OK;
  127323. }
  127324. /*
  127325. ** Add seg-reader objects to the Fts3MultiSegReader object passed as the
  127326. ** 8th argument.
  127327. **
  127328. ** This function returns SQLITE_OK if successful, or an SQLite error code
  127329. ** otherwise.
  127330. */
  127331. static int fts3SegReaderCursor(
  127332. Fts3Table *p, /* FTS3 table handle */
  127333. int iLangid, /* Language id */
  127334. int iIndex, /* Index to search (from 0 to p->nIndex-1) */
  127335. int iLevel, /* Level of segments to scan */
  127336. const char *zTerm, /* Term to query for */
  127337. int nTerm, /* Size of zTerm in bytes */
  127338. int isPrefix, /* True for a prefix search */
  127339. int isScan, /* True to scan from zTerm to EOF */
  127340. Fts3MultiSegReader *pCsr /* Cursor object to populate */
  127341. ){
  127342. int rc = SQLITE_OK; /* Error code */
  127343. sqlite3_stmt *pStmt = 0; /* Statement to iterate through segments */
  127344. int rc2; /* Result of sqlite3_reset() */
  127345. /* If iLevel is less than 0 and this is not a scan, include a seg-reader
  127346. ** for the pending-terms. If this is a scan, then this call must be being
  127347. ** made by an fts4aux module, not an FTS table. In this case calling
  127348. ** Fts3SegReaderPending might segfault, as the data structures used by
  127349. ** fts4aux are not completely populated. So it's easiest to filter these
  127350. ** calls out here. */
  127351. if( iLevel<0 && p->aIndex ){
  127352. Fts3SegReader *pSeg = 0;
  127353. rc = sqlite3Fts3SegReaderPending(p, iIndex, zTerm, nTerm, isPrefix||isScan, &pSeg);
  127354. if( rc==SQLITE_OK && pSeg ){
  127355. rc = fts3SegReaderCursorAppend(pCsr, pSeg);
  127356. }
  127357. }
  127358. if( iLevel!=FTS3_SEGCURSOR_PENDING ){
  127359. if( rc==SQLITE_OK ){
  127360. rc = sqlite3Fts3AllSegdirs(p, iLangid, iIndex, iLevel, &pStmt);
  127361. }
  127362. while( rc==SQLITE_OK && SQLITE_ROW==(rc = sqlite3_step(pStmt)) ){
  127363. Fts3SegReader *pSeg = 0;
  127364. /* Read the values returned by the SELECT into local variables. */
  127365. sqlite3_int64 iStartBlock = sqlite3_column_int64(pStmt, 1);
  127366. sqlite3_int64 iLeavesEndBlock = sqlite3_column_int64(pStmt, 2);
  127367. sqlite3_int64 iEndBlock = sqlite3_column_int64(pStmt, 3);
  127368. int nRoot = sqlite3_column_bytes(pStmt, 4);
  127369. char const *zRoot = sqlite3_column_blob(pStmt, 4);
  127370. /* If zTerm is not NULL, and this segment is not stored entirely on its
  127371. ** root node, the range of leaves scanned can be reduced. Do this. */
  127372. if( iStartBlock && zTerm ){
  127373. sqlite3_int64 *pi = (isPrefix ? &iLeavesEndBlock : 0);
  127374. rc = fts3SelectLeaf(p, zTerm, nTerm, zRoot, nRoot, &iStartBlock, pi);
  127375. if( rc!=SQLITE_OK ) goto finished;
  127376. if( isPrefix==0 && isScan==0 ) iLeavesEndBlock = iStartBlock;
  127377. }
  127378. rc = sqlite3Fts3SegReaderNew(pCsr->nSegment+1,
  127379. (isPrefix==0 && isScan==0),
  127380. iStartBlock, iLeavesEndBlock,
  127381. iEndBlock, zRoot, nRoot, &pSeg
  127382. );
  127383. if( rc!=SQLITE_OK ) goto finished;
  127384. rc = fts3SegReaderCursorAppend(pCsr, pSeg);
  127385. }
  127386. }
  127387. finished:
  127388. rc2 = sqlite3_reset(pStmt);
  127389. if( rc==SQLITE_DONE ) rc = rc2;
  127390. return rc;
  127391. }
  127392. /*
  127393. ** Set up a cursor object for iterating through a full-text index or a
  127394. ** single level therein.
  127395. */
  127396. SQLITE_PRIVATE int sqlite3Fts3SegReaderCursor(
  127397. Fts3Table *p, /* FTS3 table handle */
  127398. int iLangid, /* Language-id to search */
  127399. int iIndex, /* Index to search (from 0 to p->nIndex-1) */
  127400. int iLevel, /* Level of segments to scan */
  127401. const char *zTerm, /* Term to query for */
  127402. int nTerm, /* Size of zTerm in bytes */
  127403. int isPrefix, /* True for a prefix search */
  127404. int isScan, /* True to scan from zTerm to EOF */
  127405. Fts3MultiSegReader *pCsr /* Cursor object to populate */
  127406. ){
  127407. assert( iIndex>=0 && iIndex<p->nIndex );
  127408. assert( iLevel==FTS3_SEGCURSOR_ALL
  127409. || iLevel==FTS3_SEGCURSOR_PENDING
  127410. || iLevel>=0
  127411. );
  127412. assert( iLevel<FTS3_SEGDIR_MAXLEVEL );
  127413. assert( FTS3_SEGCURSOR_ALL<0 && FTS3_SEGCURSOR_PENDING<0 );
  127414. assert( isPrefix==0 || isScan==0 );
  127415. memset(pCsr, 0, sizeof(Fts3MultiSegReader));
  127416. return fts3SegReaderCursor(
  127417. p, iLangid, iIndex, iLevel, zTerm, nTerm, isPrefix, isScan, pCsr
  127418. );
  127419. }
  127420. /*
  127421. ** In addition to its current configuration, have the Fts3MultiSegReader
  127422. ** passed as the 4th argument also scan the doclist for term zTerm/nTerm.
  127423. **
  127424. ** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
  127425. */
  127426. static int fts3SegReaderCursorAddZero(
  127427. Fts3Table *p, /* FTS virtual table handle */
  127428. int iLangid,
  127429. const char *zTerm, /* Term to scan doclist of */
  127430. int nTerm, /* Number of bytes in zTerm */
  127431. Fts3MultiSegReader *pCsr /* Fts3MultiSegReader to modify */
  127432. ){
  127433. return fts3SegReaderCursor(p,
  127434. iLangid, 0, FTS3_SEGCURSOR_ALL, zTerm, nTerm, 0, 0,pCsr
  127435. );
  127436. }
  127437. /*
  127438. ** Open an Fts3MultiSegReader to scan the doclist for term zTerm/nTerm. Or,
  127439. ** if isPrefix is true, to scan the doclist for all terms for which
  127440. ** zTerm/nTerm is a prefix. If successful, return SQLITE_OK and write
  127441. ** a pointer to the new Fts3MultiSegReader to *ppSegcsr. Otherwise, return
  127442. ** an SQLite error code.
  127443. **
  127444. ** It is the responsibility of the caller to free this object by eventually
  127445. ** passing it to fts3SegReaderCursorFree()
  127446. **
  127447. ** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
  127448. ** Output parameter *ppSegcsr is set to 0 if an error occurs.
  127449. */
  127450. static int fts3TermSegReaderCursor(
  127451. Fts3Cursor *pCsr, /* Virtual table cursor handle */
  127452. const char *zTerm, /* Term to query for */
  127453. int nTerm, /* Size of zTerm in bytes */
  127454. int isPrefix, /* True for a prefix search */
  127455. Fts3MultiSegReader **ppSegcsr /* OUT: Allocated seg-reader cursor */
  127456. ){
  127457. Fts3MultiSegReader *pSegcsr; /* Object to allocate and return */
  127458. int rc = SQLITE_NOMEM; /* Return code */
  127459. pSegcsr = sqlite3_malloc(sizeof(Fts3MultiSegReader));
  127460. if( pSegcsr ){
  127461. int i;
  127462. int bFound = 0; /* True once an index has been found */
  127463. Fts3Table *p = (Fts3Table *)pCsr->base.pVtab;
  127464. if( isPrefix ){
  127465. for(i=1; bFound==0 && i<p->nIndex; i++){
  127466. if( p->aIndex[i].nPrefix==nTerm ){
  127467. bFound = 1;
  127468. rc = sqlite3Fts3SegReaderCursor(p, pCsr->iLangid,
  127469. i, FTS3_SEGCURSOR_ALL, zTerm, nTerm, 0, 0, pSegcsr
  127470. );
  127471. pSegcsr->bLookup = 1;
  127472. }
  127473. }
  127474. for(i=1; bFound==0 && i<p->nIndex; i++){
  127475. if( p->aIndex[i].nPrefix==nTerm+1 ){
  127476. bFound = 1;
  127477. rc = sqlite3Fts3SegReaderCursor(p, pCsr->iLangid,
  127478. i, FTS3_SEGCURSOR_ALL, zTerm, nTerm, 1, 0, pSegcsr
  127479. );
  127480. if( rc==SQLITE_OK ){
  127481. rc = fts3SegReaderCursorAddZero(
  127482. p, pCsr->iLangid, zTerm, nTerm, pSegcsr
  127483. );
  127484. }
  127485. }
  127486. }
  127487. }
  127488. if( bFound==0 ){
  127489. rc = sqlite3Fts3SegReaderCursor(p, pCsr->iLangid,
  127490. 0, FTS3_SEGCURSOR_ALL, zTerm, nTerm, isPrefix, 0, pSegcsr
  127491. );
  127492. pSegcsr->bLookup = !isPrefix;
  127493. }
  127494. }
  127495. *ppSegcsr = pSegcsr;
  127496. return rc;
  127497. }
  127498. /*
  127499. ** Free an Fts3MultiSegReader allocated by fts3TermSegReaderCursor().
  127500. */
  127501. static void fts3SegReaderCursorFree(Fts3MultiSegReader *pSegcsr){
  127502. sqlite3Fts3SegReaderFinish(pSegcsr);
  127503. sqlite3_free(pSegcsr);
  127504. }
  127505. /*
  127506. ** This function retrieves the doclist for the specified term (or term
  127507. ** prefix) from the database.
  127508. */
  127509. static int fts3TermSelect(
  127510. Fts3Table *p, /* Virtual table handle */
  127511. Fts3PhraseToken *pTok, /* Token to query for */
  127512. int iColumn, /* Column to query (or -ve for all columns) */
  127513. int *pnOut, /* OUT: Size of buffer at *ppOut */
  127514. char **ppOut /* OUT: Malloced result buffer */
  127515. ){
  127516. int rc; /* Return code */
  127517. Fts3MultiSegReader *pSegcsr; /* Seg-reader cursor for this term */
  127518. TermSelect tsc; /* Object for pair-wise doclist merging */
  127519. Fts3SegFilter filter; /* Segment term filter configuration */
  127520. pSegcsr = pTok->pSegcsr;
  127521. memset(&tsc, 0, sizeof(TermSelect));
  127522. filter.flags = FTS3_SEGMENT_IGNORE_EMPTY | FTS3_SEGMENT_REQUIRE_POS
  127523. | (pTok->isPrefix ? FTS3_SEGMENT_PREFIX : 0)
  127524. | (pTok->bFirst ? FTS3_SEGMENT_FIRST : 0)
  127525. | (iColumn<p->nColumn ? FTS3_SEGMENT_COLUMN_FILTER : 0);
  127526. filter.iCol = iColumn;
  127527. filter.zTerm = pTok->z;
  127528. filter.nTerm = pTok->n;
  127529. rc = sqlite3Fts3SegReaderStart(p, pSegcsr, &filter);
  127530. while( SQLITE_OK==rc
  127531. && SQLITE_ROW==(rc = sqlite3Fts3SegReaderStep(p, pSegcsr))
  127532. ){
  127533. rc = fts3TermSelectMerge(p, &tsc, pSegcsr->aDoclist, pSegcsr->nDoclist);
  127534. }
  127535. if( rc==SQLITE_OK ){
  127536. rc = fts3TermSelectFinishMerge(p, &tsc);
  127537. }
  127538. if( rc==SQLITE_OK ){
  127539. *ppOut = tsc.aaOutput[0];
  127540. *pnOut = tsc.anOutput[0];
  127541. }else{
  127542. int i;
  127543. for(i=0; i<SizeofArray(tsc.aaOutput); i++){
  127544. sqlite3_free(tsc.aaOutput[i]);
  127545. }
  127546. }
  127547. fts3SegReaderCursorFree(pSegcsr);
  127548. pTok->pSegcsr = 0;
  127549. return rc;
  127550. }
  127551. /*
  127552. ** This function counts the total number of docids in the doclist stored
  127553. ** in buffer aList[], size nList bytes.
  127554. **
  127555. ** If the isPoslist argument is true, then it is assumed that the doclist
  127556. ** contains a position-list following each docid. Otherwise, it is assumed
  127557. ** that the doclist is simply a list of docids stored as delta encoded
  127558. ** varints.
  127559. */
  127560. static int fts3DoclistCountDocids(char *aList, int nList){
  127561. int nDoc = 0; /* Return value */
  127562. if( aList ){
  127563. char *aEnd = &aList[nList]; /* Pointer to one byte after EOF */
  127564. char *p = aList; /* Cursor */
  127565. while( p<aEnd ){
  127566. nDoc++;
  127567. while( (*p++)&0x80 ); /* Skip docid varint */
  127568. fts3PoslistCopy(0, &p); /* Skip over position list */
  127569. }
  127570. }
  127571. return nDoc;
  127572. }
  127573. /*
  127574. ** Advance the cursor to the next row in the %_content table that
  127575. ** matches the search criteria. For a MATCH search, this will be
  127576. ** the next row that matches. For a full-table scan, this will be
  127577. ** simply the next row in the %_content table. For a docid lookup,
  127578. ** this routine simply sets the EOF flag.
  127579. **
  127580. ** Return SQLITE_OK if nothing goes wrong. SQLITE_OK is returned
  127581. ** even if we reach end-of-file. The fts3EofMethod() will be called
  127582. ** subsequently to determine whether or not an EOF was hit.
  127583. */
  127584. static int fts3NextMethod(sqlite3_vtab_cursor *pCursor){
  127585. int rc;
  127586. Fts3Cursor *pCsr = (Fts3Cursor *)pCursor;
  127587. if( pCsr->eSearch==FTS3_DOCID_SEARCH || pCsr->eSearch==FTS3_FULLSCAN_SEARCH ){
  127588. if( SQLITE_ROW!=sqlite3_step(pCsr->pStmt) ){
  127589. pCsr->isEof = 1;
  127590. rc = sqlite3_reset(pCsr->pStmt);
  127591. }else{
  127592. pCsr->iPrevId = sqlite3_column_int64(pCsr->pStmt, 0);
  127593. rc = SQLITE_OK;
  127594. }
  127595. }else{
  127596. rc = fts3EvalNext((Fts3Cursor *)pCursor);
  127597. }
  127598. assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 );
  127599. return rc;
  127600. }
  127601. /*
  127602. ** The following are copied from sqliteInt.h.
  127603. **
  127604. ** Constants for the largest and smallest possible 64-bit signed integers.
  127605. ** These macros are designed to work correctly on both 32-bit and 64-bit
  127606. ** compilers.
  127607. */
  127608. #ifndef SQLITE_AMALGAMATION
  127609. # define LARGEST_INT64 (0xffffffff|(((sqlite3_int64)0x7fffffff)<<32))
  127610. # define SMALLEST_INT64 (((sqlite3_int64)-1) - LARGEST_INT64)
  127611. #endif
  127612. /*
  127613. ** If the numeric type of argument pVal is "integer", then return it
  127614. ** converted to a 64-bit signed integer. Otherwise, return a copy of
  127615. ** the second parameter, iDefault.
  127616. */
  127617. static sqlite3_int64 fts3DocidRange(sqlite3_value *pVal, i64 iDefault){
  127618. if( pVal ){
  127619. int eType = sqlite3_value_numeric_type(pVal);
  127620. if( eType==SQLITE_INTEGER ){
  127621. return sqlite3_value_int64(pVal);
  127622. }
  127623. }
  127624. return iDefault;
  127625. }
  127626. /*
  127627. ** This is the xFilter interface for the virtual table. See
  127628. ** the virtual table xFilter method documentation for additional
  127629. ** information.
  127630. **
  127631. ** If idxNum==FTS3_FULLSCAN_SEARCH then do a full table scan against
  127632. ** the %_content table.
  127633. **
  127634. ** If idxNum==FTS3_DOCID_SEARCH then do a docid lookup for a single entry
  127635. ** in the %_content table.
  127636. **
  127637. ** If idxNum>=FTS3_FULLTEXT_SEARCH then use the full text index. The
  127638. ** column on the left-hand side of the MATCH operator is column
  127639. ** number idxNum-FTS3_FULLTEXT_SEARCH, 0 indexed. argv[0] is the right-hand
  127640. ** side of the MATCH operator.
  127641. */
  127642. static int fts3FilterMethod(
  127643. sqlite3_vtab_cursor *pCursor, /* The cursor used for this query */
  127644. int idxNum, /* Strategy index */
  127645. const char *idxStr, /* Unused */
  127646. int nVal, /* Number of elements in apVal */
  127647. sqlite3_value **apVal /* Arguments for the indexing scheme */
  127648. ){
  127649. int rc = SQLITE_OK;
  127650. char *zSql; /* SQL statement used to access %_content */
  127651. int eSearch;
  127652. Fts3Table *p = (Fts3Table *)pCursor->pVtab;
  127653. Fts3Cursor *pCsr = (Fts3Cursor *)pCursor;
  127654. sqlite3_value *pCons = 0; /* The MATCH or rowid constraint, if any */
  127655. sqlite3_value *pLangid = 0; /* The "langid = ?" constraint, if any */
  127656. sqlite3_value *pDocidGe = 0; /* The "docid >= ?" constraint, if any */
  127657. sqlite3_value *pDocidLe = 0; /* The "docid <= ?" constraint, if any */
  127658. int iIdx;
  127659. UNUSED_PARAMETER(idxStr);
  127660. UNUSED_PARAMETER(nVal);
  127661. eSearch = (idxNum & 0x0000FFFF);
  127662. assert( eSearch>=0 && eSearch<=(FTS3_FULLTEXT_SEARCH+p->nColumn) );
  127663. assert( p->pSegments==0 );
  127664. /* Collect arguments into local variables */
  127665. iIdx = 0;
  127666. if( eSearch!=FTS3_FULLSCAN_SEARCH ) pCons = apVal[iIdx++];
  127667. if( idxNum & FTS3_HAVE_LANGID ) pLangid = apVal[iIdx++];
  127668. if( idxNum & FTS3_HAVE_DOCID_GE ) pDocidGe = apVal[iIdx++];
  127669. if( idxNum & FTS3_HAVE_DOCID_LE ) pDocidLe = apVal[iIdx++];
  127670. assert( iIdx==nVal );
  127671. /* In case the cursor has been used before, clear it now. */
  127672. sqlite3_finalize(pCsr->pStmt);
  127673. sqlite3_free(pCsr->aDoclist);
  127674. sqlite3_free(pCsr->aMatchinfo);
  127675. sqlite3Fts3ExprFree(pCsr->pExpr);
  127676. memset(&pCursor[1], 0, sizeof(Fts3Cursor)-sizeof(sqlite3_vtab_cursor));
  127677. /* Set the lower and upper bounds on docids to return */
  127678. pCsr->iMinDocid = fts3DocidRange(pDocidGe, SMALLEST_INT64);
  127679. pCsr->iMaxDocid = fts3DocidRange(pDocidLe, LARGEST_INT64);
  127680. if( idxStr ){
  127681. pCsr->bDesc = (idxStr[0]=='D');
  127682. }else{
  127683. pCsr->bDesc = p->bDescIdx;
  127684. }
  127685. pCsr->eSearch = (i16)eSearch;
  127686. if( eSearch!=FTS3_DOCID_SEARCH && eSearch!=FTS3_FULLSCAN_SEARCH ){
  127687. int iCol = eSearch-FTS3_FULLTEXT_SEARCH;
  127688. const char *zQuery = (const char *)sqlite3_value_text(pCons);
  127689. if( zQuery==0 && sqlite3_value_type(pCons)!=SQLITE_NULL ){
  127690. return SQLITE_NOMEM;
  127691. }
  127692. pCsr->iLangid = 0;
  127693. if( pLangid ) pCsr->iLangid = sqlite3_value_int(pLangid);
  127694. assert( p->base.zErrMsg==0 );
  127695. rc = sqlite3Fts3ExprParse(p->pTokenizer, pCsr->iLangid,
  127696. p->azColumn, p->bFts4, p->nColumn, iCol, zQuery, -1, &pCsr->pExpr,
  127697. &p->base.zErrMsg
  127698. );
  127699. if( rc!=SQLITE_OK ){
  127700. return rc;
  127701. }
  127702. rc = fts3EvalStart(pCsr);
  127703. sqlite3Fts3SegmentsClose(p);
  127704. if( rc!=SQLITE_OK ) return rc;
  127705. pCsr->pNextId = pCsr->aDoclist;
  127706. pCsr->iPrevId = 0;
  127707. }
  127708. /* Compile a SELECT statement for this cursor. For a full-table-scan, the
  127709. ** statement loops through all rows of the %_content table. For a
  127710. ** full-text query or docid lookup, the statement retrieves a single
  127711. ** row by docid.
  127712. */
  127713. if( eSearch==FTS3_FULLSCAN_SEARCH ){
  127714. if( pDocidGe || pDocidLe ){
  127715. zSql = sqlite3_mprintf(
  127716. "SELECT %s WHERE rowid BETWEEN %lld AND %lld ORDER BY rowid %s",
  127717. p->zReadExprlist, pCsr->iMinDocid, pCsr->iMaxDocid,
  127718. (pCsr->bDesc ? "DESC" : "ASC")
  127719. );
  127720. }else{
  127721. zSql = sqlite3_mprintf("SELECT %s ORDER BY rowid %s",
  127722. p->zReadExprlist, (pCsr->bDesc ? "DESC" : "ASC")
  127723. );
  127724. }
  127725. if( zSql ){
  127726. rc = sqlite3_prepare_v2(p->db, zSql, -1, &pCsr->pStmt, 0);
  127727. sqlite3_free(zSql);
  127728. }else{
  127729. rc = SQLITE_NOMEM;
  127730. }
  127731. }else if( eSearch==FTS3_DOCID_SEARCH ){
  127732. rc = fts3CursorSeekStmt(pCsr, &pCsr->pStmt);
  127733. if( rc==SQLITE_OK ){
  127734. rc = sqlite3_bind_value(pCsr->pStmt, 1, pCons);
  127735. }
  127736. }
  127737. if( rc!=SQLITE_OK ) return rc;
  127738. return fts3NextMethod(pCursor);
  127739. }
  127740. /*
  127741. ** This is the xEof method of the virtual table. SQLite calls this
  127742. ** routine to find out if it has reached the end of a result set.
  127743. */
  127744. static int fts3EofMethod(sqlite3_vtab_cursor *pCursor){
  127745. return ((Fts3Cursor *)pCursor)->isEof;
  127746. }
  127747. /*
  127748. ** This is the xRowid method. The SQLite core calls this routine to
  127749. ** retrieve the rowid for the current row of the result set. fts3
  127750. ** exposes %_content.docid as the rowid for the virtual table. The
  127751. ** rowid should be written to *pRowid.
  127752. */
  127753. static int fts3RowidMethod(sqlite3_vtab_cursor *pCursor, sqlite_int64 *pRowid){
  127754. Fts3Cursor *pCsr = (Fts3Cursor *) pCursor;
  127755. *pRowid = pCsr->iPrevId;
  127756. return SQLITE_OK;
  127757. }
  127758. /*
  127759. ** This is the xColumn method, called by SQLite to request a value from
  127760. ** the row that the supplied cursor currently points to.
  127761. **
  127762. ** If:
  127763. **
  127764. ** (iCol < p->nColumn) -> The value of the iCol'th user column.
  127765. ** (iCol == p->nColumn) -> Magic column with the same name as the table.
  127766. ** (iCol == p->nColumn+1) -> Docid column
  127767. ** (iCol == p->nColumn+2) -> Langid column
  127768. */
  127769. static int fts3ColumnMethod(
  127770. sqlite3_vtab_cursor *pCursor, /* Cursor to retrieve value from */
  127771. sqlite3_context *pCtx, /* Context for sqlite3_result_xxx() calls */
  127772. int iCol /* Index of column to read value from */
  127773. ){
  127774. int rc = SQLITE_OK; /* Return Code */
  127775. Fts3Cursor *pCsr = (Fts3Cursor *) pCursor;
  127776. Fts3Table *p = (Fts3Table *)pCursor->pVtab;
  127777. /* The column value supplied by SQLite must be in range. */
  127778. assert( iCol>=0 && iCol<=p->nColumn+2 );
  127779. if( iCol==p->nColumn+1 ){
  127780. /* This call is a request for the "docid" column. Since "docid" is an
  127781. ** alias for "rowid", use the xRowid() method to obtain the value.
  127782. */
  127783. sqlite3_result_int64(pCtx, pCsr->iPrevId);
  127784. }else if( iCol==p->nColumn ){
  127785. /* The extra column whose name is the same as the table.
  127786. ** Return a blob which is a pointer to the cursor. */
  127787. sqlite3_result_blob(pCtx, &pCsr, sizeof(pCsr), SQLITE_TRANSIENT);
  127788. }else if( iCol==p->nColumn+2 && pCsr->pExpr ){
  127789. sqlite3_result_int64(pCtx, pCsr->iLangid);
  127790. }else{
  127791. /* The requested column is either a user column (one that contains
  127792. ** indexed data), or the language-id column. */
  127793. rc = fts3CursorSeek(0, pCsr);
  127794. if( rc==SQLITE_OK ){
  127795. if( iCol==p->nColumn+2 ){
  127796. int iLangid = 0;
  127797. if( p->zLanguageid ){
  127798. iLangid = sqlite3_column_int(pCsr->pStmt, p->nColumn+1);
  127799. }
  127800. sqlite3_result_int(pCtx, iLangid);
  127801. }else if( sqlite3_data_count(pCsr->pStmt)>(iCol+1) ){
  127802. sqlite3_result_value(pCtx, sqlite3_column_value(pCsr->pStmt, iCol+1));
  127803. }
  127804. }
  127805. }
  127806. assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 );
  127807. return rc;
  127808. }
  127809. /*
  127810. ** This function is the implementation of the xUpdate callback used by
  127811. ** FTS3 virtual tables. It is invoked by SQLite each time a row is to be
  127812. ** inserted, updated or deleted.
  127813. */
  127814. static int fts3UpdateMethod(
  127815. sqlite3_vtab *pVtab, /* Virtual table handle */
  127816. int nArg, /* Size of argument array */
  127817. sqlite3_value **apVal, /* Array of arguments */
  127818. sqlite_int64 *pRowid /* OUT: The affected (or effected) rowid */
  127819. ){
  127820. return sqlite3Fts3UpdateMethod(pVtab, nArg, apVal, pRowid);
  127821. }
  127822. /*
  127823. ** Implementation of xSync() method. Flush the contents of the pending-terms
  127824. ** hash-table to the database.
  127825. */
  127826. static int fts3SyncMethod(sqlite3_vtab *pVtab){
  127827. /* Following an incremental-merge operation, assuming that the input
  127828. ** segments are not completely consumed (the usual case), they are updated
  127829. ** in place to remove the entries that have already been merged. This
  127830. ** involves updating the leaf block that contains the smallest unmerged
  127831. ** entry and each block (if any) between the leaf and the root node. So
  127832. ** if the height of the input segment b-trees is N, and input segments
  127833. ** are merged eight at a time, updating the input segments at the end
  127834. ** of an incremental-merge requires writing (8*(1+N)) blocks. N is usually
  127835. ** small - often between 0 and 2. So the overhead of the incremental
  127836. ** merge is somewhere between 8 and 24 blocks. To avoid this overhead
  127837. ** dwarfing the actual productive work accomplished, the incremental merge
  127838. ** is only attempted if it will write at least 64 leaf blocks. Hence
  127839. ** nMinMerge.
  127840. **
  127841. ** Of course, updating the input segments also involves deleting a bunch
  127842. ** of blocks from the segments table. But this is not considered overhead
  127843. ** as it would also be required by a crisis-merge that used the same input
  127844. ** segments.
  127845. */
  127846. const u32 nMinMerge = 64; /* Minimum amount of incr-merge work to do */
  127847. Fts3Table *p = (Fts3Table*)pVtab;
  127848. int rc = sqlite3Fts3PendingTermsFlush(p);
  127849. if( rc==SQLITE_OK
  127850. && p->nLeafAdd>(nMinMerge/16)
  127851. && p->nAutoincrmerge && p->nAutoincrmerge!=0xff
  127852. ){
  127853. int mxLevel = 0; /* Maximum relative level value in db */
  127854. int A; /* Incr-merge parameter A */
  127855. rc = sqlite3Fts3MaxLevel(p, &mxLevel);
  127856. assert( rc==SQLITE_OK || mxLevel==0 );
  127857. A = p->nLeafAdd * mxLevel;
  127858. A += (A/2);
  127859. if( A>(int)nMinMerge ) rc = sqlite3Fts3Incrmerge(p, A, p->nAutoincrmerge);
  127860. }
  127861. sqlite3Fts3SegmentsClose(p);
  127862. return rc;
  127863. }
  127864. /*
  127865. ** If it is currently unknown whether or not the FTS table has an %_stat
  127866. ** table (if p->bHasStat==2), attempt to determine this (set p->bHasStat
  127867. ** to 0 or 1). Return SQLITE_OK if successful, or an SQLite error code
  127868. ** if an error occurs.
  127869. */
  127870. static int fts3SetHasStat(Fts3Table *p){
  127871. int rc = SQLITE_OK;
  127872. if( p->bHasStat==2 ){
  127873. const char *zFmt ="SELECT 1 FROM %Q.sqlite_master WHERE tbl_name='%q_stat'";
  127874. char *zSql = sqlite3_mprintf(zFmt, p->zDb, p->zName);
  127875. if( zSql ){
  127876. sqlite3_stmt *pStmt = 0;
  127877. rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
  127878. if( rc==SQLITE_OK ){
  127879. int bHasStat = (sqlite3_step(pStmt)==SQLITE_ROW);
  127880. rc = sqlite3_finalize(pStmt);
  127881. if( rc==SQLITE_OK ) p->bHasStat = bHasStat;
  127882. }
  127883. sqlite3_free(zSql);
  127884. }else{
  127885. rc = SQLITE_NOMEM;
  127886. }
  127887. }
  127888. return rc;
  127889. }
  127890. /*
  127891. ** Implementation of xBegin() method.
  127892. */
  127893. static int fts3BeginMethod(sqlite3_vtab *pVtab){
  127894. Fts3Table *p = (Fts3Table*)pVtab;
  127895. UNUSED_PARAMETER(pVtab);
  127896. assert( p->pSegments==0 );
  127897. assert( p->nPendingData==0 );
  127898. assert( p->inTransaction!=1 );
  127899. TESTONLY( p->inTransaction = 1 );
  127900. TESTONLY( p->mxSavepoint = -1; );
  127901. p->nLeafAdd = 0;
  127902. return fts3SetHasStat(p);
  127903. }
  127904. /*
  127905. ** Implementation of xCommit() method. This is a no-op. The contents of
  127906. ** the pending-terms hash-table have already been flushed into the database
  127907. ** by fts3SyncMethod().
  127908. */
  127909. static int fts3CommitMethod(sqlite3_vtab *pVtab){
  127910. TESTONLY( Fts3Table *p = (Fts3Table*)pVtab );
  127911. UNUSED_PARAMETER(pVtab);
  127912. assert( p->nPendingData==0 );
  127913. assert( p->inTransaction!=0 );
  127914. assert( p->pSegments==0 );
  127915. TESTONLY( p->inTransaction = 0 );
  127916. TESTONLY( p->mxSavepoint = -1; );
  127917. return SQLITE_OK;
  127918. }
  127919. /*
  127920. ** Implementation of xRollback(). Discard the contents of the pending-terms
  127921. ** hash-table. Any changes made to the database are reverted by SQLite.
  127922. */
  127923. static int fts3RollbackMethod(sqlite3_vtab *pVtab){
  127924. Fts3Table *p = (Fts3Table*)pVtab;
  127925. sqlite3Fts3PendingTermsClear(p);
  127926. assert( p->inTransaction!=0 );
  127927. TESTONLY( p->inTransaction = 0 );
  127928. TESTONLY( p->mxSavepoint = -1; );
  127929. return SQLITE_OK;
  127930. }
  127931. /*
  127932. ** When called, *ppPoslist must point to the byte immediately following the
  127933. ** end of a position-list. i.e. ( (*ppPoslist)[-1]==POS_END ). This function
  127934. ** moves *ppPoslist so that it instead points to the first byte of the
  127935. ** same position list.
  127936. */
  127937. static void fts3ReversePoslist(char *pStart, char **ppPoslist){
  127938. char *p = &(*ppPoslist)[-2];
  127939. char c = 0;
  127940. /* Skip backwards passed any trailing 0x00 bytes added by NearTrim() */
  127941. while( p>pStart && (c=*p--)==0 );
  127942. /* Search backwards for a varint with value zero (the end of the previous
  127943. ** poslist). This is an 0x00 byte preceded by some byte that does not
  127944. ** have the 0x80 bit set. */
  127945. while( p>pStart && (*p & 0x80) | c ){
  127946. c = *p--;
  127947. }
  127948. assert( p==pStart || c==0 );
  127949. /* At this point p points to that preceding byte without the 0x80 bit
  127950. ** set. So to find the start of the poslist, skip forward 2 bytes then
  127951. ** over a varint.
  127952. **
  127953. ** Normally. The other case is that p==pStart and the poslist to return
  127954. ** is the first in the doclist. In this case do not skip forward 2 bytes.
  127955. ** The second part of the if condition (c==0 && *ppPoslist>&p[2])
  127956. ** is required for cases where the first byte of a doclist and the
  127957. ** doclist is empty. For example, if the first docid is 10, a doclist
  127958. ** that begins with:
  127959. **
  127960. ** 0x0A 0x00 <next docid delta varint>
  127961. */
  127962. if( p>pStart || (c==0 && *ppPoslist>&p[2]) ){ p = &p[2]; }
  127963. while( *p++&0x80 );
  127964. *ppPoslist = p;
  127965. }
  127966. /*
  127967. ** Helper function used by the implementation of the overloaded snippet(),
  127968. ** offsets() and optimize() SQL functions.
  127969. **
  127970. ** If the value passed as the third argument is a blob of size
  127971. ** sizeof(Fts3Cursor*), then the blob contents are copied to the
  127972. ** output variable *ppCsr and SQLITE_OK is returned. Otherwise, an error
  127973. ** message is written to context pContext and SQLITE_ERROR returned. The
  127974. ** string passed via zFunc is used as part of the error message.
  127975. */
  127976. static int fts3FunctionArg(
  127977. sqlite3_context *pContext, /* SQL function call context */
  127978. const char *zFunc, /* Function name */
  127979. sqlite3_value *pVal, /* argv[0] passed to function */
  127980. Fts3Cursor **ppCsr /* OUT: Store cursor handle here */
  127981. ){
  127982. Fts3Cursor *pRet;
  127983. if( sqlite3_value_type(pVal)!=SQLITE_BLOB
  127984. || sqlite3_value_bytes(pVal)!=sizeof(Fts3Cursor *)
  127985. ){
  127986. char *zErr = sqlite3_mprintf("illegal first argument to %s", zFunc);
  127987. sqlite3_result_error(pContext, zErr, -1);
  127988. sqlite3_free(zErr);
  127989. return SQLITE_ERROR;
  127990. }
  127991. memcpy(&pRet, sqlite3_value_blob(pVal), sizeof(Fts3Cursor *));
  127992. *ppCsr = pRet;
  127993. return SQLITE_OK;
  127994. }
  127995. /*
  127996. ** Implementation of the snippet() function for FTS3
  127997. */
  127998. static void fts3SnippetFunc(
  127999. sqlite3_context *pContext, /* SQLite function call context */
  128000. int nVal, /* Size of apVal[] array */
  128001. sqlite3_value **apVal /* Array of arguments */
  128002. ){
  128003. Fts3Cursor *pCsr; /* Cursor handle passed through apVal[0] */
  128004. const char *zStart = "<b>";
  128005. const char *zEnd = "</b>";
  128006. const char *zEllipsis = "<b>...</b>";
  128007. int iCol = -1;
  128008. int nToken = 15; /* Default number of tokens in snippet */
  128009. /* There must be at least one argument passed to this function (otherwise
  128010. ** the non-overloaded version would have been called instead of this one).
  128011. */
  128012. assert( nVal>=1 );
  128013. if( nVal>6 ){
  128014. sqlite3_result_error(pContext,
  128015. "wrong number of arguments to function snippet()", -1);
  128016. return;
  128017. }
  128018. if( fts3FunctionArg(pContext, "snippet", apVal[0], &pCsr) ) return;
  128019. switch( nVal ){
  128020. case 6: nToken = sqlite3_value_int(apVal[5]);
  128021. case 5: iCol = sqlite3_value_int(apVal[4]);
  128022. case 4: zEllipsis = (const char*)sqlite3_value_text(apVal[3]);
  128023. case 3: zEnd = (const char*)sqlite3_value_text(apVal[2]);
  128024. case 2: zStart = (const char*)sqlite3_value_text(apVal[1]);
  128025. }
  128026. if( !zEllipsis || !zEnd || !zStart ){
  128027. sqlite3_result_error_nomem(pContext);
  128028. }else if( nToken==0 ){
  128029. sqlite3_result_text(pContext, "", -1, SQLITE_STATIC);
  128030. }else if( SQLITE_OK==fts3CursorSeek(pContext, pCsr) ){
  128031. sqlite3Fts3Snippet(pContext, pCsr, zStart, zEnd, zEllipsis, iCol, nToken);
  128032. }
  128033. }
  128034. /*
  128035. ** Implementation of the offsets() function for FTS3
  128036. */
  128037. static void fts3OffsetsFunc(
  128038. sqlite3_context *pContext, /* SQLite function call context */
  128039. int nVal, /* Size of argument array */
  128040. sqlite3_value **apVal /* Array of arguments */
  128041. ){
  128042. Fts3Cursor *pCsr; /* Cursor handle passed through apVal[0] */
  128043. UNUSED_PARAMETER(nVal);
  128044. assert( nVal==1 );
  128045. if( fts3FunctionArg(pContext, "offsets", apVal[0], &pCsr) ) return;
  128046. assert( pCsr );
  128047. if( SQLITE_OK==fts3CursorSeek(pContext, pCsr) ){
  128048. sqlite3Fts3Offsets(pContext, pCsr);
  128049. }
  128050. }
  128051. /*
  128052. ** Implementation of the special optimize() function for FTS3. This
  128053. ** function merges all segments in the database to a single segment.
  128054. ** Example usage is:
  128055. **
  128056. ** SELECT optimize(t) FROM t LIMIT 1;
  128057. **
  128058. ** where 't' is the name of an FTS3 table.
  128059. */
  128060. static void fts3OptimizeFunc(
  128061. sqlite3_context *pContext, /* SQLite function call context */
  128062. int nVal, /* Size of argument array */
  128063. sqlite3_value **apVal /* Array of arguments */
  128064. ){
  128065. int rc; /* Return code */
  128066. Fts3Table *p; /* Virtual table handle */
  128067. Fts3Cursor *pCursor; /* Cursor handle passed through apVal[0] */
  128068. UNUSED_PARAMETER(nVal);
  128069. assert( nVal==1 );
  128070. if( fts3FunctionArg(pContext, "optimize", apVal[0], &pCursor) ) return;
  128071. p = (Fts3Table *)pCursor->base.pVtab;
  128072. assert( p );
  128073. rc = sqlite3Fts3Optimize(p);
  128074. switch( rc ){
  128075. case SQLITE_OK:
  128076. sqlite3_result_text(pContext, "Index optimized", -1, SQLITE_STATIC);
  128077. break;
  128078. case SQLITE_DONE:
  128079. sqlite3_result_text(pContext, "Index already optimal", -1, SQLITE_STATIC);
  128080. break;
  128081. default:
  128082. sqlite3_result_error_code(pContext, rc);
  128083. break;
  128084. }
  128085. }
  128086. /*
  128087. ** Implementation of the matchinfo() function for FTS3
  128088. */
  128089. static void fts3MatchinfoFunc(
  128090. sqlite3_context *pContext, /* SQLite function call context */
  128091. int nVal, /* Size of argument array */
  128092. sqlite3_value **apVal /* Array of arguments */
  128093. ){
  128094. Fts3Cursor *pCsr; /* Cursor handle passed through apVal[0] */
  128095. assert( nVal==1 || nVal==2 );
  128096. if( SQLITE_OK==fts3FunctionArg(pContext, "matchinfo", apVal[0], &pCsr) ){
  128097. const char *zArg = 0;
  128098. if( nVal>1 ){
  128099. zArg = (const char *)sqlite3_value_text(apVal[1]);
  128100. }
  128101. sqlite3Fts3Matchinfo(pContext, pCsr, zArg);
  128102. }
  128103. }
  128104. /*
  128105. ** This routine implements the xFindFunction method for the FTS3
  128106. ** virtual table.
  128107. */
  128108. static int fts3FindFunctionMethod(
  128109. sqlite3_vtab *pVtab, /* Virtual table handle */
  128110. int nArg, /* Number of SQL function arguments */
  128111. const char *zName, /* Name of SQL function */
  128112. void (**pxFunc)(sqlite3_context*,int,sqlite3_value**), /* OUT: Result */
  128113. void **ppArg /* Unused */
  128114. ){
  128115. struct Overloaded {
  128116. const char *zName;
  128117. void (*xFunc)(sqlite3_context*,int,sqlite3_value**);
  128118. } aOverload[] = {
  128119. { "snippet", fts3SnippetFunc },
  128120. { "offsets", fts3OffsetsFunc },
  128121. { "optimize", fts3OptimizeFunc },
  128122. { "matchinfo", fts3MatchinfoFunc },
  128123. };
  128124. int i; /* Iterator variable */
  128125. UNUSED_PARAMETER(pVtab);
  128126. UNUSED_PARAMETER(nArg);
  128127. UNUSED_PARAMETER(ppArg);
  128128. for(i=0; i<SizeofArray(aOverload); i++){
  128129. if( strcmp(zName, aOverload[i].zName)==0 ){
  128130. *pxFunc = aOverload[i].xFunc;
  128131. return 1;
  128132. }
  128133. }
  128134. /* No function of the specified name was found. Return 0. */
  128135. return 0;
  128136. }
  128137. /*
  128138. ** Implementation of FTS3 xRename method. Rename an fts3 table.
  128139. */
  128140. static int fts3RenameMethod(
  128141. sqlite3_vtab *pVtab, /* Virtual table handle */
  128142. const char *zName /* New name of table */
  128143. ){
  128144. Fts3Table *p = (Fts3Table *)pVtab;
  128145. sqlite3 *db = p->db; /* Database connection */
  128146. int rc; /* Return Code */
  128147. /* At this point it must be known if the %_stat table exists or not.
  128148. ** So bHasStat may not be 2. */
  128149. rc = fts3SetHasStat(p);
  128150. /* As it happens, the pending terms table is always empty here. This is
  128151. ** because an "ALTER TABLE RENAME TABLE" statement inside a transaction
  128152. ** always opens a savepoint transaction. And the xSavepoint() method
  128153. ** flushes the pending terms table. But leave the (no-op) call to
  128154. ** PendingTermsFlush() in in case that changes.
  128155. */
  128156. assert( p->nPendingData==0 );
  128157. if( rc==SQLITE_OK ){
  128158. rc = sqlite3Fts3PendingTermsFlush(p);
  128159. }
  128160. if( p->zContentTbl==0 ){
  128161. fts3DbExec(&rc, db,
  128162. "ALTER TABLE %Q.'%q_content' RENAME TO '%q_content';",
  128163. p->zDb, p->zName, zName
  128164. );
  128165. }
  128166. if( p->bHasDocsize ){
  128167. fts3DbExec(&rc, db,
  128168. "ALTER TABLE %Q.'%q_docsize' RENAME TO '%q_docsize';",
  128169. p->zDb, p->zName, zName
  128170. );
  128171. }
  128172. if( p->bHasStat ){
  128173. fts3DbExec(&rc, db,
  128174. "ALTER TABLE %Q.'%q_stat' RENAME TO '%q_stat';",
  128175. p->zDb, p->zName, zName
  128176. );
  128177. }
  128178. fts3DbExec(&rc, db,
  128179. "ALTER TABLE %Q.'%q_segments' RENAME TO '%q_segments';",
  128180. p->zDb, p->zName, zName
  128181. );
  128182. fts3DbExec(&rc, db,
  128183. "ALTER TABLE %Q.'%q_segdir' RENAME TO '%q_segdir';",
  128184. p->zDb, p->zName, zName
  128185. );
  128186. return rc;
  128187. }
  128188. /*
  128189. ** The xSavepoint() method.
  128190. **
  128191. ** Flush the contents of the pending-terms table to disk.
  128192. */
  128193. static int fts3SavepointMethod(sqlite3_vtab *pVtab, int iSavepoint){
  128194. int rc = SQLITE_OK;
  128195. UNUSED_PARAMETER(iSavepoint);
  128196. assert( ((Fts3Table *)pVtab)->inTransaction );
  128197. assert( ((Fts3Table *)pVtab)->mxSavepoint < iSavepoint );
  128198. TESTONLY( ((Fts3Table *)pVtab)->mxSavepoint = iSavepoint );
  128199. if( ((Fts3Table *)pVtab)->bIgnoreSavepoint==0 ){
  128200. rc = fts3SyncMethod(pVtab);
  128201. }
  128202. return rc;
  128203. }
  128204. /*
  128205. ** The xRelease() method.
  128206. **
  128207. ** This is a no-op.
  128208. */
  128209. static int fts3ReleaseMethod(sqlite3_vtab *pVtab, int iSavepoint){
  128210. TESTONLY( Fts3Table *p = (Fts3Table*)pVtab );
  128211. UNUSED_PARAMETER(iSavepoint);
  128212. UNUSED_PARAMETER(pVtab);
  128213. assert( p->inTransaction );
  128214. assert( p->mxSavepoint >= iSavepoint );
  128215. TESTONLY( p->mxSavepoint = iSavepoint-1 );
  128216. return SQLITE_OK;
  128217. }
  128218. /*
  128219. ** The xRollbackTo() method.
  128220. **
  128221. ** Discard the contents of the pending terms table.
  128222. */
  128223. static int fts3RollbackToMethod(sqlite3_vtab *pVtab, int iSavepoint){
  128224. Fts3Table *p = (Fts3Table*)pVtab;
  128225. UNUSED_PARAMETER(iSavepoint);
  128226. assert( p->inTransaction );
  128227. assert( p->mxSavepoint >= iSavepoint );
  128228. TESTONLY( p->mxSavepoint = iSavepoint );
  128229. sqlite3Fts3PendingTermsClear(p);
  128230. return SQLITE_OK;
  128231. }
  128232. static const sqlite3_module fts3Module = {
  128233. /* iVersion */ 2,
  128234. /* xCreate */ fts3CreateMethod,
  128235. /* xConnect */ fts3ConnectMethod,
  128236. /* xBestIndex */ fts3BestIndexMethod,
  128237. /* xDisconnect */ fts3DisconnectMethod,
  128238. /* xDestroy */ fts3DestroyMethod,
  128239. /* xOpen */ fts3OpenMethod,
  128240. /* xClose */ fts3CloseMethod,
  128241. /* xFilter */ fts3FilterMethod,
  128242. /* xNext */ fts3NextMethod,
  128243. /* xEof */ fts3EofMethod,
  128244. /* xColumn */ fts3ColumnMethod,
  128245. /* xRowid */ fts3RowidMethod,
  128246. /* xUpdate */ fts3UpdateMethod,
  128247. /* xBegin */ fts3BeginMethod,
  128248. /* xSync */ fts3SyncMethod,
  128249. /* xCommit */ fts3CommitMethod,
  128250. /* xRollback */ fts3RollbackMethod,
  128251. /* xFindFunction */ fts3FindFunctionMethod,
  128252. /* xRename */ fts3RenameMethod,
  128253. /* xSavepoint */ fts3SavepointMethod,
  128254. /* xRelease */ fts3ReleaseMethod,
  128255. /* xRollbackTo */ fts3RollbackToMethod,
  128256. };
  128257. /*
  128258. ** This function is registered as the module destructor (called when an
  128259. ** FTS3 enabled database connection is closed). It frees the memory
  128260. ** allocated for the tokenizer hash table.
  128261. */
  128262. static void hashDestroy(void *p){
  128263. Fts3Hash *pHash = (Fts3Hash *)p;
  128264. sqlite3Fts3HashClear(pHash);
  128265. sqlite3_free(pHash);
  128266. }
  128267. /*
  128268. ** The fts3 built-in tokenizers - "simple", "porter" and "icu"- are
  128269. ** implemented in files fts3_tokenizer1.c, fts3_porter.c and fts3_icu.c
  128270. ** respectively. The following three forward declarations are for functions
  128271. ** declared in these files used to retrieve the respective implementations.
  128272. **
  128273. ** Calling sqlite3Fts3SimpleTokenizerModule() sets the value pointed
  128274. ** to by the argument to point to the "simple" tokenizer implementation.
  128275. ** And so on.
  128276. */
  128277. SQLITE_PRIVATE void sqlite3Fts3SimpleTokenizerModule(sqlite3_tokenizer_module const**ppModule);
  128278. SQLITE_PRIVATE void sqlite3Fts3PorterTokenizerModule(sqlite3_tokenizer_module const**ppModule);
  128279. #ifndef SQLITE_DISABLE_FTS3_UNICODE
  128280. SQLITE_PRIVATE void sqlite3Fts3UnicodeTokenizer(sqlite3_tokenizer_module const**ppModule);
  128281. #endif
  128282. #ifdef SQLITE_ENABLE_ICU
  128283. SQLITE_PRIVATE void sqlite3Fts3IcuTokenizerModule(sqlite3_tokenizer_module const**ppModule);
  128284. #endif
  128285. /*
  128286. ** Initialize the fts3 extension. If this extension is built as part
  128287. ** of the sqlite library, then this function is called directly by
  128288. ** SQLite. If fts3 is built as a dynamically loadable extension, this
  128289. ** function is called by the sqlite3_extension_init() entry point.
  128290. */
  128291. SQLITE_PRIVATE int sqlite3Fts3Init(sqlite3 *db){
  128292. int rc = SQLITE_OK;
  128293. Fts3Hash *pHash = 0;
  128294. const sqlite3_tokenizer_module *pSimple = 0;
  128295. const sqlite3_tokenizer_module *pPorter = 0;
  128296. #ifndef SQLITE_DISABLE_FTS3_UNICODE
  128297. const sqlite3_tokenizer_module *pUnicode = 0;
  128298. #endif
  128299. #ifdef SQLITE_ENABLE_ICU
  128300. const sqlite3_tokenizer_module *pIcu = 0;
  128301. sqlite3Fts3IcuTokenizerModule(&pIcu);
  128302. #endif
  128303. #ifndef SQLITE_DISABLE_FTS3_UNICODE
  128304. sqlite3Fts3UnicodeTokenizer(&pUnicode);
  128305. #endif
  128306. #ifdef SQLITE_TEST
  128307. rc = sqlite3Fts3InitTerm(db);
  128308. if( rc!=SQLITE_OK ) return rc;
  128309. #endif
  128310. rc = sqlite3Fts3InitAux(db);
  128311. if( rc!=SQLITE_OK ) return rc;
  128312. sqlite3Fts3SimpleTokenizerModule(&pSimple);
  128313. sqlite3Fts3PorterTokenizerModule(&pPorter);
  128314. /* Allocate and initialize the hash-table used to store tokenizers. */
  128315. pHash = sqlite3_malloc(sizeof(Fts3Hash));
  128316. if( !pHash ){
  128317. rc = SQLITE_NOMEM;
  128318. }else{
  128319. sqlite3Fts3HashInit(pHash, FTS3_HASH_STRING, 1);
  128320. }
  128321. /* Load the built-in tokenizers into the hash table */
  128322. if( rc==SQLITE_OK ){
  128323. if( sqlite3Fts3HashInsert(pHash, "simple", 7, (void *)pSimple)
  128324. || sqlite3Fts3HashInsert(pHash, "porter", 7, (void *)pPorter)
  128325. #ifndef SQLITE_DISABLE_FTS3_UNICODE
  128326. || sqlite3Fts3HashInsert(pHash, "unicode61", 10, (void *)pUnicode)
  128327. #endif
  128328. #ifdef SQLITE_ENABLE_ICU
  128329. || (pIcu && sqlite3Fts3HashInsert(pHash, "icu", 4, (void *)pIcu))
  128330. #endif
  128331. ){
  128332. rc = SQLITE_NOMEM;
  128333. }
  128334. }
  128335. #ifdef SQLITE_TEST
  128336. if( rc==SQLITE_OK ){
  128337. rc = sqlite3Fts3ExprInitTestInterface(db);
  128338. }
  128339. #endif
  128340. /* Create the virtual table wrapper around the hash-table and overload
  128341. ** the two scalar functions. If this is successful, register the
  128342. ** module with sqlite.
  128343. */
  128344. if( SQLITE_OK==rc
  128345. && SQLITE_OK==(rc = sqlite3Fts3InitHashTable(db, pHash, "fts3_tokenizer"))
  128346. && SQLITE_OK==(rc = sqlite3_overload_function(db, "snippet", -1))
  128347. && SQLITE_OK==(rc = sqlite3_overload_function(db, "offsets", 1))
  128348. && SQLITE_OK==(rc = sqlite3_overload_function(db, "matchinfo", 1))
  128349. && SQLITE_OK==(rc = sqlite3_overload_function(db, "matchinfo", 2))
  128350. && SQLITE_OK==(rc = sqlite3_overload_function(db, "optimize", 1))
  128351. ){
  128352. rc = sqlite3_create_module_v2(
  128353. db, "fts3", &fts3Module, (void *)pHash, hashDestroy
  128354. );
  128355. if( rc==SQLITE_OK ){
  128356. rc = sqlite3_create_module_v2(
  128357. db, "fts4", &fts3Module, (void *)pHash, 0
  128358. );
  128359. }
  128360. if( rc==SQLITE_OK ){
  128361. rc = sqlite3Fts3InitTok(db, (void *)pHash);
  128362. }
  128363. return rc;
  128364. }
  128365. /* An error has occurred. Delete the hash table and return the error code. */
  128366. assert( rc!=SQLITE_OK );
  128367. if( pHash ){
  128368. sqlite3Fts3HashClear(pHash);
  128369. sqlite3_free(pHash);
  128370. }
  128371. return rc;
  128372. }
  128373. /*
  128374. ** Allocate an Fts3MultiSegReader for each token in the expression headed
  128375. ** by pExpr.
  128376. **
  128377. ** An Fts3SegReader object is a cursor that can seek or scan a range of
  128378. ** entries within a single segment b-tree. An Fts3MultiSegReader uses multiple
  128379. ** Fts3SegReader objects internally to provide an interface to seek or scan
  128380. ** within the union of all segments of a b-tree. Hence the name.
  128381. **
  128382. ** If the allocated Fts3MultiSegReader just seeks to a single entry in a
  128383. ** segment b-tree (if the term is not a prefix or it is a prefix for which
  128384. ** there exists prefix b-tree of the right length) then it may be traversed
  128385. ** and merged incrementally. Otherwise, it has to be merged into an in-memory
  128386. ** doclist and then traversed.
  128387. */
  128388. static void fts3EvalAllocateReaders(
  128389. Fts3Cursor *pCsr, /* FTS cursor handle */
  128390. Fts3Expr *pExpr, /* Allocate readers for this expression */
  128391. int *pnToken, /* OUT: Total number of tokens in phrase. */
  128392. int *pnOr, /* OUT: Total number of OR nodes in expr. */
  128393. int *pRc /* IN/OUT: Error code */
  128394. ){
  128395. if( pExpr && SQLITE_OK==*pRc ){
  128396. if( pExpr->eType==FTSQUERY_PHRASE ){
  128397. int i;
  128398. int nToken = pExpr->pPhrase->nToken;
  128399. *pnToken += nToken;
  128400. for(i=0; i<nToken; i++){
  128401. Fts3PhraseToken *pToken = &pExpr->pPhrase->aToken[i];
  128402. int rc = fts3TermSegReaderCursor(pCsr,
  128403. pToken->z, pToken->n, pToken->isPrefix, &pToken->pSegcsr
  128404. );
  128405. if( rc!=SQLITE_OK ){
  128406. *pRc = rc;
  128407. return;
  128408. }
  128409. }
  128410. assert( pExpr->pPhrase->iDoclistToken==0 );
  128411. pExpr->pPhrase->iDoclistToken = -1;
  128412. }else{
  128413. *pnOr += (pExpr->eType==FTSQUERY_OR);
  128414. fts3EvalAllocateReaders(pCsr, pExpr->pLeft, pnToken, pnOr, pRc);
  128415. fts3EvalAllocateReaders(pCsr, pExpr->pRight, pnToken, pnOr, pRc);
  128416. }
  128417. }
  128418. }
  128419. /*
  128420. ** Arguments pList/nList contain the doclist for token iToken of phrase p.
  128421. ** It is merged into the main doclist stored in p->doclist.aAll/nAll.
  128422. **
  128423. ** This function assumes that pList points to a buffer allocated using
  128424. ** sqlite3_malloc(). This function takes responsibility for eventually
  128425. ** freeing the buffer.
  128426. **
  128427. ** SQLITE_OK is returned if successful, or SQLITE_NOMEM if an error occurs.
  128428. */
  128429. static int fts3EvalPhraseMergeToken(
  128430. Fts3Table *pTab, /* FTS Table pointer */
  128431. Fts3Phrase *p, /* Phrase to merge pList/nList into */
  128432. int iToken, /* Token pList/nList corresponds to */
  128433. char *pList, /* Pointer to doclist */
  128434. int nList /* Number of bytes in pList */
  128435. ){
  128436. int rc = SQLITE_OK;
  128437. assert( iToken!=p->iDoclistToken );
  128438. if( pList==0 ){
  128439. sqlite3_free(p->doclist.aAll);
  128440. p->doclist.aAll = 0;
  128441. p->doclist.nAll = 0;
  128442. }
  128443. else if( p->iDoclistToken<0 ){
  128444. p->doclist.aAll = pList;
  128445. p->doclist.nAll = nList;
  128446. }
  128447. else if( p->doclist.aAll==0 ){
  128448. sqlite3_free(pList);
  128449. }
  128450. else {
  128451. char *pLeft;
  128452. char *pRight;
  128453. int nLeft;
  128454. int nRight;
  128455. int nDiff;
  128456. if( p->iDoclistToken<iToken ){
  128457. pLeft = p->doclist.aAll;
  128458. nLeft = p->doclist.nAll;
  128459. pRight = pList;
  128460. nRight = nList;
  128461. nDiff = iToken - p->iDoclistToken;
  128462. }else{
  128463. pRight = p->doclist.aAll;
  128464. nRight = p->doclist.nAll;
  128465. pLeft = pList;
  128466. nLeft = nList;
  128467. nDiff = p->iDoclistToken - iToken;
  128468. }
  128469. rc = fts3DoclistPhraseMerge(
  128470. pTab->bDescIdx, nDiff, pLeft, nLeft, &pRight, &nRight
  128471. );
  128472. sqlite3_free(pLeft);
  128473. p->doclist.aAll = pRight;
  128474. p->doclist.nAll = nRight;
  128475. }
  128476. if( iToken>p->iDoclistToken ) p->iDoclistToken = iToken;
  128477. return rc;
  128478. }
  128479. /*
  128480. ** Load the doclist for phrase p into p->doclist.aAll/nAll. The loaded doclist
  128481. ** does not take deferred tokens into account.
  128482. **
  128483. ** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
  128484. */
  128485. static int fts3EvalPhraseLoad(
  128486. Fts3Cursor *pCsr, /* FTS Cursor handle */
  128487. Fts3Phrase *p /* Phrase object */
  128488. ){
  128489. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  128490. int iToken;
  128491. int rc = SQLITE_OK;
  128492. for(iToken=0; rc==SQLITE_OK && iToken<p->nToken; iToken++){
  128493. Fts3PhraseToken *pToken = &p->aToken[iToken];
  128494. assert( pToken->pDeferred==0 || pToken->pSegcsr==0 );
  128495. if( pToken->pSegcsr ){
  128496. int nThis = 0;
  128497. char *pThis = 0;
  128498. rc = fts3TermSelect(pTab, pToken, p->iColumn, &nThis, &pThis);
  128499. if( rc==SQLITE_OK ){
  128500. rc = fts3EvalPhraseMergeToken(pTab, p, iToken, pThis, nThis);
  128501. }
  128502. }
  128503. assert( pToken->pSegcsr==0 );
  128504. }
  128505. return rc;
  128506. }
  128507. /*
  128508. ** This function is called on each phrase after the position lists for
  128509. ** any deferred tokens have been loaded into memory. It updates the phrases
  128510. ** current position list to include only those positions that are really
  128511. ** instances of the phrase (after considering deferred tokens). If this
  128512. ** means that the phrase does not appear in the current row, doclist.pList
  128513. ** and doclist.nList are both zeroed.
  128514. **
  128515. ** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
  128516. */
  128517. static int fts3EvalDeferredPhrase(Fts3Cursor *pCsr, Fts3Phrase *pPhrase){
  128518. int iToken; /* Used to iterate through phrase tokens */
  128519. char *aPoslist = 0; /* Position list for deferred tokens */
  128520. int nPoslist = 0; /* Number of bytes in aPoslist */
  128521. int iPrev = -1; /* Token number of previous deferred token */
  128522. assert( pPhrase->doclist.bFreeList==0 );
  128523. for(iToken=0; iToken<pPhrase->nToken; iToken++){
  128524. Fts3PhraseToken *pToken = &pPhrase->aToken[iToken];
  128525. Fts3DeferredToken *pDeferred = pToken->pDeferred;
  128526. if( pDeferred ){
  128527. char *pList;
  128528. int nList;
  128529. int rc = sqlite3Fts3DeferredTokenList(pDeferred, &pList, &nList);
  128530. if( rc!=SQLITE_OK ) return rc;
  128531. if( pList==0 ){
  128532. sqlite3_free(aPoslist);
  128533. pPhrase->doclist.pList = 0;
  128534. pPhrase->doclist.nList = 0;
  128535. return SQLITE_OK;
  128536. }else if( aPoslist==0 ){
  128537. aPoslist = pList;
  128538. nPoslist = nList;
  128539. }else{
  128540. char *aOut = pList;
  128541. char *p1 = aPoslist;
  128542. char *p2 = aOut;
  128543. assert( iPrev>=0 );
  128544. fts3PoslistPhraseMerge(&aOut, iToken-iPrev, 0, 1, &p1, &p2);
  128545. sqlite3_free(aPoslist);
  128546. aPoslist = pList;
  128547. nPoslist = (int)(aOut - aPoslist);
  128548. if( nPoslist==0 ){
  128549. sqlite3_free(aPoslist);
  128550. pPhrase->doclist.pList = 0;
  128551. pPhrase->doclist.nList = 0;
  128552. return SQLITE_OK;
  128553. }
  128554. }
  128555. iPrev = iToken;
  128556. }
  128557. }
  128558. if( iPrev>=0 ){
  128559. int nMaxUndeferred = pPhrase->iDoclistToken;
  128560. if( nMaxUndeferred<0 ){
  128561. pPhrase->doclist.pList = aPoslist;
  128562. pPhrase->doclist.nList = nPoslist;
  128563. pPhrase->doclist.iDocid = pCsr->iPrevId;
  128564. pPhrase->doclist.bFreeList = 1;
  128565. }else{
  128566. int nDistance;
  128567. char *p1;
  128568. char *p2;
  128569. char *aOut;
  128570. if( nMaxUndeferred>iPrev ){
  128571. p1 = aPoslist;
  128572. p2 = pPhrase->doclist.pList;
  128573. nDistance = nMaxUndeferred - iPrev;
  128574. }else{
  128575. p1 = pPhrase->doclist.pList;
  128576. p2 = aPoslist;
  128577. nDistance = iPrev - nMaxUndeferred;
  128578. }
  128579. aOut = (char *)sqlite3_malloc(nPoslist+8);
  128580. if( !aOut ){
  128581. sqlite3_free(aPoslist);
  128582. return SQLITE_NOMEM;
  128583. }
  128584. pPhrase->doclist.pList = aOut;
  128585. if( fts3PoslistPhraseMerge(&aOut, nDistance, 0, 1, &p1, &p2) ){
  128586. pPhrase->doclist.bFreeList = 1;
  128587. pPhrase->doclist.nList = (int)(aOut - pPhrase->doclist.pList);
  128588. }else{
  128589. sqlite3_free(aOut);
  128590. pPhrase->doclist.pList = 0;
  128591. pPhrase->doclist.nList = 0;
  128592. }
  128593. sqlite3_free(aPoslist);
  128594. }
  128595. }
  128596. return SQLITE_OK;
  128597. }
  128598. /*
  128599. ** Maximum number of tokens a phrase may have to be considered for the
  128600. ** incremental doclists strategy.
  128601. */
  128602. #define MAX_INCR_PHRASE_TOKENS 4
  128603. /*
  128604. ** This function is called for each Fts3Phrase in a full-text query
  128605. ** expression to initialize the mechanism for returning rows. Once this
  128606. ** function has been called successfully on an Fts3Phrase, it may be
  128607. ** used with fts3EvalPhraseNext() to iterate through the matching docids.
  128608. **
  128609. ** If parameter bOptOk is true, then the phrase may (or may not) use the
  128610. ** incremental loading strategy. Otherwise, the entire doclist is loaded into
  128611. ** memory within this call.
  128612. **
  128613. ** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
  128614. */
  128615. static int fts3EvalPhraseStart(Fts3Cursor *pCsr, int bOptOk, Fts3Phrase *p){
  128616. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  128617. int rc = SQLITE_OK; /* Error code */
  128618. int i;
  128619. /* Determine if doclists may be loaded from disk incrementally. This is
  128620. ** possible if the bOptOk argument is true, the FTS doclists will be
  128621. ** scanned in forward order, and the phrase consists of
  128622. ** MAX_INCR_PHRASE_TOKENS or fewer tokens, none of which are are "^first"
  128623. ** tokens or prefix tokens that cannot use a prefix-index. */
  128624. int bHaveIncr = 0;
  128625. int bIncrOk = (bOptOk
  128626. && pCsr->bDesc==pTab->bDescIdx
  128627. && p->nToken<=MAX_INCR_PHRASE_TOKENS && p->nToken>0
  128628. && p->nToken<=MAX_INCR_PHRASE_TOKENS && p->nToken>0
  128629. #ifdef SQLITE_TEST
  128630. && pTab->bNoIncrDoclist==0
  128631. #endif
  128632. );
  128633. for(i=0; bIncrOk==1 && i<p->nToken; i++){
  128634. Fts3PhraseToken *pToken = &p->aToken[i];
  128635. if( pToken->bFirst || (pToken->pSegcsr!=0 && !pToken->pSegcsr->bLookup) ){
  128636. bIncrOk = 0;
  128637. }
  128638. if( pToken->pSegcsr ) bHaveIncr = 1;
  128639. }
  128640. if( bIncrOk && bHaveIncr ){
  128641. /* Use the incremental approach. */
  128642. int iCol = (p->iColumn >= pTab->nColumn ? -1 : p->iColumn);
  128643. for(i=0; rc==SQLITE_OK && i<p->nToken; i++){
  128644. Fts3PhraseToken *pToken = &p->aToken[i];
  128645. Fts3MultiSegReader *pSegcsr = pToken->pSegcsr;
  128646. if( pSegcsr ){
  128647. rc = sqlite3Fts3MsrIncrStart(pTab, pSegcsr, iCol, pToken->z, pToken->n);
  128648. }
  128649. }
  128650. p->bIncr = 1;
  128651. }else{
  128652. /* Load the full doclist for the phrase into memory. */
  128653. rc = fts3EvalPhraseLoad(pCsr, p);
  128654. p->bIncr = 0;
  128655. }
  128656. assert( rc!=SQLITE_OK || p->nToken<1 || p->aToken[0].pSegcsr==0 || p->bIncr );
  128657. return rc;
  128658. }
  128659. /*
  128660. ** This function is used to iterate backwards (from the end to start)
  128661. ** through doclists. It is used by this module to iterate through phrase
  128662. ** doclists in reverse and by the fts3_write.c module to iterate through
  128663. ** pending-terms lists when writing to databases with "order=desc".
  128664. **
  128665. ** The doclist may be sorted in ascending (parameter bDescIdx==0) or
  128666. ** descending (parameter bDescIdx==1) order of docid. Regardless, this
  128667. ** function iterates from the end of the doclist to the beginning.
  128668. */
  128669. SQLITE_PRIVATE void sqlite3Fts3DoclistPrev(
  128670. int bDescIdx, /* True if the doclist is desc */
  128671. char *aDoclist, /* Pointer to entire doclist */
  128672. int nDoclist, /* Length of aDoclist in bytes */
  128673. char **ppIter, /* IN/OUT: Iterator pointer */
  128674. sqlite3_int64 *piDocid, /* IN/OUT: Docid pointer */
  128675. int *pnList, /* OUT: List length pointer */
  128676. u8 *pbEof /* OUT: End-of-file flag */
  128677. ){
  128678. char *p = *ppIter;
  128679. assert( nDoclist>0 );
  128680. assert( *pbEof==0 );
  128681. assert( p || *piDocid==0 );
  128682. assert( !p || (p>aDoclist && p<&aDoclist[nDoclist]) );
  128683. if( p==0 ){
  128684. sqlite3_int64 iDocid = 0;
  128685. char *pNext = 0;
  128686. char *pDocid = aDoclist;
  128687. char *pEnd = &aDoclist[nDoclist];
  128688. int iMul = 1;
  128689. while( pDocid<pEnd ){
  128690. sqlite3_int64 iDelta;
  128691. pDocid += sqlite3Fts3GetVarint(pDocid, &iDelta);
  128692. iDocid += (iMul * iDelta);
  128693. pNext = pDocid;
  128694. fts3PoslistCopy(0, &pDocid);
  128695. while( pDocid<pEnd && *pDocid==0 ) pDocid++;
  128696. iMul = (bDescIdx ? -1 : 1);
  128697. }
  128698. *pnList = (int)(pEnd - pNext);
  128699. *ppIter = pNext;
  128700. *piDocid = iDocid;
  128701. }else{
  128702. int iMul = (bDescIdx ? -1 : 1);
  128703. sqlite3_int64 iDelta;
  128704. fts3GetReverseVarint(&p, aDoclist, &iDelta);
  128705. *piDocid -= (iMul * iDelta);
  128706. if( p==aDoclist ){
  128707. *pbEof = 1;
  128708. }else{
  128709. char *pSave = p;
  128710. fts3ReversePoslist(aDoclist, &p);
  128711. *pnList = (int)(pSave - p);
  128712. }
  128713. *ppIter = p;
  128714. }
  128715. }
  128716. /*
  128717. ** Iterate forwards through a doclist.
  128718. */
  128719. SQLITE_PRIVATE void sqlite3Fts3DoclistNext(
  128720. int bDescIdx, /* True if the doclist is desc */
  128721. char *aDoclist, /* Pointer to entire doclist */
  128722. int nDoclist, /* Length of aDoclist in bytes */
  128723. char **ppIter, /* IN/OUT: Iterator pointer */
  128724. sqlite3_int64 *piDocid, /* IN/OUT: Docid pointer */
  128725. u8 *pbEof /* OUT: End-of-file flag */
  128726. ){
  128727. char *p = *ppIter;
  128728. assert( nDoclist>0 );
  128729. assert( *pbEof==0 );
  128730. assert( p || *piDocid==0 );
  128731. assert( !p || (p>=aDoclist && p<=&aDoclist[nDoclist]) );
  128732. if( p==0 ){
  128733. p = aDoclist;
  128734. p += sqlite3Fts3GetVarint(p, piDocid);
  128735. }else{
  128736. fts3PoslistCopy(0, &p);
  128737. if( p>=&aDoclist[nDoclist] ){
  128738. *pbEof = 1;
  128739. }else{
  128740. sqlite3_int64 iVar;
  128741. p += sqlite3Fts3GetVarint(p, &iVar);
  128742. *piDocid += ((bDescIdx ? -1 : 1) * iVar);
  128743. }
  128744. }
  128745. *ppIter = p;
  128746. }
  128747. /*
  128748. ** Advance the iterator pDL to the next entry in pDL->aAll/nAll. Set *pbEof
  128749. ** to true if EOF is reached.
  128750. */
  128751. static void fts3EvalDlPhraseNext(
  128752. Fts3Table *pTab,
  128753. Fts3Doclist *pDL,
  128754. u8 *pbEof
  128755. ){
  128756. char *pIter; /* Used to iterate through aAll */
  128757. char *pEnd = &pDL->aAll[pDL->nAll]; /* 1 byte past end of aAll */
  128758. if( pDL->pNextDocid ){
  128759. pIter = pDL->pNextDocid;
  128760. }else{
  128761. pIter = pDL->aAll;
  128762. }
  128763. if( pIter>=pEnd ){
  128764. /* We have already reached the end of this doclist. EOF. */
  128765. *pbEof = 1;
  128766. }else{
  128767. sqlite3_int64 iDelta;
  128768. pIter += sqlite3Fts3GetVarint(pIter, &iDelta);
  128769. if( pTab->bDescIdx==0 || pDL->pNextDocid==0 ){
  128770. pDL->iDocid += iDelta;
  128771. }else{
  128772. pDL->iDocid -= iDelta;
  128773. }
  128774. pDL->pList = pIter;
  128775. fts3PoslistCopy(0, &pIter);
  128776. pDL->nList = (int)(pIter - pDL->pList);
  128777. /* pIter now points just past the 0x00 that terminates the position-
  128778. ** list for document pDL->iDocid. However, if this position-list was
  128779. ** edited in place by fts3EvalNearTrim(), then pIter may not actually
  128780. ** point to the start of the next docid value. The following line deals
  128781. ** with this case by advancing pIter past the zero-padding added by
  128782. ** fts3EvalNearTrim(). */
  128783. while( pIter<pEnd && *pIter==0 ) pIter++;
  128784. pDL->pNextDocid = pIter;
  128785. assert( pIter>=&pDL->aAll[pDL->nAll] || *pIter );
  128786. *pbEof = 0;
  128787. }
  128788. }
  128789. /*
  128790. ** Helper type used by fts3EvalIncrPhraseNext() and incrPhraseTokenNext().
  128791. */
  128792. typedef struct TokenDoclist TokenDoclist;
  128793. struct TokenDoclist {
  128794. int bIgnore;
  128795. sqlite3_int64 iDocid;
  128796. char *pList;
  128797. int nList;
  128798. };
  128799. /*
  128800. ** Token pToken is an incrementally loaded token that is part of a
  128801. ** multi-token phrase. Advance it to the next matching document in the
  128802. ** database and populate output variable *p with the details of the new
  128803. ** entry. Or, if the iterator has reached EOF, set *pbEof to true.
  128804. **
  128805. ** If an error occurs, return an SQLite error code. Otherwise, return
  128806. ** SQLITE_OK.
  128807. */
  128808. static int incrPhraseTokenNext(
  128809. Fts3Table *pTab, /* Virtual table handle */
  128810. Fts3Phrase *pPhrase, /* Phrase to advance token of */
  128811. int iToken, /* Specific token to advance */
  128812. TokenDoclist *p, /* OUT: Docid and doclist for new entry */
  128813. u8 *pbEof /* OUT: True if iterator is at EOF */
  128814. ){
  128815. int rc = SQLITE_OK;
  128816. if( pPhrase->iDoclistToken==iToken ){
  128817. assert( p->bIgnore==0 );
  128818. assert( pPhrase->aToken[iToken].pSegcsr==0 );
  128819. fts3EvalDlPhraseNext(pTab, &pPhrase->doclist, pbEof);
  128820. p->pList = pPhrase->doclist.pList;
  128821. p->nList = pPhrase->doclist.nList;
  128822. p->iDocid = pPhrase->doclist.iDocid;
  128823. }else{
  128824. Fts3PhraseToken *pToken = &pPhrase->aToken[iToken];
  128825. assert( pToken->pDeferred==0 );
  128826. assert( pToken->pSegcsr || pPhrase->iDoclistToken>=0 );
  128827. if( pToken->pSegcsr ){
  128828. assert( p->bIgnore==0 );
  128829. rc = sqlite3Fts3MsrIncrNext(
  128830. pTab, pToken->pSegcsr, &p->iDocid, &p->pList, &p->nList
  128831. );
  128832. if( p->pList==0 ) *pbEof = 1;
  128833. }else{
  128834. p->bIgnore = 1;
  128835. }
  128836. }
  128837. return rc;
  128838. }
  128839. /*
  128840. ** The phrase iterator passed as the second argument:
  128841. **
  128842. ** * features at least one token that uses an incremental doclist, and
  128843. **
  128844. ** * does not contain any deferred tokens.
  128845. **
  128846. ** Advance it to the next matching documnent in the database and populate
  128847. ** the Fts3Doclist.pList and nList fields.
  128848. **
  128849. ** If there is no "next" entry and no error occurs, then *pbEof is set to
  128850. ** 1 before returning. Otherwise, if no error occurs and the iterator is
  128851. ** successfully advanced, *pbEof is set to 0.
  128852. **
  128853. ** If an error occurs, return an SQLite error code. Otherwise, return
  128854. ** SQLITE_OK.
  128855. */
  128856. static int fts3EvalIncrPhraseNext(
  128857. Fts3Cursor *pCsr, /* FTS Cursor handle */
  128858. Fts3Phrase *p, /* Phrase object to advance to next docid */
  128859. u8 *pbEof /* OUT: Set to 1 if EOF */
  128860. ){
  128861. int rc = SQLITE_OK;
  128862. Fts3Doclist *pDL = &p->doclist;
  128863. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  128864. u8 bEof = 0;
  128865. /* This is only called if it is guaranteed that the phrase has at least
  128866. ** one incremental token. In which case the bIncr flag is set. */
  128867. assert( p->bIncr==1 );
  128868. if( p->nToken==1 && p->bIncr ){
  128869. rc = sqlite3Fts3MsrIncrNext(pTab, p->aToken[0].pSegcsr,
  128870. &pDL->iDocid, &pDL->pList, &pDL->nList
  128871. );
  128872. if( pDL->pList==0 ) bEof = 1;
  128873. }else{
  128874. int bDescDoclist = pCsr->bDesc;
  128875. struct TokenDoclist a[MAX_INCR_PHRASE_TOKENS];
  128876. memset(a, 0, sizeof(a));
  128877. assert( p->nToken<=MAX_INCR_PHRASE_TOKENS );
  128878. assert( p->iDoclistToken<MAX_INCR_PHRASE_TOKENS );
  128879. while( bEof==0 ){
  128880. int bMaxSet = 0;
  128881. sqlite3_int64 iMax = 0; /* Largest docid for all iterators */
  128882. int i; /* Used to iterate through tokens */
  128883. /* Advance the iterator for each token in the phrase once. */
  128884. for(i=0; rc==SQLITE_OK && i<p->nToken && bEof==0; i++){
  128885. rc = incrPhraseTokenNext(pTab, p, i, &a[i], &bEof);
  128886. if( a[i].bIgnore==0 && (bMaxSet==0 || DOCID_CMP(iMax, a[i].iDocid)<0) ){
  128887. iMax = a[i].iDocid;
  128888. bMaxSet = 1;
  128889. }
  128890. }
  128891. assert( rc!=SQLITE_OK || (p->nToken>=1 && a[p->nToken-1].bIgnore==0) );
  128892. assert( rc!=SQLITE_OK || bMaxSet );
  128893. /* Keep advancing iterators until they all point to the same document */
  128894. for(i=0; i<p->nToken; i++){
  128895. while( rc==SQLITE_OK && bEof==0
  128896. && a[i].bIgnore==0 && DOCID_CMP(a[i].iDocid, iMax)<0
  128897. ){
  128898. rc = incrPhraseTokenNext(pTab, p, i, &a[i], &bEof);
  128899. if( DOCID_CMP(a[i].iDocid, iMax)>0 ){
  128900. iMax = a[i].iDocid;
  128901. i = 0;
  128902. }
  128903. }
  128904. }
  128905. /* Check if the current entries really are a phrase match */
  128906. if( bEof==0 ){
  128907. int nList = 0;
  128908. int nByte = a[p->nToken-1].nList;
  128909. char *aDoclist = sqlite3_malloc(nByte+1);
  128910. if( !aDoclist ) return SQLITE_NOMEM;
  128911. memcpy(aDoclist, a[p->nToken-1].pList, nByte+1);
  128912. for(i=0; i<(p->nToken-1); i++){
  128913. if( a[i].bIgnore==0 ){
  128914. char *pL = a[i].pList;
  128915. char *pR = aDoclist;
  128916. char *pOut = aDoclist;
  128917. int nDist = p->nToken-1-i;
  128918. int res = fts3PoslistPhraseMerge(&pOut, nDist, 0, 1, &pL, &pR);
  128919. if( res==0 ) break;
  128920. nList = (int)(pOut - aDoclist);
  128921. }
  128922. }
  128923. if( i==(p->nToken-1) ){
  128924. pDL->iDocid = iMax;
  128925. pDL->pList = aDoclist;
  128926. pDL->nList = nList;
  128927. pDL->bFreeList = 1;
  128928. break;
  128929. }
  128930. sqlite3_free(aDoclist);
  128931. }
  128932. }
  128933. }
  128934. *pbEof = bEof;
  128935. return rc;
  128936. }
  128937. /*
  128938. ** Attempt to move the phrase iterator to point to the next matching docid.
  128939. ** If an error occurs, return an SQLite error code. Otherwise, return
  128940. ** SQLITE_OK.
  128941. **
  128942. ** If there is no "next" entry and no error occurs, then *pbEof is set to
  128943. ** 1 before returning. Otherwise, if no error occurs and the iterator is
  128944. ** successfully advanced, *pbEof is set to 0.
  128945. */
  128946. static int fts3EvalPhraseNext(
  128947. Fts3Cursor *pCsr, /* FTS Cursor handle */
  128948. Fts3Phrase *p, /* Phrase object to advance to next docid */
  128949. u8 *pbEof /* OUT: Set to 1 if EOF */
  128950. ){
  128951. int rc = SQLITE_OK;
  128952. Fts3Doclist *pDL = &p->doclist;
  128953. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  128954. if( p->bIncr ){
  128955. rc = fts3EvalIncrPhraseNext(pCsr, p, pbEof);
  128956. }else if( pCsr->bDesc!=pTab->bDescIdx && pDL->nAll ){
  128957. sqlite3Fts3DoclistPrev(pTab->bDescIdx, pDL->aAll, pDL->nAll,
  128958. &pDL->pNextDocid, &pDL->iDocid, &pDL->nList, pbEof
  128959. );
  128960. pDL->pList = pDL->pNextDocid;
  128961. }else{
  128962. fts3EvalDlPhraseNext(pTab, pDL, pbEof);
  128963. }
  128964. return rc;
  128965. }
  128966. /*
  128967. **
  128968. ** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
  128969. ** Otherwise, fts3EvalPhraseStart() is called on all phrases within the
  128970. ** expression. Also the Fts3Expr.bDeferred variable is set to true for any
  128971. ** expressions for which all descendent tokens are deferred.
  128972. **
  128973. ** If parameter bOptOk is zero, then it is guaranteed that the
  128974. ** Fts3Phrase.doclist.aAll/nAll variables contain the entire doclist for
  128975. ** each phrase in the expression (subject to deferred token processing).
  128976. ** Or, if bOptOk is non-zero, then one or more tokens within the expression
  128977. ** may be loaded incrementally, meaning doclist.aAll/nAll is not available.
  128978. **
  128979. ** If an error occurs within this function, *pRc is set to an SQLite error
  128980. ** code before returning.
  128981. */
  128982. static void fts3EvalStartReaders(
  128983. Fts3Cursor *pCsr, /* FTS Cursor handle */
  128984. Fts3Expr *pExpr, /* Expression to initialize phrases in */
  128985. int *pRc /* IN/OUT: Error code */
  128986. ){
  128987. if( pExpr && SQLITE_OK==*pRc ){
  128988. if( pExpr->eType==FTSQUERY_PHRASE ){
  128989. int nToken = pExpr->pPhrase->nToken;
  128990. if( nToken ){
  128991. int i;
  128992. for(i=0; i<nToken; i++){
  128993. if( pExpr->pPhrase->aToken[i].pDeferred==0 ) break;
  128994. }
  128995. pExpr->bDeferred = (i==nToken);
  128996. }
  128997. *pRc = fts3EvalPhraseStart(pCsr, 1, pExpr->pPhrase);
  128998. }else{
  128999. fts3EvalStartReaders(pCsr, pExpr->pLeft, pRc);
  129000. fts3EvalStartReaders(pCsr, pExpr->pRight, pRc);
  129001. pExpr->bDeferred = (pExpr->pLeft->bDeferred && pExpr->pRight->bDeferred);
  129002. }
  129003. }
  129004. }
  129005. /*
  129006. ** An array of the following structures is assembled as part of the process
  129007. ** of selecting tokens to defer before the query starts executing (as part
  129008. ** of the xFilter() method). There is one element in the array for each
  129009. ** token in the FTS expression.
  129010. **
  129011. ** Tokens are divided into AND/NEAR clusters. All tokens in a cluster belong
  129012. ** to phrases that are connected only by AND and NEAR operators (not OR or
  129013. ** NOT). When determining tokens to defer, each AND/NEAR cluster is considered
  129014. ** separately. The root of a tokens AND/NEAR cluster is stored in
  129015. ** Fts3TokenAndCost.pRoot.
  129016. */
  129017. typedef struct Fts3TokenAndCost Fts3TokenAndCost;
  129018. struct Fts3TokenAndCost {
  129019. Fts3Phrase *pPhrase; /* The phrase the token belongs to */
  129020. int iToken; /* Position of token in phrase */
  129021. Fts3PhraseToken *pToken; /* The token itself */
  129022. Fts3Expr *pRoot; /* Root of NEAR/AND cluster */
  129023. int nOvfl; /* Number of overflow pages to load doclist */
  129024. int iCol; /* The column the token must match */
  129025. };
  129026. /*
  129027. ** This function is used to populate an allocated Fts3TokenAndCost array.
  129028. **
  129029. ** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
  129030. ** Otherwise, if an error occurs during execution, *pRc is set to an
  129031. ** SQLite error code.
  129032. */
  129033. static void fts3EvalTokenCosts(
  129034. Fts3Cursor *pCsr, /* FTS Cursor handle */
  129035. Fts3Expr *pRoot, /* Root of current AND/NEAR cluster */
  129036. Fts3Expr *pExpr, /* Expression to consider */
  129037. Fts3TokenAndCost **ppTC, /* Write new entries to *(*ppTC)++ */
  129038. Fts3Expr ***ppOr, /* Write new OR root to *(*ppOr)++ */
  129039. int *pRc /* IN/OUT: Error code */
  129040. ){
  129041. if( *pRc==SQLITE_OK ){
  129042. if( pExpr->eType==FTSQUERY_PHRASE ){
  129043. Fts3Phrase *pPhrase = pExpr->pPhrase;
  129044. int i;
  129045. for(i=0; *pRc==SQLITE_OK && i<pPhrase->nToken; i++){
  129046. Fts3TokenAndCost *pTC = (*ppTC)++;
  129047. pTC->pPhrase = pPhrase;
  129048. pTC->iToken = i;
  129049. pTC->pRoot = pRoot;
  129050. pTC->pToken = &pPhrase->aToken[i];
  129051. pTC->iCol = pPhrase->iColumn;
  129052. *pRc = sqlite3Fts3MsrOvfl(pCsr, pTC->pToken->pSegcsr, &pTC->nOvfl);
  129053. }
  129054. }else if( pExpr->eType!=FTSQUERY_NOT ){
  129055. assert( pExpr->eType==FTSQUERY_OR
  129056. || pExpr->eType==FTSQUERY_AND
  129057. || pExpr->eType==FTSQUERY_NEAR
  129058. );
  129059. assert( pExpr->pLeft && pExpr->pRight );
  129060. if( pExpr->eType==FTSQUERY_OR ){
  129061. pRoot = pExpr->pLeft;
  129062. **ppOr = pRoot;
  129063. (*ppOr)++;
  129064. }
  129065. fts3EvalTokenCosts(pCsr, pRoot, pExpr->pLeft, ppTC, ppOr, pRc);
  129066. if( pExpr->eType==FTSQUERY_OR ){
  129067. pRoot = pExpr->pRight;
  129068. **ppOr = pRoot;
  129069. (*ppOr)++;
  129070. }
  129071. fts3EvalTokenCosts(pCsr, pRoot, pExpr->pRight, ppTC, ppOr, pRc);
  129072. }
  129073. }
  129074. }
  129075. /*
  129076. ** Determine the average document (row) size in pages. If successful,
  129077. ** write this value to *pnPage and return SQLITE_OK. Otherwise, return
  129078. ** an SQLite error code.
  129079. **
  129080. ** The average document size in pages is calculated by first calculating
  129081. ** determining the average size in bytes, B. If B is less than the amount
  129082. ** of data that will fit on a single leaf page of an intkey table in
  129083. ** this database, then the average docsize is 1. Otherwise, it is 1 plus
  129084. ** the number of overflow pages consumed by a record B bytes in size.
  129085. */
  129086. static int fts3EvalAverageDocsize(Fts3Cursor *pCsr, int *pnPage){
  129087. if( pCsr->nRowAvg==0 ){
  129088. /* The average document size, which is required to calculate the cost
  129089. ** of each doclist, has not yet been determined. Read the required
  129090. ** data from the %_stat table to calculate it.
  129091. **
  129092. ** Entry 0 of the %_stat table is a blob containing (nCol+1) FTS3
  129093. ** varints, where nCol is the number of columns in the FTS3 table.
  129094. ** The first varint is the number of documents currently stored in
  129095. ** the table. The following nCol varints contain the total amount of
  129096. ** data stored in all rows of each column of the table, from left
  129097. ** to right.
  129098. */
  129099. int rc;
  129100. Fts3Table *p = (Fts3Table*)pCsr->base.pVtab;
  129101. sqlite3_stmt *pStmt;
  129102. sqlite3_int64 nDoc = 0;
  129103. sqlite3_int64 nByte = 0;
  129104. const char *pEnd;
  129105. const char *a;
  129106. rc = sqlite3Fts3SelectDoctotal(p, &pStmt);
  129107. if( rc!=SQLITE_OK ) return rc;
  129108. a = sqlite3_column_blob(pStmt, 0);
  129109. assert( a );
  129110. pEnd = &a[sqlite3_column_bytes(pStmt, 0)];
  129111. a += sqlite3Fts3GetVarint(a, &nDoc);
  129112. while( a<pEnd ){
  129113. a += sqlite3Fts3GetVarint(a, &nByte);
  129114. }
  129115. if( nDoc==0 || nByte==0 ){
  129116. sqlite3_reset(pStmt);
  129117. return FTS_CORRUPT_VTAB;
  129118. }
  129119. pCsr->nDoc = nDoc;
  129120. pCsr->nRowAvg = (int)(((nByte / nDoc) + p->nPgsz) / p->nPgsz);
  129121. assert( pCsr->nRowAvg>0 );
  129122. rc = sqlite3_reset(pStmt);
  129123. if( rc!=SQLITE_OK ) return rc;
  129124. }
  129125. *pnPage = pCsr->nRowAvg;
  129126. return SQLITE_OK;
  129127. }
  129128. /*
  129129. ** This function is called to select the tokens (if any) that will be
  129130. ** deferred. The array aTC[] has already been populated when this is
  129131. ** called.
  129132. **
  129133. ** This function is called once for each AND/NEAR cluster in the
  129134. ** expression. Each invocation determines which tokens to defer within
  129135. ** the cluster with root node pRoot. See comments above the definition
  129136. ** of struct Fts3TokenAndCost for more details.
  129137. **
  129138. ** If no error occurs, SQLITE_OK is returned and sqlite3Fts3DeferToken()
  129139. ** called on each token to defer. Otherwise, an SQLite error code is
  129140. ** returned.
  129141. */
  129142. static int fts3EvalSelectDeferred(
  129143. Fts3Cursor *pCsr, /* FTS Cursor handle */
  129144. Fts3Expr *pRoot, /* Consider tokens with this root node */
  129145. Fts3TokenAndCost *aTC, /* Array of expression tokens and costs */
  129146. int nTC /* Number of entries in aTC[] */
  129147. ){
  129148. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  129149. int nDocSize = 0; /* Number of pages per doc loaded */
  129150. int rc = SQLITE_OK; /* Return code */
  129151. int ii; /* Iterator variable for various purposes */
  129152. int nOvfl = 0; /* Total overflow pages used by doclists */
  129153. int nToken = 0; /* Total number of tokens in cluster */
  129154. int nMinEst = 0; /* The minimum count for any phrase so far. */
  129155. int nLoad4 = 1; /* (Phrases that will be loaded)^4. */
  129156. /* Tokens are never deferred for FTS tables created using the content=xxx
  129157. ** option. The reason being that it is not guaranteed that the content
  129158. ** table actually contains the same data as the index. To prevent this from
  129159. ** causing any problems, the deferred token optimization is completely
  129160. ** disabled for content=xxx tables. */
  129161. if( pTab->zContentTbl ){
  129162. return SQLITE_OK;
  129163. }
  129164. /* Count the tokens in this AND/NEAR cluster. If none of the doclists
  129165. ** associated with the tokens spill onto overflow pages, or if there is
  129166. ** only 1 token, exit early. No tokens to defer in this case. */
  129167. for(ii=0; ii<nTC; ii++){
  129168. if( aTC[ii].pRoot==pRoot ){
  129169. nOvfl += aTC[ii].nOvfl;
  129170. nToken++;
  129171. }
  129172. }
  129173. if( nOvfl==0 || nToken<2 ) return SQLITE_OK;
  129174. /* Obtain the average docsize (in pages). */
  129175. rc = fts3EvalAverageDocsize(pCsr, &nDocSize);
  129176. assert( rc!=SQLITE_OK || nDocSize>0 );
  129177. /* Iterate through all tokens in this AND/NEAR cluster, in ascending order
  129178. ** of the number of overflow pages that will be loaded by the pager layer
  129179. ** to retrieve the entire doclist for the token from the full-text index.
  129180. ** Load the doclists for tokens that are either:
  129181. **
  129182. ** a. The cheapest token in the entire query (i.e. the one visited by the
  129183. ** first iteration of this loop), or
  129184. **
  129185. ** b. Part of a multi-token phrase.
  129186. **
  129187. ** After each token doclist is loaded, merge it with the others from the
  129188. ** same phrase and count the number of documents that the merged doclist
  129189. ** contains. Set variable "nMinEst" to the smallest number of documents in
  129190. ** any phrase doclist for which 1 or more token doclists have been loaded.
  129191. ** Let nOther be the number of other phrases for which it is certain that
  129192. ** one or more tokens will not be deferred.
  129193. **
  129194. ** Then, for each token, defer it if loading the doclist would result in
  129195. ** loading N or more overflow pages into memory, where N is computed as:
  129196. **
  129197. ** (nMinEst + 4^nOther - 1) / (4^nOther)
  129198. */
  129199. for(ii=0; ii<nToken && rc==SQLITE_OK; ii++){
  129200. int iTC; /* Used to iterate through aTC[] array. */
  129201. Fts3TokenAndCost *pTC = 0; /* Set to cheapest remaining token. */
  129202. /* Set pTC to point to the cheapest remaining token. */
  129203. for(iTC=0; iTC<nTC; iTC++){
  129204. if( aTC[iTC].pToken && aTC[iTC].pRoot==pRoot
  129205. && (!pTC || aTC[iTC].nOvfl<pTC->nOvfl)
  129206. ){
  129207. pTC = &aTC[iTC];
  129208. }
  129209. }
  129210. assert( pTC );
  129211. if( ii && pTC->nOvfl>=((nMinEst+(nLoad4/4)-1)/(nLoad4/4))*nDocSize ){
  129212. /* The number of overflow pages to load for this (and therefore all
  129213. ** subsequent) tokens is greater than the estimated number of pages
  129214. ** that will be loaded if all subsequent tokens are deferred.
  129215. */
  129216. Fts3PhraseToken *pToken = pTC->pToken;
  129217. rc = sqlite3Fts3DeferToken(pCsr, pToken, pTC->iCol);
  129218. fts3SegReaderCursorFree(pToken->pSegcsr);
  129219. pToken->pSegcsr = 0;
  129220. }else{
  129221. /* Set nLoad4 to the value of (4^nOther) for the next iteration of the
  129222. ** for-loop. Except, limit the value to 2^24 to prevent it from
  129223. ** overflowing the 32-bit integer it is stored in. */
  129224. if( ii<12 ) nLoad4 = nLoad4*4;
  129225. if( ii==0 || (pTC->pPhrase->nToken>1 && ii!=nToken-1) ){
  129226. /* Either this is the cheapest token in the entire query, or it is
  129227. ** part of a multi-token phrase. Either way, the entire doclist will
  129228. ** (eventually) be loaded into memory. It may as well be now. */
  129229. Fts3PhraseToken *pToken = pTC->pToken;
  129230. int nList = 0;
  129231. char *pList = 0;
  129232. rc = fts3TermSelect(pTab, pToken, pTC->iCol, &nList, &pList);
  129233. assert( rc==SQLITE_OK || pList==0 );
  129234. if( rc==SQLITE_OK ){
  129235. rc = fts3EvalPhraseMergeToken(
  129236. pTab, pTC->pPhrase, pTC->iToken,pList,nList
  129237. );
  129238. }
  129239. if( rc==SQLITE_OK ){
  129240. int nCount;
  129241. nCount = fts3DoclistCountDocids(
  129242. pTC->pPhrase->doclist.aAll, pTC->pPhrase->doclist.nAll
  129243. );
  129244. if( ii==0 || nCount<nMinEst ) nMinEst = nCount;
  129245. }
  129246. }
  129247. }
  129248. pTC->pToken = 0;
  129249. }
  129250. return rc;
  129251. }
  129252. /*
  129253. ** This function is called from within the xFilter method. It initializes
  129254. ** the full-text query currently stored in pCsr->pExpr. To iterate through
  129255. ** the results of a query, the caller does:
  129256. **
  129257. ** fts3EvalStart(pCsr);
  129258. ** while( 1 ){
  129259. ** fts3EvalNext(pCsr);
  129260. ** if( pCsr->bEof ) break;
  129261. ** ... return row pCsr->iPrevId to the caller ...
  129262. ** }
  129263. */
  129264. static int fts3EvalStart(Fts3Cursor *pCsr){
  129265. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  129266. int rc = SQLITE_OK;
  129267. int nToken = 0;
  129268. int nOr = 0;
  129269. /* Allocate a MultiSegReader for each token in the expression. */
  129270. fts3EvalAllocateReaders(pCsr, pCsr->pExpr, &nToken, &nOr, &rc);
  129271. /* Determine which, if any, tokens in the expression should be deferred. */
  129272. #ifndef SQLITE_DISABLE_FTS4_DEFERRED
  129273. if( rc==SQLITE_OK && nToken>1 && pTab->bFts4 ){
  129274. Fts3TokenAndCost *aTC;
  129275. Fts3Expr **apOr;
  129276. aTC = (Fts3TokenAndCost *)sqlite3_malloc(
  129277. sizeof(Fts3TokenAndCost) * nToken
  129278. + sizeof(Fts3Expr *) * nOr * 2
  129279. );
  129280. apOr = (Fts3Expr **)&aTC[nToken];
  129281. if( !aTC ){
  129282. rc = SQLITE_NOMEM;
  129283. }else{
  129284. int ii;
  129285. Fts3TokenAndCost *pTC = aTC;
  129286. Fts3Expr **ppOr = apOr;
  129287. fts3EvalTokenCosts(pCsr, 0, pCsr->pExpr, &pTC, &ppOr, &rc);
  129288. nToken = (int)(pTC-aTC);
  129289. nOr = (int)(ppOr-apOr);
  129290. if( rc==SQLITE_OK ){
  129291. rc = fts3EvalSelectDeferred(pCsr, 0, aTC, nToken);
  129292. for(ii=0; rc==SQLITE_OK && ii<nOr; ii++){
  129293. rc = fts3EvalSelectDeferred(pCsr, apOr[ii], aTC, nToken);
  129294. }
  129295. }
  129296. sqlite3_free(aTC);
  129297. }
  129298. }
  129299. #endif
  129300. fts3EvalStartReaders(pCsr, pCsr->pExpr, &rc);
  129301. return rc;
  129302. }
  129303. /*
  129304. ** Invalidate the current position list for phrase pPhrase.
  129305. */
  129306. static void fts3EvalInvalidatePoslist(Fts3Phrase *pPhrase){
  129307. if( pPhrase->doclist.bFreeList ){
  129308. sqlite3_free(pPhrase->doclist.pList);
  129309. }
  129310. pPhrase->doclist.pList = 0;
  129311. pPhrase->doclist.nList = 0;
  129312. pPhrase->doclist.bFreeList = 0;
  129313. }
  129314. /*
  129315. ** This function is called to edit the position list associated with
  129316. ** the phrase object passed as the fifth argument according to a NEAR
  129317. ** condition. For example:
  129318. **
  129319. ** abc NEAR/5 "def ghi"
  129320. **
  129321. ** Parameter nNear is passed the NEAR distance of the expression (5 in
  129322. ** the example above). When this function is called, *paPoslist points to
  129323. ** the position list, and *pnToken is the number of phrase tokens in, the
  129324. ** phrase on the other side of the NEAR operator to pPhrase. For example,
  129325. ** if pPhrase refers to the "def ghi" phrase, then *paPoslist points to
  129326. ** the position list associated with phrase "abc".
  129327. **
  129328. ** All positions in the pPhrase position list that are not sufficiently
  129329. ** close to a position in the *paPoslist position list are removed. If this
  129330. ** leaves 0 positions, zero is returned. Otherwise, non-zero.
  129331. **
  129332. ** Before returning, *paPoslist is set to point to the position lsit
  129333. ** associated with pPhrase. And *pnToken is set to the number of tokens in
  129334. ** pPhrase.
  129335. */
  129336. static int fts3EvalNearTrim(
  129337. int nNear, /* NEAR distance. As in "NEAR/nNear". */
  129338. char *aTmp, /* Temporary space to use */
  129339. char **paPoslist, /* IN/OUT: Position list */
  129340. int *pnToken, /* IN/OUT: Tokens in phrase of *paPoslist */
  129341. Fts3Phrase *pPhrase /* The phrase object to trim the doclist of */
  129342. ){
  129343. int nParam1 = nNear + pPhrase->nToken;
  129344. int nParam2 = nNear + *pnToken;
  129345. int nNew;
  129346. char *p2;
  129347. char *pOut;
  129348. int res;
  129349. assert( pPhrase->doclist.pList );
  129350. p2 = pOut = pPhrase->doclist.pList;
  129351. res = fts3PoslistNearMerge(
  129352. &pOut, aTmp, nParam1, nParam2, paPoslist, &p2
  129353. );
  129354. if( res ){
  129355. nNew = (int)(pOut - pPhrase->doclist.pList) - 1;
  129356. assert( pPhrase->doclist.pList[nNew]=='\0' );
  129357. assert( nNew<=pPhrase->doclist.nList && nNew>0 );
  129358. memset(&pPhrase->doclist.pList[nNew], 0, pPhrase->doclist.nList - nNew);
  129359. pPhrase->doclist.nList = nNew;
  129360. *paPoslist = pPhrase->doclist.pList;
  129361. *pnToken = pPhrase->nToken;
  129362. }
  129363. return res;
  129364. }
  129365. /*
  129366. ** This function is a no-op if *pRc is other than SQLITE_OK when it is called.
  129367. ** Otherwise, it advances the expression passed as the second argument to
  129368. ** point to the next matching row in the database. Expressions iterate through
  129369. ** matching rows in docid order. Ascending order if Fts3Cursor.bDesc is zero,
  129370. ** or descending if it is non-zero.
  129371. **
  129372. ** If an error occurs, *pRc is set to an SQLite error code. Otherwise, if
  129373. ** successful, the following variables in pExpr are set:
  129374. **
  129375. ** Fts3Expr.bEof (non-zero if EOF - there is no next row)
  129376. ** Fts3Expr.iDocid (valid if bEof==0. The docid of the next row)
  129377. **
  129378. ** If the expression is of type FTSQUERY_PHRASE, and the expression is not
  129379. ** at EOF, then the following variables are populated with the position list
  129380. ** for the phrase for the visited row:
  129381. **
  129382. ** FTs3Expr.pPhrase->doclist.nList (length of pList in bytes)
  129383. ** FTs3Expr.pPhrase->doclist.pList (pointer to position list)
  129384. **
  129385. ** It says above that this function advances the expression to the next
  129386. ** matching row. This is usually true, but there are the following exceptions:
  129387. **
  129388. ** 1. Deferred tokens are not taken into account. If a phrase consists
  129389. ** entirely of deferred tokens, it is assumed to match every row in
  129390. ** the db. In this case the position-list is not populated at all.
  129391. **
  129392. ** Or, if a phrase contains one or more deferred tokens and one or
  129393. ** more non-deferred tokens, then the expression is advanced to the
  129394. ** next possible match, considering only non-deferred tokens. In other
  129395. ** words, if the phrase is "A B C", and "B" is deferred, the expression
  129396. ** is advanced to the next row that contains an instance of "A * C",
  129397. ** where "*" may match any single token. The position list in this case
  129398. ** is populated as for "A * C" before returning.
  129399. **
  129400. ** 2. NEAR is treated as AND. If the expression is "x NEAR y", it is
  129401. ** advanced to point to the next row that matches "x AND y".
  129402. **
  129403. ** See fts3EvalTestDeferredAndNear() for details on testing if a row is
  129404. ** really a match, taking into account deferred tokens and NEAR operators.
  129405. */
  129406. static void fts3EvalNextRow(
  129407. Fts3Cursor *pCsr, /* FTS Cursor handle */
  129408. Fts3Expr *pExpr, /* Expr. to advance to next matching row */
  129409. int *pRc /* IN/OUT: Error code */
  129410. ){
  129411. if( *pRc==SQLITE_OK ){
  129412. int bDescDoclist = pCsr->bDesc; /* Used by DOCID_CMP() macro */
  129413. assert( pExpr->bEof==0 );
  129414. pExpr->bStart = 1;
  129415. switch( pExpr->eType ){
  129416. case FTSQUERY_NEAR:
  129417. case FTSQUERY_AND: {
  129418. Fts3Expr *pLeft = pExpr->pLeft;
  129419. Fts3Expr *pRight = pExpr->pRight;
  129420. assert( !pLeft->bDeferred || !pRight->bDeferred );
  129421. if( pLeft->bDeferred ){
  129422. /* LHS is entirely deferred. So we assume it matches every row.
  129423. ** Advance the RHS iterator to find the next row visited. */
  129424. fts3EvalNextRow(pCsr, pRight, pRc);
  129425. pExpr->iDocid = pRight->iDocid;
  129426. pExpr->bEof = pRight->bEof;
  129427. }else if( pRight->bDeferred ){
  129428. /* RHS is entirely deferred. So we assume it matches every row.
  129429. ** Advance the LHS iterator to find the next row visited. */
  129430. fts3EvalNextRow(pCsr, pLeft, pRc);
  129431. pExpr->iDocid = pLeft->iDocid;
  129432. pExpr->bEof = pLeft->bEof;
  129433. }else{
  129434. /* Neither the RHS or LHS are deferred. */
  129435. fts3EvalNextRow(pCsr, pLeft, pRc);
  129436. fts3EvalNextRow(pCsr, pRight, pRc);
  129437. while( !pLeft->bEof && !pRight->bEof && *pRc==SQLITE_OK ){
  129438. sqlite3_int64 iDiff = DOCID_CMP(pLeft->iDocid, pRight->iDocid);
  129439. if( iDiff==0 ) break;
  129440. if( iDiff<0 ){
  129441. fts3EvalNextRow(pCsr, pLeft, pRc);
  129442. }else{
  129443. fts3EvalNextRow(pCsr, pRight, pRc);
  129444. }
  129445. }
  129446. pExpr->iDocid = pLeft->iDocid;
  129447. pExpr->bEof = (pLeft->bEof || pRight->bEof);
  129448. if( pExpr->eType==FTSQUERY_NEAR && pExpr->bEof ){
  129449. if( pRight->pPhrase && pRight->pPhrase->doclist.aAll ){
  129450. Fts3Doclist *pDl = &pRight->pPhrase->doclist;
  129451. while( *pRc==SQLITE_OK && pRight->bEof==0 ){
  129452. memset(pDl->pList, 0, pDl->nList);
  129453. fts3EvalNextRow(pCsr, pRight, pRc);
  129454. }
  129455. }
  129456. if( pLeft->pPhrase && pLeft->pPhrase->doclist.aAll ){
  129457. Fts3Doclist *pDl = &pLeft->pPhrase->doclist;
  129458. while( *pRc==SQLITE_OK && pLeft->bEof==0 ){
  129459. memset(pDl->pList, 0, pDl->nList);
  129460. fts3EvalNextRow(pCsr, pLeft, pRc);
  129461. }
  129462. }
  129463. }
  129464. }
  129465. break;
  129466. }
  129467. case FTSQUERY_OR: {
  129468. Fts3Expr *pLeft = pExpr->pLeft;
  129469. Fts3Expr *pRight = pExpr->pRight;
  129470. sqlite3_int64 iCmp = DOCID_CMP(pLeft->iDocid, pRight->iDocid);
  129471. assert( pLeft->bStart || pLeft->iDocid==pRight->iDocid );
  129472. assert( pRight->bStart || pLeft->iDocid==pRight->iDocid );
  129473. if( pRight->bEof || (pLeft->bEof==0 && iCmp<0) ){
  129474. fts3EvalNextRow(pCsr, pLeft, pRc);
  129475. }else if( pLeft->bEof || (pRight->bEof==0 && iCmp>0) ){
  129476. fts3EvalNextRow(pCsr, pRight, pRc);
  129477. }else{
  129478. fts3EvalNextRow(pCsr, pLeft, pRc);
  129479. fts3EvalNextRow(pCsr, pRight, pRc);
  129480. }
  129481. pExpr->bEof = (pLeft->bEof && pRight->bEof);
  129482. iCmp = DOCID_CMP(pLeft->iDocid, pRight->iDocid);
  129483. if( pRight->bEof || (pLeft->bEof==0 && iCmp<0) ){
  129484. pExpr->iDocid = pLeft->iDocid;
  129485. }else{
  129486. pExpr->iDocid = pRight->iDocid;
  129487. }
  129488. break;
  129489. }
  129490. case FTSQUERY_NOT: {
  129491. Fts3Expr *pLeft = pExpr->pLeft;
  129492. Fts3Expr *pRight = pExpr->pRight;
  129493. if( pRight->bStart==0 ){
  129494. fts3EvalNextRow(pCsr, pRight, pRc);
  129495. assert( *pRc!=SQLITE_OK || pRight->bStart );
  129496. }
  129497. fts3EvalNextRow(pCsr, pLeft, pRc);
  129498. if( pLeft->bEof==0 ){
  129499. while( !*pRc
  129500. && !pRight->bEof
  129501. && DOCID_CMP(pLeft->iDocid, pRight->iDocid)>0
  129502. ){
  129503. fts3EvalNextRow(pCsr, pRight, pRc);
  129504. }
  129505. }
  129506. pExpr->iDocid = pLeft->iDocid;
  129507. pExpr->bEof = pLeft->bEof;
  129508. break;
  129509. }
  129510. default: {
  129511. Fts3Phrase *pPhrase = pExpr->pPhrase;
  129512. fts3EvalInvalidatePoslist(pPhrase);
  129513. *pRc = fts3EvalPhraseNext(pCsr, pPhrase, &pExpr->bEof);
  129514. pExpr->iDocid = pPhrase->doclist.iDocid;
  129515. break;
  129516. }
  129517. }
  129518. }
  129519. }
  129520. /*
  129521. ** If *pRc is not SQLITE_OK, or if pExpr is not the root node of a NEAR
  129522. ** cluster, then this function returns 1 immediately.
  129523. **
  129524. ** Otherwise, it checks if the current row really does match the NEAR
  129525. ** expression, using the data currently stored in the position lists
  129526. ** (Fts3Expr->pPhrase.doclist.pList/nList) for each phrase in the expression.
  129527. **
  129528. ** If the current row is a match, the position list associated with each
  129529. ** phrase in the NEAR expression is edited in place to contain only those
  129530. ** phrase instances sufficiently close to their peers to satisfy all NEAR
  129531. ** constraints. In this case it returns 1. If the NEAR expression does not
  129532. ** match the current row, 0 is returned. The position lists may or may not
  129533. ** be edited if 0 is returned.
  129534. */
  129535. static int fts3EvalNearTest(Fts3Expr *pExpr, int *pRc){
  129536. int res = 1;
  129537. /* The following block runs if pExpr is the root of a NEAR query.
  129538. ** For example, the query:
  129539. **
  129540. ** "w" NEAR "x" NEAR "y" NEAR "z"
  129541. **
  129542. ** which is represented in tree form as:
  129543. **
  129544. ** |
  129545. ** +--NEAR--+ <-- root of NEAR query
  129546. ** | |
  129547. ** +--NEAR--+ "z"
  129548. ** | |
  129549. ** +--NEAR--+ "y"
  129550. ** | |
  129551. ** "w" "x"
  129552. **
  129553. ** The right-hand child of a NEAR node is always a phrase. The
  129554. ** left-hand child may be either a phrase or a NEAR node. There are
  129555. ** no exceptions to this - it's the way the parser in fts3_expr.c works.
  129556. */
  129557. if( *pRc==SQLITE_OK
  129558. && pExpr->eType==FTSQUERY_NEAR
  129559. && pExpr->bEof==0
  129560. && (pExpr->pParent==0 || pExpr->pParent->eType!=FTSQUERY_NEAR)
  129561. ){
  129562. Fts3Expr *p;
  129563. int nTmp = 0; /* Bytes of temp space */
  129564. char *aTmp; /* Temp space for PoslistNearMerge() */
  129565. /* Allocate temporary working space. */
  129566. for(p=pExpr; p->pLeft; p=p->pLeft){
  129567. nTmp += p->pRight->pPhrase->doclist.nList;
  129568. }
  129569. nTmp += p->pPhrase->doclist.nList;
  129570. if( nTmp==0 ){
  129571. res = 0;
  129572. }else{
  129573. aTmp = sqlite3_malloc(nTmp*2);
  129574. if( !aTmp ){
  129575. *pRc = SQLITE_NOMEM;
  129576. res = 0;
  129577. }else{
  129578. char *aPoslist = p->pPhrase->doclist.pList;
  129579. int nToken = p->pPhrase->nToken;
  129580. for(p=p->pParent;res && p && p->eType==FTSQUERY_NEAR; p=p->pParent){
  129581. Fts3Phrase *pPhrase = p->pRight->pPhrase;
  129582. int nNear = p->nNear;
  129583. res = fts3EvalNearTrim(nNear, aTmp, &aPoslist, &nToken, pPhrase);
  129584. }
  129585. aPoslist = pExpr->pRight->pPhrase->doclist.pList;
  129586. nToken = pExpr->pRight->pPhrase->nToken;
  129587. for(p=pExpr->pLeft; p && res; p=p->pLeft){
  129588. int nNear;
  129589. Fts3Phrase *pPhrase;
  129590. assert( p->pParent && p->pParent->pLeft==p );
  129591. nNear = p->pParent->nNear;
  129592. pPhrase = (
  129593. p->eType==FTSQUERY_NEAR ? p->pRight->pPhrase : p->pPhrase
  129594. );
  129595. res = fts3EvalNearTrim(nNear, aTmp, &aPoslist, &nToken, pPhrase);
  129596. }
  129597. }
  129598. sqlite3_free(aTmp);
  129599. }
  129600. }
  129601. return res;
  129602. }
  129603. /*
  129604. ** This function is a helper function for fts3EvalTestDeferredAndNear().
  129605. ** Assuming no error occurs or has occurred, It returns non-zero if the
  129606. ** expression passed as the second argument matches the row that pCsr
  129607. ** currently points to, or zero if it does not.
  129608. **
  129609. ** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
  129610. ** If an error occurs during execution of this function, *pRc is set to
  129611. ** the appropriate SQLite error code. In this case the returned value is
  129612. ** undefined.
  129613. */
  129614. static int fts3EvalTestExpr(
  129615. Fts3Cursor *pCsr, /* FTS cursor handle */
  129616. Fts3Expr *pExpr, /* Expr to test. May or may not be root. */
  129617. int *pRc /* IN/OUT: Error code */
  129618. ){
  129619. int bHit = 1; /* Return value */
  129620. if( *pRc==SQLITE_OK ){
  129621. switch( pExpr->eType ){
  129622. case FTSQUERY_NEAR:
  129623. case FTSQUERY_AND:
  129624. bHit = (
  129625. fts3EvalTestExpr(pCsr, pExpr->pLeft, pRc)
  129626. && fts3EvalTestExpr(pCsr, pExpr->pRight, pRc)
  129627. && fts3EvalNearTest(pExpr, pRc)
  129628. );
  129629. /* If the NEAR expression does not match any rows, zero the doclist for
  129630. ** all phrases involved in the NEAR. This is because the snippet(),
  129631. ** offsets() and matchinfo() functions are not supposed to recognize
  129632. ** any instances of phrases that are part of unmatched NEAR queries.
  129633. ** For example if this expression:
  129634. **
  129635. ** ... MATCH 'a OR (b NEAR c)'
  129636. **
  129637. ** is matched against a row containing:
  129638. **
  129639. ** 'a b d e'
  129640. **
  129641. ** then any snippet() should ony highlight the "a" term, not the "b"
  129642. ** (as "b" is part of a non-matching NEAR clause).
  129643. */
  129644. if( bHit==0
  129645. && pExpr->eType==FTSQUERY_NEAR
  129646. && (pExpr->pParent==0 || pExpr->pParent->eType!=FTSQUERY_NEAR)
  129647. ){
  129648. Fts3Expr *p;
  129649. for(p=pExpr; p->pPhrase==0; p=p->pLeft){
  129650. if( p->pRight->iDocid==pCsr->iPrevId ){
  129651. fts3EvalInvalidatePoslist(p->pRight->pPhrase);
  129652. }
  129653. }
  129654. if( p->iDocid==pCsr->iPrevId ){
  129655. fts3EvalInvalidatePoslist(p->pPhrase);
  129656. }
  129657. }
  129658. break;
  129659. case FTSQUERY_OR: {
  129660. int bHit1 = fts3EvalTestExpr(pCsr, pExpr->pLeft, pRc);
  129661. int bHit2 = fts3EvalTestExpr(pCsr, pExpr->pRight, pRc);
  129662. bHit = bHit1 || bHit2;
  129663. break;
  129664. }
  129665. case FTSQUERY_NOT:
  129666. bHit = (
  129667. fts3EvalTestExpr(pCsr, pExpr->pLeft, pRc)
  129668. && !fts3EvalTestExpr(pCsr, pExpr->pRight, pRc)
  129669. );
  129670. break;
  129671. default: {
  129672. #ifndef SQLITE_DISABLE_FTS4_DEFERRED
  129673. if( pCsr->pDeferred
  129674. && (pExpr->iDocid==pCsr->iPrevId || pExpr->bDeferred)
  129675. ){
  129676. Fts3Phrase *pPhrase = pExpr->pPhrase;
  129677. assert( pExpr->bDeferred || pPhrase->doclist.bFreeList==0 );
  129678. if( pExpr->bDeferred ){
  129679. fts3EvalInvalidatePoslist(pPhrase);
  129680. }
  129681. *pRc = fts3EvalDeferredPhrase(pCsr, pPhrase);
  129682. bHit = (pPhrase->doclist.pList!=0);
  129683. pExpr->iDocid = pCsr->iPrevId;
  129684. }else
  129685. #endif
  129686. {
  129687. bHit = (pExpr->bEof==0 && pExpr->iDocid==pCsr->iPrevId);
  129688. }
  129689. break;
  129690. }
  129691. }
  129692. }
  129693. return bHit;
  129694. }
  129695. /*
  129696. ** This function is called as the second part of each xNext operation when
  129697. ** iterating through the results of a full-text query. At this point the
  129698. ** cursor points to a row that matches the query expression, with the
  129699. ** following caveats:
  129700. **
  129701. ** * Up until this point, "NEAR" operators in the expression have been
  129702. ** treated as "AND".
  129703. **
  129704. ** * Deferred tokens have not yet been considered.
  129705. **
  129706. ** If *pRc is not SQLITE_OK when this function is called, it immediately
  129707. ** returns 0. Otherwise, it tests whether or not after considering NEAR
  129708. ** operators and deferred tokens the current row is still a match for the
  129709. ** expression. It returns 1 if both of the following are true:
  129710. **
  129711. ** 1. *pRc is SQLITE_OK when this function returns, and
  129712. **
  129713. ** 2. After scanning the current FTS table row for the deferred tokens,
  129714. ** it is determined that the row does *not* match the query.
  129715. **
  129716. ** Or, if no error occurs and it seems the current row does match the FTS
  129717. ** query, return 0.
  129718. */
  129719. static int fts3EvalTestDeferredAndNear(Fts3Cursor *pCsr, int *pRc){
  129720. int rc = *pRc;
  129721. int bMiss = 0;
  129722. if( rc==SQLITE_OK ){
  129723. /* If there are one or more deferred tokens, load the current row into
  129724. ** memory and scan it to determine the position list for each deferred
  129725. ** token. Then, see if this row is really a match, considering deferred
  129726. ** tokens and NEAR operators (neither of which were taken into account
  129727. ** earlier, by fts3EvalNextRow()).
  129728. */
  129729. if( pCsr->pDeferred ){
  129730. rc = fts3CursorSeek(0, pCsr);
  129731. if( rc==SQLITE_OK ){
  129732. rc = sqlite3Fts3CacheDeferredDoclists(pCsr);
  129733. }
  129734. }
  129735. bMiss = (0==fts3EvalTestExpr(pCsr, pCsr->pExpr, &rc));
  129736. /* Free the position-lists accumulated for each deferred token above. */
  129737. sqlite3Fts3FreeDeferredDoclists(pCsr);
  129738. *pRc = rc;
  129739. }
  129740. return (rc==SQLITE_OK && bMiss);
  129741. }
  129742. /*
  129743. ** Advance to the next document that matches the FTS expression in
  129744. ** Fts3Cursor.pExpr.
  129745. */
  129746. static int fts3EvalNext(Fts3Cursor *pCsr){
  129747. int rc = SQLITE_OK; /* Return Code */
  129748. Fts3Expr *pExpr = pCsr->pExpr;
  129749. assert( pCsr->isEof==0 );
  129750. if( pExpr==0 ){
  129751. pCsr->isEof = 1;
  129752. }else{
  129753. do {
  129754. if( pCsr->isRequireSeek==0 ){
  129755. sqlite3_reset(pCsr->pStmt);
  129756. }
  129757. assert( sqlite3_data_count(pCsr->pStmt)==0 );
  129758. fts3EvalNextRow(pCsr, pExpr, &rc);
  129759. pCsr->isEof = pExpr->bEof;
  129760. pCsr->isRequireSeek = 1;
  129761. pCsr->isMatchinfoNeeded = 1;
  129762. pCsr->iPrevId = pExpr->iDocid;
  129763. }while( pCsr->isEof==0 && fts3EvalTestDeferredAndNear(pCsr, &rc) );
  129764. }
  129765. /* Check if the cursor is past the end of the docid range specified
  129766. ** by Fts3Cursor.iMinDocid/iMaxDocid. If so, set the EOF flag. */
  129767. if( rc==SQLITE_OK && (
  129768. (pCsr->bDesc==0 && pCsr->iPrevId>pCsr->iMaxDocid)
  129769. || (pCsr->bDesc!=0 && pCsr->iPrevId<pCsr->iMinDocid)
  129770. )){
  129771. pCsr->isEof = 1;
  129772. }
  129773. return rc;
  129774. }
  129775. /*
  129776. ** Restart interation for expression pExpr so that the next call to
  129777. ** fts3EvalNext() visits the first row. Do not allow incremental
  129778. ** loading or merging of phrase doclists for this iteration.
  129779. **
  129780. ** If *pRc is other than SQLITE_OK when this function is called, it is
  129781. ** a no-op. If an error occurs within this function, *pRc is set to an
  129782. ** SQLite error code before returning.
  129783. */
  129784. static void fts3EvalRestart(
  129785. Fts3Cursor *pCsr,
  129786. Fts3Expr *pExpr,
  129787. int *pRc
  129788. ){
  129789. if( pExpr && *pRc==SQLITE_OK ){
  129790. Fts3Phrase *pPhrase = pExpr->pPhrase;
  129791. if( pPhrase ){
  129792. fts3EvalInvalidatePoslist(pPhrase);
  129793. if( pPhrase->bIncr ){
  129794. int i;
  129795. for(i=0; i<pPhrase->nToken; i++){
  129796. Fts3PhraseToken *pToken = &pPhrase->aToken[i];
  129797. assert( pToken->pDeferred==0 );
  129798. if( pToken->pSegcsr ){
  129799. sqlite3Fts3MsrIncrRestart(pToken->pSegcsr);
  129800. }
  129801. }
  129802. *pRc = fts3EvalPhraseStart(pCsr, 0, pPhrase);
  129803. }
  129804. pPhrase->doclist.pNextDocid = 0;
  129805. pPhrase->doclist.iDocid = 0;
  129806. pPhrase->pOrPoslist = 0;
  129807. }
  129808. pExpr->iDocid = 0;
  129809. pExpr->bEof = 0;
  129810. pExpr->bStart = 0;
  129811. fts3EvalRestart(pCsr, pExpr->pLeft, pRc);
  129812. fts3EvalRestart(pCsr, pExpr->pRight, pRc);
  129813. }
  129814. }
  129815. /*
  129816. ** After allocating the Fts3Expr.aMI[] array for each phrase in the
  129817. ** expression rooted at pExpr, the cursor iterates through all rows matched
  129818. ** by pExpr, calling this function for each row. This function increments
  129819. ** the values in Fts3Expr.aMI[] according to the position-list currently
  129820. ** found in Fts3Expr.pPhrase->doclist.pList for each of the phrase
  129821. ** expression nodes.
  129822. */
  129823. static void fts3EvalUpdateCounts(Fts3Expr *pExpr){
  129824. if( pExpr ){
  129825. Fts3Phrase *pPhrase = pExpr->pPhrase;
  129826. if( pPhrase && pPhrase->doclist.pList ){
  129827. int iCol = 0;
  129828. char *p = pPhrase->doclist.pList;
  129829. assert( *p );
  129830. while( 1 ){
  129831. u8 c = 0;
  129832. int iCnt = 0;
  129833. while( 0xFE & (*p | c) ){
  129834. if( (c&0x80)==0 ) iCnt++;
  129835. c = *p++ & 0x80;
  129836. }
  129837. /* aMI[iCol*3 + 1] = Number of occurrences
  129838. ** aMI[iCol*3 + 2] = Number of rows containing at least one instance
  129839. */
  129840. pExpr->aMI[iCol*3 + 1] += iCnt;
  129841. pExpr->aMI[iCol*3 + 2] += (iCnt>0);
  129842. if( *p==0x00 ) break;
  129843. p++;
  129844. p += fts3GetVarint32(p, &iCol);
  129845. }
  129846. }
  129847. fts3EvalUpdateCounts(pExpr->pLeft);
  129848. fts3EvalUpdateCounts(pExpr->pRight);
  129849. }
  129850. }
  129851. /*
  129852. ** Expression pExpr must be of type FTSQUERY_PHRASE.
  129853. **
  129854. ** If it is not already allocated and populated, this function allocates and
  129855. ** populates the Fts3Expr.aMI[] array for expression pExpr. If pExpr is part
  129856. ** of a NEAR expression, then it also allocates and populates the same array
  129857. ** for all other phrases that are part of the NEAR expression.
  129858. **
  129859. ** SQLITE_OK is returned if the aMI[] array is successfully allocated and
  129860. ** populated. Otherwise, if an error occurs, an SQLite error code is returned.
  129861. */
  129862. static int fts3EvalGatherStats(
  129863. Fts3Cursor *pCsr, /* Cursor object */
  129864. Fts3Expr *pExpr /* FTSQUERY_PHRASE expression */
  129865. ){
  129866. int rc = SQLITE_OK; /* Return code */
  129867. assert( pExpr->eType==FTSQUERY_PHRASE );
  129868. if( pExpr->aMI==0 ){
  129869. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  129870. Fts3Expr *pRoot; /* Root of NEAR expression */
  129871. Fts3Expr *p; /* Iterator used for several purposes */
  129872. sqlite3_int64 iPrevId = pCsr->iPrevId;
  129873. sqlite3_int64 iDocid;
  129874. u8 bEof;
  129875. /* Find the root of the NEAR expression */
  129876. pRoot = pExpr;
  129877. while( pRoot->pParent && pRoot->pParent->eType==FTSQUERY_NEAR ){
  129878. pRoot = pRoot->pParent;
  129879. }
  129880. iDocid = pRoot->iDocid;
  129881. bEof = pRoot->bEof;
  129882. assert( pRoot->bStart );
  129883. /* Allocate space for the aMSI[] array of each FTSQUERY_PHRASE node */
  129884. for(p=pRoot; p; p=p->pLeft){
  129885. Fts3Expr *pE = (p->eType==FTSQUERY_PHRASE?p:p->pRight);
  129886. assert( pE->aMI==0 );
  129887. pE->aMI = (u32 *)sqlite3_malloc(pTab->nColumn * 3 * sizeof(u32));
  129888. if( !pE->aMI ) return SQLITE_NOMEM;
  129889. memset(pE->aMI, 0, pTab->nColumn * 3 * sizeof(u32));
  129890. }
  129891. fts3EvalRestart(pCsr, pRoot, &rc);
  129892. while( pCsr->isEof==0 && rc==SQLITE_OK ){
  129893. do {
  129894. /* Ensure the %_content statement is reset. */
  129895. if( pCsr->isRequireSeek==0 ) sqlite3_reset(pCsr->pStmt);
  129896. assert( sqlite3_data_count(pCsr->pStmt)==0 );
  129897. /* Advance to the next document */
  129898. fts3EvalNextRow(pCsr, pRoot, &rc);
  129899. pCsr->isEof = pRoot->bEof;
  129900. pCsr->isRequireSeek = 1;
  129901. pCsr->isMatchinfoNeeded = 1;
  129902. pCsr->iPrevId = pRoot->iDocid;
  129903. }while( pCsr->isEof==0
  129904. && pRoot->eType==FTSQUERY_NEAR
  129905. && fts3EvalTestDeferredAndNear(pCsr, &rc)
  129906. );
  129907. if( rc==SQLITE_OK && pCsr->isEof==0 ){
  129908. fts3EvalUpdateCounts(pRoot);
  129909. }
  129910. }
  129911. pCsr->isEof = 0;
  129912. pCsr->iPrevId = iPrevId;
  129913. if( bEof ){
  129914. pRoot->bEof = bEof;
  129915. }else{
  129916. /* Caution: pRoot may iterate through docids in ascending or descending
  129917. ** order. For this reason, even though it seems more defensive, the
  129918. ** do loop can not be written:
  129919. **
  129920. ** do {...} while( pRoot->iDocid<iDocid && rc==SQLITE_OK );
  129921. */
  129922. fts3EvalRestart(pCsr, pRoot, &rc);
  129923. do {
  129924. fts3EvalNextRow(pCsr, pRoot, &rc);
  129925. assert( pRoot->bEof==0 );
  129926. }while( pRoot->iDocid!=iDocid && rc==SQLITE_OK );
  129927. fts3EvalTestDeferredAndNear(pCsr, &rc);
  129928. }
  129929. }
  129930. return rc;
  129931. }
  129932. /*
  129933. ** This function is used by the matchinfo() module to query a phrase
  129934. ** expression node for the following information:
  129935. **
  129936. ** 1. The total number of occurrences of the phrase in each column of
  129937. ** the FTS table (considering all rows), and
  129938. **
  129939. ** 2. For each column, the number of rows in the table for which the
  129940. ** column contains at least one instance of the phrase.
  129941. **
  129942. ** If no error occurs, SQLITE_OK is returned and the values for each column
  129943. ** written into the array aiOut as follows:
  129944. **
  129945. ** aiOut[iCol*3 + 1] = Number of occurrences
  129946. ** aiOut[iCol*3 + 2] = Number of rows containing at least one instance
  129947. **
  129948. ** Caveats:
  129949. **
  129950. ** * If a phrase consists entirely of deferred tokens, then all output
  129951. ** values are set to the number of documents in the table. In other
  129952. ** words we assume that very common tokens occur exactly once in each
  129953. ** column of each row of the table.
  129954. **
  129955. ** * If a phrase contains some deferred tokens (and some non-deferred
  129956. ** tokens), count the potential occurrence identified by considering
  129957. ** the non-deferred tokens instead of actual phrase occurrences.
  129958. **
  129959. ** * If the phrase is part of a NEAR expression, then only phrase instances
  129960. ** that meet the NEAR constraint are included in the counts.
  129961. */
  129962. SQLITE_PRIVATE int sqlite3Fts3EvalPhraseStats(
  129963. Fts3Cursor *pCsr, /* FTS cursor handle */
  129964. Fts3Expr *pExpr, /* Phrase expression */
  129965. u32 *aiOut /* Array to write results into (see above) */
  129966. ){
  129967. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  129968. int rc = SQLITE_OK;
  129969. int iCol;
  129970. if( pExpr->bDeferred && pExpr->pParent->eType!=FTSQUERY_NEAR ){
  129971. assert( pCsr->nDoc>0 );
  129972. for(iCol=0; iCol<pTab->nColumn; iCol++){
  129973. aiOut[iCol*3 + 1] = (u32)pCsr->nDoc;
  129974. aiOut[iCol*3 + 2] = (u32)pCsr->nDoc;
  129975. }
  129976. }else{
  129977. rc = fts3EvalGatherStats(pCsr, pExpr);
  129978. if( rc==SQLITE_OK ){
  129979. assert( pExpr->aMI );
  129980. for(iCol=0; iCol<pTab->nColumn; iCol++){
  129981. aiOut[iCol*3 + 1] = pExpr->aMI[iCol*3 + 1];
  129982. aiOut[iCol*3 + 2] = pExpr->aMI[iCol*3 + 2];
  129983. }
  129984. }
  129985. }
  129986. return rc;
  129987. }
  129988. /*
  129989. ** The expression pExpr passed as the second argument to this function
  129990. ** must be of type FTSQUERY_PHRASE.
  129991. **
  129992. ** The returned value is either NULL or a pointer to a buffer containing
  129993. ** a position-list indicating the occurrences of the phrase in column iCol
  129994. ** of the current row.
  129995. **
  129996. ** More specifically, the returned buffer contains 1 varint for each
  129997. ** occurrence of the phrase in the column, stored using the normal (delta+2)
  129998. ** compression and is terminated by either an 0x01 or 0x00 byte. For example,
  129999. ** if the requested column contains "a b X c d X X" and the position-list
  130000. ** for 'X' is requested, the buffer returned may contain:
  130001. **
  130002. ** 0x04 0x05 0x03 0x01 or 0x04 0x05 0x03 0x00
  130003. **
  130004. ** This function works regardless of whether or not the phrase is deferred,
  130005. ** incremental, or neither.
  130006. */
  130007. SQLITE_PRIVATE int sqlite3Fts3EvalPhrasePoslist(
  130008. Fts3Cursor *pCsr, /* FTS3 cursor object */
  130009. Fts3Expr *pExpr, /* Phrase to return doclist for */
  130010. int iCol, /* Column to return position list for */
  130011. char **ppOut /* OUT: Pointer to position list */
  130012. ){
  130013. Fts3Phrase *pPhrase = pExpr->pPhrase;
  130014. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  130015. char *pIter;
  130016. int iThis;
  130017. sqlite3_int64 iDocid;
  130018. /* If this phrase is applies specifically to some column other than
  130019. ** column iCol, return a NULL pointer. */
  130020. *ppOut = 0;
  130021. assert( iCol>=0 && iCol<pTab->nColumn );
  130022. if( (pPhrase->iColumn<pTab->nColumn && pPhrase->iColumn!=iCol) ){
  130023. return SQLITE_OK;
  130024. }
  130025. iDocid = pExpr->iDocid;
  130026. pIter = pPhrase->doclist.pList;
  130027. if( iDocid!=pCsr->iPrevId || pExpr->bEof ){
  130028. int rc = SQLITE_OK;
  130029. int bDescDoclist = pTab->bDescIdx; /* For DOCID_CMP macro */
  130030. int bOr = 0;
  130031. u8 bEof = 0;
  130032. u8 bTreeEof = 0;
  130033. Fts3Expr *p; /* Used to iterate from pExpr to root */
  130034. Fts3Expr *pNear; /* Most senior NEAR ancestor (or pExpr) */
  130035. /* Check if this phrase descends from an OR expression node. If not,
  130036. ** return NULL. Otherwise, the entry that corresponds to docid
  130037. ** pCsr->iPrevId may lie earlier in the doclist buffer. Or, if the
  130038. ** tree that the node is part of has been marked as EOF, but the node
  130039. ** itself is not EOF, then it may point to an earlier entry. */
  130040. pNear = pExpr;
  130041. for(p=pExpr->pParent; p; p=p->pParent){
  130042. if( p->eType==FTSQUERY_OR ) bOr = 1;
  130043. if( p->eType==FTSQUERY_NEAR ) pNear = p;
  130044. if( p->bEof ) bTreeEof = 1;
  130045. }
  130046. if( bOr==0 ) return SQLITE_OK;
  130047. /* This is the descendent of an OR node. In this case we cannot use
  130048. ** an incremental phrase. Load the entire doclist for the phrase
  130049. ** into memory in this case. */
  130050. if( pPhrase->bIncr ){
  130051. int bEofSave = pNear->bEof;
  130052. fts3EvalRestart(pCsr, pNear, &rc);
  130053. while( rc==SQLITE_OK && !pNear->bEof ){
  130054. fts3EvalNextRow(pCsr, pNear, &rc);
  130055. if( bEofSave==0 && pNear->iDocid==iDocid ) break;
  130056. }
  130057. assert( rc!=SQLITE_OK || pPhrase->bIncr==0 );
  130058. }
  130059. if( bTreeEof ){
  130060. while( rc==SQLITE_OK && !pNear->bEof ){
  130061. fts3EvalNextRow(pCsr, pNear, &rc);
  130062. }
  130063. }
  130064. if( rc!=SQLITE_OK ) return rc;
  130065. pIter = pPhrase->pOrPoslist;
  130066. iDocid = pPhrase->iOrDocid;
  130067. if( pCsr->bDesc==bDescDoclist ){
  130068. bEof = !pPhrase->doclist.nAll ||
  130069. (pIter >= (pPhrase->doclist.aAll + pPhrase->doclist.nAll));
  130070. while( (pIter==0 || DOCID_CMP(iDocid, pCsr->iPrevId)<0 ) && bEof==0 ){
  130071. sqlite3Fts3DoclistNext(
  130072. bDescDoclist, pPhrase->doclist.aAll, pPhrase->doclist.nAll,
  130073. &pIter, &iDocid, &bEof
  130074. );
  130075. }
  130076. }else{
  130077. bEof = !pPhrase->doclist.nAll || (pIter && pIter<=pPhrase->doclist.aAll);
  130078. while( (pIter==0 || DOCID_CMP(iDocid, pCsr->iPrevId)>0 ) && bEof==0 ){
  130079. int dummy;
  130080. sqlite3Fts3DoclistPrev(
  130081. bDescDoclist, pPhrase->doclist.aAll, pPhrase->doclist.nAll,
  130082. &pIter, &iDocid, &dummy, &bEof
  130083. );
  130084. }
  130085. }
  130086. pPhrase->pOrPoslist = pIter;
  130087. pPhrase->iOrDocid = iDocid;
  130088. if( bEof || iDocid!=pCsr->iPrevId ) pIter = 0;
  130089. }
  130090. if( pIter==0 ) return SQLITE_OK;
  130091. if( *pIter==0x01 ){
  130092. pIter++;
  130093. pIter += fts3GetVarint32(pIter, &iThis);
  130094. }else{
  130095. iThis = 0;
  130096. }
  130097. while( iThis<iCol ){
  130098. fts3ColumnlistCopy(0, &pIter);
  130099. if( *pIter==0x00 ) return SQLITE_OK;
  130100. pIter++;
  130101. pIter += fts3GetVarint32(pIter, &iThis);
  130102. }
  130103. if( *pIter==0x00 ){
  130104. pIter = 0;
  130105. }
  130106. *ppOut = ((iCol==iThis)?pIter:0);
  130107. return SQLITE_OK;
  130108. }
  130109. /*
  130110. ** Free all components of the Fts3Phrase structure that were allocated by
  130111. ** the eval module. Specifically, this means to free:
  130112. **
  130113. ** * the contents of pPhrase->doclist, and
  130114. ** * any Fts3MultiSegReader objects held by phrase tokens.
  130115. */
  130116. SQLITE_PRIVATE void sqlite3Fts3EvalPhraseCleanup(Fts3Phrase *pPhrase){
  130117. if( pPhrase ){
  130118. int i;
  130119. sqlite3_free(pPhrase->doclist.aAll);
  130120. fts3EvalInvalidatePoslist(pPhrase);
  130121. memset(&pPhrase->doclist, 0, sizeof(Fts3Doclist));
  130122. for(i=0; i<pPhrase->nToken; i++){
  130123. fts3SegReaderCursorFree(pPhrase->aToken[i].pSegcsr);
  130124. pPhrase->aToken[i].pSegcsr = 0;
  130125. }
  130126. }
  130127. }
  130128. /*
  130129. ** Return SQLITE_CORRUPT_VTAB.
  130130. */
  130131. #ifdef SQLITE_DEBUG
  130132. SQLITE_PRIVATE int sqlite3Fts3Corrupt(){
  130133. return SQLITE_CORRUPT_VTAB;
  130134. }
  130135. #endif
  130136. #if !SQLITE_CORE
  130137. /*
  130138. ** Initialize API pointer table, if required.
  130139. */
  130140. #ifdef _WIN32
  130141. __declspec(dllexport)
  130142. #endif
  130143. SQLITE_API int SQLITE_STDCALL sqlite3_fts3_init(
  130144. sqlite3 *db,
  130145. char **pzErrMsg,
  130146. const sqlite3_api_routines *pApi
  130147. ){
  130148. SQLITE_EXTENSION_INIT2(pApi)
  130149. return sqlite3Fts3Init(db);
  130150. }
  130151. #endif
  130152. #endif
  130153. /************** End of fts3.c ************************************************/
  130154. /************** Begin file fts3_aux.c ****************************************/
  130155. /*
  130156. ** 2011 Jan 27
  130157. **
  130158. ** The author disclaims copyright to this source code. In place of
  130159. ** a legal notice, here is a blessing:
  130160. **
  130161. ** May you do good and not evil.
  130162. ** May you find forgiveness for yourself and forgive others.
  130163. ** May you share freely, never taking more than you give.
  130164. **
  130165. ******************************************************************************
  130166. **
  130167. */
  130168. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  130169. /* #include <string.h> */
  130170. /* #include <assert.h> */
  130171. typedef struct Fts3auxTable Fts3auxTable;
  130172. typedef struct Fts3auxCursor Fts3auxCursor;
  130173. struct Fts3auxTable {
  130174. sqlite3_vtab base; /* Base class used by SQLite core */
  130175. Fts3Table *pFts3Tab;
  130176. };
  130177. struct Fts3auxCursor {
  130178. sqlite3_vtab_cursor base; /* Base class used by SQLite core */
  130179. Fts3MultiSegReader csr; /* Must be right after "base" */
  130180. Fts3SegFilter filter;
  130181. char *zStop;
  130182. int nStop; /* Byte-length of string zStop */
  130183. int iLangid; /* Language id to query */
  130184. int isEof; /* True if cursor is at EOF */
  130185. sqlite3_int64 iRowid; /* Current rowid */
  130186. int iCol; /* Current value of 'col' column */
  130187. int nStat; /* Size of aStat[] array */
  130188. struct Fts3auxColstats {
  130189. sqlite3_int64 nDoc; /* 'documents' values for current csr row */
  130190. sqlite3_int64 nOcc; /* 'occurrences' values for current csr row */
  130191. } *aStat;
  130192. };
  130193. /*
  130194. ** Schema of the terms table.
  130195. */
  130196. #define FTS3_AUX_SCHEMA \
  130197. "CREATE TABLE x(term, col, documents, occurrences, languageid HIDDEN)"
  130198. /*
  130199. ** This function does all the work for both the xConnect and xCreate methods.
  130200. ** These tables have no persistent representation of their own, so xConnect
  130201. ** and xCreate are identical operations.
  130202. */
  130203. static int fts3auxConnectMethod(
  130204. sqlite3 *db, /* Database connection */
  130205. void *pUnused, /* Unused */
  130206. int argc, /* Number of elements in argv array */
  130207. const char * const *argv, /* xCreate/xConnect argument array */
  130208. sqlite3_vtab **ppVtab, /* OUT: New sqlite3_vtab object */
  130209. char **pzErr /* OUT: sqlite3_malloc'd error message */
  130210. ){
  130211. char const *zDb; /* Name of database (e.g. "main") */
  130212. char const *zFts3; /* Name of fts3 table */
  130213. int nDb; /* Result of strlen(zDb) */
  130214. int nFts3; /* Result of strlen(zFts3) */
  130215. int nByte; /* Bytes of space to allocate here */
  130216. int rc; /* value returned by declare_vtab() */
  130217. Fts3auxTable *p; /* Virtual table object to return */
  130218. UNUSED_PARAMETER(pUnused);
  130219. /* The user should invoke this in one of two forms:
  130220. **
  130221. ** CREATE VIRTUAL TABLE xxx USING fts4aux(fts4-table);
  130222. ** CREATE VIRTUAL TABLE xxx USING fts4aux(fts4-table-db, fts4-table);
  130223. */
  130224. if( argc!=4 && argc!=5 ) goto bad_args;
  130225. zDb = argv[1];
  130226. nDb = (int)strlen(zDb);
  130227. if( argc==5 ){
  130228. if( nDb==4 && 0==sqlite3_strnicmp("temp", zDb, 4) ){
  130229. zDb = argv[3];
  130230. nDb = (int)strlen(zDb);
  130231. zFts3 = argv[4];
  130232. }else{
  130233. goto bad_args;
  130234. }
  130235. }else{
  130236. zFts3 = argv[3];
  130237. }
  130238. nFts3 = (int)strlen(zFts3);
  130239. rc = sqlite3_declare_vtab(db, FTS3_AUX_SCHEMA);
  130240. if( rc!=SQLITE_OK ) return rc;
  130241. nByte = sizeof(Fts3auxTable) + sizeof(Fts3Table) + nDb + nFts3 + 2;
  130242. p = (Fts3auxTable *)sqlite3_malloc(nByte);
  130243. if( !p ) return SQLITE_NOMEM;
  130244. memset(p, 0, nByte);
  130245. p->pFts3Tab = (Fts3Table *)&p[1];
  130246. p->pFts3Tab->zDb = (char *)&p->pFts3Tab[1];
  130247. p->pFts3Tab->zName = &p->pFts3Tab->zDb[nDb+1];
  130248. p->pFts3Tab->db = db;
  130249. p->pFts3Tab->nIndex = 1;
  130250. memcpy((char *)p->pFts3Tab->zDb, zDb, nDb);
  130251. memcpy((char *)p->pFts3Tab->zName, zFts3, nFts3);
  130252. sqlite3Fts3Dequote((char *)p->pFts3Tab->zName);
  130253. *ppVtab = (sqlite3_vtab *)p;
  130254. return SQLITE_OK;
  130255. bad_args:
  130256. sqlite3Fts3ErrMsg(pzErr, "invalid arguments to fts4aux constructor");
  130257. return SQLITE_ERROR;
  130258. }
  130259. /*
  130260. ** This function does the work for both the xDisconnect and xDestroy methods.
  130261. ** These tables have no persistent representation of their own, so xDisconnect
  130262. ** and xDestroy are identical operations.
  130263. */
  130264. static int fts3auxDisconnectMethod(sqlite3_vtab *pVtab){
  130265. Fts3auxTable *p = (Fts3auxTable *)pVtab;
  130266. Fts3Table *pFts3 = p->pFts3Tab;
  130267. int i;
  130268. /* Free any prepared statements held */
  130269. for(i=0; i<SizeofArray(pFts3->aStmt); i++){
  130270. sqlite3_finalize(pFts3->aStmt[i]);
  130271. }
  130272. sqlite3_free(pFts3->zSegmentsTbl);
  130273. sqlite3_free(p);
  130274. return SQLITE_OK;
  130275. }
  130276. #define FTS4AUX_EQ_CONSTRAINT 1
  130277. #define FTS4AUX_GE_CONSTRAINT 2
  130278. #define FTS4AUX_LE_CONSTRAINT 4
  130279. /*
  130280. ** xBestIndex - Analyze a WHERE and ORDER BY clause.
  130281. */
  130282. static int fts3auxBestIndexMethod(
  130283. sqlite3_vtab *pVTab,
  130284. sqlite3_index_info *pInfo
  130285. ){
  130286. int i;
  130287. int iEq = -1;
  130288. int iGe = -1;
  130289. int iLe = -1;
  130290. int iLangid = -1;
  130291. int iNext = 1; /* Next free argvIndex value */
  130292. UNUSED_PARAMETER(pVTab);
  130293. /* This vtab delivers always results in "ORDER BY term ASC" order. */
  130294. if( pInfo->nOrderBy==1
  130295. && pInfo->aOrderBy[0].iColumn==0
  130296. && pInfo->aOrderBy[0].desc==0
  130297. ){
  130298. pInfo->orderByConsumed = 1;
  130299. }
  130300. /* Search for equality and range constraints on the "term" column.
  130301. ** And equality constraints on the hidden "languageid" column. */
  130302. for(i=0; i<pInfo->nConstraint; i++){
  130303. if( pInfo->aConstraint[i].usable ){
  130304. int op = pInfo->aConstraint[i].op;
  130305. int iCol = pInfo->aConstraint[i].iColumn;
  130306. if( iCol==0 ){
  130307. if( op==SQLITE_INDEX_CONSTRAINT_EQ ) iEq = i;
  130308. if( op==SQLITE_INDEX_CONSTRAINT_LT ) iLe = i;
  130309. if( op==SQLITE_INDEX_CONSTRAINT_LE ) iLe = i;
  130310. if( op==SQLITE_INDEX_CONSTRAINT_GT ) iGe = i;
  130311. if( op==SQLITE_INDEX_CONSTRAINT_GE ) iGe = i;
  130312. }
  130313. if( iCol==4 ){
  130314. if( op==SQLITE_INDEX_CONSTRAINT_EQ ) iLangid = i;
  130315. }
  130316. }
  130317. }
  130318. if( iEq>=0 ){
  130319. pInfo->idxNum = FTS4AUX_EQ_CONSTRAINT;
  130320. pInfo->aConstraintUsage[iEq].argvIndex = iNext++;
  130321. pInfo->estimatedCost = 5;
  130322. }else{
  130323. pInfo->idxNum = 0;
  130324. pInfo->estimatedCost = 20000;
  130325. if( iGe>=0 ){
  130326. pInfo->idxNum += FTS4AUX_GE_CONSTRAINT;
  130327. pInfo->aConstraintUsage[iGe].argvIndex = iNext++;
  130328. pInfo->estimatedCost /= 2;
  130329. }
  130330. if( iLe>=0 ){
  130331. pInfo->idxNum += FTS4AUX_LE_CONSTRAINT;
  130332. pInfo->aConstraintUsage[iLe].argvIndex = iNext++;
  130333. pInfo->estimatedCost /= 2;
  130334. }
  130335. }
  130336. if( iLangid>=0 ){
  130337. pInfo->aConstraintUsage[iLangid].argvIndex = iNext++;
  130338. pInfo->estimatedCost--;
  130339. }
  130340. return SQLITE_OK;
  130341. }
  130342. /*
  130343. ** xOpen - Open a cursor.
  130344. */
  130345. static int fts3auxOpenMethod(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCsr){
  130346. Fts3auxCursor *pCsr; /* Pointer to cursor object to return */
  130347. UNUSED_PARAMETER(pVTab);
  130348. pCsr = (Fts3auxCursor *)sqlite3_malloc(sizeof(Fts3auxCursor));
  130349. if( !pCsr ) return SQLITE_NOMEM;
  130350. memset(pCsr, 0, sizeof(Fts3auxCursor));
  130351. *ppCsr = (sqlite3_vtab_cursor *)pCsr;
  130352. return SQLITE_OK;
  130353. }
  130354. /*
  130355. ** xClose - Close a cursor.
  130356. */
  130357. static int fts3auxCloseMethod(sqlite3_vtab_cursor *pCursor){
  130358. Fts3Table *pFts3 = ((Fts3auxTable *)pCursor->pVtab)->pFts3Tab;
  130359. Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
  130360. sqlite3Fts3SegmentsClose(pFts3);
  130361. sqlite3Fts3SegReaderFinish(&pCsr->csr);
  130362. sqlite3_free((void *)pCsr->filter.zTerm);
  130363. sqlite3_free(pCsr->zStop);
  130364. sqlite3_free(pCsr->aStat);
  130365. sqlite3_free(pCsr);
  130366. return SQLITE_OK;
  130367. }
  130368. static int fts3auxGrowStatArray(Fts3auxCursor *pCsr, int nSize){
  130369. if( nSize>pCsr->nStat ){
  130370. struct Fts3auxColstats *aNew;
  130371. aNew = (struct Fts3auxColstats *)sqlite3_realloc(pCsr->aStat,
  130372. sizeof(struct Fts3auxColstats) * nSize
  130373. );
  130374. if( aNew==0 ) return SQLITE_NOMEM;
  130375. memset(&aNew[pCsr->nStat], 0,
  130376. sizeof(struct Fts3auxColstats) * (nSize - pCsr->nStat)
  130377. );
  130378. pCsr->aStat = aNew;
  130379. pCsr->nStat = nSize;
  130380. }
  130381. return SQLITE_OK;
  130382. }
  130383. /*
  130384. ** xNext - Advance the cursor to the next row, if any.
  130385. */
  130386. static int fts3auxNextMethod(sqlite3_vtab_cursor *pCursor){
  130387. Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
  130388. Fts3Table *pFts3 = ((Fts3auxTable *)pCursor->pVtab)->pFts3Tab;
  130389. int rc;
  130390. /* Increment our pretend rowid value. */
  130391. pCsr->iRowid++;
  130392. for(pCsr->iCol++; pCsr->iCol<pCsr->nStat; pCsr->iCol++){
  130393. if( pCsr->aStat[pCsr->iCol].nDoc>0 ) return SQLITE_OK;
  130394. }
  130395. rc = sqlite3Fts3SegReaderStep(pFts3, &pCsr->csr);
  130396. if( rc==SQLITE_ROW ){
  130397. int i = 0;
  130398. int nDoclist = pCsr->csr.nDoclist;
  130399. char *aDoclist = pCsr->csr.aDoclist;
  130400. int iCol;
  130401. int eState = 0;
  130402. if( pCsr->zStop ){
  130403. int n = (pCsr->nStop<pCsr->csr.nTerm) ? pCsr->nStop : pCsr->csr.nTerm;
  130404. int mc = memcmp(pCsr->zStop, pCsr->csr.zTerm, n);
  130405. if( mc<0 || (mc==0 && pCsr->csr.nTerm>pCsr->nStop) ){
  130406. pCsr->isEof = 1;
  130407. return SQLITE_OK;
  130408. }
  130409. }
  130410. if( fts3auxGrowStatArray(pCsr, 2) ) return SQLITE_NOMEM;
  130411. memset(pCsr->aStat, 0, sizeof(struct Fts3auxColstats) * pCsr->nStat);
  130412. iCol = 0;
  130413. while( i<nDoclist ){
  130414. sqlite3_int64 v = 0;
  130415. i += sqlite3Fts3GetVarint(&aDoclist[i], &v);
  130416. switch( eState ){
  130417. /* State 0. In this state the integer just read was a docid. */
  130418. case 0:
  130419. pCsr->aStat[0].nDoc++;
  130420. eState = 1;
  130421. iCol = 0;
  130422. break;
  130423. /* State 1. In this state we are expecting either a 1, indicating
  130424. ** that the following integer will be a column number, or the
  130425. ** start of a position list for column 0.
  130426. **
  130427. ** The only difference between state 1 and state 2 is that if the
  130428. ** integer encountered in state 1 is not 0 or 1, then we need to
  130429. ** increment the column 0 "nDoc" count for this term.
  130430. */
  130431. case 1:
  130432. assert( iCol==0 );
  130433. if( v>1 ){
  130434. pCsr->aStat[1].nDoc++;
  130435. }
  130436. eState = 2;
  130437. /* fall through */
  130438. case 2:
  130439. if( v==0 ){ /* 0x00. Next integer will be a docid. */
  130440. eState = 0;
  130441. }else if( v==1 ){ /* 0x01. Next integer will be a column number. */
  130442. eState = 3;
  130443. }else{ /* 2 or greater. A position. */
  130444. pCsr->aStat[iCol+1].nOcc++;
  130445. pCsr->aStat[0].nOcc++;
  130446. }
  130447. break;
  130448. /* State 3. The integer just read is a column number. */
  130449. default: assert( eState==3 );
  130450. iCol = (int)v;
  130451. if( fts3auxGrowStatArray(pCsr, iCol+2) ) return SQLITE_NOMEM;
  130452. pCsr->aStat[iCol+1].nDoc++;
  130453. eState = 2;
  130454. break;
  130455. }
  130456. }
  130457. pCsr->iCol = 0;
  130458. rc = SQLITE_OK;
  130459. }else{
  130460. pCsr->isEof = 1;
  130461. }
  130462. return rc;
  130463. }
  130464. /*
  130465. ** xFilter - Initialize a cursor to point at the start of its data.
  130466. */
  130467. static int fts3auxFilterMethod(
  130468. sqlite3_vtab_cursor *pCursor, /* The cursor used for this query */
  130469. int idxNum, /* Strategy index */
  130470. const char *idxStr, /* Unused */
  130471. int nVal, /* Number of elements in apVal */
  130472. sqlite3_value **apVal /* Arguments for the indexing scheme */
  130473. ){
  130474. Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
  130475. Fts3Table *pFts3 = ((Fts3auxTable *)pCursor->pVtab)->pFts3Tab;
  130476. int rc;
  130477. int isScan = 0;
  130478. int iLangVal = 0; /* Language id to query */
  130479. int iEq = -1; /* Index of term=? value in apVal */
  130480. int iGe = -1; /* Index of term>=? value in apVal */
  130481. int iLe = -1; /* Index of term<=? value in apVal */
  130482. int iLangid = -1; /* Index of languageid=? value in apVal */
  130483. int iNext = 0;
  130484. UNUSED_PARAMETER(nVal);
  130485. UNUSED_PARAMETER(idxStr);
  130486. assert( idxStr==0 );
  130487. assert( idxNum==FTS4AUX_EQ_CONSTRAINT || idxNum==0
  130488. || idxNum==FTS4AUX_LE_CONSTRAINT || idxNum==FTS4AUX_GE_CONSTRAINT
  130489. || idxNum==(FTS4AUX_LE_CONSTRAINT|FTS4AUX_GE_CONSTRAINT)
  130490. );
  130491. if( idxNum==FTS4AUX_EQ_CONSTRAINT ){
  130492. iEq = iNext++;
  130493. }else{
  130494. isScan = 1;
  130495. if( idxNum & FTS4AUX_GE_CONSTRAINT ){
  130496. iGe = iNext++;
  130497. }
  130498. if( idxNum & FTS4AUX_LE_CONSTRAINT ){
  130499. iLe = iNext++;
  130500. }
  130501. }
  130502. if( iNext<nVal ){
  130503. iLangid = iNext++;
  130504. }
  130505. /* In case this cursor is being reused, close and zero it. */
  130506. testcase(pCsr->filter.zTerm);
  130507. sqlite3Fts3SegReaderFinish(&pCsr->csr);
  130508. sqlite3_free((void *)pCsr->filter.zTerm);
  130509. sqlite3_free(pCsr->aStat);
  130510. memset(&pCsr->csr, 0, ((u8*)&pCsr[1]) - (u8*)&pCsr->csr);
  130511. pCsr->filter.flags = FTS3_SEGMENT_REQUIRE_POS|FTS3_SEGMENT_IGNORE_EMPTY;
  130512. if( isScan ) pCsr->filter.flags |= FTS3_SEGMENT_SCAN;
  130513. if( iEq>=0 || iGe>=0 ){
  130514. const unsigned char *zStr = sqlite3_value_text(apVal[0]);
  130515. assert( (iEq==0 && iGe==-1) || (iEq==-1 && iGe==0) );
  130516. if( zStr ){
  130517. pCsr->filter.zTerm = sqlite3_mprintf("%s", zStr);
  130518. pCsr->filter.nTerm = sqlite3_value_bytes(apVal[0]);
  130519. if( pCsr->filter.zTerm==0 ) return SQLITE_NOMEM;
  130520. }
  130521. }
  130522. if( iLe>=0 ){
  130523. pCsr->zStop = sqlite3_mprintf("%s", sqlite3_value_text(apVal[iLe]));
  130524. pCsr->nStop = sqlite3_value_bytes(apVal[iLe]);
  130525. if( pCsr->zStop==0 ) return SQLITE_NOMEM;
  130526. }
  130527. if( iLangid>=0 ){
  130528. iLangVal = sqlite3_value_int(apVal[iLangid]);
  130529. /* If the user specified a negative value for the languageid, use zero
  130530. ** instead. This works, as the "languageid=?" constraint will also
  130531. ** be tested by the VDBE layer. The test will always be false (since
  130532. ** this module will not return a row with a negative languageid), and
  130533. ** so the overall query will return zero rows. */
  130534. if( iLangVal<0 ) iLangVal = 0;
  130535. }
  130536. pCsr->iLangid = iLangVal;
  130537. rc = sqlite3Fts3SegReaderCursor(pFts3, iLangVal, 0, FTS3_SEGCURSOR_ALL,
  130538. pCsr->filter.zTerm, pCsr->filter.nTerm, 0, isScan, &pCsr->csr
  130539. );
  130540. if( rc==SQLITE_OK ){
  130541. rc = sqlite3Fts3SegReaderStart(pFts3, &pCsr->csr, &pCsr->filter);
  130542. }
  130543. if( rc==SQLITE_OK ) rc = fts3auxNextMethod(pCursor);
  130544. return rc;
  130545. }
  130546. /*
  130547. ** xEof - Return true if the cursor is at EOF, or false otherwise.
  130548. */
  130549. static int fts3auxEofMethod(sqlite3_vtab_cursor *pCursor){
  130550. Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
  130551. return pCsr->isEof;
  130552. }
  130553. /*
  130554. ** xColumn - Return a column value.
  130555. */
  130556. static int fts3auxColumnMethod(
  130557. sqlite3_vtab_cursor *pCursor, /* Cursor to retrieve value from */
  130558. sqlite3_context *pCtx, /* Context for sqlite3_result_xxx() calls */
  130559. int iCol /* Index of column to read value from */
  130560. ){
  130561. Fts3auxCursor *p = (Fts3auxCursor *)pCursor;
  130562. assert( p->isEof==0 );
  130563. switch( iCol ){
  130564. case 0: /* term */
  130565. sqlite3_result_text(pCtx, p->csr.zTerm, p->csr.nTerm, SQLITE_TRANSIENT);
  130566. break;
  130567. case 1: /* col */
  130568. if( p->iCol ){
  130569. sqlite3_result_int(pCtx, p->iCol-1);
  130570. }else{
  130571. sqlite3_result_text(pCtx, "*", -1, SQLITE_STATIC);
  130572. }
  130573. break;
  130574. case 2: /* documents */
  130575. sqlite3_result_int64(pCtx, p->aStat[p->iCol].nDoc);
  130576. break;
  130577. case 3: /* occurrences */
  130578. sqlite3_result_int64(pCtx, p->aStat[p->iCol].nOcc);
  130579. break;
  130580. default: /* languageid */
  130581. assert( iCol==4 );
  130582. sqlite3_result_int(pCtx, p->iLangid);
  130583. break;
  130584. }
  130585. return SQLITE_OK;
  130586. }
  130587. /*
  130588. ** xRowid - Return the current rowid for the cursor.
  130589. */
  130590. static int fts3auxRowidMethod(
  130591. sqlite3_vtab_cursor *pCursor, /* Cursor to retrieve value from */
  130592. sqlite_int64 *pRowid /* OUT: Rowid value */
  130593. ){
  130594. Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
  130595. *pRowid = pCsr->iRowid;
  130596. return SQLITE_OK;
  130597. }
  130598. /*
  130599. ** Register the fts3aux module with database connection db. Return SQLITE_OK
  130600. ** if successful or an error code if sqlite3_create_module() fails.
  130601. */
  130602. SQLITE_PRIVATE int sqlite3Fts3InitAux(sqlite3 *db){
  130603. static const sqlite3_module fts3aux_module = {
  130604. 0, /* iVersion */
  130605. fts3auxConnectMethod, /* xCreate */
  130606. fts3auxConnectMethod, /* xConnect */
  130607. fts3auxBestIndexMethod, /* xBestIndex */
  130608. fts3auxDisconnectMethod, /* xDisconnect */
  130609. fts3auxDisconnectMethod, /* xDestroy */
  130610. fts3auxOpenMethod, /* xOpen */
  130611. fts3auxCloseMethod, /* xClose */
  130612. fts3auxFilterMethod, /* xFilter */
  130613. fts3auxNextMethod, /* xNext */
  130614. fts3auxEofMethod, /* xEof */
  130615. fts3auxColumnMethod, /* xColumn */
  130616. fts3auxRowidMethod, /* xRowid */
  130617. 0, /* xUpdate */
  130618. 0, /* xBegin */
  130619. 0, /* xSync */
  130620. 0, /* xCommit */
  130621. 0, /* xRollback */
  130622. 0, /* xFindFunction */
  130623. 0, /* xRename */
  130624. 0, /* xSavepoint */
  130625. 0, /* xRelease */
  130626. 0 /* xRollbackTo */
  130627. };
  130628. int rc; /* Return code */
  130629. rc = sqlite3_create_module(db, "fts4aux", &fts3aux_module, 0);
  130630. return rc;
  130631. }
  130632. #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
  130633. /************** End of fts3_aux.c ********************************************/
  130634. /************** Begin file fts3_expr.c ***************************************/
  130635. /*
  130636. ** 2008 Nov 28
  130637. **
  130638. ** The author disclaims copyright to this source code. In place of
  130639. ** a legal notice, here is a blessing:
  130640. **
  130641. ** May you do good and not evil.
  130642. ** May you find forgiveness for yourself and forgive others.
  130643. ** May you share freely, never taking more than you give.
  130644. **
  130645. ******************************************************************************
  130646. **
  130647. ** This module contains code that implements a parser for fts3 query strings
  130648. ** (the right-hand argument to the MATCH operator). Because the supported
  130649. ** syntax is relatively simple, the whole tokenizer/parser system is
  130650. ** hand-coded.
  130651. */
  130652. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  130653. /*
  130654. ** By default, this module parses the legacy syntax that has been
  130655. ** traditionally used by fts3. Or, if SQLITE_ENABLE_FTS3_PARENTHESIS
  130656. ** is defined, then it uses the new syntax. The differences between
  130657. ** the new and the old syntaxes are:
  130658. **
  130659. ** a) The new syntax supports parenthesis. The old does not.
  130660. **
  130661. ** b) The new syntax supports the AND and NOT operators. The old does not.
  130662. **
  130663. ** c) The old syntax supports the "-" token qualifier. This is not
  130664. ** supported by the new syntax (it is replaced by the NOT operator).
  130665. **
  130666. ** d) When using the old syntax, the OR operator has a greater precedence
  130667. ** than an implicit AND. When using the new, both implicity and explicit
  130668. ** AND operators have a higher precedence than OR.
  130669. **
  130670. ** If compiled with SQLITE_TEST defined, then this module exports the
  130671. ** symbol "int sqlite3_fts3_enable_parentheses". Setting this variable
  130672. ** to zero causes the module to use the old syntax. If it is set to
  130673. ** non-zero the new syntax is activated. This is so both syntaxes can
  130674. ** be tested using a single build of testfixture.
  130675. **
  130676. ** The following describes the syntax supported by the fts3 MATCH
  130677. ** operator in a similar format to that used by the lemon parser
  130678. ** generator. This module does not use actually lemon, it uses a
  130679. ** custom parser.
  130680. **
  130681. ** query ::= andexpr (OR andexpr)*.
  130682. **
  130683. ** andexpr ::= notexpr (AND? notexpr)*.
  130684. **
  130685. ** notexpr ::= nearexpr (NOT nearexpr|-TOKEN)*.
  130686. ** notexpr ::= LP query RP.
  130687. **
  130688. ** nearexpr ::= phrase (NEAR distance_opt nearexpr)*.
  130689. **
  130690. ** distance_opt ::= .
  130691. ** distance_opt ::= / INTEGER.
  130692. **
  130693. ** phrase ::= TOKEN.
  130694. ** phrase ::= COLUMN:TOKEN.
  130695. ** phrase ::= "TOKEN TOKEN TOKEN...".
  130696. */
  130697. #ifdef SQLITE_TEST
  130698. SQLITE_API int sqlite3_fts3_enable_parentheses = 0;
  130699. #else
  130700. # ifdef SQLITE_ENABLE_FTS3_PARENTHESIS
  130701. # define sqlite3_fts3_enable_parentheses 1
  130702. # else
  130703. # define sqlite3_fts3_enable_parentheses 0
  130704. # endif
  130705. #endif
  130706. /*
  130707. ** Default span for NEAR operators.
  130708. */
  130709. #define SQLITE_FTS3_DEFAULT_NEAR_PARAM 10
  130710. /* #include <string.h> */
  130711. /* #include <assert.h> */
  130712. /*
  130713. ** isNot:
  130714. ** This variable is used by function getNextNode(). When getNextNode() is
  130715. ** called, it sets ParseContext.isNot to true if the 'next node' is a
  130716. ** FTSQUERY_PHRASE with a unary "-" attached to it. i.e. "mysql" in the
  130717. ** FTS3 query "sqlite -mysql". Otherwise, ParseContext.isNot is set to
  130718. ** zero.
  130719. */
  130720. typedef struct ParseContext ParseContext;
  130721. struct ParseContext {
  130722. sqlite3_tokenizer *pTokenizer; /* Tokenizer module */
  130723. int iLangid; /* Language id used with tokenizer */
  130724. const char **azCol; /* Array of column names for fts3 table */
  130725. int bFts4; /* True to allow FTS4-only syntax */
  130726. int nCol; /* Number of entries in azCol[] */
  130727. int iDefaultCol; /* Default column to query */
  130728. int isNot; /* True if getNextNode() sees a unary - */
  130729. sqlite3_context *pCtx; /* Write error message here */
  130730. int nNest; /* Number of nested brackets */
  130731. };
  130732. /*
  130733. ** This function is equivalent to the standard isspace() function.
  130734. **
  130735. ** The standard isspace() can be awkward to use safely, because although it
  130736. ** is defined to accept an argument of type int, its behavior when passed
  130737. ** an integer that falls outside of the range of the unsigned char type
  130738. ** is undefined (and sometimes, "undefined" means segfault). This wrapper
  130739. ** is defined to accept an argument of type char, and always returns 0 for
  130740. ** any values that fall outside of the range of the unsigned char type (i.e.
  130741. ** negative values).
  130742. */
  130743. static int fts3isspace(char c){
  130744. return c==' ' || c=='\t' || c=='\n' || c=='\r' || c=='\v' || c=='\f';
  130745. }
  130746. /*
  130747. ** Allocate nByte bytes of memory using sqlite3_malloc(). If successful,
  130748. ** zero the memory before returning a pointer to it. If unsuccessful,
  130749. ** return NULL.
  130750. */
  130751. static void *fts3MallocZero(int nByte){
  130752. void *pRet = sqlite3_malloc(nByte);
  130753. if( pRet ) memset(pRet, 0, nByte);
  130754. return pRet;
  130755. }
  130756. SQLITE_PRIVATE int sqlite3Fts3OpenTokenizer(
  130757. sqlite3_tokenizer *pTokenizer,
  130758. int iLangid,
  130759. const char *z,
  130760. int n,
  130761. sqlite3_tokenizer_cursor **ppCsr
  130762. ){
  130763. sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
  130764. sqlite3_tokenizer_cursor *pCsr = 0;
  130765. int rc;
  130766. rc = pModule->xOpen(pTokenizer, z, n, &pCsr);
  130767. assert( rc==SQLITE_OK || pCsr==0 );
  130768. if( rc==SQLITE_OK ){
  130769. pCsr->pTokenizer = pTokenizer;
  130770. if( pModule->iVersion>=1 ){
  130771. rc = pModule->xLanguageid(pCsr, iLangid);
  130772. if( rc!=SQLITE_OK ){
  130773. pModule->xClose(pCsr);
  130774. pCsr = 0;
  130775. }
  130776. }
  130777. }
  130778. *ppCsr = pCsr;
  130779. return rc;
  130780. }
  130781. /*
  130782. ** Function getNextNode(), which is called by fts3ExprParse(), may itself
  130783. ** call fts3ExprParse(). So this forward declaration is required.
  130784. */
  130785. static int fts3ExprParse(ParseContext *, const char *, int, Fts3Expr **, int *);
  130786. /*
  130787. ** Extract the next token from buffer z (length n) using the tokenizer
  130788. ** and other information (column names etc.) in pParse. Create an Fts3Expr
  130789. ** structure of type FTSQUERY_PHRASE containing a phrase consisting of this
  130790. ** single token and set *ppExpr to point to it. If the end of the buffer is
  130791. ** reached before a token is found, set *ppExpr to zero. It is the
  130792. ** responsibility of the caller to eventually deallocate the allocated
  130793. ** Fts3Expr structure (if any) by passing it to sqlite3_free().
  130794. **
  130795. ** Return SQLITE_OK if successful, or SQLITE_NOMEM if a memory allocation
  130796. ** fails.
  130797. */
  130798. static int getNextToken(
  130799. ParseContext *pParse, /* fts3 query parse context */
  130800. int iCol, /* Value for Fts3Phrase.iColumn */
  130801. const char *z, int n, /* Input string */
  130802. Fts3Expr **ppExpr, /* OUT: expression */
  130803. int *pnConsumed /* OUT: Number of bytes consumed */
  130804. ){
  130805. sqlite3_tokenizer *pTokenizer = pParse->pTokenizer;
  130806. sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
  130807. int rc;
  130808. sqlite3_tokenizer_cursor *pCursor;
  130809. Fts3Expr *pRet = 0;
  130810. int i = 0;
  130811. /* Set variable i to the maximum number of bytes of input to tokenize. */
  130812. for(i=0; i<n; i++){
  130813. if( sqlite3_fts3_enable_parentheses && (z[i]=='(' || z[i]==')') ) break;
  130814. if( z[i]=='"' ) break;
  130815. }
  130816. *pnConsumed = i;
  130817. rc = sqlite3Fts3OpenTokenizer(pTokenizer, pParse->iLangid, z, i, &pCursor);
  130818. if( rc==SQLITE_OK ){
  130819. const char *zToken;
  130820. int nToken = 0, iStart = 0, iEnd = 0, iPosition = 0;
  130821. int nByte; /* total space to allocate */
  130822. rc = pModule->xNext(pCursor, &zToken, &nToken, &iStart, &iEnd, &iPosition);
  130823. if( rc==SQLITE_OK ){
  130824. nByte = sizeof(Fts3Expr) + sizeof(Fts3Phrase) + nToken;
  130825. pRet = (Fts3Expr *)fts3MallocZero(nByte);
  130826. if( !pRet ){
  130827. rc = SQLITE_NOMEM;
  130828. }else{
  130829. pRet->eType = FTSQUERY_PHRASE;
  130830. pRet->pPhrase = (Fts3Phrase *)&pRet[1];
  130831. pRet->pPhrase->nToken = 1;
  130832. pRet->pPhrase->iColumn = iCol;
  130833. pRet->pPhrase->aToken[0].n = nToken;
  130834. pRet->pPhrase->aToken[0].z = (char *)&pRet->pPhrase[1];
  130835. memcpy(pRet->pPhrase->aToken[0].z, zToken, nToken);
  130836. if( iEnd<n && z[iEnd]=='*' ){
  130837. pRet->pPhrase->aToken[0].isPrefix = 1;
  130838. iEnd++;
  130839. }
  130840. while( 1 ){
  130841. if( !sqlite3_fts3_enable_parentheses
  130842. && iStart>0 && z[iStart-1]=='-'
  130843. ){
  130844. pParse->isNot = 1;
  130845. iStart--;
  130846. }else if( pParse->bFts4 && iStart>0 && z[iStart-1]=='^' ){
  130847. pRet->pPhrase->aToken[0].bFirst = 1;
  130848. iStart--;
  130849. }else{
  130850. break;
  130851. }
  130852. }
  130853. }
  130854. *pnConsumed = iEnd;
  130855. }else if( i && rc==SQLITE_DONE ){
  130856. rc = SQLITE_OK;
  130857. }
  130858. pModule->xClose(pCursor);
  130859. }
  130860. *ppExpr = pRet;
  130861. return rc;
  130862. }
  130863. /*
  130864. ** Enlarge a memory allocation. If an out-of-memory allocation occurs,
  130865. ** then free the old allocation.
  130866. */
  130867. static void *fts3ReallocOrFree(void *pOrig, int nNew){
  130868. void *pRet = sqlite3_realloc(pOrig, nNew);
  130869. if( !pRet ){
  130870. sqlite3_free(pOrig);
  130871. }
  130872. return pRet;
  130873. }
  130874. /*
  130875. ** Buffer zInput, length nInput, contains the contents of a quoted string
  130876. ** that appeared as part of an fts3 query expression. Neither quote character
  130877. ** is included in the buffer. This function attempts to tokenize the entire
  130878. ** input buffer and create an Fts3Expr structure of type FTSQUERY_PHRASE
  130879. ** containing the results.
  130880. **
  130881. ** If successful, SQLITE_OK is returned and *ppExpr set to point at the
  130882. ** allocated Fts3Expr structure. Otherwise, either SQLITE_NOMEM (out of memory
  130883. ** error) or SQLITE_ERROR (tokenization error) is returned and *ppExpr set
  130884. ** to 0.
  130885. */
  130886. static int getNextString(
  130887. ParseContext *pParse, /* fts3 query parse context */
  130888. const char *zInput, int nInput, /* Input string */
  130889. Fts3Expr **ppExpr /* OUT: expression */
  130890. ){
  130891. sqlite3_tokenizer *pTokenizer = pParse->pTokenizer;
  130892. sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
  130893. int rc;
  130894. Fts3Expr *p = 0;
  130895. sqlite3_tokenizer_cursor *pCursor = 0;
  130896. char *zTemp = 0;
  130897. int nTemp = 0;
  130898. const int nSpace = sizeof(Fts3Expr) + sizeof(Fts3Phrase);
  130899. int nToken = 0;
  130900. /* The final Fts3Expr data structure, including the Fts3Phrase,
  130901. ** Fts3PhraseToken structures token buffers are all stored as a single
  130902. ** allocation so that the expression can be freed with a single call to
  130903. ** sqlite3_free(). Setting this up requires a two pass approach.
  130904. **
  130905. ** The first pass, in the block below, uses a tokenizer cursor to iterate
  130906. ** through the tokens in the expression. This pass uses fts3ReallocOrFree()
  130907. ** to assemble data in two dynamic buffers:
  130908. **
  130909. ** Buffer p: Points to the Fts3Expr structure, followed by the Fts3Phrase
  130910. ** structure, followed by the array of Fts3PhraseToken
  130911. ** structures. This pass only populates the Fts3PhraseToken array.
  130912. **
  130913. ** Buffer zTemp: Contains copies of all tokens.
  130914. **
  130915. ** The second pass, in the block that begins "if( rc==SQLITE_DONE )" below,
  130916. ** appends buffer zTemp to buffer p, and fills in the Fts3Expr and Fts3Phrase
  130917. ** structures.
  130918. */
  130919. rc = sqlite3Fts3OpenTokenizer(
  130920. pTokenizer, pParse->iLangid, zInput, nInput, &pCursor);
  130921. if( rc==SQLITE_OK ){
  130922. int ii;
  130923. for(ii=0; rc==SQLITE_OK; ii++){
  130924. const char *zByte;
  130925. int nByte = 0, iBegin = 0, iEnd = 0, iPos = 0;
  130926. rc = pModule->xNext(pCursor, &zByte, &nByte, &iBegin, &iEnd, &iPos);
  130927. if( rc==SQLITE_OK ){
  130928. Fts3PhraseToken *pToken;
  130929. p = fts3ReallocOrFree(p, nSpace + ii*sizeof(Fts3PhraseToken));
  130930. if( !p ) goto no_mem;
  130931. zTemp = fts3ReallocOrFree(zTemp, nTemp + nByte);
  130932. if( !zTemp ) goto no_mem;
  130933. assert( nToken==ii );
  130934. pToken = &((Fts3Phrase *)(&p[1]))->aToken[ii];
  130935. memset(pToken, 0, sizeof(Fts3PhraseToken));
  130936. memcpy(&zTemp[nTemp], zByte, nByte);
  130937. nTemp += nByte;
  130938. pToken->n = nByte;
  130939. pToken->isPrefix = (iEnd<nInput && zInput[iEnd]=='*');
  130940. pToken->bFirst = (iBegin>0 && zInput[iBegin-1]=='^');
  130941. nToken = ii+1;
  130942. }
  130943. }
  130944. pModule->xClose(pCursor);
  130945. pCursor = 0;
  130946. }
  130947. if( rc==SQLITE_DONE ){
  130948. int jj;
  130949. char *zBuf = 0;
  130950. p = fts3ReallocOrFree(p, nSpace + nToken*sizeof(Fts3PhraseToken) + nTemp);
  130951. if( !p ) goto no_mem;
  130952. memset(p, 0, (char *)&(((Fts3Phrase *)&p[1])->aToken[0])-(char *)p);
  130953. p->eType = FTSQUERY_PHRASE;
  130954. p->pPhrase = (Fts3Phrase *)&p[1];
  130955. p->pPhrase->iColumn = pParse->iDefaultCol;
  130956. p->pPhrase->nToken = nToken;
  130957. zBuf = (char *)&p->pPhrase->aToken[nToken];
  130958. if( zTemp ){
  130959. memcpy(zBuf, zTemp, nTemp);
  130960. sqlite3_free(zTemp);
  130961. }else{
  130962. assert( nTemp==0 );
  130963. }
  130964. for(jj=0; jj<p->pPhrase->nToken; jj++){
  130965. p->pPhrase->aToken[jj].z = zBuf;
  130966. zBuf += p->pPhrase->aToken[jj].n;
  130967. }
  130968. rc = SQLITE_OK;
  130969. }
  130970. *ppExpr = p;
  130971. return rc;
  130972. no_mem:
  130973. if( pCursor ){
  130974. pModule->xClose(pCursor);
  130975. }
  130976. sqlite3_free(zTemp);
  130977. sqlite3_free(p);
  130978. *ppExpr = 0;
  130979. return SQLITE_NOMEM;
  130980. }
  130981. /*
  130982. ** The output variable *ppExpr is populated with an allocated Fts3Expr
  130983. ** structure, or set to 0 if the end of the input buffer is reached.
  130984. **
  130985. ** Returns an SQLite error code. SQLITE_OK if everything works, SQLITE_NOMEM
  130986. ** if a malloc failure occurs, or SQLITE_ERROR if a parse error is encountered.
  130987. ** If SQLITE_ERROR is returned, pContext is populated with an error message.
  130988. */
  130989. static int getNextNode(
  130990. ParseContext *pParse, /* fts3 query parse context */
  130991. const char *z, int n, /* Input string */
  130992. Fts3Expr **ppExpr, /* OUT: expression */
  130993. int *pnConsumed /* OUT: Number of bytes consumed */
  130994. ){
  130995. static const struct Fts3Keyword {
  130996. char *z; /* Keyword text */
  130997. unsigned char n; /* Length of the keyword */
  130998. unsigned char parenOnly; /* Only valid in paren mode */
  130999. unsigned char eType; /* Keyword code */
  131000. } aKeyword[] = {
  131001. { "OR" , 2, 0, FTSQUERY_OR },
  131002. { "AND", 3, 1, FTSQUERY_AND },
  131003. { "NOT", 3, 1, FTSQUERY_NOT },
  131004. { "NEAR", 4, 0, FTSQUERY_NEAR }
  131005. };
  131006. int ii;
  131007. int iCol;
  131008. int iColLen;
  131009. int rc;
  131010. Fts3Expr *pRet = 0;
  131011. const char *zInput = z;
  131012. int nInput = n;
  131013. pParse->isNot = 0;
  131014. /* Skip over any whitespace before checking for a keyword, an open or
  131015. ** close bracket, or a quoted string.
  131016. */
  131017. while( nInput>0 && fts3isspace(*zInput) ){
  131018. nInput--;
  131019. zInput++;
  131020. }
  131021. if( nInput==0 ){
  131022. return SQLITE_DONE;
  131023. }
  131024. /* See if we are dealing with a keyword. */
  131025. for(ii=0; ii<(int)(sizeof(aKeyword)/sizeof(struct Fts3Keyword)); ii++){
  131026. const struct Fts3Keyword *pKey = &aKeyword[ii];
  131027. if( (pKey->parenOnly & ~sqlite3_fts3_enable_parentheses)!=0 ){
  131028. continue;
  131029. }
  131030. if( nInput>=pKey->n && 0==memcmp(zInput, pKey->z, pKey->n) ){
  131031. int nNear = SQLITE_FTS3_DEFAULT_NEAR_PARAM;
  131032. int nKey = pKey->n;
  131033. char cNext;
  131034. /* If this is a "NEAR" keyword, check for an explicit nearness. */
  131035. if( pKey->eType==FTSQUERY_NEAR ){
  131036. assert( nKey==4 );
  131037. if( zInput[4]=='/' && zInput[5]>='0' && zInput[5]<='9' ){
  131038. nNear = 0;
  131039. for(nKey=5; zInput[nKey]>='0' && zInput[nKey]<='9'; nKey++){
  131040. nNear = nNear * 10 + (zInput[nKey] - '0');
  131041. }
  131042. }
  131043. }
  131044. /* At this point this is probably a keyword. But for that to be true,
  131045. ** the next byte must contain either whitespace, an open or close
  131046. ** parenthesis, a quote character, or EOF.
  131047. */
  131048. cNext = zInput[nKey];
  131049. if( fts3isspace(cNext)
  131050. || cNext=='"' || cNext=='(' || cNext==')' || cNext==0
  131051. ){
  131052. pRet = (Fts3Expr *)fts3MallocZero(sizeof(Fts3Expr));
  131053. if( !pRet ){
  131054. return SQLITE_NOMEM;
  131055. }
  131056. pRet->eType = pKey->eType;
  131057. pRet->nNear = nNear;
  131058. *ppExpr = pRet;
  131059. *pnConsumed = (int)((zInput - z) + nKey);
  131060. return SQLITE_OK;
  131061. }
  131062. /* Turns out that wasn't a keyword after all. This happens if the
  131063. ** user has supplied a token such as "ORacle". Continue.
  131064. */
  131065. }
  131066. }
  131067. /* See if we are dealing with a quoted phrase. If this is the case, then
  131068. ** search for the closing quote and pass the whole string to getNextString()
  131069. ** for processing. This is easy to do, as fts3 has no syntax for escaping
  131070. ** a quote character embedded in a string.
  131071. */
  131072. if( *zInput=='"' ){
  131073. for(ii=1; ii<nInput && zInput[ii]!='"'; ii++);
  131074. *pnConsumed = (int)((zInput - z) + ii + 1);
  131075. if( ii==nInput ){
  131076. return SQLITE_ERROR;
  131077. }
  131078. return getNextString(pParse, &zInput[1], ii-1, ppExpr);
  131079. }
  131080. if( sqlite3_fts3_enable_parentheses ){
  131081. if( *zInput=='(' ){
  131082. int nConsumed = 0;
  131083. pParse->nNest++;
  131084. rc = fts3ExprParse(pParse, zInput+1, nInput-1, ppExpr, &nConsumed);
  131085. if( rc==SQLITE_OK && !*ppExpr ){ rc = SQLITE_DONE; }
  131086. *pnConsumed = (int)(zInput - z) + 1 + nConsumed;
  131087. return rc;
  131088. }else if( *zInput==')' ){
  131089. pParse->nNest--;
  131090. *pnConsumed = (int)((zInput - z) + 1);
  131091. *ppExpr = 0;
  131092. return SQLITE_DONE;
  131093. }
  131094. }
  131095. /* If control flows to this point, this must be a regular token, or
  131096. ** the end of the input. Read a regular token using the sqlite3_tokenizer
  131097. ** interface. Before doing so, figure out if there is an explicit
  131098. ** column specifier for the token.
  131099. **
  131100. ** TODO: Strangely, it is not possible to associate a column specifier
  131101. ** with a quoted phrase, only with a single token. Not sure if this was
  131102. ** an implementation artifact or an intentional decision when fts3 was
  131103. ** first implemented. Whichever it was, this module duplicates the
  131104. ** limitation.
  131105. */
  131106. iCol = pParse->iDefaultCol;
  131107. iColLen = 0;
  131108. for(ii=0; ii<pParse->nCol; ii++){
  131109. const char *zStr = pParse->azCol[ii];
  131110. int nStr = (int)strlen(zStr);
  131111. if( nInput>nStr && zInput[nStr]==':'
  131112. && sqlite3_strnicmp(zStr, zInput, nStr)==0
  131113. ){
  131114. iCol = ii;
  131115. iColLen = (int)((zInput - z) + nStr + 1);
  131116. break;
  131117. }
  131118. }
  131119. rc = getNextToken(pParse, iCol, &z[iColLen], n-iColLen, ppExpr, pnConsumed);
  131120. *pnConsumed += iColLen;
  131121. return rc;
  131122. }
  131123. /*
  131124. ** The argument is an Fts3Expr structure for a binary operator (any type
  131125. ** except an FTSQUERY_PHRASE). Return an integer value representing the
  131126. ** precedence of the operator. Lower values have a higher precedence (i.e.
  131127. ** group more tightly). For example, in the C language, the == operator
  131128. ** groups more tightly than ||, and would therefore have a higher precedence.
  131129. **
  131130. ** When using the new fts3 query syntax (when SQLITE_ENABLE_FTS3_PARENTHESIS
  131131. ** is defined), the order of the operators in precedence from highest to
  131132. ** lowest is:
  131133. **
  131134. ** NEAR
  131135. ** NOT
  131136. ** AND (including implicit ANDs)
  131137. ** OR
  131138. **
  131139. ** Note that when using the old query syntax, the OR operator has a higher
  131140. ** precedence than the AND operator.
  131141. */
  131142. static int opPrecedence(Fts3Expr *p){
  131143. assert( p->eType!=FTSQUERY_PHRASE );
  131144. if( sqlite3_fts3_enable_parentheses ){
  131145. return p->eType;
  131146. }else if( p->eType==FTSQUERY_NEAR ){
  131147. return 1;
  131148. }else if( p->eType==FTSQUERY_OR ){
  131149. return 2;
  131150. }
  131151. assert( p->eType==FTSQUERY_AND );
  131152. return 3;
  131153. }
  131154. /*
  131155. ** Argument ppHead contains a pointer to the current head of a query
  131156. ** expression tree being parsed. pPrev is the expression node most recently
  131157. ** inserted into the tree. This function adds pNew, which is always a binary
  131158. ** operator node, into the expression tree based on the relative precedence
  131159. ** of pNew and the existing nodes of the tree. This may result in the head
  131160. ** of the tree changing, in which case *ppHead is set to the new root node.
  131161. */
  131162. static void insertBinaryOperator(
  131163. Fts3Expr **ppHead, /* Pointer to the root node of a tree */
  131164. Fts3Expr *pPrev, /* Node most recently inserted into the tree */
  131165. Fts3Expr *pNew /* New binary node to insert into expression tree */
  131166. ){
  131167. Fts3Expr *pSplit = pPrev;
  131168. while( pSplit->pParent && opPrecedence(pSplit->pParent)<=opPrecedence(pNew) ){
  131169. pSplit = pSplit->pParent;
  131170. }
  131171. if( pSplit->pParent ){
  131172. assert( pSplit->pParent->pRight==pSplit );
  131173. pSplit->pParent->pRight = pNew;
  131174. pNew->pParent = pSplit->pParent;
  131175. }else{
  131176. *ppHead = pNew;
  131177. }
  131178. pNew->pLeft = pSplit;
  131179. pSplit->pParent = pNew;
  131180. }
  131181. /*
  131182. ** Parse the fts3 query expression found in buffer z, length n. This function
  131183. ** returns either when the end of the buffer is reached or an unmatched
  131184. ** closing bracket - ')' - is encountered.
  131185. **
  131186. ** If successful, SQLITE_OK is returned, *ppExpr is set to point to the
  131187. ** parsed form of the expression and *pnConsumed is set to the number of
  131188. ** bytes read from buffer z. Otherwise, *ppExpr is set to 0 and SQLITE_NOMEM
  131189. ** (out of memory error) or SQLITE_ERROR (parse error) is returned.
  131190. */
  131191. static int fts3ExprParse(
  131192. ParseContext *pParse, /* fts3 query parse context */
  131193. const char *z, int n, /* Text of MATCH query */
  131194. Fts3Expr **ppExpr, /* OUT: Parsed query structure */
  131195. int *pnConsumed /* OUT: Number of bytes consumed */
  131196. ){
  131197. Fts3Expr *pRet = 0;
  131198. Fts3Expr *pPrev = 0;
  131199. Fts3Expr *pNotBranch = 0; /* Only used in legacy parse mode */
  131200. int nIn = n;
  131201. const char *zIn = z;
  131202. int rc = SQLITE_OK;
  131203. int isRequirePhrase = 1;
  131204. while( rc==SQLITE_OK ){
  131205. Fts3Expr *p = 0;
  131206. int nByte = 0;
  131207. rc = getNextNode(pParse, zIn, nIn, &p, &nByte);
  131208. assert( nByte>0 || (rc!=SQLITE_OK && p==0) );
  131209. if( rc==SQLITE_OK ){
  131210. if( p ){
  131211. int isPhrase;
  131212. if( !sqlite3_fts3_enable_parentheses
  131213. && p->eType==FTSQUERY_PHRASE && pParse->isNot
  131214. ){
  131215. /* Create an implicit NOT operator. */
  131216. Fts3Expr *pNot = fts3MallocZero(sizeof(Fts3Expr));
  131217. if( !pNot ){
  131218. sqlite3Fts3ExprFree(p);
  131219. rc = SQLITE_NOMEM;
  131220. goto exprparse_out;
  131221. }
  131222. pNot->eType = FTSQUERY_NOT;
  131223. pNot->pRight = p;
  131224. p->pParent = pNot;
  131225. if( pNotBranch ){
  131226. pNot->pLeft = pNotBranch;
  131227. pNotBranch->pParent = pNot;
  131228. }
  131229. pNotBranch = pNot;
  131230. p = pPrev;
  131231. }else{
  131232. int eType = p->eType;
  131233. isPhrase = (eType==FTSQUERY_PHRASE || p->pLeft);
  131234. /* The isRequirePhrase variable is set to true if a phrase or
  131235. ** an expression contained in parenthesis is required. If a
  131236. ** binary operator (AND, OR, NOT or NEAR) is encounted when
  131237. ** isRequirePhrase is set, this is a syntax error.
  131238. */
  131239. if( !isPhrase && isRequirePhrase ){
  131240. sqlite3Fts3ExprFree(p);
  131241. rc = SQLITE_ERROR;
  131242. goto exprparse_out;
  131243. }
  131244. if( isPhrase && !isRequirePhrase ){
  131245. /* Insert an implicit AND operator. */
  131246. Fts3Expr *pAnd;
  131247. assert( pRet && pPrev );
  131248. pAnd = fts3MallocZero(sizeof(Fts3Expr));
  131249. if( !pAnd ){
  131250. sqlite3Fts3ExprFree(p);
  131251. rc = SQLITE_NOMEM;
  131252. goto exprparse_out;
  131253. }
  131254. pAnd->eType = FTSQUERY_AND;
  131255. insertBinaryOperator(&pRet, pPrev, pAnd);
  131256. pPrev = pAnd;
  131257. }
  131258. /* This test catches attempts to make either operand of a NEAR
  131259. ** operator something other than a phrase. For example, either of
  131260. ** the following:
  131261. **
  131262. ** (bracketed expression) NEAR phrase
  131263. ** phrase NEAR (bracketed expression)
  131264. **
  131265. ** Return an error in either case.
  131266. */
  131267. if( pPrev && (
  131268. (eType==FTSQUERY_NEAR && !isPhrase && pPrev->eType!=FTSQUERY_PHRASE)
  131269. || (eType!=FTSQUERY_PHRASE && isPhrase && pPrev->eType==FTSQUERY_NEAR)
  131270. )){
  131271. sqlite3Fts3ExprFree(p);
  131272. rc = SQLITE_ERROR;
  131273. goto exprparse_out;
  131274. }
  131275. if( isPhrase ){
  131276. if( pRet ){
  131277. assert( pPrev && pPrev->pLeft && pPrev->pRight==0 );
  131278. pPrev->pRight = p;
  131279. p->pParent = pPrev;
  131280. }else{
  131281. pRet = p;
  131282. }
  131283. }else{
  131284. insertBinaryOperator(&pRet, pPrev, p);
  131285. }
  131286. isRequirePhrase = !isPhrase;
  131287. }
  131288. pPrev = p;
  131289. }
  131290. assert( nByte>0 );
  131291. }
  131292. assert( rc!=SQLITE_OK || (nByte>0 && nByte<=nIn) );
  131293. nIn -= nByte;
  131294. zIn += nByte;
  131295. }
  131296. if( rc==SQLITE_DONE && pRet && isRequirePhrase ){
  131297. rc = SQLITE_ERROR;
  131298. }
  131299. if( rc==SQLITE_DONE ){
  131300. rc = SQLITE_OK;
  131301. if( !sqlite3_fts3_enable_parentheses && pNotBranch ){
  131302. if( !pRet ){
  131303. rc = SQLITE_ERROR;
  131304. }else{
  131305. Fts3Expr *pIter = pNotBranch;
  131306. while( pIter->pLeft ){
  131307. pIter = pIter->pLeft;
  131308. }
  131309. pIter->pLeft = pRet;
  131310. pRet->pParent = pIter;
  131311. pRet = pNotBranch;
  131312. }
  131313. }
  131314. }
  131315. *pnConsumed = n - nIn;
  131316. exprparse_out:
  131317. if( rc!=SQLITE_OK ){
  131318. sqlite3Fts3ExprFree(pRet);
  131319. sqlite3Fts3ExprFree(pNotBranch);
  131320. pRet = 0;
  131321. }
  131322. *ppExpr = pRet;
  131323. return rc;
  131324. }
  131325. /*
  131326. ** Return SQLITE_ERROR if the maximum depth of the expression tree passed
  131327. ** as the only argument is more than nMaxDepth.
  131328. */
  131329. static int fts3ExprCheckDepth(Fts3Expr *p, int nMaxDepth){
  131330. int rc = SQLITE_OK;
  131331. if( p ){
  131332. if( nMaxDepth<0 ){
  131333. rc = SQLITE_TOOBIG;
  131334. }else{
  131335. rc = fts3ExprCheckDepth(p->pLeft, nMaxDepth-1);
  131336. if( rc==SQLITE_OK ){
  131337. rc = fts3ExprCheckDepth(p->pRight, nMaxDepth-1);
  131338. }
  131339. }
  131340. }
  131341. return rc;
  131342. }
  131343. /*
  131344. ** This function attempts to transform the expression tree at (*pp) to
  131345. ** an equivalent but more balanced form. The tree is modified in place.
  131346. ** If successful, SQLITE_OK is returned and (*pp) set to point to the
  131347. ** new root expression node.
  131348. **
  131349. ** nMaxDepth is the maximum allowable depth of the balanced sub-tree.
  131350. **
  131351. ** Otherwise, if an error occurs, an SQLite error code is returned and
  131352. ** expression (*pp) freed.
  131353. */
  131354. static int fts3ExprBalance(Fts3Expr **pp, int nMaxDepth){
  131355. int rc = SQLITE_OK; /* Return code */
  131356. Fts3Expr *pRoot = *pp; /* Initial root node */
  131357. Fts3Expr *pFree = 0; /* List of free nodes. Linked by pParent. */
  131358. int eType = pRoot->eType; /* Type of node in this tree */
  131359. if( nMaxDepth==0 ){
  131360. rc = SQLITE_ERROR;
  131361. }
  131362. if( rc==SQLITE_OK && (eType==FTSQUERY_AND || eType==FTSQUERY_OR) ){
  131363. Fts3Expr **apLeaf;
  131364. apLeaf = (Fts3Expr **)sqlite3_malloc(sizeof(Fts3Expr *) * nMaxDepth);
  131365. if( 0==apLeaf ){
  131366. rc = SQLITE_NOMEM;
  131367. }else{
  131368. memset(apLeaf, 0, sizeof(Fts3Expr *) * nMaxDepth);
  131369. }
  131370. if( rc==SQLITE_OK ){
  131371. int i;
  131372. Fts3Expr *p;
  131373. /* Set $p to point to the left-most leaf in the tree of eType nodes. */
  131374. for(p=pRoot; p->eType==eType; p=p->pLeft){
  131375. assert( p->pParent==0 || p->pParent->pLeft==p );
  131376. assert( p->pLeft && p->pRight );
  131377. }
  131378. /* This loop runs once for each leaf in the tree of eType nodes. */
  131379. while( 1 ){
  131380. int iLvl;
  131381. Fts3Expr *pParent = p->pParent; /* Current parent of p */
  131382. assert( pParent==0 || pParent->pLeft==p );
  131383. p->pParent = 0;
  131384. if( pParent ){
  131385. pParent->pLeft = 0;
  131386. }else{
  131387. pRoot = 0;
  131388. }
  131389. rc = fts3ExprBalance(&p, nMaxDepth-1);
  131390. if( rc!=SQLITE_OK ) break;
  131391. for(iLvl=0; p && iLvl<nMaxDepth; iLvl++){
  131392. if( apLeaf[iLvl]==0 ){
  131393. apLeaf[iLvl] = p;
  131394. p = 0;
  131395. }else{
  131396. assert( pFree );
  131397. pFree->pLeft = apLeaf[iLvl];
  131398. pFree->pRight = p;
  131399. pFree->pLeft->pParent = pFree;
  131400. pFree->pRight->pParent = pFree;
  131401. p = pFree;
  131402. pFree = pFree->pParent;
  131403. p->pParent = 0;
  131404. apLeaf[iLvl] = 0;
  131405. }
  131406. }
  131407. if( p ){
  131408. sqlite3Fts3ExprFree(p);
  131409. rc = SQLITE_TOOBIG;
  131410. break;
  131411. }
  131412. /* If that was the last leaf node, break out of the loop */
  131413. if( pParent==0 ) break;
  131414. /* Set $p to point to the next leaf in the tree of eType nodes */
  131415. for(p=pParent->pRight; p->eType==eType; p=p->pLeft);
  131416. /* Remove pParent from the original tree. */
  131417. assert( pParent->pParent==0 || pParent->pParent->pLeft==pParent );
  131418. pParent->pRight->pParent = pParent->pParent;
  131419. if( pParent->pParent ){
  131420. pParent->pParent->pLeft = pParent->pRight;
  131421. }else{
  131422. assert( pParent==pRoot );
  131423. pRoot = pParent->pRight;
  131424. }
  131425. /* Link pParent into the free node list. It will be used as an
  131426. ** internal node of the new tree. */
  131427. pParent->pParent = pFree;
  131428. pFree = pParent;
  131429. }
  131430. if( rc==SQLITE_OK ){
  131431. p = 0;
  131432. for(i=0; i<nMaxDepth; i++){
  131433. if( apLeaf[i] ){
  131434. if( p==0 ){
  131435. p = apLeaf[i];
  131436. p->pParent = 0;
  131437. }else{
  131438. assert( pFree!=0 );
  131439. pFree->pRight = p;
  131440. pFree->pLeft = apLeaf[i];
  131441. pFree->pLeft->pParent = pFree;
  131442. pFree->pRight->pParent = pFree;
  131443. p = pFree;
  131444. pFree = pFree->pParent;
  131445. p->pParent = 0;
  131446. }
  131447. }
  131448. }
  131449. pRoot = p;
  131450. }else{
  131451. /* An error occurred. Delete the contents of the apLeaf[] array
  131452. ** and pFree list. Everything else is cleaned up by the call to
  131453. ** sqlite3Fts3ExprFree(pRoot) below. */
  131454. Fts3Expr *pDel;
  131455. for(i=0; i<nMaxDepth; i++){
  131456. sqlite3Fts3ExprFree(apLeaf[i]);
  131457. }
  131458. while( (pDel=pFree)!=0 ){
  131459. pFree = pDel->pParent;
  131460. sqlite3_free(pDel);
  131461. }
  131462. }
  131463. assert( pFree==0 );
  131464. sqlite3_free( apLeaf );
  131465. }
  131466. }
  131467. if( rc!=SQLITE_OK ){
  131468. sqlite3Fts3ExprFree(pRoot);
  131469. pRoot = 0;
  131470. }
  131471. *pp = pRoot;
  131472. return rc;
  131473. }
  131474. /*
  131475. ** This function is similar to sqlite3Fts3ExprParse(), with the following
  131476. ** differences:
  131477. **
  131478. ** 1. It does not do expression rebalancing.
  131479. ** 2. It does not check that the expression does not exceed the
  131480. ** maximum allowable depth.
  131481. ** 3. Even if it fails, *ppExpr may still be set to point to an
  131482. ** expression tree. It should be deleted using sqlite3Fts3ExprFree()
  131483. ** in this case.
  131484. */
  131485. static int fts3ExprParseUnbalanced(
  131486. sqlite3_tokenizer *pTokenizer, /* Tokenizer module */
  131487. int iLangid, /* Language id for tokenizer */
  131488. char **azCol, /* Array of column names for fts3 table */
  131489. int bFts4, /* True to allow FTS4-only syntax */
  131490. int nCol, /* Number of entries in azCol[] */
  131491. int iDefaultCol, /* Default column to query */
  131492. const char *z, int n, /* Text of MATCH query */
  131493. Fts3Expr **ppExpr /* OUT: Parsed query structure */
  131494. ){
  131495. int nParsed;
  131496. int rc;
  131497. ParseContext sParse;
  131498. memset(&sParse, 0, sizeof(ParseContext));
  131499. sParse.pTokenizer = pTokenizer;
  131500. sParse.iLangid = iLangid;
  131501. sParse.azCol = (const char **)azCol;
  131502. sParse.nCol = nCol;
  131503. sParse.iDefaultCol = iDefaultCol;
  131504. sParse.bFts4 = bFts4;
  131505. if( z==0 ){
  131506. *ppExpr = 0;
  131507. return SQLITE_OK;
  131508. }
  131509. if( n<0 ){
  131510. n = (int)strlen(z);
  131511. }
  131512. rc = fts3ExprParse(&sParse, z, n, ppExpr, &nParsed);
  131513. assert( rc==SQLITE_OK || *ppExpr==0 );
  131514. /* Check for mismatched parenthesis */
  131515. if( rc==SQLITE_OK && sParse.nNest ){
  131516. rc = SQLITE_ERROR;
  131517. }
  131518. return rc;
  131519. }
  131520. /*
  131521. ** Parameters z and n contain a pointer to and length of a buffer containing
  131522. ** an fts3 query expression, respectively. This function attempts to parse the
  131523. ** query expression and create a tree of Fts3Expr structures representing the
  131524. ** parsed expression. If successful, *ppExpr is set to point to the head
  131525. ** of the parsed expression tree and SQLITE_OK is returned. If an error
  131526. ** occurs, either SQLITE_NOMEM (out-of-memory error) or SQLITE_ERROR (parse
  131527. ** error) is returned and *ppExpr is set to 0.
  131528. **
  131529. ** If parameter n is a negative number, then z is assumed to point to a
  131530. ** nul-terminated string and the length is determined using strlen().
  131531. **
  131532. ** The first parameter, pTokenizer, is passed the fts3 tokenizer module to
  131533. ** use to normalize query tokens while parsing the expression. The azCol[]
  131534. ** array, which is assumed to contain nCol entries, should contain the names
  131535. ** of each column in the target fts3 table, in order from left to right.
  131536. ** Column names must be nul-terminated strings.
  131537. **
  131538. ** The iDefaultCol parameter should be passed the index of the table column
  131539. ** that appears on the left-hand-side of the MATCH operator (the default
  131540. ** column to match against for tokens for which a column name is not explicitly
  131541. ** specified as part of the query string), or -1 if tokens may by default
  131542. ** match any table column.
  131543. */
  131544. SQLITE_PRIVATE int sqlite3Fts3ExprParse(
  131545. sqlite3_tokenizer *pTokenizer, /* Tokenizer module */
  131546. int iLangid, /* Language id for tokenizer */
  131547. char **azCol, /* Array of column names for fts3 table */
  131548. int bFts4, /* True to allow FTS4-only syntax */
  131549. int nCol, /* Number of entries in azCol[] */
  131550. int iDefaultCol, /* Default column to query */
  131551. const char *z, int n, /* Text of MATCH query */
  131552. Fts3Expr **ppExpr, /* OUT: Parsed query structure */
  131553. char **pzErr /* OUT: Error message (sqlite3_malloc) */
  131554. ){
  131555. int rc = fts3ExprParseUnbalanced(
  131556. pTokenizer, iLangid, azCol, bFts4, nCol, iDefaultCol, z, n, ppExpr
  131557. );
  131558. /* Rebalance the expression. And check that its depth does not exceed
  131559. ** SQLITE_FTS3_MAX_EXPR_DEPTH. */
  131560. if( rc==SQLITE_OK && *ppExpr ){
  131561. rc = fts3ExprBalance(ppExpr, SQLITE_FTS3_MAX_EXPR_DEPTH);
  131562. if( rc==SQLITE_OK ){
  131563. rc = fts3ExprCheckDepth(*ppExpr, SQLITE_FTS3_MAX_EXPR_DEPTH);
  131564. }
  131565. }
  131566. if( rc!=SQLITE_OK ){
  131567. sqlite3Fts3ExprFree(*ppExpr);
  131568. *ppExpr = 0;
  131569. if( rc==SQLITE_TOOBIG ){
  131570. sqlite3Fts3ErrMsg(pzErr,
  131571. "FTS expression tree is too large (maximum depth %d)",
  131572. SQLITE_FTS3_MAX_EXPR_DEPTH
  131573. );
  131574. rc = SQLITE_ERROR;
  131575. }else if( rc==SQLITE_ERROR ){
  131576. sqlite3Fts3ErrMsg(pzErr, "malformed MATCH expression: [%s]", z);
  131577. }
  131578. }
  131579. return rc;
  131580. }
  131581. /*
  131582. ** Free a single node of an expression tree.
  131583. */
  131584. static void fts3FreeExprNode(Fts3Expr *p){
  131585. assert( p->eType==FTSQUERY_PHRASE || p->pPhrase==0 );
  131586. sqlite3Fts3EvalPhraseCleanup(p->pPhrase);
  131587. sqlite3_free(p->aMI);
  131588. sqlite3_free(p);
  131589. }
  131590. /*
  131591. ** Free a parsed fts3 query expression allocated by sqlite3Fts3ExprParse().
  131592. **
  131593. ** This function would be simpler if it recursively called itself. But
  131594. ** that would mean passing a sufficiently large expression to ExprParse()
  131595. ** could cause a stack overflow.
  131596. */
  131597. SQLITE_PRIVATE void sqlite3Fts3ExprFree(Fts3Expr *pDel){
  131598. Fts3Expr *p;
  131599. assert( pDel==0 || pDel->pParent==0 );
  131600. for(p=pDel; p && (p->pLeft||p->pRight); p=(p->pLeft ? p->pLeft : p->pRight)){
  131601. assert( p->pParent==0 || p==p->pParent->pRight || p==p->pParent->pLeft );
  131602. }
  131603. while( p ){
  131604. Fts3Expr *pParent = p->pParent;
  131605. fts3FreeExprNode(p);
  131606. if( pParent && p==pParent->pLeft && pParent->pRight ){
  131607. p = pParent->pRight;
  131608. while( p && (p->pLeft || p->pRight) ){
  131609. assert( p==p->pParent->pRight || p==p->pParent->pLeft );
  131610. p = (p->pLeft ? p->pLeft : p->pRight);
  131611. }
  131612. }else{
  131613. p = pParent;
  131614. }
  131615. }
  131616. }
  131617. /****************************************************************************
  131618. *****************************************************************************
  131619. ** Everything after this point is just test code.
  131620. */
  131621. #ifdef SQLITE_TEST
  131622. /* #include <stdio.h> */
  131623. /*
  131624. ** Function to query the hash-table of tokenizers (see README.tokenizers).
  131625. */
  131626. static int queryTestTokenizer(
  131627. sqlite3 *db,
  131628. const char *zName,
  131629. const sqlite3_tokenizer_module **pp
  131630. ){
  131631. int rc;
  131632. sqlite3_stmt *pStmt;
  131633. const char zSql[] = "SELECT fts3_tokenizer(?)";
  131634. *pp = 0;
  131635. rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
  131636. if( rc!=SQLITE_OK ){
  131637. return rc;
  131638. }
  131639. sqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC);
  131640. if( SQLITE_ROW==sqlite3_step(pStmt) ){
  131641. if( sqlite3_column_type(pStmt, 0)==SQLITE_BLOB ){
  131642. memcpy((void *)pp, sqlite3_column_blob(pStmt, 0), sizeof(*pp));
  131643. }
  131644. }
  131645. return sqlite3_finalize(pStmt);
  131646. }
  131647. /*
  131648. ** Return a pointer to a buffer containing a text representation of the
  131649. ** expression passed as the first argument. The buffer is obtained from
  131650. ** sqlite3_malloc(). It is the responsibility of the caller to use
  131651. ** sqlite3_free() to release the memory. If an OOM condition is encountered,
  131652. ** NULL is returned.
  131653. **
  131654. ** If the second argument is not NULL, then its contents are prepended to
  131655. ** the returned expression text and then freed using sqlite3_free().
  131656. */
  131657. static char *exprToString(Fts3Expr *pExpr, char *zBuf){
  131658. if( pExpr==0 ){
  131659. return sqlite3_mprintf("");
  131660. }
  131661. switch( pExpr->eType ){
  131662. case FTSQUERY_PHRASE: {
  131663. Fts3Phrase *pPhrase = pExpr->pPhrase;
  131664. int i;
  131665. zBuf = sqlite3_mprintf(
  131666. "%zPHRASE %d 0", zBuf, pPhrase->iColumn);
  131667. for(i=0; zBuf && i<pPhrase->nToken; i++){
  131668. zBuf = sqlite3_mprintf("%z %.*s%s", zBuf,
  131669. pPhrase->aToken[i].n, pPhrase->aToken[i].z,
  131670. (pPhrase->aToken[i].isPrefix?"+":"")
  131671. );
  131672. }
  131673. return zBuf;
  131674. }
  131675. case FTSQUERY_NEAR:
  131676. zBuf = sqlite3_mprintf("%zNEAR/%d ", zBuf, pExpr->nNear);
  131677. break;
  131678. case FTSQUERY_NOT:
  131679. zBuf = sqlite3_mprintf("%zNOT ", zBuf);
  131680. break;
  131681. case FTSQUERY_AND:
  131682. zBuf = sqlite3_mprintf("%zAND ", zBuf);
  131683. break;
  131684. case FTSQUERY_OR:
  131685. zBuf = sqlite3_mprintf("%zOR ", zBuf);
  131686. break;
  131687. }
  131688. if( zBuf ) zBuf = sqlite3_mprintf("%z{", zBuf);
  131689. if( zBuf ) zBuf = exprToString(pExpr->pLeft, zBuf);
  131690. if( zBuf ) zBuf = sqlite3_mprintf("%z} {", zBuf);
  131691. if( zBuf ) zBuf = exprToString(pExpr->pRight, zBuf);
  131692. if( zBuf ) zBuf = sqlite3_mprintf("%z}", zBuf);
  131693. return zBuf;
  131694. }
  131695. /*
  131696. ** This is the implementation of a scalar SQL function used to test the
  131697. ** expression parser. It should be called as follows:
  131698. **
  131699. ** fts3_exprtest(<tokenizer>, <expr>, <column 1>, ...);
  131700. **
  131701. ** The first argument, <tokenizer>, is the name of the fts3 tokenizer used
  131702. ** to parse the query expression (see README.tokenizers). The second argument
  131703. ** is the query expression to parse. Each subsequent argument is the name
  131704. ** of a column of the fts3 table that the query expression may refer to.
  131705. ** For example:
  131706. **
  131707. ** SELECT fts3_exprtest('simple', 'Bill col2:Bloggs', 'col1', 'col2');
  131708. */
  131709. static void fts3ExprTest(
  131710. sqlite3_context *context,
  131711. int argc,
  131712. sqlite3_value **argv
  131713. ){
  131714. sqlite3_tokenizer_module const *pModule = 0;
  131715. sqlite3_tokenizer *pTokenizer = 0;
  131716. int rc;
  131717. char **azCol = 0;
  131718. const char *zExpr;
  131719. int nExpr;
  131720. int nCol;
  131721. int ii;
  131722. Fts3Expr *pExpr;
  131723. char *zBuf = 0;
  131724. sqlite3 *db = sqlite3_context_db_handle(context);
  131725. if( argc<3 ){
  131726. sqlite3_result_error(context,
  131727. "Usage: fts3_exprtest(tokenizer, expr, col1, ...", -1
  131728. );
  131729. return;
  131730. }
  131731. rc = queryTestTokenizer(db,
  131732. (const char *)sqlite3_value_text(argv[0]), &pModule);
  131733. if( rc==SQLITE_NOMEM ){
  131734. sqlite3_result_error_nomem(context);
  131735. goto exprtest_out;
  131736. }else if( !pModule ){
  131737. sqlite3_result_error(context, "No such tokenizer module", -1);
  131738. goto exprtest_out;
  131739. }
  131740. rc = pModule->xCreate(0, 0, &pTokenizer);
  131741. assert( rc==SQLITE_NOMEM || rc==SQLITE_OK );
  131742. if( rc==SQLITE_NOMEM ){
  131743. sqlite3_result_error_nomem(context);
  131744. goto exprtest_out;
  131745. }
  131746. pTokenizer->pModule = pModule;
  131747. zExpr = (const char *)sqlite3_value_text(argv[1]);
  131748. nExpr = sqlite3_value_bytes(argv[1]);
  131749. nCol = argc-2;
  131750. azCol = (char **)sqlite3_malloc(nCol*sizeof(char *));
  131751. if( !azCol ){
  131752. sqlite3_result_error_nomem(context);
  131753. goto exprtest_out;
  131754. }
  131755. for(ii=0; ii<nCol; ii++){
  131756. azCol[ii] = (char *)sqlite3_value_text(argv[ii+2]);
  131757. }
  131758. if( sqlite3_user_data(context) ){
  131759. char *zDummy = 0;
  131760. rc = sqlite3Fts3ExprParse(
  131761. pTokenizer, 0, azCol, 0, nCol, nCol, zExpr, nExpr, &pExpr, &zDummy
  131762. );
  131763. assert( rc==SQLITE_OK || pExpr==0 );
  131764. sqlite3_free(zDummy);
  131765. }else{
  131766. rc = fts3ExprParseUnbalanced(
  131767. pTokenizer, 0, azCol, 0, nCol, nCol, zExpr, nExpr, &pExpr
  131768. );
  131769. }
  131770. if( rc!=SQLITE_OK && rc!=SQLITE_NOMEM ){
  131771. sqlite3Fts3ExprFree(pExpr);
  131772. sqlite3_result_error(context, "Error parsing expression", -1);
  131773. }else if( rc==SQLITE_NOMEM || !(zBuf = exprToString(pExpr, 0)) ){
  131774. sqlite3_result_error_nomem(context);
  131775. }else{
  131776. sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
  131777. sqlite3_free(zBuf);
  131778. }
  131779. sqlite3Fts3ExprFree(pExpr);
  131780. exprtest_out:
  131781. if( pModule && pTokenizer ){
  131782. rc = pModule->xDestroy(pTokenizer);
  131783. }
  131784. sqlite3_free(azCol);
  131785. }
  131786. /*
  131787. ** Register the query expression parser test function fts3_exprtest()
  131788. ** with database connection db.
  131789. */
  131790. SQLITE_PRIVATE int sqlite3Fts3ExprInitTestInterface(sqlite3* db){
  131791. int rc = sqlite3_create_function(
  131792. db, "fts3_exprtest", -1, SQLITE_UTF8, 0, fts3ExprTest, 0, 0
  131793. );
  131794. if( rc==SQLITE_OK ){
  131795. rc = sqlite3_create_function(db, "fts3_exprtest_rebalance",
  131796. -1, SQLITE_UTF8, (void *)1, fts3ExprTest, 0, 0
  131797. );
  131798. }
  131799. return rc;
  131800. }
  131801. #endif
  131802. #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
  131803. /************** End of fts3_expr.c *******************************************/
  131804. /************** Begin file fts3_hash.c ***************************************/
  131805. /*
  131806. ** 2001 September 22
  131807. **
  131808. ** The author disclaims copyright to this source code. In place of
  131809. ** a legal notice, here is a blessing:
  131810. **
  131811. ** May you do good and not evil.
  131812. ** May you find forgiveness for yourself and forgive others.
  131813. ** May you share freely, never taking more than you give.
  131814. **
  131815. *************************************************************************
  131816. ** This is the implementation of generic hash-tables used in SQLite.
  131817. ** We've modified it slightly to serve as a standalone hash table
  131818. ** implementation for the full-text indexing module.
  131819. */
  131820. /*
  131821. ** The code in this file is only compiled if:
  131822. **
  131823. ** * The FTS3 module is being built as an extension
  131824. ** (in which case SQLITE_CORE is not defined), or
  131825. **
  131826. ** * The FTS3 module is being built into the core of
  131827. ** SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
  131828. */
  131829. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  131830. /* #include <assert.h> */
  131831. /* #include <stdlib.h> */
  131832. /* #include <string.h> */
  131833. /*
  131834. ** Malloc and Free functions
  131835. */
  131836. static void *fts3HashMalloc(int n){
  131837. void *p = sqlite3_malloc(n);
  131838. if( p ){
  131839. memset(p, 0, n);
  131840. }
  131841. return p;
  131842. }
  131843. static void fts3HashFree(void *p){
  131844. sqlite3_free(p);
  131845. }
  131846. /* Turn bulk memory into a hash table object by initializing the
  131847. ** fields of the Hash structure.
  131848. **
  131849. ** "pNew" is a pointer to the hash table that is to be initialized.
  131850. ** keyClass is one of the constants
  131851. ** FTS3_HASH_BINARY or FTS3_HASH_STRING. The value of keyClass
  131852. ** determines what kind of key the hash table will use. "copyKey" is
  131853. ** true if the hash table should make its own private copy of keys and
  131854. ** false if it should just use the supplied pointer.
  131855. */
  131856. SQLITE_PRIVATE void sqlite3Fts3HashInit(Fts3Hash *pNew, char keyClass, char copyKey){
  131857. assert( pNew!=0 );
  131858. assert( keyClass>=FTS3_HASH_STRING && keyClass<=FTS3_HASH_BINARY );
  131859. pNew->keyClass = keyClass;
  131860. pNew->copyKey = copyKey;
  131861. pNew->first = 0;
  131862. pNew->count = 0;
  131863. pNew->htsize = 0;
  131864. pNew->ht = 0;
  131865. }
  131866. /* Remove all entries from a hash table. Reclaim all memory.
  131867. ** Call this routine to delete a hash table or to reset a hash table
  131868. ** to the empty state.
  131869. */
  131870. SQLITE_PRIVATE void sqlite3Fts3HashClear(Fts3Hash *pH){
  131871. Fts3HashElem *elem; /* For looping over all elements of the table */
  131872. assert( pH!=0 );
  131873. elem = pH->first;
  131874. pH->first = 0;
  131875. fts3HashFree(pH->ht);
  131876. pH->ht = 0;
  131877. pH->htsize = 0;
  131878. while( elem ){
  131879. Fts3HashElem *next_elem = elem->next;
  131880. if( pH->copyKey && elem->pKey ){
  131881. fts3HashFree(elem->pKey);
  131882. }
  131883. fts3HashFree(elem);
  131884. elem = next_elem;
  131885. }
  131886. pH->count = 0;
  131887. }
  131888. /*
  131889. ** Hash and comparison functions when the mode is FTS3_HASH_STRING
  131890. */
  131891. static int fts3StrHash(const void *pKey, int nKey){
  131892. const char *z = (const char *)pKey;
  131893. unsigned h = 0;
  131894. if( nKey<=0 ) nKey = (int) strlen(z);
  131895. while( nKey > 0 ){
  131896. h = (h<<3) ^ h ^ *z++;
  131897. nKey--;
  131898. }
  131899. return (int)(h & 0x7fffffff);
  131900. }
  131901. static int fts3StrCompare(const void *pKey1, int n1, const void *pKey2, int n2){
  131902. if( n1!=n2 ) return 1;
  131903. return strncmp((const char*)pKey1,(const char*)pKey2,n1);
  131904. }
  131905. /*
  131906. ** Hash and comparison functions when the mode is FTS3_HASH_BINARY
  131907. */
  131908. static int fts3BinHash(const void *pKey, int nKey){
  131909. int h = 0;
  131910. const char *z = (const char *)pKey;
  131911. while( nKey-- > 0 ){
  131912. h = (h<<3) ^ h ^ *(z++);
  131913. }
  131914. return h & 0x7fffffff;
  131915. }
  131916. static int fts3BinCompare(const void *pKey1, int n1, const void *pKey2, int n2){
  131917. if( n1!=n2 ) return 1;
  131918. return memcmp(pKey1,pKey2,n1);
  131919. }
  131920. /*
  131921. ** Return a pointer to the appropriate hash function given the key class.
  131922. **
  131923. ** The C syntax in this function definition may be unfamilar to some
  131924. ** programmers, so we provide the following additional explanation:
  131925. **
  131926. ** The name of the function is "ftsHashFunction". The function takes a
  131927. ** single parameter "keyClass". The return value of ftsHashFunction()
  131928. ** is a pointer to another function. Specifically, the return value
  131929. ** of ftsHashFunction() is a pointer to a function that takes two parameters
  131930. ** with types "const void*" and "int" and returns an "int".
  131931. */
  131932. static int (*ftsHashFunction(int keyClass))(const void*,int){
  131933. if( keyClass==FTS3_HASH_STRING ){
  131934. return &fts3StrHash;
  131935. }else{
  131936. assert( keyClass==FTS3_HASH_BINARY );
  131937. return &fts3BinHash;
  131938. }
  131939. }
  131940. /*
  131941. ** Return a pointer to the appropriate hash function given the key class.
  131942. **
  131943. ** For help in interpreted the obscure C code in the function definition,
  131944. ** see the header comment on the previous function.
  131945. */
  131946. static int (*ftsCompareFunction(int keyClass))(const void*,int,const void*,int){
  131947. if( keyClass==FTS3_HASH_STRING ){
  131948. return &fts3StrCompare;
  131949. }else{
  131950. assert( keyClass==FTS3_HASH_BINARY );
  131951. return &fts3BinCompare;
  131952. }
  131953. }
  131954. /* Link an element into the hash table
  131955. */
  131956. static void fts3HashInsertElement(
  131957. Fts3Hash *pH, /* The complete hash table */
  131958. struct _fts3ht *pEntry, /* The entry into which pNew is inserted */
  131959. Fts3HashElem *pNew /* The element to be inserted */
  131960. ){
  131961. Fts3HashElem *pHead; /* First element already in pEntry */
  131962. pHead = pEntry->chain;
  131963. if( pHead ){
  131964. pNew->next = pHead;
  131965. pNew->prev = pHead->prev;
  131966. if( pHead->prev ){ pHead->prev->next = pNew; }
  131967. else { pH->first = pNew; }
  131968. pHead->prev = pNew;
  131969. }else{
  131970. pNew->next = pH->first;
  131971. if( pH->first ){ pH->first->prev = pNew; }
  131972. pNew->prev = 0;
  131973. pH->first = pNew;
  131974. }
  131975. pEntry->count++;
  131976. pEntry->chain = pNew;
  131977. }
  131978. /* Resize the hash table so that it cantains "new_size" buckets.
  131979. ** "new_size" must be a power of 2. The hash table might fail
  131980. ** to resize if sqliteMalloc() fails.
  131981. **
  131982. ** Return non-zero if a memory allocation error occurs.
  131983. */
  131984. static int fts3Rehash(Fts3Hash *pH, int new_size){
  131985. struct _fts3ht *new_ht; /* The new hash table */
  131986. Fts3HashElem *elem, *next_elem; /* For looping over existing elements */
  131987. int (*xHash)(const void*,int); /* The hash function */
  131988. assert( (new_size & (new_size-1))==0 );
  131989. new_ht = (struct _fts3ht *)fts3HashMalloc( new_size*sizeof(struct _fts3ht) );
  131990. if( new_ht==0 ) return 1;
  131991. fts3HashFree(pH->ht);
  131992. pH->ht = new_ht;
  131993. pH->htsize = new_size;
  131994. xHash = ftsHashFunction(pH->keyClass);
  131995. for(elem=pH->first, pH->first=0; elem; elem = next_elem){
  131996. int h = (*xHash)(elem->pKey, elem->nKey) & (new_size-1);
  131997. next_elem = elem->next;
  131998. fts3HashInsertElement(pH, &new_ht[h], elem);
  131999. }
  132000. return 0;
  132001. }
  132002. /* This function (for internal use only) locates an element in an
  132003. ** hash table that matches the given key. The hash for this key has
  132004. ** already been computed and is passed as the 4th parameter.
  132005. */
  132006. static Fts3HashElem *fts3FindElementByHash(
  132007. const Fts3Hash *pH, /* The pH to be searched */
  132008. const void *pKey, /* The key we are searching for */
  132009. int nKey,
  132010. int h /* The hash for this key. */
  132011. ){
  132012. Fts3HashElem *elem; /* Used to loop thru the element list */
  132013. int count; /* Number of elements left to test */
  132014. int (*xCompare)(const void*,int,const void*,int); /* comparison function */
  132015. if( pH->ht ){
  132016. struct _fts3ht *pEntry = &pH->ht[h];
  132017. elem = pEntry->chain;
  132018. count = pEntry->count;
  132019. xCompare = ftsCompareFunction(pH->keyClass);
  132020. while( count-- && elem ){
  132021. if( (*xCompare)(elem->pKey,elem->nKey,pKey,nKey)==0 ){
  132022. return elem;
  132023. }
  132024. elem = elem->next;
  132025. }
  132026. }
  132027. return 0;
  132028. }
  132029. /* Remove a single entry from the hash table given a pointer to that
  132030. ** element and a hash on the element's key.
  132031. */
  132032. static void fts3RemoveElementByHash(
  132033. Fts3Hash *pH, /* The pH containing "elem" */
  132034. Fts3HashElem* elem, /* The element to be removed from the pH */
  132035. int h /* Hash value for the element */
  132036. ){
  132037. struct _fts3ht *pEntry;
  132038. if( elem->prev ){
  132039. elem->prev->next = elem->next;
  132040. }else{
  132041. pH->first = elem->next;
  132042. }
  132043. if( elem->next ){
  132044. elem->next->prev = elem->prev;
  132045. }
  132046. pEntry = &pH->ht[h];
  132047. if( pEntry->chain==elem ){
  132048. pEntry->chain = elem->next;
  132049. }
  132050. pEntry->count--;
  132051. if( pEntry->count<=0 ){
  132052. pEntry->chain = 0;
  132053. }
  132054. if( pH->copyKey && elem->pKey ){
  132055. fts3HashFree(elem->pKey);
  132056. }
  132057. fts3HashFree( elem );
  132058. pH->count--;
  132059. if( pH->count<=0 ){
  132060. assert( pH->first==0 );
  132061. assert( pH->count==0 );
  132062. fts3HashClear(pH);
  132063. }
  132064. }
  132065. SQLITE_PRIVATE Fts3HashElem *sqlite3Fts3HashFindElem(
  132066. const Fts3Hash *pH,
  132067. const void *pKey,
  132068. int nKey
  132069. ){
  132070. int h; /* A hash on key */
  132071. int (*xHash)(const void*,int); /* The hash function */
  132072. if( pH==0 || pH->ht==0 ) return 0;
  132073. xHash = ftsHashFunction(pH->keyClass);
  132074. assert( xHash!=0 );
  132075. h = (*xHash)(pKey,nKey);
  132076. assert( (pH->htsize & (pH->htsize-1))==0 );
  132077. return fts3FindElementByHash(pH,pKey,nKey, h & (pH->htsize-1));
  132078. }
  132079. /*
  132080. ** Attempt to locate an element of the hash table pH with a key
  132081. ** that matches pKey,nKey. Return the data for this element if it is
  132082. ** found, or NULL if there is no match.
  132083. */
  132084. SQLITE_PRIVATE void *sqlite3Fts3HashFind(const Fts3Hash *pH, const void *pKey, int nKey){
  132085. Fts3HashElem *pElem; /* The element that matches key (if any) */
  132086. pElem = sqlite3Fts3HashFindElem(pH, pKey, nKey);
  132087. return pElem ? pElem->data : 0;
  132088. }
  132089. /* Insert an element into the hash table pH. The key is pKey,nKey
  132090. ** and the data is "data".
  132091. **
  132092. ** If no element exists with a matching key, then a new
  132093. ** element is created. A copy of the key is made if the copyKey
  132094. ** flag is set. NULL is returned.
  132095. **
  132096. ** If another element already exists with the same key, then the
  132097. ** new data replaces the old data and the old data is returned.
  132098. ** The key is not copied in this instance. If a malloc fails, then
  132099. ** the new data is returned and the hash table is unchanged.
  132100. **
  132101. ** If the "data" parameter to this function is NULL, then the
  132102. ** element corresponding to "key" is removed from the hash table.
  132103. */
  132104. SQLITE_PRIVATE void *sqlite3Fts3HashInsert(
  132105. Fts3Hash *pH, /* The hash table to insert into */
  132106. const void *pKey, /* The key */
  132107. int nKey, /* Number of bytes in the key */
  132108. void *data /* The data */
  132109. ){
  132110. int hraw; /* Raw hash value of the key */
  132111. int h; /* the hash of the key modulo hash table size */
  132112. Fts3HashElem *elem; /* Used to loop thru the element list */
  132113. Fts3HashElem *new_elem; /* New element added to the pH */
  132114. int (*xHash)(const void*,int); /* The hash function */
  132115. assert( pH!=0 );
  132116. xHash = ftsHashFunction(pH->keyClass);
  132117. assert( xHash!=0 );
  132118. hraw = (*xHash)(pKey, nKey);
  132119. assert( (pH->htsize & (pH->htsize-1))==0 );
  132120. h = hraw & (pH->htsize-1);
  132121. elem = fts3FindElementByHash(pH,pKey,nKey,h);
  132122. if( elem ){
  132123. void *old_data = elem->data;
  132124. if( data==0 ){
  132125. fts3RemoveElementByHash(pH,elem,h);
  132126. }else{
  132127. elem->data = data;
  132128. }
  132129. return old_data;
  132130. }
  132131. if( data==0 ) return 0;
  132132. if( (pH->htsize==0 && fts3Rehash(pH,8))
  132133. || (pH->count>=pH->htsize && fts3Rehash(pH, pH->htsize*2))
  132134. ){
  132135. pH->count = 0;
  132136. return data;
  132137. }
  132138. assert( pH->htsize>0 );
  132139. new_elem = (Fts3HashElem*)fts3HashMalloc( sizeof(Fts3HashElem) );
  132140. if( new_elem==0 ) return data;
  132141. if( pH->copyKey && pKey!=0 ){
  132142. new_elem->pKey = fts3HashMalloc( nKey );
  132143. if( new_elem->pKey==0 ){
  132144. fts3HashFree(new_elem);
  132145. return data;
  132146. }
  132147. memcpy((void*)new_elem->pKey, pKey, nKey);
  132148. }else{
  132149. new_elem->pKey = (void*)pKey;
  132150. }
  132151. new_elem->nKey = nKey;
  132152. pH->count++;
  132153. assert( pH->htsize>0 );
  132154. assert( (pH->htsize & (pH->htsize-1))==0 );
  132155. h = hraw & (pH->htsize-1);
  132156. fts3HashInsertElement(pH, &pH->ht[h], new_elem);
  132157. new_elem->data = data;
  132158. return 0;
  132159. }
  132160. #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
  132161. /************** End of fts3_hash.c *******************************************/
  132162. /************** Begin file fts3_porter.c *************************************/
  132163. /*
  132164. ** 2006 September 30
  132165. **
  132166. ** The author disclaims copyright to this source code. In place of
  132167. ** a legal notice, here is a blessing:
  132168. **
  132169. ** May you do good and not evil.
  132170. ** May you find forgiveness for yourself and forgive others.
  132171. ** May you share freely, never taking more than you give.
  132172. **
  132173. *************************************************************************
  132174. ** Implementation of the full-text-search tokenizer that implements
  132175. ** a Porter stemmer.
  132176. */
  132177. /*
  132178. ** The code in this file is only compiled if:
  132179. **
  132180. ** * The FTS3 module is being built as an extension
  132181. ** (in which case SQLITE_CORE is not defined), or
  132182. **
  132183. ** * The FTS3 module is being built into the core of
  132184. ** SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
  132185. */
  132186. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  132187. /* #include <assert.h> */
  132188. /* #include <stdlib.h> */
  132189. /* #include <stdio.h> */
  132190. /* #include <string.h> */
  132191. /*
  132192. ** Class derived from sqlite3_tokenizer
  132193. */
  132194. typedef struct porter_tokenizer {
  132195. sqlite3_tokenizer base; /* Base class */
  132196. } porter_tokenizer;
  132197. /*
  132198. ** Class derived from sqlite3_tokenizer_cursor
  132199. */
  132200. typedef struct porter_tokenizer_cursor {
  132201. sqlite3_tokenizer_cursor base;
  132202. const char *zInput; /* input we are tokenizing */
  132203. int nInput; /* size of the input */
  132204. int iOffset; /* current position in zInput */
  132205. int iToken; /* index of next token to be returned */
  132206. char *zToken; /* storage for current token */
  132207. int nAllocated; /* space allocated to zToken buffer */
  132208. } porter_tokenizer_cursor;
  132209. /*
  132210. ** Create a new tokenizer instance.
  132211. */
  132212. static int porterCreate(
  132213. int argc, const char * const *argv,
  132214. sqlite3_tokenizer **ppTokenizer
  132215. ){
  132216. porter_tokenizer *t;
  132217. UNUSED_PARAMETER(argc);
  132218. UNUSED_PARAMETER(argv);
  132219. t = (porter_tokenizer *) sqlite3_malloc(sizeof(*t));
  132220. if( t==NULL ) return SQLITE_NOMEM;
  132221. memset(t, 0, sizeof(*t));
  132222. *ppTokenizer = &t->base;
  132223. return SQLITE_OK;
  132224. }
  132225. /*
  132226. ** Destroy a tokenizer
  132227. */
  132228. static int porterDestroy(sqlite3_tokenizer *pTokenizer){
  132229. sqlite3_free(pTokenizer);
  132230. return SQLITE_OK;
  132231. }
  132232. /*
  132233. ** Prepare to begin tokenizing a particular string. The input
  132234. ** string to be tokenized is zInput[0..nInput-1]. A cursor
  132235. ** used to incrementally tokenize this string is returned in
  132236. ** *ppCursor.
  132237. */
  132238. static int porterOpen(
  132239. sqlite3_tokenizer *pTokenizer, /* The tokenizer */
  132240. const char *zInput, int nInput, /* String to be tokenized */
  132241. sqlite3_tokenizer_cursor **ppCursor /* OUT: Tokenization cursor */
  132242. ){
  132243. porter_tokenizer_cursor *c;
  132244. UNUSED_PARAMETER(pTokenizer);
  132245. c = (porter_tokenizer_cursor *) sqlite3_malloc(sizeof(*c));
  132246. if( c==NULL ) return SQLITE_NOMEM;
  132247. c->zInput = zInput;
  132248. if( zInput==0 ){
  132249. c->nInput = 0;
  132250. }else if( nInput<0 ){
  132251. c->nInput = (int)strlen(zInput);
  132252. }else{
  132253. c->nInput = nInput;
  132254. }
  132255. c->iOffset = 0; /* start tokenizing at the beginning */
  132256. c->iToken = 0;
  132257. c->zToken = NULL; /* no space allocated, yet. */
  132258. c->nAllocated = 0;
  132259. *ppCursor = &c->base;
  132260. return SQLITE_OK;
  132261. }
  132262. /*
  132263. ** Close a tokenization cursor previously opened by a call to
  132264. ** porterOpen() above.
  132265. */
  132266. static int porterClose(sqlite3_tokenizer_cursor *pCursor){
  132267. porter_tokenizer_cursor *c = (porter_tokenizer_cursor *) pCursor;
  132268. sqlite3_free(c->zToken);
  132269. sqlite3_free(c);
  132270. return SQLITE_OK;
  132271. }
  132272. /*
  132273. ** Vowel or consonant
  132274. */
  132275. static const char cType[] = {
  132276. 0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0,
  132277. 1, 1, 1, 2, 1
  132278. };
  132279. /*
  132280. ** isConsonant() and isVowel() determine if their first character in
  132281. ** the string they point to is a consonant or a vowel, according
  132282. ** to Porter ruls.
  132283. **
  132284. ** A consonate is any letter other than 'a', 'e', 'i', 'o', or 'u'.
  132285. ** 'Y' is a consonant unless it follows another consonant,
  132286. ** in which case it is a vowel.
  132287. **
  132288. ** In these routine, the letters are in reverse order. So the 'y' rule
  132289. ** is that 'y' is a consonant unless it is followed by another
  132290. ** consonent.
  132291. */
  132292. static int isVowel(const char*);
  132293. static int isConsonant(const char *z){
  132294. int j;
  132295. char x = *z;
  132296. if( x==0 ) return 0;
  132297. assert( x>='a' && x<='z' );
  132298. j = cType[x-'a'];
  132299. if( j<2 ) return j;
  132300. return z[1]==0 || isVowel(z + 1);
  132301. }
  132302. static int isVowel(const char *z){
  132303. int j;
  132304. char x = *z;
  132305. if( x==0 ) return 0;
  132306. assert( x>='a' && x<='z' );
  132307. j = cType[x-'a'];
  132308. if( j<2 ) return 1-j;
  132309. return isConsonant(z + 1);
  132310. }
  132311. /*
  132312. ** Let any sequence of one or more vowels be represented by V and let
  132313. ** C be sequence of one or more consonants. Then every word can be
  132314. ** represented as:
  132315. **
  132316. ** [C] (VC){m} [V]
  132317. **
  132318. ** In prose: A word is an optional consonant followed by zero or
  132319. ** vowel-consonant pairs followed by an optional vowel. "m" is the
  132320. ** number of vowel consonant pairs. This routine computes the value
  132321. ** of m for the first i bytes of a word.
  132322. **
  132323. ** Return true if the m-value for z is 1 or more. In other words,
  132324. ** return true if z contains at least one vowel that is followed
  132325. ** by a consonant.
  132326. **
  132327. ** In this routine z[] is in reverse order. So we are really looking
  132328. ** for an instance of a consonant followed by a vowel.
  132329. */
  132330. static int m_gt_0(const char *z){
  132331. while( isVowel(z) ){ z++; }
  132332. if( *z==0 ) return 0;
  132333. while( isConsonant(z) ){ z++; }
  132334. return *z!=0;
  132335. }
  132336. /* Like mgt0 above except we are looking for a value of m which is
  132337. ** exactly 1
  132338. */
  132339. static int m_eq_1(const char *z){
  132340. while( isVowel(z) ){ z++; }
  132341. if( *z==0 ) return 0;
  132342. while( isConsonant(z) ){ z++; }
  132343. if( *z==0 ) return 0;
  132344. while( isVowel(z) ){ z++; }
  132345. if( *z==0 ) return 1;
  132346. while( isConsonant(z) ){ z++; }
  132347. return *z==0;
  132348. }
  132349. /* Like mgt0 above except we are looking for a value of m>1 instead
  132350. ** or m>0
  132351. */
  132352. static int m_gt_1(const char *z){
  132353. while( isVowel(z) ){ z++; }
  132354. if( *z==0 ) return 0;
  132355. while( isConsonant(z) ){ z++; }
  132356. if( *z==0 ) return 0;
  132357. while( isVowel(z) ){ z++; }
  132358. if( *z==0 ) return 0;
  132359. while( isConsonant(z) ){ z++; }
  132360. return *z!=0;
  132361. }
  132362. /*
  132363. ** Return TRUE if there is a vowel anywhere within z[0..n-1]
  132364. */
  132365. static int hasVowel(const char *z){
  132366. while( isConsonant(z) ){ z++; }
  132367. return *z!=0;
  132368. }
  132369. /*
  132370. ** Return TRUE if the word ends in a double consonant.
  132371. **
  132372. ** The text is reversed here. So we are really looking at
  132373. ** the first two characters of z[].
  132374. */
  132375. static int doubleConsonant(const char *z){
  132376. return isConsonant(z) && z[0]==z[1];
  132377. }
  132378. /*
  132379. ** Return TRUE if the word ends with three letters which
  132380. ** are consonant-vowel-consonent and where the final consonant
  132381. ** is not 'w', 'x', or 'y'.
  132382. **
  132383. ** The word is reversed here. So we are really checking the
  132384. ** first three letters and the first one cannot be in [wxy].
  132385. */
  132386. static int star_oh(const char *z){
  132387. return
  132388. isConsonant(z) &&
  132389. z[0]!='w' && z[0]!='x' && z[0]!='y' &&
  132390. isVowel(z+1) &&
  132391. isConsonant(z+2);
  132392. }
  132393. /*
  132394. ** If the word ends with zFrom and xCond() is true for the stem
  132395. ** of the word that preceeds the zFrom ending, then change the
  132396. ** ending to zTo.
  132397. **
  132398. ** The input word *pz and zFrom are both in reverse order. zTo
  132399. ** is in normal order.
  132400. **
  132401. ** Return TRUE if zFrom matches. Return FALSE if zFrom does not
  132402. ** match. Not that TRUE is returned even if xCond() fails and
  132403. ** no substitution occurs.
  132404. */
  132405. static int stem(
  132406. char **pz, /* The word being stemmed (Reversed) */
  132407. const char *zFrom, /* If the ending matches this... (Reversed) */
  132408. const char *zTo, /* ... change the ending to this (not reversed) */
  132409. int (*xCond)(const char*) /* Condition that must be true */
  132410. ){
  132411. char *z = *pz;
  132412. while( *zFrom && *zFrom==*z ){ z++; zFrom++; }
  132413. if( *zFrom!=0 ) return 0;
  132414. if( xCond && !xCond(z) ) return 1;
  132415. while( *zTo ){
  132416. *(--z) = *(zTo++);
  132417. }
  132418. *pz = z;
  132419. return 1;
  132420. }
  132421. /*
  132422. ** This is the fallback stemmer used when the porter stemmer is
  132423. ** inappropriate. The input word is copied into the output with
  132424. ** US-ASCII case folding. If the input word is too long (more
  132425. ** than 20 bytes if it contains no digits or more than 6 bytes if
  132426. ** it contains digits) then word is truncated to 20 or 6 bytes
  132427. ** by taking 10 or 3 bytes from the beginning and end.
  132428. */
  132429. static void copy_stemmer(const char *zIn, int nIn, char *zOut, int *pnOut){
  132430. int i, mx, j;
  132431. int hasDigit = 0;
  132432. for(i=0; i<nIn; i++){
  132433. char c = zIn[i];
  132434. if( c>='A' && c<='Z' ){
  132435. zOut[i] = c - 'A' + 'a';
  132436. }else{
  132437. if( c>='0' && c<='9' ) hasDigit = 1;
  132438. zOut[i] = c;
  132439. }
  132440. }
  132441. mx = hasDigit ? 3 : 10;
  132442. if( nIn>mx*2 ){
  132443. for(j=mx, i=nIn-mx; i<nIn; i++, j++){
  132444. zOut[j] = zOut[i];
  132445. }
  132446. i = j;
  132447. }
  132448. zOut[i] = 0;
  132449. *pnOut = i;
  132450. }
  132451. /*
  132452. ** Stem the input word zIn[0..nIn-1]. Store the output in zOut.
  132453. ** zOut is at least big enough to hold nIn bytes. Write the actual
  132454. ** size of the output word (exclusive of the '\0' terminator) into *pnOut.
  132455. **
  132456. ** Any upper-case characters in the US-ASCII character set ([A-Z])
  132457. ** are converted to lower case. Upper-case UTF characters are
  132458. ** unchanged.
  132459. **
  132460. ** Words that are longer than about 20 bytes are stemmed by retaining
  132461. ** a few bytes from the beginning and the end of the word. If the
  132462. ** word contains digits, 3 bytes are taken from the beginning and
  132463. ** 3 bytes from the end. For long words without digits, 10 bytes
  132464. ** are taken from each end. US-ASCII case folding still applies.
  132465. **
  132466. ** If the input word contains not digits but does characters not
  132467. ** in [a-zA-Z] then no stemming is attempted and this routine just
  132468. ** copies the input into the input into the output with US-ASCII
  132469. ** case folding.
  132470. **
  132471. ** Stemming never increases the length of the word. So there is
  132472. ** no chance of overflowing the zOut buffer.
  132473. */
  132474. static void porter_stemmer(const char *zIn, int nIn, char *zOut, int *pnOut){
  132475. int i, j;
  132476. char zReverse[28];
  132477. char *z, *z2;
  132478. if( nIn<3 || nIn>=(int)sizeof(zReverse)-7 ){
  132479. /* The word is too big or too small for the porter stemmer.
  132480. ** Fallback to the copy stemmer */
  132481. copy_stemmer(zIn, nIn, zOut, pnOut);
  132482. return;
  132483. }
  132484. for(i=0, j=sizeof(zReverse)-6; i<nIn; i++, j--){
  132485. char c = zIn[i];
  132486. if( c>='A' && c<='Z' ){
  132487. zReverse[j] = c + 'a' - 'A';
  132488. }else if( c>='a' && c<='z' ){
  132489. zReverse[j] = c;
  132490. }else{
  132491. /* The use of a character not in [a-zA-Z] means that we fallback
  132492. ** to the copy stemmer */
  132493. copy_stemmer(zIn, nIn, zOut, pnOut);
  132494. return;
  132495. }
  132496. }
  132497. memset(&zReverse[sizeof(zReverse)-5], 0, 5);
  132498. z = &zReverse[j+1];
  132499. /* Step 1a */
  132500. if( z[0]=='s' ){
  132501. if(
  132502. !stem(&z, "sess", "ss", 0) &&
  132503. !stem(&z, "sei", "i", 0) &&
  132504. !stem(&z, "ss", "ss", 0)
  132505. ){
  132506. z++;
  132507. }
  132508. }
  132509. /* Step 1b */
  132510. z2 = z;
  132511. if( stem(&z, "dee", "ee", m_gt_0) ){
  132512. /* Do nothing. The work was all in the test */
  132513. }else if(
  132514. (stem(&z, "gni", "", hasVowel) || stem(&z, "de", "", hasVowel))
  132515. && z!=z2
  132516. ){
  132517. if( stem(&z, "ta", "ate", 0) ||
  132518. stem(&z, "lb", "ble", 0) ||
  132519. stem(&z, "zi", "ize", 0) ){
  132520. /* Do nothing. The work was all in the test */
  132521. }else if( doubleConsonant(z) && (*z!='l' && *z!='s' && *z!='z') ){
  132522. z++;
  132523. }else if( m_eq_1(z) && star_oh(z) ){
  132524. *(--z) = 'e';
  132525. }
  132526. }
  132527. /* Step 1c */
  132528. if( z[0]=='y' && hasVowel(z+1) ){
  132529. z[0] = 'i';
  132530. }
  132531. /* Step 2 */
  132532. switch( z[1] ){
  132533. case 'a':
  132534. if( !stem(&z, "lanoita", "ate", m_gt_0) ){
  132535. stem(&z, "lanoit", "tion", m_gt_0);
  132536. }
  132537. break;
  132538. case 'c':
  132539. if( !stem(&z, "icne", "ence", m_gt_0) ){
  132540. stem(&z, "icna", "ance", m_gt_0);
  132541. }
  132542. break;
  132543. case 'e':
  132544. stem(&z, "rezi", "ize", m_gt_0);
  132545. break;
  132546. case 'g':
  132547. stem(&z, "igol", "log", m_gt_0);
  132548. break;
  132549. case 'l':
  132550. if( !stem(&z, "ilb", "ble", m_gt_0)
  132551. && !stem(&z, "illa", "al", m_gt_0)
  132552. && !stem(&z, "iltne", "ent", m_gt_0)
  132553. && !stem(&z, "ile", "e", m_gt_0)
  132554. ){
  132555. stem(&z, "ilsuo", "ous", m_gt_0);
  132556. }
  132557. break;
  132558. case 'o':
  132559. if( !stem(&z, "noitazi", "ize", m_gt_0)
  132560. && !stem(&z, "noita", "ate", m_gt_0)
  132561. ){
  132562. stem(&z, "rota", "ate", m_gt_0);
  132563. }
  132564. break;
  132565. case 's':
  132566. if( !stem(&z, "msila", "al", m_gt_0)
  132567. && !stem(&z, "ssenevi", "ive", m_gt_0)
  132568. && !stem(&z, "ssenluf", "ful", m_gt_0)
  132569. ){
  132570. stem(&z, "ssensuo", "ous", m_gt_0);
  132571. }
  132572. break;
  132573. case 't':
  132574. if( !stem(&z, "itila", "al", m_gt_0)
  132575. && !stem(&z, "itivi", "ive", m_gt_0)
  132576. ){
  132577. stem(&z, "itilib", "ble", m_gt_0);
  132578. }
  132579. break;
  132580. }
  132581. /* Step 3 */
  132582. switch( z[0] ){
  132583. case 'e':
  132584. if( !stem(&z, "etaci", "ic", m_gt_0)
  132585. && !stem(&z, "evita", "", m_gt_0)
  132586. ){
  132587. stem(&z, "ezila", "al", m_gt_0);
  132588. }
  132589. break;
  132590. case 'i':
  132591. stem(&z, "itici", "ic", m_gt_0);
  132592. break;
  132593. case 'l':
  132594. if( !stem(&z, "laci", "ic", m_gt_0) ){
  132595. stem(&z, "luf", "", m_gt_0);
  132596. }
  132597. break;
  132598. case 's':
  132599. stem(&z, "ssen", "", m_gt_0);
  132600. break;
  132601. }
  132602. /* Step 4 */
  132603. switch( z[1] ){
  132604. case 'a':
  132605. if( z[0]=='l' && m_gt_1(z+2) ){
  132606. z += 2;
  132607. }
  132608. break;
  132609. case 'c':
  132610. if( z[0]=='e' && z[2]=='n' && (z[3]=='a' || z[3]=='e') && m_gt_1(z+4) ){
  132611. z += 4;
  132612. }
  132613. break;
  132614. case 'e':
  132615. if( z[0]=='r' && m_gt_1(z+2) ){
  132616. z += 2;
  132617. }
  132618. break;
  132619. case 'i':
  132620. if( z[0]=='c' && m_gt_1(z+2) ){
  132621. z += 2;
  132622. }
  132623. break;
  132624. case 'l':
  132625. if( z[0]=='e' && z[2]=='b' && (z[3]=='a' || z[3]=='i') && m_gt_1(z+4) ){
  132626. z += 4;
  132627. }
  132628. break;
  132629. case 'n':
  132630. if( z[0]=='t' ){
  132631. if( z[2]=='a' ){
  132632. if( m_gt_1(z+3) ){
  132633. z += 3;
  132634. }
  132635. }else if( z[2]=='e' ){
  132636. if( !stem(&z, "tneme", "", m_gt_1)
  132637. && !stem(&z, "tnem", "", m_gt_1)
  132638. ){
  132639. stem(&z, "tne", "", m_gt_1);
  132640. }
  132641. }
  132642. }
  132643. break;
  132644. case 'o':
  132645. if( z[0]=='u' ){
  132646. if( m_gt_1(z+2) ){
  132647. z += 2;
  132648. }
  132649. }else if( z[3]=='s' || z[3]=='t' ){
  132650. stem(&z, "noi", "", m_gt_1);
  132651. }
  132652. break;
  132653. case 's':
  132654. if( z[0]=='m' && z[2]=='i' && m_gt_1(z+3) ){
  132655. z += 3;
  132656. }
  132657. break;
  132658. case 't':
  132659. if( !stem(&z, "eta", "", m_gt_1) ){
  132660. stem(&z, "iti", "", m_gt_1);
  132661. }
  132662. break;
  132663. case 'u':
  132664. if( z[0]=='s' && z[2]=='o' && m_gt_1(z+3) ){
  132665. z += 3;
  132666. }
  132667. break;
  132668. case 'v':
  132669. case 'z':
  132670. if( z[0]=='e' && z[2]=='i' && m_gt_1(z+3) ){
  132671. z += 3;
  132672. }
  132673. break;
  132674. }
  132675. /* Step 5a */
  132676. if( z[0]=='e' ){
  132677. if( m_gt_1(z+1) ){
  132678. z++;
  132679. }else if( m_eq_1(z+1) && !star_oh(z+1) ){
  132680. z++;
  132681. }
  132682. }
  132683. /* Step 5b */
  132684. if( m_gt_1(z) && z[0]=='l' && z[1]=='l' ){
  132685. z++;
  132686. }
  132687. /* z[] is now the stemmed word in reverse order. Flip it back
  132688. ** around into forward order and return.
  132689. */
  132690. *pnOut = i = (int)strlen(z);
  132691. zOut[i] = 0;
  132692. while( *z ){
  132693. zOut[--i] = *(z++);
  132694. }
  132695. }
  132696. /*
  132697. ** Characters that can be part of a token. We assume any character
  132698. ** whose value is greater than 0x80 (any UTF character) can be
  132699. ** part of a token. In other words, delimiters all must have
  132700. ** values of 0x7f or lower.
  132701. */
  132702. static const char porterIdChar[] = {
  132703. /* x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 xA xB xC xD xE xF */
  132704. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, /* 3x */
  132705. 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 4x */
  132706. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, /* 5x */
  132707. 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 6x */
  132708. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, /* 7x */
  132709. };
  132710. #define isDelim(C) (((ch=C)&0x80)==0 && (ch<0x30 || !porterIdChar[ch-0x30]))
  132711. /*
  132712. ** Extract the next token from a tokenization cursor. The cursor must
  132713. ** have been opened by a prior call to porterOpen().
  132714. */
  132715. static int porterNext(
  132716. sqlite3_tokenizer_cursor *pCursor, /* Cursor returned by porterOpen */
  132717. const char **pzToken, /* OUT: *pzToken is the token text */
  132718. int *pnBytes, /* OUT: Number of bytes in token */
  132719. int *piStartOffset, /* OUT: Starting offset of token */
  132720. int *piEndOffset, /* OUT: Ending offset of token */
  132721. int *piPosition /* OUT: Position integer of token */
  132722. ){
  132723. porter_tokenizer_cursor *c = (porter_tokenizer_cursor *) pCursor;
  132724. const char *z = c->zInput;
  132725. while( c->iOffset<c->nInput ){
  132726. int iStartOffset, ch;
  132727. /* Scan past delimiter characters */
  132728. while( c->iOffset<c->nInput && isDelim(z[c->iOffset]) ){
  132729. c->iOffset++;
  132730. }
  132731. /* Count non-delimiter characters. */
  132732. iStartOffset = c->iOffset;
  132733. while( c->iOffset<c->nInput && !isDelim(z[c->iOffset]) ){
  132734. c->iOffset++;
  132735. }
  132736. if( c->iOffset>iStartOffset ){
  132737. int n = c->iOffset-iStartOffset;
  132738. if( n>c->nAllocated ){
  132739. char *pNew;
  132740. c->nAllocated = n+20;
  132741. pNew = sqlite3_realloc(c->zToken, c->nAllocated);
  132742. if( !pNew ) return SQLITE_NOMEM;
  132743. c->zToken = pNew;
  132744. }
  132745. porter_stemmer(&z[iStartOffset], n, c->zToken, pnBytes);
  132746. *pzToken = c->zToken;
  132747. *piStartOffset = iStartOffset;
  132748. *piEndOffset = c->iOffset;
  132749. *piPosition = c->iToken++;
  132750. return SQLITE_OK;
  132751. }
  132752. }
  132753. return SQLITE_DONE;
  132754. }
  132755. /*
  132756. ** The set of routines that implement the porter-stemmer tokenizer
  132757. */
  132758. static const sqlite3_tokenizer_module porterTokenizerModule = {
  132759. 0,
  132760. porterCreate,
  132761. porterDestroy,
  132762. porterOpen,
  132763. porterClose,
  132764. porterNext,
  132765. 0
  132766. };
  132767. /*
  132768. ** Allocate a new porter tokenizer. Return a pointer to the new
  132769. ** tokenizer in *ppModule
  132770. */
  132771. SQLITE_PRIVATE void sqlite3Fts3PorterTokenizerModule(
  132772. sqlite3_tokenizer_module const**ppModule
  132773. ){
  132774. *ppModule = &porterTokenizerModule;
  132775. }
  132776. #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
  132777. /************** End of fts3_porter.c *****************************************/
  132778. /************** Begin file fts3_tokenizer.c **********************************/
  132779. /*
  132780. ** 2007 June 22
  132781. **
  132782. ** The author disclaims copyright to this source code. In place of
  132783. ** a legal notice, here is a blessing:
  132784. **
  132785. ** May you do good and not evil.
  132786. ** May you find forgiveness for yourself and forgive others.
  132787. ** May you share freely, never taking more than you give.
  132788. **
  132789. ******************************************************************************
  132790. **
  132791. ** This is part of an SQLite module implementing full-text search.
  132792. ** This particular file implements the generic tokenizer interface.
  132793. */
  132794. /*
  132795. ** The code in this file is only compiled if:
  132796. **
  132797. ** * The FTS3 module is being built as an extension
  132798. ** (in which case SQLITE_CORE is not defined), or
  132799. **
  132800. ** * The FTS3 module is being built into the core of
  132801. ** SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
  132802. */
  132803. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  132804. /* #include <assert.h> */
  132805. /* #include <string.h> */
  132806. /*
  132807. ** Implementation of the SQL scalar function for accessing the underlying
  132808. ** hash table. This function may be called as follows:
  132809. **
  132810. ** SELECT <function-name>(<key-name>);
  132811. ** SELECT <function-name>(<key-name>, <pointer>);
  132812. **
  132813. ** where <function-name> is the name passed as the second argument
  132814. ** to the sqlite3Fts3InitHashTable() function (e.g. 'fts3_tokenizer').
  132815. **
  132816. ** If the <pointer> argument is specified, it must be a blob value
  132817. ** containing a pointer to be stored as the hash data corresponding
  132818. ** to the string <key-name>. If <pointer> is not specified, then
  132819. ** the string <key-name> must already exist in the has table. Otherwise,
  132820. ** an error is returned.
  132821. **
  132822. ** Whether or not the <pointer> argument is specified, the value returned
  132823. ** is a blob containing the pointer stored as the hash data corresponding
  132824. ** to string <key-name> (after the hash-table is updated, if applicable).
  132825. */
  132826. static void scalarFunc(
  132827. sqlite3_context *context,
  132828. int argc,
  132829. sqlite3_value **argv
  132830. ){
  132831. Fts3Hash *pHash;
  132832. void *pPtr = 0;
  132833. const unsigned char *zName;
  132834. int nName;
  132835. assert( argc==1 || argc==2 );
  132836. pHash = (Fts3Hash *)sqlite3_user_data(context);
  132837. zName = sqlite3_value_text(argv[0]);
  132838. nName = sqlite3_value_bytes(argv[0])+1;
  132839. if( argc==2 ){
  132840. void *pOld;
  132841. int n = sqlite3_value_bytes(argv[1]);
  132842. if( zName==0 || n!=sizeof(pPtr) ){
  132843. sqlite3_result_error(context, "argument type mismatch", -1);
  132844. return;
  132845. }
  132846. pPtr = *(void **)sqlite3_value_blob(argv[1]);
  132847. pOld = sqlite3Fts3HashInsert(pHash, (void *)zName, nName, pPtr);
  132848. if( pOld==pPtr ){
  132849. sqlite3_result_error(context, "out of memory", -1);
  132850. return;
  132851. }
  132852. }else{
  132853. if( zName ){
  132854. pPtr = sqlite3Fts3HashFind(pHash, zName, nName);
  132855. }
  132856. if( !pPtr ){
  132857. char *zErr = sqlite3_mprintf("unknown tokenizer: %s", zName);
  132858. sqlite3_result_error(context, zErr, -1);
  132859. sqlite3_free(zErr);
  132860. return;
  132861. }
  132862. }
  132863. sqlite3_result_blob(context, (void *)&pPtr, sizeof(pPtr), SQLITE_TRANSIENT);
  132864. }
  132865. SQLITE_PRIVATE int sqlite3Fts3IsIdChar(char c){
  132866. static const char isFtsIdChar[] = {
  132867. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0x */
  132868. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 1x */
  132869. 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 2x */
  132870. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, /* 3x */
  132871. 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 4x */
  132872. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, /* 5x */
  132873. 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 6x */
  132874. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, /* 7x */
  132875. };
  132876. return (c&0x80 || isFtsIdChar[(int)(c)]);
  132877. }
  132878. SQLITE_PRIVATE const char *sqlite3Fts3NextToken(const char *zStr, int *pn){
  132879. const char *z1;
  132880. const char *z2 = 0;
  132881. /* Find the start of the next token. */
  132882. z1 = zStr;
  132883. while( z2==0 ){
  132884. char c = *z1;
  132885. switch( c ){
  132886. case '\0': return 0; /* No more tokens here */
  132887. case '\'':
  132888. case '"':
  132889. case '`': {
  132890. z2 = z1;
  132891. while( *++z2 && (*z2!=c || *++z2==c) );
  132892. break;
  132893. }
  132894. case '[':
  132895. z2 = &z1[1];
  132896. while( *z2 && z2[0]!=']' ) z2++;
  132897. if( *z2 ) z2++;
  132898. break;
  132899. default:
  132900. if( sqlite3Fts3IsIdChar(*z1) ){
  132901. z2 = &z1[1];
  132902. while( sqlite3Fts3IsIdChar(*z2) ) z2++;
  132903. }else{
  132904. z1++;
  132905. }
  132906. }
  132907. }
  132908. *pn = (int)(z2-z1);
  132909. return z1;
  132910. }
  132911. SQLITE_PRIVATE int sqlite3Fts3InitTokenizer(
  132912. Fts3Hash *pHash, /* Tokenizer hash table */
  132913. const char *zArg, /* Tokenizer name */
  132914. sqlite3_tokenizer **ppTok, /* OUT: Tokenizer (if applicable) */
  132915. char **pzErr /* OUT: Set to malloced error message */
  132916. ){
  132917. int rc;
  132918. char *z = (char *)zArg;
  132919. int n = 0;
  132920. char *zCopy;
  132921. char *zEnd; /* Pointer to nul-term of zCopy */
  132922. sqlite3_tokenizer_module *m;
  132923. zCopy = sqlite3_mprintf("%s", zArg);
  132924. if( !zCopy ) return SQLITE_NOMEM;
  132925. zEnd = &zCopy[strlen(zCopy)];
  132926. z = (char *)sqlite3Fts3NextToken(zCopy, &n);
  132927. if( z==0 ){
  132928. assert( n==0 );
  132929. z = zCopy;
  132930. }
  132931. z[n] = '\0';
  132932. sqlite3Fts3Dequote(z);
  132933. m = (sqlite3_tokenizer_module *)sqlite3Fts3HashFind(pHash,z,(int)strlen(z)+1);
  132934. if( !m ){
  132935. sqlite3Fts3ErrMsg(pzErr, "unknown tokenizer: %s", z);
  132936. rc = SQLITE_ERROR;
  132937. }else{
  132938. char const **aArg = 0;
  132939. int iArg = 0;
  132940. z = &z[n+1];
  132941. while( z<zEnd && (NULL!=(z = (char *)sqlite3Fts3NextToken(z, &n))) ){
  132942. int nNew = sizeof(char *)*(iArg+1);
  132943. char const **aNew = (const char **)sqlite3_realloc((void *)aArg, nNew);
  132944. if( !aNew ){
  132945. sqlite3_free(zCopy);
  132946. sqlite3_free((void *)aArg);
  132947. return SQLITE_NOMEM;
  132948. }
  132949. aArg = aNew;
  132950. aArg[iArg++] = z;
  132951. z[n] = '\0';
  132952. sqlite3Fts3Dequote(z);
  132953. z = &z[n+1];
  132954. }
  132955. rc = m->xCreate(iArg, aArg, ppTok);
  132956. assert( rc!=SQLITE_OK || *ppTok );
  132957. if( rc!=SQLITE_OK ){
  132958. sqlite3Fts3ErrMsg(pzErr, "unknown tokenizer");
  132959. }else{
  132960. (*ppTok)->pModule = m;
  132961. }
  132962. sqlite3_free((void *)aArg);
  132963. }
  132964. sqlite3_free(zCopy);
  132965. return rc;
  132966. }
  132967. #ifdef SQLITE_TEST
  132968. #include <tcl.h>
  132969. /* #include <string.h> */
  132970. /*
  132971. ** Implementation of a special SQL scalar function for testing tokenizers
  132972. ** designed to be used in concert with the Tcl testing framework. This
  132973. ** function must be called with two or more arguments:
  132974. **
  132975. ** SELECT <function-name>(<key-name>, ..., <input-string>);
  132976. **
  132977. ** where <function-name> is the name passed as the second argument
  132978. ** to the sqlite3Fts3InitHashTable() function (e.g. 'fts3_tokenizer')
  132979. ** concatenated with the string '_test' (e.g. 'fts3_tokenizer_test').
  132980. **
  132981. ** The return value is a string that may be interpreted as a Tcl
  132982. ** list. For each token in the <input-string>, three elements are
  132983. ** added to the returned list. The first is the token position, the
  132984. ** second is the token text (folded, stemmed, etc.) and the third is the
  132985. ** substring of <input-string> associated with the token. For example,
  132986. ** using the built-in "simple" tokenizer:
  132987. **
  132988. ** SELECT fts_tokenizer_test('simple', 'I don't see how');
  132989. **
  132990. ** will return the string:
  132991. **
  132992. ** "{0 i I 1 dont don't 2 see see 3 how how}"
  132993. **
  132994. */
  132995. static void testFunc(
  132996. sqlite3_context *context,
  132997. int argc,
  132998. sqlite3_value **argv
  132999. ){
  133000. Fts3Hash *pHash;
  133001. sqlite3_tokenizer_module *p;
  133002. sqlite3_tokenizer *pTokenizer = 0;
  133003. sqlite3_tokenizer_cursor *pCsr = 0;
  133004. const char *zErr = 0;
  133005. const char *zName;
  133006. int nName;
  133007. const char *zInput;
  133008. int nInput;
  133009. const char *azArg[64];
  133010. const char *zToken;
  133011. int nToken = 0;
  133012. int iStart = 0;
  133013. int iEnd = 0;
  133014. int iPos = 0;
  133015. int i;
  133016. Tcl_Obj *pRet;
  133017. if( argc<2 ){
  133018. sqlite3_result_error(context, "insufficient arguments", -1);
  133019. return;
  133020. }
  133021. nName = sqlite3_value_bytes(argv[0]);
  133022. zName = (const char *)sqlite3_value_text(argv[0]);
  133023. nInput = sqlite3_value_bytes(argv[argc-1]);
  133024. zInput = (const char *)sqlite3_value_text(argv[argc-1]);
  133025. pHash = (Fts3Hash *)sqlite3_user_data(context);
  133026. p = (sqlite3_tokenizer_module *)sqlite3Fts3HashFind(pHash, zName, nName+1);
  133027. if( !p ){
  133028. char *zErr2 = sqlite3_mprintf("unknown tokenizer: %s", zName);
  133029. sqlite3_result_error(context, zErr2, -1);
  133030. sqlite3_free(zErr2);
  133031. return;
  133032. }
  133033. pRet = Tcl_NewObj();
  133034. Tcl_IncrRefCount(pRet);
  133035. for(i=1; i<argc-1; i++){
  133036. azArg[i-1] = (const char *)sqlite3_value_text(argv[i]);
  133037. }
  133038. if( SQLITE_OK!=p->xCreate(argc-2, azArg, &pTokenizer) ){
  133039. zErr = "error in xCreate()";
  133040. goto finish;
  133041. }
  133042. pTokenizer->pModule = p;
  133043. if( sqlite3Fts3OpenTokenizer(pTokenizer, 0, zInput, nInput, &pCsr) ){
  133044. zErr = "error in xOpen()";
  133045. goto finish;
  133046. }
  133047. while( SQLITE_OK==p->xNext(pCsr, &zToken, &nToken, &iStart, &iEnd, &iPos) ){
  133048. Tcl_ListObjAppendElement(0, pRet, Tcl_NewIntObj(iPos));
  133049. Tcl_ListObjAppendElement(0, pRet, Tcl_NewStringObj(zToken, nToken));
  133050. zToken = &zInput[iStart];
  133051. nToken = iEnd-iStart;
  133052. Tcl_ListObjAppendElement(0, pRet, Tcl_NewStringObj(zToken, nToken));
  133053. }
  133054. if( SQLITE_OK!=p->xClose(pCsr) ){
  133055. zErr = "error in xClose()";
  133056. goto finish;
  133057. }
  133058. if( SQLITE_OK!=p->xDestroy(pTokenizer) ){
  133059. zErr = "error in xDestroy()";
  133060. goto finish;
  133061. }
  133062. finish:
  133063. if( zErr ){
  133064. sqlite3_result_error(context, zErr, -1);
  133065. }else{
  133066. sqlite3_result_text(context, Tcl_GetString(pRet), -1, SQLITE_TRANSIENT);
  133067. }
  133068. Tcl_DecrRefCount(pRet);
  133069. }
  133070. static
  133071. int registerTokenizer(
  133072. sqlite3 *db,
  133073. char *zName,
  133074. const sqlite3_tokenizer_module *p
  133075. ){
  133076. int rc;
  133077. sqlite3_stmt *pStmt;
  133078. const char zSql[] = "SELECT fts3_tokenizer(?, ?)";
  133079. rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
  133080. if( rc!=SQLITE_OK ){
  133081. return rc;
  133082. }
  133083. sqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC);
  133084. sqlite3_bind_blob(pStmt, 2, &p, sizeof(p), SQLITE_STATIC);
  133085. sqlite3_step(pStmt);
  133086. return sqlite3_finalize(pStmt);
  133087. }
  133088. static
  133089. int queryTokenizer(
  133090. sqlite3 *db,
  133091. char *zName,
  133092. const sqlite3_tokenizer_module **pp
  133093. ){
  133094. int rc;
  133095. sqlite3_stmt *pStmt;
  133096. const char zSql[] = "SELECT fts3_tokenizer(?)";
  133097. *pp = 0;
  133098. rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
  133099. if( rc!=SQLITE_OK ){
  133100. return rc;
  133101. }
  133102. sqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC);
  133103. if( SQLITE_ROW==sqlite3_step(pStmt) ){
  133104. if( sqlite3_column_type(pStmt, 0)==SQLITE_BLOB ){
  133105. memcpy((void *)pp, sqlite3_column_blob(pStmt, 0), sizeof(*pp));
  133106. }
  133107. }
  133108. return sqlite3_finalize(pStmt);
  133109. }
  133110. SQLITE_PRIVATE void sqlite3Fts3SimpleTokenizerModule(sqlite3_tokenizer_module const**ppModule);
  133111. /*
  133112. ** Implementation of the scalar function fts3_tokenizer_internal_test().
  133113. ** This function is used for testing only, it is not included in the
  133114. ** build unless SQLITE_TEST is defined.
  133115. **
  133116. ** The purpose of this is to test that the fts3_tokenizer() function
  133117. ** can be used as designed by the C-code in the queryTokenizer and
  133118. ** registerTokenizer() functions above. These two functions are repeated
  133119. ** in the README.tokenizer file as an example, so it is important to
  133120. ** test them.
  133121. **
  133122. ** To run the tests, evaluate the fts3_tokenizer_internal_test() scalar
  133123. ** function with no arguments. An assert() will fail if a problem is
  133124. ** detected. i.e.:
  133125. **
  133126. ** SELECT fts3_tokenizer_internal_test();
  133127. **
  133128. */
  133129. static void intTestFunc(
  133130. sqlite3_context *context,
  133131. int argc,
  133132. sqlite3_value **argv
  133133. ){
  133134. int rc;
  133135. const sqlite3_tokenizer_module *p1;
  133136. const sqlite3_tokenizer_module *p2;
  133137. sqlite3 *db = (sqlite3 *)sqlite3_user_data(context);
  133138. UNUSED_PARAMETER(argc);
  133139. UNUSED_PARAMETER(argv);
  133140. /* Test the query function */
  133141. sqlite3Fts3SimpleTokenizerModule(&p1);
  133142. rc = queryTokenizer(db, "simple", &p2);
  133143. assert( rc==SQLITE_OK );
  133144. assert( p1==p2 );
  133145. rc = queryTokenizer(db, "nosuchtokenizer", &p2);
  133146. assert( rc==SQLITE_ERROR );
  133147. assert( p2==0 );
  133148. assert( 0==strcmp(sqlite3_errmsg(db), "unknown tokenizer: nosuchtokenizer") );
  133149. /* Test the storage function */
  133150. rc = registerTokenizer(db, "nosuchtokenizer", p1);
  133151. assert( rc==SQLITE_OK );
  133152. rc = queryTokenizer(db, "nosuchtokenizer", &p2);
  133153. assert( rc==SQLITE_OK );
  133154. assert( p2==p1 );
  133155. sqlite3_result_text(context, "ok", -1, SQLITE_STATIC);
  133156. }
  133157. #endif
  133158. /*
  133159. ** Set up SQL objects in database db used to access the contents of
  133160. ** the hash table pointed to by argument pHash. The hash table must
  133161. ** been initialized to use string keys, and to take a private copy
  133162. ** of the key when a value is inserted. i.e. by a call similar to:
  133163. **
  133164. ** sqlite3Fts3HashInit(pHash, FTS3_HASH_STRING, 1);
  133165. **
  133166. ** This function adds a scalar function (see header comment above
  133167. ** scalarFunc() in this file for details) and, if ENABLE_TABLE is
  133168. ** defined at compilation time, a temporary virtual table (see header
  133169. ** comment above struct HashTableVtab) to the database schema. Both
  133170. ** provide read/write access to the contents of *pHash.
  133171. **
  133172. ** The third argument to this function, zName, is used as the name
  133173. ** of both the scalar and, if created, the virtual table.
  133174. */
  133175. SQLITE_PRIVATE int sqlite3Fts3InitHashTable(
  133176. sqlite3 *db,
  133177. Fts3Hash *pHash,
  133178. const char *zName
  133179. ){
  133180. int rc = SQLITE_OK;
  133181. void *p = (void *)pHash;
  133182. const int any = SQLITE_ANY;
  133183. #ifdef SQLITE_TEST
  133184. char *zTest = 0;
  133185. char *zTest2 = 0;
  133186. void *pdb = (void *)db;
  133187. zTest = sqlite3_mprintf("%s_test", zName);
  133188. zTest2 = sqlite3_mprintf("%s_internal_test", zName);
  133189. if( !zTest || !zTest2 ){
  133190. rc = SQLITE_NOMEM;
  133191. }
  133192. #endif
  133193. if( SQLITE_OK==rc ){
  133194. rc = sqlite3_create_function(db, zName, 1, any, p, scalarFunc, 0, 0);
  133195. }
  133196. if( SQLITE_OK==rc ){
  133197. rc = sqlite3_create_function(db, zName, 2, any, p, scalarFunc, 0, 0);
  133198. }
  133199. #ifdef SQLITE_TEST
  133200. if( SQLITE_OK==rc ){
  133201. rc = sqlite3_create_function(db, zTest, -1, any, p, testFunc, 0, 0);
  133202. }
  133203. if( SQLITE_OK==rc ){
  133204. rc = sqlite3_create_function(db, zTest2, 0, any, pdb, intTestFunc, 0, 0);
  133205. }
  133206. #endif
  133207. #ifdef SQLITE_TEST
  133208. sqlite3_free(zTest);
  133209. sqlite3_free(zTest2);
  133210. #endif
  133211. return rc;
  133212. }
  133213. #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
  133214. /************** End of fts3_tokenizer.c **************************************/
  133215. /************** Begin file fts3_tokenizer1.c *********************************/
  133216. /*
  133217. ** 2006 Oct 10
  133218. **
  133219. ** The author disclaims copyright to this source code. In place of
  133220. ** a legal notice, here is a blessing:
  133221. **
  133222. ** May you do good and not evil.
  133223. ** May you find forgiveness for yourself and forgive others.
  133224. ** May you share freely, never taking more than you give.
  133225. **
  133226. ******************************************************************************
  133227. **
  133228. ** Implementation of the "simple" full-text-search tokenizer.
  133229. */
  133230. /*
  133231. ** The code in this file is only compiled if:
  133232. **
  133233. ** * The FTS3 module is being built as an extension
  133234. ** (in which case SQLITE_CORE is not defined), or
  133235. **
  133236. ** * The FTS3 module is being built into the core of
  133237. ** SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
  133238. */
  133239. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  133240. /* #include <assert.h> */
  133241. /* #include <stdlib.h> */
  133242. /* #include <stdio.h> */
  133243. /* #include <string.h> */
  133244. typedef struct simple_tokenizer {
  133245. sqlite3_tokenizer base;
  133246. char delim[128]; /* flag ASCII delimiters */
  133247. } simple_tokenizer;
  133248. typedef struct simple_tokenizer_cursor {
  133249. sqlite3_tokenizer_cursor base;
  133250. const char *pInput; /* input we are tokenizing */
  133251. int nBytes; /* size of the input */
  133252. int iOffset; /* current position in pInput */
  133253. int iToken; /* index of next token to be returned */
  133254. char *pToken; /* storage for current token */
  133255. int nTokenAllocated; /* space allocated to zToken buffer */
  133256. } simple_tokenizer_cursor;
  133257. static int simpleDelim(simple_tokenizer *t, unsigned char c){
  133258. return c<0x80 && t->delim[c];
  133259. }
  133260. static int fts3_isalnum(int x){
  133261. return (x>='0' && x<='9') || (x>='A' && x<='Z') || (x>='a' && x<='z');
  133262. }
  133263. /*
  133264. ** Create a new tokenizer instance.
  133265. */
  133266. static int simpleCreate(
  133267. int argc, const char * const *argv,
  133268. sqlite3_tokenizer **ppTokenizer
  133269. ){
  133270. simple_tokenizer *t;
  133271. t = (simple_tokenizer *) sqlite3_malloc(sizeof(*t));
  133272. if( t==NULL ) return SQLITE_NOMEM;
  133273. memset(t, 0, sizeof(*t));
  133274. /* TODO(shess) Delimiters need to remain the same from run to run,
  133275. ** else we need to reindex. One solution would be a meta-table to
  133276. ** track such information in the database, then we'd only want this
  133277. ** information on the initial create.
  133278. */
  133279. if( argc>1 ){
  133280. int i, n = (int)strlen(argv[1]);
  133281. for(i=0; i<n; i++){
  133282. unsigned char ch = argv[1][i];
  133283. /* We explicitly don't support UTF-8 delimiters for now. */
  133284. if( ch>=0x80 ){
  133285. sqlite3_free(t);
  133286. return SQLITE_ERROR;
  133287. }
  133288. t->delim[ch] = 1;
  133289. }
  133290. } else {
  133291. /* Mark non-alphanumeric ASCII characters as delimiters */
  133292. int i;
  133293. for(i=1; i<0x80; i++){
  133294. t->delim[i] = !fts3_isalnum(i) ? -1 : 0;
  133295. }
  133296. }
  133297. *ppTokenizer = &t->base;
  133298. return SQLITE_OK;
  133299. }
  133300. /*
  133301. ** Destroy a tokenizer
  133302. */
  133303. static int simpleDestroy(sqlite3_tokenizer *pTokenizer){
  133304. sqlite3_free(pTokenizer);
  133305. return SQLITE_OK;
  133306. }
  133307. /*
  133308. ** Prepare to begin tokenizing a particular string. The input
  133309. ** string to be tokenized is pInput[0..nBytes-1]. A cursor
  133310. ** used to incrementally tokenize this string is returned in
  133311. ** *ppCursor.
  133312. */
  133313. static int simpleOpen(
  133314. sqlite3_tokenizer *pTokenizer, /* The tokenizer */
  133315. const char *pInput, int nBytes, /* String to be tokenized */
  133316. sqlite3_tokenizer_cursor **ppCursor /* OUT: Tokenization cursor */
  133317. ){
  133318. simple_tokenizer_cursor *c;
  133319. UNUSED_PARAMETER(pTokenizer);
  133320. c = (simple_tokenizer_cursor *) sqlite3_malloc(sizeof(*c));
  133321. if( c==NULL ) return SQLITE_NOMEM;
  133322. c->pInput = pInput;
  133323. if( pInput==0 ){
  133324. c->nBytes = 0;
  133325. }else if( nBytes<0 ){
  133326. c->nBytes = (int)strlen(pInput);
  133327. }else{
  133328. c->nBytes = nBytes;
  133329. }
  133330. c->iOffset = 0; /* start tokenizing at the beginning */
  133331. c->iToken = 0;
  133332. c->pToken = NULL; /* no space allocated, yet. */
  133333. c->nTokenAllocated = 0;
  133334. *ppCursor = &c->base;
  133335. return SQLITE_OK;
  133336. }
  133337. /*
  133338. ** Close a tokenization cursor previously opened by a call to
  133339. ** simpleOpen() above.
  133340. */
  133341. static int simpleClose(sqlite3_tokenizer_cursor *pCursor){
  133342. simple_tokenizer_cursor *c = (simple_tokenizer_cursor *) pCursor;
  133343. sqlite3_free(c->pToken);
  133344. sqlite3_free(c);
  133345. return SQLITE_OK;
  133346. }
  133347. /*
  133348. ** Extract the next token from a tokenization cursor. The cursor must
  133349. ** have been opened by a prior call to simpleOpen().
  133350. */
  133351. static int simpleNext(
  133352. sqlite3_tokenizer_cursor *pCursor, /* Cursor returned by simpleOpen */
  133353. const char **ppToken, /* OUT: *ppToken is the token text */
  133354. int *pnBytes, /* OUT: Number of bytes in token */
  133355. int *piStartOffset, /* OUT: Starting offset of token */
  133356. int *piEndOffset, /* OUT: Ending offset of token */
  133357. int *piPosition /* OUT: Position integer of token */
  133358. ){
  133359. simple_tokenizer_cursor *c = (simple_tokenizer_cursor *) pCursor;
  133360. simple_tokenizer *t = (simple_tokenizer *) pCursor->pTokenizer;
  133361. unsigned char *p = (unsigned char *)c->pInput;
  133362. while( c->iOffset<c->nBytes ){
  133363. int iStartOffset;
  133364. /* Scan past delimiter characters */
  133365. while( c->iOffset<c->nBytes && simpleDelim(t, p[c->iOffset]) ){
  133366. c->iOffset++;
  133367. }
  133368. /* Count non-delimiter characters. */
  133369. iStartOffset = c->iOffset;
  133370. while( c->iOffset<c->nBytes && !simpleDelim(t, p[c->iOffset]) ){
  133371. c->iOffset++;
  133372. }
  133373. if( c->iOffset>iStartOffset ){
  133374. int i, n = c->iOffset-iStartOffset;
  133375. if( n>c->nTokenAllocated ){
  133376. char *pNew;
  133377. c->nTokenAllocated = n+20;
  133378. pNew = sqlite3_realloc(c->pToken, c->nTokenAllocated);
  133379. if( !pNew ) return SQLITE_NOMEM;
  133380. c->pToken = pNew;
  133381. }
  133382. for(i=0; i<n; i++){
  133383. /* TODO(shess) This needs expansion to handle UTF-8
  133384. ** case-insensitivity.
  133385. */
  133386. unsigned char ch = p[iStartOffset+i];
  133387. c->pToken[i] = (char)((ch>='A' && ch<='Z') ? ch-'A'+'a' : ch);
  133388. }
  133389. *ppToken = c->pToken;
  133390. *pnBytes = n;
  133391. *piStartOffset = iStartOffset;
  133392. *piEndOffset = c->iOffset;
  133393. *piPosition = c->iToken++;
  133394. return SQLITE_OK;
  133395. }
  133396. }
  133397. return SQLITE_DONE;
  133398. }
  133399. /*
  133400. ** The set of routines that implement the simple tokenizer
  133401. */
  133402. static const sqlite3_tokenizer_module simpleTokenizerModule = {
  133403. 0,
  133404. simpleCreate,
  133405. simpleDestroy,
  133406. simpleOpen,
  133407. simpleClose,
  133408. simpleNext,
  133409. 0,
  133410. };
  133411. /*
  133412. ** Allocate a new simple tokenizer. Return a pointer to the new
  133413. ** tokenizer in *ppModule
  133414. */
  133415. SQLITE_PRIVATE void sqlite3Fts3SimpleTokenizerModule(
  133416. sqlite3_tokenizer_module const**ppModule
  133417. ){
  133418. *ppModule = &simpleTokenizerModule;
  133419. }
  133420. #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
  133421. /************** End of fts3_tokenizer1.c *************************************/
  133422. /************** Begin file fts3_tokenize_vtab.c ******************************/
  133423. /*
  133424. ** 2013 Apr 22
  133425. **
  133426. ** The author disclaims copyright to this source code. In place of
  133427. ** a legal notice, here is a blessing:
  133428. **
  133429. ** May you do good and not evil.
  133430. ** May you find forgiveness for yourself and forgive others.
  133431. ** May you share freely, never taking more than you give.
  133432. **
  133433. ******************************************************************************
  133434. **
  133435. ** This file contains code for the "fts3tokenize" virtual table module.
  133436. ** An fts3tokenize virtual table is created as follows:
  133437. **
  133438. ** CREATE VIRTUAL TABLE <tbl> USING fts3tokenize(
  133439. ** <tokenizer-name>, <arg-1>, ...
  133440. ** );
  133441. **
  133442. ** The table created has the following schema:
  133443. **
  133444. ** CREATE TABLE <tbl>(input, token, start, end, position)
  133445. **
  133446. ** When queried, the query must include a WHERE clause of type:
  133447. **
  133448. ** input = <string>
  133449. **
  133450. ** The virtual table module tokenizes this <string>, using the FTS3
  133451. ** tokenizer specified by the arguments to the CREATE VIRTUAL TABLE
  133452. ** statement and returns one row for each token in the result. With
  133453. ** fields set as follows:
  133454. **
  133455. ** input: Always set to a copy of <string>
  133456. ** token: A token from the input.
  133457. ** start: Byte offset of the token within the input <string>.
  133458. ** end: Byte offset of the byte immediately following the end of the
  133459. ** token within the input string.
  133460. ** pos: Token offset of token within input.
  133461. **
  133462. */
  133463. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  133464. /* #include <string.h> */
  133465. /* #include <assert.h> */
  133466. typedef struct Fts3tokTable Fts3tokTable;
  133467. typedef struct Fts3tokCursor Fts3tokCursor;
  133468. /*
  133469. ** Virtual table structure.
  133470. */
  133471. struct Fts3tokTable {
  133472. sqlite3_vtab base; /* Base class used by SQLite core */
  133473. const sqlite3_tokenizer_module *pMod;
  133474. sqlite3_tokenizer *pTok;
  133475. };
  133476. /*
  133477. ** Virtual table cursor structure.
  133478. */
  133479. struct Fts3tokCursor {
  133480. sqlite3_vtab_cursor base; /* Base class used by SQLite core */
  133481. char *zInput; /* Input string */
  133482. sqlite3_tokenizer_cursor *pCsr; /* Cursor to iterate through zInput */
  133483. int iRowid; /* Current 'rowid' value */
  133484. const char *zToken; /* Current 'token' value */
  133485. int nToken; /* Size of zToken in bytes */
  133486. int iStart; /* Current 'start' value */
  133487. int iEnd; /* Current 'end' value */
  133488. int iPos; /* Current 'pos' value */
  133489. };
  133490. /*
  133491. ** Query FTS for the tokenizer implementation named zName.
  133492. */
  133493. static int fts3tokQueryTokenizer(
  133494. Fts3Hash *pHash,
  133495. const char *zName,
  133496. const sqlite3_tokenizer_module **pp,
  133497. char **pzErr
  133498. ){
  133499. sqlite3_tokenizer_module *p;
  133500. int nName = (int)strlen(zName);
  133501. p = (sqlite3_tokenizer_module *)sqlite3Fts3HashFind(pHash, zName, nName+1);
  133502. if( !p ){
  133503. sqlite3Fts3ErrMsg(pzErr, "unknown tokenizer: %s", zName);
  133504. return SQLITE_ERROR;
  133505. }
  133506. *pp = p;
  133507. return SQLITE_OK;
  133508. }
  133509. /*
  133510. ** The second argument, argv[], is an array of pointers to nul-terminated
  133511. ** strings. This function makes a copy of the array and strings into a
  133512. ** single block of memory. It then dequotes any of the strings that appear
  133513. ** to be quoted.
  133514. **
  133515. ** If successful, output parameter *pazDequote is set to point at the
  133516. ** array of dequoted strings and SQLITE_OK is returned. The caller is
  133517. ** responsible for eventually calling sqlite3_free() to free the array
  133518. ** in this case. Or, if an error occurs, an SQLite error code is returned.
  133519. ** The final value of *pazDequote is undefined in this case.
  133520. */
  133521. static int fts3tokDequoteArray(
  133522. int argc, /* Number of elements in argv[] */
  133523. const char * const *argv, /* Input array */
  133524. char ***pazDequote /* Output array */
  133525. ){
  133526. int rc = SQLITE_OK; /* Return code */
  133527. if( argc==0 ){
  133528. *pazDequote = 0;
  133529. }else{
  133530. int i;
  133531. int nByte = 0;
  133532. char **azDequote;
  133533. for(i=0; i<argc; i++){
  133534. nByte += (int)(strlen(argv[i]) + 1);
  133535. }
  133536. *pazDequote = azDequote = sqlite3_malloc(sizeof(char *)*argc + nByte);
  133537. if( azDequote==0 ){
  133538. rc = SQLITE_NOMEM;
  133539. }else{
  133540. char *pSpace = (char *)&azDequote[argc];
  133541. for(i=0; i<argc; i++){
  133542. int n = (int)strlen(argv[i]);
  133543. azDequote[i] = pSpace;
  133544. memcpy(pSpace, argv[i], n+1);
  133545. sqlite3Fts3Dequote(pSpace);
  133546. pSpace += (n+1);
  133547. }
  133548. }
  133549. }
  133550. return rc;
  133551. }
  133552. /*
  133553. ** Schema of the tokenizer table.
  133554. */
  133555. #define FTS3_TOK_SCHEMA "CREATE TABLE x(input, token, start, end, position)"
  133556. /*
  133557. ** This function does all the work for both the xConnect and xCreate methods.
  133558. ** These tables have no persistent representation of their own, so xConnect
  133559. ** and xCreate are identical operations.
  133560. **
  133561. ** argv[0]: module name
  133562. ** argv[1]: database name
  133563. ** argv[2]: table name
  133564. ** argv[3]: first argument (tokenizer name)
  133565. */
  133566. static int fts3tokConnectMethod(
  133567. sqlite3 *db, /* Database connection */
  133568. void *pHash, /* Hash table of tokenizers */
  133569. int argc, /* Number of elements in argv array */
  133570. const char * const *argv, /* xCreate/xConnect argument array */
  133571. sqlite3_vtab **ppVtab, /* OUT: New sqlite3_vtab object */
  133572. char **pzErr /* OUT: sqlite3_malloc'd error message */
  133573. ){
  133574. Fts3tokTable *pTab = 0;
  133575. const sqlite3_tokenizer_module *pMod = 0;
  133576. sqlite3_tokenizer *pTok = 0;
  133577. int rc;
  133578. char **azDequote = 0;
  133579. int nDequote;
  133580. rc = sqlite3_declare_vtab(db, FTS3_TOK_SCHEMA);
  133581. if( rc!=SQLITE_OK ) return rc;
  133582. nDequote = argc-3;
  133583. rc = fts3tokDequoteArray(nDequote, &argv[3], &azDequote);
  133584. if( rc==SQLITE_OK ){
  133585. const char *zModule;
  133586. if( nDequote<1 ){
  133587. zModule = "simple";
  133588. }else{
  133589. zModule = azDequote[0];
  133590. }
  133591. rc = fts3tokQueryTokenizer((Fts3Hash*)pHash, zModule, &pMod, pzErr);
  133592. }
  133593. assert( (rc==SQLITE_OK)==(pMod!=0) );
  133594. if( rc==SQLITE_OK ){
  133595. const char * const *azArg = (const char * const *)&azDequote[1];
  133596. rc = pMod->xCreate((nDequote>1 ? nDequote-1 : 0), azArg, &pTok);
  133597. }
  133598. if( rc==SQLITE_OK ){
  133599. pTab = (Fts3tokTable *)sqlite3_malloc(sizeof(Fts3tokTable));
  133600. if( pTab==0 ){
  133601. rc = SQLITE_NOMEM;
  133602. }
  133603. }
  133604. if( rc==SQLITE_OK ){
  133605. memset(pTab, 0, sizeof(Fts3tokTable));
  133606. pTab->pMod = pMod;
  133607. pTab->pTok = pTok;
  133608. *ppVtab = &pTab->base;
  133609. }else{
  133610. if( pTok ){
  133611. pMod->xDestroy(pTok);
  133612. }
  133613. }
  133614. sqlite3_free(azDequote);
  133615. return rc;
  133616. }
  133617. /*
  133618. ** This function does the work for both the xDisconnect and xDestroy methods.
  133619. ** These tables have no persistent representation of their own, so xDisconnect
  133620. ** and xDestroy are identical operations.
  133621. */
  133622. static int fts3tokDisconnectMethod(sqlite3_vtab *pVtab){
  133623. Fts3tokTable *pTab = (Fts3tokTable *)pVtab;
  133624. pTab->pMod->xDestroy(pTab->pTok);
  133625. sqlite3_free(pTab);
  133626. return SQLITE_OK;
  133627. }
  133628. /*
  133629. ** xBestIndex - Analyze a WHERE and ORDER BY clause.
  133630. */
  133631. static int fts3tokBestIndexMethod(
  133632. sqlite3_vtab *pVTab,
  133633. sqlite3_index_info *pInfo
  133634. ){
  133635. int i;
  133636. UNUSED_PARAMETER(pVTab);
  133637. for(i=0; i<pInfo->nConstraint; i++){
  133638. if( pInfo->aConstraint[i].usable
  133639. && pInfo->aConstraint[i].iColumn==0
  133640. && pInfo->aConstraint[i].op==SQLITE_INDEX_CONSTRAINT_EQ
  133641. ){
  133642. pInfo->idxNum = 1;
  133643. pInfo->aConstraintUsage[i].argvIndex = 1;
  133644. pInfo->aConstraintUsage[i].omit = 1;
  133645. pInfo->estimatedCost = 1;
  133646. return SQLITE_OK;
  133647. }
  133648. }
  133649. pInfo->idxNum = 0;
  133650. assert( pInfo->estimatedCost>1000000.0 );
  133651. return SQLITE_OK;
  133652. }
  133653. /*
  133654. ** xOpen - Open a cursor.
  133655. */
  133656. static int fts3tokOpenMethod(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCsr){
  133657. Fts3tokCursor *pCsr;
  133658. UNUSED_PARAMETER(pVTab);
  133659. pCsr = (Fts3tokCursor *)sqlite3_malloc(sizeof(Fts3tokCursor));
  133660. if( pCsr==0 ){
  133661. return SQLITE_NOMEM;
  133662. }
  133663. memset(pCsr, 0, sizeof(Fts3tokCursor));
  133664. *ppCsr = (sqlite3_vtab_cursor *)pCsr;
  133665. return SQLITE_OK;
  133666. }
  133667. /*
  133668. ** Reset the tokenizer cursor passed as the only argument. As if it had
  133669. ** just been returned by fts3tokOpenMethod().
  133670. */
  133671. static void fts3tokResetCursor(Fts3tokCursor *pCsr){
  133672. if( pCsr->pCsr ){
  133673. Fts3tokTable *pTab = (Fts3tokTable *)(pCsr->base.pVtab);
  133674. pTab->pMod->xClose(pCsr->pCsr);
  133675. pCsr->pCsr = 0;
  133676. }
  133677. sqlite3_free(pCsr->zInput);
  133678. pCsr->zInput = 0;
  133679. pCsr->zToken = 0;
  133680. pCsr->nToken = 0;
  133681. pCsr->iStart = 0;
  133682. pCsr->iEnd = 0;
  133683. pCsr->iPos = 0;
  133684. pCsr->iRowid = 0;
  133685. }
  133686. /*
  133687. ** xClose - Close a cursor.
  133688. */
  133689. static int fts3tokCloseMethod(sqlite3_vtab_cursor *pCursor){
  133690. Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor;
  133691. fts3tokResetCursor(pCsr);
  133692. sqlite3_free(pCsr);
  133693. return SQLITE_OK;
  133694. }
  133695. /*
  133696. ** xNext - Advance the cursor to the next row, if any.
  133697. */
  133698. static int fts3tokNextMethod(sqlite3_vtab_cursor *pCursor){
  133699. Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor;
  133700. Fts3tokTable *pTab = (Fts3tokTable *)(pCursor->pVtab);
  133701. int rc; /* Return code */
  133702. pCsr->iRowid++;
  133703. rc = pTab->pMod->xNext(pCsr->pCsr,
  133704. &pCsr->zToken, &pCsr->nToken,
  133705. &pCsr->iStart, &pCsr->iEnd, &pCsr->iPos
  133706. );
  133707. if( rc!=SQLITE_OK ){
  133708. fts3tokResetCursor(pCsr);
  133709. if( rc==SQLITE_DONE ) rc = SQLITE_OK;
  133710. }
  133711. return rc;
  133712. }
  133713. /*
  133714. ** xFilter - Initialize a cursor to point at the start of its data.
  133715. */
  133716. static int fts3tokFilterMethod(
  133717. sqlite3_vtab_cursor *pCursor, /* The cursor used for this query */
  133718. int idxNum, /* Strategy index */
  133719. const char *idxStr, /* Unused */
  133720. int nVal, /* Number of elements in apVal */
  133721. sqlite3_value **apVal /* Arguments for the indexing scheme */
  133722. ){
  133723. int rc = SQLITE_ERROR;
  133724. Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor;
  133725. Fts3tokTable *pTab = (Fts3tokTable *)(pCursor->pVtab);
  133726. UNUSED_PARAMETER(idxStr);
  133727. UNUSED_PARAMETER(nVal);
  133728. fts3tokResetCursor(pCsr);
  133729. if( idxNum==1 ){
  133730. const char *zByte = (const char *)sqlite3_value_text(apVal[0]);
  133731. int nByte = sqlite3_value_bytes(apVal[0]);
  133732. pCsr->zInput = sqlite3_malloc(nByte+1);
  133733. if( pCsr->zInput==0 ){
  133734. rc = SQLITE_NOMEM;
  133735. }else{
  133736. memcpy(pCsr->zInput, zByte, nByte);
  133737. pCsr->zInput[nByte] = 0;
  133738. rc = pTab->pMod->xOpen(pTab->pTok, pCsr->zInput, nByte, &pCsr->pCsr);
  133739. if( rc==SQLITE_OK ){
  133740. pCsr->pCsr->pTokenizer = pTab->pTok;
  133741. }
  133742. }
  133743. }
  133744. if( rc!=SQLITE_OK ) return rc;
  133745. return fts3tokNextMethod(pCursor);
  133746. }
  133747. /*
  133748. ** xEof - Return true if the cursor is at EOF, or false otherwise.
  133749. */
  133750. static int fts3tokEofMethod(sqlite3_vtab_cursor *pCursor){
  133751. Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor;
  133752. return (pCsr->zToken==0);
  133753. }
  133754. /*
  133755. ** xColumn - Return a column value.
  133756. */
  133757. static int fts3tokColumnMethod(
  133758. sqlite3_vtab_cursor *pCursor, /* Cursor to retrieve value from */
  133759. sqlite3_context *pCtx, /* Context for sqlite3_result_xxx() calls */
  133760. int iCol /* Index of column to read value from */
  133761. ){
  133762. Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor;
  133763. /* CREATE TABLE x(input, token, start, end, position) */
  133764. switch( iCol ){
  133765. case 0:
  133766. sqlite3_result_text(pCtx, pCsr->zInput, -1, SQLITE_TRANSIENT);
  133767. break;
  133768. case 1:
  133769. sqlite3_result_text(pCtx, pCsr->zToken, pCsr->nToken, SQLITE_TRANSIENT);
  133770. break;
  133771. case 2:
  133772. sqlite3_result_int(pCtx, pCsr->iStart);
  133773. break;
  133774. case 3:
  133775. sqlite3_result_int(pCtx, pCsr->iEnd);
  133776. break;
  133777. default:
  133778. assert( iCol==4 );
  133779. sqlite3_result_int(pCtx, pCsr->iPos);
  133780. break;
  133781. }
  133782. return SQLITE_OK;
  133783. }
  133784. /*
  133785. ** xRowid - Return the current rowid for the cursor.
  133786. */
  133787. static int fts3tokRowidMethod(
  133788. sqlite3_vtab_cursor *pCursor, /* Cursor to retrieve value from */
  133789. sqlite_int64 *pRowid /* OUT: Rowid value */
  133790. ){
  133791. Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor;
  133792. *pRowid = (sqlite3_int64)pCsr->iRowid;
  133793. return SQLITE_OK;
  133794. }
  133795. /*
  133796. ** Register the fts3tok module with database connection db. Return SQLITE_OK
  133797. ** if successful or an error code if sqlite3_create_module() fails.
  133798. */
  133799. SQLITE_PRIVATE int sqlite3Fts3InitTok(sqlite3 *db, Fts3Hash *pHash){
  133800. static const sqlite3_module fts3tok_module = {
  133801. 0, /* iVersion */
  133802. fts3tokConnectMethod, /* xCreate */
  133803. fts3tokConnectMethod, /* xConnect */
  133804. fts3tokBestIndexMethod, /* xBestIndex */
  133805. fts3tokDisconnectMethod, /* xDisconnect */
  133806. fts3tokDisconnectMethod, /* xDestroy */
  133807. fts3tokOpenMethod, /* xOpen */
  133808. fts3tokCloseMethod, /* xClose */
  133809. fts3tokFilterMethod, /* xFilter */
  133810. fts3tokNextMethod, /* xNext */
  133811. fts3tokEofMethod, /* xEof */
  133812. fts3tokColumnMethod, /* xColumn */
  133813. fts3tokRowidMethod, /* xRowid */
  133814. 0, /* xUpdate */
  133815. 0, /* xBegin */
  133816. 0, /* xSync */
  133817. 0, /* xCommit */
  133818. 0, /* xRollback */
  133819. 0, /* xFindFunction */
  133820. 0, /* xRename */
  133821. 0, /* xSavepoint */
  133822. 0, /* xRelease */
  133823. 0 /* xRollbackTo */
  133824. };
  133825. int rc; /* Return code */
  133826. rc = sqlite3_create_module(db, "fts3tokenize", &fts3tok_module, (void*)pHash);
  133827. return rc;
  133828. }
  133829. #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
  133830. /************** End of fts3_tokenize_vtab.c **********************************/
  133831. /************** Begin file fts3_write.c **************************************/
  133832. /*
  133833. ** 2009 Oct 23
  133834. **
  133835. ** The author disclaims copyright to this source code. In place of
  133836. ** a legal notice, here is a blessing:
  133837. **
  133838. ** May you do good and not evil.
  133839. ** May you find forgiveness for yourself and forgive others.
  133840. ** May you share freely, never taking more than you give.
  133841. **
  133842. ******************************************************************************
  133843. **
  133844. ** This file is part of the SQLite FTS3 extension module. Specifically,
  133845. ** this file contains code to insert, update and delete rows from FTS3
  133846. ** tables. It also contains code to merge FTS3 b-tree segments. Some
  133847. ** of the sub-routines used to merge segments are also used by the query
  133848. ** code in fts3.c.
  133849. */
  133850. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  133851. /* #include <string.h> */
  133852. /* #include <assert.h> */
  133853. /* #include <stdlib.h> */
  133854. #define FTS_MAX_APPENDABLE_HEIGHT 16
  133855. /*
  133856. ** When full-text index nodes are loaded from disk, the buffer that they
  133857. ** are loaded into has the following number of bytes of padding at the end
  133858. ** of it. i.e. if a full-text index node is 900 bytes in size, then a buffer
  133859. ** of 920 bytes is allocated for it.
  133860. **
  133861. ** This means that if we have a pointer into a buffer containing node data,
  133862. ** it is always safe to read up to two varints from it without risking an
  133863. ** overread, even if the node data is corrupted.
  133864. */
  133865. #define FTS3_NODE_PADDING (FTS3_VARINT_MAX*2)
  133866. /*
  133867. ** Under certain circumstances, b-tree nodes (doclists) can be loaded into
  133868. ** memory incrementally instead of all at once. This can be a big performance
  133869. ** win (reduced IO and CPU) if SQLite stops calling the virtual table xNext()
  133870. ** method before retrieving all query results (as may happen, for example,
  133871. ** if a query has a LIMIT clause).
  133872. **
  133873. ** Incremental loading is used for b-tree nodes FTS3_NODE_CHUNK_THRESHOLD
  133874. ** bytes and larger. Nodes are loaded in chunks of FTS3_NODE_CHUNKSIZE bytes.
  133875. ** The code is written so that the hard lower-limit for each of these values
  133876. ** is 1. Clearly such small values would be inefficient, but can be useful
  133877. ** for testing purposes.
  133878. **
  133879. ** If this module is built with SQLITE_TEST defined, these constants may
  133880. ** be overridden at runtime for testing purposes. File fts3_test.c contains
  133881. ** a Tcl interface to read and write the values.
  133882. */
  133883. #ifdef SQLITE_TEST
  133884. int test_fts3_node_chunksize = (4*1024);
  133885. int test_fts3_node_chunk_threshold = (4*1024)*4;
  133886. # define FTS3_NODE_CHUNKSIZE test_fts3_node_chunksize
  133887. # define FTS3_NODE_CHUNK_THRESHOLD test_fts3_node_chunk_threshold
  133888. #else
  133889. # define FTS3_NODE_CHUNKSIZE (4*1024)
  133890. # define FTS3_NODE_CHUNK_THRESHOLD (FTS3_NODE_CHUNKSIZE*4)
  133891. #endif
  133892. /*
  133893. ** The two values that may be meaningfully bound to the :1 parameter in
  133894. ** statements SQL_REPLACE_STAT and SQL_SELECT_STAT.
  133895. */
  133896. #define FTS_STAT_DOCTOTAL 0
  133897. #define FTS_STAT_INCRMERGEHINT 1
  133898. #define FTS_STAT_AUTOINCRMERGE 2
  133899. /*
  133900. ** If FTS_LOG_MERGES is defined, call sqlite3_log() to report each automatic
  133901. ** and incremental merge operation that takes place. This is used for
  133902. ** debugging FTS only, it should not usually be turned on in production
  133903. ** systems.
  133904. */
  133905. #ifdef FTS3_LOG_MERGES
  133906. static void fts3LogMerge(int nMerge, sqlite3_int64 iAbsLevel){
  133907. sqlite3_log(SQLITE_OK, "%d-way merge from level %d", nMerge, (int)iAbsLevel);
  133908. }
  133909. #else
  133910. #define fts3LogMerge(x, y)
  133911. #endif
  133912. typedef struct PendingList PendingList;
  133913. typedef struct SegmentNode SegmentNode;
  133914. typedef struct SegmentWriter SegmentWriter;
  133915. /*
  133916. ** An instance of the following data structure is used to build doclists
  133917. ** incrementally. See function fts3PendingListAppend() for details.
  133918. */
  133919. struct PendingList {
  133920. int nData;
  133921. char *aData;
  133922. int nSpace;
  133923. sqlite3_int64 iLastDocid;
  133924. sqlite3_int64 iLastCol;
  133925. sqlite3_int64 iLastPos;
  133926. };
  133927. /*
  133928. ** Each cursor has a (possibly empty) linked list of the following objects.
  133929. */
  133930. struct Fts3DeferredToken {
  133931. Fts3PhraseToken *pToken; /* Pointer to corresponding expr token */
  133932. int iCol; /* Column token must occur in */
  133933. Fts3DeferredToken *pNext; /* Next in list of deferred tokens */
  133934. PendingList *pList; /* Doclist is assembled here */
  133935. };
  133936. /*
  133937. ** An instance of this structure is used to iterate through the terms on
  133938. ** a contiguous set of segment b-tree leaf nodes. Although the details of
  133939. ** this structure are only manipulated by code in this file, opaque handles
  133940. ** of type Fts3SegReader* are also used by code in fts3.c to iterate through
  133941. ** terms when querying the full-text index. See functions:
  133942. **
  133943. ** sqlite3Fts3SegReaderNew()
  133944. ** sqlite3Fts3SegReaderFree()
  133945. ** sqlite3Fts3SegReaderIterate()
  133946. **
  133947. ** Methods used to manipulate Fts3SegReader structures:
  133948. **
  133949. ** fts3SegReaderNext()
  133950. ** fts3SegReaderFirstDocid()
  133951. ** fts3SegReaderNextDocid()
  133952. */
  133953. struct Fts3SegReader {
  133954. int iIdx; /* Index within level, or 0x7FFFFFFF for PT */
  133955. u8 bLookup; /* True for a lookup only */
  133956. u8 rootOnly; /* True for a root-only reader */
  133957. sqlite3_int64 iStartBlock; /* Rowid of first leaf block to traverse */
  133958. sqlite3_int64 iLeafEndBlock; /* Rowid of final leaf block to traverse */
  133959. sqlite3_int64 iEndBlock; /* Rowid of final block in segment (or 0) */
  133960. sqlite3_int64 iCurrentBlock; /* Current leaf block (or 0) */
  133961. char *aNode; /* Pointer to node data (or NULL) */
  133962. int nNode; /* Size of buffer at aNode (or 0) */
  133963. int nPopulate; /* If >0, bytes of buffer aNode[] loaded */
  133964. sqlite3_blob *pBlob; /* If not NULL, blob handle to read node */
  133965. Fts3HashElem **ppNextElem;
  133966. /* Variables set by fts3SegReaderNext(). These may be read directly
  133967. ** by the caller. They are valid from the time SegmentReaderNew() returns
  133968. ** until SegmentReaderNext() returns something other than SQLITE_OK
  133969. ** (i.e. SQLITE_DONE).
  133970. */
  133971. int nTerm; /* Number of bytes in current term */
  133972. char *zTerm; /* Pointer to current term */
  133973. int nTermAlloc; /* Allocated size of zTerm buffer */
  133974. char *aDoclist; /* Pointer to doclist of current entry */
  133975. int nDoclist; /* Size of doclist in current entry */
  133976. /* The following variables are used by fts3SegReaderNextDocid() to iterate
  133977. ** through the current doclist (aDoclist/nDoclist).
  133978. */
  133979. char *pOffsetList;
  133980. int nOffsetList; /* For descending pending seg-readers only */
  133981. sqlite3_int64 iDocid;
  133982. };
  133983. #define fts3SegReaderIsPending(p) ((p)->ppNextElem!=0)
  133984. #define fts3SegReaderIsRootOnly(p) ((p)->rootOnly!=0)
  133985. /*
  133986. ** An instance of this structure is used to create a segment b-tree in the
  133987. ** database. The internal details of this type are only accessed by the
  133988. ** following functions:
  133989. **
  133990. ** fts3SegWriterAdd()
  133991. ** fts3SegWriterFlush()
  133992. ** fts3SegWriterFree()
  133993. */
  133994. struct SegmentWriter {
  133995. SegmentNode *pTree; /* Pointer to interior tree structure */
  133996. sqlite3_int64 iFirst; /* First slot in %_segments written */
  133997. sqlite3_int64 iFree; /* Next free slot in %_segments */
  133998. char *zTerm; /* Pointer to previous term buffer */
  133999. int nTerm; /* Number of bytes in zTerm */
  134000. int nMalloc; /* Size of malloc'd buffer at zMalloc */
  134001. char *zMalloc; /* Malloc'd space (possibly) used for zTerm */
  134002. int nSize; /* Size of allocation at aData */
  134003. int nData; /* Bytes of data in aData */
  134004. char *aData; /* Pointer to block from malloc() */
  134005. i64 nLeafData; /* Number of bytes of leaf data written */
  134006. };
  134007. /*
  134008. ** Type SegmentNode is used by the following three functions to create
  134009. ** the interior part of the segment b+-tree structures (everything except
  134010. ** the leaf nodes). These functions and type are only ever used by code
  134011. ** within the fts3SegWriterXXX() family of functions described above.
  134012. **
  134013. ** fts3NodeAddTerm()
  134014. ** fts3NodeWrite()
  134015. ** fts3NodeFree()
  134016. **
  134017. ** When a b+tree is written to the database (either as a result of a merge
  134018. ** or the pending-terms table being flushed), leaves are written into the
  134019. ** database file as soon as they are completely populated. The interior of
  134020. ** the tree is assembled in memory and written out only once all leaves have
  134021. ** been populated and stored. This is Ok, as the b+-tree fanout is usually
  134022. ** very large, meaning that the interior of the tree consumes relatively
  134023. ** little memory.
  134024. */
  134025. struct SegmentNode {
  134026. SegmentNode *pParent; /* Parent node (or NULL for root node) */
  134027. SegmentNode *pRight; /* Pointer to right-sibling */
  134028. SegmentNode *pLeftmost; /* Pointer to left-most node of this depth */
  134029. int nEntry; /* Number of terms written to node so far */
  134030. char *zTerm; /* Pointer to previous term buffer */
  134031. int nTerm; /* Number of bytes in zTerm */
  134032. int nMalloc; /* Size of malloc'd buffer at zMalloc */
  134033. char *zMalloc; /* Malloc'd space (possibly) used for zTerm */
  134034. int nData; /* Bytes of valid data so far */
  134035. char *aData; /* Node data */
  134036. };
  134037. /*
  134038. ** Valid values for the second argument to fts3SqlStmt().
  134039. */
  134040. #define SQL_DELETE_CONTENT 0
  134041. #define SQL_IS_EMPTY 1
  134042. #define SQL_DELETE_ALL_CONTENT 2
  134043. #define SQL_DELETE_ALL_SEGMENTS 3
  134044. #define SQL_DELETE_ALL_SEGDIR 4
  134045. #define SQL_DELETE_ALL_DOCSIZE 5
  134046. #define SQL_DELETE_ALL_STAT 6
  134047. #define SQL_SELECT_CONTENT_BY_ROWID 7
  134048. #define SQL_NEXT_SEGMENT_INDEX 8
  134049. #define SQL_INSERT_SEGMENTS 9
  134050. #define SQL_NEXT_SEGMENTS_ID 10
  134051. #define SQL_INSERT_SEGDIR 11
  134052. #define SQL_SELECT_LEVEL 12
  134053. #define SQL_SELECT_LEVEL_RANGE 13
  134054. #define SQL_SELECT_LEVEL_COUNT 14
  134055. #define SQL_SELECT_SEGDIR_MAX_LEVEL 15
  134056. #define SQL_DELETE_SEGDIR_LEVEL 16
  134057. #define SQL_DELETE_SEGMENTS_RANGE 17
  134058. #define SQL_CONTENT_INSERT 18
  134059. #define SQL_DELETE_DOCSIZE 19
  134060. #define SQL_REPLACE_DOCSIZE 20
  134061. #define SQL_SELECT_DOCSIZE 21
  134062. #define SQL_SELECT_STAT 22
  134063. #define SQL_REPLACE_STAT 23
  134064. #define SQL_SELECT_ALL_PREFIX_LEVEL 24
  134065. #define SQL_DELETE_ALL_TERMS_SEGDIR 25
  134066. #define SQL_DELETE_SEGDIR_RANGE 26
  134067. #define SQL_SELECT_ALL_LANGID 27
  134068. #define SQL_FIND_MERGE_LEVEL 28
  134069. #define SQL_MAX_LEAF_NODE_ESTIMATE 29
  134070. #define SQL_DELETE_SEGDIR_ENTRY 30
  134071. #define SQL_SHIFT_SEGDIR_ENTRY 31
  134072. #define SQL_SELECT_SEGDIR 32
  134073. #define SQL_CHOMP_SEGDIR 33
  134074. #define SQL_SEGMENT_IS_APPENDABLE 34
  134075. #define SQL_SELECT_INDEXES 35
  134076. #define SQL_SELECT_MXLEVEL 36
  134077. #define SQL_SELECT_LEVEL_RANGE2 37
  134078. #define SQL_UPDATE_LEVEL_IDX 38
  134079. #define SQL_UPDATE_LEVEL 39
  134080. /*
  134081. ** This function is used to obtain an SQLite prepared statement handle
  134082. ** for the statement identified by the second argument. If successful,
  134083. ** *pp is set to the requested statement handle and SQLITE_OK returned.
  134084. ** Otherwise, an SQLite error code is returned and *pp is set to 0.
  134085. **
  134086. ** If argument apVal is not NULL, then it must point to an array with
  134087. ** at least as many entries as the requested statement has bound
  134088. ** parameters. The values are bound to the statements parameters before
  134089. ** returning.
  134090. */
  134091. static int fts3SqlStmt(
  134092. Fts3Table *p, /* Virtual table handle */
  134093. int eStmt, /* One of the SQL_XXX constants above */
  134094. sqlite3_stmt **pp, /* OUT: Statement handle */
  134095. sqlite3_value **apVal /* Values to bind to statement */
  134096. ){
  134097. const char *azSql[] = {
  134098. /* 0 */ "DELETE FROM %Q.'%q_content' WHERE rowid = ?",
  134099. /* 1 */ "SELECT NOT EXISTS(SELECT docid FROM %Q.'%q_content' WHERE rowid!=?)",
  134100. /* 2 */ "DELETE FROM %Q.'%q_content'",
  134101. /* 3 */ "DELETE FROM %Q.'%q_segments'",
  134102. /* 4 */ "DELETE FROM %Q.'%q_segdir'",
  134103. /* 5 */ "DELETE FROM %Q.'%q_docsize'",
  134104. /* 6 */ "DELETE FROM %Q.'%q_stat'",
  134105. /* 7 */ "SELECT %s WHERE rowid=?",
  134106. /* 8 */ "SELECT (SELECT max(idx) FROM %Q.'%q_segdir' WHERE level = ?) + 1",
  134107. /* 9 */ "REPLACE INTO %Q.'%q_segments'(blockid, block) VALUES(?, ?)",
  134108. /* 10 */ "SELECT coalesce((SELECT max(blockid) FROM %Q.'%q_segments') + 1, 1)",
  134109. /* 11 */ "REPLACE INTO %Q.'%q_segdir' VALUES(?,?,?,?,?,?)",
  134110. /* Return segments in order from oldest to newest.*/
  134111. /* 12 */ "SELECT idx, start_block, leaves_end_block, end_block, root "
  134112. "FROM %Q.'%q_segdir' WHERE level = ? ORDER BY idx ASC",
  134113. /* 13 */ "SELECT idx, start_block, leaves_end_block, end_block, root "
  134114. "FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?"
  134115. "ORDER BY level DESC, idx ASC",
  134116. /* 14 */ "SELECT count(*) FROM %Q.'%q_segdir' WHERE level = ?",
  134117. /* 15 */ "SELECT max(level) FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?",
  134118. /* 16 */ "DELETE FROM %Q.'%q_segdir' WHERE level = ?",
  134119. /* 17 */ "DELETE FROM %Q.'%q_segments' WHERE blockid BETWEEN ? AND ?",
  134120. /* 18 */ "INSERT INTO %Q.'%q_content' VALUES(%s)",
  134121. /* 19 */ "DELETE FROM %Q.'%q_docsize' WHERE docid = ?",
  134122. /* 20 */ "REPLACE INTO %Q.'%q_docsize' VALUES(?,?)",
  134123. /* 21 */ "SELECT size FROM %Q.'%q_docsize' WHERE docid=?",
  134124. /* 22 */ "SELECT value FROM %Q.'%q_stat' WHERE id=?",
  134125. /* 23 */ "REPLACE INTO %Q.'%q_stat' VALUES(?,?)",
  134126. /* 24 */ "",
  134127. /* 25 */ "",
  134128. /* 26 */ "DELETE FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?",
  134129. /* 27 */ "SELECT ? UNION SELECT level / (1024 * ?) FROM %Q.'%q_segdir'",
  134130. /* This statement is used to determine which level to read the input from
  134131. ** when performing an incremental merge. It returns the absolute level number
  134132. ** of the oldest level in the db that contains at least ? segments. Or,
  134133. ** if no level in the FTS index contains more than ? segments, the statement
  134134. ** returns zero rows. */
  134135. /* 28 */ "SELECT level FROM %Q.'%q_segdir' GROUP BY level HAVING count(*)>=?"
  134136. " ORDER BY (level %% 1024) ASC LIMIT 1",
  134137. /* Estimate the upper limit on the number of leaf nodes in a new segment
  134138. ** created by merging the oldest :2 segments from absolute level :1. See
  134139. ** function sqlite3Fts3Incrmerge() for details. */
  134140. /* 29 */ "SELECT 2 * total(1 + leaves_end_block - start_block) "
  134141. " FROM %Q.'%q_segdir' WHERE level = ? AND idx < ?",
  134142. /* SQL_DELETE_SEGDIR_ENTRY
  134143. ** Delete the %_segdir entry on absolute level :1 with index :2. */
  134144. /* 30 */ "DELETE FROM %Q.'%q_segdir' WHERE level = ? AND idx = ?",
  134145. /* SQL_SHIFT_SEGDIR_ENTRY
  134146. ** Modify the idx value for the segment with idx=:3 on absolute level :2
  134147. ** to :1. */
  134148. /* 31 */ "UPDATE %Q.'%q_segdir' SET idx = ? WHERE level=? AND idx=?",
  134149. /* SQL_SELECT_SEGDIR
  134150. ** Read a single entry from the %_segdir table. The entry from absolute
  134151. ** level :1 with index value :2. */
  134152. /* 32 */ "SELECT idx, start_block, leaves_end_block, end_block, root "
  134153. "FROM %Q.'%q_segdir' WHERE level = ? AND idx = ?",
  134154. /* SQL_CHOMP_SEGDIR
  134155. ** Update the start_block (:1) and root (:2) fields of the %_segdir
  134156. ** entry located on absolute level :3 with index :4. */
  134157. /* 33 */ "UPDATE %Q.'%q_segdir' SET start_block = ?, root = ?"
  134158. "WHERE level = ? AND idx = ?",
  134159. /* SQL_SEGMENT_IS_APPENDABLE
  134160. ** Return a single row if the segment with end_block=? is appendable. Or
  134161. ** no rows otherwise. */
  134162. /* 34 */ "SELECT 1 FROM %Q.'%q_segments' WHERE blockid=? AND block IS NULL",
  134163. /* SQL_SELECT_INDEXES
  134164. ** Return the list of valid segment indexes for absolute level ? */
  134165. /* 35 */ "SELECT idx FROM %Q.'%q_segdir' WHERE level=? ORDER BY 1 ASC",
  134166. /* SQL_SELECT_MXLEVEL
  134167. ** Return the largest relative level in the FTS index or indexes. */
  134168. /* 36 */ "SELECT max( level %% 1024 ) FROM %Q.'%q_segdir'",
  134169. /* Return segments in order from oldest to newest.*/
  134170. /* 37 */ "SELECT level, idx, end_block "
  134171. "FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ? "
  134172. "ORDER BY level DESC, idx ASC",
  134173. /* Update statements used while promoting segments */
  134174. /* 38 */ "UPDATE OR FAIL %Q.'%q_segdir' SET level=-1,idx=? "
  134175. "WHERE level=? AND idx=?",
  134176. /* 39 */ "UPDATE OR FAIL %Q.'%q_segdir' SET level=? WHERE level=-1"
  134177. };
  134178. int rc = SQLITE_OK;
  134179. sqlite3_stmt *pStmt;
  134180. assert( SizeofArray(azSql)==SizeofArray(p->aStmt) );
  134181. assert( eStmt<SizeofArray(azSql) && eStmt>=0 );
  134182. pStmt = p->aStmt[eStmt];
  134183. if( !pStmt ){
  134184. char *zSql;
  134185. if( eStmt==SQL_CONTENT_INSERT ){
  134186. zSql = sqlite3_mprintf(azSql[eStmt], p->zDb, p->zName, p->zWriteExprlist);
  134187. }else if( eStmt==SQL_SELECT_CONTENT_BY_ROWID ){
  134188. zSql = sqlite3_mprintf(azSql[eStmt], p->zReadExprlist);
  134189. }else{
  134190. zSql = sqlite3_mprintf(azSql[eStmt], p->zDb, p->zName);
  134191. }
  134192. if( !zSql ){
  134193. rc = SQLITE_NOMEM;
  134194. }else{
  134195. rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, NULL);
  134196. sqlite3_free(zSql);
  134197. assert( rc==SQLITE_OK || pStmt==0 );
  134198. p->aStmt[eStmt] = pStmt;
  134199. }
  134200. }
  134201. if( apVal ){
  134202. int i;
  134203. int nParam = sqlite3_bind_parameter_count(pStmt);
  134204. for(i=0; rc==SQLITE_OK && i<nParam; i++){
  134205. rc = sqlite3_bind_value(pStmt, i+1, apVal[i]);
  134206. }
  134207. }
  134208. *pp = pStmt;
  134209. return rc;
  134210. }
  134211. static int fts3SelectDocsize(
  134212. Fts3Table *pTab, /* FTS3 table handle */
  134213. sqlite3_int64 iDocid, /* Docid to bind for SQL_SELECT_DOCSIZE */
  134214. sqlite3_stmt **ppStmt /* OUT: Statement handle */
  134215. ){
  134216. sqlite3_stmt *pStmt = 0; /* Statement requested from fts3SqlStmt() */
  134217. int rc; /* Return code */
  134218. rc = fts3SqlStmt(pTab, SQL_SELECT_DOCSIZE, &pStmt, 0);
  134219. if( rc==SQLITE_OK ){
  134220. sqlite3_bind_int64(pStmt, 1, iDocid);
  134221. rc = sqlite3_step(pStmt);
  134222. if( rc!=SQLITE_ROW || sqlite3_column_type(pStmt, 0)!=SQLITE_BLOB ){
  134223. rc = sqlite3_reset(pStmt);
  134224. if( rc==SQLITE_OK ) rc = FTS_CORRUPT_VTAB;
  134225. pStmt = 0;
  134226. }else{
  134227. rc = SQLITE_OK;
  134228. }
  134229. }
  134230. *ppStmt = pStmt;
  134231. return rc;
  134232. }
  134233. SQLITE_PRIVATE int sqlite3Fts3SelectDoctotal(
  134234. Fts3Table *pTab, /* Fts3 table handle */
  134235. sqlite3_stmt **ppStmt /* OUT: Statement handle */
  134236. ){
  134237. sqlite3_stmt *pStmt = 0;
  134238. int rc;
  134239. rc = fts3SqlStmt(pTab, SQL_SELECT_STAT, &pStmt, 0);
  134240. if( rc==SQLITE_OK ){
  134241. sqlite3_bind_int(pStmt, 1, FTS_STAT_DOCTOTAL);
  134242. if( sqlite3_step(pStmt)!=SQLITE_ROW
  134243. || sqlite3_column_type(pStmt, 0)!=SQLITE_BLOB
  134244. ){
  134245. rc = sqlite3_reset(pStmt);
  134246. if( rc==SQLITE_OK ) rc = FTS_CORRUPT_VTAB;
  134247. pStmt = 0;
  134248. }
  134249. }
  134250. *ppStmt = pStmt;
  134251. return rc;
  134252. }
  134253. SQLITE_PRIVATE int sqlite3Fts3SelectDocsize(
  134254. Fts3Table *pTab, /* Fts3 table handle */
  134255. sqlite3_int64 iDocid, /* Docid to read size data for */
  134256. sqlite3_stmt **ppStmt /* OUT: Statement handle */
  134257. ){
  134258. return fts3SelectDocsize(pTab, iDocid, ppStmt);
  134259. }
  134260. /*
  134261. ** Similar to fts3SqlStmt(). Except, after binding the parameters in
  134262. ** array apVal[] to the SQL statement identified by eStmt, the statement
  134263. ** is executed.
  134264. **
  134265. ** Returns SQLITE_OK if the statement is successfully executed, or an
  134266. ** SQLite error code otherwise.
  134267. */
  134268. static void fts3SqlExec(
  134269. int *pRC, /* Result code */
  134270. Fts3Table *p, /* The FTS3 table */
  134271. int eStmt, /* Index of statement to evaluate */
  134272. sqlite3_value **apVal /* Parameters to bind */
  134273. ){
  134274. sqlite3_stmt *pStmt;
  134275. int rc;
  134276. if( *pRC ) return;
  134277. rc = fts3SqlStmt(p, eStmt, &pStmt, apVal);
  134278. if( rc==SQLITE_OK ){
  134279. sqlite3_step(pStmt);
  134280. rc = sqlite3_reset(pStmt);
  134281. }
  134282. *pRC = rc;
  134283. }
  134284. /*
  134285. ** This function ensures that the caller has obtained an exclusive
  134286. ** shared-cache table-lock on the %_segdir table. This is required before
  134287. ** writing data to the fts3 table. If this lock is not acquired first, then
  134288. ** the caller may end up attempting to take this lock as part of committing
  134289. ** a transaction, causing SQLite to return SQLITE_LOCKED or
  134290. ** LOCKED_SHAREDCACHEto a COMMIT command.
  134291. **
  134292. ** It is best to avoid this because if FTS3 returns any error when
  134293. ** committing a transaction, the whole transaction will be rolled back.
  134294. ** And this is not what users expect when they get SQLITE_LOCKED_SHAREDCACHE.
  134295. ** It can still happen if the user locks the underlying tables directly
  134296. ** instead of accessing them via FTS.
  134297. */
  134298. static int fts3Writelock(Fts3Table *p){
  134299. int rc = SQLITE_OK;
  134300. if( p->nPendingData==0 ){
  134301. sqlite3_stmt *pStmt;
  134302. rc = fts3SqlStmt(p, SQL_DELETE_SEGDIR_LEVEL, &pStmt, 0);
  134303. if( rc==SQLITE_OK ){
  134304. sqlite3_bind_null(pStmt, 1);
  134305. sqlite3_step(pStmt);
  134306. rc = sqlite3_reset(pStmt);
  134307. }
  134308. }
  134309. return rc;
  134310. }
  134311. /*
  134312. ** FTS maintains a separate indexes for each language-id (a 32-bit integer).
  134313. ** Within each language id, a separate index is maintained to store the
  134314. ** document terms, and each configured prefix size (configured the FTS
  134315. ** "prefix=" option). And each index consists of multiple levels ("relative
  134316. ** levels").
  134317. **
  134318. ** All three of these values (the language id, the specific index and the
  134319. ** level within the index) are encoded in 64-bit integer values stored
  134320. ** in the %_segdir table on disk. This function is used to convert three
  134321. ** separate component values into the single 64-bit integer value that
  134322. ** can be used to query the %_segdir table.
  134323. **
  134324. ** Specifically, each language-id/index combination is allocated 1024
  134325. ** 64-bit integer level values ("absolute levels"). The main terms index
  134326. ** for language-id 0 is allocate values 0-1023. The first prefix index
  134327. ** (if any) for language-id 0 is allocated values 1024-2047. And so on.
  134328. ** Language 1 indexes are allocated immediately following language 0.
  134329. **
  134330. ** So, for a system with nPrefix prefix indexes configured, the block of
  134331. ** absolute levels that corresponds to language-id iLangid and index
  134332. ** iIndex starts at absolute level ((iLangid * (nPrefix+1) + iIndex) * 1024).
  134333. */
  134334. static sqlite3_int64 getAbsoluteLevel(
  134335. Fts3Table *p, /* FTS3 table handle */
  134336. int iLangid, /* Language id */
  134337. int iIndex, /* Index in p->aIndex[] */
  134338. int iLevel /* Level of segments */
  134339. ){
  134340. sqlite3_int64 iBase; /* First absolute level for iLangid/iIndex */
  134341. assert( iLangid>=0 );
  134342. assert( p->nIndex>0 );
  134343. assert( iIndex>=0 && iIndex<p->nIndex );
  134344. iBase = ((sqlite3_int64)iLangid * p->nIndex + iIndex) * FTS3_SEGDIR_MAXLEVEL;
  134345. return iBase + iLevel;
  134346. }
  134347. /*
  134348. ** Set *ppStmt to a statement handle that may be used to iterate through
  134349. ** all rows in the %_segdir table, from oldest to newest. If successful,
  134350. ** return SQLITE_OK. If an error occurs while preparing the statement,
  134351. ** return an SQLite error code.
  134352. **
  134353. ** There is only ever one instance of this SQL statement compiled for
  134354. ** each FTS3 table.
  134355. **
  134356. ** The statement returns the following columns from the %_segdir table:
  134357. **
  134358. ** 0: idx
  134359. ** 1: start_block
  134360. ** 2: leaves_end_block
  134361. ** 3: end_block
  134362. ** 4: root
  134363. */
  134364. SQLITE_PRIVATE int sqlite3Fts3AllSegdirs(
  134365. Fts3Table *p, /* FTS3 table */
  134366. int iLangid, /* Language being queried */
  134367. int iIndex, /* Index for p->aIndex[] */
  134368. int iLevel, /* Level to select (relative level) */
  134369. sqlite3_stmt **ppStmt /* OUT: Compiled statement */
  134370. ){
  134371. int rc;
  134372. sqlite3_stmt *pStmt = 0;
  134373. assert( iLevel==FTS3_SEGCURSOR_ALL || iLevel>=0 );
  134374. assert( iLevel<FTS3_SEGDIR_MAXLEVEL );
  134375. assert( iIndex>=0 && iIndex<p->nIndex );
  134376. if( iLevel<0 ){
  134377. /* "SELECT * FROM %_segdir WHERE level BETWEEN ? AND ? ORDER BY ..." */
  134378. rc = fts3SqlStmt(p, SQL_SELECT_LEVEL_RANGE, &pStmt, 0);
  134379. if( rc==SQLITE_OK ){
  134380. sqlite3_bind_int64(pStmt, 1, getAbsoluteLevel(p, iLangid, iIndex, 0));
  134381. sqlite3_bind_int64(pStmt, 2,
  134382. getAbsoluteLevel(p, iLangid, iIndex, FTS3_SEGDIR_MAXLEVEL-1)
  134383. );
  134384. }
  134385. }else{
  134386. /* "SELECT * FROM %_segdir WHERE level = ? ORDER BY ..." */
  134387. rc = fts3SqlStmt(p, SQL_SELECT_LEVEL, &pStmt, 0);
  134388. if( rc==SQLITE_OK ){
  134389. sqlite3_bind_int64(pStmt, 1, getAbsoluteLevel(p, iLangid, iIndex,iLevel));
  134390. }
  134391. }
  134392. *ppStmt = pStmt;
  134393. return rc;
  134394. }
  134395. /*
  134396. ** Append a single varint to a PendingList buffer. SQLITE_OK is returned
  134397. ** if successful, or an SQLite error code otherwise.
  134398. **
  134399. ** This function also serves to allocate the PendingList structure itself.
  134400. ** For example, to create a new PendingList structure containing two
  134401. ** varints:
  134402. **
  134403. ** PendingList *p = 0;
  134404. ** fts3PendingListAppendVarint(&p, 1);
  134405. ** fts3PendingListAppendVarint(&p, 2);
  134406. */
  134407. static int fts3PendingListAppendVarint(
  134408. PendingList **pp, /* IN/OUT: Pointer to PendingList struct */
  134409. sqlite3_int64 i /* Value to append to data */
  134410. ){
  134411. PendingList *p = *pp;
  134412. /* Allocate or grow the PendingList as required. */
  134413. if( !p ){
  134414. p = sqlite3_malloc(sizeof(*p) + 100);
  134415. if( !p ){
  134416. return SQLITE_NOMEM;
  134417. }
  134418. p->nSpace = 100;
  134419. p->aData = (char *)&p[1];
  134420. p->nData = 0;
  134421. }
  134422. else if( p->nData+FTS3_VARINT_MAX+1>p->nSpace ){
  134423. int nNew = p->nSpace * 2;
  134424. p = sqlite3_realloc(p, sizeof(*p) + nNew);
  134425. if( !p ){
  134426. sqlite3_free(*pp);
  134427. *pp = 0;
  134428. return SQLITE_NOMEM;
  134429. }
  134430. p->nSpace = nNew;
  134431. p->aData = (char *)&p[1];
  134432. }
  134433. /* Append the new serialized varint to the end of the list. */
  134434. p->nData += sqlite3Fts3PutVarint(&p->aData[p->nData], i);
  134435. p->aData[p->nData] = '\0';
  134436. *pp = p;
  134437. return SQLITE_OK;
  134438. }
  134439. /*
  134440. ** Add a docid/column/position entry to a PendingList structure. Non-zero
  134441. ** is returned if the structure is sqlite3_realloced as part of adding
  134442. ** the entry. Otherwise, zero.
  134443. **
  134444. ** If an OOM error occurs, *pRc is set to SQLITE_NOMEM before returning.
  134445. ** Zero is always returned in this case. Otherwise, if no OOM error occurs,
  134446. ** it is set to SQLITE_OK.
  134447. */
  134448. static int fts3PendingListAppend(
  134449. PendingList **pp, /* IN/OUT: PendingList structure */
  134450. sqlite3_int64 iDocid, /* Docid for entry to add */
  134451. sqlite3_int64 iCol, /* Column for entry to add */
  134452. sqlite3_int64 iPos, /* Position of term for entry to add */
  134453. int *pRc /* OUT: Return code */
  134454. ){
  134455. PendingList *p = *pp;
  134456. int rc = SQLITE_OK;
  134457. assert( !p || p->iLastDocid<=iDocid );
  134458. if( !p || p->iLastDocid!=iDocid ){
  134459. sqlite3_int64 iDelta = iDocid - (p ? p->iLastDocid : 0);
  134460. if( p ){
  134461. assert( p->nData<p->nSpace );
  134462. assert( p->aData[p->nData]==0 );
  134463. p->nData++;
  134464. }
  134465. if( SQLITE_OK!=(rc = fts3PendingListAppendVarint(&p, iDelta)) ){
  134466. goto pendinglistappend_out;
  134467. }
  134468. p->iLastCol = -1;
  134469. p->iLastPos = 0;
  134470. p->iLastDocid = iDocid;
  134471. }
  134472. if( iCol>0 && p->iLastCol!=iCol ){
  134473. if( SQLITE_OK!=(rc = fts3PendingListAppendVarint(&p, 1))
  134474. || SQLITE_OK!=(rc = fts3PendingListAppendVarint(&p, iCol))
  134475. ){
  134476. goto pendinglistappend_out;
  134477. }
  134478. p->iLastCol = iCol;
  134479. p->iLastPos = 0;
  134480. }
  134481. if( iCol>=0 ){
  134482. assert( iPos>p->iLastPos || (iPos==0 && p->iLastPos==0) );
  134483. rc = fts3PendingListAppendVarint(&p, 2+iPos-p->iLastPos);
  134484. if( rc==SQLITE_OK ){
  134485. p->iLastPos = iPos;
  134486. }
  134487. }
  134488. pendinglistappend_out:
  134489. *pRc = rc;
  134490. if( p!=*pp ){
  134491. *pp = p;
  134492. return 1;
  134493. }
  134494. return 0;
  134495. }
  134496. /*
  134497. ** Free a PendingList object allocated by fts3PendingListAppend().
  134498. */
  134499. static void fts3PendingListDelete(PendingList *pList){
  134500. sqlite3_free(pList);
  134501. }
  134502. /*
  134503. ** Add an entry to one of the pending-terms hash tables.
  134504. */
  134505. static int fts3PendingTermsAddOne(
  134506. Fts3Table *p,
  134507. int iCol,
  134508. int iPos,
  134509. Fts3Hash *pHash, /* Pending terms hash table to add entry to */
  134510. const char *zToken,
  134511. int nToken
  134512. ){
  134513. PendingList *pList;
  134514. int rc = SQLITE_OK;
  134515. pList = (PendingList *)fts3HashFind(pHash, zToken, nToken);
  134516. if( pList ){
  134517. p->nPendingData -= (pList->nData + nToken + sizeof(Fts3HashElem));
  134518. }
  134519. if( fts3PendingListAppend(&pList, p->iPrevDocid, iCol, iPos, &rc) ){
  134520. if( pList==fts3HashInsert(pHash, zToken, nToken, pList) ){
  134521. /* Malloc failed while inserting the new entry. This can only
  134522. ** happen if there was no previous entry for this token.
  134523. */
  134524. assert( 0==fts3HashFind(pHash, zToken, nToken) );
  134525. sqlite3_free(pList);
  134526. rc = SQLITE_NOMEM;
  134527. }
  134528. }
  134529. if( rc==SQLITE_OK ){
  134530. p->nPendingData += (pList->nData + nToken + sizeof(Fts3HashElem));
  134531. }
  134532. return rc;
  134533. }
  134534. /*
  134535. ** Tokenize the nul-terminated string zText and add all tokens to the
  134536. ** pending-terms hash-table. The docid used is that currently stored in
  134537. ** p->iPrevDocid, and the column is specified by argument iCol.
  134538. **
  134539. ** If successful, SQLITE_OK is returned. Otherwise, an SQLite error code.
  134540. */
  134541. static int fts3PendingTermsAdd(
  134542. Fts3Table *p, /* Table into which text will be inserted */
  134543. int iLangid, /* Language id to use */
  134544. const char *zText, /* Text of document to be inserted */
  134545. int iCol, /* Column into which text is being inserted */
  134546. u32 *pnWord /* IN/OUT: Incr. by number tokens inserted */
  134547. ){
  134548. int rc;
  134549. int iStart = 0;
  134550. int iEnd = 0;
  134551. int iPos = 0;
  134552. int nWord = 0;
  134553. char const *zToken;
  134554. int nToken = 0;
  134555. sqlite3_tokenizer *pTokenizer = p->pTokenizer;
  134556. sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
  134557. sqlite3_tokenizer_cursor *pCsr;
  134558. int (*xNext)(sqlite3_tokenizer_cursor *pCursor,
  134559. const char**,int*,int*,int*,int*);
  134560. assert( pTokenizer && pModule );
  134561. /* If the user has inserted a NULL value, this function may be called with
  134562. ** zText==0. In this case, add zero token entries to the hash table and
  134563. ** return early. */
  134564. if( zText==0 ){
  134565. *pnWord = 0;
  134566. return SQLITE_OK;
  134567. }
  134568. rc = sqlite3Fts3OpenTokenizer(pTokenizer, iLangid, zText, -1, &pCsr);
  134569. if( rc!=SQLITE_OK ){
  134570. return rc;
  134571. }
  134572. xNext = pModule->xNext;
  134573. while( SQLITE_OK==rc
  134574. && SQLITE_OK==(rc = xNext(pCsr, &zToken, &nToken, &iStart, &iEnd, &iPos))
  134575. ){
  134576. int i;
  134577. if( iPos>=nWord ) nWord = iPos+1;
  134578. /* Positions cannot be negative; we use -1 as a terminator internally.
  134579. ** Tokens must have a non-zero length.
  134580. */
  134581. if( iPos<0 || !zToken || nToken<=0 ){
  134582. rc = SQLITE_ERROR;
  134583. break;
  134584. }
  134585. /* Add the term to the terms index */
  134586. rc = fts3PendingTermsAddOne(
  134587. p, iCol, iPos, &p->aIndex[0].hPending, zToken, nToken
  134588. );
  134589. /* Add the term to each of the prefix indexes that it is not too
  134590. ** short for. */
  134591. for(i=1; rc==SQLITE_OK && i<p->nIndex; i++){
  134592. struct Fts3Index *pIndex = &p->aIndex[i];
  134593. if( nToken<pIndex->nPrefix ) continue;
  134594. rc = fts3PendingTermsAddOne(
  134595. p, iCol, iPos, &pIndex->hPending, zToken, pIndex->nPrefix
  134596. );
  134597. }
  134598. }
  134599. pModule->xClose(pCsr);
  134600. *pnWord += nWord;
  134601. return (rc==SQLITE_DONE ? SQLITE_OK : rc);
  134602. }
  134603. /*
  134604. ** Calling this function indicates that subsequent calls to
  134605. ** fts3PendingTermsAdd() are to add term/position-list pairs for the
  134606. ** contents of the document with docid iDocid.
  134607. */
  134608. static int fts3PendingTermsDocid(
  134609. Fts3Table *p, /* Full-text table handle */
  134610. int iLangid, /* Language id of row being written */
  134611. sqlite_int64 iDocid /* Docid of row being written */
  134612. ){
  134613. assert( iLangid>=0 );
  134614. /* TODO(shess) Explore whether partially flushing the buffer on
  134615. ** forced-flush would provide better performance. I suspect that if
  134616. ** we ordered the doclists by size and flushed the largest until the
  134617. ** buffer was half empty, that would let the less frequent terms
  134618. ** generate longer doclists.
  134619. */
  134620. if( iDocid<=p->iPrevDocid
  134621. || p->iPrevLangid!=iLangid
  134622. || p->nPendingData>p->nMaxPendingData
  134623. ){
  134624. int rc = sqlite3Fts3PendingTermsFlush(p);
  134625. if( rc!=SQLITE_OK ) return rc;
  134626. }
  134627. p->iPrevDocid = iDocid;
  134628. p->iPrevLangid = iLangid;
  134629. return SQLITE_OK;
  134630. }
  134631. /*
  134632. ** Discard the contents of the pending-terms hash tables.
  134633. */
  134634. SQLITE_PRIVATE void sqlite3Fts3PendingTermsClear(Fts3Table *p){
  134635. int i;
  134636. for(i=0; i<p->nIndex; i++){
  134637. Fts3HashElem *pElem;
  134638. Fts3Hash *pHash = &p->aIndex[i].hPending;
  134639. for(pElem=fts3HashFirst(pHash); pElem; pElem=fts3HashNext(pElem)){
  134640. PendingList *pList = (PendingList *)fts3HashData(pElem);
  134641. fts3PendingListDelete(pList);
  134642. }
  134643. fts3HashClear(pHash);
  134644. }
  134645. p->nPendingData = 0;
  134646. }
  134647. /*
  134648. ** This function is called by the xUpdate() method as part of an INSERT
  134649. ** operation. It adds entries for each term in the new record to the
  134650. ** pendingTerms hash table.
  134651. **
  134652. ** Argument apVal is the same as the similarly named argument passed to
  134653. ** fts3InsertData(). Parameter iDocid is the docid of the new row.
  134654. */
  134655. static int fts3InsertTerms(
  134656. Fts3Table *p,
  134657. int iLangid,
  134658. sqlite3_value **apVal,
  134659. u32 *aSz
  134660. ){
  134661. int i; /* Iterator variable */
  134662. for(i=2; i<p->nColumn+2; i++){
  134663. int iCol = i-2;
  134664. if( p->abNotindexed[iCol]==0 ){
  134665. const char *zText = (const char *)sqlite3_value_text(apVal[i]);
  134666. int rc = fts3PendingTermsAdd(p, iLangid, zText, iCol, &aSz[iCol]);
  134667. if( rc!=SQLITE_OK ){
  134668. return rc;
  134669. }
  134670. aSz[p->nColumn] += sqlite3_value_bytes(apVal[i]);
  134671. }
  134672. }
  134673. return SQLITE_OK;
  134674. }
  134675. /*
  134676. ** This function is called by the xUpdate() method for an INSERT operation.
  134677. ** The apVal parameter is passed a copy of the apVal argument passed by
  134678. ** SQLite to the xUpdate() method. i.e:
  134679. **
  134680. ** apVal[0] Not used for INSERT.
  134681. ** apVal[1] rowid
  134682. ** apVal[2] Left-most user-defined column
  134683. ** ...
  134684. ** apVal[p->nColumn+1] Right-most user-defined column
  134685. ** apVal[p->nColumn+2] Hidden column with same name as table
  134686. ** apVal[p->nColumn+3] Hidden "docid" column (alias for rowid)
  134687. ** apVal[p->nColumn+4] Hidden languageid column
  134688. */
  134689. static int fts3InsertData(
  134690. Fts3Table *p, /* Full-text table */
  134691. sqlite3_value **apVal, /* Array of values to insert */
  134692. sqlite3_int64 *piDocid /* OUT: Docid for row just inserted */
  134693. ){
  134694. int rc; /* Return code */
  134695. sqlite3_stmt *pContentInsert; /* INSERT INTO %_content VALUES(...) */
  134696. if( p->zContentTbl ){
  134697. sqlite3_value *pRowid = apVal[p->nColumn+3];
  134698. if( sqlite3_value_type(pRowid)==SQLITE_NULL ){
  134699. pRowid = apVal[1];
  134700. }
  134701. if( sqlite3_value_type(pRowid)!=SQLITE_INTEGER ){
  134702. return SQLITE_CONSTRAINT;
  134703. }
  134704. *piDocid = sqlite3_value_int64(pRowid);
  134705. return SQLITE_OK;
  134706. }
  134707. /* Locate the statement handle used to insert data into the %_content
  134708. ** table. The SQL for this statement is:
  134709. **
  134710. ** INSERT INTO %_content VALUES(?, ?, ?, ...)
  134711. **
  134712. ** The statement features N '?' variables, where N is the number of user
  134713. ** defined columns in the FTS3 table, plus one for the docid field.
  134714. */
  134715. rc = fts3SqlStmt(p, SQL_CONTENT_INSERT, &pContentInsert, &apVal[1]);
  134716. if( rc==SQLITE_OK && p->zLanguageid ){
  134717. rc = sqlite3_bind_int(
  134718. pContentInsert, p->nColumn+2,
  134719. sqlite3_value_int(apVal[p->nColumn+4])
  134720. );
  134721. }
  134722. if( rc!=SQLITE_OK ) return rc;
  134723. /* There is a quirk here. The users INSERT statement may have specified
  134724. ** a value for the "rowid" field, for the "docid" field, or for both.
  134725. ** Which is a problem, since "rowid" and "docid" are aliases for the
  134726. ** same value. For example:
  134727. **
  134728. ** INSERT INTO fts3tbl(rowid, docid) VALUES(1, 2);
  134729. **
  134730. ** In FTS3, this is an error. It is an error to specify non-NULL values
  134731. ** for both docid and some other rowid alias.
  134732. */
  134733. if( SQLITE_NULL!=sqlite3_value_type(apVal[3+p->nColumn]) ){
  134734. if( SQLITE_NULL==sqlite3_value_type(apVal[0])
  134735. && SQLITE_NULL!=sqlite3_value_type(apVal[1])
  134736. ){
  134737. /* A rowid/docid conflict. */
  134738. return SQLITE_ERROR;
  134739. }
  134740. rc = sqlite3_bind_value(pContentInsert, 1, apVal[3+p->nColumn]);
  134741. if( rc!=SQLITE_OK ) return rc;
  134742. }
  134743. /* Execute the statement to insert the record. Set *piDocid to the
  134744. ** new docid value.
  134745. */
  134746. sqlite3_step(pContentInsert);
  134747. rc = sqlite3_reset(pContentInsert);
  134748. *piDocid = sqlite3_last_insert_rowid(p->db);
  134749. return rc;
  134750. }
  134751. /*
  134752. ** Remove all data from the FTS3 table. Clear the hash table containing
  134753. ** pending terms.
  134754. */
  134755. static int fts3DeleteAll(Fts3Table *p, int bContent){
  134756. int rc = SQLITE_OK; /* Return code */
  134757. /* Discard the contents of the pending-terms hash table. */
  134758. sqlite3Fts3PendingTermsClear(p);
  134759. /* Delete everything from the shadow tables. Except, leave %_content as
  134760. ** is if bContent is false. */
  134761. assert( p->zContentTbl==0 || bContent==0 );
  134762. if( bContent ) fts3SqlExec(&rc, p, SQL_DELETE_ALL_CONTENT, 0);
  134763. fts3SqlExec(&rc, p, SQL_DELETE_ALL_SEGMENTS, 0);
  134764. fts3SqlExec(&rc, p, SQL_DELETE_ALL_SEGDIR, 0);
  134765. if( p->bHasDocsize ){
  134766. fts3SqlExec(&rc, p, SQL_DELETE_ALL_DOCSIZE, 0);
  134767. }
  134768. if( p->bHasStat ){
  134769. fts3SqlExec(&rc, p, SQL_DELETE_ALL_STAT, 0);
  134770. }
  134771. return rc;
  134772. }
  134773. /*
  134774. **
  134775. */
  134776. static int langidFromSelect(Fts3Table *p, sqlite3_stmt *pSelect){
  134777. int iLangid = 0;
  134778. if( p->zLanguageid ) iLangid = sqlite3_column_int(pSelect, p->nColumn+1);
  134779. return iLangid;
  134780. }
  134781. /*
  134782. ** The first element in the apVal[] array is assumed to contain the docid
  134783. ** (an integer) of a row about to be deleted. Remove all terms from the
  134784. ** full-text index.
  134785. */
  134786. static void fts3DeleteTerms(
  134787. int *pRC, /* Result code */
  134788. Fts3Table *p, /* The FTS table to delete from */
  134789. sqlite3_value *pRowid, /* The docid to be deleted */
  134790. u32 *aSz, /* Sizes of deleted document written here */
  134791. int *pbFound /* OUT: Set to true if row really does exist */
  134792. ){
  134793. int rc;
  134794. sqlite3_stmt *pSelect;
  134795. assert( *pbFound==0 );
  134796. if( *pRC ) return;
  134797. rc = fts3SqlStmt(p, SQL_SELECT_CONTENT_BY_ROWID, &pSelect, &pRowid);
  134798. if( rc==SQLITE_OK ){
  134799. if( SQLITE_ROW==sqlite3_step(pSelect) ){
  134800. int i;
  134801. int iLangid = langidFromSelect(p, pSelect);
  134802. rc = fts3PendingTermsDocid(p, iLangid, sqlite3_column_int64(pSelect, 0));
  134803. for(i=1; rc==SQLITE_OK && i<=p->nColumn; i++){
  134804. int iCol = i-1;
  134805. if( p->abNotindexed[iCol]==0 ){
  134806. const char *zText = (const char *)sqlite3_column_text(pSelect, i);
  134807. rc = fts3PendingTermsAdd(p, iLangid, zText, -1, &aSz[iCol]);
  134808. aSz[p->nColumn] += sqlite3_column_bytes(pSelect, i);
  134809. }
  134810. }
  134811. if( rc!=SQLITE_OK ){
  134812. sqlite3_reset(pSelect);
  134813. *pRC = rc;
  134814. return;
  134815. }
  134816. *pbFound = 1;
  134817. }
  134818. rc = sqlite3_reset(pSelect);
  134819. }else{
  134820. sqlite3_reset(pSelect);
  134821. }
  134822. *pRC = rc;
  134823. }
  134824. /*
  134825. ** Forward declaration to account for the circular dependency between
  134826. ** functions fts3SegmentMerge() and fts3AllocateSegdirIdx().
  134827. */
  134828. static int fts3SegmentMerge(Fts3Table *, int, int, int);
  134829. /*
  134830. ** This function allocates a new level iLevel index in the segdir table.
  134831. ** Usually, indexes are allocated within a level sequentially starting
  134832. ** with 0, so the allocated index is one greater than the value returned
  134833. ** by:
  134834. **
  134835. ** SELECT max(idx) FROM %_segdir WHERE level = :iLevel
  134836. **
  134837. ** However, if there are already FTS3_MERGE_COUNT indexes at the requested
  134838. ** level, they are merged into a single level (iLevel+1) segment and the
  134839. ** allocated index is 0.
  134840. **
  134841. ** If successful, *piIdx is set to the allocated index slot and SQLITE_OK
  134842. ** returned. Otherwise, an SQLite error code is returned.
  134843. */
  134844. static int fts3AllocateSegdirIdx(
  134845. Fts3Table *p,
  134846. int iLangid, /* Language id */
  134847. int iIndex, /* Index for p->aIndex */
  134848. int iLevel,
  134849. int *piIdx
  134850. ){
  134851. int rc; /* Return Code */
  134852. sqlite3_stmt *pNextIdx; /* Query for next idx at level iLevel */
  134853. int iNext = 0; /* Result of query pNextIdx */
  134854. assert( iLangid>=0 );
  134855. assert( p->nIndex>=1 );
  134856. /* Set variable iNext to the next available segdir index at level iLevel. */
  134857. rc = fts3SqlStmt(p, SQL_NEXT_SEGMENT_INDEX, &pNextIdx, 0);
  134858. if( rc==SQLITE_OK ){
  134859. sqlite3_bind_int64(
  134860. pNextIdx, 1, getAbsoluteLevel(p, iLangid, iIndex, iLevel)
  134861. );
  134862. if( SQLITE_ROW==sqlite3_step(pNextIdx) ){
  134863. iNext = sqlite3_column_int(pNextIdx, 0);
  134864. }
  134865. rc = sqlite3_reset(pNextIdx);
  134866. }
  134867. if( rc==SQLITE_OK ){
  134868. /* If iNext is FTS3_MERGE_COUNT, indicating that level iLevel is already
  134869. ** full, merge all segments in level iLevel into a single iLevel+1
  134870. ** segment and allocate (newly freed) index 0 at level iLevel. Otherwise,
  134871. ** if iNext is less than FTS3_MERGE_COUNT, allocate index iNext.
  134872. */
  134873. if( iNext>=FTS3_MERGE_COUNT ){
  134874. fts3LogMerge(16, getAbsoluteLevel(p, iLangid, iIndex, iLevel));
  134875. rc = fts3SegmentMerge(p, iLangid, iIndex, iLevel);
  134876. *piIdx = 0;
  134877. }else{
  134878. *piIdx = iNext;
  134879. }
  134880. }
  134881. return rc;
  134882. }
  134883. /*
  134884. ** The %_segments table is declared as follows:
  134885. **
  134886. ** CREATE TABLE %_segments(blockid INTEGER PRIMARY KEY, block BLOB)
  134887. **
  134888. ** This function reads data from a single row of the %_segments table. The
  134889. ** specific row is identified by the iBlockid parameter. If paBlob is not
  134890. ** NULL, then a buffer is allocated using sqlite3_malloc() and populated
  134891. ** with the contents of the blob stored in the "block" column of the
  134892. ** identified table row is. Whether or not paBlob is NULL, *pnBlob is set
  134893. ** to the size of the blob in bytes before returning.
  134894. **
  134895. ** If an error occurs, or the table does not contain the specified row,
  134896. ** an SQLite error code is returned. Otherwise, SQLITE_OK is returned. If
  134897. ** paBlob is non-NULL, then it is the responsibility of the caller to
  134898. ** eventually free the returned buffer.
  134899. **
  134900. ** This function may leave an open sqlite3_blob* handle in the
  134901. ** Fts3Table.pSegments variable. This handle is reused by subsequent calls
  134902. ** to this function. The handle may be closed by calling the
  134903. ** sqlite3Fts3SegmentsClose() function. Reusing a blob handle is a handy
  134904. ** performance improvement, but the blob handle should always be closed
  134905. ** before control is returned to the user (to prevent a lock being held
  134906. ** on the database file for longer than necessary). Thus, any virtual table
  134907. ** method (xFilter etc.) that may directly or indirectly call this function
  134908. ** must call sqlite3Fts3SegmentsClose() before returning.
  134909. */
  134910. SQLITE_PRIVATE int sqlite3Fts3ReadBlock(
  134911. Fts3Table *p, /* FTS3 table handle */
  134912. sqlite3_int64 iBlockid, /* Access the row with blockid=$iBlockid */
  134913. char **paBlob, /* OUT: Blob data in malloc'd buffer */
  134914. int *pnBlob, /* OUT: Size of blob data */
  134915. int *pnLoad /* OUT: Bytes actually loaded */
  134916. ){
  134917. int rc; /* Return code */
  134918. /* pnBlob must be non-NULL. paBlob may be NULL or non-NULL. */
  134919. assert( pnBlob );
  134920. if( p->pSegments ){
  134921. rc = sqlite3_blob_reopen(p->pSegments, iBlockid);
  134922. }else{
  134923. if( 0==p->zSegmentsTbl ){
  134924. p->zSegmentsTbl = sqlite3_mprintf("%s_segments", p->zName);
  134925. if( 0==p->zSegmentsTbl ) return SQLITE_NOMEM;
  134926. }
  134927. rc = sqlite3_blob_open(
  134928. p->db, p->zDb, p->zSegmentsTbl, "block", iBlockid, 0, &p->pSegments
  134929. );
  134930. }
  134931. if( rc==SQLITE_OK ){
  134932. int nByte = sqlite3_blob_bytes(p->pSegments);
  134933. *pnBlob = nByte;
  134934. if( paBlob ){
  134935. char *aByte = sqlite3_malloc(nByte + FTS3_NODE_PADDING);
  134936. if( !aByte ){
  134937. rc = SQLITE_NOMEM;
  134938. }else{
  134939. if( pnLoad && nByte>(FTS3_NODE_CHUNK_THRESHOLD) ){
  134940. nByte = FTS3_NODE_CHUNKSIZE;
  134941. *pnLoad = nByte;
  134942. }
  134943. rc = sqlite3_blob_read(p->pSegments, aByte, nByte, 0);
  134944. memset(&aByte[nByte], 0, FTS3_NODE_PADDING);
  134945. if( rc!=SQLITE_OK ){
  134946. sqlite3_free(aByte);
  134947. aByte = 0;
  134948. }
  134949. }
  134950. *paBlob = aByte;
  134951. }
  134952. }
  134953. return rc;
  134954. }
  134955. /*
  134956. ** Close the blob handle at p->pSegments, if it is open. See comments above
  134957. ** the sqlite3Fts3ReadBlock() function for details.
  134958. */
  134959. SQLITE_PRIVATE void sqlite3Fts3SegmentsClose(Fts3Table *p){
  134960. sqlite3_blob_close(p->pSegments);
  134961. p->pSegments = 0;
  134962. }
  134963. static int fts3SegReaderIncrRead(Fts3SegReader *pReader){
  134964. int nRead; /* Number of bytes to read */
  134965. int rc; /* Return code */
  134966. nRead = MIN(pReader->nNode - pReader->nPopulate, FTS3_NODE_CHUNKSIZE);
  134967. rc = sqlite3_blob_read(
  134968. pReader->pBlob,
  134969. &pReader->aNode[pReader->nPopulate],
  134970. nRead,
  134971. pReader->nPopulate
  134972. );
  134973. if( rc==SQLITE_OK ){
  134974. pReader->nPopulate += nRead;
  134975. memset(&pReader->aNode[pReader->nPopulate], 0, FTS3_NODE_PADDING);
  134976. if( pReader->nPopulate==pReader->nNode ){
  134977. sqlite3_blob_close(pReader->pBlob);
  134978. pReader->pBlob = 0;
  134979. pReader->nPopulate = 0;
  134980. }
  134981. }
  134982. return rc;
  134983. }
  134984. static int fts3SegReaderRequire(Fts3SegReader *pReader, char *pFrom, int nByte){
  134985. int rc = SQLITE_OK;
  134986. assert( !pReader->pBlob
  134987. || (pFrom>=pReader->aNode && pFrom<&pReader->aNode[pReader->nNode])
  134988. );
  134989. while( pReader->pBlob && rc==SQLITE_OK
  134990. && (pFrom - pReader->aNode + nByte)>pReader->nPopulate
  134991. ){
  134992. rc = fts3SegReaderIncrRead(pReader);
  134993. }
  134994. return rc;
  134995. }
  134996. /*
  134997. ** Set an Fts3SegReader cursor to point at EOF.
  134998. */
  134999. static void fts3SegReaderSetEof(Fts3SegReader *pSeg){
  135000. if( !fts3SegReaderIsRootOnly(pSeg) ){
  135001. sqlite3_free(pSeg->aNode);
  135002. sqlite3_blob_close(pSeg->pBlob);
  135003. pSeg->pBlob = 0;
  135004. }
  135005. pSeg->aNode = 0;
  135006. }
  135007. /*
  135008. ** Move the iterator passed as the first argument to the next term in the
  135009. ** segment. If successful, SQLITE_OK is returned. If there is no next term,
  135010. ** SQLITE_DONE. Otherwise, an SQLite error code.
  135011. */
  135012. static int fts3SegReaderNext(
  135013. Fts3Table *p,
  135014. Fts3SegReader *pReader,
  135015. int bIncr
  135016. ){
  135017. int rc; /* Return code of various sub-routines */
  135018. char *pNext; /* Cursor variable */
  135019. int nPrefix; /* Number of bytes in term prefix */
  135020. int nSuffix; /* Number of bytes in term suffix */
  135021. if( !pReader->aDoclist ){
  135022. pNext = pReader->aNode;
  135023. }else{
  135024. pNext = &pReader->aDoclist[pReader->nDoclist];
  135025. }
  135026. if( !pNext || pNext>=&pReader->aNode[pReader->nNode] ){
  135027. if( fts3SegReaderIsPending(pReader) ){
  135028. Fts3HashElem *pElem = *(pReader->ppNextElem);
  135029. if( pElem==0 ){
  135030. pReader->aNode = 0;
  135031. }else{
  135032. PendingList *pList = (PendingList *)fts3HashData(pElem);
  135033. pReader->zTerm = (char *)fts3HashKey(pElem);
  135034. pReader->nTerm = fts3HashKeysize(pElem);
  135035. pReader->nNode = pReader->nDoclist = pList->nData + 1;
  135036. pReader->aNode = pReader->aDoclist = pList->aData;
  135037. pReader->ppNextElem++;
  135038. assert( pReader->aNode );
  135039. }
  135040. return SQLITE_OK;
  135041. }
  135042. fts3SegReaderSetEof(pReader);
  135043. /* If iCurrentBlock>=iLeafEndBlock, this is an EOF condition. All leaf
  135044. ** blocks have already been traversed. */
  135045. assert( pReader->iCurrentBlock<=pReader->iLeafEndBlock );
  135046. if( pReader->iCurrentBlock>=pReader->iLeafEndBlock ){
  135047. return SQLITE_OK;
  135048. }
  135049. rc = sqlite3Fts3ReadBlock(
  135050. p, ++pReader->iCurrentBlock, &pReader->aNode, &pReader->nNode,
  135051. (bIncr ? &pReader->nPopulate : 0)
  135052. );
  135053. if( rc!=SQLITE_OK ) return rc;
  135054. assert( pReader->pBlob==0 );
  135055. if( bIncr && pReader->nPopulate<pReader->nNode ){
  135056. pReader->pBlob = p->pSegments;
  135057. p->pSegments = 0;
  135058. }
  135059. pNext = pReader->aNode;
  135060. }
  135061. assert( !fts3SegReaderIsPending(pReader) );
  135062. rc = fts3SegReaderRequire(pReader, pNext, FTS3_VARINT_MAX*2);
  135063. if( rc!=SQLITE_OK ) return rc;
  135064. /* Because of the FTS3_NODE_PADDING bytes of padding, the following is
  135065. ** safe (no risk of overread) even if the node data is corrupted. */
  135066. pNext += fts3GetVarint32(pNext, &nPrefix);
  135067. pNext += fts3GetVarint32(pNext, &nSuffix);
  135068. if( nPrefix<0 || nSuffix<=0
  135069. || &pNext[nSuffix]>&pReader->aNode[pReader->nNode]
  135070. ){
  135071. return FTS_CORRUPT_VTAB;
  135072. }
  135073. if( nPrefix+nSuffix>pReader->nTermAlloc ){
  135074. int nNew = (nPrefix+nSuffix)*2;
  135075. char *zNew = sqlite3_realloc(pReader->zTerm, nNew);
  135076. if( !zNew ){
  135077. return SQLITE_NOMEM;
  135078. }
  135079. pReader->zTerm = zNew;
  135080. pReader->nTermAlloc = nNew;
  135081. }
  135082. rc = fts3SegReaderRequire(pReader, pNext, nSuffix+FTS3_VARINT_MAX);
  135083. if( rc!=SQLITE_OK ) return rc;
  135084. memcpy(&pReader->zTerm[nPrefix], pNext, nSuffix);
  135085. pReader->nTerm = nPrefix+nSuffix;
  135086. pNext += nSuffix;
  135087. pNext += fts3GetVarint32(pNext, &pReader->nDoclist);
  135088. pReader->aDoclist = pNext;
  135089. pReader->pOffsetList = 0;
  135090. /* Check that the doclist does not appear to extend past the end of the
  135091. ** b-tree node. And that the final byte of the doclist is 0x00. If either
  135092. ** of these statements is untrue, then the data structure is corrupt.
  135093. */
  135094. if( &pReader->aDoclist[pReader->nDoclist]>&pReader->aNode[pReader->nNode]
  135095. || (pReader->nPopulate==0 && pReader->aDoclist[pReader->nDoclist-1])
  135096. ){
  135097. return FTS_CORRUPT_VTAB;
  135098. }
  135099. return SQLITE_OK;
  135100. }
  135101. /*
  135102. ** Set the SegReader to point to the first docid in the doclist associated
  135103. ** with the current term.
  135104. */
  135105. static int fts3SegReaderFirstDocid(Fts3Table *pTab, Fts3SegReader *pReader){
  135106. int rc = SQLITE_OK;
  135107. assert( pReader->aDoclist );
  135108. assert( !pReader->pOffsetList );
  135109. if( pTab->bDescIdx && fts3SegReaderIsPending(pReader) ){
  135110. u8 bEof = 0;
  135111. pReader->iDocid = 0;
  135112. pReader->nOffsetList = 0;
  135113. sqlite3Fts3DoclistPrev(0,
  135114. pReader->aDoclist, pReader->nDoclist, &pReader->pOffsetList,
  135115. &pReader->iDocid, &pReader->nOffsetList, &bEof
  135116. );
  135117. }else{
  135118. rc = fts3SegReaderRequire(pReader, pReader->aDoclist, FTS3_VARINT_MAX);
  135119. if( rc==SQLITE_OK ){
  135120. int n = sqlite3Fts3GetVarint(pReader->aDoclist, &pReader->iDocid);
  135121. pReader->pOffsetList = &pReader->aDoclist[n];
  135122. }
  135123. }
  135124. return rc;
  135125. }
  135126. /*
  135127. ** Advance the SegReader to point to the next docid in the doclist
  135128. ** associated with the current term.
  135129. **
  135130. ** If arguments ppOffsetList and pnOffsetList are not NULL, then
  135131. ** *ppOffsetList is set to point to the first column-offset list
  135132. ** in the doclist entry (i.e. immediately past the docid varint).
  135133. ** *pnOffsetList is set to the length of the set of column-offset
  135134. ** lists, not including the nul-terminator byte. For example:
  135135. */
  135136. static int fts3SegReaderNextDocid(
  135137. Fts3Table *pTab,
  135138. Fts3SegReader *pReader, /* Reader to advance to next docid */
  135139. char **ppOffsetList, /* OUT: Pointer to current position-list */
  135140. int *pnOffsetList /* OUT: Length of *ppOffsetList in bytes */
  135141. ){
  135142. int rc = SQLITE_OK;
  135143. char *p = pReader->pOffsetList;
  135144. char c = 0;
  135145. assert( p );
  135146. if( pTab->bDescIdx && fts3SegReaderIsPending(pReader) ){
  135147. /* A pending-terms seg-reader for an FTS4 table that uses order=desc.
  135148. ** Pending-terms doclists are always built up in ascending order, so
  135149. ** we have to iterate through them backwards here. */
  135150. u8 bEof = 0;
  135151. if( ppOffsetList ){
  135152. *ppOffsetList = pReader->pOffsetList;
  135153. *pnOffsetList = pReader->nOffsetList - 1;
  135154. }
  135155. sqlite3Fts3DoclistPrev(0,
  135156. pReader->aDoclist, pReader->nDoclist, &p, &pReader->iDocid,
  135157. &pReader->nOffsetList, &bEof
  135158. );
  135159. if( bEof ){
  135160. pReader->pOffsetList = 0;
  135161. }else{
  135162. pReader->pOffsetList = p;
  135163. }
  135164. }else{
  135165. char *pEnd = &pReader->aDoclist[pReader->nDoclist];
  135166. /* Pointer p currently points at the first byte of an offset list. The
  135167. ** following block advances it to point one byte past the end of
  135168. ** the same offset list. */
  135169. while( 1 ){
  135170. /* The following line of code (and the "p++" below the while() loop) is
  135171. ** normally all that is required to move pointer p to the desired
  135172. ** position. The exception is if this node is being loaded from disk
  135173. ** incrementally and pointer "p" now points to the first byte past
  135174. ** the populated part of pReader->aNode[].
  135175. */
  135176. while( *p | c ) c = *p++ & 0x80;
  135177. assert( *p==0 );
  135178. if( pReader->pBlob==0 || p<&pReader->aNode[pReader->nPopulate] ) break;
  135179. rc = fts3SegReaderIncrRead(pReader);
  135180. if( rc!=SQLITE_OK ) return rc;
  135181. }
  135182. p++;
  135183. /* If required, populate the output variables with a pointer to and the
  135184. ** size of the previous offset-list.
  135185. */
  135186. if( ppOffsetList ){
  135187. *ppOffsetList = pReader->pOffsetList;
  135188. *pnOffsetList = (int)(p - pReader->pOffsetList - 1);
  135189. }
  135190. /* List may have been edited in place by fts3EvalNearTrim() */
  135191. while( p<pEnd && *p==0 ) p++;
  135192. /* If there are no more entries in the doclist, set pOffsetList to
  135193. ** NULL. Otherwise, set Fts3SegReader.iDocid to the next docid and
  135194. ** Fts3SegReader.pOffsetList to point to the next offset list before
  135195. ** returning.
  135196. */
  135197. if( p>=pEnd ){
  135198. pReader->pOffsetList = 0;
  135199. }else{
  135200. rc = fts3SegReaderRequire(pReader, p, FTS3_VARINT_MAX);
  135201. if( rc==SQLITE_OK ){
  135202. sqlite3_int64 iDelta;
  135203. pReader->pOffsetList = p + sqlite3Fts3GetVarint(p, &iDelta);
  135204. if( pTab->bDescIdx ){
  135205. pReader->iDocid -= iDelta;
  135206. }else{
  135207. pReader->iDocid += iDelta;
  135208. }
  135209. }
  135210. }
  135211. }
  135212. return SQLITE_OK;
  135213. }
  135214. SQLITE_PRIVATE int sqlite3Fts3MsrOvfl(
  135215. Fts3Cursor *pCsr,
  135216. Fts3MultiSegReader *pMsr,
  135217. int *pnOvfl
  135218. ){
  135219. Fts3Table *p = (Fts3Table*)pCsr->base.pVtab;
  135220. int nOvfl = 0;
  135221. int ii;
  135222. int rc = SQLITE_OK;
  135223. int pgsz = p->nPgsz;
  135224. assert( p->bFts4 );
  135225. assert( pgsz>0 );
  135226. for(ii=0; rc==SQLITE_OK && ii<pMsr->nSegment; ii++){
  135227. Fts3SegReader *pReader = pMsr->apSegment[ii];
  135228. if( !fts3SegReaderIsPending(pReader)
  135229. && !fts3SegReaderIsRootOnly(pReader)
  135230. ){
  135231. sqlite3_int64 jj;
  135232. for(jj=pReader->iStartBlock; jj<=pReader->iLeafEndBlock; jj++){
  135233. int nBlob;
  135234. rc = sqlite3Fts3ReadBlock(p, jj, 0, &nBlob, 0);
  135235. if( rc!=SQLITE_OK ) break;
  135236. if( (nBlob+35)>pgsz ){
  135237. nOvfl += (nBlob + 34)/pgsz;
  135238. }
  135239. }
  135240. }
  135241. }
  135242. *pnOvfl = nOvfl;
  135243. return rc;
  135244. }
  135245. /*
  135246. ** Free all allocations associated with the iterator passed as the
  135247. ** second argument.
  135248. */
  135249. SQLITE_PRIVATE void sqlite3Fts3SegReaderFree(Fts3SegReader *pReader){
  135250. if( pReader && !fts3SegReaderIsPending(pReader) ){
  135251. sqlite3_free(pReader->zTerm);
  135252. if( !fts3SegReaderIsRootOnly(pReader) ){
  135253. sqlite3_free(pReader->aNode);
  135254. sqlite3_blob_close(pReader->pBlob);
  135255. }
  135256. }
  135257. sqlite3_free(pReader);
  135258. }
  135259. /*
  135260. ** Allocate a new SegReader object.
  135261. */
  135262. SQLITE_PRIVATE int sqlite3Fts3SegReaderNew(
  135263. int iAge, /* Segment "age". */
  135264. int bLookup, /* True for a lookup only */
  135265. sqlite3_int64 iStartLeaf, /* First leaf to traverse */
  135266. sqlite3_int64 iEndLeaf, /* Final leaf to traverse */
  135267. sqlite3_int64 iEndBlock, /* Final block of segment */
  135268. const char *zRoot, /* Buffer containing root node */
  135269. int nRoot, /* Size of buffer containing root node */
  135270. Fts3SegReader **ppReader /* OUT: Allocated Fts3SegReader */
  135271. ){
  135272. Fts3SegReader *pReader; /* Newly allocated SegReader object */
  135273. int nExtra = 0; /* Bytes to allocate segment root node */
  135274. assert( iStartLeaf<=iEndLeaf );
  135275. if( iStartLeaf==0 ){
  135276. nExtra = nRoot + FTS3_NODE_PADDING;
  135277. }
  135278. pReader = (Fts3SegReader *)sqlite3_malloc(sizeof(Fts3SegReader) + nExtra);
  135279. if( !pReader ){
  135280. return SQLITE_NOMEM;
  135281. }
  135282. memset(pReader, 0, sizeof(Fts3SegReader));
  135283. pReader->iIdx = iAge;
  135284. pReader->bLookup = bLookup!=0;
  135285. pReader->iStartBlock = iStartLeaf;
  135286. pReader->iLeafEndBlock = iEndLeaf;
  135287. pReader->iEndBlock = iEndBlock;
  135288. if( nExtra ){
  135289. /* The entire segment is stored in the root node. */
  135290. pReader->aNode = (char *)&pReader[1];
  135291. pReader->rootOnly = 1;
  135292. pReader->nNode = nRoot;
  135293. memcpy(pReader->aNode, zRoot, nRoot);
  135294. memset(&pReader->aNode[nRoot], 0, FTS3_NODE_PADDING);
  135295. }else{
  135296. pReader->iCurrentBlock = iStartLeaf-1;
  135297. }
  135298. *ppReader = pReader;
  135299. return SQLITE_OK;
  135300. }
  135301. /*
  135302. ** This is a comparison function used as a qsort() callback when sorting
  135303. ** an array of pending terms by term. This occurs as part of flushing
  135304. ** the contents of the pending-terms hash table to the database.
  135305. */
  135306. static int SQLITE_CDECL fts3CompareElemByTerm(
  135307. const void *lhs,
  135308. const void *rhs
  135309. ){
  135310. char *z1 = fts3HashKey(*(Fts3HashElem **)lhs);
  135311. char *z2 = fts3HashKey(*(Fts3HashElem **)rhs);
  135312. int n1 = fts3HashKeysize(*(Fts3HashElem **)lhs);
  135313. int n2 = fts3HashKeysize(*(Fts3HashElem **)rhs);
  135314. int n = (n1<n2 ? n1 : n2);
  135315. int c = memcmp(z1, z2, n);
  135316. if( c==0 ){
  135317. c = n1 - n2;
  135318. }
  135319. return c;
  135320. }
  135321. /*
  135322. ** This function is used to allocate an Fts3SegReader that iterates through
  135323. ** a subset of the terms stored in the Fts3Table.pendingTerms array.
  135324. **
  135325. ** If the isPrefixIter parameter is zero, then the returned SegReader iterates
  135326. ** through each term in the pending-terms table. Or, if isPrefixIter is
  135327. ** non-zero, it iterates through each term and its prefixes. For example, if
  135328. ** the pending terms hash table contains the terms "sqlite", "mysql" and
  135329. ** "firebird", then the iterator visits the following 'terms' (in the order
  135330. ** shown):
  135331. **
  135332. ** f fi fir fire fireb firebi firebir firebird
  135333. ** m my mys mysq mysql
  135334. ** s sq sql sqli sqlit sqlite
  135335. **
  135336. ** Whereas if isPrefixIter is zero, the terms visited are:
  135337. **
  135338. ** firebird mysql sqlite
  135339. */
  135340. SQLITE_PRIVATE int sqlite3Fts3SegReaderPending(
  135341. Fts3Table *p, /* Virtual table handle */
  135342. int iIndex, /* Index for p->aIndex */
  135343. const char *zTerm, /* Term to search for */
  135344. int nTerm, /* Size of buffer zTerm */
  135345. int bPrefix, /* True for a prefix iterator */
  135346. Fts3SegReader **ppReader /* OUT: SegReader for pending-terms */
  135347. ){
  135348. Fts3SegReader *pReader = 0; /* Fts3SegReader object to return */
  135349. Fts3HashElem *pE; /* Iterator variable */
  135350. Fts3HashElem **aElem = 0; /* Array of term hash entries to scan */
  135351. int nElem = 0; /* Size of array at aElem */
  135352. int rc = SQLITE_OK; /* Return Code */
  135353. Fts3Hash *pHash;
  135354. pHash = &p->aIndex[iIndex].hPending;
  135355. if( bPrefix ){
  135356. int nAlloc = 0; /* Size of allocated array at aElem */
  135357. for(pE=fts3HashFirst(pHash); pE; pE=fts3HashNext(pE)){
  135358. char *zKey = (char *)fts3HashKey(pE);
  135359. int nKey = fts3HashKeysize(pE);
  135360. if( nTerm==0 || (nKey>=nTerm && 0==memcmp(zKey, zTerm, nTerm)) ){
  135361. if( nElem==nAlloc ){
  135362. Fts3HashElem **aElem2;
  135363. nAlloc += 16;
  135364. aElem2 = (Fts3HashElem **)sqlite3_realloc(
  135365. aElem, nAlloc*sizeof(Fts3HashElem *)
  135366. );
  135367. if( !aElem2 ){
  135368. rc = SQLITE_NOMEM;
  135369. nElem = 0;
  135370. break;
  135371. }
  135372. aElem = aElem2;
  135373. }
  135374. aElem[nElem++] = pE;
  135375. }
  135376. }
  135377. /* If more than one term matches the prefix, sort the Fts3HashElem
  135378. ** objects in term order using qsort(). This uses the same comparison
  135379. ** callback as is used when flushing terms to disk.
  135380. */
  135381. if( nElem>1 ){
  135382. qsort(aElem, nElem, sizeof(Fts3HashElem *), fts3CompareElemByTerm);
  135383. }
  135384. }else{
  135385. /* The query is a simple term lookup that matches at most one term in
  135386. ** the index. All that is required is a straight hash-lookup.
  135387. **
  135388. ** Because the stack address of pE may be accessed via the aElem pointer
  135389. ** below, the "Fts3HashElem *pE" must be declared so that it is valid
  135390. ** within this entire function, not just this "else{...}" block.
  135391. */
  135392. pE = fts3HashFindElem(pHash, zTerm, nTerm);
  135393. if( pE ){
  135394. aElem = &pE;
  135395. nElem = 1;
  135396. }
  135397. }
  135398. if( nElem>0 ){
  135399. int nByte = sizeof(Fts3SegReader) + (nElem+1)*sizeof(Fts3HashElem *);
  135400. pReader = (Fts3SegReader *)sqlite3_malloc(nByte);
  135401. if( !pReader ){
  135402. rc = SQLITE_NOMEM;
  135403. }else{
  135404. memset(pReader, 0, nByte);
  135405. pReader->iIdx = 0x7FFFFFFF;
  135406. pReader->ppNextElem = (Fts3HashElem **)&pReader[1];
  135407. memcpy(pReader->ppNextElem, aElem, nElem*sizeof(Fts3HashElem *));
  135408. }
  135409. }
  135410. if( bPrefix ){
  135411. sqlite3_free(aElem);
  135412. }
  135413. *ppReader = pReader;
  135414. return rc;
  135415. }
  135416. /*
  135417. ** Compare the entries pointed to by two Fts3SegReader structures.
  135418. ** Comparison is as follows:
  135419. **
  135420. ** 1) EOF is greater than not EOF.
  135421. **
  135422. ** 2) The current terms (if any) are compared using memcmp(). If one
  135423. ** term is a prefix of another, the longer term is considered the
  135424. ** larger.
  135425. **
  135426. ** 3) By segment age. An older segment is considered larger.
  135427. */
  135428. static int fts3SegReaderCmp(Fts3SegReader *pLhs, Fts3SegReader *pRhs){
  135429. int rc;
  135430. if( pLhs->aNode && pRhs->aNode ){
  135431. int rc2 = pLhs->nTerm - pRhs->nTerm;
  135432. if( rc2<0 ){
  135433. rc = memcmp(pLhs->zTerm, pRhs->zTerm, pLhs->nTerm);
  135434. }else{
  135435. rc = memcmp(pLhs->zTerm, pRhs->zTerm, pRhs->nTerm);
  135436. }
  135437. if( rc==0 ){
  135438. rc = rc2;
  135439. }
  135440. }else{
  135441. rc = (pLhs->aNode==0) - (pRhs->aNode==0);
  135442. }
  135443. if( rc==0 ){
  135444. rc = pRhs->iIdx - pLhs->iIdx;
  135445. }
  135446. assert( rc!=0 );
  135447. return rc;
  135448. }
  135449. /*
  135450. ** A different comparison function for SegReader structures. In this
  135451. ** version, it is assumed that each SegReader points to an entry in
  135452. ** a doclist for identical terms. Comparison is made as follows:
  135453. **
  135454. ** 1) EOF (end of doclist in this case) is greater than not EOF.
  135455. **
  135456. ** 2) By current docid.
  135457. **
  135458. ** 3) By segment age. An older segment is considered larger.
  135459. */
  135460. static int fts3SegReaderDoclistCmp(Fts3SegReader *pLhs, Fts3SegReader *pRhs){
  135461. int rc = (pLhs->pOffsetList==0)-(pRhs->pOffsetList==0);
  135462. if( rc==0 ){
  135463. if( pLhs->iDocid==pRhs->iDocid ){
  135464. rc = pRhs->iIdx - pLhs->iIdx;
  135465. }else{
  135466. rc = (pLhs->iDocid > pRhs->iDocid) ? 1 : -1;
  135467. }
  135468. }
  135469. assert( pLhs->aNode && pRhs->aNode );
  135470. return rc;
  135471. }
  135472. static int fts3SegReaderDoclistCmpRev(Fts3SegReader *pLhs, Fts3SegReader *pRhs){
  135473. int rc = (pLhs->pOffsetList==0)-(pRhs->pOffsetList==0);
  135474. if( rc==0 ){
  135475. if( pLhs->iDocid==pRhs->iDocid ){
  135476. rc = pRhs->iIdx - pLhs->iIdx;
  135477. }else{
  135478. rc = (pLhs->iDocid < pRhs->iDocid) ? 1 : -1;
  135479. }
  135480. }
  135481. assert( pLhs->aNode && pRhs->aNode );
  135482. return rc;
  135483. }
  135484. /*
  135485. ** Compare the term that the Fts3SegReader object passed as the first argument
  135486. ** points to with the term specified by arguments zTerm and nTerm.
  135487. **
  135488. ** If the pSeg iterator is already at EOF, return 0. Otherwise, return
  135489. ** -ve if the pSeg term is less than zTerm/nTerm, 0 if the two terms are
  135490. ** equal, or +ve if the pSeg term is greater than zTerm/nTerm.
  135491. */
  135492. static int fts3SegReaderTermCmp(
  135493. Fts3SegReader *pSeg, /* Segment reader object */
  135494. const char *zTerm, /* Term to compare to */
  135495. int nTerm /* Size of term zTerm in bytes */
  135496. ){
  135497. int res = 0;
  135498. if( pSeg->aNode ){
  135499. if( pSeg->nTerm>nTerm ){
  135500. res = memcmp(pSeg->zTerm, zTerm, nTerm);
  135501. }else{
  135502. res = memcmp(pSeg->zTerm, zTerm, pSeg->nTerm);
  135503. }
  135504. if( res==0 ){
  135505. res = pSeg->nTerm-nTerm;
  135506. }
  135507. }
  135508. return res;
  135509. }
  135510. /*
  135511. ** Argument apSegment is an array of nSegment elements. It is known that
  135512. ** the final (nSegment-nSuspect) members are already in sorted order
  135513. ** (according to the comparison function provided). This function shuffles
  135514. ** the array around until all entries are in sorted order.
  135515. */
  135516. static void fts3SegReaderSort(
  135517. Fts3SegReader **apSegment, /* Array to sort entries of */
  135518. int nSegment, /* Size of apSegment array */
  135519. int nSuspect, /* Unsorted entry count */
  135520. int (*xCmp)(Fts3SegReader *, Fts3SegReader *) /* Comparison function */
  135521. ){
  135522. int i; /* Iterator variable */
  135523. assert( nSuspect<=nSegment );
  135524. if( nSuspect==nSegment ) nSuspect--;
  135525. for(i=nSuspect-1; i>=0; i--){
  135526. int j;
  135527. for(j=i; j<(nSegment-1); j++){
  135528. Fts3SegReader *pTmp;
  135529. if( xCmp(apSegment[j], apSegment[j+1])<0 ) break;
  135530. pTmp = apSegment[j+1];
  135531. apSegment[j+1] = apSegment[j];
  135532. apSegment[j] = pTmp;
  135533. }
  135534. }
  135535. #ifndef NDEBUG
  135536. /* Check that the list really is sorted now. */
  135537. for(i=0; i<(nSuspect-1); i++){
  135538. assert( xCmp(apSegment[i], apSegment[i+1])<0 );
  135539. }
  135540. #endif
  135541. }
  135542. /*
  135543. ** Insert a record into the %_segments table.
  135544. */
  135545. static int fts3WriteSegment(
  135546. Fts3Table *p, /* Virtual table handle */
  135547. sqlite3_int64 iBlock, /* Block id for new block */
  135548. char *z, /* Pointer to buffer containing block data */
  135549. int n /* Size of buffer z in bytes */
  135550. ){
  135551. sqlite3_stmt *pStmt;
  135552. int rc = fts3SqlStmt(p, SQL_INSERT_SEGMENTS, &pStmt, 0);
  135553. if( rc==SQLITE_OK ){
  135554. sqlite3_bind_int64(pStmt, 1, iBlock);
  135555. sqlite3_bind_blob(pStmt, 2, z, n, SQLITE_STATIC);
  135556. sqlite3_step(pStmt);
  135557. rc = sqlite3_reset(pStmt);
  135558. }
  135559. return rc;
  135560. }
  135561. /*
  135562. ** Find the largest relative level number in the table. If successful, set
  135563. ** *pnMax to this value and return SQLITE_OK. Otherwise, if an error occurs,
  135564. ** set *pnMax to zero and return an SQLite error code.
  135565. */
  135566. SQLITE_PRIVATE int sqlite3Fts3MaxLevel(Fts3Table *p, int *pnMax){
  135567. int rc;
  135568. int mxLevel = 0;
  135569. sqlite3_stmt *pStmt = 0;
  135570. rc = fts3SqlStmt(p, SQL_SELECT_MXLEVEL, &pStmt, 0);
  135571. if( rc==SQLITE_OK ){
  135572. if( SQLITE_ROW==sqlite3_step(pStmt) ){
  135573. mxLevel = sqlite3_column_int(pStmt, 0);
  135574. }
  135575. rc = sqlite3_reset(pStmt);
  135576. }
  135577. *pnMax = mxLevel;
  135578. return rc;
  135579. }
  135580. /*
  135581. ** Insert a record into the %_segdir table.
  135582. */
  135583. static int fts3WriteSegdir(
  135584. Fts3Table *p, /* Virtual table handle */
  135585. sqlite3_int64 iLevel, /* Value for "level" field (absolute level) */
  135586. int iIdx, /* Value for "idx" field */
  135587. sqlite3_int64 iStartBlock, /* Value for "start_block" field */
  135588. sqlite3_int64 iLeafEndBlock, /* Value for "leaves_end_block" field */
  135589. sqlite3_int64 iEndBlock, /* Value for "end_block" field */
  135590. sqlite3_int64 nLeafData, /* Bytes of leaf data in segment */
  135591. char *zRoot, /* Blob value for "root" field */
  135592. int nRoot /* Number of bytes in buffer zRoot */
  135593. ){
  135594. sqlite3_stmt *pStmt;
  135595. int rc = fts3SqlStmt(p, SQL_INSERT_SEGDIR, &pStmt, 0);
  135596. if( rc==SQLITE_OK ){
  135597. sqlite3_bind_int64(pStmt, 1, iLevel);
  135598. sqlite3_bind_int(pStmt, 2, iIdx);
  135599. sqlite3_bind_int64(pStmt, 3, iStartBlock);
  135600. sqlite3_bind_int64(pStmt, 4, iLeafEndBlock);
  135601. if( nLeafData==0 ){
  135602. sqlite3_bind_int64(pStmt, 5, iEndBlock);
  135603. }else{
  135604. char *zEnd = sqlite3_mprintf("%lld %lld", iEndBlock, nLeafData);
  135605. if( !zEnd ) return SQLITE_NOMEM;
  135606. sqlite3_bind_text(pStmt, 5, zEnd, -1, sqlite3_free);
  135607. }
  135608. sqlite3_bind_blob(pStmt, 6, zRoot, nRoot, SQLITE_STATIC);
  135609. sqlite3_step(pStmt);
  135610. rc = sqlite3_reset(pStmt);
  135611. }
  135612. return rc;
  135613. }
  135614. /*
  135615. ** Return the size of the common prefix (if any) shared by zPrev and
  135616. ** zNext, in bytes. For example,
  135617. **
  135618. ** fts3PrefixCompress("abc", 3, "abcdef", 6) // returns 3
  135619. ** fts3PrefixCompress("abX", 3, "abcdef", 6) // returns 2
  135620. ** fts3PrefixCompress("abX", 3, "Xbcdef", 6) // returns 0
  135621. */
  135622. static int fts3PrefixCompress(
  135623. const char *zPrev, /* Buffer containing previous term */
  135624. int nPrev, /* Size of buffer zPrev in bytes */
  135625. const char *zNext, /* Buffer containing next term */
  135626. int nNext /* Size of buffer zNext in bytes */
  135627. ){
  135628. int n;
  135629. UNUSED_PARAMETER(nNext);
  135630. for(n=0; n<nPrev && zPrev[n]==zNext[n]; n++);
  135631. return n;
  135632. }
  135633. /*
  135634. ** Add term zTerm to the SegmentNode. It is guaranteed that zTerm is larger
  135635. ** (according to memcmp) than the previous term.
  135636. */
  135637. static int fts3NodeAddTerm(
  135638. Fts3Table *p, /* Virtual table handle */
  135639. SegmentNode **ppTree, /* IN/OUT: SegmentNode handle */
  135640. int isCopyTerm, /* True if zTerm/nTerm is transient */
  135641. const char *zTerm, /* Pointer to buffer containing term */
  135642. int nTerm /* Size of term in bytes */
  135643. ){
  135644. SegmentNode *pTree = *ppTree;
  135645. int rc;
  135646. SegmentNode *pNew;
  135647. /* First try to append the term to the current node. Return early if
  135648. ** this is possible.
  135649. */
  135650. if( pTree ){
  135651. int nData = pTree->nData; /* Current size of node in bytes */
  135652. int nReq = nData; /* Required space after adding zTerm */
  135653. int nPrefix; /* Number of bytes of prefix compression */
  135654. int nSuffix; /* Suffix length */
  135655. nPrefix = fts3PrefixCompress(pTree->zTerm, pTree->nTerm, zTerm, nTerm);
  135656. nSuffix = nTerm-nPrefix;
  135657. nReq += sqlite3Fts3VarintLen(nPrefix)+sqlite3Fts3VarintLen(nSuffix)+nSuffix;
  135658. if( nReq<=p->nNodeSize || !pTree->zTerm ){
  135659. if( nReq>p->nNodeSize ){
  135660. /* An unusual case: this is the first term to be added to the node
  135661. ** and the static node buffer (p->nNodeSize bytes) is not large
  135662. ** enough. Use a separately malloced buffer instead This wastes
  135663. ** p->nNodeSize bytes, but since this scenario only comes about when
  135664. ** the database contain two terms that share a prefix of almost 2KB,
  135665. ** this is not expected to be a serious problem.
  135666. */
  135667. assert( pTree->aData==(char *)&pTree[1] );
  135668. pTree->aData = (char *)sqlite3_malloc(nReq);
  135669. if( !pTree->aData ){
  135670. return SQLITE_NOMEM;
  135671. }
  135672. }
  135673. if( pTree->zTerm ){
  135674. /* There is no prefix-length field for first term in a node */
  135675. nData += sqlite3Fts3PutVarint(&pTree->aData[nData], nPrefix);
  135676. }
  135677. nData += sqlite3Fts3PutVarint(&pTree->aData[nData], nSuffix);
  135678. memcpy(&pTree->aData[nData], &zTerm[nPrefix], nSuffix);
  135679. pTree->nData = nData + nSuffix;
  135680. pTree->nEntry++;
  135681. if( isCopyTerm ){
  135682. if( pTree->nMalloc<nTerm ){
  135683. char *zNew = sqlite3_realloc(pTree->zMalloc, nTerm*2);
  135684. if( !zNew ){
  135685. return SQLITE_NOMEM;
  135686. }
  135687. pTree->nMalloc = nTerm*2;
  135688. pTree->zMalloc = zNew;
  135689. }
  135690. pTree->zTerm = pTree->zMalloc;
  135691. memcpy(pTree->zTerm, zTerm, nTerm);
  135692. pTree->nTerm = nTerm;
  135693. }else{
  135694. pTree->zTerm = (char *)zTerm;
  135695. pTree->nTerm = nTerm;
  135696. }
  135697. return SQLITE_OK;
  135698. }
  135699. }
  135700. /* If control flows to here, it was not possible to append zTerm to the
  135701. ** current node. Create a new node (a right-sibling of the current node).
  135702. ** If this is the first node in the tree, the term is added to it.
  135703. **
  135704. ** Otherwise, the term is not added to the new node, it is left empty for
  135705. ** now. Instead, the term is inserted into the parent of pTree. If pTree
  135706. ** has no parent, one is created here.
  135707. */
  135708. pNew = (SegmentNode *)sqlite3_malloc(sizeof(SegmentNode) + p->nNodeSize);
  135709. if( !pNew ){
  135710. return SQLITE_NOMEM;
  135711. }
  135712. memset(pNew, 0, sizeof(SegmentNode));
  135713. pNew->nData = 1 + FTS3_VARINT_MAX;
  135714. pNew->aData = (char *)&pNew[1];
  135715. if( pTree ){
  135716. SegmentNode *pParent = pTree->pParent;
  135717. rc = fts3NodeAddTerm(p, &pParent, isCopyTerm, zTerm, nTerm);
  135718. if( pTree->pParent==0 ){
  135719. pTree->pParent = pParent;
  135720. }
  135721. pTree->pRight = pNew;
  135722. pNew->pLeftmost = pTree->pLeftmost;
  135723. pNew->pParent = pParent;
  135724. pNew->zMalloc = pTree->zMalloc;
  135725. pNew->nMalloc = pTree->nMalloc;
  135726. pTree->zMalloc = 0;
  135727. }else{
  135728. pNew->pLeftmost = pNew;
  135729. rc = fts3NodeAddTerm(p, &pNew, isCopyTerm, zTerm, nTerm);
  135730. }
  135731. *ppTree = pNew;
  135732. return rc;
  135733. }
  135734. /*
  135735. ** Helper function for fts3NodeWrite().
  135736. */
  135737. static int fts3TreeFinishNode(
  135738. SegmentNode *pTree,
  135739. int iHeight,
  135740. sqlite3_int64 iLeftChild
  135741. ){
  135742. int nStart;
  135743. assert( iHeight>=1 && iHeight<128 );
  135744. nStart = FTS3_VARINT_MAX - sqlite3Fts3VarintLen(iLeftChild);
  135745. pTree->aData[nStart] = (char)iHeight;
  135746. sqlite3Fts3PutVarint(&pTree->aData[nStart+1], iLeftChild);
  135747. return nStart;
  135748. }
  135749. /*
  135750. ** Write the buffer for the segment node pTree and all of its peers to the
  135751. ** database. Then call this function recursively to write the parent of
  135752. ** pTree and its peers to the database.
  135753. **
  135754. ** Except, if pTree is a root node, do not write it to the database. Instead,
  135755. ** set output variables *paRoot and *pnRoot to contain the root node.
  135756. **
  135757. ** If successful, SQLITE_OK is returned and output variable *piLast is
  135758. ** set to the largest blockid written to the database (or zero if no
  135759. ** blocks were written to the db). Otherwise, an SQLite error code is
  135760. ** returned.
  135761. */
  135762. static int fts3NodeWrite(
  135763. Fts3Table *p, /* Virtual table handle */
  135764. SegmentNode *pTree, /* SegmentNode handle */
  135765. int iHeight, /* Height of this node in tree */
  135766. sqlite3_int64 iLeaf, /* Block id of first leaf node */
  135767. sqlite3_int64 iFree, /* Block id of next free slot in %_segments */
  135768. sqlite3_int64 *piLast, /* OUT: Block id of last entry written */
  135769. char **paRoot, /* OUT: Data for root node */
  135770. int *pnRoot /* OUT: Size of root node in bytes */
  135771. ){
  135772. int rc = SQLITE_OK;
  135773. if( !pTree->pParent ){
  135774. /* Root node of the tree. */
  135775. int nStart = fts3TreeFinishNode(pTree, iHeight, iLeaf);
  135776. *piLast = iFree-1;
  135777. *pnRoot = pTree->nData - nStart;
  135778. *paRoot = &pTree->aData[nStart];
  135779. }else{
  135780. SegmentNode *pIter;
  135781. sqlite3_int64 iNextFree = iFree;
  135782. sqlite3_int64 iNextLeaf = iLeaf;
  135783. for(pIter=pTree->pLeftmost; pIter && rc==SQLITE_OK; pIter=pIter->pRight){
  135784. int nStart = fts3TreeFinishNode(pIter, iHeight, iNextLeaf);
  135785. int nWrite = pIter->nData - nStart;
  135786. rc = fts3WriteSegment(p, iNextFree, &pIter->aData[nStart], nWrite);
  135787. iNextFree++;
  135788. iNextLeaf += (pIter->nEntry+1);
  135789. }
  135790. if( rc==SQLITE_OK ){
  135791. assert( iNextLeaf==iFree );
  135792. rc = fts3NodeWrite(
  135793. p, pTree->pParent, iHeight+1, iFree, iNextFree, piLast, paRoot, pnRoot
  135794. );
  135795. }
  135796. }
  135797. return rc;
  135798. }
  135799. /*
  135800. ** Free all memory allocations associated with the tree pTree.
  135801. */
  135802. static void fts3NodeFree(SegmentNode *pTree){
  135803. if( pTree ){
  135804. SegmentNode *p = pTree->pLeftmost;
  135805. fts3NodeFree(p->pParent);
  135806. while( p ){
  135807. SegmentNode *pRight = p->pRight;
  135808. if( p->aData!=(char *)&p[1] ){
  135809. sqlite3_free(p->aData);
  135810. }
  135811. assert( pRight==0 || p->zMalloc==0 );
  135812. sqlite3_free(p->zMalloc);
  135813. sqlite3_free(p);
  135814. p = pRight;
  135815. }
  135816. }
  135817. }
  135818. /*
  135819. ** Add a term to the segment being constructed by the SegmentWriter object
  135820. ** *ppWriter. When adding the first term to a segment, *ppWriter should
  135821. ** be passed NULL. This function will allocate a new SegmentWriter object
  135822. ** and return it via the input/output variable *ppWriter in this case.
  135823. **
  135824. ** If successful, SQLITE_OK is returned. Otherwise, an SQLite error code.
  135825. */
  135826. static int fts3SegWriterAdd(
  135827. Fts3Table *p, /* Virtual table handle */
  135828. SegmentWriter **ppWriter, /* IN/OUT: SegmentWriter handle */
  135829. int isCopyTerm, /* True if buffer zTerm must be copied */
  135830. const char *zTerm, /* Pointer to buffer containing term */
  135831. int nTerm, /* Size of term in bytes */
  135832. const char *aDoclist, /* Pointer to buffer containing doclist */
  135833. int nDoclist /* Size of doclist in bytes */
  135834. ){
  135835. int nPrefix; /* Size of term prefix in bytes */
  135836. int nSuffix; /* Size of term suffix in bytes */
  135837. int nReq; /* Number of bytes required on leaf page */
  135838. int nData;
  135839. SegmentWriter *pWriter = *ppWriter;
  135840. if( !pWriter ){
  135841. int rc;
  135842. sqlite3_stmt *pStmt;
  135843. /* Allocate the SegmentWriter structure */
  135844. pWriter = (SegmentWriter *)sqlite3_malloc(sizeof(SegmentWriter));
  135845. if( !pWriter ) return SQLITE_NOMEM;
  135846. memset(pWriter, 0, sizeof(SegmentWriter));
  135847. *ppWriter = pWriter;
  135848. /* Allocate a buffer in which to accumulate data */
  135849. pWriter->aData = (char *)sqlite3_malloc(p->nNodeSize);
  135850. if( !pWriter->aData ) return SQLITE_NOMEM;
  135851. pWriter->nSize = p->nNodeSize;
  135852. /* Find the next free blockid in the %_segments table */
  135853. rc = fts3SqlStmt(p, SQL_NEXT_SEGMENTS_ID, &pStmt, 0);
  135854. if( rc!=SQLITE_OK ) return rc;
  135855. if( SQLITE_ROW==sqlite3_step(pStmt) ){
  135856. pWriter->iFree = sqlite3_column_int64(pStmt, 0);
  135857. pWriter->iFirst = pWriter->iFree;
  135858. }
  135859. rc = sqlite3_reset(pStmt);
  135860. if( rc!=SQLITE_OK ) return rc;
  135861. }
  135862. nData = pWriter->nData;
  135863. nPrefix = fts3PrefixCompress(pWriter->zTerm, pWriter->nTerm, zTerm, nTerm);
  135864. nSuffix = nTerm-nPrefix;
  135865. /* Figure out how many bytes are required by this new entry */
  135866. nReq = sqlite3Fts3VarintLen(nPrefix) + /* varint containing prefix size */
  135867. sqlite3Fts3VarintLen(nSuffix) + /* varint containing suffix size */
  135868. nSuffix + /* Term suffix */
  135869. sqlite3Fts3VarintLen(nDoclist) + /* Size of doclist */
  135870. nDoclist; /* Doclist data */
  135871. if( nData>0 && nData+nReq>p->nNodeSize ){
  135872. int rc;
  135873. /* The current leaf node is full. Write it out to the database. */
  135874. rc = fts3WriteSegment(p, pWriter->iFree++, pWriter->aData, nData);
  135875. if( rc!=SQLITE_OK ) return rc;
  135876. p->nLeafAdd++;
  135877. /* Add the current term to the interior node tree. The term added to
  135878. ** the interior tree must:
  135879. **
  135880. ** a) be greater than the largest term on the leaf node just written
  135881. ** to the database (still available in pWriter->zTerm), and
  135882. **
  135883. ** b) be less than or equal to the term about to be added to the new
  135884. ** leaf node (zTerm/nTerm).
  135885. **
  135886. ** In other words, it must be the prefix of zTerm 1 byte longer than
  135887. ** the common prefix (if any) of zTerm and pWriter->zTerm.
  135888. */
  135889. assert( nPrefix<nTerm );
  135890. rc = fts3NodeAddTerm(p, &pWriter->pTree, isCopyTerm, zTerm, nPrefix+1);
  135891. if( rc!=SQLITE_OK ) return rc;
  135892. nData = 0;
  135893. pWriter->nTerm = 0;
  135894. nPrefix = 0;
  135895. nSuffix = nTerm;
  135896. nReq = 1 + /* varint containing prefix size */
  135897. sqlite3Fts3VarintLen(nTerm) + /* varint containing suffix size */
  135898. nTerm + /* Term suffix */
  135899. sqlite3Fts3VarintLen(nDoclist) + /* Size of doclist */
  135900. nDoclist; /* Doclist data */
  135901. }
  135902. /* Increase the total number of bytes written to account for the new entry. */
  135903. pWriter->nLeafData += nReq;
  135904. /* If the buffer currently allocated is too small for this entry, realloc
  135905. ** the buffer to make it large enough.
  135906. */
  135907. if( nReq>pWriter->nSize ){
  135908. char *aNew = sqlite3_realloc(pWriter->aData, nReq);
  135909. if( !aNew ) return SQLITE_NOMEM;
  135910. pWriter->aData = aNew;
  135911. pWriter->nSize = nReq;
  135912. }
  135913. assert( nData+nReq<=pWriter->nSize );
  135914. /* Append the prefix-compressed term and doclist to the buffer. */
  135915. nData += sqlite3Fts3PutVarint(&pWriter->aData[nData], nPrefix);
  135916. nData += sqlite3Fts3PutVarint(&pWriter->aData[nData], nSuffix);
  135917. memcpy(&pWriter->aData[nData], &zTerm[nPrefix], nSuffix);
  135918. nData += nSuffix;
  135919. nData += sqlite3Fts3PutVarint(&pWriter->aData[nData], nDoclist);
  135920. memcpy(&pWriter->aData[nData], aDoclist, nDoclist);
  135921. pWriter->nData = nData + nDoclist;
  135922. /* Save the current term so that it can be used to prefix-compress the next.
  135923. ** If the isCopyTerm parameter is true, then the buffer pointed to by
  135924. ** zTerm is transient, so take a copy of the term data. Otherwise, just
  135925. ** store a copy of the pointer.
  135926. */
  135927. if( isCopyTerm ){
  135928. if( nTerm>pWriter->nMalloc ){
  135929. char *zNew = sqlite3_realloc(pWriter->zMalloc, nTerm*2);
  135930. if( !zNew ){
  135931. return SQLITE_NOMEM;
  135932. }
  135933. pWriter->nMalloc = nTerm*2;
  135934. pWriter->zMalloc = zNew;
  135935. pWriter->zTerm = zNew;
  135936. }
  135937. assert( pWriter->zTerm==pWriter->zMalloc );
  135938. memcpy(pWriter->zTerm, zTerm, nTerm);
  135939. }else{
  135940. pWriter->zTerm = (char *)zTerm;
  135941. }
  135942. pWriter->nTerm = nTerm;
  135943. return SQLITE_OK;
  135944. }
  135945. /*
  135946. ** Flush all data associated with the SegmentWriter object pWriter to the
  135947. ** database. This function must be called after all terms have been added
  135948. ** to the segment using fts3SegWriterAdd(). If successful, SQLITE_OK is
  135949. ** returned. Otherwise, an SQLite error code.
  135950. */
  135951. static int fts3SegWriterFlush(
  135952. Fts3Table *p, /* Virtual table handle */
  135953. SegmentWriter *pWriter, /* SegmentWriter to flush to the db */
  135954. sqlite3_int64 iLevel, /* Value for 'level' column of %_segdir */
  135955. int iIdx /* Value for 'idx' column of %_segdir */
  135956. ){
  135957. int rc; /* Return code */
  135958. if( pWriter->pTree ){
  135959. sqlite3_int64 iLast = 0; /* Largest block id written to database */
  135960. sqlite3_int64 iLastLeaf; /* Largest leaf block id written to db */
  135961. char *zRoot = NULL; /* Pointer to buffer containing root node */
  135962. int nRoot = 0; /* Size of buffer zRoot */
  135963. iLastLeaf = pWriter->iFree;
  135964. rc = fts3WriteSegment(p, pWriter->iFree++, pWriter->aData, pWriter->nData);
  135965. if( rc==SQLITE_OK ){
  135966. rc = fts3NodeWrite(p, pWriter->pTree, 1,
  135967. pWriter->iFirst, pWriter->iFree, &iLast, &zRoot, &nRoot);
  135968. }
  135969. if( rc==SQLITE_OK ){
  135970. rc = fts3WriteSegdir(p, iLevel, iIdx,
  135971. pWriter->iFirst, iLastLeaf, iLast, pWriter->nLeafData, zRoot, nRoot);
  135972. }
  135973. }else{
  135974. /* The entire tree fits on the root node. Write it to the segdir table. */
  135975. rc = fts3WriteSegdir(p, iLevel, iIdx,
  135976. 0, 0, 0, pWriter->nLeafData, pWriter->aData, pWriter->nData);
  135977. }
  135978. p->nLeafAdd++;
  135979. return rc;
  135980. }
  135981. /*
  135982. ** Release all memory held by the SegmentWriter object passed as the
  135983. ** first argument.
  135984. */
  135985. static void fts3SegWriterFree(SegmentWriter *pWriter){
  135986. if( pWriter ){
  135987. sqlite3_free(pWriter->aData);
  135988. sqlite3_free(pWriter->zMalloc);
  135989. fts3NodeFree(pWriter->pTree);
  135990. sqlite3_free(pWriter);
  135991. }
  135992. }
  135993. /*
  135994. ** The first value in the apVal[] array is assumed to contain an integer.
  135995. ** This function tests if there exist any documents with docid values that
  135996. ** are different from that integer. i.e. if deleting the document with docid
  135997. ** pRowid would mean the FTS3 table were empty.
  135998. **
  135999. ** If successful, *pisEmpty is set to true if the table is empty except for
  136000. ** document pRowid, or false otherwise, and SQLITE_OK is returned. If an
  136001. ** error occurs, an SQLite error code is returned.
  136002. */
  136003. static int fts3IsEmpty(Fts3Table *p, sqlite3_value *pRowid, int *pisEmpty){
  136004. sqlite3_stmt *pStmt;
  136005. int rc;
  136006. if( p->zContentTbl ){
  136007. /* If using the content=xxx option, assume the table is never empty */
  136008. *pisEmpty = 0;
  136009. rc = SQLITE_OK;
  136010. }else{
  136011. rc = fts3SqlStmt(p, SQL_IS_EMPTY, &pStmt, &pRowid);
  136012. if( rc==SQLITE_OK ){
  136013. if( SQLITE_ROW==sqlite3_step(pStmt) ){
  136014. *pisEmpty = sqlite3_column_int(pStmt, 0);
  136015. }
  136016. rc = sqlite3_reset(pStmt);
  136017. }
  136018. }
  136019. return rc;
  136020. }
  136021. /*
  136022. ** Set *pnMax to the largest segment level in the database for the index
  136023. ** iIndex.
  136024. **
  136025. ** Segment levels are stored in the 'level' column of the %_segdir table.
  136026. **
  136027. ** Return SQLITE_OK if successful, or an SQLite error code if not.
  136028. */
  136029. static int fts3SegmentMaxLevel(
  136030. Fts3Table *p,
  136031. int iLangid,
  136032. int iIndex,
  136033. sqlite3_int64 *pnMax
  136034. ){
  136035. sqlite3_stmt *pStmt;
  136036. int rc;
  136037. assert( iIndex>=0 && iIndex<p->nIndex );
  136038. /* Set pStmt to the compiled version of:
  136039. **
  136040. ** SELECT max(level) FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?
  136041. **
  136042. ** (1024 is actually the value of macro FTS3_SEGDIR_PREFIXLEVEL_STR).
  136043. */
  136044. rc = fts3SqlStmt(p, SQL_SELECT_SEGDIR_MAX_LEVEL, &pStmt, 0);
  136045. if( rc!=SQLITE_OK ) return rc;
  136046. sqlite3_bind_int64(pStmt, 1, getAbsoluteLevel(p, iLangid, iIndex, 0));
  136047. sqlite3_bind_int64(pStmt, 2,
  136048. getAbsoluteLevel(p, iLangid, iIndex, FTS3_SEGDIR_MAXLEVEL-1)
  136049. );
  136050. if( SQLITE_ROW==sqlite3_step(pStmt) ){
  136051. *pnMax = sqlite3_column_int64(pStmt, 0);
  136052. }
  136053. return sqlite3_reset(pStmt);
  136054. }
  136055. /*
  136056. ** iAbsLevel is an absolute level that may be assumed to exist within
  136057. ** the database. This function checks if it is the largest level number
  136058. ** within its index. Assuming no error occurs, *pbMax is set to 1 if
  136059. ** iAbsLevel is indeed the largest level, or 0 otherwise, and SQLITE_OK
  136060. ** is returned. If an error occurs, an error code is returned and the
  136061. ** final value of *pbMax is undefined.
  136062. */
  136063. static int fts3SegmentIsMaxLevel(Fts3Table *p, i64 iAbsLevel, int *pbMax){
  136064. /* Set pStmt to the compiled version of:
  136065. **
  136066. ** SELECT max(level) FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?
  136067. **
  136068. ** (1024 is actually the value of macro FTS3_SEGDIR_PREFIXLEVEL_STR).
  136069. */
  136070. sqlite3_stmt *pStmt;
  136071. int rc = fts3SqlStmt(p, SQL_SELECT_SEGDIR_MAX_LEVEL, &pStmt, 0);
  136072. if( rc!=SQLITE_OK ) return rc;
  136073. sqlite3_bind_int64(pStmt, 1, iAbsLevel+1);
  136074. sqlite3_bind_int64(pStmt, 2,
  136075. ((iAbsLevel/FTS3_SEGDIR_MAXLEVEL)+1) * FTS3_SEGDIR_MAXLEVEL
  136076. );
  136077. *pbMax = 0;
  136078. if( SQLITE_ROW==sqlite3_step(pStmt) ){
  136079. *pbMax = sqlite3_column_type(pStmt, 0)==SQLITE_NULL;
  136080. }
  136081. return sqlite3_reset(pStmt);
  136082. }
  136083. /*
  136084. ** Delete all entries in the %_segments table associated with the segment
  136085. ** opened with seg-reader pSeg. This function does not affect the contents
  136086. ** of the %_segdir table.
  136087. */
  136088. static int fts3DeleteSegment(
  136089. Fts3Table *p, /* FTS table handle */
  136090. Fts3SegReader *pSeg /* Segment to delete */
  136091. ){
  136092. int rc = SQLITE_OK; /* Return code */
  136093. if( pSeg->iStartBlock ){
  136094. sqlite3_stmt *pDelete; /* SQL statement to delete rows */
  136095. rc = fts3SqlStmt(p, SQL_DELETE_SEGMENTS_RANGE, &pDelete, 0);
  136096. if( rc==SQLITE_OK ){
  136097. sqlite3_bind_int64(pDelete, 1, pSeg->iStartBlock);
  136098. sqlite3_bind_int64(pDelete, 2, pSeg->iEndBlock);
  136099. sqlite3_step(pDelete);
  136100. rc = sqlite3_reset(pDelete);
  136101. }
  136102. }
  136103. return rc;
  136104. }
  136105. /*
  136106. ** This function is used after merging multiple segments into a single large
  136107. ** segment to delete the old, now redundant, segment b-trees. Specifically,
  136108. ** it:
  136109. **
  136110. ** 1) Deletes all %_segments entries for the segments associated with
  136111. ** each of the SegReader objects in the array passed as the third
  136112. ** argument, and
  136113. **
  136114. ** 2) deletes all %_segdir entries with level iLevel, or all %_segdir
  136115. ** entries regardless of level if (iLevel<0).
  136116. **
  136117. ** SQLITE_OK is returned if successful, otherwise an SQLite error code.
  136118. */
  136119. static int fts3DeleteSegdir(
  136120. Fts3Table *p, /* Virtual table handle */
  136121. int iLangid, /* Language id */
  136122. int iIndex, /* Index for p->aIndex */
  136123. int iLevel, /* Level of %_segdir entries to delete */
  136124. Fts3SegReader **apSegment, /* Array of SegReader objects */
  136125. int nReader /* Size of array apSegment */
  136126. ){
  136127. int rc = SQLITE_OK; /* Return Code */
  136128. int i; /* Iterator variable */
  136129. sqlite3_stmt *pDelete = 0; /* SQL statement to delete rows */
  136130. for(i=0; rc==SQLITE_OK && i<nReader; i++){
  136131. rc = fts3DeleteSegment(p, apSegment[i]);
  136132. }
  136133. if( rc!=SQLITE_OK ){
  136134. return rc;
  136135. }
  136136. assert( iLevel>=0 || iLevel==FTS3_SEGCURSOR_ALL );
  136137. if( iLevel==FTS3_SEGCURSOR_ALL ){
  136138. rc = fts3SqlStmt(p, SQL_DELETE_SEGDIR_RANGE, &pDelete, 0);
  136139. if( rc==SQLITE_OK ){
  136140. sqlite3_bind_int64(pDelete, 1, getAbsoluteLevel(p, iLangid, iIndex, 0));
  136141. sqlite3_bind_int64(pDelete, 2,
  136142. getAbsoluteLevel(p, iLangid, iIndex, FTS3_SEGDIR_MAXLEVEL-1)
  136143. );
  136144. }
  136145. }else{
  136146. rc = fts3SqlStmt(p, SQL_DELETE_SEGDIR_LEVEL, &pDelete, 0);
  136147. if( rc==SQLITE_OK ){
  136148. sqlite3_bind_int64(
  136149. pDelete, 1, getAbsoluteLevel(p, iLangid, iIndex, iLevel)
  136150. );
  136151. }
  136152. }
  136153. if( rc==SQLITE_OK ){
  136154. sqlite3_step(pDelete);
  136155. rc = sqlite3_reset(pDelete);
  136156. }
  136157. return rc;
  136158. }
  136159. /*
  136160. ** When this function is called, buffer *ppList (size *pnList bytes) contains
  136161. ** a position list that may (or may not) feature multiple columns. This
  136162. ** function adjusts the pointer *ppList and the length *pnList so that they
  136163. ** identify the subset of the position list that corresponds to column iCol.
  136164. **
  136165. ** If there are no entries in the input position list for column iCol, then
  136166. ** *pnList is set to zero before returning.
  136167. **
  136168. ** If parameter bZero is non-zero, then any part of the input list following
  136169. ** the end of the output list is zeroed before returning.
  136170. */
  136171. static void fts3ColumnFilter(
  136172. int iCol, /* Column to filter on */
  136173. int bZero, /* Zero out anything following *ppList */
  136174. char **ppList, /* IN/OUT: Pointer to position list */
  136175. int *pnList /* IN/OUT: Size of buffer *ppList in bytes */
  136176. ){
  136177. char *pList = *ppList;
  136178. int nList = *pnList;
  136179. char *pEnd = &pList[nList];
  136180. int iCurrent = 0;
  136181. char *p = pList;
  136182. assert( iCol>=0 );
  136183. while( 1 ){
  136184. char c = 0;
  136185. while( p<pEnd && (c | *p)&0xFE ) c = *p++ & 0x80;
  136186. if( iCol==iCurrent ){
  136187. nList = (int)(p - pList);
  136188. break;
  136189. }
  136190. nList -= (int)(p - pList);
  136191. pList = p;
  136192. if( nList==0 ){
  136193. break;
  136194. }
  136195. p = &pList[1];
  136196. p += fts3GetVarint32(p, &iCurrent);
  136197. }
  136198. if( bZero && &pList[nList]!=pEnd ){
  136199. memset(&pList[nList], 0, pEnd - &pList[nList]);
  136200. }
  136201. *ppList = pList;
  136202. *pnList = nList;
  136203. }
  136204. /*
  136205. ** Cache data in the Fts3MultiSegReader.aBuffer[] buffer (overwriting any
  136206. ** existing data). Grow the buffer if required.
  136207. **
  136208. ** If successful, return SQLITE_OK. Otherwise, if an OOM error is encountered
  136209. ** trying to resize the buffer, return SQLITE_NOMEM.
  136210. */
  136211. static int fts3MsrBufferData(
  136212. Fts3MultiSegReader *pMsr, /* Multi-segment-reader handle */
  136213. char *pList,
  136214. int nList
  136215. ){
  136216. if( nList>pMsr->nBuffer ){
  136217. char *pNew;
  136218. pMsr->nBuffer = nList*2;
  136219. pNew = (char *)sqlite3_realloc(pMsr->aBuffer, pMsr->nBuffer);
  136220. if( !pNew ) return SQLITE_NOMEM;
  136221. pMsr->aBuffer = pNew;
  136222. }
  136223. memcpy(pMsr->aBuffer, pList, nList);
  136224. return SQLITE_OK;
  136225. }
  136226. SQLITE_PRIVATE int sqlite3Fts3MsrIncrNext(
  136227. Fts3Table *p, /* Virtual table handle */
  136228. Fts3MultiSegReader *pMsr, /* Multi-segment-reader handle */
  136229. sqlite3_int64 *piDocid, /* OUT: Docid value */
  136230. char **paPoslist, /* OUT: Pointer to position list */
  136231. int *pnPoslist /* OUT: Size of position list in bytes */
  136232. ){
  136233. int nMerge = pMsr->nAdvance;
  136234. Fts3SegReader **apSegment = pMsr->apSegment;
  136235. int (*xCmp)(Fts3SegReader *, Fts3SegReader *) = (
  136236. p->bDescIdx ? fts3SegReaderDoclistCmpRev : fts3SegReaderDoclistCmp
  136237. );
  136238. if( nMerge==0 ){
  136239. *paPoslist = 0;
  136240. return SQLITE_OK;
  136241. }
  136242. while( 1 ){
  136243. Fts3SegReader *pSeg;
  136244. pSeg = pMsr->apSegment[0];
  136245. if( pSeg->pOffsetList==0 ){
  136246. *paPoslist = 0;
  136247. break;
  136248. }else{
  136249. int rc;
  136250. char *pList;
  136251. int nList;
  136252. int j;
  136253. sqlite3_int64 iDocid = apSegment[0]->iDocid;
  136254. rc = fts3SegReaderNextDocid(p, apSegment[0], &pList, &nList);
  136255. j = 1;
  136256. while( rc==SQLITE_OK
  136257. && j<nMerge
  136258. && apSegment[j]->pOffsetList
  136259. && apSegment[j]->iDocid==iDocid
  136260. ){
  136261. rc = fts3SegReaderNextDocid(p, apSegment[j], 0, 0);
  136262. j++;
  136263. }
  136264. if( rc!=SQLITE_OK ) return rc;
  136265. fts3SegReaderSort(pMsr->apSegment, nMerge, j, xCmp);
  136266. if( nList>0 && fts3SegReaderIsPending(apSegment[0]) ){
  136267. rc = fts3MsrBufferData(pMsr, pList, nList+1);
  136268. if( rc!=SQLITE_OK ) return rc;
  136269. assert( (pMsr->aBuffer[nList] & 0xFE)==0x00 );
  136270. pList = pMsr->aBuffer;
  136271. }
  136272. if( pMsr->iColFilter>=0 ){
  136273. fts3ColumnFilter(pMsr->iColFilter, 1, &pList, &nList);
  136274. }
  136275. if( nList>0 ){
  136276. *paPoslist = pList;
  136277. *piDocid = iDocid;
  136278. *pnPoslist = nList;
  136279. break;
  136280. }
  136281. }
  136282. }
  136283. return SQLITE_OK;
  136284. }
  136285. static int fts3SegReaderStart(
  136286. Fts3Table *p, /* Virtual table handle */
  136287. Fts3MultiSegReader *pCsr, /* Cursor object */
  136288. const char *zTerm, /* Term searched for (or NULL) */
  136289. int nTerm /* Length of zTerm in bytes */
  136290. ){
  136291. int i;
  136292. int nSeg = pCsr->nSegment;
  136293. /* If the Fts3SegFilter defines a specific term (or term prefix) to search
  136294. ** for, then advance each segment iterator until it points to a term of
  136295. ** equal or greater value than the specified term. This prevents many
  136296. ** unnecessary merge/sort operations for the case where single segment
  136297. ** b-tree leaf nodes contain more than one term.
  136298. */
  136299. for(i=0; pCsr->bRestart==0 && i<pCsr->nSegment; i++){
  136300. int res = 0;
  136301. Fts3SegReader *pSeg = pCsr->apSegment[i];
  136302. do {
  136303. int rc = fts3SegReaderNext(p, pSeg, 0);
  136304. if( rc!=SQLITE_OK ) return rc;
  136305. }while( zTerm && (res = fts3SegReaderTermCmp(pSeg, zTerm, nTerm))<0 );
  136306. if( pSeg->bLookup && res!=0 ){
  136307. fts3SegReaderSetEof(pSeg);
  136308. }
  136309. }
  136310. fts3SegReaderSort(pCsr->apSegment, nSeg, nSeg, fts3SegReaderCmp);
  136311. return SQLITE_OK;
  136312. }
  136313. SQLITE_PRIVATE int sqlite3Fts3SegReaderStart(
  136314. Fts3Table *p, /* Virtual table handle */
  136315. Fts3MultiSegReader *pCsr, /* Cursor object */
  136316. Fts3SegFilter *pFilter /* Restrictions on range of iteration */
  136317. ){
  136318. pCsr->pFilter = pFilter;
  136319. return fts3SegReaderStart(p, pCsr, pFilter->zTerm, pFilter->nTerm);
  136320. }
  136321. SQLITE_PRIVATE int sqlite3Fts3MsrIncrStart(
  136322. Fts3Table *p, /* Virtual table handle */
  136323. Fts3MultiSegReader *pCsr, /* Cursor object */
  136324. int iCol, /* Column to match on. */
  136325. const char *zTerm, /* Term to iterate through a doclist for */
  136326. int nTerm /* Number of bytes in zTerm */
  136327. ){
  136328. int i;
  136329. int rc;
  136330. int nSegment = pCsr->nSegment;
  136331. int (*xCmp)(Fts3SegReader *, Fts3SegReader *) = (
  136332. p->bDescIdx ? fts3SegReaderDoclistCmpRev : fts3SegReaderDoclistCmp
  136333. );
  136334. assert( pCsr->pFilter==0 );
  136335. assert( zTerm && nTerm>0 );
  136336. /* Advance each segment iterator until it points to the term zTerm/nTerm. */
  136337. rc = fts3SegReaderStart(p, pCsr, zTerm, nTerm);
  136338. if( rc!=SQLITE_OK ) return rc;
  136339. /* Determine how many of the segments actually point to zTerm/nTerm. */
  136340. for(i=0; i<nSegment; i++){
  136341. Fts3SegReader *pSeg = pCsr->apSegment[i];
  136342. if( !pSeg->aNode || fts3SegReaderTermCmp(pSeg, zTerm, nTerm) ){
  136343. break;
  136344. }
  136345. }
  136346. pCsr->nAdvance = i;
  136347. /* Advance each of the segments to point to the first docid. */
  136348. for(i=0; i<pCsr->nAdvance; i++){
  136349. rc = fts3SegReaderFirstDocid(p, pCsr->apSegment[i]);
  136350. if( rc!=SQLITE_OK ) return rc;
  136351. }
  136352. fts3SegReaderSort(pCsr->apSegment, i, i, xCmp);
  136353. assert( iCol<0 || iCol<p->nColumn );
  136354. pCsr->iColFilter = iCol;
  136355. return SQLITE_OK;
  136356. }
  136357. /*
  136358. ** This function is called on a MultiSegReader that has been started using
  136359. ** sqlite3Fts3MsrIncrStart(). One or more calls to MsrIncrNext() may also
  136360. ** have been made. Calling this function puts the MultiSegReader in such
  136361. ** a state that if the next two calls are:
  136362. **
  136363. ** sqlite3Fts3SegReaderStart()
  136364. ** sqlite3Fts3SegReaderStep()
  136365. **
  136366. ** then the entire doclist for the term is available in
  136367. ** MultiSegReader.aDoclist/nDoclist.
  136368. */
  136369. SQLITE_PRIVATE int sqlite3Fts3MsrIncrRestart(Fts3MultiSegReader *pCsr){
  136370. int i; /* Used to iterate through segment-readers */
  136371. assert( pCsr->zTerm==0 );
  136372. assert( pCsr->nTerm==0 );
  136373. assert( pCsr->aDoclist==0 );
  136374. assert( pCsr->nDoclist==0 );
  136375. pCsr->nAdvance = 0;
  136376. pCsr->bRestart = 1;
  136377. for(i=0; i<pCsr->nSegment; i++){
  136378. pCsr->apSegment[i]->pOffsetList = 0;
  136379. pCsr->apSegment[i]->nOffsetList = 0;
  136380. pCsr->apSegment[i]->iDocid = 0;
  136381. }
  136382. return SQLITE_OK;
  136383. }
  136384. SQLITE_PRIVATE int sqlite3Fts3SegReaderStep(
  136385. Fts3Table *p, /* Virtual table handle */
  136386. Fts3MultiSegReader *pCsr /* Cursor object */
  136387. ){
  136388. int rc = SQLITE_OK;
  136389. int isIgnoreEmpty = (pCsr->pFilter->flags & FTS3_SEGMENT_IGNORE_EMPTY);
  136390. int isRequirePos = (pCsr->pFilter->flags & FTS3_SEGMENT_REQUIRE_POS);
  136391. int isColFilter = (pCsr->pFilter->flags & FTS3_SEGMENT_COLUMN_FILTER);
  136392. int isPrefix = (pCsr->pFilter->flags & FTS3_SEGMENT_PREFIX);
  136393. int isScan = (pCsr->pFilter->flags & FTS3_SEGMENT_SCAN);
  136394. int isFirst = (pCsr->pFilter->flags & FTS3_SEGMENT_FIRST);
  136395. Fts3SegReader **apSegment = pCsr->apSegment;
  136396. int nSegment = pCsr->nSegment;
  136397. Fts3SegFilter *pFilter = pCsr->pFilter;
  136398. int (*xCmp)(Fts3SegReader *, Fts3SegReader *) = (
  136399. p->bDescIdx ? fts3SegReaderDoclistCmpRev : fts3SegReaderDoclistCmp
  136400. );
  136401. if( pCsr->nSegment==0 ) return SQLITE_OK;
  136402. do {
  136403. int nMerge;
  136404. int i;
  136405. /* Advance the first pCsr->nAdvance entries in the apSegment[] array
  136406. ** forward. Then sort the list in order of current term again.
  136407. */
  136408. for(i=0; i<pCsr->nAdvance; i++){
  136409. Fts3SegReader *pSeg = apSegment[i];
  136410. if( pSeg->bLookup ){
  136411. fts3SegReaderSetEof(pSeg);
  136412. }else{
  136413. rc = fts3SegReaderNext(p, pSeg, 0);
  136414. }
  136415. if( rc!=SQLITE_OK ) return rc;
  136416. }
  136417. fts3SegReaderSort(apSegment, nSegment, pCsr->nAdvance, fts3SegReaderCmp);
  136418. pCsr->nAdvance = 0;
  136419. /* If all the seg-readers are at EOF, we're finished. return SQLITE_OK. */
  136420. assert( rc==SQLITE_OK );
  136421. if( apSegment[0]->aNode==0 ) break;
  136422. pCsr->nTerm = apSegment[0]->nTerm;
  136423. pCsr->zTerm = apSegment[0]->zTerm;
  136424. /* If this is a prefix-search, and if the term that apSegment[0] points
  136425. ** to does not share a suffix with pFilter->zTerm/nTerm, then all
  136426. ** required callbacks have been made. In this case exit early.
  136427. **
  136428. ** Similarly, if this is a search for an exact match, and the first term
  136429. ** of segment apSegment[0] is not a match, exit early.
  136430. */
  136431. if( pFilter->zTerm && !isScan ){
  136432. if( pCsr->nTerm<pFilter->nTerm
  136433. || (!isPrefix && pCsr->nTerm>pFilter->nTerm)
  136434. || memcmp(pCsr->zTerm, pFilter->zTerm, pFilter->nTerm)
  136435. ){
  136436. break;
  136437. }
  136438. }
  136439. nMerge = 1;
  136440. while( nMerge<nSegment
  136441. && apSegment[nMerge]->aNode
  136442. && apSegment[nMerge]->nTerm==pCsr->nTerm
  136443. && 0==memcmp(pCsr->zTerm, apSegment[nMerge]->zTerm, pCsr->nTerm)
  136444. ){
  136445. nMerge++;
  136446. }
  136447. assert( isIgnoreEmpty || (isRequirePos && !isColFilter) );
  136448. if( nMerge==1
  136449. && !isIgnoreEmpty
  136450. && !isFirst
  136451. && (p->bDescIdx==0 || fts3SegReaderIsPending(apSegment[0])==0)
  136452. ){
  136453. pCsr->nDoclist = apSegment[0]->nDoclist;
  136454. if( fts3SegReaderIsPending(apSegment[0]) ){
  136455. rc = fts3MsrBufferData(pCsr, apSegment[0]->aDoclist, pCsr->nDoclist);
  136456. pCsr->aDoclist = pCsr->aBuffer;
  136457. }else{
  136458. pCsr->aDoclist = apSegment[0]->aDoclist;
  136459. }
  136460. if( rc==SQLITE_OK ) rc = SQLITE_ROW;
  136461. }else{
  136462. int nDoclist = 0; /* Size of doclist */
  136463. sqlite3_int64 iPrev = 0; /* Previous docid stored in doclist */
  136464. /* The current term of the first nMerge entries in the array
  136465. ** of Fts3SegReader objects is the same. The doclists must be merged
  136466. ** and a single term returned with the merged doclist.
  136467. */
  136468. for(i=0; i<nMerge; i++){
  136469. fts3SegReaderFirstDocid(p, apSegment[i]);
  136470. }
  136471. fts3SegReaderSort(apSegment, nMerge, nMerge, xCmp);
  136472. while( apSegment[0]->pOffsetList ){
  136473. int j; /* Number of segments that share a docid */
  136474. char *pList = 0;
  136475. int nList = 0;
  136476. int nByte;
  136477. sqlite3_int64 iDocid = apSegment[0]->iDocid;
  136478. fts3SegReaderNextDocid(p, apSegment[0], &pList, &nList);
  136479. j = 1;
  136480. while( j<nMerge
  136481. && apSegment[j]->pOffsetList
  136482. && apSegment[j]->iDocid==iDocid
  136483. ){
  136484. fts3SegReaderNextDocid(p, apSegment[j], 0, 0);
  136485. j++;
  136486. }
  136487. if( isColFilter ){
  136488. fts3ColumnFilter(pFilter->iCol, 0, &pList, &nList);
  136489. }
  136490. if( !isIgnoreEmpty || nList>0 ){
  136491. /* Calculate the 'docid' delta value to write into the merged
  136492. ** doclist. */
  136493. sqlite3_int64 iDelta;
  136494. if( p->bDescIdx && nDoclist>0 ){
  136495. iDelta = iPrev - iDocid;
  136496. }else{
  136497. iDelta = iDocid - iPrev;
  136498. }
  136499. assert( iDelta>0 || (nDoclist==0 && iDelta==iDocid) );
  136500. assert( nDoclist>0 || iDelta==iDocid );
  136501. nByte = sqlite3Fts3VarintLen(iDelta) + (isRequirePos?nList+1:0);
  136502. if( nDoclist+nByte>pCsr->nBuffer ){
  136503. char *aNew;
  136504. pCsr->nBuffer = (nDoclist+nByte)*2;
  136505. aNew = sqlite3_realloc(pCsr->aBuffer, pCsr->nBuffer);
  136506. if( !aNew ){
  136507. return SQLITE_NOMEM;
  136508. }
  136509. pCsr->aBuffer = aNew;
  136510. }
  136511. if( isFirst ){
  136512. char *a = &pCsr->aBuffer[nDoclist];
  136513. int nWrite;
  136514. nWrite = sqlite3Fts3FirstFilter(iDelta, pList, nList, a);
  136515. if( nWrite ){
  136516. iPrev = iDocid;
  136517. nDoclist += nWrite;
  136518. }
  136519. }else{
  136520. nDoclist += sqlite3Fts3PutVarint(&pCsr->aBuffer[nDoclist], iDelta);
  136521. iPrev = iDocid;
  136522. if( isRequirePos ){
  136523. memcpy(&pCsr->aBuffer[nDoclist], pList, nList);
  136524. nDoclist += nList;
  136525. pCsr->aBuffer[nDoclist++] = '\0';
  136526. }
  136527. }
  136528. }
  136529. fts3SegReaderSort(apSegment, nMerge, j, xCmp);
  136530. }
  136531. if( nDoclist>0 ){
  136532. pCsr->aDoclist = pCsr->aBuffer;
  136533. pCsr->nDoclist = nDoclist;
  136534. rc = SQLITE_ROW;
  136535. }
  136536. }
  136537. pCsr->nAdvance = nMerge;
  136538. }while( rc==SQLITE_OK );
  136539. return rc;
  136540. }
  136541. SQLITE_PRIVATE void sqlite3Fts3SegReaderFinish(
  136542. Fts3MultiSegReader *pCsr /* Cursor object */
  136543. ){
  136544. if( pCsr ){
  136545. int i;
  136546. for(i=0; i<pCsr->nSegment; i++){
  136547. sqlite3Fts3SegReaderFree(pCsr->apSegment[i]);
  136548. }
  136549. sqlite3_free(pCsr->apSegment);
  136550. sqlite3_free(pCsr->aBuffer);
  136551. pCsr->nSegment = 0;
  136552. pCsr->apSegment = 0;
  136553. pCsr->aBuffer = 0;
  136554. }
  136555. }
  136556. /*
  136557. ** Decode the "end_block" field, selected by column iCol of the SELECT
  136558. ** statement passed as the first argument.
  136559. **
  136560. ** The "end_block" field may contain either an integer, or a text field
  136561. ** containing the text representation of two non-negative integers separated
  136562. ** by one or more space (0x20) characters. In the first case, set *piEndBlock
  136563. ** to the integer value and *pnByte to zero before returning. In the second,
  136564. ** set *piEndBlock to the first value and *pnByte to the second.
  136565. */
  136566. static void fts3ReadEndBlockField(
  136567. sqlite3_stmt *pStmt,
  136568. int iCol,
  136569. i64 *piEndBlock,
  136570. i64 *pnByte
  136571. ){
  136572. const unsigned char *zText = sqlite3_column_text(pStmt, iCol);
  136573. if( zText ){
  136574. int i;
  136575. int iMul = 1;
  136576. i64 iVal = 0;
  136577. for(i=0; zText[i]>='0' && zText[i]<='9'; i++){
  136578. iVal = iVal*10 + (zText[i] - '0');
  136579. }
  136580. *piEndBlock = iVal;
  136581. while( zText[i]==' ' ) i++;
  136582. iVal = 0;
  136583. if( zText[i]=='-' ){
  136584. i++;
  136585. iMul = -1;
  136586. }
  136587. for(/* no-op */; zText[i]>='0' && zText[i]<='9'; i++){
  136588. iVal = iVal*10 + (zText[i] - '0');
  136589. }
  136590. *pnByte = (iVal * (i64)iMul);
  136591. }
  136592. }
  136593. /*
  136594. ** A segment of size nByte bytes has just been written to absolute level
  136595. ** iAbsLevel. Promote any segments that should be promoted as a result.
  136596. */
  136597. static int fts3PromoteSegments(
  136598. Fts3Table *p, /* FTS table handle */
  136599. sqlite3_int64 iAbsLevel, /* Absolute level just updated */
  136600. sqlite3_int64 nByte /* Size of new segment at iAbsLevel */
  136601. ){
  136602. int rc = SQLITE_OK;
  136603. sqlite3_stmt *pRange;
  136604. rc = fts3SqlStmt(p, SQL_SELECT_LEVEL_RANGE2, &pRange, 0);
  136605. if( rc==SQLITE_OK ){
  136606. int bOk = 0;
  136607. i64 iLast = (iAbsLevel/FTS3_SEGDIR_MAXLEVEL + 1) * FTS3_SEGDIR_MAXLEVEL - 1;
  136608. i64 nLimit = (nByte*3)/2;
  136609. /* Loop through all entries in the %_segdir table corresponding to
  136610. ** segments in this index on levels greater than iAbsLevel. If there is
  136611. ** at least one such segment, and it is possible to determine that all
  136612. ** such segments are smaller than nLimit bytes in size, they will be
  136613. ** promoted to level iAbsLevel. */
  136614. sqlite3_bind_int64(pRange, 1, iAbsLevel+1);
  136615. sqlite3_bind_int64(pRange, 2, iLast);
  136616. while( SQLITE_ROW==sqlite3_step(pRange) ){
  136617. i64 nSize = 0, dummy;
  136618. fts3ReadEndBlockField(pRange, 2, &dummy, &nSize);
  136619. if( nSize<=0 || nSize>nLimit ){
  136620. /* If nSize==0, then the %_segdir.end_block field does not not
  136621. ** contain a size value. This happens if it was written by an
  136622. ** old version of FTS. In this case it is not possible to determine
  136623. ** the size of the segment, and so segment promotion does not
  136624. ** take place. */
  136625. bOk = 0;
  136626. break;
  136627. }
  136628. bOk = 1;
  136629. }
  136630. rc = sqlite3_reset(pRange);
  136631. if( bOk ){
  136632. int iIdx = 0;
  136633. sqlite3_stmt *pUpdate1 = 0;
  136634. sqlite3_stmt *pUpdate2 = 0;
  136635. if( rc==SQLITE_OK ){
  136636. rc = fts3SqlStmt(p, SQL_UPDATE_LEVEL_IDX, &pUpdate1, 0);
  136637. }
  136638. if( rc==SQLITE_OK ){
  136639. rc = fts3SqlStmt(p, SQL_UPDATE_LEVEL, &pUpdate2, 0);
  136640. }
  136641. if( rc==SQLITE_OK ){
  136642. /* Loop through all %_segdir entries for segments in this index with
  136643. ** levels equal to or greater than iAbsLevel. As each entry is visited,
  136644. ** updated it to set (level = -1) and (idx = N), where N is 0 for the
  136645. ** oldest segment in the range, 1 for the next oldest, and so on.
  136646. **
  136647. ** In other words, move all segments being promoted to level -1,
  136648. ** setting the "idx" fields as appropriate to keep them in the same
  136649. ** order. The contents of level -1 (which is never used, except
  136650. ** transiently here), will be moved back to level iAbsLevel below. */
  136651. sqlite3_bind_int64(pRange, 1, iAbsLevel);
  136652. while( SQLITE_ROW==sqlite3_step(pRange) ){
  136653. sqlite3_bind_int(pUpdate1, 1, iIdx++);
  136654. sqlite3_bind_int(pUpdate1, 2, sqlite3_column_int(pRange, 0));
  136655. sqlite3_bind_int(pUpdate1, 3, sqlite3_column_int(pRange, 1));
  136656. sqlite3_step(pUpdate1);
  136657. rc = sqlite3_reset(pUpdate1);
  136658. if( rc!=SQLITE_OK ){
  136659. sqlite3_reset(pRange);
  136660. break;
  136661. }
  136662. }
  136663. }
  136664. if( rc==SQLITE_OK ){
  136665. rc = sqlite3_reset(pRange);
  136666. }
  136667. /* Move level -1 to level iAbsLevel */
  136668. if( rc==SQLITE_OK ){
  136669. sqlite3_bind_int64(pUpdate2, 1, iAbsLevel);
  136670. sqlite3_step(pUpdate2);
  136671. rc = sqlite3_reset(pUpdate2);
  136672. }
  136673. }
  136674. }
  136675. return rc;
  136676. }
  136677. /*
  136678. ** Merge all level iLevel segments in the database into a single
  136679. ** iLevel+1 segment. Or, if iLevel<0, merge all segments into a
  136680. ** single segment with a level equal to the numerically largest level
  136681. ** currently present in the database.
  136682. **
  136683. ** If this function is called with iLevel<0, but there is only one
  136684. ** segment in the database, SQLITE_DONE is returned immediately.
  136685. ** Otherwise, if successful, SQLITE_OK is returned. If an error occurs,
  136686. ** an SQLite error code is returned.
  136687. */
  136688. static int fts3SegmentMerge(
  136689. Fts3Table *p,
  136690. int iLangid, /* Language id to merge */
  136691. int iIndex, /* Index in p->aIndex[] to merge */
  136692. int iLevel /* Level to merge */
  136693. ){
  136694. int rc; /* Return code */
  136695. int iIdx = 0; /* Index of new segment */
  136696. sqlite3_int64 iNewLevel = 0; /* Level/index to create new segment at */
  136697. SegmentWriter *pWriter = 0; /* Used to write the new, merged, segment */
  136698. Fts3SegFilter filter; /* Segment term filter condition */
  136699. Fts3MultiSegReader csr; /* Cursor to iterate through level(s) */
  136700. int bIgnoreEmpty = 0; /* True to ignore empty segments */
  136701. i64 iMaxLevel = 0; /* Max level number for this index/langid */
  136702. assert( iLevel==FTS3_SEGCURSOR_ALL
  136703. || iLevel==FTS3_SEGCURSOR_PENDING
  136704. || iLevel>=0
  136705. );
  136706. assert( iLevel<FTS3_SEGDIR_MAXLEVEL );
  136707. assert( iIndex>=0 && iIndex<p->nIndex );
  136708. rc = sqlite3Fts3SegReaderCursor(p, iLangid, iIndex, iLevel, 0, 0, 1, 0, &csr);
  136709. if( rc!=SQLITE_OK || csr.nSegment==0 ) goto finished;
  136710. if( iLevel!=FTS3_SEGCURSOR_PENDING ){
  136711. rc = fts3SegmentMaxLevel(p, iLangid, iIndex, &iMaxLevel);
  136712. if( rc!=SQLITE_OK ) goto finished;
  136713. }
  136714. if( iLevel==FTS3_SEGCURSOR_ALL ){
  136715. /* This call is to merge all segments in the database to a single
  136716. ** segment. The level of the new segment is equal to the numerically
  136717. ** greatest segment level currently present in the database for this
  136718. ** index. The idx of the new segment is always 0. */
  136719. if( csr.nSegment==1 ){
  136720. rc = SQLITE_DONE;
  136721. goto finished;
  136722. }
  136723. iNewLevel = iMaxLevel;
  136724. bIgnoreEmpty = 1;
  136725. }else{
  136726. /* This call is to merge all segments at level iLevel. find the next
  136727. ** available segment index at level iLevel+1. The call to
  136728. ** fts3AllocateSegdirIdx() will merge the segments at level iLevel+1 to
  136729. ** a single iLevel+2 segment if necessary. */
  136730. assert( FTS3_SEGCURSOR_PENDING==-1 );
  136731. iNewLevel = getAbsoluteLevel(p, iLangid, iIndex, iLevel+1);
  136732. rc = fts3AllocateSegdirIdx(p, iLangid, iIndex, iLevel+1, &iIdx);
  136733. bIgnoreEmpty = (iLevel!=FTS3_SEGCURSOR_PENDING) && (iNewLevel>iMaxLevel);
  136734. }
  136735. if( rc!=SQLITE_OK ) goto finished;
  136736. assert( csr.nSegment>0 );
  136737. assert( iNewLevel>=getAbsoluteLevel(p, iLangid, iIndex, 0) );
  136738. assert( iNewLevel<getAbsoluteLevel(p, iLangid, iIndex,FTS3_SEGDIR_MAXLEVEL) );
  136739. memset(&filter, 0, sizeof(Fts3SegFilter));
  136740. filter.flags = FTS3_SEGMENT_REQUIRE_POS;
  136741. filter.flags |= (bIgnoreEmpty ? FTS3_SEGMENT_IGNORE_EMPTY : 0);
  136742. rc = sqlite3Fts3SegReaderStart(p, &csr, &filter);
  136743. while( SQLITE_OK==rc ){
  136744. rc = sqlite3Fts3SegReaderStep(p, &csr);
  136745. if( rc!=SQLITE_ROW ) break;
  136746. rc = fts3SegWriterAdd(p, &pWriter, 1,
  136747. csr.zTerm, csr.nTerm, csr.aDoclist, csr.nDoclist);
  136748. }
  136749. if( rc!=SQLITE_OK ) goto finished;
  136750. assert( pWriter || bIgnoreEmpty );
  136751. if( iLevel!=FTS3_SEGCURSOR_PENDING ){
  136752. rc = fts3DeleteSegdir(
  136753. p, iLangid, iIndex, iLevel, csr.apSegment, csr.nSegment
  136754. );
  136755. if( rc!=SQLITE_OK ) goto finished;
  136756. }
  136757. if( pWriter ){
  136758. rc = fts3SegWriterFlush(p, pWriter, iNewLevel, iIdx);
  136759. if( rc==SQLITE_OK ){
  136760. if( iLevel==FTS3_SEGCURSOR_PENDING || iNewLevel<iMaxLevel ){
  136761. rc = fts3PromoteSegments(p, iNewLevel, pWriter->nLeafData);
  136762. }
  136763. }
  136764. }
  136765. finished:
  136766. fts3SegWriterFree(pWriter);
  136767. sqlite3Fts3SegReaderFinish(&csr);
  136768. return rc;
  136769. }
  136770. /*
  136771. ** Flush the contents of pendingTerms to level 0 segments.
  136772. */
  136773. SQLITE_PRIVATE int sqlite3Fts3PendingTermsFlush(Fts3Table *p){
  136774. int rc = SQLITE_OK;
  136775. int i;
  136776. for(i=0; rc==SQLITE_OK && i<p->nIndex; i++){
  136777. rc = fts3SegmentMerge(p, p->iPrevLangid, i, FTS3_SEGCURSOR_PENDING);
  136778. if( rc==SQLITE_DONE ) rc = SQLITE_OK;
  136779. }
  136780. sqlite3Fts3PendingTermsClear(p);
  136781. /* Determine the auto-incr-merge setting if unknown. If enabled,
  136782. ** estimate the number of leaf blocks of content to be written
  136783. */
  136784. if( rc==SQLITE_OK && p->bHasStat
  136785. && p->nAutoincrmerge==0xff && p->nLeafAdd>0
  136786. ){
  136787. sqlite3_stmt *pStmt = 0;
  136788. rc = fts3SqlStmt(p, SQL_SELECT_STAT, &pStmt, 0);
  136789. if( rc==SQLITE_OK ){
  136790. sqlite3_bind_int(pStmt, 1, FTS_STAT_AUTOINCRMERGE);
  136791. rc = sqlite3_step(pStmt);
  136792. if( rc==SQLITE_ROW ){
  136793. p->nAutoincrmerge = sqlite3_column_int(pStmt, 0);
  136794. if( p->nAutoincrmerge==1 ) p->nAutoincrmerge = 8;
  136795. }else if( rc==SQLITE_DONE ){
  136796. p->nAutoincrmerge = 0;
  136797. }
  136798. rc = sqlite3_reset(pStmt);
  136799. }
  136800. }
  136801. return rc;
  136802. }
  136803. /*
  136804. ** Encode N integers as varints into a blob.
  136805. */
  136806. static void fts3EncodeIntArray(
  136807. int N, /* The number of integers to encode */
  136808. u32 *a, /* The integer values */
  136809. char *zBuf, /* Write the BLOB here */
  136810. int *pNBuf /* Write number of bytes if zBuf[] used here */
  136811. ){
  136812. int i, j;
  136813. for(i=j=0; i<N; i++){
  136814. j += sqlite3Fts3PutVarint(&zBuf[j], (sqlite3_int64)a[i]);
  136815. }
  136816. *pNBuf = j;
  136817. }
  136818. /*
  136819. ** Decode a blob of varints into N integers
  136820. */
  136821. static void fts3DecodeIntArray(
  136822. int N, /* The number of integers to decode */
  136823. u32 *a, /* Write the integer values */
  136824. const char *zBuf, /* The BLOB containing the varints */
  136825. int nBuf /* size of the BLOB */
  136826. ){
  136827. int i, j;
  136828. UNUSED_PARAMETER(nBuf);
  136829. for(i=j=0; i<N; i++){
  136830. sqlite3_int64 x;
  136831. j += sqlite3Fts3GetVarint(&zBuf[j], &x);
  136832. assert(j<=nBuf);
  136833. a[i] = (u32)(x & 0xffffffff);
  136834. }
  136835. }
  136836. /*
  136837. ** Insert the sizes (in tokens) for each column of the document
  136838. ** with docid equal to p->iPrevDocid. The sizes are encoded as
  136839. ** a blob of varints.
  136840. */
  136841. static void fts3InsertDocsize(
  136842. int *pRC, /* Result code */
  136843. Fts3Table *p, /* Table into which to insert */
  136844. u32 *aSz /* Sizes of each column, in tokens */
  136845. ){
  136846. char *pBlob; /* The BLOB encoding of the document size */
  136847. int nBlob; /* Number of bytes in the BLOB */
  136848. sqlite3_stmt *pStmt; /* Statement used to insert the encoding */
  136849. int rc; /* Result code from subfunctions */
  136850. if( *pRC ) return;
  136851. pBlob = sqlite3_malloc( 10*p->nColumn );
  136852. if( pBlob==0 ){
  136853. *pRC = SQLITE_NOMEM;
  136854. return;
  136855. }
  136856. fts3EncodeIntArray(p->nColumn, aSz, pBlob, &nBlob);
  136857. rc = fts3SqlStmt(p, SQL_REPLACE_DOCSIZE, &pStmt, 0);
  136858. if( rc ){
  136859. sqlite3_free(pBlob);
  136860. *pRC = rc;
  136861. return;
  136862. }
  136863. sqlite3_bind_int64(pStmt, 1, p->iPrevDocid);
  136864. sqlite3_bind_blob(pStmt, 2, pBlob, nBlob, sqlite3_free);
  136865. sqlite3_step(pStmt);
  136866. *pRC = sqlite3_reset(pStmt);
  136867. }
  136868. /*
  136869. ** Record 0 of the %_stat table contains a blob consisting of N varints,
  136870. ** where N is the number of user defined columns in the fts3 table plus
  136871. ** two. If nCol is the number of user defined columns, then values of the
  136872. ** varints are set as follows:
  136873. **
  136874. ** Varint 0: Total number of rows in the table.
  136875. **
  136876. ** Varint 1..nCol: For each column, the total number of tokens stored in
  136877. ** the column for all rows of the table.
  136878. **
  136879. ** Varint 1+nCol: The total size, in bytes, of all text values in all
  136880. ** columns of all rows of the table.
  136881. **
  136882. */
  136883. static void fts3UpdateDocTotals(
  136884. int *pRC, /* The result code */
  136885. Fts3Table *p, /* Table being updated */
  136886. u32 *aSzIns, /* Size increases */
  136887. u32 *aSzDel, /* Size decreases */
  136888. int nChng /* Change in the number of documents */
  136889. ){
  136890. char *pBlob; /* Storage for BLOB written into %_stat */
  136891. int nBlob; /* Size of BLOB written into %_stat */
  136892. u32 *a; /* Array of integers that becomes the BLOB */
  136893. sqlite3_stmt *pStmt; /* Statement for reading and writing */
  136894. int i; /* Loop counter */
  136895. int rc; /* Result code from subfunctions */
  136896. const int nStat = p->nColumn+2;
  136897. if( *pRC ) return;
  136898. a = sqlite3_malloc( (sizeof(u32)+10)*nStat );
  136899. if( a==0 ){
  136900. *pRC = SQLITE_NOMEM;
  136901. return;
  136902. }
  136903. pBlob = (char*)&a[nStat];
  136904. rc = fts3SqlStmt(p, SQL_SELECT_STAT, &pStmt, 0);
  136905. if( rc ){
  136906. sqlite3_free(a);
  136907. *pRC = rc;
  136908. return;
  136909. }
  136910. sqlite3_bind_int(pStmt, 1, FTS_STAT_DOCTOTAL);
  136911. if( sqlite3_step(pStmt)==SQLITE_ROW ){
  136912. fts3DecodeIntArray(nStat, a,
  136913. sqlite3_column_blob(pStmt, 0),
  136914. sqlite3_column_bytes(pStmt, 0));
  136915. }else{
  136916. memset(a, 0, sizeof(u32)*(nStat) );
  136917. }
  136918. rc = sqlite3_reset(pStmt);
  136919. if( rc!=SQLITE_OK ){
  136920. sqlite3_free(a);
  136921. *pRC = rc;
  136922. return;
  136923. }
  136924. if( nChng<0 && a[0]<(u32)(-nChng) ){
  136925. a[0] = 0;
  136926. }else{
  136927. a[0] += nChng;
  136928. }
  136929. for(i=0; i<p->nColumn+1; i++){
  136930. u32 x = a[i+1];
  136931. if( x+aSzIns[i] < aSzDel[i] ){
  136932. x = 0;
  136933. }else{
  136934. x = x + aSzIns[i] - aSzDel[i];
  136935. }
  136936. a[i+1] = x;
  136937. }
  136938. fts3EncodeIntArray(nStat, a, pBlob, &nBlob);
  136939. rc = fts3SqlStmt(p, SQL_REPLACE_STAT, &pStmt, 0);
  136940. if( rc ){
  136941. sqlite3_free(a);
  136942. *pRC = rc;
  136943. return;
  136944. }
  136945. sqlite3_bind_int(pStmt, 1, FTS_STAT_DOCTOTAL);
  136946. sqlite3_bind_blob(pStmt, 2, pBlob, nBlob, SQLITE_STATIC);
  136947. sqlite3_step(pStmt);
  136948. *pRC = sqlite3_reset(pStmt);
  136949. sqlite3_free(a);
  136950. }
  136951. /*
  136952. ** Merge the entire database so that there is one segment for each
  136953. ** iIndex/iLangid combination.
  136954. */
  136955. static int fts3DoOptimize(Fts3Table *p, int bReturnDone){
  136956. int bSeenDone = 0;
  136957. int rc;
  136958. sqlite3_stmt *pAllLangid = 0;
  136959. rc = fts3SqlStmt(p, SQL_SELECT_ALL_LANGID, &pAllLangid, 0);
  136960. if( rc==SQLITE_OK ){
  136961. int rc2;
  136962. sqlite3_bind_int(pAllLangid, 1, p->iPrevLangid);
  136963. sqlite3_bind_int(pAllLangid, 2, p->nIndex);
  136964. while( sqlite3_step(pAllLangid)==SQLITE_ROW ){
  136965. int i;
  136966. int iLangid = sqlite3_column_int(pAllLangid, 0);
  136967. for(i=0; rc==SQLITE_OK && i<p->nIndex; i++){
  136968. rc = fts3SegmentMerge(p, iLangid, i, FTS3_SEGCURSOR_ALL);
  136969. if( rc==SQLITE_DONE ){
  136970. bSeenDone = 1;
  136971. rc = SQLITE_OK;
  136972. }
  136973. }
  136974. }
  136975. rc2 = sqlite3_reset(pAllLangid);
  136976. if( rc==SQLITE_OK ) rc = rc2;
  136977. }
  136978. sqlite3Fts3SegmentsClose(p);
  136979. sqlite3Fts3PendingTermsClear(p);
  136980. return (rc==SQLITE_OK && bReturnDone && bSeenDone) ? SQLITE_DONE : rc;
  136981. }
  136982. /*
  136983. ** This function is called when the user executes the following statement:
  136984. **
  136985. ** INSERT INTO <tbl>(<tbl>) VALUES('rebuild');
  136986. **
  136987. ** The entire FTS index is discarded and rebuilt. If the table is one
  136988. ** created using the content=xxx option, then the new index is based on
  136989. ** the current contents of the xxx table. Otherwise, it is rebuilt based
  136990. ** on the contents of the %_content table.
  136991. */
  136992. static int fts3DoRebuild(Fts3Table *p){
  136993. int rc; /* Return Code */
  136994. rc = fts3DeleteAll(p, 0);
  136995. if( rc==SQLITE_OK ){
  136996. u32 *aSz = 0;
  136997. u32 *aSzIns = 0;
  136998. u32 *aSzDel = 0;
  136999. sqlite3_stmt *pStmt = 0;
  137000. int nEntry = 0;
  137001. /* Compose and prepare an SQL statement to loop through the content table */
  137002. char *zSql = sqlite3_mprintf("SELECT %s" , p->zReadExprlist);
  137003. if( !zSql ){
  137004. rc = SQLITE_NOMEM;
  137005. }else{
  137006. rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
  137007. sqlite3_free(zSql);
  137008. }
  137009. if( rc==SQLITE_OK ){
  137010. int nByte = sizeof(u32) * (p->nColumn+1)*3;
  137011. aSz = (u32 *)sqlite3_malloc(nByte);
  137012. if( aSz==0 ){
  137013. rc = SQLITE_NOMEM;
  137014. }else{
  137015. memset(aSz, 0, nByte);
  137016. aSzIns = &aSz[p->nColumn+1];
  137017. aSzDel = &aSzIns[p->nColumn+1];
  137018. }
  137019. }
  137020. while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
  137021. int iCol;
  137022. int iLangid = langidFromSelect(p, pStmt);
  137023. rc = fts3PendingTermsDocid(p, iLangid, sqlite3_column_int64(pStmt, 0));
  137024. memset(aSz, 0, sizeof(aSz[0]) * (p->nColumn+1));
  137025. for(iCol=0; rc==SQLITE_OK && iCol<p->nColumn; iCol++){
  137026. if( p->abNotindexed[iCol]==0 ){
  137027. const char *z = (const char *) sqlite3_column_text(pStmt, iCol+1);
  137028. rc = fts3PendingTermsAdd(p, iLangid, z, iCol, &aSz[iCol]);
  137029. aSz[p->nColumn] += sqlite3_column_bytes(pStmt, iCol+1);
  137030. }
  137031. }
  137032. if( p->bHasDocsize ){
  137033. fts3InsertDocsize(&rc, p, aSz);
  137034. }
  137035. if( rc!=SQLITE_OK ){
  137036. sqlite3_finalize(pStmt);
  137037. pStmt = 0;
  137038. }else{
  137039. nEntry++;
  137040. for(iCol=0; iCol<=p->nColumn; iCol++){
  137041. aSzIns[iCol] += aSz[iCol];
  137042. }
  137043. }
  137044. }
  137045. if( p->bFts4 ){
  137046. fts3UpdateDocTotals(&rc, p, aSzIns, aSzDel, nEntry);
  137047. }
  137048. sqlite3_free(aSz);
  137049. if( pStmt ){
  137050. int rc2 = sqlite3_finalize(pStmt);
  137051. if( rc==SQLITE_OK ){
  137052. rc = rc2;
  137053. }
  137054. }
  137055. }
  137056. return rc;
  137057. }
  137058. /*
  137059. ** This function opens a cursor used to read the input data for an
  137060. ** incremental merge operation. Specifically, it opens a cursor to scan
  137061. ** the oldest nSeg segments (idx=0 through idx=(nSeg-1)) in absolute
  137062. ** level iAbsLevel.
  137063. */
  137064. static int fts3IncrmergeCsr(
  137065. Fts3Table *p, /* FTS3 table handle */
  137066. sqlite3_int64 iAbsLevel, /* Absolute level to open */
  137067. int nSeg, /* Number of segments to merge */
  137068. Fts3MultiSegReader *pCsr /* Cursor object to populate */
  137069. ){
  137070. int rc; /* Return Code */
  137071. sqlite3_stmt *pStmt = 0; /* Statement used to read %_segdir entry */
  137072. int nByte; /* Bytes allocated at pCsr->apSegment[] */
  137073. /* Allocate space for the Fts3MultiSegReader.aCsr[] array */
  137074. memset(pCsr, 0, sizeof(*pCsr));
  137075. nByte = sizeof(Fts3SegReader *) * nSeg;
  137076. pCsr->apSegment = (Fts3SegReader **)sqlite3_malloc(nByte);
  137077. if( pCsr->apSegment==0 ){
  137078. rc = SQLITE_NOMEM;
  137079. }else{
  137080. memset(pCsr->apSegment, 0, nByte);
  137081. rc = fts3SqlStmt(p, SQL_SELECT_LEVEL, &pStmt, 0);
  137082. }
  137083. if( rc==SQLITE_OK ){
  137084. int i;
  137085. int rc2;
  137086. sqlite3_bind_int64(pStmt, 1, iAbsLevel);
  137087. assert( pCsr->nSegment==0 );
  137088. for(i=0; rc==SQLITE_OK && sqlite3_step(pStmt)==SQLITE_ROW && i<nSeg; i++){
  137089. rc = sqlite3Fts3SegReaderNew(i, 0,
  137090. sqlite3_column_int64(pStmt, 1), /* segdir.start_block */
  137091. sqlite3_column_int64(pStmt, 2), /* segdir.leaves_end_block */
  137092. sqlite3_column_int64(pStmt, 3), /* segdir.end_block */
  137093. sqlite3_column_blob(pStmt, 4), /* segdir.root */
  137094. sqlite3_column_bytes(pStmt, 4), /* segdir.root */
  137095. &pCsr->apSegment[i]
  137096. );
  137097. pCsr->nSegment++;
  137098. }
  137099. rc2 = sqlite3_reset(pStmt);
  137100. if( rc==SQLITE_OK ) rc = rc2;
  137101. }
  137102. return rc;
  137103. }
  137104. typedef struct IncrmergeWriter IncrmergeWriter;
  137105. typedef struct NodeWriter NodeWriter;
  137106. typedef struct Blob Blob;
  137107. typedef struct NodeReader NodeReader;
  137108. /*
  137109. ** An instance of the following structure is used as a dynamic buffer
  137110. ** to build up nodes or other blobs of data in.
  137111. **
  137112. ** The function blobGrowBuffer() is used to extend the allocation.
  137113. */
  137114. struct Blob {
  137115. char *a; /* Pointer to allocation */
  137116. int n; /* Number of valid bytes of data in a[] */
  137117. int nAlloc; /* Allocated size of a[] (nAlloc>=n) */
  137118. };
  137119. /*
  137120. ** This structure is used to build up buffers containing segment b-tree
  137121. ** nodes (blocks).
  137122. */
  137123. struct NodeWriter {
  137124. sqlite3_int64 iBlock; /* Current block id */
  137125. Blob key; /* Last key written to the current block */
  137126. Blob block; /* Current block image */
  137127. };
  137128. /*
  137129. ** An object of this type contains the state required to create or append
  137130. ** to an appendable b-tree segment.
  137131. */
  137132. struct IncrmergeWriter {
  137133. int nLeafEst; /* Space allocated for leaf blocks */
  137134. int nWork; /* Number of leaf pages flushed */
  137135. sqlite3_int64 iAbsLevel; /* Absolute level of input segments */
  137136. int iIdx; /* Index of *output* segment in iAbsLevel+1 */
  137137. sqlite3_int64 iStart; /* Block number of first allocated block */
  137138. sqlite3_int64 iEnd; /* Block number of last allocated block */
  137139. sqlite3_int64 nLeafData; /* Bytes of leaf page data so far */
  137140. u8 bNoLeafData; /* If true, store 0 for segment size */
  137141. NodeWriter aNodeWriter[FTS_MAX_APPENDABLE_HEIGHT];
  137142. };
  137143. /*
  137144. ** An object of the following type is used to read data from a single
  137145. ** FTS segment node. See the following functions:
  137146. **
  137147. ** nodeReaderInit()
  137148. ** nodeReaderNext()
  137149. ** nodeReaderRelease()
  137150. */
  137151. struct NodeReader {
  137152. const char *aNode;
  137153. int nNode;
  137154. int iOff; /* Current offset within aNode[] */
  137155. /* Output variables. Containing the current node entry. */
  137156. sqlite3_int64 iChild; /* Pointer to child node */
  137157. Blob term; /* Current term */
  137158. const char *aDoclist; /* Pointer to doclist */
  137159. int nDoclist; /* Size of doclist in bytes */
  137160. };
  137161. /*
  137162. ** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
  137163. ** Otherwise, if the allocation at pBlob->a is not already at least nMin
  137164. ** bytes in size, extend (realloc) it to be so.
  137165. **
  137166. ** If an OOM error occurs, set *pRc to SQLITE_NOMEM and leave pBlob->a
  137167. ** unmodified. Otherwise, if the allocation succeeds, update pBlob->nAlloc
  137168. ** to reflect the new size of the pBlob->a[] buffer.
  137169. */
  137170. static void blobGrowBuffer(Blob *pBlob, int nMin, int *pRc){
  137171. if( *pRc==SQLITE_OK && nMin>pBlob->nAlloc ){
  137172. int nAlloc = nMin;
  137173. char *a = (char *)sqlite3_realloc(pBlob->a, nAlloc);
  137174. if( a ){
  137175. pBlob->nAlloc = nAlloc;
  137176. pBlob->a = a;
  137177. }else{
  137178. *pRc = SQLITE_NOMEM;
  137179. }
  137180. }
  137181. }
  137182. /*
  137183. ** Attempt to advance the node-reader object passed as the first argument to
  137184. ** the next entry on the node.
  137185. **
  137186. ** Return an error code if an error occurs (SQLITE_NOMEM is possible).
  137187. ** Otherwise return SQLITE_OK. If there is no next entry on the node
  137188. ** (e.g. because the current entry is the last) set NodeReader->aNode to
  137189. ** NULL to indicate EOF. Otherwise, populate the NodeReader structure output
  137190. ** variables for the new entry.
  137191. */
  137192. static int nodeReaderNext(NodeReader *p){
  137193. int bFirst = (p->term.n==0); /* True for first term on the node */
  137194. int nPrefix = 0; /* Bytes to copy from previous term */
  137195. int nSuffix = 0; /* Bytes to append to the prefix */
  137196. int rc = SQLITE_OK; /* Return code */
  137197. assert( p->aNode );
  137198. if( p->iChild && bFirst==0 ) p->iChild++;
  137199. if( p->iOff>=p->nNode ){
  137200. /* EOF */
  137201. p->aNode = 0;
  137202. }else{
  137203. if( bFirst==0 ){
  137204. p->iOff += fts3GetVarint32(&p->aNode[p->iOff], &nPrefix);
  137205. }
  137206. p->iOff += fts3GetVarint32(&p->aNode[p->iOff], &nSuffix);
  137207. blobGrowBuffer(&p->term, nPrefix+nSuffix, &rc);
  137208. if( rc==SQLITE_OK ){
  137209. memcpy(&p->term.a[nPrefix], &p->aNode[p->iOff], nSuffix);
  137210. p->term.n = nPrefix+nSuffix;
  137211. p->iOff += nSuffix;
  137212. if( p->iChild==0 ){
  137213. p->iOff += fts3GetVarint32(&p->aNode[p->iOff], &p->nDoclist);
  137214. p->aDoclist = &p->aNode[p->iOff];
  137215. p->iOff += p->nDoclist;
  137216. }
  137217. }
  137218. }
  137219. assert( p->iOff<=p->nNode );
  137220. return rc;
  137221. }
  137222. /*
  137223. ** Release all dynamic resources held by node-reader object *p.
  137224. */
  137225. static void nodeReaderRelease(NodeReader *p){
  137226. sqlite3_free(p->term.a);
  137227. }
  137228. /*
  137229. ** Initialize a node-reader object to read the node in buffer aNode/nNode.
  137230. **
  137231. ** If successful, SQLITE_OK is returned and the NodeReader object set to
  137232. ** point to the first entry on the node (if any). Otherwise, an SQLite
  137233. ** error code is returned.
  137234. */
  137235. static int nodeReaderInit(NodeReader *p, const char *aNode, int nNode){
  137236. memset(p, 0, sizeof(NodeReader));
  137237. p->aNode = aNode;
  137238. p->nNode = nNode;
  137239. /* Figure out if this is a leaf or an internal node. */
  137240. if( p->aNode[0] ){
  137241. /* An internal node. */
  137242. p->iOff = 1 + sqlite3Fts3GetVarint(&p->aNode[1], &p->iChild);
  137243. }else{
  137244. p->iOff = 1;
  137245. }
  137246. return nodeReaderNext(p);
  137247. }
  137248. /*
  137249. ** This function is called while writing an FTS segment each time a leaf o
  137250. ** node is finished and written to disk. The key (zTerm/nTerm) is guaranteed
  137251. ** to be greater than the largest key on the node just written, but smaller
  137252. ** than or equal to the first key that will be written to the next leaf
  137253. ** node.
  137254. **
  137255. ** The block id of the leaf node just written to disk may be found in
  137256. ** (pWriter->aNodeWriter[0].iBlock) when this function is called.
  137257. */
  137258. static int fts3IncrmergePush(
  137259. Fts3Table *p, /* Fts3 table handle */
  137260. IncrmergeWriter *pWriter, /* Writer object */
  137261. const char *zTerm, /* Term to write to internal node */
  137262. int nTerm /* Bytes at zTerm */
  137263. ){
  137264. sqlite3_int64 iPtr = pWriter->aNodeWriter[0].iBlock;
  137265. int iLayer;
  137266. assert( nTerm>0 );
  137267. for(iLayer=1; ALWAYS(iLayer<FTS_MAX_APPENDABLE_HEIGHT); iLayer++){
  137268. sqlite3_int64 iNextPtr = 0;
  137269. NodeWriter *pNode = &pWriter->aNodeWriter[iLayer];
  137270. int rc = SQLITE_OK;
  137271. int nPrefix;
  137272. int nSuffix;
  137273. int nSpace;
  137274. /* Figure out how much space the key will consume if it is written to
  137275. ** the current node of layer iLayer. Due to the prefix compression,
  137276. ** the space required changes depending on which node the key is to
  137277. ** be added to. */
  137278. nPrefix = fts3PrefixCompress(pNode->key.a, pNode->key.n, zTerm, nTerm);
  137279. nSuffix = nTerm - nPrefix;
  137280. nSpace = sqlite3Fts3VarintLen(nPrefix);
  137281. nSpace += sqlite3Fts3VarintLen(nSuffix) + nSuffix;
  137282. if( pNode->key.n==0 || (pNode->block.n + nSpace)<=p->nNodeSize ){
  137283. /* If the current node of layer iLayer contains zero keys, or if adding
  137284. ** the key to it will not cause it to grow to larger than nNodeSize
  137285. ** bytes in size, write the key here. */
  137286. Blob *pBlk = &pNode->block;
  137287. if( pBlk->n==0 ){
  137288. blobGrowBuffer(pBlk, p->nNodeSize, &rc);
  137289. if( rc==SQLITE_OK ){
  137290. pBlk->a[0] = (char)iLayer;
  137291. pBlk->n = 1 + sqlite3Fts3PutVarint(&pBlk->a[1], iPtr);
  137292. }
  137293. }
  137294. blobGrowBuffer(pBlk, pBlk->n + nSpace, &rc);
  137295. blobGrowBuffer(&pNode->key, nTerm, &rc);
  137296. if( rc==SQLITE_OK ){
  137297. if( pNode->key.n ){
  137298. pBlk->n += sqlite3Fts3PutVarint(&pBlk->a[pBlk->n], nPrefix);
  137299. }
  137300. pBlk->n += sqlite3Fts3PutVarint(&pBlk->a[pBlk->n], nSuffix);
  137301. memcpy(&pBlk->a[pBlk->n], &zTerm[nPrefix], nSuffix);
  137302. pBlk->n += nSuffix;
  137303. memcpy(pNode->key.a, zTerm, nTerm);
  137304. pNode->key.n = nTerm;
  137305. }
  137306. }else{
  137307. /* Otherwise, flush the current node of layer iLayer to disk.
  137308. ** Then allocate a new, empty sibling node. The key will be written
  137309. ** into the parent of this node. */
  137310. rc = fts3WriteSegment(p, pNode->iBlock, pNode->block.a, pNode->block.n);
  137311. assert( pNode->block.nAlloc>=p->nNodeSize );
  137312. pNode->block.a[0] = (char)iLayer;
  137313. pNode->block.n = 1 + sqlite3Fts3PutVarint(&pNode->block.a[1], iPtr+1);
  137314. iNextPtr = pNode->iBlock;
  137315. pNode->iBlock++;
  137316. pNode->key.n = 0;
  137317. }
  137318. if( rc!=SQLITE_OK || iNextPtr==0 ) return rc;
  137319. iPtr = iNextPtr;
  137320. }
  137321. assert( 0 );
  137322. return 0;
  137323. }
  137324. /*
  137325. ** Append a term and (optionally) doclist to the FTS segment node currently
  137326. ** stored in blob *pNode. The node need not contain any terms, but the
  137327. ** header must be written before this function is called.
  137328. **
  137329. ** A node header is a single 0x00 byte for a leaf node, or a height varint
  137330. ** followed by the left-hand-child varint for an internal node.
  137331. **
  137332. ** The term to be appended is passed via arguments zTerm/nTerm. For a
  137333. ** leaf node, the doclist is passed as aDoclist/nDoclist. For an internal
  137334. ** node, both aDoclist and nDoclist must be passed 0.
  137335. **
  137336. ** If the size of the value in blob pPrev is zero, then this is the first
  137337. ** term written to the node. Otherwise, pPrev contains a copy of the
  137338. ** previous term. Before this function returns, it is updated to contain a
  137339. ** copy of zTerm/nTerm.
  137340. **
  137341. ** It is assumed that the buffer associated with pNode is already large
  137342. ** enough to accommodate the new entry. The buffer associated with pPrev
  137343. ** is extended by this function if requrired.
  137344. **
  137345. ** If an error (i.e. OOM condition) occurs, an SQLite error code is
  137346. ** returned. Otherwise, SQLITE_OK.
  137347. */
  137348. static int fts3AppendToNode(
  137349. Blob *pNode, /* Current node image to append to */
  137350. Blob *pPrev, /* Buffer containing previous term written */
  137351. const char *zTerm, /* New term to write */
  137352. int nTerm, /* Size of zTerm in bytes */
  137353. const char *aDoclist, /* Doclist (or NULL) to write */
  137354. int nDoclist /* Size of aDoclist in bytes */
  137355. ){
  137356. int rc = SQLITE_OK; /* Return code */
  137357. int bFirst = (pPrev->n==0); /* True if this is the first term written */
  137358. int nPrefix; /* Size of term prefix in bytes */
  137359. int nSuffix; /* Size of term suffix in bytes */
  137360. /* Node must have already been started. There must be a doclist for a
  137361. ** leaf node, and there must not be a doclist for an internal node. */
  137362. assert( pNode->n>0 );
  137363. assert( (pNode->a[0]=='\0')==(aDoclist!=0) );
  137364. blobGrowBuffer(pPrev, nTerm, &rc);
  137365. if( rc!=SQLITE_OK ) return rc;
  137366. nPrefix = fts3PrefixCompress(pPrev->a, pPrev->n, zTerm, nTerm);
  137367. nSuffix = nTerm - nPrefix;
  137368. memcpy(pPrev->a, zTerm, nTerm);
  137369. pPrev->n = nTerm;
  137370. if( bFirst==0 ){
  137371. pNode->n += sqlite3Fts3PutVarint(&pNode->a[pNode->n], nPrefix);
  137372. }
  137373. pNode->n += sqlite3Fts3PutVarint(&pNode->a[pNode->n], nSuffix);
  137374. memcpy(&pNode->a[pNode->n], &zTerm[nPrefix], nSuffix);
  137375. pNode->n += nSuffix;
  137376. if( aDoclist ){
  137377. pNode->n += sqlite3Fts3PutVarint(&pNode->a[pNode->n], nDoclist);
  137378. memcpy(&pNode->a[pNode->n], aDoclist, nDoclist);
  137379. pNode->n += nDoclist;
  137380. }
  137381. assert( pNode->n<=pNode->nAlloc );
  137382. return SQLITE_OK;
  137383. }
  137384. /*
  137385. ** Append the current term and doclist pointed to by cursor pCsr to the
  137386. ** appendable b-tree segment opened for writing by pWriter.
  137387. **
  137388. ** Return SQLITE_OK if successful, or an SQLite error code otherwise.
  137389. */
  137390. static int fts3IncrmergeAppend(
  137391. Fts3Table *p, /* Fts3 table handle */
  137392. IncrmergeWriter *pWriter, /* Writer object */
  137393. Fts3MultiSegReader *pCsr /* Cursor containing term and doclist */
  137394. ){
  137395. const char *zTerm = pCsr->zTerm;
  137396. int nTerm = pCsr->nTerm;
  137397. const char *aDoclist = pCsr->aDoclist;
  137398. int nDoclist = pCsr->nDoclist;
  137399. int rc = SQLITE_OK; /* Return code */
  137400. int nSpace; /* Total space in bytes required on leaf */
  137401. int nPrefix; /* Size of prefix shared with previous term */
  137402. int nSuffix; /* Size of suffix (nTerm - nPrefix) */
  137403. NodeWriter *pLeaf; /* Object used to write leaf nodes */
  137404. pLeaf = &pWriter->aNodeWriter[0];
  137405. nPrefix = fts3PrefixCompress(pLeaf->key.a, pLeaf->key.n, zTerm, nTerm);
  137406. nSuffix = nTerm - nPrefix;
  137407. nSpace = sqlite3Fts3VarintLen(nPrefix);
  137408. nSpace += sqlite3Fts3VarintLen(nSuffix) + nSuffix;
  137409. nSpace += sqlite3Fts3VarintLen(nDoclist) + nDoclist;
  137410. /* If the current block is not empty, and if adding this term/doclist
  137411. ** to the current block would make it larger than Fts3Table.nNodeSize
  137412. ** bytes, write this block out to the database. */
  137413. if( pLeaf->block.n>0 && (pLeaf->block.n + nSpace)>p->nNodeSize ){
  137414. rc = fts3WriteSegment(p, pLeaf->iBlock, pLeaf->block.a, pLeaf->block.n);
  137415. pWriter->nWork++;
  137416. /* Add the current term to the parent node. The term added to the
  137417. ** parent must:
  137418. **
  137419. ** a) be greater than the largest term on the leaf node just written
  137420. ** to the database (still available in pLeaf->key), and
  137421. **
  137422. ** b) be less than or equal to the term about to be added to the new
  137423. ** leaf node (zTerm/nTerm).
  137424. **
  137425. ** In other words, it must be the prefix of zTerm 1 byte longer than
  137426. ** the common prefix (if any) of zTerm and pWriter->zTerm.
  137427. */
  137428. if( rc==SQLITE_OK ){
  137429. rc = fts3IncrmergePush(p, pWriter, zTerm, nPrefix+1);
  137430. }
  137431. /* Advance to the next output block */
  137432. pLeaf->iBlock++;
  137433. pLeaf->key.n = 0;
  137434. pLeaf->block.n = 0;
  137435. nSuffix = nTerm;
  137436. nSpace = 1;
  137437. nSpace += sqlite3Fts3VarintLen(nSuffix) + nSuffix;
  137438. nSpace += sqlite3Fts3VarintLen(nDoclist) + nDoclist;
  137439. }
  137440. pWriter->nLeafData += nSpace;
  137441. blobGrowBuffer(&pLeaf->block, pLeaf->block.n + nSpace, &rc);
  137442. if( rc==SQLITE_OK ){
  137443. if( pLeaf->block.n==0 ){
  137444. pLeaf->block.n = 1;
  137445. pLeaf->block.a[0] = '\0';
  137446. }
  137447. rc = fts3AppendToNode(
  137448. &pLeaf->block, &pLeaf->key, zTerm, nTerm, aDoclist, nDoclist
  137449. );
  137450. }
  137451. return rc;
  137452. }
  137453. /*
  137454. ** This function is called to release all dynamic resources held by the
  137455. ** merge-writer object pWriter, and if no error has occurred, to flush
  137456. ** all outstanding node buffers held by pWriter to disk.
  137457. **
  137458. ** If *pRc is not SQLITE_OK when this function is called, then no attempt
  137459. ** is made to write any data to disk. Instead, this function serves only
  137460. ** to release outstanding resources.
  137461. **
  137462. ** Otherwise, if *pRc is initially SQLITE_OK and an error occurs while
  137463. ** flushing buffers to disk, *pRc is set to an SQLite error code before
  137464. ** returning.
  137465. */
  137466. static void fts3IncrmergeRelease(
  137467. Fts3Table *p, /* FTS3 table handle */
  137468. IncrmergeWriter *pWriter, /* Merge-writer object */
  137469. int *pRc /* IN/OUT: Error code */
  137470. ){
  137471. int i; /* Used to iterate through non-root layers */
  137472. int iRoot; /* Index of root in pWriter->aNodeWriter */
  137473. NodeWriter *pRoot; /* NodeWriter for root node */
  137474. int rc = *pRc; /* Error code */
  137475. /* Set iRoot to the index in pWriter->aNodeWriter[] of the output segment
  137476. ** root node. If the segment fits entirely on a single leaf node, iRoot
  137477. ** will be set to 0. If the root node is the parent of the leaves, iRoot
  137478. ** will be 1. And so on. */
  137479. for(iRoot=FTS_MAX_APPENDABLE_HEIGHT-1; iRoot>=0; iRoot--){
  137480. NodeWriter *pNode = &pWriter->aNodeWriter[iRoot];
  137481. if( pNode->block.n>0 ) break;
  137482. assert( *pRc || pNode->block.nAlloc==0 );
  137483. assert( *pRc || pNode->key.nAlloc==0 );
  137484. sqlite3_free(pNode->block.a);
  137485. sqlite3_free(pNode->key.a);
  137486. }
  137487. /* Empty output segment. This is a no-op. */
  137488. if( iRoot<0 ) return;
  137489. /* The entire output segment fits on a single node. Normally, this means
  137490. ** the node would be stored as a blob in the "root" column of the %_segdir
  137491. ** table. However, this is not permitted in this case. The problem is that
  137492. ** space has already been reserved in the %_segments table, and so the
  137493. ** start_block and end_block fields of the %_segdir table must be populated.
  137494. ** And, by design or by accident, released versions of FTS cannot handle
  137495. ** segments that fit entirely on the root node with start_block!=0.
  137496. **
  137497. ** Instead, create a synthetic root node that contains nothing but a
  137498. ** pointer to the single content node. So that the segment consists of a
  137499. ** single leaf and a single interior (root) node.
  137500. **
  137501. ** Todo: Better might be to defer allocating space in the %_segments
  137502. ** table until we are sure it is needed.
  137503. */
  137504. if( iRoot==0 ){
  137505. Blob *pBlock = &pWriter->aNodeWriter[1].block;
  137506. blobGrowBuffer(pBlock, 1 + FTS3_VARINT_MAX, &rc);
  137507. if( rc==SQLITE_OK ){
  137508. pBlock->a[0] = 0x01;
  137509. pBlock->n = 1 + sqlite3Fts3PutVarint(
  137510. &pBlock->a[1], pWriter->aNodeWriter[0].iBlock
  137511. );
  137512. }
  137513. iRoot = 1;
  137514. }
  137515. pRoot = &pWriter->aNodeWriter[iRoot];
  137516. /* Flush all currently outstanding nodes to disk. */
  137517. for(i=0; i<iRoot; i++){
  137518. NodeWriter *pNode = &pWriter->aNodeWriter[i];
  137519. if( pNode->block.n>0 && rc==SQLITE_OK ){
  137520. rc = fts3WriteSegment(p, pNode->iBlock, pNode->block.a, pNode->block.n);
  137521. }
  137522. sqlite3_free(pNode->block.a);
  137523. sqlite3_free(pNode->key.a);
  137524. }
  137525. /* Write the %_segdir record. */
  137526. if( rc==SQLITE_OK ){
  137527. rc = fts3WriteSegdir(p,
  137528. pWriter->iAbsLevel+1, /* level */
  137529. pWriter->iIdx, /* idx */
  137530. pWriter->iStart, /* start_block */
  137531. pWriter->aNodeWriter[0].iBlock, /* leaves_end_block */
  137532. pWriter->iEnd, /* end_block */
  137533. (pWriter->bNoLeafData==0 ? pWriter->nLeafData : 0), /* end_block */
  137534. pRoot->block.a, pRoot->block.n /* root */
  137535. );
  137536. }
  137537. sqlite3_free(pRoot->block.a);
  137538. sqlite3_free(pRoot->key.a);
  137539. *pRc = rc;
  137540. }
  137541. /*
  137542. ** Compare the term in buffer zLhs (size in bytes nLhs) with that in
  137543. ** zRhs (size in bytes nRhs) using memcmp. If one term is a prefix of
  137544. ** the other, it is considered to be smaller than the other.
  137545. **
  137546. ** Return -ve if zLhs is smaller than zRhs, 0 if it is equal, or +ve
  137547. ** if it is greater.
  137548. */
  137549. static int fts3TermCmp(
  137550. const char *zLhs, int nLhs, /* LHS of comparison */
  137551. const char *zRhs, int nRhs /* RHS of comparison */
  137552. ){
  137553. int nCmp = MIN(nLhs, nRhs);
  137554. int res;
  137555. res = memcmp(zLhs, zRhs, nCmp);
  137556. if( res==0 ) res = nLhs - nRhs;
  137557. return res;
  137558. }
  137559. /*
  137560. ** Query to see if the entry in the %_segments table with blockid iEnd is
  137561. ** NULL. If no error occurs and the entry is NULL, set *pbRes 1 before
  137562. ** returning. Otherwise, set *pbRes to 0.
  137563. **
  137564. ** Or, if an error occurs while querying the database, return an SQLite
  137565. ** error code. The final value of *pbRes is undefined in this case.
  137566. **
  137567. ** This is used to test if a segment is an "appendable" segment. If it
  137568. ** is, then a NULL entry has been inserted into the %_segments table
  137569. ** with blockid %_segdir.end_block.
  137570. */
  137571. static int fts3IsAppendable(Fts3Table *p, sqlite3_int64 iEnd, int *pbRes){
  137572. int bRes = 0; /* Result to set *pbRes to */
  137573. sqlite3_stmt *pCheck = 0; /* Statement to query database with */
  137574. int rc; /* Return code */
  137575. rc = fts3SqlStmt(p, SQL_SEGMENT_IS_APPENDABLE, &pCheck, 0);
  137576. if( rc==SQLITE_OK ){
  137577. sqlite3_bind_int64(pCheck, 1, iEnd);
  137578. if( SQLITE_ROW==sqlite3_step(pCheck) ) bRes = 1;
  137579. rc = sqlite3_reset(pCheck);
  137580. }
  137581. *pbRes = bRes;
  137582. return rc;
  137583. }
  137584. /*
  137585. ** This function is called when initializing an incremental-merge operation.
  137586. ** It checks if the existing segment with index value iIdx at absolute level
  137587. ** (iAbsLevel+1) can be appended to by the incremental merge. If it can, the
  137588. ** merge-writer object *pWriter is initialized to write to it.
  137589. **
  137590. ** An existing segment can be appended to by an incremental merge if:
  137591. **
  137592. ** * It was initially created as an appendable segment (with all required
  137593. ** space pre-allocated), and
  137594. **
  137595. ** * The first key read from the input (arguments zKey and nKey) is
  137596. ** greater than the largest key currently stored in the potential
  137597. ** output segment.
  137598. */
  137599. static int fts3IncrmergeLoad(
  137600. Fts3Table *p, /* Fts3 table handle */
  137601. sqlite3_int64 iAbsLevel, /* Absolute level of input segments */
  137602. int iIdx, /* Index of candidate output segment */
  137603. const char *zKey, /* First key to write */
  137604. int nKey, /* Number of bytes in nKey */
  137605. IncrmergeWriter *pWriter /* Populate this object */
  137606. ){
  137607. int rc; /* Return code */
  137608. sqlite3_stmt *pSelect = 0; /* SELECT to read %_segdir entry */
  137609. rc = fts3SqlStmt(p, SQL_SELECT_SEGDIR, &pSelect, 0);
  137610. if( rc==SQLITE_OK ){
  137611. sqlite3_int64 iStart = 0; /* Value of %_segdir.start_block */
  137612. sqlite3_int64 iLeafEnd = 0; /* Value of %_segdir.leaves_end_block */
  137613. sqlite3_int64 iEnd = 0; /* Value of %_segdir.end_block */
  137614. const char *aRoot = 0; /* Pointer to %_segdir.root buffer */
  137615. int nRoot = 0; /* Size of aRoot[] in bytes */
  137616. int rc2; /* Return code from sqlite3_reset() */
  137617. int bAppendable = 0; /* Set to true if segment is appendable */
  137618. /* Read the %_segdir entry for index iIdx absolute level (iAbsLevel+1) */
  137619. sqlite3_bind_int64(pSelect, 1, iAbsLevel+1);
  137620. sqlite3_bind_int(pSelect, 2, iIdx);
  137621. if( sqlite3_step(pSelect)==SQLITE_ROW ){
  137622. iStart = sqlite3_column_int64(pSelect, 1);
  137623. iLeafEnd = sqlite3_column_int64(pSelect, 2);
  137624. fts3ReadEndBlockField(pSelect, 3, &iEnd, &pWriter->nLeafData);
  137625. if( pWriter->nLeafData<0 ){
  137626. pWriter->nLeafData = pWriter->nLeafData * -1;
  137627. }
  137628. pWriter->bNoLeafData = (pWriter->nLeafData==0);
  137629. nRoot = sqlite3_column_bytes(pSelect, 4);
  137630. aRoot = sqlite3_column_blob(pSelect, 4);
  137631. }else{
  137632. return sqlite3_reset(pSelect);
  137633. }
  137634. /* Check for the zero-length marker in the %_segments table */
  137635. rc = fts3IsAppendable(p, iEnd, &bAppendable);
  137636. /* Check that zKey/nKey is larger than the largest key the candidate */
  137637. if( rc==SQLITE_OK && bAppendable ){
  137638. char *aLeaf = 0;
  137639. int nLeaf = 0;
  137640. rc = sqlite3Fts3ReadBlock(p, iLeafEnd, &aLeaf, &nLeaf, 0);
  137641. if( rc==SQLITE_OK ){
  137642. NodeReader reader;
  137643. for(rc = nodeReaderInit(&reader, aLeaf, nLeaf);
  137644. rc==SQLITE_OK && reader.aNode;
  137645. rc = nodeReaderNext(&reader)
  137646. ){
  137647. assert( reader.aNode );
  137648. }
  137649. if( fts3TermCmp(zKey, nKey, reader.term.a, reader.term.n)<=0 ){
  137650. bAppendable = 0;
  137651. }
  137652. nodeReaderRelease(&reader);
  137653. }
  137654. sqlite3_free(aLeaf);
  137655. }
  137656. if( rc==SQLITE_OK && bAppendable ){
  137657. /* It is possible to append to this segment. Set up the IncrmergeWriter
  137658. ** object to do so. */
  137659. int i;
  137660. int nHeight = (int)aRoot[0];
  137661. NodeWriter *pNode;
  137662. pWriter->nLeafEst = (int)((iEnd - iStart) + 1)/FTS_MAX_APPENDABLE_HEIGHT;
  137663. pWriter->iStart = iStart;
  137664. pWriter->iEnd = iEnd;
  137665. pWriter->iAbsLevel = iAbsLevel;
  137666. pWriter->iIdx = iIdx;
  137667. for(i=nHeight+1; i<FTS_MAX_APPENDABLE_HEIGHT; i++){
  137668. pWriter->aNodeWriter[i].iBlock = pWriter->iStart + i*pWriter->nLeafEst;
  137669. }
  137670. pNode = &pWriter->aNodeWriter[nHeight];
  137671. pNode->iBlock = pWriter->iStart + pWriter->nLeafEst*nHeight;
  137672. blobGrowBuffer(&pNode->block, MAX(nRoot, p->nNodeSize), &rc);
  137673. if( rc==SQLITE_OK ){
  137674. memcpy(pNode->block.a, aRoot, nRoot);
  137675. pNode->block.n = nRoot;
  137676. }
  137677. for(i=nHeight; i>=0 && rc==SQLITE_OK; i--){
  137678. NodeReader reader;
  137679. pNode = &pWriter->aNodeWriter[i];
  137680. rc = nodeReaderInit(&reader, pNode->block.a, pNode->block.n);
  137681. while( reader.aNode && rc==SQLITE_OK ) rc = nodeReaderNext(&reader);
  137682. blobGrowBuffer(&pNode->key, reader.term.n, &rc);
  137683. if( rc==SQLITE_OK ){
  137684. memcpy(pNode->key.a, reader.term.a, reader.term.n);
  137685. pNode->key.n = reader.term.n;
  137686. if( i>0 ){
  137687. char *aBlock = 0;
  137688. int nBlock = 0;
  137689. pNode = &pWriter->aNodeWriter[i-1];
  137690. pNode->iBlock = reader.iChild;
  137691. rc = sqlite3Fts3ReadBlock(p, reader.iChild, &aBlock, &nBlock, 0);
  137692. blobGrowBuffer(&pNode->block, MAX(nBlock, p->nNodeSize), &rc);
  137693. if( rc==SQLITE_OK ){
  137694. memcpy(pNode->block.a, aBlock, nBlock);
  137695. pNode->block.n = nBlock;
  137696. }
  137697. sqlite3_free(aBlock);
  137698. }
  137699. }
  137700. nodeReaderRelease(&reader);
  137701. }
  137702. }
  137703. rc2 = sqlite3_reset(pSelect);
  137704. if( rc==SQLITE_OK ) rc = rc2;
  137705. }
  137706. return rc;
  137707. }
  137708. /*
  137709. ** Determine the largest segment index value that exists within absolute
  137710. ** level iAbsLevel+1. If no error occurs, set *piIdx to this value plus
  137711. ** one before returning SQLITE_OK. Or, if there are no segments at all
  137712. ** within level iAbsLevel, set *piIdx to zero.
  137713. **
  137714. ** If an error occurs, return an SQLite error code. The final value of
  137715. ** *piIdx is undefined in this case.
  137716. */
  137717. static int fts3IncrmergeOutputIdx(
  137718. Fts3Table *p, /* FTS Table handle */
  137719. sqlite3_int64 iAbsLevel, /* Absolute index of input segments */
  137720. int *piIdx /* OUT: Next free index at iAbsLevel+1 */
  137721. ){
  137722. int rc;
  137723. sqlite3_stmt *pOutputIdx = 0; /* SQL used to find output index */
  137724. rc = fts3SqlStmt(p, SQL_NEXT_SEGMENT_INDEX, &pOutputIdx, 0);
  137725. if( rc==SQLITE_OK ){
  137726. sqlite3_bind_int64(pOutputIdx, 1, iAbsLevel+1);
  137727. sqlite3_step(pOutputIdx);
  137728. *piIdx = sqlite3_column_int(pOutputIdx, 0);
  137729. rc = sqlite3_reset(pOutputIdx);
  137730. }
  137731. return rc;
  137732. }
  137733. /*
  137734. ** Allocate an appendable output segment on absolute level iAbsLevel+1
  137735. ** with idx value iIdx.
  137736. **
  137737. ** In the %_segdir table, a segment is defined by the values in three
  137738. ** columns:
  137739. **
  137740. ** start_block
  137741. ** leaves_end_block
  137742. ** end_block
  137743. **
  137744. ** When an appendable segment is allocated, it is estimated that the
  137745. ** maximum number of leaf blocks that may be required is the sum of the
  137746. ** number of leaf blocks consumed by the input segments, plus the number
  137747. ** of input segments, multiplied by two. This value is stored in stack
  137748. ** variable nLeafEst.
  137749. **
  137750. ** A total of 16*nLeafEst blocks are allocated when an appendable segment
  137751. ** is created ((1 + end_block - start_block)==16*nLeafEst). The contiguous
  137752. ** array of leaf nodes starts at the first block allocated. The array
  137753. ** of interior nodes that are parents of the leaf nodes start at block
  137754. ** (start_block + (1 + end_block - start_block) / 16). And so on.
  137755. **
  137756. ** In the actual code below, the value "16" is replaced with the
  137757. ** pre-processor macro FTS_MAX_APPENDABLE_HEIGHT.
  137758. */
  137759. static int fts3IncrmergeWriter(
  137760. Fts3Table *p, /* Fts3 table handle */
  137761. sqlite3_int64 iAbsLevel, /* Absolute level of input segments */
  137762. int iIdx, /* Index of new output segment */
  137763. Fts3MultiSegReader *pCsr, /* Cursor that data will be read from */
  137764. IncrmergeWriter *pWriter /* Populate this object */
  137765. ){
  137766. int rc; /* Return Code */
  137767. int i; /* Iterator variable */
  137768. int nLeafEst = 0; /* Blocks allocated for leaf nodes */
  137769. sqlite3_stmt *pLeafEst = 0; /* SQL used to determine nLeafEst */
  137770. sqlite3_stmt *pFirstBlock = 0; /* SQL used to determine first block */
  137771. /* Calculate nLeafEst. */
  137772. rc = fts3SqlStmt(p, SQL_MAX_LEAF_NODE_ESTIMATE, &pLeafEst, 0);
  137773. if( rc==SQLITE_OK ){
  137774. sqlite3_bind_int64(pLeafEst, 1, iAbsLevel);
  137775. sqlite3_bind_int64(pLeafEst, 2, pCsr->nSegment);
  137776. if( SQLITE_ROW==sqlite3_step(pLeafEst) ){
  137777. nLeafEst = sqlite3_column_int(pLeafEst, 0);
  137778. }
  137779. rc = sqlite3_reset(pLeafEst);
  137780. }
  137781. if( rc!=SQLITE_OK ) return rc;
  137782. /* Calculate the first block to use in the output segment */
  137783. rc = fts3SqlStmt(p, SQL_NEXT_SEGMENTS_ID, &pFirstBlock, 0);
  137784. if( rc==SQLITE_OK ){
  137785. if( SQLITE_ROW==sqlite3_step(pFirstBlock) ){
  137786. pWriter->iStart = sqlite3_column_int64(pFirstBlock, 0);
  137787. pWriter->iEnd = pWriter->iStart - 1;
  137788. pWriter->iEnd += nLeafEst * FTS_MAX_APPENDABLE_HEIGHT;
  137789. }
  137790. rc = sqlite3_reset(pFirstBlock);
  137791. }
  137792. if( rc!=SQLITE_OK ) return rc;
  137793. /* Insert the marker in the %_segments table to make sure nobody tries
  137794. ** to steal the space just allocated. This is also used to identify
  137795. ** appendable segments. */
  137796. rc = fts3WriteSegment(p, pWriter->iEnd, 0, 0);
  137797. if( rc!=SQLITE_OK ) return rc;
  137798. pWriter->iAbsLevel = iAbsLevel;
  137799. pWriter->nLeafEst = nLeafEst;
  137800. pWriter->iIdx = iIdx;
  137801. /* Set up the array of NodeWriter objects */
  137802. for(i=0; i<FTS_MAX_APPENDABLE_HEIGHT; i++){
  137803. pWriter->aNodeWriter[i].iBlock = pWriter->iStart + i*pWriter->nLeafEst;
  137804. }
  137805. return SQLITE_OK;
  137806. }
  137807. /*
  137808. ** Remove an entry from the %_segdir table. This involves running the
  137809. ** following two statements:
  137810. **
  137811. ** DELETE FROM %_segdir WHERE level = :iAbsLevel AND idx = :iIdx
  137812. ** UPDATE %_segdir SET idx = idx - 1 WHERE level = :iAbsLevel AND idx > :iIdx
  137813. **
  137814. ** The DELETE statement removes the specific %_segdir level. The UPDATE
  137815. ** statement ensures that the remaining segments have contiguously allocated
  137816. ** idx values.
  137817. */
  137818. static int fts3RemoveSegdirEntry(
  137819. Fts3Table *p, /* FTS3 table handle */
  137820. sqlite3_int64 iAbsLevel, /* Absolute level to delete from */
  137821. int iIdx /* Index of %_segdir entry to delete */
  137822. ){
  137823. int rc; /* Return code */
  137824. sqlite3_stmt *pDelete = 0; /* DELETE statement */
  137825. rc = fts3SqlStmt(p, SQL_DELETE_SEGDIR_ENTRY, &pDelete, 0);
  137826. if( rc==SQLITE_OK ){
  137827. sqlite3_bind_int64(pDelete, 1, iAbsLevel);
  137828. sqlite3_bind_int(pDelete, 2, iIdx);
  137829. sqlite3_step(pDelete);
  137830. rc = sqlite3_reset(pDelete);
  137831. }
  137832. return rc;
  137833. }
  137834. /*
  137835. ** One or more segments have just been removed from absolute level iAbsLevel.
  137836. ** Update the 'idx' values of the remaining segments in the level so that
  137837. ** the idx values are a contiguous sequence starting from 0.
  137838. */
  137839. static int fts3RepackSegdirLevel(
  137840. Fts3Table *p, /* FTS3 table handle */
  137841. sqlite3_int64 iAbsLevel /* Absolute level to repack */
  137842. ){
  137843. int rc; /* Return code */
  137844. int *aIdx = 0; /* Array of remaining idx values */
  137845. int nIdx = 0; /* Valid entries in aIdx[] */
  137846. int nAlloc = 0; /* Allocated size of aIdx[] */
  137847. int i; /* Iterator variable */
  137848. sqlite3_stmt *pSelect = 0; /* Select statement to read idx values */
  137849. sqlite3_stmt *pUpdate = 0; /* Update statement to modify idx values */
  137850. rc = fts3SqlStmt(p, SQL_SELECT_INDEXES, &pSelect, 0);
  137851. if( rc==SQLITE_OK ){
  137852. int rc2;
  137853. sqlite3_bind_int64(pSelect, 1, iAbsLevel);
  137854. while( SQLITE_ROW==sqlite3_step(pSelect) ){
  137855. if( nIdx>=nAlloc ){
  137856. int *aNew;
  137857. nAlloc += 16;
  137858. aNew = sqlite3_realloc(aIdx, nAlloc*sizeof(int));
  137859. if( !aNew ){
  137860. rc = SQLITE_NOMEM;
  137861. break;
  137862. }
  137863. aIdx = aNew;
  137864. }
  137865. aIdx[nIdx++] = sqlite3_column_int(pSelect, 0);
  137866. }
  137867. rc2 = sqlite3_reset(pSelect);
  137868. if( rc==SQLITE_OK ) rc = rc2;
  137869. }
  137870. if( rc==SQLITE_OK ){
  137871. rc = fts3SqlStmt(p, SQL_SHIFT_SEGDIR_ENTRY, &pUpdate, 0);
  137872. }
  137873. if( rc==SQLITE_OK ){
  137874. sqlite3_bind_int64(pUpdate, 2, iAbsLevel);
  137875. }
  137876. assert( p->bIgnoreSavepoint==0 );
  137877. p->bIgnoreSavepoint = 1;
  137878. for(i=0; rc==SQLITE_OK && i<nIdx; i++){
  137879. if( aIdx[i]!=i ){
  137880. sqlite3_bind_int(pUpdate, 3, aIdx[i]);
  137881. sqlite3_bind_int(pUpdate, 1, i);
  137882. sqlite3_step(pUpdate);
  137883. rc = sqlite3_reset(pUpdate);
  137884. }
  137885. }
  137886. p->bIgnoreSavepoint = 0;
  137887. sqlite3_free(aIdx);
  137888. return rc;
  137889. }
  137890. static void fts3StartNode(Blob *pNode, int iHeight, sqlite3_int64 iChild){
  137891. pNode->a[0] = (char)iHeight;
  137892. if( iChild ){
  137893. assert( pNode->nAlloc>=1+sqlite3Fts3VarintLen(iChild) );
  137894. pNode->n = 1 + sqlite3Fts3PutVarint(&pNode->a[1], iChild);
  137895. }else{
  137896. assert( pNode->nAlloc>=1 );
  137897. pNode->n = 1;
  137898. }
  137899. }
  137900. /*
  137901. ** The first two arguments are a pointer to and the size of a segment b-tree
  137902. ** node. The node may be a leaf or an internal node.
  137903. **
  137904. ** This function creates a new node image in blob object *pNew by copying
  137905. ** all terms that are greater than or equal to zTerm/nTerm (for leaf nodes)
  137906. ** or greater than zTerm/nTerm (for internal nodes) from aNode/nNode.
  137907. */
  137908. static int fts3TruncateNode(
  137909. const char *aNode, /* Current node image */
  137910. int nNode, /* Size of aNode in bytes */
  137911. Blob *pNew, /* OUT: Write new node image here */
  137912. const char *zTerm, /* Omit all terms smaller than this */
  137913. int nTerm, /* Size of zTerm in bytes */
  137914. sqlite3_int64 *piBlock /* OUT: Block number in next layer down */
  137915. ){
  137916. NodeReader reader; /* Reader object */
  137917. Blob prev = {0, 0, 0}; /* Previous term written to new node */
  137918. int rc = SQLITE_OK; /* Return code */
  137919. int bLeaf = aNode[0]=='\0'; /* True for a leaf node */
  137920. /* Allocate required output space */
  137921. blobGrowBuffer(pNew, nNode, &rc);
  137922. if( rc!=SQLITE_OK ) return rc;
  137923. pNew->n = 0;
  137924. /* Populate new node buffer */
  137925. for(rc = nodeReaderInit(&reader, aNode, nNode);
  137926. rc==SQLITE_OK && reader.aNode;
  137927. rc = nodeReaderNext(&reader)
  137928. ){
  137929. if( pNew->n==0 ){
  137930. int res = fts3TermCmp(reader.term.a, reader.term.n, zTerm, nTerm);
  137931. if( res<0 || (bLeaf==0 && res==0) ) continue;
  137932. fts3StartNode(pNew, (int)aNode[0], reader.iChild);
  137933. *piBlock = reader.iChild;
  137934. }
  137935. rc = fts3AppendToNode(
  137936. pNew, &prev, reader.term.a, reader.term.n,
  137937. reader.aDoclist, reader.nDoclist
  137938. );
  137939. if( rc!=SQLITE_OK ) break;
  137940. }
  137941. if( pNew->n==0 ){
  137942. fts3StartNode(pNew, (int)aNode[0], reader.iChild);
  137943. *piBlock = reader.iChild;
  137944. }
  137945. assert( pNew->n<=pNew->nAlloc );
  137946. nodeReaderRelease(&reader);
  137947. sqlite3_free(prev.a);
  137948. return rc;
  137949. }
  137950. /*
  137951. ** Remove all terms smaller than zTerm/nTerm from segment iIdx in absolute
  137952. ** level iAbsLevel. This may involve deleting entries from the %_segments
  137953. ** table, and modifying existing entries in both the %_segments and %_segdir
  137954. ** tables.
  137955. **
  137956. ** SQLITE_OK is returned if the segment is updated successfully. Or an
  137957. ** SQLite error code otherwise.
  137958. */
  137959. static int fts3TruncateSegment(
  137960. Fts3Table *p, /* FTS3 table handle */
  137961. sqlite3_int64 iAbsLevel, /* Absolute level of segment to modify */
  137962. int iIdx, /* Index within level of segment to modify */
  137963. const char *zTerm, /* Remove terms smaller than this */
  137964. int nTerm /* Number of bytes in buffer zTerm */
  137965. ){
  137966. int rc = SQLITE_OK; /* Return code */
  137967. Blob root = {0,0,0}; /* New root page image */
  137968. Blob block = {0,0,0}; /* Buffer used for any other block */
  137969. sqlite3_int64 iBlock = 0; /* Block id */
  137970. sqlite3_int64 iNewStart = 0; /* New value for iStartBlock */
  137971. sqlite3_int64 iOldStart = 0; /* Old value for iStartBlock */
  137972. sqlite3_stmt *pFetch = 0; /* Statement used to fetch segdir */
  137973. rc = fts3SqlStmt(p, SQL_SELECT_SEGDIR, &pFetch, 0);
  137974. if( rc==SQLITE_OK ){
  137975. int rc2; /* sqlite3_reset() return code */
  137976. sqlite3_bind_int64(pFetch, 1, iAbsLevel);
  137977. sqlite3_bind_int(pFetch, 2, iIdx);
  137978. if( SQLITE_ROW==sqlite3_step(pFetch) ){
  137979. const char *aRoot = sqlite3_column_blob(pFetch, 4);
  137980. int nRoot = sqlite3_column_bytes(pFetch, 4);
  137981. iOldStart = sqlite3_column_int64(pFetch, 1);
  137982. rc = fts3TruncateNode(aRoot, nRoot, &root, zTerm, nTerm, &iBlock);
  137983. }
  137984. rc2 = sqlite3_reset(pFetch);
  137985. if( rc==SQLITE_OK ) rc = rc2;
  137986. }
  137987. while( rc==SQLITE_OK && iBlock ){
  137988. char *aBlock = 0;
  137989. int nBlock = 0;
  137990. iNewStart = iBlock;
  137991. rc = sqlite3Fts3ReadBlock(p, iBlock, &aBlock, &nBlock, 0);
  137992. if( rc==SQLITE_OK ){
  137993. rc = fts3TruncateNode(aBlock, nBlock, &block, zTerm, nTerm, &iBlock);
  137994. }
  137995. if( rc==SQLITE_OK ){
  137996. rc = fts3WriteSegment(p, iNewStart, block.a, block.n);
  137997. }
  137998. sqlite3_free(aBlock);
  137999. }
  138000. /* Variable iNewStart now contains the first valid leaf node. */
  138001. if( rc==SQLITE_OK && iNewStart ){
  138002. sqlite3_stmt *pDel = 0;
  138003. rc = fts3SqlStmt(p, SQL_DELETE_SEGMENTS_RANGE, &pDel, 0);
  138004. if( rc==SQLITE_OK ){
  138005. sqlite3_bind_int64(pDel, 1, iOldStart);
  138006. sqlite3_bind_int64(pDel, 2, iNewStart-1);
  138007. sqlite3_step(pDel);
  138008. rc = sqlite3_reset(pDel);
  138009. }
  138010. }
  138011. if( rc==SQLITE_OK ){
  138012. sqlite3_stmt *pChomp = 0;
  138013. rc = fts3SqlStmt(p, SQL_CHOMP_SEGDIR, &pChomp, 0);
  138014. if( rc==SQLITE_OK ){
  138015. sqlite3_bind_int64(pChomp, 1, iNewStart);
  138016. sqlite3_bind_blob(pChomp, 2, root.a, root.n, SQLITE_STATIC);
  138017. sqlite3_bind_int64(pChomp, 3, iAbsLevel);
  138018. sqlite3_bind_int(pChomp, 4, iIdx);
  138019. sqlite3_step(pChomp);
  138020. rc = sqlite3_reset(pChomp);
  138021. }
  138022. }
  138023. sqlite3_free(root.a);
  138024. sqlite3_free(block.a);
  138025. return rc;
  138026. }
  138027. /*
  138028. ** This function is called after an incrmental-merge operation has run to
  138029. ** merge (or partially merge) two or more segments from absolute level
  138030. ** iAbsLevel.
  138031. **
  138032. ** Each input segment is either removed from the db completely (if all of
  138033. ** its data was copied to the output segment by the incrmerge operation)
  138034. ** or modified in place so that it no longer contains those entries that
  138035. ** have been duplicated in the output segment.
  138036. */
  138037. static int fts3IncrmergeChomp(
  138038. Fts3Table *p, /* FTS table handle */
  138039. sqlite3_int64 iAbsLevel, /* Absolute level containing segments */
  138040. Fts3MultiSegReader *pCsr, /* Chomp all segments opened by this cursor */
  138041. int *pnRem /* Number of segments not deleted */
  138042. ){
  138043. int i;
  138044. int nRem = 0;
  138045. int rc = SQLITE_OK;
  138046. for(i=pCsr->nSegment-1; i>=0 && rc==SQLITE_OK; i--){
  138047. Fts3SegReader *pSeg = 0;
  138048. int j;
  138049. /* Find the Fts3SegReader object with Fts3SegReader.iIdx==i. It is hiding
  138050. ** somewhere in the pCsr->apSegment[] array. */
  138051. for(j=0; ALWAYS(j<pCsr->nSegment); j++){
  138052. pSeg = pCsr->apSegment[j];
  138053. if( pSeg->iIdx==i ) break;
  138054. }
  138055. assert( j<pCsr->nSegment && pSeg->iIdx==i );
  138056. if( pSeg->aNode==0 ){
  138057. /* Seg-reader is at EOF. Remove the entire input segment. */
  138058. rc = fts3DeleteSegment(p, pSeg);
  138059. if( rc==SQLITE_OK ){
  138060. rc = fts3RemoveSegdirEntry(p, iAbsLevel, pSeg->iIdx);
  138061. }
  138062. *pnRem = 0;
  138063. }else{
  138064. /* The incremental merge did not copy all the data from this
  138065. ** segment to the upper level. The segment is modified in place
  138066. ** so that it contains no keys smaller than zTerm/nTerm. */
  138067. const char *zTerm = pSeg->zTerm;
  138068. int nTerm = pSeg->nTerm;
  138069. rc = fts3TruncateSegment(p, iAbsLevel, pSeg->iIdx, zTerm, nTerm);
  138070. nRem++;
  138071. }
  138072. }
  138073. if( rc==SQLITE_OK && nRem!=pCsr->nSegment ){
  138074. rc = fts3RepackSegdirLevel(p, iAbsLevel);
  138075. }
  138076. *pnRem = nRem;
  138077. return rc;
  138078. }
  138079. /*
  138080. ** Store an incr-merge hint in the database.
  138081. */
  138082. static int fts3IncrmergeHintStore(Fts3Table *p, Blob *pHint){
  138083. sqlite3_stmt *pReplace = 0;
  138084. int rc; /* Return code */
  138085. rc = fts3SqlStmt(p, SQL_REPLACE_STAT, &pReplace, 0);
  138086. if( rc==SQLITE_OK ){
  138087. sqlite3_bind_int(pReplace, 1, FTS_STAT_INCRMERGEHINT);
  138088. sqlite3_bind_blob(pReplace, 2, pHint->a, pHint->n, SQLITE_STATIC);
  138089. sqlite3_step(pReplace);
  138090. rc = sqlite3_reset(pReplace);
  138091. }
  138092. return rc;
  138093. }
  138094. /*
  138095. ** Load an incr-merge hint from the database. The incr-merge hint, if one
  138096. ** exists, is stored in the rowid==1 row of the %_stat table.
  138097. **
  138098. ** If successful, populate blob *pHint with the value read from the %_stat
  138099. ** table and return SQLITE_OK. Otherwise, if an error occurs, return an
  138100. ** SQLite error code.
  138101. */
  138102. static int fts3IncrmergeHintLoad(Fts3Table *p, Blob *pHint){
  138103. sqlite3_stmt *pSelect = 0;
  138104. int rc;
  138105. pHint->n = 0;
  138106. rc = fts3SqlStmt(p, SQL_SELECT_STAT, &pSelect, 0);
  138107. if( rc==SQLITE_OK ){
  138108. int rc2;
  138109. sqlite3_bind_int(pSelect, 1, FTS_STAT_INCRMERGEHINT);
  138110. if( SQLITE_ROW==sqlite3_step(pSelect) ){
  138111. const char *aHint = sqlite3_column_blob(pSelect, 0);
  138112. int nHint = sqlite3_column_bytes(pSelect, 0);
  138113. if( aHint ){
  138114. blobGrowBuffer(pHint, nHint, &rc);
  138115. if( rc==SQLITE_OK ){
  138116. memcpy(pHint->a, aHint, nHint);
  138117. pHint->n = nHint;
  138118. }
  138119. }
  138120. }
  138121. rc2 = sqlite3_reset(pSelect);
  138122. if( rc==SQLITE_OK ) rc = rc2;
  138123. }
  138124. return rc;
  138125. }
  138126. /*
  138127. ** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
  138128. ** Otherwise, append an entry to the hint stored in blob *pHint. Each entry
  138129. ** consists of two varints, the absolute level number of the input segments
  138130. ** and the number of input segments.
  138131. **
  138132. ** If successful, leave *pRc set to SQLITE_OK and return. If an error occurs,
  138133. ** set *pRc to an SQLite error code before returning.
  138134. */
  138135. static void fts3IncrmergeHintPush(
  138136. Blob *pHint, /* Hint blob to append to */
  138137. i64 iAbsLevel, /* First varint to store in hint */
  138138. int nInput, /* Second varint to store in hint */
  138139. int *pRc /* IN/OUT: Error code */
  138140. ){
  138141. blobGrowBuffer(pHint, pHint->n + 2*FTS3_VARINT_MAX, pRc);
  138142. if( *pRc==SQLITE_OK ){
  138143. pHint->n += sqlite3Fts3PutVarint(&pHint->a[pHint->n], iAbsLevel);
  138144. pHint->n += sqlite3Fts3PutVarint(&pHint->a[pHint->n], (i64)nInput);
  138145. }
  138146. }
  138147. /*
  138148. ** Read the last entry (most recently pushed) from the hint blob *pHint
  138149. ** and then remove the entry. Write the two values read to *piAbsLevel and
  138150. ** *pnInput before returning.
  138151. **
  138152. ** If no error occurs, return SQLITE_OK. If the hint blob in *pHint does
  138153. ** not contain at least two valid varints, return SQLITE_CORRUPT_VTAB.
  138154. */
  138155. static int fts3IncrmergeHintPop(Blob *pHint, i64 *piAbsLevel, int *pnInput){
  138156. const int nHint = pHint->n;
  138157. int i;
  138158. i = pHint->n-2;
  138159. while( i>0 && (pHint->a[i-1] & 0x80) ) i--;
  138160. while( i>0 && (pHint->a[i-1] & 0x80) ) i--;
  138161. pHint->n = i;
  138162. i += sqlite3Fts3GetVarint(&pHint->a[i], piAbsLevel);
  138163. i += fts3GetVarint32(&pHint->a[i], pnInput);
  138164. if( i!=nHint ) return FTS_CORRUPT_VTAB;
  138165. return SQLITE_OK;
  138166. }
  138167. /*
  138168. ** Attempt an incremental merge that writes nMerge leaf blocks.
  138169. **
  138170. ** Incremental merges happen nMin segments at a time. The segments
  138171. ** to be merged are the nMin oldest segments (the ones with the smallest
  138172. ** values for the _segdir.idx field) in the highest level that contains
  138173. ** at least nMin segments. Multiple merges might occur in an attempt to
  138174. ** write the quota of nMerge leaf blocks.
  138175. */
  138176. SQLITE_PRIVATE int sqlite3Fts3Incrmerge(Fts3Table *p, int nMerge, int nMin){
  138177. int rc; /* Return code */
  138178. int nRem = nMerge; /* Number of leaf pages yet to be written */
  138179. Fts3MultiSegReader *pCsr; /* Cursor used to read input data */
  138180. Fts3SegFilter *pFilter; /* Filter used with cursor pCsr */
  138181. IncrmergeWriter *pWriter; /* Writer object */
  138182. int nSeg = 0; /* Number of input segments */
  138183. sqlite3_int64 iAbsLevel = 0; /* Absolute level number to work on */
  138184. Blob hint = {0, 0, 0}; /* Hint read from %_stat table */
  138185. int bDirtyHint = 0; /* True if blob 'hint' has been modified */
  138186. /* Allocate space for the cursor, filter and writer objects */
  138187. const int nAlloc = sizeof(*pCsr) + sizeof(*pFilter) + sizeof(*pWriter);
  138188. pWriter = (IncrmergeWriter *)sqlite3_malloc(nAlloc);
  138189. if( !pWriter ) return SQLITE_NOMEM;
  138190. pFilter = (Fts3SegFilter *)&pWriter[1];
  138191. pCsr = (Fts3MultiSegReader *)&pFilter[1];
  138192. rc = fts3IncrmergeHintLoad(p, &hint);
  138193. while( rc==SQLITE_OK && nRem>0 ){
  138194. const i64 nMod = FTS3_SEGDIR_MAXLEVEL * p->nIndex;
  138195. sqlite3_stmt *pFindLevel = 0; /* SQL used to determine iAbsLevel */
  138196. int bUseHint = 0; /* True if attempting to append */
  138197. int iIdx = 0; /* Largest idx in level (iAbsLevel+1) */
  138198. /* Search the %_segdir table for the absolute level with the smallest
  138199. ** relative level number that contains at least nMin segments, if any.
  138200. ** If one is found, set iAbsLevel to the absolute level number and
  138201. ** nSeg to nMin. If no level with at least nMin segments can be found,
  138202. ** set nSeg to -1.
  138203. */
  138204. rc = fts3SqlStmt(p, SQL_FIND_MERGE_LEVEL, &pFindLevel, 0);
  138205. sqlite3_bind_int(pFindLevel, 1, nMin);
  138206. if( sqlite3_step(pFindLevel)==SQLITE_ROW ){
  138207. iAbsLevel = sqlite3_column_int64(pFindLevel, 0);
  138208. nSeg = nMin;
  138209. }else{
  138210. nSeg = -1;
  138211. }
  138212. rc = sqlite3_reset(pFindLevel);
  138213. /* If the hint read from the %_stat table is not empty, check if the
  138214. ** last entry in it specifies a relative level smaller than or equal
  138215. ** to the level identified by the block above (if any). If so, this
  138216. ** iteration of the loop will work on merging at the hinted level.
  138217. */
  138218. if( rc==SQLITE_OK && hint.n ){
  138219. int nHint = hint.n;
  138220. sqlite3_int64 iHintAbsLevel = 0; /* Hint level */
  138221. int nHintSeg = 0; /* Hint number of segments */
  138222. rc = fts3IncrmergeHintPop(&hint, &iHintAbsLevel, &nHintSeg);
  138223. if( nSeg<0 || (iAbsLevel % nMod) >= (iHintAbsLevel % nMod) ){
  138224. iAbsLevel = iHintAbsLevel;
  138225. nSeg = nHintSeg;
  138226. bUseHint = 1;
  138227. bDirtyHint = 1;
  138228. }else{
  138229. /* This undoes the effect of the HintPop() above - so that no entry
  138230. ** is removed from the hint blob. */
  138231. hint.n = nHint;
  138232. }
  138233. }
  138234. /* If nSeg is less that zero, then there is no level with at least
  138235. ** nMin segments and no hint in the %_stat table. No work to do.
  138236. ** Exit early in this case. */
  138237. if( nSeg<0 ) break;
  138238. /* Open a cursor to iterate through the contents of the oldest nSeg
  138239. ** indexes of absolute level iAbsLevel. If this cursor is opened using
  138240. ** the 'hint' parameters, it is possible that there are less than nSeg
  138241. ** segments available in level iAbsLevel. In this case, no work is
  138242. ** done on iAbsLevel - fall through to the next iteration of the loop
  138243. ** to start work on some other level. */
  138244. memset(pWriter, 0, nAlloc);
  138245. pFilter->flags = FTS3_SEGMENT_REQUIRE_POS;
  138246. if( rc==SQLITE_OK ){
  138247. rc = fts3IncrmergeOutputIdx(p, iAbsLevel, &iIdx);
  138248. assert( bUseHint==1 || bUseHint==0 );
  138249. if( iIdx==0 || (bUseHint && iIdx==1) ){
  138250. int bIgnore = 0;
  138251. rc = fts3SegmentIsMaxLevel(p, iAbsLevel+1, &bIgnore);
  138252. if( bIgnore ){
  138253. pFilter->flags |= FTS3_SEGMENT_IGNORE_EMPTY;
  138254. }
  138255. }
  138256. }
  138257. if( rc==SQLITE_OK ){
  138258. rc = fts3IncrmergeCsr(p, iAbsLevel, nSeg, pCsr);
  138259. }
  138260. if( SQLITE_OK==rc && pCsr->nSegment==nSeg
  138261. && SQLITE_OK==(rc = sqlite3Fts3SegReaderStart(p, pCsr, pFilter))
  138262. && SQLITE_ROW==(rc = sqlite3Fts3SegReaderStep(p, pCsr))
  138263. ){
  138264. if( bUseHint && iIdx>0 ){
  138265. const char *zKey = pCsr->zTerm;
  138266. int nKey = pCsr->nTerm;
  138267. rc = fts3IncrmergeLoad(p, iAbsLevel, iIdx-1, zKey, nKey, pWriter);
  138268. }else{
  138269. rc = fts3IncrmergeWriter(p, iAbsLevel, iIdx, pCsr, pWriter);
  138270. }
  138271. if( rc==SQLITE_OK && pWriter->nLeafEst ){
  138272. fts3LogMerge(nSeg, iAbsLevel);
  138273. do {
  138274. rc = fts3IncrmergeAppend(p, pWriter, pCsr);
  138275. if( rc==SQLITE_OK ) rc = sqlite3Fts3SegReaderStep(p, pCsr);
  138276. if( pWriter->nWork>=nRem && rc==SQLITE_ROW ) rc = SQLITE_OK;
  138277. }while( rc==SQLITE_ROW );
  138278. /* Update or delete the input segments */
  138279. if( rc==SQLITE_OK ){
  138280. nRem -= (1 + pWriter->nWork);
  138281. rc = fts3IncrmergeChomp(p, iAbsLevel, pCsr, &nSeg);
  138282. if( nSeg!=0 ){
  138283. bDirtyHint = 1;
  138284. fts3IncrmergeHintPush(&hint, iAbsLevel, nSeg, &rc);
  138285. }
  138286. }
  138287. }
  138288. if( nSeg!=0 ){
  138289. pWriter->nLeafData = pWriter->nLeafData * -1;
  138290. }
  138291. fts3IncrmergeRelease(p, pWriter, &rc);
  138292. if( nSeg==0 && pWriter->bNoLeafData==0 ){
  138293. fts3PromoteSegments(p, iAbsLevel+1, pWriter->nLeafData);
  138294. }
  138295. }
  138296. sqlite3Fts3SegReaderFinish(pCsr);
  138297. }
  138298. /* Write the hint values into the %_stat table for the next incr-merger */
  138299. if( bDirtyHint && rc==SQLITE_OK ){
  138300. rc = fts3IncrmergeHintStore(p, &hint);
  138301. }
  138302. sqlite3_free(pWriter);
  138303. sqlite3_free(hint.a);
  138304. return rc;
  138305. }
  138306. /*
  138307. ** Convert the text beginning at *pz into an integer and return
  138308. ** its value. Advance *pz to point to the first character past
  138309. ** the integer.
  138310. */
  138311. static int fts3Getint(const char **pz){
  138312. const char *z = *pz;
  138313. int i = 0;
  138314. while( (*z)>='0' && (*z)<='9' ) i = 10*i + *(z++) - '0';
  138315. *pz = z;
  138316. return i;
  138317. }
  138318. /*
  138319. ** Process statements of the form:
  138320. **
  138321. ** INSERT INTO table(table) VALUES('merge=A,B');
  138322. **
  138323. ** A and B are integers that decode to be the number of leaf pages
  138324. ** written for the merge, and the minimum number of segments on a level
  138325. ** before it will be selected for a merge, respectively.
  138326. */
  138327. static int fts3DoIncrmerge(
  138328. Fts3Table *p, /* FTS3 table handle */
  138329. const char *zParam /* Nul-terminated string containing "A,B" */
  138330. ){
  138331. int rc;
  138332. int nMin = (FTS3_MERGE_COUNT / 2);
  138333. int nMerge = 0;
  138334. const char *z = zParam;
  138335. /* Read the first integer value */
  138336. nMerge = fts3Getint(&z);
  138337. /* If the first integer value is followed by a ',', read the second
  138338. ** integer value. */
  138339. if( z[0]==',' && z[1]!='\0' ){
  138340. z++;
  138341. nMin = fts3Getint(&z);
  138342. }
  138343. if( z[0]!='\0' || nMin<2 ){
  138344. rc = SQLITE_ERROR;
  138345. }else{
  138346. rc = SQLITE_OK;
  138347. if( !p->bHasStat ){
  138348. assert( p->bFts4==0 );
  138349. sqlite3Fts3CreateStatTable(&rc, p);
  138350. }
  138351. if( rc==SQLITE_OK ){
  138352. rc = sqlite3Fts3Incrmerge(p, nMerge, nMin);
  138353. }
  138354. sqlite3Fts3SegmentsClose(p);
  138355. }
  138356. return rc;
  138357. }
  138358. /*
  138359. ** Process statements of the form:
  138360. **
  138361. ** INSERT INTO table(table) VALUES('automerge=X');
  138362. **
  138363. ** where X is an integer. X==0 means to turn automerge off. X!=0 means
  138364. ** turn it on. The setting is persistent.
  138365. */
  138366. static int fts3DoAutoincrmerge(
  138367. Fts3Table *p, /* FTS3 table handle */
  138368. const char *zParam /* Nul-terminated string containing boolean */
  138369. ){
  138370. int rc = SQLITE_OK;
  138371. sqlite3_stmt *pStmt = 0;
  138372. p->nAutoincrmerge = fts3Getint(&zParam);
  138373. if( p->nAutoincrmerge==1 || p->nAutoincrmerge>FTS3_MERGE_COUNT ){
  138374. p->nAutoincrmerge = 8;
  138375. }
  138376. if( !p->bHasStat ){
  138377. assert( p->bFts4==0 );
  138378. sqlite3Fts3CreateStatTable(&rc, p);
  138379. if( rc ) return rc;
  138380. }
  138381. rc = fts3SqlStmt(p, SQL_REPLACE_STAT, &pStmt, 0);
  138382. if( rc ) return rc;
  138383. sqlite3_bind_int(pStmt, 1, FTS_STAT_AUTOINCRMERGE);
  138384. sqlite3_bind_int(pStmt, 2, p->nAutoincrmerge);
  138385. sqlite3_step(pStmt);
  138386. rc = sqlite3_reset(pStmt);
  138387. return rc;
  138388. }
  138389. /*
  138390. ** Return a 64-bit checksum for the FTS index entry specified by the
  138391. ** arguments to this function.
  138392. */
  138393. static u64 fts3ChecksumEntry(
  138394. const char *zTerm, /* Pointer to buffer containing term */
  138395. int nTerm, /* Size of zTerm in bytes */
  138396. int iLangid, /* Language id for current row */
  138397. int iIndex, /* Index (0..Fts3Table.nIndex-1) */
  138398. i64 iDocid, /* Docid for current row. */
  138399. int iCol, /* Column number */
  138400. int iPos /* Position */
  138401. ){
  138402. int i;
  138403. u64 ret = (u64)iDocid;
  138404. ret += (ret<<3) + iLangid;
  138405. ret += (ret<<3) + iIndex;
  138406. ret += (ret<<3) + iCol;
  138407. ret += (ret<<3) + iPos;
  138408. for(i=0; i<nTerm; i++) ret += (ret<<3) + zTerm[i];
  138409. return ret;
  138410. }
  138411. /*
  138412. ** Return a checksum of all entries in the FTS index that correspond to
  138413. ** language id iLangid. The checksum is calculated by XORing the checksums
  138414. ** of each individual entry (see fts3ChecksumEntry()) together.
  138415. **
  138416. ** If successful, the checksum value is returned and *pRc set to SQLITE_OK.
  138417. ** Otherwise, if an error occurs, *pRc is set to an SQLite error code. The
  138418. ** return value is undefined in this case.
  138419. */
  138420. static u64 fts3ChecksumIndex(
  138421. Fts3Table *p, /* FTS3 table handle */
  138422. int iLangid, /* Language id to return cksum for */
  138423. int iIndex, /* Index to cksum (0..p->nIndex-1) */
  138424. int *pRc /* OUT: Return code */
  138425. ){
  138426. Fts3SegFilter filter;
  138427. Fts3MultiSegReader csr;
  138428. int rc;
  138429. u64 cksum = 0;
  138430. assert( *pRc==SQLITE_OK );
  138431. memset(&filter, 0, sizeof(filter));
  138432. memset(&csr, 0, sizeof(csr));
  138433. filter.flags = FTS3_SEGMENT_REQUIRE_POS|FTS3_SEGMENT_IGNORE_EMPTY;
  138434. filter.flags |= FTS3_SEGMENT_SCAN;
  138435. rc = sqlite3Fts3SegReaderCursor(
  138436. p, iLangid, iIndex, FTS3_SEGCURSOR_ALL, 0, 0, 0, 1,&csr
  138437. );
  138438. if( rc==SQLITE_OK ){
  138439. rc = sqlite3Fts3SegReaderStart(p, &csr, &filter);
  138440. }
  138441. if( rc==SQLITE_OK ){
  138442. while( SQLITE_ROW==(rc = sqlite3Fts3SegReaderStep(p, &csr)) ){
  138443. char *pCsr = csr.aDoclist;
  138444. char *pEnd = &pCsr[csr.nDoclist];
  138445. i64 iDocid = 0;
  138446. i64 iCol = 0;
  138447. i64 iPos = 0;
  138448. pCsr += sqlite3Fts3GetVarint(pCsr, &iDocid);
  138449. while( pCsr<pEnd ){
  138450. i64 iVal = 0;
  138451. pCsr += sqlite3Fts3GetVarint(pCsr, &iVal);
  138452. if( pCsr<pEnd ){
  138453. if( iVal==0 || iVal==1 ){
  138454. iCol = 0;
  138455. iPos = 0;
  138456. if( iVal ){
  138457. pCsr += sqlite3Fts3GetVarint(pCsr, &iCol);
  138458. }else{
  138459. pCsr += sqlite3Fts3GetVarint(pCsr, &iVal);
  138460. iDocid += iVal;
  138461. }
  138462. }else{
  138463. iPos += (iVal - 2);
  138464. cksum = cksum ^ fts3ChecksumEntry(
  138465. csr.zTerm, csr.nTerm, iLangid, iIndex, iDocid,
  138466. (int)iCol, (int)iPos
  138467. );
  138468. }
  138469. }
  138470. }
  138471. }
  138472. }
  138473. sqlite3Fts3SegReaderFinish(&csr);
  138474. *pRc = rc;
  138475. return cksum;
  138476. }
  138477. /*
  138478. ** Check if the contents of the FTS index match the current contents of the
  138479. ** content table. If no error occurs and the contents do match, set *pbOk
  138480. ** to true and return SQLITE_OK. Or if the contents do not match, set *pbOk
  138481. ** to false before returning.
  138482. **
  138483. ** If an error occurs (e.g. an OOM or IO error), return an SQLite error
  138484. ** code. The final value of *pbOk is undefined in this case.
  138485. */
  138486. static int fts3IntegrityCheck(Fts3Table *p, int *pbOk){
  138487. int rc = SQLITE_OK; /* Return code */
  138488. u64 cksum1 = 0; /* Checksum based on FTS index contents */
  138489. u64 cksum2 = 0; /* Checksum based on %_content contents */
  138490. sqlite3_stmt *pAllLangid = 0; /* Statement to return all language-ids */
  138491. /* This block calculates the checksum according to the FTS index. */
  138492. rc = fts3SqlStmt(p, SQL_SELECT_ALL_LANGID, &pAllLangid, 0);
  138493. if( rc==SQLITE_OK ){
  138494. int rc2;
  138495. sqlite3_bind_int(pAllLangid, 1, p->iPrevLangid);
  138496. sqlite3_bind_int(pAllLangid, 2, p->nIndex);
  138497. while( rc==SQLITE_OK && sqlite3_step(pAllLangid)==SQLITE_ROW ){
  138498. int iLangid = sqlite3_column_int(pAllLangid, 0);
  138499. int i;
  138500. for(i=0; i<p->nIndex; i++){
  138501. cksum1 = cksum1 ^ fts3ChecksumIndex(p, iLangid, i, &rc);
  138502. }
  138503. }
  138504. rc2 = sqlite3_reset(pAllLangid);
  138505. if( rc==SQLITE_OK ) rc = rc2;
  138506. }
  138507. /* This block calculates the checksum according to the %_content table */
  138508. if( rc==SQLITE_OK ){
  138509. sqlite3_tokenizer_module const *pModule = p->pTokenizer->pModule;
  138510. sqlite3_stmt *pStmt = 0;
  138511. char *zSql;
  138512. zSql = sqlite3_mprintf("SELECT %s" , p->zReadExprlist);
  138513. if( !zSql ){
  138514. rc = SQLITE_NOMEM;
  138515. }else{
  138516. rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
  138517. sqlite3_free(zSql);
  138518. }
  138519. while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
  138520. i64 iDocid = sqlite3_column_int64(pStmt, 0);
  138521. int iLang = langidFromSelect(p, pStmt);
  138522. int iCol;
  138523. for(iCol=0; rc==SQLITE_OK && iCol<p->nColumn; iCol++){
  138524. if( p->abNotindexed[iCol]==0 ){
  138525. const char *zText = (const char *)sqlite3_column_text(pStmt, iCol+1);
  138526. int nText = sqlite3_column_bytes(pStmt, iCol+1);
  138527. sqlite3_tokenizer_cursor *pT = 0;
  138528. rc = sqlite3Fts3OpenTokenizer(p->pTokenizer, iLang, zText, nText,&pT);
  138529. while( rc==SQLITE_OK ){
  138530. char const *zToken; /* Buffer containing token */
  138531. int nToken = 0; /* Number of bytes in token */
  138532. int iDum1 = 0, iDum2 = 0; /* Dummy variables */
  138533. int iPos = 0; /* Position of token in zText */
  138534. rc = pModule->xNext(pT, &zToken, &nToken, &iDum1, &iDum2, &iPos);
  138535. if( rc==SQLITE_OK ){
  138536. int i;
  138537. cksum2 = cksum2 ^ fts3ChecksumEntry(
  138538. zToken, nToken, iLang, 0, iDocid, iCol, iPos
  138539. );
  138540. for(i=1; i<p->nIndex; i++){
  138541. if( p->aIndex[i].nPrefix<=nToken ){
  138542. cksum2 = cksum2 ^ fts3ChecksumEntry(
  138543. zToken, p->aIndex[i].nPrefix, iLang, i, iDocid, iCol, iPos
  138544. );
  138545. }
  138546. }
  138547. }
  138548. }
  138549. if( pT ) pModule->xClose(pT);
  138550. if( rc==SQLITE_DONE ) rc = SQLITE_OK;
  138551. }
  138552. }
  138553. }
  138554. sqlite3_finalize(pStmt);
  138555. }
  138556. *pbOk = (cksum1==cksum2);
  138557. return rc;
  138558. }
  138559. /*
  138560. ** Run the integrity-check. If no error occurs and the current contents of
  138561. ** the FTS index are correct, return SQLITE_OK. Or, if the contents of the
  138562. ** FTS index are incorrect, return SQLITE_CORRUPT_VTAB.
  138563. **
  138564. ** Or, if an error (e.g. an OOM or IO error) occurs, return an SQLite
  138565. ** error code.
  138566. **
  138567. ** The integrity-check works as follows. For each token and indexed token
  138568. ** prefix in the document set, a 64-bit checksum is calculated (by code
  138569. ** in fts3ChecksumEntry()) based on the following:
  138570. **
  138571. ** + The index number (0 for the main index, 1 for the first prefix
  138572. ** index etc.),
  138573. ** + The token (or token prefix) text itself,
  138574. ** + The language-id of the row it appears in,
  138575. ** + The docid of the row it appears in,
  138576. ** + The column it appears in, and
  138577. ** + The tokens position within that column.
  138578. **
  138579. ** The checksums for all entries in the index are XORed together to create
  138580. ** a single checksum for the entire index.
  138581. **
  138582. ** The integrity-check code calculates the same checksum in two ways:
  138583. **
  138584. ** 1. By scanning the contents of the FTS index, and
  138585. ** 2. By scanning and tokenizing the content table.
  138586. **
  138587. ** If the two checksums are identical, the integrity-check is deemed to have
  138588. ** passed.
  138589. */
  138590. static int fts3DoIntegrityCheck(
  138591. Fts3Table *p /* FTS3 table handle */
  138592. ){
  138593. int rc;
  138594. int bOk = 0;
  138595. rc = fts3IntegrityCheck(p, &bOk);
  138596. if( rc==SQLITE_OK && bOk==0 ) rc = FTS_CORRUPT_VTAB;
  138597. return rc;
  138598. }
  138599. /*
  138600. ** Handle a 'special' INSERT of the form:
  138601. **
  138602. ** "INSERT INTO tbl(tbl) VALUES(<expr>)"
  138603. **
  138604. ** Argument pVal contains the result of <expr>. Currently the only
  138605. ** meaningful value to insert is the text 'optimize'.
  138606. */
  138607. static int fts3SpecialInsert(Fts3Table *p, sqlite3_value *pVal){
  138608. int rc; /* Return Code */
  138609. const char *zVal = (const char *)sqlite3_value_text(pVal);
  138610. int nVal = sqlite3_value_bytes(pVal);
  138611. if( !zVal ){
  138612. return SQLITE_NOMEM;
  138613. }else if( nVal==8 && 0==sqlite3_strnicmp(zVal, "optimize", 8) ){
  138614. rc = fts3DoOptimize(p, 0);
  138615. }else if( nVal==7 && 0==sqlite3_strnicmp(zVal, "rebuild", 7) ){
  138616. rc = fts3DoRebuild(p);
  138617. }else if( nVal==15 && 0==sqlite3_strnicmp(zVal, "integrity-check", 15) ){
  138618. rc = fts3DoIntegrityCheck(p);
  138619. }else if( nVal>6 && 0==sqlite3_strnicmp(zVal, "merge=", 6) ){
  138620. rc = fts3DoIncrmerge(p, &zVal[6]);
  138621. }else if( nVal>10 && 0==sqlite3_strnicmp(zVal, "automerge=", 10) ){
  138622. rc = fts3DoAutoincrmerge(p, &zVal[10]);
  138623. #ifdef SQLITE_TEST
  138624. }else if( nVal>9 && 0==sqlite3_strnicmp(zVal, "nodesize=", 9) ){
  138625. p->nNodeSize = atoi(&zVal[9]);
  138626. rc = SQLITE_OK;
  138627. }else if( nVal>11 && 0==sqlite3_strnicmp(zVal, "maxpending=", 9) ){
  138628. p->nMaxPendingData = atoi(&zVal[11]);
  138629. rc = SQLITE_OK;
  138630. }else if( nVal>21 && 0==sqlite3_strnicmp(zVal, "test-no-incr-doclist=", 21) ){
  138631. p->bNoIncrDoclist = atoi(&zVal[21]);
  138632. rc = SQLITE_OK;
  138633. #endif
  138634. }else{
  138635. rc = SQLITE_ERROR;
  138636. }
  138637. return rc;
  138638. }
  138639. #ifndef SQLITE_DISABLE_FTS4_DEFERRED
  138640. /*
  138641. ** Delete all cached deferred doclists. Deferred doclists are cached
  138642. ** (allocated) by the sqlite3Fts3CacheDeferredDoclists() function.
  138643. */
  138644. SQLITE_PRIVATE void sqlite3Fts3FreeDeferredDoclists(Fts3Cursor *pCsr){
  138645. Fts3DeferredToken *pDef;
  138646. for(pDef=pCsr->pDeferred; pDef; pDef=pDef->pNext){
  138647. fts3PendingListDelete(pDef->pList);
  138648. pDef->pList = 0;
  138649. }
  138650. }
  138651. /*
  138652. ** Free all entries in the pCsr->pDeffered list. Entries are added to
  138653. ** this list using sqlite3Fts3DeferToken().
  138654. */
  138655. SQLITE_PRIVATE void sqlite3Fts3FreeDeferredTokens(Fts3Cursor *pCsr){
  138656. Fts3DeferredToken *pDef;
  138657. Fts3DeferredToken *pNext;
  138658. for(pDef=pCsr->pDeferred; pDef; pDef=pNext){
  138659. pNext = pDef->pNext;
  138660. fts3PendingListDelete(pDef->pList);
  138661. sqlite3_free(pDef);
  138662. }
  138663. pCsr->pDeferred = 0;
  138664. }
  138665. /*
  138666. ** Generate deferred-doclists for all tokens in the pCsr->pDeferred list
  138667. ** based on the row that pCsr currently points to.
  138668. **
  138669. ** A deferred-doclist is like any other doclist with position information
  138670. ** included, except that it only contains entries for a single row of the
  138671. ** table, not for all rows.
  138672. */
  138673. SQLITE_PRIVATE int sqlite3Fts3CacheDeferredDoclists(Fts3Cursor *pCsr){
  138674. int rc = SQLITE_OK; /* Return code */
  138675. if( pCsr->pDeferred ){
  138676. int i; /* Used to iterate through table columns */
  138677. sqlite3_int64 iDocid; /* Docid of the row pCsr points to */
  138678. Fts3DeferredToken *pDef; /* Used to iterate through deferred tokens */
  138679. Fts3Table *p = (Fts3Table *)pCsr->base.pVtab;
  138680. sqlite3_tokenizer *pT = p->pTokenizer;
  138681. sqlite3_tokenizer_module const *pModule = pT->pModule;
  138682. assert( pCsr->isRequireSeek==0 );
  138683. iDocid = sqlite3_column_int64(pCsr->pStmt, 0);
  138684. for(i=0; i<p->nColumn && rc==SQLITE_OK; i++){
  138685. if( p->abNotindexed[i]==0 ){
  138686. const char *zText = (const char *)sqlite3_column_text(pCsr->pStmt, i+1);
  138687. sqlite3_tokenizer_cursor *pTC = 0;
  138688. rc = sqlite3Fts3OpenTokenizer(pT, pCsr->iLangid, zText, -1, &pTC);
  138689. while( rc==SQLITE_OK ){
  138690. char const *zToken; /* Buffer containing token */
  138691. int nToken = 0; /* Number of bytes in token */
  138692. int iDum1 = 0, iDum2 = 0; /* Dummy variables */
  138693. int iPos = 0; /* Position of token in zText */
  138694. rc = pModule->xNext(pTC, &zToken, &nToken, &iDum1, &iDum2, &iPos);
  138695. for(pDef=pCsr->pDeferred; pDef && rc==SQLITE_OK; pDef=pDef->pNext){
  138696. Fts3PhraseToken *pPT = pDef->pToken;
  138697. if( (pDef->iCol>=p->nColumn || pDef->iCol==i)
  138698. && (pPT->bFirst==0 || iPos==0)
  138699. && (pPT->n==nToken || (pPT->isPrefix && pPT->n<nToken))
  138700. && (0==memcmp(zToken, pPT->z, pPT->n))
  138701. ){
  138702. fts3PendingListAppend(&pDef->pList, iDocid, i, iPos, &rc);
  138703. }
  138704. }
  138705. }
  138706. if( pTC ) pModule->xClose(pTC);
  138707. if( rc==SQLITE_DONE ) rc = SQLITE_OK;
  138708. }
  138709. }
  138710. for(pDef=pCsr->pDeferred; pDef && rc==SQLITE_OK; pDef=pDef->pNext){
  138711. if( pDef->pList ){
  138712. rc = fts3PendingListAppendVarint(&pDef->pList, 0);
  138713. }
  138714. }
  138715. }
  138716. return rc;
  138717. }
  138718. SQLITE_PRIVATE int sqlite3Fts3DeferredTokenList(
  138719. Fts3DeferredToken *p,
  138720. char **ppData,
  138721. int *pnData
  138722. ){
  138723. char *pRet;
  138724. int nSkip;
  138725. sqlite3_int64 dummy;
  138726. *ppData = 0;
  138727. *pnData = 0;
  138728. if( p->pList==0 ){
  138729. return SQLITE_OK;
  138730. }
  138731. pRet = (char *)sqlite3_malloc(p->pList->nData);
  138732. if( !pRet ) return SQLITE_NOMEM;
  138733. nSkip = sqlite3Fts3GetVarint(p->pList->aData, &dummy);
  138734. *pnData = p->pList->nData - nSkip;
  138735. *ppData = pRet;
  138736. memcpy(pRet, &p->pList->aData[nSkip], *pnData);
  138737. return SQLITE_OK;
  138738. }
  138739. /*
  138740. ** Add an entry for token pToken to the pCsr->pDeferred list.
  138741. */
  138742. SQLITE_PRIVATE int sqlite3Fts3DeferToken(
  138743. Fts3Cursor *pCsr, /* Fts3 table cursor */
  138744. Fts3PhraseToken *pToken, /* Token to defer */
  138745. int iCol /* Column that token must appear in (or -1) */
  138746. ){
  138747. Fts3DeferredToken *pDeferred;
  138748. pDeferred = sqlite3_malloc(sizeof(*pDeferred));
  138749. if( !pDeferred ){
  138750. return SQLITE_NOMEM;
  138751. }
  138752. memset(pDeferred, 0, sizeof(*pDeferred));
  138753. pDeferred->pToken = pToken;
  138754. pDeferred->pNext = pCsr->pDeferred;
  138755. pDeferred->iCol = iCol;
  138756. pCsr->pDeferred = pDeferred;
  138757. assert( pToken->pDeferred==0 );
  138758. pToken->pDeferred = pDeferred;
  138759. return SQLITE_OK;
  138760. }
  138761. #endif
  138762. /*
  138763. ** SQLite value pRowid contains the rowid of a row that may or may not be
  138764. ** present in the FTS3 table. If it is, delete it and adjust the contents
  138765. ** of subsiduary data structures accordingly.
  138766. */
  138767. static int fts3DeleteByRowid(
  138768. Fts3Table *p,
  138769. sqlite3_value *pRowid,
  138770. int *pnChng, /* IN/OUT: Decrement if row is deleted */
  138771. u32 *aSzDel
  138772. ){
  138773. int rc = SQLITE_OK; /* Return code */
  138774. int bFound = 0; /* True if *pRowid really is in the table */
  138775. fts3DeleteTerms(&rc, p, pRowid, aSzDel, &bFound);
  138776. if( bFound && rc==SQLITE_OK ){
  138777. int isEmpty = 0; /* Deleting *pRowid leaves the table empty */
  138778. rc = fts3IsEmpty(p, pRowid, &isEmpty);
  138779. if( rc==SQLITE_OK ){
  138780. if( isEmpty ){
  138781. /* Deleting this row means the whole table is empty. In this case
  138782. ** delete the contents of all three tables and throw away any
  138783. ** data in the pendingTerms hash table. */
  138784. rc = fts3DeleteAll(p, 1);
  138785. *pnChng = 0;
  138786. memset(aSzDel, 0, sizeof(u32) * (p->nColumn+1) * 2);
  138787. }else{
  138788. *pnChng = *pnChng - 1;
  138789. if( p->zContentTbl==0 ){
  138790. fts3SqlExec(&rc, p, SQL_DELETE_CONTENT, &pRowid);
  138791. }
  138792. if( p->bHasDocsize ){
  138793. fts3SqlExec(&rc, p, SQL_DELETE_DOCSIZE, &pRowid);
  138794. }
  138795. }
  138796. }
  138797. }
  138798. return rc;
  138799. }
  138800. /*
  138801. ** This function does the work for the xUpdate method of FTS3 virtual
  138802. ** tables. The schema of the virtual table being:
  138803. **
  138804. ** CREATE TABLE <table name>(
  138805. ** <user columns>,
  138806. ** <table name> HIDDEN,
  138807. ** docid HIDDEN,
  138808. ** <langid> HIDDEN
  138809. ** );
  138810. **
  138811. **
  138812. */
  138813. SQLITE_PRIVATE int sqlite3Fts3UpdateMethod(
  138814. sqlite3_vtab *pVtab, /* FTS3 vtab object */
  138815. int nArg, /* Size of argument array */
  138816. sqlite3_value **apVal, /* Array of arguments */
  138817. sqlite_int64 *pRowid /* OUT: The affected (or effected) rowid */
  138818. ){
  138819. Fts3Table *p = (Fts3Table *)pVtab;
  138820. int rc = SQLITE_OK; /* Return Code */
  138821. int isRemove = 0; /* True for an UPDATE or DELETE */
  138822. u32 *aSzIns = 0; /* Sizes of inserted documents */
  138823. u32 *aSzDel = 0; /* Sizes of deleted documents */
  138824. int nChng = 0; /* Net change in number of documents */
  138825. int bInsertDone = 0;
  138826. /* At this point it must be known if the %_stat table exists or not.
  138827. ** So bHasStat may not be 2. */
  138828. assert( p->bHasStat==0 || p->bHasStat==1 );
  138829. assert( p->pSegments==0 );
  138830. assert(
  138831. nArg==1 /* DELETE operations */
  138832. || nArg==(2 + p->nColumn + 3) /* INSERT or UPDATE operations */
  138833. );
  138834. /* Check for a "special" INSERT operation. One of the form:
  138835. **
  138836. ** INSERT INTO xyz(xyz) VALUES('command');
  138837. */
  138838. if( nArg>1
  138839. && sqlite3_value_type(apVal[0])==SQLITE_NULL
  138840. && sqlite3_value_type(apVal[p->nColumn+2])!=SQLITE_NULL
  138841. ){
  138842. rc = fts3SpecialInsert(p, apVal[p->nColumn+2]);
  138843. goto update_out;
  138844. }
  138845. if( nArg>1 && sqlite3_value_int(apVal[2 + p->nColumn + 2])<0 ){
  138846. rc = SQLITE_CONSTRAINT;
  138847. goto update_out;
  138848. }
  138849. /* Allocate space to hold the change in document sizes */
  138850. aSzDel = sqlite3_malloc( sizeof(aSzDel[0])*(p->nColumn+1)*2 );
  138851. if( aSzDel==0 ){
  138852. rc = SQLITE_NOMEM;
  138853. goto update_out;
  138854. }
  138855. aSzIns = &aSzDel[p->nColumn+1];
  138856. memset(aSzDel, 0, sizeof(aSzDel[0])*(p->nColumn+1)*2);
  138857. rc = fts3Writelock(p);
  138858. if( rc!=SQLITE_OK ) goto update_out;
  138859. /* If this is an INSERT operation, or an UPDATE that modifies the rowid
  138860. ** value, then this operation requires constraint handling.
  138861. **
  138862. ** If the on-conflict mode is REPLACE, this means that the existing row
  138863. ** should be deleted from the database before inserting the new row. Or,
  138864. ** if the on-conflict mode is other than REPLACE, then this method must
  138865. ** detect the conflict and return SQLITE_CONSTRAINT before beginning to
  138866. ** modify the database file.
  138867. */
  138868. if( nArg>1 && p->zContentTbl==0 ){
  138869. /* Find the value object that holds the new rowid value. */
  138870. sqlite3_value *pNewRowid = apVal[3+p->nColumn];
  138871. if( sqlite3_value_type(pNewRowid)==SQLITE_NULL ){
  138872. pNewRowid = apVal[1];
  138873. }
  138874. if( sqlite3_value_type(pNewRowid)!=SQLITE_NULL && (
  138875. sqlite3_value_type(apVal[0])==SQLITE_NULL
  138876. || sqlite3_value_int64(apVal[0])!=sqlite3_value_int64(pNewRowid)
  138877. )){
  138878. /* The new rowid is not NULL (in this case the rowid will be
  138879. ** automatically assigned and there is no chance of a conflict), and
  138880. ** the statement is either an INSERT or an UPDATE that modifies the
  138881. ** rowid column. So if the conflict mode is REPLACE, then delete any
  138882. ** existing row with rowid=pNewRowid.
  138883. **
  138884. ** Or, if the conflict mode is not REPLACE, insert the new record into
  138885. ** the %_content table. If we hit the duplicate rowid constraint (or any
  138886. ** other error) while doing so, return immediately.
  138887. **
  138888. ** This branch may also run if pNewRowid contains a value that cannot
  138889. ** be losslessly converted to an integer. In this case, the eventual
  138890. ** call to fts3InsertData() (either just below or further on in this
  138891. ** function) will return SQLITE_MISMATCH. If fts3DeleteByRowid is
  138892. ** invoked, it will delete zero rows (since no row will have
  138893. ** docid=$pNewRowid if $pNewRowid is not an integer value).
  138894. */
  138895. if( sqlite3_vtab_on_conflict(p->db)==SQLITE_REPLACE ){
  138896. rc = fts3DeleteByRowid(p, pNewRowid, &nChng, aSzDel);
  138897. }else{
  138898. rc = fts3InsertData(p, apVal, pRowid);
  138899. bInsertDone = 1;
  138900. }
  138901. }
  138902. }
  138903. if( rc!=SQLITE_OK ){
  138904. goto update_out;
  138905. }
  138906. /* If this is a DELETE or UPDATE operation, remove the old record. */
  138907. if( sqlite3_value_type(apVal[0])!=SQLITE_NULL ){
  138908. assert( sqlite3_value_type(apVal[0])==SQLITE_INTEGER );
  138909. rc = fts3DeleteByRowid(p, apVal[0], &nChng, aSzDel);
  138910. isRemove = 1;
  138911. }
  138912. /* If this is an INSERT or UPDATE operation, insert the new record. */
  138913. if( nArg>1 && rc==SQLITE_OK ){
  138914. int iLangid = sqlite3_value_int(apVal[2 + p->nColumn + 2]);
  138915. if( bInsertDone==0 ){
  138916. rc = fts3InsertData(p, apVal, pRowid);
  138917. if( rc==SQLITE_CONSTRAINT && p->zContentTbl==0 ){
  138918. rc = FTS_CORRUPT_VTAB;
  138919. }
  138920. }
  138921. if( rc==SQLITE_OK && (!isRemove || *pRowid!=p->iPrevDocid ) ){
  138922. rc = fts3PendingTermsDocid(p, iLangid, *pRowid);
  138923. }
  138924. if( rc==SQLITE_OK ){
  138925. assert( p->iPrevDocid==*pRowid );
  138926. rc = fts3InsertTerms(p, iLangid, apVal, aSzIns);
  138927. }
  138928. if( p->bHasDocsize ){
  138929. fts3InsertDocsize(&rc, p, aSzIns);
  138930. }
  138931. nChng++;
  138932. }
  138933. if( p->bFts4 ){
  138934. fts3UpdateDocTotals(&rc, p, aSzIns, aSzDel, nChng);
  138935. }
  138936. update_out:
  138937. sqlite3_free(aSzDel);
  138938. sqlite3Fts3SegmentsClose(p);
  138939. return rc;
  138940. }
  138941. /*
  138942. ** Flush any data in the pending-terms hash table to disk. If successful,
  138943. ** merge all segments in the database (including the new segment, if
  138944. ** there was any data to flush) into a single segment.
  138945. */
  138946. SQLITE_PRIVATE int sqlite3Fts3Optimize(Fts3Table *p){
  138947. int rc;
  138948. rc = sqlite3_exec(p->db, "SAVEPOINT fts3", 0, 0, 0);
  138949. if( rc==SQLITE_OK ){
  138950. rc = fts3DoOptimize(p, 1);
  138951. if( rc==SQLITE_OK || rc==SQLITE_DONE ){
  138952. int rc2 = sqlite3_exec(p->db, "RELEASE fts3", 0, 0, 0);
  138953. if( rc2!=SQLITE_OK ) rc = rc2;
  138954. }else{
  138955. sqlite3_exec(p->db, "ROLLBACK TO fts3", 0, 0, 0);
  138956. sqlite3_exec(p->db, "RELEASE fts3", 0, 0, 0);
  138957. }
  138958. }
  138959. sqlite3Fts3SegmentsClose(p);
  138960. return rc;
  138961. }
  138962. #endif
  138963. /************** End of fts3_write.c ******************************************/
  138964. /************** Begin file fts3_snippet.c ************************************/
  138965. /*
  138966. ** 2009 Oct 23
  138967. **
  138968. ** The author disclaims copyright to this source code. In place of
  138969. ** a legal notice, here is a blessing:
  138970. **
  138971. ** May you do good and not evil.
  138972. ** May you find forgiveness for yourself and forgive others.
  138973. ** May you share freely, never taking more than you give.
  138974. **
  138975. ******************************************************************************
  138976. */
  138977. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  138978. /* #include <string.h> */
  138979. /* #include <assert.h> */
  138980. /*
  138981. ** Characters that may appear in the second argument to matchinfo().
  138982. */
  138983. #define FTS3_MATCHINFO_NPHRASE 'p' /* 1 value */
  138984. #define FTS3_MATCHINFO_NCOL 'c' /* 1 value */
  138985. #define FTS3_MATCHINFO_NDOC 'n' /* 1 value */
  138986. #define FTS3_MATCHINFO_AVGLENGTH 'a' /* nCol values */
  138987. #define FTS3_MATCHINFO_LENGTH 'l' /* nCol values */
  138988. #define FTS3_MATCHINFO_LCS 's' /* nCol values */
  138989. #define FTS3_MATCHINFO_HITS 'x' /* 3*nCol*nPhrase values */
  138990. #define FTS3_MATCHINFO_LHITS 'y' /* nCol*nPhrase values */
  138991. /*
  138992. ** The default value for the second argument to matchinfo().
  138993. */
  138994. #define FTS3_MATCHINFO_DEFAULT "pcx"
  138995. /*
  138996. ** Used as an fts3ExprIterate() context when loading phrase doclists to
  138997. ** Fts3Expr.aDoclist[]/nDoclist.
  138998. */
  138999. typedef struct LoadDoclistCtx LoadDoclistCtx;
  139000. struct LoadDoclistCtx {
  139001. Fts3Cursor *pCsr; /* FTS3 Cursor */
  139002. int nPhrase; /* Number of phrases seen so far */
  139003. int nToken; /* Number of tokens seen so far */
  139004. };
  139005. /*
  139006. ** The following types are used as part of the implementation of the
  139007. ** fts3BestSnippet() routine.
  139008. */
  139009. typedef struct SnippetIter SnippetIter;
  139010. typedef struct SnippetPhrase SnippetPhrase;
  139011. typedef struct SnippetFragment SnippetFragment;
  139012. struct SnippetIter {
  139013. Fts3Cursor *pCsr; /* Cursor snippet is being generated from */
  139014. int iCol; /* Extract snippet from this column */
  139015. int nSnippet; /* Requested snippet length (in tokens) */
  139016. int nPhrase; /* Number of phrases in query */
  139017. SnippetPhrase *aPhrase; /* Array of size nPhrase */
  139018. int iCurrent; /* First token of current snippet */
  139019. };
  139020. struct SnippetPhrase {
  139021. int nToken; /* Number of tokens in phrase */
  139022. char *pList; /* Pointer to start of phrase position list */
  139023. int iHead; /* Next value in position list */
  139024. char *pHead; /* Position list data following iHead */
  139025. int iTail; /* Next value in trailing position list */
  139026. char *pTail; /* Position list data following iTail */
  139027. };
  139028. struct SnippetFragment {
  139029. int iCol; /* Column snippet is extracted from */
  139030. int iPos; /* Index of first token in snippet */
  139031. u64 covered; /* Mask of query phrases covered */
  139032. u64 hlmask; /* Mask of snippet terms to highlight */
  139033. };
  139034. /*
  139035. ** This type is used as an fts3ExprIterate() context object while
  139036. ** accumulating the data returned by the matchinfo() function.
  139037. */
  139038. typedef struct MatchInfo MatchInfo;
  139039. struct MatchInfo {
  139040. Fts3Cursor *pCursor; /* FTS3 Cursor */
  139041. int nCol; /* Number of columns in table */
  139042. int nPhrase; /* Number of matchable phrases in query */
  139043. sqlite3_int64 nDoc; /* Number of docs in database */
  139044. u32 *aMatchinfo; /* Pre-allocated buffer */
  139045. };
  139046. /*
  139047. ** The snippet() and offsets() functions both return text values. An instance
  139048. ** of the following structure is used to accumulate those values while the
  139049. ** functions are running. See fts3StringAppend() for details.
  139050. */
  139051. typedef struct StrBuffer StrBuffer;
  139052. struct StrBuffer {
  139053. char *z; /* Pointer to buffer containing string */
  139054. int n; /* Length of z in bytes (excl. nul-term) */
  139055. int nAlloc; /* Allocated size of buffer z in bytes */
  139056. };
  139057. /*
  139058. ** This function is used to help iterate through a position-list. A position
  139059. ** list is a list of unique integers, sorted from smallest to largest. Each
  139060. ** element of the list is represented by an FTS3 varint that takes the value
  139061. ** of the difference between the current element and the previous one plus
  139062. ** two. For example, to store the position-list:
  139063. **
  139064. ** 4 9 113
  139065. **
  139066. ** the three varints:
  139067. **
  139068. ** 6 7 106
  139069. **
  139070. ** are encoded.
  139071. **
  139072. ** When this function is called, *pp points to the start of an element of
  139073. ** the list. *piPos contains the value of the previous entry in the list.
  139074. ** After it returns, *piPos contains the value of the next element of the
  139075. ** list and *pp is advanced to the following varint.
  139076. */
  139077. static void fts3GetDeltaPosition(char **pp, int *piPos){
  139078. int iVal;
  139079. *pp += fts3GetVarint32(*pp, &iVal);
  139080. *piPos += (iVal-2);
  139081. }
  139082. /*
  139083. ** Helper function for fts3ExprIterate() (see below).
  139084. */
  139085. static int fts3ExprIterate2(
  139086. Fts3Expr *pExpr, /* Expression to iterate phrases of */
  139087. int *piPhrase, /* Pointer to phrase counter */
  139088. int (*x)(Fts3Expr*,int,void*), /* Callback function to invoke for phrases */
  139089. void *pCtx /* Second argument to pass to callback */
  139090. ){
  139091. int rc; /* Return code */
  139092. int eType = pExpr->eType; /* Type of expression node pExpr */
  139093. if( eType!=FTSQUERY_PHRASE ){
  139094. assert( pExpr->pLeft && pExpr->pRight );
  139095. rc = fts3ExprIterate2(pExpr->pLeft, piPhrase, x, pCtx);
  139096. if( rc==SQLITE_OK && eType!=FTSQUERY_NOT ){
  139097. rc = fts3ExprIterate2(pExpr->pRight, piPhrase, x, pCtx);
  139098. }
  139099. }else{
  139100. rc = x(pExpr, *piPhrase, pCtx);
  139101. (*piPhrase)++;
  139102. }
  139103. return rc;
  139104. }
  139105. /*
  139106. ** Iterate through all phrase nodes in an FTS3 query, except those that
  139107. ** are part of a sub-tree that is the right-hand-side of a NOT operator.
  139108. ** For each phrase node found, the supplied callback function is invoked.
  139109. **
  139110. ** If the callback function returns anything other than SQLITE_OK,
  139111. ** the iteration is abandoned and the error code returned immediately.
  139112. ** Otherwise, SQLITE_OK is returned after a callback has been made for
  139113. ** all eligible phrase nodes.
  139114. */
  139115. static int fts3ExprIterate(
  139116. Fts3Expr *pExpr, /* Expression to iterate phrases of */
  139117. int (*x)(Fts3Expr*,int,void*), /* Callback function to invoke for phrases */
  139118. void *pCtx /* Second argument to pass to callback */
  139119. ){
  139120. int iPhrase = 0; /* Variable used as the phrase counter */
  139121. return fts3ExprIterate2(pExpr, &iPhrase, x, pCtx);
  139122. }
  139123. /*
  139124. ** This is an fts3ExprIterate() callback used while loading the doclists
  139125. ** for each phrase into Fts3Expr.aDoclist[]/nDoclist. See also
  139126. ** fts3ExprLoadDoclists().
  139127. */
  139128. static int fts3ExprLoadDoclistsCb(Fts3Expr *pExpr, int iPhrase, void *ctx){
  139129. int rc = SQLITE_OK;
  139130. Fts3Phrase *pPhrase = pExpr->pPhrase;
  139131. LoadDoclistCtx *p = (LoadDoclistCtx *)ctx;
  139132. UNUSED_PARAMETER(iPhrase);
  139133. p->nPhrase++;
  139134. p->nToken += pPhrase->nToken;
  139135. return rc;
  139136. }
  139137. /*
  139138. ** Load the doclists for each phrase in the query associated with FTS3 cursor
  139139. ** pCsr.
  139140. **
  139141. ** If pnPhrase is not NULL, then *pnPhrase is set to the number of matchable
  139142. ** phrases in the expression (all phrases except those directly or
  139143. ** indirectly descended from the right-hand-side of a NOT operator). If
  139144. ** pnToken is not NULL, then it is set to the number of tokens in all
  139145. ** matchable phrases of the expression.
  139146. */
  139147. static int fts3ExprLoadDoclists(
  139148. Fts3Cursor *pCsr, /* Fts3 cursor for current query */
  139149. int *pnPhrase, /* OUT: Number of phrases in query */
  139150. int *pnToken /* OUT: Number of tokens in query */
  139151. ){
  139152. int rc; /* Return Code */
  139153. LoadDoclistCtx sCtx = {0,0,0}; /* Context for fts3ExprIterate() */
  139154. sCtx.pCsr = pCsr;
  139155. rc = fts3ExprIterate(pCsr->pExpr, fts3ExprLoadDoclistsCb, (void *)&sCtx);
  139156. if( pnPhrase ) *pnPhrase = sCtx.nPhrase;
  139157. if( pnToken ) *pnToken = sCtx.nToken;
  139158. return rc;
  139159. }
  139160. static int fts3ExprPhraseCountCb(Fts3Expr *pExpr, int iPhrase, void *ctx){
  139161. (*(int *)ctx)++;
  139162. UNUSED_PARAMETER(pExpr);
  139163. UNUSED_PARAMETER(iPhrase);
  139164. return SQLITE_OK;
  139165. }
  139166. static int fts3ExprPhraseCount(Fts3Expr *pExpr){
  139167. int nPhrase = 0;
  139168. (void)fts3ExprIterate(pExpr, fts3ExprPhraseCountCb, (void *)&nPhrase);
  139169. return nPhrase;
  139170. }
  139171. /*
  139172. ** Advance the position list iterator specified by the first two
  139173. ** arguments so that it points to the first element with a value greater
  139174. ** than or equal to parameter iNext.
  139175. */
  139176. static void fts3SnippetAdvance(char **ppIter, int *piIter, int iNext){
  139177. char *pIter = *ppIter;
  139178. if( pIter ){
  139179. int iIter = *piIter;
  139180. while( iIter<iNext ){
  139181. if( 0==(*pIter & 0xFE) ){
  139182. iIter = -1;
  139183. pIter = 0;
  139184. break;
  139185. }
  139186. fts3GetDeltaPosition(&pIter, &iIter);
  139187. }
  139188. *piIter = iIter;
  139189. *ppIter = pIter;
  139190. }
  139191. }
  139192. /*
  139193. ** Advance the snippet iterator to the next candidate snippet.
  139194. */
  139195. static int fts3SnippetNextCandidate(SnippetIter *pIter){
  139196. int i; /* Loop counter */
  139197. if( pIter->iCurrent<0 ){
  139198. /* The SnippetIter object has just been initialized. The first snippet
  139199. ** candidate always starts at offset 0 (even if this candidate has a
  139200. ** score of 0.0).
  139201. */
  139202. pIter->iCurrent = 0;
  139203. /* Advance the 'head' iterator of each phrase to the first offset that
  139204. ** is greater than or equal to (iNext+nSnippet).
  139205. */
  139206. for(i=0; i<pIter->nPhrase; i++){
  139207. SnippetPhrase *pPhrase = &pIter->aPhrase[i];
  139208. fts3SnippetAdvance(&pPhrase->pHead, &pPhrase->iHead, pIter->nSnippet);
  139209. }
  139210. }else{
  139211. int iStart;
  139212. int iEnd = 0x7FFFFFFF;
  139213. for(i=0; i<pIter->nPhrase; i++){
  139214. SnippetPhrase *pPhrase = &pIter->aPhrase[i];
  139215. if( pPhrase->pHead && pPhrase->iHead<iEnd ){
  139216. iEnd = pPhrase->iHead;
  139217. }
  139218. }
  139219. if( iEnd==0x7FFFFFFF ){
  139220. return 1;
  139221. }
  139222. pIter->iCurrent = iStart = iEnd - pIter->nSnippet + 1;
  139223. for(i=0; i<pIter->nPhrase; i++){
  139224. SnippetPhrase *pPhrase = &pIter->aPhrase[i];
  139225. fts3SnippetAdvance(&pPhrase->pHead, &pPhrase->iHead, iEnd+1);
  139226. fts3SnippetAdvance(&pPhrase->pTail, &pPhrase->iTail, iStart);
  139227. }
  139228. }
  139229. return 0;
  139230. }
  139231. /*
  139232. ** Retrieve information about the current candidate snippet of snippet
  139233. ** iterator pIter.
  139234. */
  139235. static void fts3SnippetDetails(
  139236. SnippetIter *pIter, /* Snippet iterator */
  139237. u64 mCovered, /* Bitmask of phrases already covered */
  139238. int *piToken, /* OUT: First token of proposed snippet */
  139239. int *piScore, /* OUT: "Score" for this snippet */
  139240. u64 *pmCover, /* OUT: Bitmask of phrases covered */
  139241. u64 *pmHighlight /* OUT: Bitmask of terms to highlight */
  139242. ){
  139243. int iStart = pIter->iCurrent; /* First token of snippet */
  139244. int iScore = 0; /* Score of this snippet */
  139245. int i; /* Loop counter */
  139246. u64 mCover = 0; /* Mask of phrases covered by this snippet */
  139247. u64 mHighlight = 0; /* Mask of tokens to highlight in snippet */
  139248. for(i=0; i<pIter->nPhrase; i++){
  139249. SnippetPhrase *pPhrase = &pIter->aPhrase[i];
  139250. if( pPhrase->pTail ){
  139251. char *pCsr = pPhrase->pTail;
  139252. int iCsr = pPhrase->iTail;
  139253. while( iCsr<(iStart+pIter->nSnippet) ){
  139254. int j;
  139255. u64 mPhrase = (u64)1 << i;
  139256. u64 mPos = (u64)1 << (iCsr - iStart);
  139257. assert( iCsr>=iStart );
  139258. if( (mCover|mCovered)&mPhrase ){
  139259. iScore++;
  139260. }else{
  139261. iScore += 1000;
  139262. }
  139263. mCover |= mPhrase;
  139264. for(j=0; j<pPhrase->nToken; j++){
  139265. mHighlight |= (mPos>>j);
  139266. }
  139267. if( 0==(*pCsr & 0x0FE) ) break;
  139268. fts3GetDeltaPosition(&pCsr, &iCsr);
  139269. }
  139270. }
  139271. }
  139272. /* Set the output variables before returning. */
  139273. *piToken = iStart;
  139274. *piScore = iScore;
  139275. *pmCover = mCover;
  139276. *pmHighlight = mHighlight;
  139277. }
  139278. /*
  139279. ** This function is an fts3ExprIterate() callback used by fts3BestSnippet().
  139280. ** Each invocation populates an element of the SnippetIter.aPhrase[] array.
  139281. */
  139282. static int fts3SnippetFindPositions(Fts3Expr *pExpr, int iPhrase, void *ctx){
  139283. SnippetIter *p = (SnippetIter *)ctx;
  139284. SnippetPhrase *pPhrase = &p->aPhrase[iPhrase];
  139285. char *pCsr;
  139286. int rc;
  139287. pPhrase->nToken = pExpr->pPhrase->nToken;
  139288. rc = sqlite3Fts3EvalPhrasePoslist(p->pCsr, pExpr, p->iCol, &pCsr);
  139289. assert( rc==SQLITE_OK || pCsr==0 );
  139290. if( pCsr ){
  139291. int iFirst = 0;
  139292. pPhrase->pList = pCsr;
  139293. fts3GetDeltaPosition(&pCsr, &iFirst);
  139294. assert( iFirst>=0 );
  139295. pPhrase->pHead = pCsr;
  139296. pPhrase->pTail = pCsr;
  139297. pPhrase->iHead = iFirst;
  139298. pPhrase->iTail = iFirst;
  139299. }else{
  139300. assert( rc!=SQLITE_OK || (
  139301. pPhrase->pList==0 && pPhrase->pHead==0 && pPhrase->pTail==0
  139302. ));
  139303. }
  139304. return rc;
  139305. }
  139306. /*
  139307. ** Select the fragment of text consisting of nFragment contiguous tokens
  139308. ** from column iCol that represent the "best" snippet. The best snippet
  139309. ** is the snippet with the highest score, where scores are calculated
  139310. ** by adding:
  139311. **
  139312. ** (a) +1 point for each occurrence of a matchable phrase in the snippet.
  139313. **
  139314. ** (b) +1000 points for the first occurrence of each matchable phrase in
  139315. ** the snippet for which the corresponding mCovered bit is not set.
  139316. **
  139317. ** The selected snippet parameters are stored in structure *pFragment before
  139318. ** returning. The score of the selected snippet is stored in *piScore
  139319. ** before returning.
  139320. */
  139321. static int fts3BestSnippet(
  139322. int nSnippet, /* Desired snippet length */
  139323. Fts3Cursor *pCsr, /* Cursor to create snippet for */
  139324. int iCol, /* Index of column to create snippet from */
  139325. u64 mCovered, /* Mask of phrases already covered */
  139326. u64 *pmSeen, /* IN/OUT: Mask of phrases seen */
  139327. SnippetFragment *pFragment, /* OUT: Best snippet found */
  139328. int *piScore /* OUT: Score of snippet pFragment */
  139329. ){
  139330. int rc; /* Return Code */
  139331. int nList; /* Number of phrases in expression */
  139332. SnippetIter sIter; /* Iterates through snippet candidates */
  139333. int nByte; /* Number of bytes of space to allocate */
  139334. int iBestScore = -1; /* Best snippet score found so far */
  139335. int i; /* Loop counter */
  139336. memset(&sIter, 0, sizeof(sIter));
  139337. /* Iterate through the phrases in the expression to count them. The same
  139338. ** callback makes sure the doclists are loaded for each phrase.
  139339. */
  139340. rc = fts3ExprLoadDoclists(pCsr, &nList, 0);
  139341. if( rc!=SQLITE_OK ){
  139342. return rc;
  139343. }
  139344. /* Now that it is known how many phrases there are, allocate and zero
  139345. ** the required space using malloc().
  139346. */
  139347. nByte = sizeof(SnippetPhrase) * nList;
  139348. sIter.aPhrase = (SnippetPhrase *)sqlite3_malloc(nByte);
  139349. if( !sIter.aPhrase ){
  139350. return SQLITE_NOMEM;
  139351. }
  139352. memset(sIter.aPhrase, 0, nByte);
  139353. /* Initialize the contents of the SnippetIter object. Then iterate through
  139354. ** the set of phrases in the expression to populate the aPhrase[] array.
  139355. */
  139356. sIter.pCsr = pCsr;
  139357. sIter.iCol = iCol;
  139358. sIter.nSnippet = nSnippet;
  139359. sIter.nPhrase = nList;
  139360. sIter.iCurrent = -1;
  139361. rc = fts3ExprIterate(pCsr->pExpr, fts3SnippetFindPositions, (void *)&sIter);
  139362. if( rc==SQLITE_OK ){
  139363. /* Set the *pmSeen output variable. */
  139364. for(i=0; i<nList; i++){
  139365. if( sIter.aPhrase[i].pHead ){
  139366. *pmSeen |= (u64)1 << i;
  139367. }
  139368. }
  139369. /* Loop through all candidate snippets. Store the best snippet in
  139370. ** *pFragment. Store its associated 'score' in iBestScore.
  139371. */
  139372. pFragment->iCol = iCol;
  139373. while( !fts3SnippetNextCandidate(&sIter) ){
  139374. int iPos;
  139375. int iScore;
  139376. u64 mCover;
  139377. u64 mHighlite;
  139378. fts3SnippetDetails(&sIter, mCovered, &iPos, &iScore, &mCover,&mHighlite);
  139379. assert( iScore>=0 );
  139380. if( iScore>iBestScore ){
  139381. pFragment->iPos = iPos;
  139382. pFragment->hlmask = mHighlite;
  139383. pFragment->covered = mCover;
  139384. iBestScore = iScore;
  139385. }
  139386. }
  139387. *piScore = iBestScore;
  139388. }
  139389. sqlite3_free(sIter.aPhrase);
  139390. return rc;
  139391. }
  139392. /*
  139393. ** Append a string to the string-buffer passed as the first argument.
  139394. **
  139395. ** If nAppend is negative, then the length of the string zAppend is
  139396. ** determined using strlen().
  139397. */
  139398. static int fts3StringAppend(
  139399. StrBuffer *pStr, /* Buffer to append to */
  139400. const char *zAppend, /* Pointer to data to append to buffer */
  139401. int nAppend /* Size of zAppend in bytes (or -1) */
  139402. ){
  139403. if( nAppend<0 ){
  139404. nAppend = (int)strlen(zAppend);
  139405. }
  139406. /* If there is insufficient space allocated at StrBuffer.z, use realloc()
  139407. ** to grow the buffer until so that it is big enough to accomadate the
  139408. ** appended data.
  139409. */
  139410. if( pStr->n+nAppend+1>=pStr->nAlloc ){
  139411. int nAlloc = pStr->nAlloc+nAppend+100;
  139412. char *zNew = sqlite3_realloc(pStr->z, nAlloc);
  139413. if( !zNew ){
  139414. return SQLITE_NOMEM;
  139415. }
  139416. pStr->z = zNew;
  139417. pStr->nAlloc = nAlloc;
  139418. }
  139419. assert( pStr->z!=0 && (pStr->nAlloc >= pStr->n+nAppend+1) );
  139420. /* Append the data to the string buffer. */
  139421. memcpy(&pStr->z[pStr->n], zAppend, nAppend);
  139422. pStr->n += nAppend;
  139423. pStr->z[pStr->n] = '\0';
  139424. return SQLITE_OK;
  139425. }
  139426. /*
  139427. ** The fts3BestSnippet() function often selects snippets that end with a
  139428. ** query term. That is, the final term of the snippet is always a term
  139429. ** that requires highlighting. For example, if 'X' is a highlighted term
  139430. ** and '.' is a non-highlighted term, BestSnippet() may select:
  139431. **
  139432. ** ........X.....X
  139433. **
  139434. ** This function "shifts" the beginning of the snippet forward in the
  139435. ** document so that there are approximately the same number of
  139436. ** non-highlighted terms to the right of the final highlighted term as there
  139437. ** are to the left of the first highlighted term. For example, to this:
  139438. **
  139439. ** ....X.....X....
  139440. **
  139441. ** This is done as part of extracting the snippet text, not when selecting
  139442. ** the snippet. Snippet selection is done based on doclists only, so there
  139443. ** is no way for fts3BestSnippet() to know whether or not the document
  139444. ** actually contains terms that follow the final highlighted term.
  139445. */
  139446. static int fts3SnippetShift(
  139447. Fts3Table *pTab, /* FTS3 table snippet comes from */
  139448. int iLangid, /* Language id to use in tokenizing */
  139449. int nSnippet, /* Number of tokens desired for snippet */
  139450. const char *zDoc, /* Document text to extract snippet from */
  139451. int nDoc, /* Size of buffer zDoc in bytes */
  139452. int *piPos, /* IN/OUT: First token of snippet */
  139453. u64 *pHlmask /* IN/OUT: Mask of tokens to highlight */
  139454. ){
  139455. u64 hlmask = *pHlmask; /* Local copy of initial highlight-mask */
  139456. if( hlmask ){
  139457. int nLeft; /* Tokens to the left of first highlight */
  139458. int nRight; /* Tokens to the right of last highlight */
  139459. int nDesired; /* Ideal number of tokens to shift forward */
  139460. for(nLeft=0; !(hlmask & ((u64)1 << nLeft)); nLeft++);
  139461. for(nRight=0; !(hlmask & ((u64)1 << (nSnippet-1-nRight))); nRight++);
  139462. nDesired = (nLeft-nRight)/2;
  139463. /* Ideally, the start of the snippet should be pushed forward in the
  139464. ** document nDesired tokens. This block checks if there are actually
  139465. ** nDesired tokens to the right of the snippet. If so, *piPos and
  139466. ** *pHlMask are updated to shift the snippet nDesired tokens to the
  139467. ** right. Otherwise, the snippet is shifted by the number of tokens
  139468. ** available.
  139469. */
  139470. if( nDesired>0 ){
  139471. int nShift; /* Number of tokens to shift snippet by */
  139472. int iCurrent = 0; /* Token counter */
  139473. int rc; /* Return Code */
  139474. sqlite3_tokenizer_module *pMod;
  139475. sqlite3_tokenizer_cursor *pC;
  139476. pMod = (sqlite3_tokenizer_module *)pTab->pTokenizer->pModule;
  139477. /* Open a cursor on zDoc/nDoc. Check if there are (nSnippet+nDesired)
  139478. ** or more tokens in zDoc/nDoc.
  139479. */
  139480. rc = sqlite3Fts3OpenTokenizer(pTab->pTokenizer, iLangid, zDoc, nDoc, &pC);
  139481. if( rc!=SQLITE_OK ){
  139482. return rc;
  139483. }
  139484. while( rc==SQLITE_OK && iCurrent<(nSnippet+nDesired) ){
  139485. const char *ZDUMMY; int DUMMY1 = 0, DUMMY2 = 0, DUMMY3 = 0;
  139486. rc = pMod->xNext(pC, &ZDUMMY, &DUMMY1, &DUMMY2, &DUMMY3, &iCurrent);
  139487. }
  139488. pMod->xClose(pC);
  139489. if( rc!=SQLITE_OK && rc!=SQLITE_DONE ){ return rc; }
  139490. nShift = (rc==SQLITE_DONE)+iCurrent-nSnippet;
  139491. assert( nShift<=nDesired );
  139492. if( nShift>0 ){
  139493. *piPos += nShift;
  139494. *pHlmask = hlmask >> nShift;
  139495. }
  139496. }
  139497. }
  139498. return SQLITE_OK;
  139499. }
  139500. /*
  139501. ** Extract the snippet text for fragment pFragment from cursor pCsr and
  139502. ** append it to string buffer pOut.
  139503. */
  139504. static int fts3SnippetText(
  139505. Fts3Cursor *pCsr, /* FTS3 Cursor */
  139506. SnippetFragment *pFragment, /* Snippet to extract */
  139507. int iFragment, /* Fragment number */
  139508. int isLast, /* True for final fragment in snippet */
  139509. int nSnippet, /* Number of tokens in extracted snippet */
  139510. const char *zOpen, /* String inserted before highlighted term */
  139511. const char *zClose, /* String inserted after highlighted term */
  139512. const char *zEllipsis, /* String inserted between snippets */
  139513. StrBuffer *pOut /* Write output here */
  139514. ){
  139515. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  139516. int rc; /* Return code */
  139517. const char *zDoc; /* Document text to extract snippet from */
  139518. int nDoc; /* Size of zDoc in bytes */
  139519. int iCurrent = 0; /* Current token number of document */
  139520. int iEnd = 0; /* Byte offset of end of current token */
  139521. int isShiftDone = 0; /* True after snippet is shifted */
  139522. int iPos = pFragment->iPos; /* First token of snippet */
  139523. u64 hlmask = pFragment->hlmask; /* Highlight-mask for snippet */
  139524. int iCol = pFragment->iCol+1; /* Query column to extract text from */
  139525. sqlite3_tokenizer_module *pMod; /* Tokenizer module methods object */
  139526. sqlite3_tokenizer_cursor *pC; /* Tokenizer cursor open on zDoc/nDoc */
  139527. zDoc = (const char *)sqlite3_column_text(pCsr->pStmt, iCol);
  139528. if( zDoc==0 ){
  139529. if( sqlite3_column_type(pCsr->pStmt, iCol)!=SQLITE_NULL ){
  139530. return SQLITE_NOMEM;
  139531. }
  139532. return SQLITE_OK;
  139533. }
  139534. nDoc = sqlite3_column_bytes(pCsr->pStmt, iCol);
  139535. /* Open a token cursor on the document. */
  139536. pMod = (sqlite3_tokenizer_module *)pTab->pTokenizer->pModule;
  139537. rc = sqlite3Fts3OpenTokenizer(pTab->pTokenizer, pCsr->iLangid, zDoc,nDoc,&pC);
  139538. if( rc!=SQLITE_OK ){
  139539. return rc;
  139540. }
  139541. while( rc==SQLITE_OK ){
  139542. const char *ZDUMMY; /* Dummy argument used with tokenizer */
  139543. int DUMMY1 = -1; /* Dummy argument used with tokenizer */
  139544. int iBegin = 0; /* Offset in zDoc of start of token */
  139545. int iFin = 0; /* Offset in zDoc of end of token */
  139546. int isHighlight = 0; /* True for highlighted terms */
  139547. /* Variable DUMMY1 is initialized to a negative value above. Elsewhere
  139548. ** in the FTS code the variable that the third argument to xNext points to
  139549. ** is initialized to zero before the first (*but not necessarily
  139550. ** subsequent*) call to xNext(). This is done for a particular application
  139551. ** that needs to know whether or not the tokenizer is being used for
  139552. ** snippet generation or for some other purpose.
  139553. **
  139554. ** Extreme care is required when writing code to depend on this
  139555. ** initialization. It is not a documented part of the tokenizer interface.
  139556. ** If a tokenizer is used directly by any code outside of FTS, this
  139557. ** convention might not be respected. */
  139558. rc = pMod->xNext(pC, &ZDUMMY, &DUMMY1, &iBegin, &iFin, &iCurrent);
  139559. if( rc!=SQLITE_OK ){
  139560. if( rc==SQLITE_DONE ){
  139561. /* Special case - the last token of the snippet is also the last token
  139562. ** of the column. Append any punctuation that occurred between the end
  139563. ** of the previous token and the end of the document to the output.
  139564. ** Then break out of the loop. */
  139565. rc = fts3StringAppend(pOut, &zDoc[iEnd], -1);
  139566. }
  139567. break;
  139568. }
  139569. if( iCurrent<iPos ){ continue; }
  139570. if( !isShiftDone ){
  139571. int n = nDoc - iBegin;
  139572. rc = fts3SnippetShift(
  139573. pTab, pCsr->iLangid, nSnippet, &zDoc[iBegin], n, &iPos, &hlmask
  139574. );
  139575. isShiftDone = 1;
  139576. /* Now that the shift has been done, check if the initial "..." are
  139577. ** required. They are required if (a) this is not the first fragment,
  139578. ** or (b) this fragment does not begin at position 0 of its column.
  139579. */
  139580. if( rc==SQLITE_OK ){
  139581. if( iPos>0 || iFragment>0 ){
  139582. rc = fts3StringAppend(pOut, zEllipsis, -1);
  139583. }else if( iBegin ){
  139584. rc = fts3StringAppend(pOut, zDoc, iBegin);
  139585. }
  139586. }
  139587. if( rc!=SQLITE_OK || iCurrent<iPos ) continue;
  139588. }
  139589. if( iCurrent>=(iPos+nSnippet) ){
  139590. if( isLast ){
  139591. rc = fts3StringAppend(pOut, zEllipsis, -1);
  139592. }
  139593. break;
  139594. }
  139595. /* Set isHighlight to true if this term should be highlighted. */
  139596. isHighlight = (hlmask & ((u64)1 << (iCurrent-iPos)))!=0;
  139597. if( iCurrent>iPos ) rc = fts3StringAppend(pOut, &zDoc[iEnd], iBegin-iEnd);
  139598. if( rc==SQLITE_OK && isHighlight ) rc = fts3StringAppend(pOut, zOpen, -1);
  139599. if( rc==SQLITE_OK ) rc = fts3StringAppend(pOut, &zDoc[iBegin], iFin-iBegin);
  139600. if( rc==SQLITE_OK && isHighlight ) rc = fts3StringAppend(pOut, zClose, -1);
  139601. iEnd = iFin;
  139602. }
  139603. pMod->xClose(pC);
  139604. return rc;
  139605. }
  139606. /*
  139607. ** This function is used to count the entries in a column-list (a
  139608. ** delta-encoded list of term offsets within a single column of a single
  139609. ** row). When this function is called, *ppCollist should point to the
  139610. ** beginning of the first varint in the column-list (the varint that
  139611. ** contains the position of the first matching term in the column data).
  139612. ** Before returning, *ppCollist is set to point to the first byte after
  139613. ** the last varint in the column-list (either the 0x00 signifying the end
  139614. ** of the position-list, or the 0x01 that precedes the column number of
  139615. ** the next column in the position-list).
  139616. **
  139617. ** The number of elements in the column-list is returned.
  139618. */
  139619. static int fts3ColumnlistCount(char **ppCollist){
  139620. char *pEnd = *ppCollist;
  139621. char c = 0;
  139622. int nEntry = 0;
  139623. /* A column-list is terminated by either a 0x01 or 0x00. */
  139624. while( 0xFE & (*pEnd | c) ){
  139625. c = *pEnd++ & 0x80;
  139626. if( !c ) nEntry++;
  139627. }
  139628. *ppCollist = pEnd;
  139629. return nEntry;
  139630. }
  139631. /*
  139632. ** fts3ExprIterate() callback used to collect the "global" matchinfo stats
  139633. ** for a single query.
  139634. **
  139635. ** fts3ExprIterate() callback to load the 'global' elements of a
  139636. ** FTS3_MATCHINFO_HITS matchinfo array. The global stats are those elements
  139637. ** of the matchinfo array that are constant for all rows returned by the
  139638. ** current query.
  139639. **
  139640. ** Argument pCtx is actually a pointer to a struct of type MatchInfo. This
  139641. ** function populates Matchinfo.aMatchinfo[] as follows:
  139642. **
  139643. ** for(iCol=0; iCol<nCol; iCol++){
  139644. ** aMatchinfo[3*iPhrase*nCol + 3*iCol + 1] = X;
  139645. ** aMatchinfo[3*iPhrase*nCol + 3*iCol + 2] = Y;
  139646. ** }
  139647. **
  139648. ** where X is the number of matches for phrase iPhrase is column iCol of all
  139649. ** rows of the table. Y is the number of rows for which column iCol contains
  139650. ** at least one instance of phrase iPhrase.
  139651. **
  139652. ** If the phrase pExpr consists entirely of deferred tokens, then all X and
  139653. ** Y values are set to nDoc, where nDoc is the number of documents in the
  139654. ** file system. This is done because the full-text index doclist is required
  139655. ** to calculate these values properly, and the full-text index doclist is
  139656. ** not available for deferred tokens.
  139657. */
  139658. static int fts3ExprGlobalHitsCb(
  139659. Fts3Expr *pExpr, /* Phrase expression node */
  139660. int iPhrase, /* Phrase number (numbered from zero) */
  139661. void *pCtx /* Pointer to MatchInfo structure */
  139662. ){
  139663. MatchInfo *p = (MatchInfo *)pCtx;
  139664. return sqlite3Fts3EvalPhraseStats(
  139665. p->pCursor, pExpr, &p->aMatchinfo[3*iPhrase*p->nCol]
  139666. );
  139667. }
  139668. /*
  139669. ** fts3ExprIterate() callback used to collect the "local" part of the
  139670. ** FTS3_MATCHINFO_HITS array. The local stats are those elements of the
  139671. ** array that are different for each row returned by the query.
  139672. */
  139673. static int fts3ExprLocalHitsCb(
  139674. Fts3Expr *pExpr, /* Phrase expression node */
  139675. int iPhrase, /* Phrase number */
  139676. void *pCtx /* Pointer to MatchInfo structure */
  139677. ){
  139678. int rc = SQLITE_OK;
  139679. MatchInfo *p = (MatchInfo *)pCtx;
  139680. int iStart = iPhrase * p->nCol * 3;
  139681. int i;
  139682. for(i=0; i<p->nCol && rc==SQLITE_OK; i++){
  139683. char *pCsr;
  139684. rc = sqlite3Fts3EvalPhrasePoslist(p->pCursor, pExpr, i, &pCsr);
  139685. if( pCsr ){
  139686. p->aMatchinfo[iStart+i*3] = fts3ColumnlistCount(&pCsr);
  139687. }else{
  139688. p->aMatchinfo[iStart+i*3] = 0;
  139689. }
  139690. }
  139691. return rc;
  139692. }
  139693. /*
  139694. ** fts3ExprIterate() callback used to gather information for the matchinfo
  139695. ** directive 'y'.
  139696. */
  139697. static int fts3ExprLHitsCb(
  139698. Fts3Expr *pExpr, /* Phrase expression node */
  139699. int iPhrase, /* Phrase number */
  139700. void *pCtx /* Pointer to MatchInfo structure */
  139701. ){
  139702. MatchInfo *p = (MatchInfo *)pCtx;
  139703. Fts3Table *pTab = (Fts3Table *)p->pCursor->base.pVtab;
  139704. int rc = SQLITE_OK;
  139705. int iStart = iPhrase * p->nCol;
  139706. Fts3Expr *pEof; /* Ancestor node already at EOF */
  139707. /* This must be a phrase */
  139708. assert( pExpr->pPhrase );
  139709. /* Initialize all output integers to zero. */
  139710. memset(&p->aMatchinfo[iStart], 0, sizeof(u32) * p->nCol);
  139711. /* Check if this or any parent node is at EOF. If so, then all output
  139712. ** values are zero. */
  139713. for(pEof=pExpr; pEof && pEof->bEof==0; pEof=pEof->pParent);
  139714. if( pEof==0 && pExpr->iDocid==p->pCursor->iPrevId ){
  139715. Fts3Phrase *pPhrase = pExpr->pPhrase;
  139716. char *pIter = pPhrase->doclist.pList;
  139717. int iCol = 0;
  139718. while( 1 ){
  139719. int nHit = fts3ColumnlistCount(&pIter);
  139720. if( (pPhrase->iColumn>=pTab->nColumn || pPhrase->iColumn==iCol) ){
  139721. p->aMatchinfo[iStart + iCol] = (u32)nHit;
  139722. }
  139723. assert( *pIter==0x00 || *pIter==0x01 );
  139724. if( *pIter!=0x01 ) break;
  139725. pIter++;
  139726. pIter += fts3GetVarint32(pIter, &iCol);
  139727. }
  139728. }
  139729. return rc;
  139730. }
  139731. static int fts3MatchinfoCheck(
  139732. Fts3Table *pTab,
  139733. char cArg,
  139734. char **pzErr
  139735. ){
  139736. if( (cArg==FTS3_MATCHINFO_NPHRASE)
  139737. || (cArg==FTS3_MATCHINFO_NCOL)
  139738. || (cArg==FTS3_MATCHINFO_NDOC && pTab->bFts4)
  139739. || (cArg==FTS3_MATCHINFO_AVGLENGTH && pTab->bFts4)
  139740. || (cArg==FTS3_MATCHINFO_LENGTH && pTab->bHasDocsize)
  139741. || (cArg==FTS3_MATCHINFO_LCS)
  139742. || (cArg==FTS3_MATCHINFO_HITS)
  139743. || (cArg==FTS3_MATCHINFO_LHITS)
  139744. ){
  139745. return SQLITE_OK;
  139746. }
  139747. sqlite3Fts3ErrMsg(pzErr, "unrecognized matchinfo request: %c", cArg);
  139748. return SQLITE_ERROR;
  139749. }
  139750. static int fts3MatchinfoSize(MatchInfo *pInfo, char cArg){
  139751. int nVal; /* Number of integers output by cArg */
  139752. switch( cArg ){
  139753. case FTS3_MATCHINFO_NDOC:
  139754. case FTS3_MATCHINFO_NPHRASE:
  139755. case FTS3_MATCHINFO_NCOL:
  139756. nVal = 1;
  139757. break;
  139758. case FTS3_MATCHINFO_AVGLENGTH:
  139759. case FTS3_MATCHINFO_LENGTH:
  139760. case FTS3_MATCHINFO_LCS:
  139761. nVal = pInfo->nCol;
  139762. break;
  139763. case FTS3_MATCHINFO_LHITS:
  139764. nVal = pInfo->nCol * pInfo->nPhrase;
  139765. break;
  139766. default:
  139767. assert( cArg==FTS3_MATCHINFO_HITS );
  139768. nVal = pInfo->nCol * pInfo->nPhrase * 3;
  139769. break;
  139770. }
  139771. return nVal;
  139772. }
  139773. static int fts3MatchinfoSelectDoctotal(
  139774. Fts3Table *pTab,
  139775. sqlite3_stmt **ppStmt,
  139776. sqlite3_int64 *pnDoc,
  139777. const char **paLen
  139778. ){
  139779. sqlite3_stmt *pStmt;
  139780. const char *a;
  139781. sqlite3_int64 nDoc;
  139782. if( !*ppStmt ){
  139783. int rc = sqlite3Fts3SelectDoctotal(pTab, ppStmt);
  139784. if( rc!=SQLITE_OK ) return rc;
  139785. }
  139786. pStmt = *ppStmt;
  139787. assert( sqlite3_data_count(pStmt)==1 );
  139788. a = sqlite3_column_blob(pStmt, 0);
  139789. a += sqlite3Fts3GetVarint(a, &nDoc);
  139790. if( nDoc==0 ) return FTS_CORRUPT_VTAB;
  139791. *pnDoc = (u32)nDoc;
  139792. if( paLen ) *paLen = a;
  139793. return SQLITE_OK;
  139794. }
  139795. /*
  139796. ** An instance of the following structure is used to store state while
  139797. ** iterating through a multi-column position-list corresponding to the
  139798. ** hits for a single phrase on a single row in order to calculate the
  139799. ** values for a matchinfo() FTS3_MATCHINFO_LCS request.
  139800. */
  139801. typedef struct LcsIterator LcsIterator;
  139802. struct LcsIterator {
  139803. Fts3Expr *pExpr; /* Pointer to phrase expression */
  139804. int iPosOffset; /* Tokens count up to end of this phrase */
  139805. char *pRead; /* Cursor used to iterate through aDoclist */
  139806. int iPos; /* Current position */
  139807. };
  139808. /*
  139809. ** If LcsIterator.iCol is set to the following value, the iterator has
  139810. ** finished iterating through all offsets for all columns.
  139811. */
  139812. #define LCS_ITERATOR_FINISHED 0x7FFFFFFF;
  139813. static int fts3MatchinfoLcsCb(
  139814. Fts3Expr *pExpr, /* Phrase expression node */
  139815. int iPhrase, /* Phrase number (numbered from zero) */
  139816. void *pCtx /* Pointer to MatchInfo structure */
  139817. ){
  139818. LcsIterator *aIter = (LcsIterator *)pCtx;
  139819. aIter[iPhrase].pExpr = pExpr;
  139820. return SQLITE_OK;
  139821. }
  139822. /*
  139823. ** Advance the iterator passed as an argument to the next position. Return
  139824. ** 1 if the iterator is at EOF or if it now points to the start of the
  139825. ** position list for the next column.
  139826. */
  139827. static int fts3LcsIteratorAdvance(LcsIterator *pIter){
  139828. char *pRead = pIter->pRead;
  139829. sqlite3_int64 iRead;
  139830. int rc = 0;
  139831. pRead += sqlite3Fts3GetVarint(pRead, &iRead);
  139832. if( iRead==0 || iRead==1 ){
  139833. pRead = 0;
  139834. rc = 1;
  139835. }else{
  139836. pIter->iPos += (int)(iRead-2);
  139837. }
  139838. pIter->pRead = pRead;
  139839. return rc;
  139840. }
  139841. /*
  139842. ** This function implements the FTS3_MATCHINFO_LCS matchinfo() flag.
  139843. **
  139844. ** If the call is successful, the longest-common-substring lengths for each
  139845. ** column are written into the first nCol elements of the pInfo->aMatchinfo[]
  139846. ** array before returning. SQLITE_OK is returned in this case.
  139847. **
  139848. ** Otherwise, if an error occurs, an SQLite error code is returned and the
  139849. ** data written to the first nCol elements of pInfo->aMatchinfo[] is
  139850. ** undefined.
  139851. */
  139852. static int fts3MatchinfoLcs(Fts3Cursor *pCsr, MatchInfo *pInfo){
  139853. LcsIterator *aIter;
  139854. int i;
  139855. int iCol;
  139856. int nToken = 0;
  139857. /* Allocate and populate the array of LcsIterator objects. The array
  139858. ** contains one element for each matchable phrase in the query.
  139859. **/
  139860. aIter = sqlite3_malloc(sizeof(LcsIterator) * pCsr->nPhrase);
  139861. if( !aIter ) return SQLITE_NOMEM;
  139862. memset(aIter, 0, sizeof(LcsIterator) * pCsr->nPhrase);
  139863. (void)fts3ExprIterate(pCsr->pExpr, fts3MatchinfoLcsCb, (void*)aIter);
  139864. for(i=0; i<pInfo->nPhrase; i++){
  139865. LcsIterator *pIter = &aIter[i];
  139866. nToken -= pIter->pExpr->pPhrase->nToken;
  139867. pIter->iPosOffset = nToken;
  139868. }
  139869. for(iCol=0; iCol<pInfo->nCol; iCol++){
  139870. int nLcs = 0; /* LCS value for this column */
  139871. int nLive = 0; /* Number of iterators in aIter not at EOF */
  139872. for(i=0; i<pInfo->nPhrase; i++){
  139873. int rc;
  139874. LcsIterator *pIt = &aIter[i];
  139875. rc = sqlite3Fts3EvalPhrasePoslist(pCsr, pIt->pExpr, iCol, &pIt->pRead);
  139876. if( rc!=SQLITE_OK ) return rc;
  139877. if( pIt->pRead ){
  139878. pIt->iPos = pIt->iPosOffset;
  139879. fts3LcsIteratorAdvance(&aIter[i]);
  139880. nLive++;
  139881. }
  139882. }
  139883. while( nLive>0 ){
  139884. LcsIterator *pAdv = 0; /* The iterator to advance by one position */
  139885. int nThisLcs = 0; /* LCS for the current iterator positions */
  139886. for(i=0; i<pInfo->nPhrase; i++){
  139887. LcsIterator *pIter = &aIter[i];
  139888. if( pIter->pRead==0 ){
  139889. /* This iterator is already at EOF for this column. */
  139890. nThisLcs = 0;
  139891. }else{
  139892. if( pAdv==0 || pIter->iPos<pAdv->iPos ){
  139893. pAdv = pIter;
  139894. }
  139895. if( nThisLcs==0 || pIter->iPos==pIter[-1].iPos ){
  139896. nThisLcs++;
  139897. }else{
  139898. nThisLcs = 1;
  139899. }
  139900. if( nThisLcs>nLcs ) nLcs = nThisLcs;
  139901. }
  139902. }
  139903. if( fts3LcsIteratorAdvance(pAdv) ) nLive--;
  139904. }
  139905. pInfo->aMatchinfo[iCol] = nLcs;
  139906. }
  139907. sqlite3_free(aIter);
  139908. return SQLITE_OK;
  139909. }
  139910. /*
  139911. ** Populate the buffer pInfo->aMatchinfo[] with an array of integers to
  139912. ** be returned by the matchinfo() function. Argument zArg contains the
  139913. ** format string passed as the second argument to matchinfo (or the
  139914. ** default value "pcx" if no second argument was specified). The format
  139915. ** string has already been validated and the pInfo->aMatchinfo[] array
  139916. ** is guaranteed to be large enough for the output.
  139917. **
  139918. ** If bGlobal is true, then populate all fields of the matchinfo() output.
  139919. ** If it is false, then assume that those fields that do not change between
  139920. ** rows (i.e. FTS3_MATCHINFO_NPHRASE, NCOL, NDOC, AVGLENGTH and part of HITS)
  139921. ** have already been populated.
  139922. **
  139923. ** Return SQLITE_OK if successful, or an SQLite error code if an error
  139924. ** occurs. If a value other than SQLITE_OK is returned, the state the
  139925. ** pInfo->aMatchinfo[] buffer is left in is undefined.
  139926. */
  139927. static int fts3MatchinfoValues(
  139928. Fts3Cursor *pCsr, /* FTS3 cursor object */
  139929. int bGlobal, /* True to grab the global stats */
  139930. MatchInfo *pInfo, /* Matchinfo context object */
  139931. const char *zArg /* Matchinfo format string */
  139932. ){
  139933. int rc = SQLITE_OK;
  139934. int i;
  139935. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  139936. sqlite3_stmt *pSelect = 0;
  139937. for(i=0; rc==SQLITE_OK && zArg[i]; i++){
  139938. switch( zArg[i] ){
  139939. case FTS3_MATCHINFO_NPHRASE:
  139940. if( bGlobal ) pInfo->aMatchinfo[0] = pInfo->nPhrase;
  139941. break;
  139942. case FTS3_MATCHINFO_NCOL:
  139943. if( bGlobal ) pInfo->aMatchinfo[0] = pInfo->nCol;
  139944. break;
  139945. case FTS3_MATCHINFO_NDOC:
  139946. if( bGlobal ){
  139947. sqlite3_int64 nDoc = 0;
  139948. rc = fts3MatchinfoSelectDoctotal(pTab, &pSelect, &nDoc, 0);
  139949. pInfo->aMatchinfo[0] = (u32)nDoc;
  139950. }
  139951. break;
  139952. case FTS3_MATCHINFO_AVGLENGTH:
  139953. if( bGlobal ){
  139954. sqlite3_int64 nDoc; /* Number of rows in table */
  139955. const char *a; /* Aggregate column length array */
  139956. rc = fts3MatchinfoSelectDoctotal(pTab, &pSelect, &nDoc, &a);
  139957. if( rc==SQLITE_OK ){
  139958. int iCol;
  139959. for(iCol=0; iCol<pInfo->nCol; iCol++){
  139960. u32 iVal;
  139961. sqlite3_int64 nToken;
  139962. a += sqlite3Fts3GetVarint(a, &nToken);
  139963. iVal = (u32)(((u32)(nToken&0xffffffff)+nDoc/2)/nDoc);
  139964. pInfo->aMatchinfo[iCol] = iVal;
  139965. }
  139966. }
  139967. }
  139968. break;
  139969. case FTS3_MATCHINFO_LENGTH: {
  139970. sqlite3_stmt *pSelectDocsize = 0;
  139971. rc = sqlite3Fts3SelectDocsize(pTab, pCsr->iPrevId, &pSelectDocsize);
  139972. if( rc==SQLITE_OK ){
  139973. int iCol;
  139974. const char *a = sqlite3_column_blob(pSelectDocsize, 0);
  139975. for(iCol=0; iCol<pInfo->nCol; iCol++){
  139976. sqlite3_int64 nToken;
  139977. a += sqlite3Fts3GetVarint(a, &nToken);
  139978. pInfo->aMatchinfo[iCol] = (u32)nToken;
  139979. }
  139980. }
  139981. sqlite3_reset(pSelectDocsize);
  139982. break;
  139983. }
  139984. case FTS3_MATCHINFO_LCS:
  139985. rc = fts3ExprLoadDoclists(pCsr, 0, 0);
  139986. if( rc==SQLITE_OK ){
  139987. rc = fts3MatchinfoLcs(pCsr, pInfo);
  139988. }
  139989. break;
  139990. case FTS3_MATCHINFO_LHITS:
  139991. (void)fts3ExprIterate(pCsr->pExpr, fts3ExprLHitsCb, (void*)pInfo);
  139992. break;
  139993. default: {
  139994. Fts3Expr *pExpr;
  139995. assert( zArg[i]==FTS3_MATCHINFO_HITS );
  139996. pExpr = pCsr->pExpr;
  139997. rc = fts3ExprLoadDoclists(pCsr, 0, 0);
  139998. if( rc!=SQLITE_OK ) break;
  139999. if( bGlobal ){
  140000. if( pCsr->pDeferred ){
  140001. rc = fts3MatchinfoSelectDoctotal(pTab, &pSelect, &pInfo->nDoc, 0);
  140002. if( rc!=SQLITE_OK ) break;
  140003. }
  140004. rc = fts3ExprIterate(pExpr, fts3ExprGlobalHitsCb,(void*)pInfo);
  140005. if( rc!=SQLITE_OK ) break;
  140006. }
  140007. (void)fts3ExprIterate(pExpr, fts3ExprLocalHitsCb,(void*)pInfo);
  140008. break;
  140009. }
  140010. }
  140011. pInfo->aMatchinfo += fts3MatchinfoSize(pInfo, zArg[i]);
  140012. }
  140013. sqlite3_reset(pSelect);
  140014. return rc;
  140015. }
  140016. /*
  140017. ** Populate pCsr->aMatchinfo[] with data for the current row. The
  140018. ** 'matchinfo' data is an array of 32-bit unsigned integers (C type u32).
  140019. */
  140020. static int fts3GetMatchinfo(
  140021. Fts3Cursor *pCsr, /* FTS3 Cursor object */
  140022. const char *zArg /* Second argument to matchinfo() function */
  140023. ){
  140024. MatchInfo sInfo;
  140025. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  140026. int rc = SQLITE_OK;
  140027. int bGlobal = 0; /* Collect 'global' stats as well as local */
  140028. memset(&sInfo, 0, sizeof(MatchInfo));
  140029. sInfo.pCursor = pCsr;
  140030. sInfo.nCol = pTab->nColumn;
  140031. /* If there is cached matchinfo() data, but the format string for the
  140032. ** cache does not match the format string for this request, discard
  140033. ** the cached data. */
  140034. if( pCsr->zMatchinfo && strcmp(pCsr->zMatchinfo, zArg) ){
  140035. assert( pCsr->aMatchinfo );
  140036. sqlite3_free(pCsr->aMatchinfo);
  140037. pCsr->zMatchinfo = 0;
  140038. pCsr->aMatchinfo = 0;
  140039. }
  140040. /* If Fts3Cursor.aMatchinfo[] is NULL, then this is the first time the
  140041. ** matchinfo function has been called for this query. In this case
  140042. ** allocate the array used to accumulate the matchinfo data and
  140043. ** initialize those elements that are constant for every row.
  140044. */
  140045. if( pCsr->aMatchinfo==0 ){
  140046. int nMatchinfo = 0; /* Number of u32 elements in match-info */
  140047. int nArg; /* Bytes in zArg */
  140048. int i; /* Used to iterate through zArg */
  140049. /* Determine the number of phrases in the query */
  140050. pCsr->nPhrase = fts3ExprPhraseCount(pCsr->pExpr);
  140051. sInfo.nPhrase = pCsr->nPhrase;
  140052. /* Determine the number of integers in the buffer returned by this call. */
  140053. for(i=0; zArg[i]; i++){
  140054. nMatchinfo += fts3MatchinfoSize(&sInfo, zArg[i]);
  140055. }
  140056. /* Allocate space for Fts3Cursor.aMatchinfo[] and Fts3Cursor.zMatchinfo. */
  140057. nArg = (int)strlen(zArg);
  140058. pCsr->aMatchinfo = (u32 *)sqlite3_malloc(sizeof(u32)*nMatchinfo + nArg + 1);
  140059. if( !pCsr->aMatchinfo ) return SQLITE_NOMEM;
  140060. pCsr->zMatchinfo = (char *)&pCsr->aMatchinfo[nMatchinfo];
  140061. pCsr->nMatchinfo = nMatchinfo;
  140062. memcpy(pCsr->zMatchinfo, zArg, nArg+1);
  140063. memset(pCsr->aMatchinfo, 0, sizeof(u32)*nMatchinfo);
  140064. pCsr->isMatchinfoNeeded = 1;
  140065. bGlobal = 1;
  140066. }
  140067. sInfo.aMatchinfo = pCsr->aMatchinfo;
  140068. sInfo.nPhrase = pCsr->nPhrase;
  140069. if( pCsr->isMatchinfoNeeded ){
  140070. rc = fts3MatchinfoValues(pCsr, bGlobal, &sInfo, zArg);
  140071. pCsr->isMatchinfoNeeded = 0;
  140072. }
  140073. return rc;
  140074. }
  140075. /*
  140076. ** Implementation of snippet() function.
  140077. */
  140078. SQLITE_PRIVATE void sqlite3Fts3Snippet(
  140079. sqlite3_context *pCtx, /* SQLite function call context */
  140080. Fts3Cursor *pCsr, /* Cursor object */
  140081. const char *zStart, /* Snippet start text - "<b>" */
  140082. const char *zEnd, /* Snippet end text - "</b>" */
  140083. const char *zEllipsis, /* Snippet ellipsis text - "<b>...</b>" */
  140084. int iCol, /* Extract snippet from this column */
  140085. int nToken /* Approximate number of tokens in snippet */
  140086. ){
  140087. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  140088. int rc = SQLITE_OK;
  140089. int i;
  140090. StrBuffer res = {0, 0, 0};
  140091. /* The returned text includes up to four fragments of text extracted from
  140092. ** the data in the current row. The first iteration of the for(...) loop
  140093. ** below attempts to locate a single fragment of text nToken tokens in
  140094. ** size that contains at least one instance of all phrases in the query
  140095. ** expression that appear in the current row. If such a fragment of text
  140096. ** cannot be found, the second iteration of the loop attempts to locate
  140097. ** a pair of fragments, and so on.
  140098. */
  140099. int nSnippet = 0; /* Number of fragments in this snippet */
  140100. SnippetFragment aSnippet[4]; /* Maximum of 4 fragments per snippet */
  140101. int nFToken = -1; /* Number of tokens in each fragment */
  140102. if( !pCsr->pExpr ){
  140103. sqlite3_result_text(pCtx, "", 0, SQLITE_STATIC);
  140104. return;
  140105. }
  140106. for(nSnippet=1; 1; nSnippet++){
  140107. int iSnip; /* Loop counter 0..nSnippet-1 */
  140108. u64 mCovered = 0; /* Bitmask of phrases covered by snippet */
  140109. u64 mSeen = 0; /* Bitmask of phrases seen by BestSnippet() */
  140110. if( nToken>=0 ){
  140111. nFToken = (nToken+nSnippet-1) / nSnippet;
  140112. }else{
  140113. nFToken = -1 * nToken;
  140114. }
  140115. for(iSnip=0; iSnip<nSnippet; iSnip++){
  140116. int iBestScore = -1; /* Best score of columns checked so far */
  140117. int iRead; /* Used to iterate through columns */
  140118. SnippetFragment *pFragment = &aSnippet[iSnip];
  140119. memset(pFragment, 0, sizeof(*pFragment));
  140120. /* Loop through all columns of the table being considered for snippets.
  140121. ** If the iCol argument to this function was negative, this means all
  140122. ** columns of the FTS3 table. Otherwise, only column iCol is considered.
  140123. */
  140124. for(iRead=0; iRead<pTab->nColumn; iRead++){
  140125. SnippetFragment sF = {0, 0, 0, 0};
  140126. int iS = 0;
  140127. if( iCol>=0 && iRead!=iCol ) continue;
  140128. /* Find the best snippet of nFToken tokens in column iRead. */
  140129. rc = fts3BestSnippet(nFToken, pCsr, iRead, mCovered, &mSeen, &sF, &iS);
  140130. if( rc!=SQLITE_OK ){
  140131. goto snippet_out;
  140132. }
  140133. if( iS>iBestScore ){
  140134. *pFragment = sF;
  140135. iBestScore = iS;
  140136. }
  140137. }
  140138. mCovered |= pFragment->covered;
  140139. }
  140140. /* If all query phrases seen by fts3BestSnippet() are present in at least
  140141. ** one of the nSnippet snippet fragments, break out of the loop.
  140142. */
  140143. assert( (mCovered&mSeen)==mCovered );
  140144. if( mSeen==mCovered || nSnippet==SizeofArray(aSnippet) ) break;
  140145. }
  140146. assert( nFToken>0 );
  140147. for(i=0; i<nSnippet && rc==SQLITE_OK; i++){
  140148. rc = fts3SnippetText(pCsr, &aSnippet[i],
  140149. i, (i==nSnippet-1), nFToken, zStart, zEnd, zEllipsis, &res
  140150. );
  140151. }
  140152. snippet_out:
  140153. sqlite3Fts3SegmentsClose(pTab);
  140154. if( rc!=SQLITE_OK ){
  140155. sqlite3_result_error_code(pCtx, rc);
  140156. sqlite3_free(res.z);
  140157. }else{
  140158. sqlite3_result_text(pCtx, res.z, -1, sqlite3_free);
  140159. }
  140160. }
  140161. typedef struct TermOffset TermOffset;
  140162. typedef struct TermOffsetCtx TermOffsetCtx;
  140163. struct TermOffset {
  140164. char *pList; /* Position-list */
  140165. int iPos; /* Position just read from pList */
  140166. int iOff; /* Offset of this term from read positions */
  140167. };
  140168. struct TermOffsetCtx {
  140169. Fts3Cursor *pCsr;
  140170. int iCol; /* Column of table to populate aTerm for */
  140171. int iTerm;
  140172. sqlite3_int64 iDocid;
  140173. TermOffset *aTerm;
  140174. };
  140175. /*
  140176. ** This function is an fts3ExprIterate() callback used by sqlite3Fts3Offsets().
  140177. */
  140178. static int fts3ExprTermOffsetInit(Fts3Expr *pExpr, int iPhrase, void *ctx){
  140179. TermOffsetCtx *p = (TermOffsetCtx *)ctx;
  140180. int nTerm; /* Number of tokens in phrase */
  140181. int iTerm; /* For looping through nTerm phrase terms */
  140182. char *pList; /* Pointer to position list for phrase */
  140183. int iPos = 0; /* First position in position-list */
  140184. int rc;
  140185. UNUSED_PARAMETER(iPhrase);
  140186. rc = sqlite3Fts3EvalPhrasePoslist(p->pCsr, pExpr, p->iCol, &pList);
  140187. nTerm = pExpr->pPhrase->nToken;
  140188. if( pList ){
  140189. fts3GetDeltaPosition(&pList, &iPos);
  140190. assert( iPos>=0 );
  140191. }
  140192. for(iTerm=0; iTerm<nTerm; iTerm++){
  140193. TermOffset *pT = &p->aTerm[p->iTerm++];
  140194. pT->iOff = nTerm-iTerm-1;
  140195. pT->pList = pList;
  140196. pT->iPos = iPos;
  140197. }
  140198. return rc;
  140199. }
  140200. /*
  140201. ** Implementation of offsets() function.
  140202. */
  140203. SQLITE_PRIVATE void sqlite3Fts3Offsets(
  140204. sqlite3_context *pCtx, /* SQLite function call context */
  140205. Fts3Cursor *pCsr /* Cursor object */
  140206. ){
  140207. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  140208. sqlite3_tokenizer_module const *pMod = pTab->pTokenizer->pModule;
  140209. int rc; /* Return Code */
  140210. int nToken; /* Number of tokens in query */
  140211. int iCol; /* Column currently being processed */
  140212. StrBuffer res = {0, 0, 0}; /* Result string */
  140213. TermOffsetCtx sCtx; /* Context for fts3ExprTermOffsetInit() */
  140214. if( !pCsr->pExpr ){
  140215. sqlite3_result_text(pCtx, "", 0, SQLITE_STATIC);
  140216. return;
  140217. }
  140218. memset(&sCtx, 0, sizeof(sCtx));
  140219. assert( pCsr->isRequireSeek==0 );
  140220. /* Count the number of terms in the query */
  140221. rc = fts3ExprLoadDoclists(pCsr, 0, &nToken);
  140222. if( rc!=SQLITE_OK ) goto offsets_out;
  140223. /* Allocate the array of TermOffset iterators. */
  140224. sCtx.aTerm = (TermOffset *)sqlite3_malloc(sizeof(TermOffset)*nToken);
  140225. if( 0==sCtx.aTerm ){
  140226. rc = SQLITE_NOMEM;
  140227. goto offsets_out;
  140228. }
  140229. sCtx.iDocid = pCsr->iPrevId;
  140230. sCtx.pCsr = pCsr;
  140231. /* Loop through the table columns, appending offset information to
  140232. ** string-buffer res for each column.
  140233. */
  140234. for(iCol=0; iCol<pTab->nColumn; iCol++){
  140235. sqlite3_tokenizer_cursor *pC; /* Tokenizer cursor */
  140236. const char *ZDUMMY; /* Dummy argument used with xNext() */
  140237. int NDUMMY = 0; /* Dummy argument used with xNext() */
  140238. int iStart = 0;
  140239. int iEnd = 0;
  140240. int iCurrent = 0;
  140241. const char *zDoc;
  140242. int nDoc;
  140243. /* Initialize the contents of sCtx.aTerm[] for column iCol. There is
  140244. ** no way that this operation can fail, so the return code from
  140245. ** fts3ExprIterate() can be discarded.
  140246. */
  140247. sCtx.iCol = iCol;
  140248. sCtx.iTerm = 0;
  140249. (void)fts3ExprIterate(pCsr->pExpr, fts3ExprTermOffsetInit, (void *)&sCtx);
  140250. /* Retreive the text stored in column iCol. If an SQL NULL is stored
  140251. ** in column iCol, jump immediately to the next iteration of the loop.
  140252. ** If an OOM occurs while retrieving the data (this can happen if SQLite
  140253. ** needs to transform the data from utf-16 to utf-8), return SQLITE_NOMEM
  140254. ** to the caller.
  140255. */
  140256. zDoc = (const char *)sqlite3_column_text(pCsr->pStmt, iCol+1);
  140257. nDoc = sqlite3_column_bytes(pCsr->pStmt, iCol+1);
  140258. if( zDoc==0 ){
  140259. if( sqlite3_column_type(pCsr->pStmt, iCol+1)==SQLITE_NULL ){
  140260. continue;
  140261. }
  140262. rc = SQLITE_NOMEM;
  140263. goto offsets_out;
  140264. }
  140265. /* Initialize a tokenizer iterator to iterate through column iCol. */
  140266. rc = sqlite3Fts3OpenTokenizer(pTab->pTokenizer, pCsr->iLangid,
  140267. zDoc, nDoc, &pC
  140268. );
  140269. if( rc!=SQLITE_OK ) goto offsets_out;
  140270. rc = pMod->xNext(pC, &ZDUMMY, &NDUMMY, &iStart, &iEnd, &iCurrent);
  140271. while( rc==SQLITE_OK ){
  140272. int i; /* Used to loop through terms */
  140273. int iMinPos = 0x7FFFFFFF; /* Position of next token */
  140274. TermOffset *pTerm = 0; /* TermOffset associated with next token */
  140275. for(i=0; i<nToken; i++){
  140276. TermOffset *pT = &sCtx.aTerm[i];
  140277. if( pT->pList && (pT->iPos-pT->iOff)<iMinPos ){
  140278. iMinPos = pT->iPos-pT->iOff;
  140279. pTerm = pT;
  140280. }
  140281. }
  140282. if( !pTerm ){
  140283. /* All offsets for this column have been gathered. */
  140284. rc = SQLITE_DONE;
  140285. }else{
  140286. assert( iCurrent<=iMinPos );
  140287. if( 0==(0xFE&*pTerm->pList) ){
  140288. pTerm->pList = 0;
  140289. }else{
  140290. fts3GetDeltaPosition(&pTerm->pList, &pTerm->iPos);
  140291. }
  140292. while( rc==SQLITE_OK && iCurrent<iMinPos ){
  140293. rc = pMod->xNext(pC, &ZDUMMY, &NDUMMY, &iStart, &iEnd, &iCurrent);
  140294. }
  140295. if( rc==SQLITE_OK ){
  140296. char aBuffer[64];
  140297. sqlite3_snprintf(sizeof(aBuffer), aBuffer,
  140298. "%d %d %d %d ", iCol, pTerm-sCtx.aTerm, iStart, iEnd-iStart
  140299. );
  140300. rc = fts3StringAppend(&res, aBuffer, -1);
  140301. }else if( rc==SQLITE_DONE && pTab->zContentTbl==0 ){
  140302. rc = FTS_CORRUPT_VTAB;
  140303. }
  140304. }
  140305. }
  140306. if( rc==SQLITE_DONE ){
  140307. rc = SQLITE_OK;
  140308. }
  140309. pMod->xClose(pC);
  140310. if( rc!=SQLITE_OK ) goto offsets_out;
  140311. }
  140312. offsets_out:
  140313. sqlite3_free(sCtx.aTerm);
  140314. assert( rc!=SQLITE_DONE );
  140315. sqlite3Fts3SegmentsClose(pTab);
  140316. if( rc!=SQLITE_OK ){
  140317. sqlite3_result_error_code(pCtx, rc);
  140318. sqlite3_free(res.z);
  140319. }else{
  140320. sqlite3_result_text(pCtx, res.z, res.n-1, sqlite3_free);
  140321. }
  140322. return;
  140323. }
  140324. /*
  140325. ** Implementation of matchinfo() function.
  140326. */
  140327. SQLITE_PRIVATE void sqlite3Fts3Matchinfo(
  140328. sqlite3_context *pContext, /* Function call context */
  140329. Fts3Cursor *pCsr, /* FTS3 table cursor */
  140330. const char *zArg /* Second arg to matchinfo() function */
  140331. ){
  140332. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  140333. int rc;
  140334. int i;
  140335. const char *zFormat;
  140336. if( zArg ){
  140337. for(i=0; zArg[i]; i++){
  140338. char *zErr = 0;
  140339. if( fts3MatchinfoCheck(pTab, zArg[i], &zErr) ){
  140340. sqlite3_result_error(pContext, zErr, -1);
  140341. sqlite3_free(zErr);
  140342. return;
  140343. }
  140344. }
  140345. zFormat = zArg;
  140346. }else{
  140347. zFormat = FTS3_MATCHINFO_DEFAULT;
  140348. }
  140349. if( !pCsr->pExpr ){
  140350. sqlite3_result_blob(pContext, "", 0, SQLITE_STATIC);
  140351. return;
  140352. }
  140353. /* Retrieve matchinfo() data. */
  140354. rc = fts3GetMatchinfo(pCsr, zFormat);
  140355. sqlite3Fts3SegmentsClose(pTab);
  140356. if( rc!=SQLITE_OK ){
  140357. sqlite3_result_error_code(pContext, rc);
  140358. }else{
  140359. int n = pCsr->nMatchinfo * sizeof(u32);
  140360. sqlite3_result_blob(pContext, pCsr->aMatchinfo, n, SQLITE_TRANSIENT);
  140361. }
  140362. }
  140363. #endif
  140364. /************** End of fts3_snippet.c ****************************************/
  140365. /************** Begin file fts3_unicode.c ************************************/
  140366. /*
  140367. ** 2012 May 24
  140368. **
  140369. ** The author disclaims copyright to this source code. In place of
  140370. ** a legal notice, here is a blessing:
  140371. **
  140372. ** May you do good and not evil.
  140373. ** May you find forgiveness for yourself and forgive others.
  140374. ** May you share freely, never taking more than you give.
  140375. **
  140376. ******************************************************************************
  140377. **
  140378. ** Implementation of the "unicode" full-text-search tokenizer.
  140379. */
  140380. #ifndef SQLITE_DISABLE_FTS3_UNICODE
  140381. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  140382. /* #include <assert.h> */
  140383. /* #include <stdlib.h> */
  140384. /* #include <stdio.h> */
  140385. /* #include <string.h> */
  140386. /*
  140387. ** The following two macros - READ_UTF8 and WRITE_UTF8 - have been copied
  140388. ** from the sqlite3 source file utf.c. If this file is compiled as part
  140389. ** of the amalgamation, they are not required.
  140390. */
  140391. #ifndef SQLITE_AMALGAMATION
  140392. static const unsigned char sqlite3Utf8Trans1[] = {
  140393. 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
  140394. 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
  140395. 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
  140396. 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
  140397. 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
  140398. 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
  140399. 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
  140400. 0x00, 0x01, 0x02, 0x03, 0x00, 0x01, 0x00, 0x00,
  140401. };
  140402. #define READ_UTF8(zIn, zTerm, c) \
  140403. c = *(zIn++); \
  140404. if( c>=0xc0 ){ \
  140405. c = sqlite3Utf8Trans1[c-0xc0]; \
  140406. while( zIn!=zTerm && (*zIn & 0xc0)==0x80 ){ \
  140407. c = (c<<6) + (0x3f & *(zIn++)); \
  140408. } \
  140409. if( c<0x80 \
  140410. || (c&0xFFFFF800)==0xD800 \
  140411. || (c&0xFFFFFFFE)==0xFFFE ){ c = 0xFFFD; } \
  140412. }
  140413. #define WRITE_UTF8(zOut, c) { \
  140414. if( c<0x00080 ){ \
  140415. *zOut++ = (u8)(c&0xFF); \
  140416. } \
  140417. else if( c<0x00800 ){ \
  140418. *zOut++ = 0xC0 + (u8)((c>>6)&0x1F); \
  140419. *zOut++ = 0x80 + (u8)(c & 0x3F); \
  140420. } \
  140421. else if( c<0x10000 ){ \
  140422. *zOut++ = 0xE0 + (u8)((c>>12)&0x0F); \
  140423. *zOut++ = 0x80 + (u8)((c>>6) & 0x3F); \
  140424. *zOut++ = 0x80 + (u8)(c & 0x3F); \
  140425. }else{ \
  140426. *zOut++ = 0xF0 + (u8)((c>>18) & 0x07); \
  140427. *zOut++ = 0x80 + (u8)((c>>12) & 0x3F); \
  140428. *zOut++ = 0x80 + (u8)((c>>6) & 0x3F); \
  140429. *zOut++ = 0x80 + (u8)(c & 0x3F); \
  140430. } \
  140431. }
  140432. #endif /* ifndef SQLITE_AMALGAMATION */
  140433. typedef struct unicode_tokenizer unicode_tokenizer;
  140434. typedef struct unicode_cursor unicode_cursor;
  140435. struct unicode_tokenizer {
  140436. sqlite3_tokenizer base;
  140437. int bRemoveDiacritic;
  140438. int nException;
  140439. int *aiException;
  140440. };
  140441. struct unicode_cursor {
  140442. sqlite3_tokenizer_cursor base;
  140443. const unsigned char *aInput; /* Input text being tokenized */
  140444. int nInput; /* Size of aInput[] in bytes */
  140445. int iOff; /* Current offset within aInput[] */
  140446. int iToken; /* Index of next token to be returned */
  140447. char *zToken; /* storage for current token */
  140448. int nAlloc; /* space allocated at zToken */
  140449. };
  140450. /*
  140451. ** Destroy a tokenizer allocated by unicodeCreate().
  140452. */
  140453. static int unicodeDestroy(sqlite3_tokenizer *pTokenizer){
  140454. if( pTokenizer ){
  140455. unicode_tokenizer *p = (unicode_tokenizer *)pTokenizer;
  140456. sqlite3_free(p->aiException);
  140457. sqlite3_free(p);
  140458. }
  140459. return SQLITE_OK;
  140460. }
  140461. /*
  140462. ** As part of a tokenchars= or separators= option, the CREATE VIRTUAL TABLE
  140463. ** statement has specified that the tokenizer for this table shall consider
  140464. ** all characters in string zIn/nIn to be separators (if bAlnum==0) or
  140465. ** token characters (if bAlnum==1).
  140466. **
  140467. ** For each codepoint in the zIn/nIn string, this function checks if the
  140468. ** sqlite3FtsUnicodeIsalnum() function already returns the desired result.
  140469. ** If so, no action is taken. Otherwise, the codepoint is added to the
  140470. ** unicode_tokenizer.aiException[] array. For the purposes of tokenization,
  140471. ** the return value of sqlite3FtsUnicodeIsalnum() is inverted for all
  140472. ** codepoints in the aiException[] array.
  140473. **
  140474. ** If a standalone diacritic mark (one that sqlite3FtsUnicodeIsdiacritic()
  140475. ** identifies as a diacritic) occurs in the zIn/nIn string it is ignored.
  140476. ** It is not possible to change the behavior of the tokenizer with respect
  140477. ** to these codepoints.
  140478. */
  140479. static int unicodeAddExceptions(
  140480. unicode_tokenizer *p, /* Tokenizer to add exceptions to */
  140481. int bAlnum, /* Replace Isalnum() return value with this */
  140482. const char *zIn, /* Array of characters to make exceptions */
  140483. int nIn /* Length of z in bytes */
  140484. ){
  140485. const unsigned char *z = (const unsigned char *)zIn;
  140486. const unsigned char *zTerm = &z[nIn];
  140487. int iCode;
  140488. int nEntry = 0;
  140489. assert( bAlnum==0 || bAlnum==1 );
  140490. while( z<zTerm ){
  140491. READ_UTF8(z, zTerm, iCode);
  140492. assert( (sqlite3FtsUnicodeIsalnum(iCode) & 0xFFFFFFFE)==0 );
  140493. if( sqlite3FtsUnicodeIsalnum(iCode)!=bAlnum
  140494. && sqlite3FtsUnicodeIsdiacritic(iCode)==0
  140495. ){
  140496. nEntry++;
  140497. }
  140498. }
  140499. if( nEntry ){
  140500. int *aNew; /* New aiException[] array */
  140501. int nNew; /* Number of valid entries in array aNew[] */
  140502. aNew = sqlite3_realloc(p->aiException, (p->nException+nEntry)*sizeof(int));
  140503. if( aNew==0 ) return SQLITE_NOMEM;
  140504. nNew = p->nException;
  140505. z = (const unsigned char *)zIn;
  140506. while( z<zTerm ){
  140507. READ_UTF8(z, zTerm, iCode);
  140508. if( sqlite3FtsUnicodeIsalnum(iCode)!=bAlnum
  140509. && sqlite3FtsUnicodeIsdiacritic(iCode)==0
  140510. ){
  140511. int i, j;
  140512. for(i=0; i<nNew && aNew[i]<iCode; i++);
  140513. for(j=nNew; j>i; j--) aNew[j] = aNew[j-1];
  140514. aNew[i] = iCode;
  140515. nNew++;
  140516. }
  140517. }
  140518. p->aiException = aNew;
  140519. p->nException = nNew;
  140520. }
  140521. return SQLITE_OK;
  140522. }
  140523. /*
  140524. ** Return true if the p->aiException[] array contains the value iCode.
  140525. */
  140526. static int unicodeIsException(unicode_tokenizer *p, int iCode){
  140527. if( p->nException>0 ){
  140528. int *a = p->aiException;
  140529. int iLo = 0;
  140530. int iHi = p->nException-1;
  140531. while( iHi>=iLo ){
  140532. int iTest = (iHi + iLo) / 2;
  140533. if( iCode==a[iTest] ){
  140534. return 1;
  140535. }else if( iCode>a[iTest] ){
  140536. iLo = iTest+1;
  140537. }else{
  140538. iHi = iTest-1;
  140539. }
  140540. }
  140541. }
  140542. return 0;
  140543. }
  140544. /*
  140545. ** Return true if, for the purposes of tokenization, codepoint iCode is
  140546. ** considered a token character (not a separator).
  140547. */
  140548. static int unicodeIsAlnum(unicode_tokenizer *p, int iCode){
  140549. assert( (sqlite3FtsUnicodeIsalnum(iCode) & 0xFFFFFFFE)==0 );
  140550. return sqlite3FtsUnicodeIsalnum(iCode) ^ unicodeIsException(p, iCode);
  140551. }
  140552. /*
  140553. ** Create a new tokenizer instance.
  140554. */
  140555. static int unicodeCreate(
  140556. int nArg, /* Size of array argv[] */
  140557. const char * const *azArg, /* Tokenizer creation arguments */
  140558. sqlite3_tokenizer **pp /* OUT: New tokenizer handle */
  140559. ){
  140560. unicode_tokenizer *pNew; /* New tokenizer object */
  140561. int i;
  140562. int rc = SQLITE_OK;
  140563. pNew = (unicode_tokenizer *) sqlite3_malloc(sizeof(unicode_tokenizer));
  140564. if( pNew==NULL ) return SQLITE_NOMEM;
  140565. memset(pNew, 0, sizeof(unicode_tokenizer));
  140566. pNew->bRemoveDiacritic = 1;
  140567. for(i=0; rc==SQLITE_OK && i<nArg; i++){
  140568. const char *z = azArg[i];
  140569. int n = (int)strlen(z);
  140570. if( n==19 && memcmp("remove_diacritics=1", z, 19)==0 ){
  140571. pNew->bRemoveDiacritic = 1;
  140572. }
  140573. else if( n==19 && memcmp("remove_diacritics=0", z, 19)==0 ){
  140574. pNew->bRemoveDiacritic = 0;
  140575. }
  140576. else if( n>=11 && memcmp("tokenchars=", z, 11)==0 ){
  140577. rc = unicodeAddExceptions(pNew, 1, &z[11], n-11);
  140578. }
  140579. else if( n>=11 && memcmp("separators=", z, 11)==0 ){
  140580. rc = unicodeAddExceptions(pNew, 0, &z[11], n-11);
  140581. }
  140582. else{
  140583. /* Unrecognized argument */
  140584. rc = SQLITE_ERROR;
  140585. }
  140586. }
  140587. if( rc!=SQLITE_OK ){
  140588. unicodeDestroy((sqlite3_tokenizer *)pNew);
  140589. pNew = 0;
  140590. }
  140591. *pp = (sqlite3_tokenizer *)pNew;
  140592. return rc;
  140593. }
  140594. /*
  140595. ** Prepare to begin tokenizing a particular string. The input
  140596. ** string to be tokenized is pInput[0..nBytes-1]. A cursor
  140597. ** used to incrementally tokenize this string is returned in
  140598. ** *ppCursor.
  140599. */
  140600. static int unicodeOpen(
  140601. sqlite3_tokenizer *p, /* The tokenizer */
  140602. const char *aInput, /* Input string */
  140603. int nInput, /* Size of string aInput in bytes */
  140604. sqlite3_tokenizer_cursor **pp /* OUT: New cursor object */
  140605. ){
  140606. unicode_cursor *pCsr;
  140607. pCsr = (unicode_cursor *)sqlite3_malloc(sizeof(unicode_cursor));
  140608. if( pCsr==0 ){
  140609. return SQLITE_NOMEM;
  140610. }
  140611. memset(pCsr, 0, sizeof(unicode_cursor));
  140612. pCsr->aInput = (const unsigned char *)aInput;
  140613. if( aInput==0 ){
  140614. pCsr->nInput = 0;
  140615. }else if( nInput<0 ){
  140616. pCsr->nInput = (int)strlen(aInput);
  140617. }else{
  140618. pCsr->nInput = nInput;
  140619. }
  140620. *pp = &pCsr->base;
  140621. UNUSED_PARAMETER(p);
  140622. return SQLITE_OK;
  140623. }
  140624. /*
  140625. ** Close a tokenization cursor previously opened by a call to
  140626. ** simpleOpen() above.
  140627. */
  140628. static int unicodeClose(sqlite3_tokenizer_cursor *pCursor){
  140629. unicode_cursor *pCsr = (unicode_cursor *) pCursor;
  140630. sqlite3_free(pCsr->zToken);
  140631. sqlite3_free(pCsr);
  140632. return SQLITE_OK;
  140633. }
  140634. /*
  140635. ** Extract the next token from a tokenization cursor. The cursor must
  140636. ** have been opened by a prior call to simpleOpen().
  140637. */
  140638. static int unicodeNext(
  140639. sqlite3_tokenizer_cursor *pC, /* Cursor returned by simpleOpen */
  140640. const char **paToken, /* OUT: Token text */
  140641. int *pnToken, /* OUT: Number of bytes at *paToken */
  140642. int *piStart, /* OUT: Starting offset of token */
  140643. int *piEnd, /* OUT: Ending offset of token */
  140644. int *piPos /* OUT: Position integer of token */
  140645. ){
  140646. unicode_cursor *pCsr = (unicode_cursor *)pC;
  140647. unicode_tokenizer *p = ((unicode_tokenizer *)pCsr->base.pTokenizer);
  140648. int iCode = 0;
  140649. char *zOut;
  140650. const unsigned char *z = &pCsr->aInput[pCsr->iOff];
  140651. const unsigned char *zStart = z;
  140652. const unsigned char *zEnd;
  140653. const unsigned char *zTerm = &pCsr->aInput[pCsr->nInput];
  140654. /* Scan past any delimiter characters before the start of the next token.
  140655. ** Return SQLITE_DONE early if this takes us all the way to the end of
  140656. ** the input. */
  140657. while( z<zTerm ){
  140658. READ_UTF8(z, zTerm, iCode);
  140659. if( unicodeIsAlnum(p, iCode) ) break;
  140660. zStart = z;
  140661. }
  140662. if( zStart>=zTerm ) return SQLITE_DONE;
  140663. zOut = pCsr->zToken;
  140664. do {
  140665. int iOut;
  140666. /* Grow the output buffer if required. */
  140667. if( (zOut-pCsr->zToken)>=(pCsr->nAlloc-4) ){
  140668. char *zNew = sqlite3_realloc(pCsr->zToken, pCsr->nAlloc+64);
  140669. if( !zNew ) return SQLITE_NOMEM;
  140670. zOut = &zNew[zOut - pCsr->zToken];
  140671. pCsr->zToken = zNew;
  140672. pCsr->nAlloc += 64;
  140673. }
  140674. /* Write the folded case of the last character read to the output */
  140675. zEnd = z;
  140676. iOut = sqlite3FtsUnicodeFold(iCode, p->bRemoveDiacritic);
  140677. if( iOut ){
  140678. WRITE_UTF8(zOut, iOut);
  140679. }
  140680. /* If the cursor is not at EOF, read the next character */
  140681. if( z>=zTerm ) break;
  140682. READ_UTF8(z, zTerm, iCode);
  140683. }while( unicodeIsAlnum(p, iCode)
  140684. || sqlite3FtsUnicodeIsdiacritic(iCode)
  140685. );
  140686. /* Set the output variables and return. */
  140687. pCsr->iOff = (int)(z - pCsr->aInput);
  140688. *paToken = pCsr->zToken;
  140689. *pnToken = (int)(zOut - pCsr->zToken);
  140690. *piStart = (int)(zStart - pCsr->aInput);
  140691. *piEnd = (int)(zEnd - pCsr->aInput);
  140692. *piPos = pCsr->iToken++;
  140693. return SQLITE_OK;
  140694. }
  140695. /*
  140696. ** Set *ppModule to a pointer to the sqlite3_tokenizer_module
  140697. ** structure for the unicode tokenizer.
  140698. */
  140699. SQLITE_PRIVATE void sqlite3Fts3UnicodeTokenizer(sqlite3_tokenizer_module const **ppModule){
  140700. static const sqlite3_tokenizer_module module = {
  140701. 0,
  140702. unicodeCreate,
  140703. unicodeDestroy,
  140704. unicodeOpen,
  140705. unicodeClose,
  140706. unicodeNext,
  140707. 0,
  140708. };
  140709. *ppModule = &module;
  140710. }
  140711. #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
  140712. #endif /* ifndef SQLITE_DISABLE_FTS3_UNICODE */
  140713. /************** End of fts3_unicode.c ****************************************/
  140714. /************** Begin file fts3_unicode2.c ***********************************/
  140715. /*
  140716. ** 2012 May 25
  140717. **
  140718. ** The author disclaims copyright to this source code. In place of
  140719. ** a legal notice, here is a blessing:
  140720. **
  140721. ** May you do good and not evil.
  140722. ** May you find forgiveness for yourself and forgive others.
  140723. ** May you share freely, never taking more than you give.
  140724. **
  140725. ******************************************************************************
  140726. */
  140727. /*
  140728. ** DO NOT EDIT THIS MACHINE GENERATED FILE.
  140729. */
  140730. #ifndef SQLITE_DISABLE_FTS3_UNICODE
  140731. #if defined(SQLITE_ENABLE_FTS3) || defined(SQLITE_ENABLE_FTS4)
  140732. /* #include <assert.h> */
  140733. /*
  140734. ** Return true if the argument corresponds to a unicode codepoint
  140735. ** classified as either a letter or a number. Otherwise false.
  140736. **
  140737. ** The results are undefined if the value passed to this function
  140738. ** is less than zero.
  140739. */
  140740. SQLITE_PRIVATE int sqlite3FtsUnicodeIsalnum(int c){
  140741. /* Each unsigned integer in the following array corresponds to a contiguous
  140742. ** range of unicode codepoints that are not either letters or numbers (i.e.
  140743. ** codepoints for which this function should return 0).
  140744. **
  140745. ** The most significant 22 bits in each 32-bit value contain the first
  140746. ** codepoint in the range. The least significant 10 bits are used to store
  140747. ** the size of the range (always at least 1). In other words, the value
  140748. ** ((C<<22) + N) represents a range of N codepoints starting with codepoint
  140749. ** C. It is not possible to represent a range larger than 1023 codepoints
  140750. ** using this format.
  140751. */
  140752. static const unsigned int aEntry[] = {
  140753. 0x00000030, 0x0000E807, 0x00016C06, 0x0001EC2F, 0x0002AC07,
  140754. 0x0002D001, 0x0002D803, 0x0002EC01, 0x0002FC01, 0x00035C01,
  140755. 0x0003DC01, 0x000B0804, 0x000B480E, 0x000B9407, 0x000BB401,
  140756. 0x000BBC81, 0x000DD401, 0x000DF801, 0x000E1002, 0x000E1C01,
  140757. 0x000FD801, 0x00120808, 0x00156806, 0x00162402, 0x00163C01,
  140758. 0x00164437, 0x0017CC02, 0x00180005, 0x00181816, 0x00187802,
  140759. 0x00192C15, 0x0019A804, 0x0019C001, 0x001B5001, 0x001B580F,
  140760. 0x001B9C07, 0x001BF402, 0x001C000E, 0x001C3C01, 0x001C4401,
  140761. 0x001CC01B, 0x001E980B, 0x001FAC09, 0x001FD804, 0x00205804,
  140762. 0x00206C09, 0x00209403, 0x0020A405, 0x0020C00F, 0x00216403,
  140763. 0x00217801, 0x0023901B, 0x00240004, 0x0024E803, 0x0024F812,
  140764. 0x00254407, 0x00258804, 0x0025C001, 0x00260403, 0x0026F001,
  140765. 0x0026F807, 0x00271C02, 0x00272C03, 0x00275C01, 0x00278802,
  140766. 0x0027C802, 0x0027E802, 0x00280403, 0x0028F001, 0x0028F805,
  140767. 0x00291C02, 0x00292C03, 0x00294401, 0x0029C002, 0x0029D401,
  140768. 0x002A0403, 0x002AF001, 0x002AF808, 0x002B1C03, 0x002B2C03,
  140769. 0x002B8802, 0x002BC002, 0x002C0403, 0x002CF001, 0x002CF807,
  140770. 0x002D1C02, 0x002D2C03, 0x002D5802, 0x002D8802, 0x002DC001,
  140771. 0x002E0801, 0x002EF805, 0x002F1803, 0x002F2804, 0x002F5C01,
  140772. 0x002FCC08, 0x00300403, 0x0030F807, 0x00311803, 0x00312804,
  140773. 0x00315402, 0x00318802, 0x0031FC01, 0x00320802, 0x0032F001,
  140774. 0x0032F807, 0x00331803, 0x00332804, 0x00335402, 0x00338802,
  140775. 0x00340802, 0x0034F807, 0x00351803, 0x00352804, 0x00355C01,
  140776. 0x00358802, 0x0035E401, 0x00360802, 0x00372801, 0x00373C06,
  140777. 0x00375801, 0x00376008, 0x0037C803, 0x0038C401, 0x0038D007,
  140778. 0x0038FC01, 0x00391C09, 0x00396802, 0x003AC401, 0x003AD006,
  140779. 0x003AEC02, 0x003B2006, 0x003C041F, 0x003CD00C, 0x003DC417,
  140780. 0x003E340B, 0x003E6424, 0x003EF80F, 0x003F380D, 0x0040AC14,
  140781. 0x00412806, 0x00415804, 0x00417803, 0x00418803, 0x00419C07,
  140782. 0x0041C404, 0x0042080C, 0x00423C01, 0x00426806, 0x0043EC01,
  140783. 0x004D740C, 0x004E400A, 0x00500001, 0x0059B402, 0x005A0001,
  140784. 0x005A6C02, 0x005BAC03, 0x005C4803, 0x005CC805, 0x005D4802,
  140785. 0x005DC802, 0x005ED023, 0x005F6004, 0x005F7401, 0x0060000F,
  140786. 0x0062A401, 0x0064800C, 0x0064C00C, 0x00650001, 0x00651002,
  140787. 0x0066C011, 0x00672002, 0x00677822, 0x00685C05, 0x00687802,
  140788. 0x0069540A, 0x0069801D, 0x0069FC01, 0x006A8007, 0x006AA006,
  140789. 0x006C0005, 0x006CD011, 0x006D6823, 0x006E0003, 0x006E840D,
  140790. 0x006F980E, 0x006FF004, 0x00709014, 0x0070EC05, 0x0071F802,
  140791. 0x00730008, 0x00734019, 0x0073B401, 0x0073C803, 0x00770027,
  140792. 0x0077F004, 0x007EF401, 0x007EFC03, 0x007F3403, 0x007F7403,
  140793. 0x007FB403, 0x007FF402, 0x00800065, 0x0081A806, 0x0081E805,
  140794. 0x00822805, 0x0082801A, 0x00834021, 0x00840002, 0x00840C04,
  140795. 0x00842002, 0x00845001, 0x00845803, 0x00847806, 0x00849401,
  140796. 0x00849C01, 0x0084A401, 0x0084B801, 0x0084E802, 0x00850005,
  140797. 0x00852804, 0x00853C01, 0x00864264, 0x00900027, 0x0091000B,
  140798. 0x0092704E, 0x00940200, 0x009C0475, 0x009E53B9, 0x00AD400A,
  140799. 0x00B39406, 0x00B3BC03, 0x00B3E404, 0x00B3F802, 0x00B5C001,
  140800. 0x00B5FC01, 0x00B7804F, 0x00B8C00C, 0x00BA001A, 0x00BA6C59,
  140801. 0x00BC00D6, 0x00BFC00C, 0x00C00005, 0x00C02019, 0x00C0A807,
  140802. 0x00C0D802, 0x00C0F403, 0x00C26404, 0x00C28001, 0x00C3EC01,
  140803. 0x00C64002, 0x00C6580A, 0x00C70024, 0x00C8001F, 0x00C8A81E,
  140804. 0x00C94001, 0x00C98020, 0x00CA2827, 0x00CB003F, 0x00CC0100,
  140805. 0x01370040, 0x02924037, 0x0293F802, 0x02983403, 0x0299BC10,
  140806. 0x029A7C01, 0x029BC008, 0x029C0017, 0x029C8002, 0x029E2402,
  140807. 0x02A00801, 0x02A01801, 0x02A02C01, 0x02A08C09, 0x02A0D804,
  140808. 0x02A1D004, 0x02A20002, 0x02A2D011, 0x02A33802, 0x02A38012,
  140809. 0x02A3E003, 0x02A4980A, 0x02A51C0D, 0x02A57C01, 0x02A60004,
  140810. 0x02A6CC1B, 0x02A77802, 0x02A8A40E, 0x02A90C01, 0x02A93002,
  140811. 0x02A97004, 0x02A9DC03, 0x02A9EC01, 0x02AAC001, 0x02AAC803,
  140812. 0x02AADC02, 0x02AAF802, 0x02AB0401, 0x02AB7802, 0x02ABAC07,
  140813. 0x02ABD402, 0x02AF8C0B, 0x03600001, 0x036DFC02, 0x036FFC02,
  140814. 0x037FFC01, 0x03EC7801, 0x03ECA401, 0x03EEC810, 0x03F4F802,
  140815. 0x03F7F002, 0x03F8001A, 0x03F88007, 0x03F8C023, 0x03F95013,
  140816. 0x03F9A004, 0x03FBFC01, 0x03FC040F, 0x03FC6807, 0x03FCEC06,
  140817. 0x03FD6C0B, 0x03FF8007, 0x03FFA007, 0x03FFE405, 0x04040003,
  140818. 0x0404DC09, 0x0405E411, 0x0406400C, 0x0407402E, 0x040E7C01,
  140819. 0x040F4001, 0x04215C01, 0x04247C01, 0x0424FC01, 0x04280403,
  140820. 0x04281402, 0x04283004, 0x0428E003, 0x0428FC01, 0x04294009,
  140821. 0x0429FC01, 0x042CE407, 0x04400003, 0x0440E016, 0x04420003,
  140822. 0x0442C012, 0x04440003, 0x04449C0E, 0x04450004, 0x04460003,
  140823. 0x0446CC0E, 0x04471404, 0x045AAC0D, 0x0491C004, 0x05BD442E,
  140824. 0x05BE3C04, 0x074000F6, 0x07440027, 0x0744A4B5, 0x07480046,
  140825. 0x074C0057, 0x075B0401, 0x075B6C01, 0x075BEC01, 0x075C5401,
  140826. 0x075CD401, 0x075D3C01, 0x075DBC01, 0x075E2401, 0x075EA401,
  140827. 0x075F0C01, 0x07BBC002, 0x07C0002C, 0x07C0C064, 0x07C2800F,
  140828. 0x07C2C40E, 0x07C3040F, 0x07C3440F, 0x07C4401F, 0x07C4C03C,
  140829. 0x07C5C02B, 0x07C7981D, 0x07C8402B, 0x07C90009, 0x07C94002,
  140830. 0x07CC0021, 0x07CCC006, 0x07CCDC46, 0x07CE0014, 0x07CE8025,
  140831. 0x07CF1805, 0x07CF8011, 0x07D0003F, 0x07D10001, 0x07D108B6,
  140832. 0x07D3E404, 0x07D4003E, 0x07D50004, 0x07D54018, 0x07D7EC46,
  140833. 0x07D9140B, 0x07DA0046, 0x07DC0074, 0x38000401, 0x38008060,
  140834. 0x380400F0,
  140835. };
  140836. static const unsigned int aAscii[4] = {
  140837. 0xFFFFFFFF, 0xFC00FFFF, 0xF8000001, 0xF8000001,
  140838. };
  140839. if( c<128 ){
  140840. return ( (aAscii[c >> 5] & (1 << (c & 0x001F)))==0 );
  140841. }else if( c<(1<<22) ){
  140842. unsigned int key = (((unsigned int)c)<<10) | 0x000003FF;
  140843. int iRes = 0;
  140844. int iHi = sizeof(aEntry)/sizeof(aEntry[0]) - 1;
  140845. int iLo = 0;
  140846. while( iHi>=iLo ){
  140847. int iTest = (iHi + iLo) / 2;
  140848. if( key >= aEntry[iTest] ){
  140849. iRes = iTest;
  140850. iLo = iTest+1;
  140851. }else{
  140852. iHi = iTest-1;
  140853. }
  140854. }
  140855. assert( aEntry[0]<key );
  140856. assert( key>=aEntry[iRes] );
  140857. return (((unsigned int)c) >= ((aEntry[iRes]>>10) + (aEntry[iRes]&0x3FF)));
  140858. }
  140859. return 1;
  140860. }
  140861. /*
  140862. ** If the argument is a codepoint corresponding to a lowercase letter
  140863. ** in the ASCII range with a diacritic added, return the codepoint
  140864. ** of the ASCII letter only. For example, if passed 235 - "LATIN
  140865. ** SMALL LETTER E WITH DIAERESIS" - return 65 ("LATIN SMALL LETTER
  140866. ** E"). The resuls of passing a codepoint that corresponds to an
  140867. ** uppercase letter are undefined.
  140868. */
  140869. static int remove_diacritic(int c){
  140870. unsigned short aDia[] = {
  140871. 0, 1797, 1848, 1859, 1891, 1928, 1940, 1995,
  140872. 2024, 2040, 2060, 2110, 2168, 2206, 2264, 2286,
  140873. 2344, 2383, 2472, 2488, 2516, 2596, 2668, 2732,
  140874. 2782, 2842, 2894, 2954, 2984, 3000, 3028, 3336,
  140875. 3456, 3696, 3712, 3728, 3744, 3896, 3912, 3928,
  140876. 3968, 4008, 4040, 4106, 4138, 4170, 4202, 4234,
  140877. 4266, 4296, 4312, 4344, 4408, 4424, 4472, 4504,
  140878. 6148, 6198, 6264, 6280, 6360, 6429, 6505, 6529,
  140879. 61448, 61468, 61534, 61592, 61642, 61688, 61704, 61726,
  140880. 61784, 61800, 61836, 61880, 61914, 61948, 61998, 62122,
  140881. 62154, 62200, 62218, 62302, 62364, 62442, 62478, 62536,
  140882. 62554, 62584, 62604, 62640, 62648, 62656, 62664, 62730,
  140883. 62924, 63050, 63082, 63274, 63390,
  140884. };
  140885. char aChar[] = {
  140886. '\0', 'a', 'c', 'e', 'i', 'n', 'o', 'u', 'y', 'y', 'a', 'c',
  140887. 'd', 'e', 'e', 'g', 'h', 'i', 'j', 'k', 'l', 'n', 'o', 'r',
  140888. 's', 't', 'u', 'u', 'w', 'y', 'z', 'o', 'u', 'a', 'i', 'o',
  140889. 'u', 'g', 'k', 'o', 'j', 'g', 'n', 'a', 'e', 'i', 'o', 'r',
  140890. 'u', 's', 't', 'h', 'a', 'e', 'o', 'y', '\0', '\0', '\0', '\0',
  140891. '\0', '\0', '\0', '\0', 'a', 'b', 'd', 'd', 'e', 'f', 'g', 'h',
  140892. 'h', 'i', 'k', 'l', 'l', 'm', 'n', 'p', 'r', 'r', 's', 't',
  140893. 'u', 'v', 'w', 'w', 'x', 'y', 'z', 'h', 't', 'w', 'y', 'a',
  140894. 'e', 'i', 'o', 'u', 'y',
  140895. };
  140896. unsigned int key = (((unsigned int)c)<<3) | 0x00000007;
  140897. int iRes = 0;
  140898. int iHi = sizeof(aDia)/sizeof(aDia[0]) - 1;
  140899. int iLo = 0;
  140900. while( iHi>=iLo ){
  140901. int iTest = (iHi + iLo) / 2;
  140902. if( key >= aDia[iTest] ){
  140903. iRes = iTest;
  140904. iLo = iTest+1;
  140905. }else{
  140906. iHi = iTest-1;
  140907. }
  140908. }
  140909. assert( key>=aDia[iRes] );
  140910. return ((c > (aDia[iRes]>>3) + (aDia[iRes]&0x07)) ? c : (int)aChar[iRes]);
  140911. }
  140912. /*
  140913. ** Return true if the argument interpreted as a unicode codepoint
  140914. ** is a diacritical modifier character.
  140915. */
  140916. SQLITE_PRIVATE int sqlite3FtsUnicodeIsdiacritic(int c){
  140917. unsigned int mask0 = 0x08029FDF;
  140918. unsigned int mask1 = 0x000361F8;
  140919. if( c<768 || c>817 ) return 0;
  140920. return (c < 768+32) ?
  140921. (mask0 & (1 << (c-768))) :
  140922. (mask1 & (1 << (c-768-32)));
  140923. }
  140924. /*
  140925. ** Interpret the argument as a unicode codepoint. If the codepoint
  140926. ** is an upper case character that has a lower case equivalent,
  140927. ** return the codepoint corresponding to the lower case version.
  140928. ** Otherwise, return a copy of the argument.
  140929. **
  140930. ** The results are undefined if the value passed to this function
  140931. ** is less than zero.
  140932. */
  140933. SQLITE_PRIVATE int sqlite3FtsUnicodeFold(int c, int bRemoveDiacritic){
  140934. /* Each entry in the following array defines a rule for folding a range
  140935. ** of codepoints to lower case. The rule applies to a range of nRange
  140936. ** codepoints starting at codepoint iCode.
  140937. **
  140938. ** If the least significant bit in flags is clear, then the rule applies
  140939. ** to all nRange codepoints (i.e. all nRange codepoints are upper case and
  140940. ** need to be folded). Or, if it is set, then the rule only applies to
  140941. ** every second codepoint in the range, starting with codepoint C.
  140942. **
  140943. ** The 7 most significant bits in flags are an index into the aiOff[]
  140944. ** array. If a specific codepoint C does require folding, then its lower
  140945. ** case equivalent is ((C + aiOff[flags>>1]) & 0xFFFF).
  140946. **
  140947. ** The contents of this array are generated by parsing the CaseFolding.txt
  140948. ** file distributed as part of the "Unicode Character Database". See
  140949. ** http://www.unicode.org for details.
  140950. */
  140951. static const struct TableEntry {
  140952. unsigned short iCode;
  140953. unsigned char flags;
  140954. unsigned char nRange;
  140955. } aEntry[] = {
  140956. {65, 14, 26}, {181, 64, 1}, {192, 14, 23},
  140957. {216, 14, 7}, {256, 1, 48}, {306, 1, 6},
  140958. {313, 1, 16}, {330, 1, 46}, {376, 116, 1},
  140959. {377, 1, 6}, {383, 104, 1}, {385, 50, 1},
  140960. {386, 1, 4}, {390, 44, 1}, {391, 0, 1},
  140961. {393, 42, 2}, {395, 0, 1}, {398, 32, 1},
  140962. {399, 38, 1}, {400, 40, 1}, {401, 0, 1},
  140963. {403, 42, 1}, {404, 46, 1}, {406, 52, 1},
  140964. {407, 48, 1}, {408, 0, 1}, {412, 52, 1},
  140965. {413, 54, 1}, {415, 56, 1}, {416, 1, 6},
  140966. {422, 60, 1}, {423, 0, 1}, {425, 60, 1},
  140967. {428, 0, 1}, {430, 60, 1}, {431, 0, 1},
  140968. {433, 58, 2}, {435, 1, 4}, {439, 62, 1},
  140969. {440, 0, 1}, {444, 0, 1}, {452, 2, 1},
  140970. {453, 0, 1}, {455, 2, 1}, {456, 0, 1},
  140971. {458, 2, 1}, {459, 1, 18}, {478, 1, 18},
  140972. {497, 2, 1}, {498, 1, 4}, {502, 122, 1},
  140973. {503, 134, 1}, {504, 1, 40}, {544, 110, 1},
  140974. {546, 1, 18}, {570, 70, 1}, {571, 0, 1},
  140975. {573, 108, 1}, {574, 68, 1}, {577, 0, 1},
  140976. {579, 106, 1}, {580, 28, 1}, {581, 30, 1},
  140977. {582, 1, 10}, {837, 36, 1}, {880, 1, 4},
  140978. {886, 0, 1}, {902, 18, 1}, {904, 16, 3},
  140979. {908, 26, 1}, {910, 24, 2}, {913, 14, 17},
  140980. {931, 14, 9}, {962, 0, 1}, {975, 4, 1},
  140981. {976, 140, 1}, {977, 142, 1}, {981, 146, 1},
  140982. {982, 144, 1}, {984, 1, 24}, {1008, 136, 1},
  140983. {1009, 138, 1}, {1012, 130, 1}, {1013, 128, 1},
  140984. {1015, 0, 1}, {1017, 152, 1}, {1018, 0, 1},
  140985. {1021, 110, 3}, {1024, 34, 16}, {1040, 14, 32},
  140986. {1120, 1, 34}, {1162, 1, 54}, {1216, 6, 1},
  140987. {1217, 1, 14}, {1232, 1, 88}, {1329, 22, 38},
  140988. {4256, 66, 38}, {4295, 66, 1}, {4301, 66, 1},
  140989. {7680, 1, 150}, {7835, 132, 1}, {7838, 96, 1},
  140990. {7840, 1, 96}, {7944, 150, 8}, {7960, 150, 6},
  140991. {7976, 150, 8}, {7992, 150, 8}, {8008, 150, 6},
  140992. {8025, 151, 8}, {8040, 150, 8}, {8072, 150, 8},
  140993. {8088, 150, 8}, {8104, 150, 8}, {8120, 150, 2},
  140994. {8122, 126, 2}, {8124, 148, 1}, {8126, 100, 1},
  140995. {8136, 124, 4}, {8140, 148, 1}, {8152, 150, 2},
  140996. {8154, 120, 2}, {8168, 150, 2}, {8170, 118, 2},
  140997. {8172, 152, 1}, {8184, 112, 2}, {8186, 114, 2},
  140998. {8188, 148, 1}, {8486, 98, 1}, {8490, 92, 1},
  140999. {8491, 94, 1}, {8498, 12, 1}, {8544, 8, 16},
  141000. {8579, 0, 1}, {9398, 10, 26}, {11264, 22, 47},
  141001. {11360, 0, 1}, {11362, 88, 1}, {11363, 102, 1},
  141002. {11364, 90, 1}, {11367, 1, 6}, {11373, 84, 1},
  141003. {11374, 86, 1}, {11375, 80, 1}, {11376, 82, 1},
  141004. {11378, 0, 1}, {11381, 0, 1}, {11390, 78, 2},
  141005. {11392, 1, 100}, {11499, 1, 4}, {11506, 0, 1},
  141006. {42560, 1, 46}, {42624, 1, 24}, {42786, 1, 14},
  141007. {42802, 1, 62}, {42873, 1, 4}, {42877, 76, 1},
  141008. {42878, 1, 10}, {42891, 0, 1}, {42893, 74, 1},
  141009. {42896, 1, 4}, {42912, 1, 10}, {42922, 72, 1},
  141010. {65313, 14, 26},
  141011. };
  141012. static const unsigned short aiOff[] = {
  141013. 1, 2, 8, 15, 16, 26, 28, 32,
  141014. 37, 38, 40, 48, 63, 64, 69, 71,
  141015. 79, 80, 116, 202, 203, 205, 206, 207,
  141016. 209, 210, 211, 213, 214, 217, 218, 219,
  141017. 775, 7264, 10792, 10795, 23228, 23256, 30204, 54721,
  141018. 54753, 54754, 54756, 54787, 54793, 54809, 57153, 57274,
  141019. 57921, 58019, 58363, 61722, 65268, 65341, 65373, 65406,
  141020. 65408, 65410, 65415, 65424, 65436, 65439, 65450, 65462,
  141021. 65472, 65476, 65478, 65480, 65482, 65488, 65506, 65511,
  141022. 65514, 65521, 65527, 65528, 65529,
  141023. };
  141024. int ret = c;
  141025. assert( c>=0 );
  141026. assert( sizeof(unsigned short)==2 && sizeof(unsigned char)==1 );
  141027. if( c<128 ){
  141028. if( c>='A' && c<='Z' ) ret = c + ('a' - 'A');
  141029. }else if( c<65536 ){
  141030. int iHi = sizeof(aEntry)/sizeof(aEntry[0]) - 1;
  141031. int iLo = 0;
  141032. int iRes = -1;
  141033. while( iHi>=iLo ){
  141034. int iTest = (iHi + iLo) / 2;
  141035. int cmp = (c - aEntry[iTest].iCode);
  141036. if( cmp>=0 ){
  141037. iRes = iTest;
  141038. iLo = iTest+1;
  141039. }else{
  141040. iHi = iTest-1;
  141041. }
  141042. }
  141043. assert( iRes<0 || c>=aEntry[iRes].iCode );
  141044. if( iRes>=0 ){
  141045. const struct TableEntry *p = &aEntry[iRes];
  141046. if( c<(p->iCode + p->nRange) && 0==(0x01 & p->flags & (p->iCode ^ c)) ){
  141047. ret = (c + (aiOff[p->flags>>1])) & 0x0000FFFF;
  141048. assert( ret>0 );
  141049. }
  141050. }
  141051. if( bRemoveDiacritic ) ret = remove_diacritic(ret);
  141052. }
  141053. else if( c>=66560 && c<66600 ){
  141054. ret = c + 40;
  141055. }
  141056. return ret;
  141057. }
  141058. #endif /* defined(SQLITE_ENABLE_FTS3) || defined(SQLITE_ENABLE_FTS4) */
  141059. #endif /* !defined(SQLITE_DISABLE_FTS3_UNICODE) */
  141060. /************** End of fts3_unicode2.c ***************************************/
  141061. /************** Begin file rtree.c *******************************************/
  141062. /*
  141063. ** 2001 September 15
  141064. **
  141065. ** The author disclaims copyright to this source code. In place of
  141066. ** a legal notice, here is a blessing:
  141067. **
  141068. ** May you do good and not evil.
  141069. ** May you find forgiveness for yourself and forgive others.
  141070. ** May you share freely, never taking more than you give.
  141071. **
  141072. *************************************************************************
  141073. ** This file contains code for implementations of the r-tree and r*-tree
  141074. ** algorithms packaged as an SQLite virtual table module.
  141075. */
  141076. /*
  141077. ** Database Format of R-Tree Tables
  141078. ** --------------------------------
  141079. **
  141080. ** The data structure for a single virtual r-tree table is stored in three
  141081. ** native SQLite tables declared as follows. In each case, the '%' character
  141082. ** in the table name is replaced with the user-supplied name of the r-tree
  141083. ** table.
  141084. **
  141085. ** CREATE TABLE %_node(nodeno INTEGER PRIMARY KEY, data BLOB)
  141086. ** CREATE TABLE %_parent(nodeno INTEGER PRIMARY KEY, parentnode INTEGER)
  141087. ** CREATE TABLE %_rowid(rowid INTEGER PRIMARY KEY, nodeno INTEGER)
  141088. **
  141089. ** The data for each node of the r-tree structure is stored in the %_node
  141090. ** table. For each node that is not the root node of the r-tree, there is
  141091. ** an entry in the %_parent table associating the node with its parent.
  141092. ** And for each row of data in the table, there is an entry in the %_rowid
  141093. ** table that maps from the entries rowid to the id of the node that it
  141094. ** is stored on.
  141095. **
  141096. ** The root node of an r-tree always exists, even if the r-tree table is
  141097. ** empty. The nodeno of the root node is always 1. All other nodes in the
  141098. ** table must be the same size as the root node. The content of each node
  141099. ** is formatted as follows:
  141100. **
  141101. ** 1. If the node is the root node (node 1), then the first 2 bytes
  141102. ** of the node contain the tree depth as a big-endian integer.
  141103. ** For non-root nodes, the first 2 bytes are left unused.
  141104. **
  141105. ** 2. The next 2 bytes contain the number of entries currently
  141106. ** stored in the node.
  141107. **
  141108. ** 3. The remainder of the node contains the node entries. Each entry
  141109. ** consists of a single 8-byte integer followed by an even number
  141110. ** of 4-byte coordinates. For leaf nodes the integer is the rowid
  141111. ** of a record. For internal nodes it is the node number of a
  141112. ** child page.
  141113. */
  141114. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_RTREE)
  141115. #ifndef SQLITE_CORE
  141116. SQLITE_EXTENSION_INIT1
  141117. #else
  141118. #endif
  141119. /* #include <string.h> */
  141120. /* #include <assert.h> */
  141121. /* #include <stdio.h> */
  141122. #ifndef SQLITE_AMALGAMATION
  141123. #include "sqlite3rtree.h"
  141124. typedef sqlite3_int64 i64;
  141125. typedef unsigned char u8;
  141126. typedef unsigned short u16;
  141127. typedef unsigned int u32;
  141128. #endif
  141129. /* The following macro is used to suppress compiler warnings.
  141130. */
  141131. #ifndef UNUSED_PARAMETER
  141132. # define UNUSED_PARAMETER(x) (void)(x)
  141133. #endif
  141134. typedef struct Rtree Rtree;
  141135. typedef struct RtreeCursor RtreeCursor;
  141136. typedef struct RtreeNode RtreeNode;
  141137. typedef struct RtreeCell RtreeCell;
  141138. typedef struct RtreeConstraint RtreeConstraint;
  141139. typedef struct RtreeMatchArg RtreeMatchArg;
  141140. typedef struct RtreeGeomCallback RtreeGeomCallback;
  141141. typedef union RtreeCoord RtreeCoord;
  141142. typedef struct RtreeSearchPoint RtreeSearchPoint;
  141143. /* The rtree may have between 1 and RTREE_MAX_DIMENSIONS dimensions. */
  141144. #define RTREE_MAX_DIMENSIONS 5
  141145. /* Size of hash table Rtree.aHash. This hash table is not expected to
  141146. ** ever contain very many entries, so a fixed number of buckets is
  141147. ** used.
  141148. */
  141149. #define HASHSIZE 97
  141150. /* The xBestIndex method of this virtual table requires an estimate of
  141151. ** the number of rows in the virtual table to calculate the costs of
  141152. ** various strategies. If possible, this estimate is loaded from the
  141153. ** sqlite_stat1 table (with RTREE_MIN_ROWEST as a hard-coded minimum).
  141154. ** Otherwise, if no sqlite_stat1 entry is available, use
  141155. ** RTREE_DEFAULT_ROWEST.
  141156. */
  141157. #define RTREE_DEFAULT_ROWEST 1048576
  141158. #define RTREE_MIN_ROWEST 100
  141159. /*
  141160. ** An rtree virtual-table object.
  141161. */
  141162. struct Rtree {
  141163. sqlite3_vtab base; /* Base class. Must be first */
  141164. sqlite3 *db; /* Host database connection */
  141165. int iNodeSize; /* Size in bytes of each node in the node table */
  141166. u8 nDim; /* Number of dimensions */
  141167. u8 eCoordType; /* RTREE_COORD_REAL32 or RTREE_COORD_INT32 */
  141168. u8 nBytesPerCell; /* Bytes consumed per cell */
  141169. int iDepth; /* Current depth of the r-tree structure */
  141170. char *zDb; /* Name of database containing r-tree table */
  141171. char *zName; /* Name of r-tree table */
  141172. int nBusy; /* Current number of users of this structure */
  141173. i64 nRowEst; /* Estimated number of rows in this table */
  141174. /* List of nodes removed during a CondenseTree operation. List is
  141175. ** linked together via the pointer normally used for hash chains -
  141176. ** RtreeNode.pNext. RtreeNode.iNode stores the depth of the sub-tree
  141177. ** headed by the node (leaf nodes have RtreeNode.iNode==0).
  141178. */
  141179. RtreeNode *pDeleted;
  141180. int iReinsertHeight; /* Height of sub-trees Reinsert() has run on */
  141181. /* Statements to read/write/delete a record from xxx_node */
  141182. sqlite3_stmt *pReadNode;
  141183. sqlite3_stmt *pWriteNode;
  141184. sqlite3_stmt *pDeleteNode;
  141185. /* Statements to read/write/delete a record from xxx_rowid */
  141186. sqlite3_stmt *pReadRowid;
  141187. sqlite3_stmt *pWriteRowid;
  141188. sqlite3_stmt *pDeleteRowid;
  141189. /* Statements to read/write/delete a record from xxx_parent */
  141190. sqlite3_stmt *pReadParent;
  141191. sqlite3_stmt *pWriteParent;
  141192. sqlite3_stmt *pDeleteParent;
  141193. RtreeNode *aHash[HASHSIZE]; /* Hash table of in-memory nodes. */
  141194. };
  141195. /* Possible values for Rtree.eCoordType: */
  141196. #define RTREE_COORD_REAL32 0
  141197. #define RTREE_COORD_INT32 1
  141198. /*
  141199. ** If SQLITE_RTREE_INT_ONLY is defined, then this virtual table will
  141200. ** only deal with integer coordinates. No floating point operations
  141201. ** will be done.
  141202. */
  141203. #ifdef SQLITE_RTREE_INT_ONLY
  141204. typedef sqlite3_int64 RtreeDValue; /* High accuracy coordinate */
  141205. typedef int RtreeValue; /* Low accuracy coordinate */
  141206. # define RTREE_ZERO 0
  141207. #else
  141208. typedef double RtreeDValue; /* High accuracy coordinate */
  141209. typedef float RtreeValue; /* Low accuracy coordinate */
  141210. # define RTREE_ZERO 0.0
  141211. #endif
  141212. /*
  141213. ** When doing a search of an r-tree, instances of the following structure
  141214. ** record intermediate results from the tree walk.
  141215. **
  141216. ** The id is always a node-id. For iLevel>=1 the id is the node-id of
  141217. ** the node that the RtreeSearchPoint represents. When iLevel==0, however,
  141218. ** the id is of the parent node and the cell that RtreeSearchPoint
  141219. ** represents is the iCell-th entry in the parent node.
  141220. */
  141221. struct RtreeSearchPoint {
  141222. RtreeDValue rScore; /* The score for this node. Smallest goes first. */
  141223. sqlite3_int64 id; /* Node ID */
  141224. u8 iLevel; /* 0=entries. 1=leaf node. 2+ for higher */
  141225. u8 eWithin; /* PARTLY_WITHIN or FULLY_WITHIN */
  141226. u8 iCell; /* Cell index within the node */
  141227. };
  141228. /*
  141229. ** The minimum number of cells allowed for a node is a third of the
  141230. ** maximum. In Gutman's notation:
  141231. **
  141232. ** m = M/3
  141233. **
  141234. ** If an R*-tree "Reinsert" operation is required, the same number of
  141235. ** cells are removed from the overfull node and reinserted into the tree.
  141236. */
  141237. #define RTREE_MINCELLS(p) ((((p)->iNodeSize-4)/(p)->nBytesPerCell)/3)
  141238. #define RTREE_REINSERT(p) RTREE_MINCELLS(p)
  141239. #define RTREE_MAXCELLS 51
  141240. /*
  141241. ** The smallest possible node-size is (512-64)==448 bytes. And the largest
  141242. ** supported cell size is 48 bytes (8 byte rowid + ten 4 byte coordinates).
  141243. ** Therefore all non-root nodes must contain at least 3 entries. Since
  141244. ** 2^40 is greater than 2^64, an r-tree structure always has a depth of
  141245. ** 40 or less.
  141246. */
  141247. #define RTREE_MAX_DEPTH 40
  141248. /*
  141249. ** Number of entries in the cursor RtreeNode cache. The first entry is
  141250. ** used to cache the RtreeNode for RtreeCursor.sPoint. The remaining
  141251. ** entries cache the RtreeNode for the first elements of the priority queue.
  141252. */
  141253. #define RTREE_CACHE_SZ 5
  141254. /*
  141255. ** An rtree cursor object.
  141256. */
  141257. struct RtreeCursor {
  141258. sqlite3_vtab_cursor base; /* Base class. Must be first */
  141259. u8 atEOF; /* True if at end of search */
  141260. u8 bPoint; /* True if sPoint is valid */
  141261. int iStrategy; /* Copy of idxNum search parameter */
  141262. int nConstraint; /* Number of entries in aConstraint */
  141263. RtreeConstraint *aConstraint; /* Search constraints. */
  141264. int nPointAlloc; /* Number of slots allocated for aPoint[] */
  141265. int nPoint; /* Number of slots used in aPoint[] */
  141266. int mxLevel; /* iLevel value for root of the tree */
  141267. RtreeSearchPoint *aPoint; /* Priority queue for search points */
  141268. RtreeSearchPoint sPoint; /* Cached next search point */
  141269. RtreeNode *aNode[RTREE_CACHE_SZ]; /* Rtree node cache */
  141270. u32 anQueue[RTREE_MAX_DEPTH+1]; /* Number of queued entries by iLevel */
  141271. };
  141272. /* Return the Rtree of a RtreeCursor */
  141273. #define RTREE_OF_CURSOR(X) ((Rtree*)((X)->base.pVtab))
  141274. /*
  141275. ** A coordinate can be either a floating point number or a integer. All
  141276. ** coordinates within a single R-Tree are always of the same time.
  141277. */
  141278. union RtreeCoord {
  141279. RtreeValue f; /* Floating point value */
  141280. int i; /* Integer value */
  141281. u32 u; /* Unsigned for byte-order conversions */
  141282. };
  141283. /*
  141284. ** The argument is an RtreeCoord. Return the value stored within the RtreeCoord
  141285. ** formatted as a RtreeDValue (double or int64). This macro assumes that local
  141286. ** variable pRtree points to the Rtree structure associated with the
  141287. ** RtreeCoord.
  141288. */
  141289. #ifdef SQLITE_RTREE_INT_ONLY
  141290. # define DCOORD(coord) ((RtreeDValue)coord.i)
  141291. #else
  141292. # define DCOORD(coord) ( \
  141293. (pRtree->eCoordType==RTREE_COORD_REAL32) ? \
  141294. ((double)coord.f) : \
  141295. ((double)coord.i) \
  141296. )
  141297. #endif
  141298. /*
  141299. ** A search constraint.
  141300. */
  141301. struct RtreeConstraint {
  141302. int iCoord; /* Index of constrained coordinate */
  141303. int op; /* Constraining operation */
  141304. union {
  141305. RtreeDValue rValue; /* Constraint value. */
  141306. int (*xGeom)(sqlite3_rtree_geometry*,int,RtreeDValue*,int*);
  141307. int (*xQueryFunc)(sqlite3_rtree_query_info*);
  141308. } u;
  141309. sqlite3_rtree_query_info *pInfo; /* xGeom and xQueryFunc argument */
  141310. };
  141311. /* Possible values for RtreeConstraint.op */
  141312. #define RTREE_EQ 0x41 /* A */
  141313. #define RTREE_LE 0x42 /* B */
  141314. #define RTREE_LT 0x43 /* C */
  141315. #define RTREE_GE 0x44 /* D */
  141316. #define RTREE_GT 0x45 /* E */
  141317. #define RTREE_MATCH 0x46 /* F: Old-style sqlite3_rtree_geometry_callback() */
  141318. #define RTREE_QUERY 0x47 /* G: New-style sqlite3_rtree_query_callback() */
  141319. /*
  141320. ** An rtree structure node.
  141321. */
  141322. struct RtreeNode {
  141323. RtreeNode *pParent; /* Parent node */
  141324. i64 iNode; /* The node number */
  141325. int nRef; /* Number of references to this node */
  141326. int isDirty; /* True if the node needs to be written to disk */
  141327. u8 *zData; /* Content of the node, as should be on disk */
  141328. RtreeNode *pNext; /* Next node in this hash collision chain */
  141329. };
  141330. /* Return the number of cells in a node */
  141331. #define NCELL(pNode) readInt16(&(pNode)->zData[2])
  141332. /*
  141333. ** A single cell from a node, deserialized
  141334. */
  141335. struct RtreeCell {
  141336. i64 iRowid; /* Node or entry ID */
  141337. RtreeCoord aCoord[RTREE_MAX_DIMENSIONS*2]; /* Bounding box coordinates */
  141338. };
  141339. /*
  141340. ** This object becomes the sqlite3_user_data() for the SQL functions
  141341. ** that are created by sqlite3_rtree_geometry_callback() and
  141342. ** sqlite3_rtree_query_callback() and which appear on the right of MATCH
  141343. ** operators in order to constrain a search.
  141344. **
  141345. ** xGeom and xQueryFunc are the callback functions. Exactly one of
  141346. ** xGeom and xQueryFunc fields is non-NULL, depending on whether the
  141347. ** SQL function was created using sqlite3_rtree_geometry_callback() or
  141348. ** sqlite3_rtree_query_callback().
  141349. **
  141350. ** This object is deleted automatically by the destructor mechanism in
  141351. ** sqlite3_create_function_v2().
  141352. */
  141353. struct RtreeGeomCallback {
  141354. int (*xGeom)(sqlite3_rtree_geometry*, int, RtreeDValue*, int*);
  141355. int (*xQueryFunc)(sqlite3_rtree_query_info*);
  141356. void (*xDestructor)(void*);
  141357. void *pContext;
  141358. };
  141359. /*
  141360. ** Value for the first field of every RtreeMatchArg object. The MATCH
  141361. ** operator tests that the first field of a blob operand matches this
  141362. ** value to avoid operating on invalid blobs (which could cause a segfault).
  141363. */
  141364. #define RTREE_GEOMETRY_MAGIC 0x891245AB
  141365. /*
  141366. ** An instance of this structure (in the form of a BLOB) is returned by
  141367. ** the SQL functions that sqlite3_rtree_geometry_callback() and
  141368. ** sqlite3_rtree_query_callback() create, and is read as the right-hand
  141369. ** operand to the MATCH operator of an R-Tree.
  141370. */
  141371. struct RtreeMatchArg {
  141372. u32 magic; /* Always RTREE_GEOMETRY_MAGIC */
  141373. RtreeGeomCallback cb; /* Info about the callback functions */
  141374. int nParam; /* Number of parameters to the SQL function */
  141375. RtreeDValue aParam[1]; /* Values for parameters to the SQL function */
  141376. };
  141377. #ifndef MAX
  141378. # define MAX(x,y) ((x) < (y) ? (y) : (x))
  141379. #endif
  141380. #ifndef MIN
  141381. # define MIN(x,y) ((x) > (y) ? (y) : (x))
  141382. #endif
  141383. /*
  141384. ** Functions to deserialize a 16 bit integer, 32 bit real number and
  141385. ** 64 bit integer. The deserialized value is returned.
  141386. */
  141387. static int readInt16(u8 *p){
  141388. return (p[0]<<8) + p[1];
  141389. }
  141390. static void readCoord(u8 *p, RtreeCoord *pCoord){
  141391. pCoord->u = (
  141392. (((u32)p[0]) << 24) +
  141393. (((u32)p[1]) << 16) +
  141394. (((u32)p[2]) << 8) +
  141395. (((u32)p[3]) << 0)
  141396. );
  141397. }
  141398. static i64 readInt64(u8 *p){
  141399. return (
  141400. (((i64)p[0]) << 56) +
  141401. (((i64)p[1]) << 48) +
  141402. (((i64)p[2]) << 40) +
  141403. (((i64)p[3]) << 32) +
  141404. (((i64)p[4]) << 24) +
  141405. (((i64)p[5]) << 16) +
  141406. (((i64)p[6]) << 8) +
  141407. (((i64)p[7]) << 0)
  141408. );
  141409. }
  141410. /*
  141411. ** Functions to serialize a 16 bit integer, 32 bit real number and
  141412. ** 64 bit integer. The value returned is the number of bytes written
  141413. ** to the argument buffer (always 2, 4 and 8 respectively).
  141414. */
  141415. static int writeInt16(u8 *p, int i){
  141416. p[0] = (i>> 8)&0xFF;
  141417. p[1] = (i>> 0)&0xFF;
  141418. return 2;
  141419. }
  141420. static int writeCoord(u8 *p, RtreeCoord *pCoord){
  141421. u32 i;
  141422. assert( sizeof(RtreeCoord)==4 );
  141423. assert( sizeof(u32)==4 );
  141424. i = pCoord->u;
  141425. p[0] = (i>>24)&0xFF;
  141426. p[1] = (i>>16)&0xFF;
  141427. p[2] = (i>> 8)&0xFF;
  141428. p[3] = (i>> 0)&0xFF;
  141429. return 4;
  141430. }
  141431. static int writeInt64(u8 *p, i64 i){
  141432. p[0] = (i>>56)&0xFF;
  141433. p[1] = (i>>48)&0xFF;
  141434. p[2] = (i>>40)&0xFF;
  141435. p[3] = (i>>32)&0xFF;
  141436. p[4] = (i>>24)&0xFF;
  141437. p[5] = (i>>16)&0xFF;
  141438. p[6] = (i>> 8)&0xFF;
  141439. p[7] = (i>> 0)&0xFF;
  141440. return 8;
  141441. }
  141442. /*
  141443. ** Increment the reference count of node p.
  141444. */
  141445. static void nodeReference(RtreeNode *p){
  141446. if( p ){
  141447. p->nRef++;
  141448. }
  141449. }
  141450. /*
  141451. ** Clear the content of node p (set all bytes to 0x00).
  141452. */
  141453. static void nodeZero(Rtree *pRtree, RtreeNode *p){
  141454. memset(&p->zData[2], 0, pRtree->iNodeSize-2);
  141455. p->isDirty = 1;
  141456. }
  141457. /*
  141458. ** Given a node number iNode, return the corresponding key to use
  141459. ** in the Rtree.aHash table.
  141460. */
  141461. static int nodeHash(i64 iNode){
  141462. return iNode % HASHSIZE;
  141463. }
  141464. /*
  141465. ** Search the node hash table for node iNode. If found, return a pointer
  141466. ** to it. Otherwise, return 0.
  141467. */
  141468. static RtreeNode *nodeHashLookup(Rtree *pRtree, i64 iNode){
  141469. RtreeNode *p;
  141470. for(p=pRtree->aHash[nodeHash(iNode)]; p && p->iNode!=iNode; p=p->pNext);
  141471. return p;
  141472. }
  141473. /*
  141474. ** Add node pNode to the node hash table.
  141475. */
  141476. static void nodeHashInsert(Rtree *pRtree, RtreeNode *pNode){
  141477. int iHash;
  141478. assert( pNode->pNext==0 );
  141479. iHash = nodeHash(pNode->iNode);
  141480. pNode->pNext = pRtree->aHash[iHash];
  141481. pRtree->aHash[iHash] = pNode;
  141482. }
  141483. /*
  141484. ** Remove node pNode from the node hash table.
  141485. */
  141486. static void nodeHashDelete(Rtree *pRtree, RtreeNode *pNode){
  141487. RtreeNode **pp;
  141488. if( pNode->iNode!=0 ){
  141489. pp = &pRtree->aHash[nodeHash(pNode->iNode)];
  141490. for( ; (*pp)!=pNode; pp = &(*pp)->pNext){ assert(*pp); }
  141491. *pp = pNode->pNext;
  141492. pNode->pNext = 0;
  141493. }
  141494. }
  141495. /*
  141496. ** Allocate and return new r-tree node. Initially, (RtreeNode.iNode==0),
  141497. ** indicating that node has not yet been assigned a node number. It is
  141498. ** assigned a node number when nodeWrite() is called to write the
  141499. ** node contents out to the database.
  141500. */
  141501. static RtreeNode *nodeNew(Rtree *pRtree, RtreeNode *pParent){
  141502. RtreeNode *pNode;
  141503. pNode = (RtreeNode *)sqlite3_malloc(sizeof(RtreeNode) + pRtree->iNodeSize);
  141504. if( pNode ){
  141505. memset(pNode, 0, sizeof(RtreeNode) + pRtree->iNodeSize);
  141506. pNode->zData = (u8 *)&pNode[1];
  141507. pNode->nRef = 1;
  141508. pNode->pParent = pParent;
  141509. pNode->isDirty = 1;
  141510. nodeReference(pParent);
  141511. }
  141512. return pNode;
  141513. }
  141514. /*
  141515. ** Obtain a reference to an r-tree node.
  141516. */
  141517. static int nodeAcquire(
  141518. Rtree *pRtree, /* R-tree structure */
  141519. i64 iNode, /* Node number to load */
  141520. RtreeNode *pParent, /* Either the parent node or NULL */
  141521. RtreeNode **ppNode /* OUT: Acquired node */
  141522. ){
  141523. int rc;
  141524. int rc2 = SQLITE_OK;
  141525. RtreeNode *pNode;
  141526. /* Check if the requested node is already in the hash table. If so,
  141527. ** increase its reference count and return it.
  141528. */
  141529. if( (pNode = nodeHashLookup(pRtree, iNode)) ){
  141530. assert( !pParent || !pNode->pParent || pNode->pParent==pParent );
  141531. if( pParent && !pNode->pParent ){
  141532. nodeReference(pParent);
  141533. pNode->pParent = pParent;
  141534. }
  141535. pNode->nRef++;
  141536. *ppNode = pNode;
  141537. return SQLITE_OK;
  141538. }
  141539. sqlite3_bind_int64(pRtree->pReadNode, 1, iNode);
  141540. rc = sqlite3_step(pRtree->pReadNode);
  141541. if( rc==SQLITE_ROW ){
  141542. const u8 *zBlob = sqlite3_column_blob(pRtree->pReadNode, 0);
  141543. if( pRtree->iNodeSize==sqlite3_column_bytes(pRtree->pReadNode, 0) ){
  141544. pNode = (RtreeNode *)sqlite3_malloc(sizeof(RtreeNode)+pRtree->iNodeSize);
  141545. if( !pNode ){
  141546. rc2 = SQLITE_NOMEM;
  141547. }else{
  141548. pNode->pParent = pParent;
  141549. pNode->zData = (u8 *)&pNode[1];
  141550. pNode->nRef = 1;
  141551. pNode->iNode = iNode;
  141552. pNode->isDirty = 0;
  141553. pNode->pNext = 0;
  141554. memcpy(pNode->zData, zBlob, pRtree->iNodeSize);
  141555. nodeReference(pParent);
  141556. }
  141557. }
  141558. }
  141559. rc = sqlite3_reset(pRtree->pReadNode);
  141560. if( rc==SQLITE_OK ) rc = rc2;
  141561. /* If the root node was just loaded, set pRtree->iDepth to the height
  141562. ** of the r-tree structure. A height of zero means all data is stored on
  141563. ** the root node. A height of one means the children of the root node
  141564. ** are the leaves, and so on. If the depth as specified on the root node
  141565. ** is greater than RTREE_MAX_DEPTH, the r-tree structure must be corrupt.
  141566. */
  141567. if( pNode && iNode==1 ){
  141568. pRtree->iDepth = readInt16(pNode->zData);
  141569. if( pRtree->iDepth>RTREE_MAX_DEPTH ){
  141570. rc = SQLITE_CORRUPT_VTAB;
  141571. }
  141572. }
  141573. /* If no error has occurred so far, check if the "number of entries"
  141574. ** field on the node is too large. If so, set the return code to
  141575. ** SQLITE_CORRUPT_VTAB.
  141576. */
  141577. if( pNode && rc==SQLITE_OK ){
  141578. if( NCELL(pNode)>((pRtree->iNodeSize-4)/pRtree->nBytesPerCell) ){
  141579. rc = SQLITE_CORRUPT_VTAB;
  141580. }
  141581. }
  141582. if( rc==SQLITE_OK ){
  141583. if( pNode!=0 ){
  141584. nodeHashInsert(pRtree, pNode);
  141585. }else{
  141586. rc = SQLITE_CORRUPT_VTAB;
  141587. }
  141588. *ppNode = pNode;
  141589. }else{
  141590. sqlite3_free(pNode);
  141591. *ppNode = 0;
  141592. }
  141593. return rc;
  141594. }
  141595. /*
  141596. ** Overwrite cell iCell of node pNode with the contents of pCell.
  141597. */
  141598. static void nodeOverwriteCell(
  141599. Rtree *pRtree, /* The overall R-Tree */
  141600. RtreeNode *pNode, /* The node into which the cell is to be written */
  141601. RtreeCell *pCell, /* The cell to write */
  141602. int iCell /* Index into pNode into which pCell is written */
  141603. ){
  141604. int ii;
  141605. u8 *p = &pNode->zData[4 + pRtree->nBytesPerCell*iCell];
  141606. p += writeInt64(p, pCell->iRowid);
  141607. for(ii=0; ii<(pRtree->nDim*2); ii++){
  141608. p += writeCoord(p, &pCell->aCoord[ii]);
  141609. }
  141610. pNode->isDirty = 1;
  141611. }
  141612. /*
  141613. ** Remove the cell with index iCell from node pNode.
  141614. */
  141615. static void nodeDeleteCell(Rtree *pRtree, RtreeNode *pNode, int iCell){
  141616. u8 *pDst = &pNode->zData[4 + pRtree->nBytesPerCell*iCell];
  141617. u8 *pSrc = &pDst[pRtree->nBytesPerCell];
  141618. int nByte = (NCELL(pNode) - iCell - 1) * pRtree->nBytesPerCell;
  141619. memmove(pDst, pSrc, nByte);
  141620. writeInt16(&pNode->zData[2], NCELL(pNode)-1);
  141621. pNode->isDirty = 1;
  141622. }
  141623. /*
  141624. ** Insert the contents of cell pCell into node pNode. If the insert
  141625. ** is successful, return SQLITE_OK.
  141626. **
  141627. ** If there is not enough free space in pNode, return SQLITE_FULL.
  141628. */
  141629. static int nodeInsertCell(
  141630. Rtree *pRtree, /* The overall R-Tree */
  141631. RtreeNode *pNode, /* Write new cell into this node */
  141632. RtreeCell *pCell /* The cell to be inserted */
  141633. ){
  141634. int nCell; /* Current number of cells in pNode */
  141635. int nMaxCell; /* Maximum number of cells for pNode */
  141636. nMaxCell = (pRtree->iNodeSize-4)/pRtree->nBytesPerCell;
  141637. nCell = NCELL(pNode);
  141638. assert( nCell<=nMaxCell );
  141639. if( nCell<nMaxCell ){
  141640. nodeOverwriteCell(pRtree, pNode, pCell, nCell);
  141641. writeInt16(&pNode->zData[2], nCell+1);
  141642. pNode->isDirty = 1;
  141643. }
  141644. return (nCell==nMaxCell);
  141645. }
  141646. /*
  141647. ** If the node is dirty, write it out to the database.
  141648. */
  141649. static int nodeWrite(Rtree *pRtree, RtreeNode *pNode){
  141650. int rc = SQLITE_OK;
  141651. if( pNode->isDirty ){
  141652. sqlite3_stmt *p = pRtree->pWriteNode;
  141653. if( pNode->iNode ){
  141654. sqlite3_bind_int64(p, 1, pNode->iNode);
  141655. }else{
  141656. sqlite3_bind_null(p, 1);
  141657. }
  141658. sqlite3_bind_blob(p, 2, pNode->zData, pRtree->iNodeSize, SQLITE_STATIC);
  141659. sqlite3_step(p);
  141660. pNode->isDirty = 0;
  141661. rc = sqlite3_reset(p);
  141662. if( pNode->iNode==0 && rc==SQLITE_OK ){
  141663. pNode->iNode = sqlite3_last_insert_rowid(pRtree->db);
  141664. nodeHashInsert(pRtree, pNode);
  141665. }
  141666. }
  141667. return rc;
  141668. }
  141669. /*
  141670. ** Release a reference to a node. If the node is dirty and the reference
  141671. ** count drops to zero, the node data is written to the database.
  141672. */
  141673. static int nodeRelease(Rtree *pRtree, RtreeNode *pNode){
  141674. int rc = SQLITE_OK;
  141675. if( pNode ){
  141676. assert( pNode->nRef>0 );
  141677. pNode->nRef--;
  141678. if( pNode->nRef==0 ){
  141679. if( pNode->iNode==1 ){
  141680. pRtree->iDepth = -1;
  141681. }
  141682. if( pNode->pParent ){
  141683. rc = nodeRelease(pRtree, pNode->pParent);
  141684. }
  141685. if( rc==SQLITE_OK ){
  141686. rc = nodeWrite(pRtree, pNode);
  141687. }
  141688. nodeHashDelete(pRtree, pNode);
  141689. sqlite3_free(pNode);
  141690. }
  141691. }
  141692. return rc;
  141693. }
  141694. /*
  141695. ** Return the 64-bit integer value associated with cell iCell of
  141696. ** node pNode. If pNode is a leaf node, this is a rowid. If it is
  141697. ** an internal node, then the 64-bit integer is a child page number.
  141698. */
  141699. static i64 nodeGetRowid(
  141700. Rtree *pRtree, /* The overall R-Tree */
  141701. RtreeNode *pNode, /* The node from which to extract the ID */
  141702. int iCell /* The cell index from which to extract the ID */
  141703. ){
  141704. assert( iCell<NCELL(pNode) );
  141705. return readInt64(&pNode->zData[4 + pRtree->nBytesPerCell*iCell]);
  141706. }
  141707. /*
  141708. ** Return coordinate iCoord from cell iCell in node pNode.
  141709. */
  141710. static void nodeGetCoord(
  141711. Rtree *pRtree, /* The overall R-Tree */
  141712. RtreeNode *pNode, /* The node from which to extract a coordinate */
  141713. int iCell, /* The index of the cell within the node */
  141714. int iCoord, /* Which coordinate to extract */
  141715. RtreeCoord *pCoord /* OUT: Space to write result to */
  141716. ){
  141717. readCoord(&pNode->zData[12 + pRtree->nBytesPerCell*iCell + 4*iCoord], pCoord);
  141718. }
  141719. /*
  141720. ** Deserialize cell iCell of node pNode. Populate the structure pointed
  141721. ** to by pCell with the results.
  141722. */
  141723. static void nodeGetCell(
  141724. Rtree *pRtree, /* The overall R-Tree */
  141725. RtreeNode *pNode, /* The node containing the cell to be read */
  141726. int iCell, /* Index of the cell within the node */
  141727. RtreeCell *pCell /* OUT: Write the cell contents here */
  141728. ){
  141729. u8 *pData;
  141730. RtreeCoord *pCoord;
  141731. int ii;
  141732. pCell->iRowid = nodeGetRowid(pRtree, pNode, iCell);
  141733. pData = pNode->zData + (12 + pRtree->nBytesPerCell*iCell);
  141734. pCoord = pCell->aCoord;
  141735. for(ii=0; ii<pRtree->nDim*2; ii++){
  141736. readCoord(&pData[ii*4], &pCoord[ii]);
  141737. }
  141738. }
  141739. /* Forward declaration for the function that does the work of
  141740. ** the virtual table module xCreate() and xConnect() methods.
  141741. */
  141742. static int rtreeInit(
  141743. sqlite3 *, void *, int, const char *const*, sqlite3_vtab **, char **, int
  141744. );
  141745. /*
  141746. ** Rtree virtual table module xCreate method.
  141747. */
  141748. static int rtreeCreate(
  141749. sqlite3 *db,
  141750. void *pAux,
  141751. int argc, const char *const*argv,
  141752. sqlite3_vtab **ppVtab,
  141753. char **pzErr
  141754. ){
  141755. return rtreeInit(db, pAux, argc, argv, ppVtab, pzErr, 1);
  141756. }
  141757. /*
  141758. ** Rtree virtual table module xConnect method.
  141759. */
  141760. static int rtreeConnect(
  141761. sqlite3 *db,
  141762. void *pAux,
  141763. int argc, const char *const*argv,
  141764. sqlite3_vtab **ppVtab,
  141765. char **pzErr
  141766. ){
  141767. return rtreeInit(db, pAux, argc, argv, ppVtab, pzErr, 0);
  141768. }
  141769. /*
  141770. ** Increment the r-tree reference count.
  141771. */
  141772. static void rtreeReference(Rtree *pRtree){
  141773. pRtree->nBusy++;
  141774. }
  141775. /*
  141776. ** Decrement the r-tree reference count. When the reference count reaches
  141777. ** zero the structure is deleted.
  141778. */
  141779. static void rtreeRelease(Rtree *pRtree){
  141780. pRtree->nBusy--;
  141781. if( pRtree->nBusy==0 ){
  141782. sqlite3_finalize(pRtree->pReadNode);
  141783. sqlite3_finalize(pRtree->pWriteNode);
  141784. sqlite3_finalize(pRtree->pDeleteNode);
  141785. sqlite3_finalize(pRtree->pReadRowid);
  141786. sqlite3_finalize(pRtree->pWriteRowid);
  141787. sqlite3_finalize(pRtree->pDeleteRowid);
  141788. sqlite3_finalize(pRtree->pReadParent);
  141789. sqlite3_finalize(pRtree->pWriteParent);
  141790. sqlite3_finalize(pRtree->pDeleteParent);
  141791. sqlite3_free(pRtree);
  141792. }
  141793. }
  141794. /*
  141795. ** Rtree virtual table module xDisconnect method.
  141796. */
  141797. static int rtreeDisconnect(sqlite3_vtab *pVtab){
  141798. rtreeRelease((Rtree *)pVtab);
  141799. return SQLITE_OK;
  141800. }
  141801. /*
  141802. ** Rtree virtual table module xDestroy method.
  141803. */
  141804. static int rtreeDestroy(sqlite3_vtab *pVtab){
  141805. Rtree *pRtree = (Rtree *)pVtab;
  141806. int rc;
  141807. char *zCreate = sqlite3_mprintf(
  141808. "DROP TABLE '%q'.'%q_node';"
  141809. "DROP TABLE '%q'.'%q_rowid';"
  141810. "DROP TABLE '%q'.'%q_parent';",
  141811. pRtree->zDb, pRtree->zName,
  141812. pRtree->zDb, pRtree->zName,
  141813. pRtree->zDb, pRtree->zName
  141814. );
  141815. if( !zCreate ){
  141816. rc = SQLITE_NOMEM;
  141817. }else{
  141818. rc = sqlite3_exec(pRtree->db, zCreate, 0, 0, 0);
  141819. sqlite3_free(zCreate);
  141820. }
  141821. if( rc==SQLITE_OK ){
  141822. rtreeRelease(pRtree);
  141823. }
  141824. return rc;
  141825. }
  141826. /*
  141827. ** Rtree virtual table module xOpen method.
  141828. */
  141829. static int rtreeOpen(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor){
  141830. int rc = SQLITE_NOMEM;
  141831. RtreeCursor *pCsr;
  141832. pCsr = (RtreeCursor *)sqlite3_malloc(sizeof(RtreeCursor));
  141833. if( pCsr ){
  141834. memset(pCsr, 0, sizeof(RtreeCursor));
  141835. pCsr->base.pVtab = pVTab;
  141836. rc = SQLITE_OK;
  141837. }
  141838. *ppCursor = (sqlite3_vtab_cursor *)pCsr;
  141839. return rc;
  141840. }
  141841. /*
  141842. ** Free the RtreeCursor.aConstraint[] array and its contents.
  141843. */
  141844. static void freeCursorConstraints(RtreeCursor *pCsr){
  141845. if( pCsr->aConstraint ){
  141846. int i; /* Used to iterate through constraint array */
  141847. for(i=0; i<pCsr->nConstraint; i++){
  141848. sqlite3_rtree_query_info *pInfo = pCsr->aConstraint[i].pInfo;
  141849. if( pInfo ){
  141850. if( pInfo->xDelUser ) pInfo->xDelUser(pInfo->pUser);
  141851. sqlite3_free(pInfo);
  141852. }
  141853. }
  141854. sqlite3_free(pCsr->aConstraint);
  141855. pCsr->aConstraint = 0;
  141856. }
  141857. }
  141858. /*
  141859. ** Rtree virtual table module xClose method.
  141860. */
  141861. static int rtreeClose(sqlite3_vtab_cursor *cur){
  141862. Rtree *pRtree = (Rtree *)(cur->pVtab);
  141863. int ii;
  141864. RtreeCursor *pCsr = (RtreeCursor *)cur;
  141865. freeCursorConstraints(pCsr);
  141866. sqlite3_free(pCsr->aPoint);
  141867. for(ii=0; ii<RTREE_CACHE_SZ; ii++) nodeRelease(pRtree, pCsr->aNode[ii]);
  141868. sqlite3_free(pCsr);
  141869. return SQLITE_OK;
  141870. }
  141871. /*
  141872. ** Rtree virtual table module xEof method.
  141873. **
  141874. ** Return non-zero if the cursor does not currently point to a valid
  141875. ** record (i.e if the scan has finished), or zero otherwise.
  141876. */
  141877. static int rtreeEof(sqlite3_vtab_cursor *cur){
  141878. RtreeCursor *pCsr = (RtreeCursor *)cur;
  141879. return pCsr->atEOF;
  141880. }
  141881. /*
  141882. ** Convert raw bits from the on-disk RTree record into a coordinate value.
  141883. ** The on-disk format is big-endian and needs to be converted for little-
  141884. ** endian platforms. The on-disk record stores integer coordinates if
  141885. ** eInt is true and it stores 32-bit floating point records if eInt is
  141886. ** false. a[] is the four bytes of the on-disk record to be decoded.
  141887. ** Store the results in "r".
  141888. **
  141889. ** There are three versions of this macro, one each for little-endian and
  141890. ** big-endian processors and a third generic implementation. The endian-
  141891. ** specific implementations are much faster and are preferred if the
  141892. ** processor endianness is known at compile-time. The SQLITE_BYTEORDER
  141893. ** macro is part of sqliteInt.h and hence the endian-specific
  141894. ** implementation will only be used if this module is compiled as part
  141895. ** of the amalgamation.
  141896. */
  141897. #if defined(SQLITE_BYTEORDER) && SQLITE_BYTEORDER==1234
  141898. #define RTREE_DECODE_COORD(eInt, a, r) { \
  141899. RtreeCoord c; /* Coordinate decoded */ \
  141900. memcpy(&c.u,a,4); \
  141901. c.u = ((c.u>>24)&0xff)|((c.u>>8)&0xff00)| \
  141902. ((c.u&0xff)<<24)|((c.u&0xff00)<<8); \
  141903. r = eInt ? (sqlite3_rtree_dbl)c.i : (sqlite3_rtree_dbl)c.f; \
  141904. }
  141905. #elif defined(SQLITE_BYTEORDER) && SQLITE_BYTEORDER==4321
  141906. #define RTREE_DECODE_COORD(eInt, a, r) { \
  141907. RtreeCoord c; /* Coordinate decoded */ \
  141908. memcpy(&c.u,a,4); \
  141909. r = eInt ? (sqlite3_rtree_dbl)c.i : (sqlite3_rtree_dbl)c.f; \
  141910. }
  141911. #else
  141912. #define RTREE_DECODE_COORD(eInt, a, r) { \
  141913. RtreeCoord c; /* Coordinate decoded */ \
  141914. c.u = ((u32)a[0]<<24) + ((u32)a[1]<<16) \
  141915. +((u32)a[2]<<8) + a[3]; \
  141916. r = eInt ? (sqlite3_rtree_dbl)c.i : (sqlite3_rtree_dbl)c.f; \
  141917. }
  141918. #endif
  141919. /*
  141920. ** Check the RTree node or entry given by pCellData and p against the MATCH
  141921. ** constraint pConstraint.
  141922. */
  141923. static int rtreeCallbackConstraint(
  141924. RtreeConstraint *pConstraint, /* The constraint to test */
  141925. int eInt, /* True if RTree holding integer coordinates */
  141926. u8 *pCellData, /* Raw cell content */
  141927. RtreeSearchPoint *pSearch, /* Container of this cell */
  141928. sqlite3_rtree_dbl *prScore, /* OUT: score for the cell */
  141929. int *peWithin /* OUT: visibility of the cell */
  141930. ){
  141931. int i; /* Loop counter */
  141932. sqlite3_rtree_query_info *pInfo = pConstraint->pInfo; /* Callback info */
  141933. int nCoord = pInfo->nCoord; /* No. of coordinates */
  141934. int rc; /* Callback return code */
  141935. sqlite3_rtree_dbl aCoord[RTREE_MAX_DIMENSIONS*2]; /* Decoded coordinates */
  141936. assert( pConstraint->op==RTREE_MATCH || pConstraint->op==RTREE_QUERY );
  141937. assert( nCoord==2 || nCoord==4 || nCoord==6 || nCoord==8 || nCoord==10 );
  141938. if( pConstraint->op==RTREE_QUERY && pSearch->iLevel==1 ){
  141939. pInfo->iRowid = readInt64(pCellData);
  141940. }
  141941. pCellData += 8;
  141942. for(i=0; i<nCoord; i++, pCellData += 4){
  141943. RTREE_DECODE_COORD(eInt, pCellData, aCoord[i]);
  141944. }
  141945. if( pConstraint->op==RTREE_MATCH ){
  141946. rc = pConstraint->u.xGeom((sqlite3_rtree_geometry*)pInfo,
  141947. nCoord, aCoord, &i);
  141948. if( i==0 ) *peWithin = NOT_WITHIN;
  141949. *prScore = RTREE_ZERO;
  141950. }else{
  141951. pInfo->aCoord = aCoord;
  141952. pInfo->iLevel = pSearch->iLevel - 1;
  141953. pInfo->rScore = pInfo->rParentScore = pSearch->rScore;
  141954. pInfo->eWithin = pInfo->eParentWithin = pSearch->eWithin;
  141955. rc = pConstraint->u.xQueryFunc(pInfo);
  141956. if( pInfo->eWithin<*peWithin ) *peWithin = pInfo->eWithin;
  141957. if( pInfo->rScore<*prScore || *prScore<RTREE_ZERO ){
  141958. *prScore = pInfo->rScore;
  141959. }
  141960. }
  141961. return rc;
  141962. }
  141963. /*
  141964. ** Check the internal RTree node given by pCellData against constraint p.
  141965. ** If this constraint cannot be satisfied by any child within the node,
  141966. ** set *peWithin to NOT_WITHIN.
  141967. */
  141968. static void rtreeNonleafConstraint(
  141969. RtreeConstraint *p, /* The constraint to test */
  141970. int eInt, /* True if RTree holds integer coordinates */
  141971. u8 *pCellData, /* Raw cell content as appears on disk */
  141972. int *peWithin /* Adjust downward, as appropriate */
  141973. ){
  141974. sqlite3_rtree_dbl val; /* Coordinate value convert to a double */
  141975. /* p->iCoord might point to either a lower or upper bound coordinate
  141976. ** in a coordinate pair. But make pCellData point to the lower bound.
  141977. */
  141978. pCellData += 8 + 4*(p->iCoord&0xfe);
  141979. assert(p->op==RTREE_LE || p->op==RTREE_LT || p->op==RTREE_GE
  141980. || p->op==RTREE_GT || p->op==RTREE_EQ );
  141981. switch( p->op ){
  141982. case RTREE_LE:
  141983. case RTREE_LT:
  141984. case RTREE_EQ:
  141985. RTREE_DECODE_COORD(eInt, pCellData, val);
  141986. /* val now holds the lower bound of the coordinate pair */
  141987. if( p->u.rValue>=val ) return;
  141988. if( p->op!=RTREE_EQ ) break; /* RTREE_LE and RTREE_LT end here */
  141989. /* Fall through for the RTREE_EQ case */
  141990. default: /* RTREE_GT or RTREE_GE, or fallthrough of RTREE_EQ */
  141991. pCellData += 4;
  141992. RTREE_DECODE_COORD(eInt, pCellData, val);
  141993. /* val now holds the upper bound of the coordinate pair */
  141994. if( p->u.rValue<=val ) return;
  141995. }
  141996. *peWithin = NOT_WITHIN;
  141997. }
  141998. /*
  141999. ** Check the leaf RTree cell given by pCellData against constraint p.
  142000. ** If this constraint is not satisfied, set *peWithin to NOT_WITHIN.
  142001. ** If the constraint is satisfied, leave *peWithin unchanged.
  142002. **
  142003. ** The constraint is of the form: xN op $val
  142004. **
  142005. ** The op is given by p->op. The xN is p->iCoord-th coordinate in
  142006. ** pCellData. $val is given by p->u.rValue.
  142007. */
  142008. static void rtreeLeafConstraint(
  142009. RtreeConstraint *p, /* The constraint to test */
  142010. int eInt, /* True if RTree holds integer coordinates */
  142011. u8 *pCellData, /* Raw cell content as appears on disk */
  142012. int *peWithin /* Adjust downward, as appropriate */
  142013. ){
  142014. RtreeDValue xN; /* Coordinate value converted to a double */
  142015. assert(p->op==RTREE_LE || p->op==RTREE_LT || p->op==RTREE_GE
  142016. || p->op==RTREE_GT || p->op==RTREE_EQ );
  142017. pCellData += 8 + p->iCoord*4;
  142018. RTREE_DECODE_COORD(eInt, pCellData, xN);
  142019. switch( p->op ){
  142020. case RTREE_LE: if( xN <= p->u.rValue ) return; break;
  142021. case RTREE_LT: if( xN < p->u.rValue ) return; break;
  142022. case RTREE_GE: if( xN >= p->u.rValue ) return; break;
  142023. case RTREE_GT: if( xN > p->u.rValue ) return; break;
  142024. default: if( xN == p->u.rValue ) return; break;
  142025. }
  142026. *peWithin = NOT_WITHIN;
  142027. }
  142028. /*
  142029. ** One of the cells in node pNode is guaranteed to have a 64-bit
  142030. ** integer value equal to iRowid. Return the index of this cell.
  142031. */
  142032. static int nodeRowidIndex(
  142033. Rtree *pRtree,
  142034. RtreeNode *pNode,
  142035. i64 iRowid,
  142036. int *piIndex
  142037. ){
  142038. int ii;
  142039. int nCell = NCELL(pNode);
  142040. assert( nCell<200 );
  142041. for(ii=0; ii<nCell; ii++){
  142042. if( nodeGetRowid(pRtree, pNode, ii)==iRowid ){
  142043. *piIndex = ii;
  142044. return SQLITE_OK;
  142045. }
  142046. }
  142047. return SQLITE_CORRUPT_VTAB;
  142048. }
  142049. /*
  142050. ** Return the index of the cell containing a pointer to node pNode
  142051. ** in its parent. If pNode is the root node, return -1.
  142052. */
  142053. static int nodeParentIndex(Rtree *pRtree, RtreeNode *pNode, int *piIndex){
  142054. RtreeNode *pParent = pNode->pParent;
  142055. if( pParent ){
  142056. return nodeRowidIndex(pRtree, pParent, pNode->iNode, piIndex);
  142057. }
  142058. *piIndex = -1;
  142059. return SQLITE_OK;
  142060. }
  142061. /*
  142062. ** Compare two search points. Return negative, zero, or positive if the first
  142063. ** is less than, equal to, or greater than the second.
  142064. **
  142065. ** The rScore is the primary key. Smaller rScore values come first.
  142066. ** If the rScore is a tie, then use iLevel as the tie breaker with smaller
  142067. ** iLevel values coming first. In this way, if rScore is the same for all
  142068. ** SearchPoints, then iLevel becomes the deciding factor and the result
  142069. ** is a depth-first search, which is the desired default behavior.
  142070. */
  142071. static int rtreeSearchPointCompare(
  142072. const RtreeSearchPoint *pA,
  142073. const RtreeSearchPoint *pB
  142074. ){
  142075. if( pA->rScore<pB->rScore ) return -1;
  142076. if( pA->rScore>pB->rScore ) return +1;
  142077. if( pA->iLevel<pB->iLevel ) return -1;
  142078. if( pA->iLevel>pB->iLevel ) return +1;
  142079. return 0;
  142080. }
  142081. /*
  142082. ** Interchange to search points in a cursor.
  142083. */
  142084. static void rtreeSearchPointSwap(RtreeCursor *p, int i, int j){
  142085. RtreeSearchPoint t = p->aPoint[i];
  142086. assert( i<j );
  142087. p->aPoint[i] = p->aPoint[j];
  142088. p->aPoint[j] = t;
  142089. i++; j++;
  142090. if( i<RTREE_CACHE_SZ ){
  142091. if( j>=RTREE_CACHE_SZ ){
  142092. nodeRelease(RTREE_OF_CURSOR(p), p->aNode[i]);
  142093. p->aNode[i] = 0;
  142094. }else{
  142095. RtreeNode *pTemp = p->aNode[i];
  142096. p->aNode[i] = p->aNode[j];
  142097. p->aNode[j] = pTemp;
  142098. }
  142099. }
  142100. }
  142101. /*
  142102. ** Return the search point with the lowest current score.
  142103. */
  142104. static RtreeSearchPoint *rtreeSearchPointFirst(RtreeCursor *pCur){
  142105. return pCur->bPoint ? &pCur->sPoint : pCur->nPoint ? pCur->aPoint : 0;
  142106. }
  142107. /*
  142108. ** Get the RtreeNode for the search point with the lowest score.
  142109. */
  142110. static RtreeNode *rtreeNodeOfFirstSearchPoint(RtreeCursor *pCur, int *pRC){
  142111. sqlite3_int64 id;
  142112. int ii = 1 - pCur->bPoint;
  142113. assert( ii==0 || ii==1 );
  142114. assert( pCur->bPoint || pCur->nPoint );
  142115. if( pCur->aNode[ii]==0 ){
  142116. assert( pRC!=0 );
  142117. id = ii ? pCur->aPoint[0].id : pCur->sPoint.id;
  142118. *pRC = nodeAcquire(RTREE_OF_CURSOR(pCur), id, 0, &pCur->aNode[ii]);
  142119. }
  142120. return pCur->aNode[ii];
  142121. }
  142122. /*
  142123. ** Push a new element onto the priority queue
  142124. */
  142125. static RtreeSearchPoint *rtreeEnqueue(
  142126. RtreeCursor *pCur, /* The cursor */
  142127. RtreeDValue rScore, /* Score for the new search point */
  142128. u8 iLevel /* Level for the new search point */
  142129. ){
  142130. int i, j;
  142131. RtreeSearchPoint *pNew;
  142132. if( pCur->nPoint>=pCur->nPointAlloc ){
  142133. int nNew = pCur->nPointAlloc*2 + 8;
  142134. pNew = sqlite3_realloc(pCur->aPoint, nNew*sizeof(pCur->aPoint[0]));
  142135. if( pNew==0 ) return 0;
  142136. pCur->aPoint = pNew;
  142137. pCur->nPointAlloc = nNew;
  142138. }
  142139. i = pCur->nPoint++;
  142140. pNew = pCur->aPoint + i;
  142141. pNew->rScore = rScore;
  142142. pNew->iLevel = iLevel;
  142143. assert( iLevel<=RTREE_MAX_DEPTH );
  142144. while( i>0 ){
  142145. RtreeSearchPoint *pParent;
  142146. j = (i-1)/2;
  142147. pParent = pCur->aPoint + j;
  142148. if( rtreeSearchPointCompare(pNew, pParent)>=0 ) break;
  142149. rtreeSearchPointSwap(pCur, j, i);
  142150. i = j;
  142151. pNew = pParent;
  142152. }
  142153. return pNew;
  142154. }
  142155. /*
  142156. ** Allocate a new RtreeSearchPoint and return a pointer to it. Return
  142157. ** NULL if malloc fails.
  142158. */
  142159. static RtreeSearchPoint *rtreeSearchPointNew(
  142160. RtreeCursor *pCur, /* The cursor */
  142161. RtreeDValue rScore, /* Score for the new search point */
  142162. u8 iLevel /* Level for the new search point */
  142163. ){
  142164. RtreeSearchPoint *pNew, *pFirst;
  142165. pFirst = rtreeSearchPointFirst(pCur);
  142166. pCur->anQueue[iLevel]++;
  142167. if( pFirst==0
  142168. || pFirst->rScore>rScore
  142169. || (pFirst->rScore==rScore && pFirst->iLevel>iLevel)
  142170. ){
  142171. if( pCur->bPoint ){
  142172. int ii;
  142173. pNew = rtreeEnqueue(pCur, rScore, iLevel);
  142174. if( pNew==0 ) return 0;
  142175. ii = (int)(pNew - pCur->aPoint) + 1;
  142176. if( ii<RTREE_CACHE_SZ ){
  142177. assert( pCur->aNode[ii]==0 );
  142178. pCur->aNode[ii] = pCur->aNode[0];
  142179. }else{
  142180. nodeRelease(RTREE_OF_CURSOR(pCur), pCur->aNode[0]);
  142181. }
  142182. pCur->aNode[0] = 0;
  142183. *pNew = pCur->sPoint;
  142184. }
  142185. pCur->sPoint.rScore = rScore;
  142186. pCur->sPoint.iLevel = iLevel;
  142187. pCur->bPoint = 1;
  142188. return &pCur->sPoint;
  142189. }else{
  142190. return rtreeEnqueue(pCur, rScore, iLevel);
  142191. }
  142192. }
  142193. #if 0
  142194. /* Tracing routines for the RtreeSearchPoint queue */
  142195. static void tracePoint(RtreeSearchPoint *p, int idx, RtreeCursor *pCur){
  142196. if( idx<0 ){ printf(" s"); }else{ printf("%2d", idx); }
  142197. printf(" %d.%05lld.%02d %g %d",
  142198. p->iLevel, p->id, p->iCell, p->rScore, p->eWithin
  142199. );
  142200. idx++;
  142201. if( idx<RTREE_CACHE_SZ ){
  142202. printf(" %p\n", pCur->aNode[idx]);
  142203. }else{
  142204. printf("\n");
  142205. }
  142206. }
  142207. static void traceQueue(RtreeCursor *pCur, const char *zPrefix){
  142208. int ii;
  142209. printf("=== %9s ", zPrefix);
  142210. if( pCur->bPoint ){
  142211. tracePoint(&pCur->sPoint, -1, pCur);
  142212. }
  142213. for(ii=0; ii<pCur->nPoint; ii++){
  142214. if( ii>0 || pCur->bPoint ) printf(" ");
  142215. tracePoint(&pCur->aPoint[ii], ii, pCur);
  142216. }
  142217. }
  142218. # define RTREE_QUEUE_TRACE(A,B) traceQueue(A,B)
  142219. #else
  142220. # define RTREE_QUEUE_TRACE(A,B) /* no-op */
  142221. #endif
  142222. /* Remove the search point with the lowest current score.
  142223. */
  142224. static void rtreeSearchPointPop(RtreeCursor *p){
  142225. int i, j, k, n;
  142226. i = 1 - p->bPoint;
  142227. assert( i==0 || i==1 );
  142228. if( p->aNode[i] ){
  142229. nodeRelease(RTREE_OF_CURSOR(p), p->aNode[i]);
  142230. p->aNode[i] = 0;
  142231. }
  142232. if( p->bPoint ){
  142233. p->anQueue[p->sPoint.iLevel]--;
  142234. p->bPoint = 0;
  142235. }else if( p->nPoint ){
  142236. p->anQueue[p->aPoint[0].iLevel]--;
  142237. n = --p->nPoint;
  142238. p->aPoint[0] = p->aPoint[n];
  142239. if( n<RTREE_CACHE_SZ-1 ){
  142240. p->aNode[1] = p->aNode[n+1];
  142241. p->aNode[n+1] = 0;
  142242. }
  142243. i = 0;
  142244. while( (j = i*2+1)<n ){
  142245. k = j+1;
  142246. if( k<n && rtreeSearchPointCompare(&p->aPoint[k], &p->aPoint[j])<0 ){
  142247. if( rtreeSearchPointCompare(&p->aPoint[k], &p->aPoint[i])<0 ){
  142248. rtreeSearchPointSwap(p, i, k);
  142249. i = k;
  142250. }else{
  142251. break;
  142252. }
  142253. }else{
  142254. if( rtreeSearchPointCompare(&p->aPoint[j], &p->aPoint[i])<0 ){
  142255. rtreeSearchPointSwap(p, i, j);
  142256. i = j;
  142257. }else{
  142258. break;
  142259. }
  142260. }
  142261. }
  142262. }
  142263. }
  142264. /*
  142265. ** Continue the search on cursor pCur until the front of the queue
  142266. ** contains an entry suitable for returning as a result-set row,
  142267. ** or until the RtreeSearchPoint queue is empty, indicating that the
  142268. ** query has completed.
  142269. */
  142270. static int rtreeStepToLeaf(RtreeCursor *pCur){
  142271. RtreeSearchPoint *p;
  142272. Rtree *pRtree = RTREE_OF_CURSOR(pCur);
  142273. RtreeNode *pNode;
  142274. int eWithin;
  142275. int rc = SQLITE_OK;
  142276. int nCell;
  142277. int nConstraint = pCur->nConstraint;
  142278. int ii;
  142279. int eInt;
  142280. RtreeSearchPoint x;
  142281. eInt = pRtree->eCoordType==RTREE_COORD_INT32;
  142282. while( (p = rtreeSearchPointFirst(pCur))!=0 && p->iLevel>0 ){
  142283. pNode = rtreeNodeOfFirstSearchPoint(pCur, &rc);
  142284. if( rc ) return rc;
  142285. nCell = NCELL(pNode);
  142286. assert( nCell<200 );
  142287. while( p->iCell<nCell ){
  142288. sqlite3_rtree_dbl rScore = (sqlite3_rtree_dbl)-1;
  142289. u8 *pCellData = pNode->zData + (4+pRtree->nBytesPerCell*p->iCell);
  142290. eWithin = FULLY_WITHIN;
  142291. for(ii=0; ii<nConstraint; ii++){
  142292. RtreeConstraint *pConstraint = pCur->aConstraint + ii;
  142293. if( pConstraint->op>=RTREE_MATCH ){
  142294. rc = rtreeCallbackConstraint(pConstraint, eInt, pCellData, p,
  142295. &rScore, &eWithin);
  142296. if( rc ) return rc;
  142297. }else if( p->iLevel==1 ){
  142298. rtreeLeafConstraint(pConstraint, eInt, pCellData, &eWithin);
  142299. }else{
  142300. rtreeNonleafConstraint(pConstraint, eInt, pCellData, &eWithin);
  142301. }
  142302. if( eWithin==NOT_WITHIN ) break;
  142303. }
  142304. p->iCell++;
  142305. if( eWithin==NOT_WITHIN ) continue;
  142306. x.iLevel = p->iLevel - 1;
  142307. if( x.iLevel ){
  142308. x.id = readInt64(pCellData);
  142309. x.iCell = 0;
  142310. }else{
  142311. x.id = p->id;
  142312. x.iCell = p->iCell - 1;
  142313. }
  142314. if( p->iCell>=nCell ){
  142315. RTREE_QUEUE_TRACE(pCur, "POP-S:");
  142316. rtreeSearchPointPop(pCur);
  142317. }
  142318. if( rScore<RTREE_ZERO ) rScore = RTREE_ZERO;
  142319. p = rtreeSearchPointNew(pCur, rScore, x.iLevel);
  142320. if( p==0 ) return SQLITE_NOMEM;
  142321. p->eWithin = eWithin;
  142322. p->id = x.id;
  142323. p->iCell = x.iCell;
  142324. RTREE_QUEUE_TRACE(pCur, "PUSH-S:");
  142325. break;
  142326. }
  142327. if( p->iCell>=nCell ){
  142328. RTREE_QUEUE_TRACE(pCur, "POP-Se:");
  142329. rtreeSearchPointPop(pCur);
  142330. }
  142331. }
  142332. pCur->atEOF = p==0;
  142333. return SQLITE_OK;
  142334. }
  142335. /*
  142336. ** Rtree virtual table module xNext method.
  142337. */
  142338. static int rtreeNext(sqlite3_vtab_cursor *pVtabCursor){
  142339. RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;
  142340. int rc = SQLITE_OK;
  142341. /* Move to the next entry that matches the configured constraints. */
  142342. RTREE_QUEUE_TRACE(pCsr, "POP-Nx:");
  142343. rtreeSearchPointPop(pCsr);
  142344. rc = rtreeStepToLeaf(pCsr);
  142345. return rc;
  142346. }
  142347. /*
  142348. ** Rtree virtual table module xRowid method.
  142349. */
  142350. static int rtreeRowid(sqlite3_vtab_cursor *pVtabCursor, sqlite_int64 *pRowid){
  142351. RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;
  142352. RtreeSearchPoint *p = rtreeSearchPointFirst(pCsr);
  142353. int rc = SQLITE_OK;
  142354. RtreeNode *pNode = rtreeNodeOfFirstSearchPoint(pCsr, &rc);
  142355. if( rc==SQLITE_OK && p ){
  142356. *pRowid = nodeGetRowid(RTREE_OF_CURSOR(pCsr), pNode, p->iCell);
  142357. }
  142358. return rc;
  142359. }
  142360. /*
  142361. ** Rtree virtual table module xColumn method.
  142362. */
  142363. static int rtreeColumn(sqlite3_vtab_cursor *cur, sqlite3_context *ctx, int i){
  142364. Rtree *pRtree = (Rtree *)cur->pVtab;
  142365. RtreeCursor *pCsr = (RtreeCursor *)cur;
  142366. RtreeSearchPoint *p = rtreeSearchPointFirst(pCsr);
  142367. RtreeCoord c;
  142368. int rc = SQLITE_OK;
  142369. RtreeNode *pNode = rtreeNodeOfFirstSearchPoint(pCsr, &rc);
  142370. if( rc ) return rc;
  142371. if( p==0 ) return SQLITE_OK;
  142372. if( i==0 ){
  142373. sqlite3_result_int64(ctx, nodeGetRowid(pRtree, pNode, p->iCell));
  142374. }else{
  142375. if( rc ) return rc;
  142376. nodeGetCoord(pRtree, pNode, p->iCell, i-1, &c);
  142377. #ifndef SQLITE_RTREE_INT_ONLY
  142378. if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
  142379. sqlite3_result_double(ctx, c.f);
  142380. }else
  142381. #endif
  142382. {
  142383. assert( pRtree->eCoordType==RTREE_COORD_INT32 );
  142384. sqlite3_result_int(ctx, c.i);
  142385. }
  142386. }
  142387. return SQLITE_OK;
  142388. }
  142389. /*
  142390. ** Use nodeAcquire() to obtain the leaf node containing the record with
  142391. ** rowid iRowid. If successful, set *ppLeaf to point to the node and
  142392. ** return SQLITE_OK. If there is no such record in the table, set
  142393. ** *ppLeaf to 0 and return SQLITE_OK. If an error occurs, set *ppLeaf
  142394. ** to zero and return an SQLite error code.
  142395. */
  142396. static int findLeafNode(
  142397. Rtree *pRtree, /* RTree to search */
  142398. i64 iRowid, /* The rowid searching for */
  142399. RtreeNode **ppLeaf, /* Write the node here */
  142400. sqlite3_int64 *piNode /* Write the node-id here */
  142401. ){
  142402. int rc;
  142403. *ppLeaf = 0;
  142404. sqlite3_bind_int64(pRtree->pReadRowid, 1, iRowid);
  142405. if( sqlite3_step(pRtree->pReadRowid)==SQLITE_ROW ){
  142406. i64 iNode = sqlite3_column_int64(pRtree->pReadRowid, 0);
  142407. if( piNode ) *piNode = iNode;
  142408. rc = nodeAcquire(pRtree, iNode, 0, ppLeaf);
  142409. sqlite3_reset(pRtree->pReadRowid);
  142410. }else{
  142411. rc = sqlite3_reset(pRtree->pReadRowid);
  142412. }
  142413. return rc;
  142414. }
  142415. /*
  142416. ** This function is called to configure the RtreeConstraint object passed
  142417. ** as the second argument for a MATCH constraint. The value passed as the
  142418. ** first argument to this function is the right-hand operand to the MATCH
  142419. ** operator.
  142420. */
  142421. static int deserializeGeometry(sqlite3_value *pValue, RtreeConstraint *pCons){
  142422. RtreeMatchArg *pBlob; /* BLOB returned by geometry function */
  142423. sqlite3_rtree_query_info *pInfo; /* Callback information */
  142424. int nBlob; /* Size of the geometry function blob */
  142425. int nExpected; /* Expected size of the BLOB */
  142426. /* Check that value is actually a blob. */
  142427. if( sqlite3_value_type(pValue)!=SQLITE_BLOB ) return SQLITE_ERROR;
  142428. /* Check that the blob is roughly the right size. */
  142429. nBlob = sqlite3_value_bytes(pValue);
  142430. if( nBlob<(int)sizeof(RtreeMatchArg)
  142431. || ((nBlob-sizeof(RtreeMatchArg))%sizeof(RtreeDValue))!=0
  142432. ){
  142433. return SQLITE_ERROR;
  142434. }
  142435. pInfo = (sqlite3_rtree_query_info*)sqlite3_malloc( sizeof(*pInfo)+nBlob );
  142436. if( !pInfo ) return SQLITE_NOMEM;
  142437. memset(pInfo, 0, sizeof(*pInfo));
  142438. pBlob = (RtreeMatchArg*)&pInfo[1];
  142439. memcpy(pBlob, sqlite3_value_blob(pValue), nBlob);
  142440. nExpected = (int)(sizeof(RtreeMatchArg) +
  142441. (pBlob->nParam-1)*sizeof(RtreeDValue));
  142442. if( pBlob->magic!=RTREE_GEOMETRY_MAGIC || nBlob!=nExpected ){
  142443. sqlite3_free(pInfo);
  142444. return SQLITE_ERROR;
  142445. }
  142446. pInfo->pContext = pBlob->cb.pContext;
  142447. pInfo->nParam = pBlob->nParam;
  142448. pInfo->aParam = pBlob->aParam;
  142449. if( pBlob->cb.xGeom ){
  142450. pCons->u.xGeom = pBlob->cb.xGeom;
  142451. }else{
  142452. pCons->op = RTREE_QUERY;
  142453. pCons->u.xQueryFunc = pBlob->cb.xQueryFunc;
  142454. }
  142455. pCons->pInfo = pInfo;
  142456. return SQLITE_OK;
  142457. }
  142458. /*
  142459. ** Rtree virtual table module xFilter method.
  142460. */
  142461. static int rtreeFilter(
  142462. sqlite3_vtab_cursor *pVtabCursor,
  142463. int idxNum, const char *idxStr,
  142464. int argc, sqlite3_value **argv
  142465. ){
  142466. Rtree *pRtree = (Rtree *)pVtabCursor->pVtab;
  142467. RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;
  142468. RtreeNode *pRoot = 0;
  142469. int ii;
  142470. int rc = SQLITE_OK;
  142471. int iCell = 0;
  142472. rtreeReference(pRtree);
  142473. /* Reset the cursor to the same state as rtreeOpen() leaves it in. */
  142474. freeCursorConstraints(pCsr);
  142475. sqlite3_free(pCsr->aPoint);
  142476. memset(pCsr, 0, sizeof(RtreeCursor));
  142477. pCsr->base.pVtab = (sqlite3_vtab*)pRtree;
  142478. pCsr->iStrategy = idxNum;
  142479. if( idxNum==1 ){
  142480. /* Special case - lookup by rowid. */
  142481. RtreeNode *pLeaf; /* Leaf on which the required cell resides */
  142482. RtreeSearchPoint *p; /* Search point for the the leaf */
  142483. i64 iRowid = sqlite3_value_int64(argv[0]);
  142484. i64 iNode = 0;
  142485. rc = findLeafNode(pRtree, iRowid, &pLeaf, &iNode);
  142486. if( rc==SQLITE_OK && pLeaf!=0 ){
  142487. p = rtreeSearchPointNew(pCsr, RTREE_ZERO, 0);
  142488. assert( p!=0 ); /* Always returns pCsr->sPoint */
  142489. pCsr->aNode[0] = pLeaf;
  142490. p->id = iNode;
  142491. p->eWithin = PARTLY_WITHIN;
  142492. rc = nodeRowidIndex(pRtree, pLeaf, iRowid, &iCell);
  142493. p->iCell = iCell;
  142494. RTREE_QUEUE_TRACE(pCsr, "PUSH-F1:");
  142495. }else{
  142496. pCsr->atEOF = 1;
  142497. }
  142498. }else{
  142499. /* Normal case - r-tree scan. Set up the RtreeCursor.aConstraint array
  142500. ** with the configured constraints.
  142501. */
  142502. rc = nodeAcquire(pRtree, 1, 0, &pRoot);
  142503. if( rc==SQLITE_OK && argc>0 ){
  142504. pCsr->aConstraint = sqlite3_malloc(sizeof(RtreeConstraint)*argc);
  142505. pCsr->nConstraint = argc;
  142506. if( !pCsr->aConstraint ){
  142507. rc = SQLITE_NOMEM;
  142508. }else{
  142509. memset(pCsr->aConstraint, 0, sizeof(RtreeConstraint)*argc);
  142510. memset(pCsr->anQueue, 0, sizeof(u32)*(pRtree->iDepth + 1));
  142511. assert( (idxStr==0 && argc==0)
  142512. || (idxStr && (int)strlen(idxStr)==argc*2) );
  142513. for(ii=0; ii<argc; ii++){
  142514. RtreeConstraint *p = &pCsr->aConstraint[ii];
  142515. p->op = idxStr[ii*2];
  142516. p->iCoord = idxStr[ii*2+1]-'0';
  142517. if( p->op>=RTREE_MATCH ){
  142518. /* A MATCH operator. The right-hand-side must be a blob that
  142519. ** can be cast into an RtreeMatchArg object. One created using
  142520. ** an sqlite3_rtree_geometry_callback() SQL user function.
  142521. */
  142522. rc = deserializeGeometry(argv[ii], p);
  142523. if( rc!=SQLITE_OK ){
  142524. break;
  142525. }
  142526. p->pInfo->nCoord = pRtree->nDim*2;
  142527. p->pInfo->anQueue = pCsr->anQueue;
  142528. p->pInfo->mxLevel = pRtree->iDepth + 1;
  142529. }else{
  142530. #ifdef SQLITE_RTREE_INT_ONLY
  142531. p->u.rValue = sqlite3_value_int64(argv[ii]);
  142532. #else
  142533. p->u.rValue = sqlite3_value_double(argv[ii]);
  142534. #endif
  142535. }
  142536. }
  142537. }
  142538. }
  142539. if( rc==SQLITE_OK ){
  142540. RtreeSearchPoint *pNew;
  142541. pNew = rtreeSearchPointNew(pCsr, RTREE_ZERO, pRtree->iDepth+1);
  142542. if( pNew==0 ) return SQLITE_NOMEM;
  142543. pNew->id = 1;
  142544. pNew->iCell = 0;
  142545. pNew->eWithin = PARTLY_WITHIN;
  142546. assert( pCsr->bPoint==1 );
  142547. pCsr->aNode[0] = pRoot;
  142548. pRoot = 0;
  142549. RTREE_QUEUE_TRACE(pCsr, "PUSH-Fm:");
  142550. rc = rtreeStepToLeaf(pCsr);
  142551. }
  142552. }
  142553. nodeRelease(pRtree, pRoot);
  142554. rtreeRelease(pRtree);
  142555. return rc;
  142556. }
  142557. /*
  142558. ** Set the pIdxInfo->estimatedRows variable to nRow. Unless this
  142559. ** extension is currently being used by a version of SQLite too old to
  142560. ** support estimatedRows. In that case this function is a no-op.
  142561. */
  142562. static void setEstimatedRows(sqlite3_index_info *pIdxInfo, i64 nRow){
  142563. #if SQLITE_VERSION_NUMBER>=3008002
  142564. if( sqlite3_libversion_number()>=3008002 ){
  142565. pIdxInfo->estimatedRows = nRow;
  142566. }
  142567. #endif
  142568. }
  142569. /*
  142570. ** Rtree virtual table module xBestIndex method. There are three
  142571. ** table scan strategies to choose from (in order from most to
  142572. ** least desirable):
  142573. **
  142574. ** idxNum idxStr Strategy
  142575. ** ------------------------------------------------
  142576. ** 1 Unused Direct lookup by rowid.
  142577. ** 2 See below R-tree query or full-table scan.
  142578. ** ------------------------------------------------
  142579. **
  142580. ** If strategy 1 is used, then idxStr is not meaningful. If strategy
  142581. ** 2 is used, idxStr is formatted to contain 2 bytes for each
  142582. ** constraint used. The first two bytes of idxStr correspond to
  142583. ** the constraint in sqlite3_index_info.aConstraintUsage[] with
  142584. ** (argvIndex==1) etc.
  142585. **
  142586. ** The first of each pair of bytes in idxStr identifies the constraint
  142587. ** operator as follows:
  142588. **
  142589. ** Operator Byte Value
  142590. ** ----------------------
  142591. ** = 0x41 ('A')
  142592. ** <= 0x42 ('B')
  142593. ** < 0x43 ('C')
  142594. ** >= 0x44 ('D')
  142595. ** > 0x45 ('E')
  142596. ** MATCH 0x46 ('F')
  142597. ** ----------------------
  142598. **
  142599. ** The second of each pair of bytes identifies the coordinate column
  142600. ** to which the constraint applies. The leftmost coordinate column
  142601. ** is 'a', the second from the left 'b' etc.
  142602. */
  142603. static int rtreeBestIndex(sqlite3_vtab *tab, sqlite3_index_info *pIdxInfo){
  142604. Rtree *pRtree = (Rtree*)tab;
  142605. int rc = SQLITE_OK;
  142606. int ii;
  142607. i64 nRow; /* Estimated rows returned by this scan */
  142608. int iIdx = 0;
  142609. char zIdxStr[RTREE_MAX_DIMENSIONS*8+1];
  142610. memset(zIdxStr, 0, sizeof(zIdxStr));
  142611. assert( pIdxInfo->idxStr==0 );
  142612. for(ii=0; ii<pIdxInfo->nConstraint && iIdx<(int)(sizeof(zIdxStr)-1); ii++){
  142613. struct sqlite3_index_constraint *p = &pIdxInfo->aConstraint[ii];
  142614. if( p->usable && p->iColumn==0 && p->op==SQLITE_INDEX_CONSTRAINT_EQ ){
  142615. /* We have an equality constraint on the rowid. Use strategy 1. */
  142616. int jj;
  142617. for(jj=0; jj<ii; jj++){
  142618. pIdxInfo->aConstraintUsage[jj].argvIndex = 0;
  142619. pIdxInfo->aConstraintUsage[jj].omit = 0;
  142620. }
  142621. pIdxInfo->idxNum = 1;
  142622. pIdxInfo->aConstraintUsage[ii].argvIndex = 1;
  142623. pIdxInfo->aConstraintUsage[jj].omit = 1;
  142624. /* This strategy involves a two rowid lookups on an B-Tree structures
  142625. ** and then a linear search of an R-Tree node. This should be
  142626. ** considered almost as quick as a direct rowid lookup (for which
  142627. ** sqlite uses an internal cost of 0.0). It is expected to return
  142628. ** a single row.
  142629. */
  142630. pIdxInfo->estimatedCost = 30.0;
  142631. setEstimatedRows(pIdxInfo, 1);
  142632. return SQLITE_OK;
  142633. }
  142634. if( p->usable && (p->iColumn>0 || p->op==SQLITE_INDEX_CONSTRAINT_MATCH) ){
  142635. u8 op;
  142636. switch( p->op ){
  142637. case SQLITE_INDEX_CONSTRAINT_EQ: op = RTREE_EQ; break;
  142638. case SQLITE_INDEX_CONSTRAINT_GT: op = RTREE_GT; break;
  142639. case SQLITE_INDEX_CONSTRAINT_LE: op = RTREE_LE; break;
  142640. case SQLITE_INDEX_CONSTRAINT_LT: op = RTREE_LT; break;
  142641. case SQLITE_INDEX_CONSTRAINT_GE: op = RTREE_GE; break;
  142642. default:
  142643. assert( p->op==SQLITE_INDEX_CONSTRAINT_MATCH );
  142644. op = RTREE_MATCH;
  142645. break;
  142646. }
  142647. zIdxStr[iIdx++] = op;
  142648. zIdxStr[iIdx++] = p->iColumn - 1 + '0';
  142649. pIdxInfo->aConstraintUsage[ii].argvIndex = (iIdx/2);
  142650. pIdxInfo->aConstraintUsage[ii].omit = 1;
  142651. }
  142652. }
  142653. pIdxInfo->idxNum = 2;
  142654. pIdxInfo->needToFreeIdxStr = 1;
  142655. if( iIdx>0 && 0==(pIdxInfo->idxStr = sqlite3_mprintf("%s", zIdxStr)) ){
  142656. return SQLITE_NOMEM;
  142657. }
  142658. nRow = pRtree->nRowEst / (iIdx + 1);
  142659. pIdxInfo->estimatedCost = (double)6.0 * (double)nRow;
  142660. setEstimatedRows(pIdxInfo, nRow);
  142661. return rc;
  142662. }
  142663. /*
  142664. ** Return the N-dimensional volumn of the cell stored in *p.
  142665. */
  142666. static RtreeDValue cellArea(Rtree *pRtree, RtreeCell *p){
  142667. RtreeDValue area = (RtreeDValue)1;
  142668. int ii;
  142669. for(ii=0; ii<(pRtree->nDim*2); ii+=2){
  142670. area = (area * (DCOORD(p->aCoord[ii+1]) - DCOORD(p->aCoord[ii])));
  142671. }
  142672. return area;
  142673. }
  142674. /*
  142675. ** Return the margin length of cell p. The margin length is the sum
  142676. ** of the objects size in each dimension.
  142677. */
  142678. static RtreeDValue cellMargin(Rtree *pRtree, RtreeCell *p){
  142679. RtreeDValue margin = (RtreeDValue)0;
  142680. int ii;
  142681. for(ii=0; ii<(pRtree->nDim*2); ii+=2){
  142682. margin += (DCOORD(p->aCoord[ii+1]) - DCOORD(p->aCoord[ii]));
  142683. }
  142684. return margin;
  142685. }
  142686. /*
  142687. ** Store the union of cells p1 and p2 in p1.
  142688. */
  142689. static void cellUnion(Rtree *pRtree, RtreeCell *p1, RtreeCell *p2){
  142690. int ii;
  142691. if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
  142692. for(ii=0; ii<(pRtree->nDim*2); ii+=2){
  142693. p1->aCoord[ii].f = MIN(p1->aCoord[ii].f, p2->aCoord[ii].f);
  142694. p1->aCoord[ii+1].f = MAX(p1->aCoord[ii+1].f, p2->aCoord[ii+1].f);
  142695. }
  142696. }else{
  142697. for(ii=0; ii<(pRtree->nDim*2); ii+=2){
  142698. p1->aCoord[ii].i = MIN(p1->aCoord[ii].i, p2->aCoord[ii].i);
  142699. p1->aCoord[ii+1].i = MAX(p1->aCoord[ii+1].i, p2->aCoord[ii+1].i);
  142700. }
  142701. }
  142702. }
  142703. /*
  142704. ** Return true if the area covered by p2 is a subset of the area covered
  142705. ** by p1. False otherwise.
  142706. */
  142707. static int cellContains(Rtree *pRtree, RtreeCell *p1, RtreeCell *p2){
  142708. int ii;
  142709. int isInt = (pRtree->eCoordType==RTREE_COORD_INT32);
  142710. for(ii=0; ii<(pRtree->nDim*2); ii+=2){
  142711. RtreeCoord *a1 = &p1->aCoord[ii];
  142712. RtreeCoord *a2 = &p2->aCoord[ii];
  142713. if( (!isInt && (a2[0].f<a1[0].f || a2[1].f>a1[1].f))
  142714. || ( isInt && (a2[0].i<a1[0].i || a2[1].i>a1[1].i))
  142715. ){
  142716. return 0;
  142717. }
  142718. }
  142719. return 1;
  142720. }
  142721. /*
  142722. ** Return the amount cell p would grow by if it were unioned with pCell.
  142723. */
  142724. static RtreeDValue cellGrowth(Rtree *pRtree, RtreeCell *p, RtreeCell *pCell){
  142725. RtreeDValue area;
  142726. RtreeCell cell;
  142727. memcpy(&cell, p, sizeof(RtreeCell));
  142728. area = cellArea(pRtree, &cell);
  142729. cellUnion(pRtree, &cell, pCell);
  142730. return (cellArea(pRtree, &cell)-area);
  142731. }
  142732. static RtreeDValue cellOverlap(
  142733. Rtree *pRtree,
  142734. RtreeCell *p,
  142735. RtreeCell *aCell,
  142736. int nCell
  142737. ){
  142738. int ii;
  142739. RtreeDValue overlap = RTREE_ZERO;
  142740. for(ii=0; ii<nCell; ii++){
  142741. int jj;
  142742. RtreeDValue o = (RtreeDValue)1;
  142743. for(jj=0; jj<(pRtree->nDim*2); jj+=2){
  142744. RtreeDValue x1, x2;
  142745. x1 = MAX(DCOORD(p->aCoord[jj]), DCOORD(aCell[ii].aCoord[jj]));
  142746. x2 = MIN(DCOORD(p->aCoord[jj+1]), DCOORD(aCell[ii].aCoord[jj+1]));
  142747. if( x2<x1 ){
  142748. o = (RtreeDValue)0;
  142749. break;
  142750. }else{
  142751. o = o * (x2-x1);
  142752. }
  142753. }
  142754. overlap += o;
  142755. }
  142756. return overlap;
  142757. }
  142758. /*
  142759. ** This function implements the ChooseLeaf algorithm from Gutman[84].
  142760. ** ChooseSubTree in r*tree terminology.
  142761. */
  142762. static int ChooseLeaf(
  142763. Rtree *pRtree, /* Rtree table */
  142764. RtreeCell *pCell, /* Cell to insert into rtree */
  142765. int iHeight, /* Height of sub-tree rooted at pCell */
  142766. RtreeNode **ppLeaf /* OUT: Selected leaf page */
  142767. ){
  142768. int rc;
  142769. int ii;
  142770. RtreeNode *pNode;
  142771. rc = nodeAcquire(pRtree, 1, 0, &pNode);
  142772. for(ii=0; rc==SQLITE_OK && ii<(pRtree->iDepth-iHeight); ii++){
  142773. int iCell;
  142774. sqlite3_int64 iBest = 0;
  142775. RtreeDValue fMinGrowth = RTREE_ZERO;
  142776. RtreeDValue fMinArea = RTREE_ZERO;
  142777. int nCell = NCELL(pNode);
  142778. RtreeCell cell;
  142779. RtreeNode *pChild;
  142780. RtreeCell *aCell = 0;
  142781. /* Select the child node which will be enlarged the least if pCell
  142782. ** is inserted into it. Resolve ties by choosing the entry with
  142783. ** the smallest area.
  142784. */
  142785. for(iCell=0; iCell<nCell; iCell++){
  142786. int bBest = 0;
  142787. RtreeDValue growth;
  142788. RtreeDValue area;
  142789. nodeGetCell(pRtree, pNode, iCell, &cell);
  142790. growth = cellGrowth(pRtree, &cell, pCell);
  142791. area = cellArea(pRtree, &cell);
  142792. if( iCell==0||growth<fMinGrowth||(growth==fMinGrowth && area<fMinArea) ){
  142793. bBest = 1;
  142794. }
  142795. if( bBest ){
  142796. fMinGrowth = growth;
  142797. fMinArea = area;
  142798. iBest = cell.iRowid;
  142799. }
  142800. }
  142801. sqlite3_free(aCell);
  142802. rc = nodeAcquire(pRtree, iBest, pNode, &pChild);
  142803. nodeRelease(pRtree, pNode);
  142804. pNode = pChild;
  142805. }
  142806. *ppLeaf = pNode;
  142807. return rc;
  142808. }
  142809. /*
  142810. ** A cell with the same content as pCell has just been inserted into
  142811. ** the node pNode. This function updates the bounding box cells in
  142812. ** all ancestor elements.
  142813. */
  142814. static int AdjustTree(
  142815. Rtree *pRtree, /* Rtree table */
  142816. RtreeNode *pNode, /* Adjust ancestry of this node. */
  142817. RtreeCell *pCell /* This cell was just inserted */
  142818. ){
  142819. RtreeNode *p = pNode;
  142820. while( p->pParent ){
  142821. RtreeNode *pParent = p->pParent;
  142822. RtreeCell cell;
  142823. int iCell;
  142824. if( nodeParentIndex(pRtree, p, &iCell) ){
  142825. return SQLITE_CORRUPT_VTAB;
  142826. }
  142827. nodeGetCell(pRtree, pParent, iCell, &cell);
  142828. if( !cellContains(pRtree, &cell, pCell) ){
  142829. cellUnion(pRtree, &cell, pCell);
  142830. nodeOverwriteCell(pRtree, pParent, &cell, iCell);
  142831. }
  142832. p = pParent;
  142833. }
  142834. return SQLITE_OK;
  142835. }
  142836. /*
  142837. ** Write mapping (iRowid->iNode) to the <rtree>_rowid table.
  142838. */
  142839. static int rowidWrite(Rtree *pRtree, sqlite3_int64 iRowid, sqlite3_int64 iNode){
  142840. sqlite3_bind_int64(pRtree->pWriteRowid, 1, iRowid);
  142841. sqlite3_bind_int64(pRtree->pWriteRowid, 2, iNode);
  142842. sqlite3_step(pRtree->pWriteRowid);
  142843. return sqlite3_reset(pRtree->pWriteRowid);
  142844. }
  142845. /*
  142846. ** Write mapping (iNode->iPar) to the <rtree>_parent table.
  142847. */
  142848. static int parentWrite(Rtree *pRtree, sqlite3_int64 iNode, sqlite3_int64 iPar){
  142849. sqlite3_bind_int64(pRtree->pWriteParent, 1, iNode);
  142850. sqlite3_bind_int64(pRtree->pWriteParent, 2, iPar);
  142851. sqlite3_step(pRtree->pWriteParent);
  142852. return sqlite3_reset(pRtree->pWriteParent);
  142853. }
  142854. static int rtreeInsertCell(Rtree *, RtreeNode *, RtreeCell *, int);
  142855. /*
  142856. ** Arguments aIdx, aDistance and aSpare all point to arrays of size
  142857. ** nIdx. The aIdx array contains the set of integers from 0 to
  142858. ** (nIdx-1) in no particular order. This function sorts the values
  142859. ** in aIdx according to the indexed values in aDistance. For
  142860. ** example, assuming the inputs:
  142861. **
  142862. ** aIdx = { 0, 1, 2, 3 }
  142863. ** aDistance = { 5.0, 2.0, 7.0, 6.0 }
  142864. **
  142865. ** this function sets the aIdx array to contain:
  142866. **
  142867. ** aIdx = { 0, 1, 2, 3 }
  142868. **
  142869. ** The aSpare array is used as temporary working space by the
  142870. ** sorting algorithm.
  142871. */
  142872. static void SortByDistance(
  142873. int *aIdx,
  142874. int nIdx,
  142875. RtreeDValue *aDistance,
  142876. int *aSpare
  142877. ){
  142878. if( nIdx>1 ){
  142879. int iLeft = 0;
  142880. int iRight = 0;
  142881. int nLeft = nIdx/2;
  142882. int nRight = nIdx-nLeft;
  142883. int *aLeft = aIdx;
  142884. int *aRight = &aIdx[nLeft];
  142885. SortByDistance(aLeft, nLeft, aDistance, aSpare);
  142886. SortByDistance(aRight, nRight, aDistance, aSpare);
  142887. memcpy(aSpare, aLeft, sizeof(int)*nLeft);
  142888. aLeft = aSpare;
  142889. while( iLeft<nLeft || iRight<nRight ){
  142890. if( iLeft==nLeft ){
  142891. aIdx[iLeft+iRight] = aRight[iRight];
  142892. iRight++;
  142893. }else if( iRight==nRight ){
  142894. aIdx[iLeft+iRight] = aLeft[iLeft];
  142895. iLeft++;
  142896. }else{
  142897. RtreeDValue fLeft = aDistance[aLeft[iLeft]];
  142898. RtreeDValue fRight = aDistance[aRight[iRight]];
  142899. if( fLeft<fRight ){
  142900. aIdx[iLeft+iRight] = aLeft[iLeft];
  142901. iLeft++;
  142902. }else{
  142903. aIdx[iLeft+iRight] = aRight[iRight];
  142904. iRight++;
  142905. }
  142906. }
  142907. }
  142908. #if 0
  142909. /* Check that the sort worked */
  142910. {
  142911. int jj;
  142912. for(jj=1; jj<nIdx; jj++){
  142913. RtreeDValue left = aDistance[aIdx[jj-1]];
  142914. RtreeDValue right = aDistance[aIdx[jj]];
  142915. assert( left<=right );
  142916. }
  142917. }
  142918. #endif
  142919. }
  142920. }
  142921. /*
  142922. ** Arguments aIdx, aCell and aSpare all point to arrays of size
  142923. ** nIdx. The aIdx array contains the set of integers from 0 to
  142924. ** (nIdx-1) in no particular order. This function sorts the values
  142925. ** in aIdx according to dimension iDim of the cells in aCell. The
  142926. ** minimum value of dimension iDim is considered first, the
  142927. ** maximum used to break ties.
  142928. **
  142929. ** The aSpare array is used as temporary working space by the
  142930. ** sorting algorithm.
  142931. */
  142932. static void SortByDimension(
  142933. Rtree *pRtree,
  142934. int *aIdx,
  142935. int nIdx,
  142936. int iDim,
  142937. RtreeCell *aCell,
  142938. int *aSpare
  142939. ){
  142940. if( nIdx>1 ){
  142941. int iLeft = 0;
  142942. int iRight = 0;
  142943. int nLeft = nIdx/2;
  142944. int nRight = nIdx-nLeft;
  142945. int *aLeft = aIdx;
  142946. int *aRight = &aIdx[nLeft];
  142947. SortByDimension(pRtree, aLeft, nLeft, iDim, aCell, aSpare);
  142948. SortByDimension(pRtree, aRight, nRight, iDim, aCell, aSpare);
  142949. memcpy(aSpare, aLeft, sizeof(int)*nLeft);
  142950. aLeft = aSpare;
  142951. while( iLeft<nLeft || iRight<nRight ){
  142952. RtreeDValue xleft1 = DCOORD(aCell[aLeft[iLeft]].aCoord[iDim*2]);
  142953. RtreeDValue xleft2 = DCOORD(aCell[aLeft[iLeft]].aCoord[iDim*2+1]);
  142954. RtreeDValue xright1 = DCOORD(aCell[aRight[iRight]].aCoord[iDim*2]);
  142955. RtreeDValue xright2 = DCOORD(aCell[aRight[iRight]].aCoord[iDim*2+1]);
  142956. if( (iLeft!=nLeft) && ((iRight==nRight)
  142957. || (xleft1<xright1)
  142958. || (xleft1==xright1 && xleft2<xright2)
  142959. )){
  142960. aIdx[iLeft+iRight] = aLeft[iLeft];
  142961. iLeft++;
  142962. }else{
  142963. aIdx[iLeft+iRight] = aRight[iRight];
  142964. iRight++;
  142965. }
  142966. }
  142967. #if 0
  142968. /* Check that the sort worked */
  142969. {
  142970. int jj;
  142971. for(jj=1; jj<nIdx; jj++){
  142972. RtreeDValue xleft1 = aCell[aIdx[jj-1]].aCoord[iDim*2];
  142973. RtreeDValue xleft2 = aCell[aIdx[jj-1]].aCoord[iDim*2+1];
  142974. RtreeDValue xright1 = aCell[aIdx[jj]].aCoord[iDim*2];
  142975. RtreeDValue xright2 = aCell[aIdx[jj]].aCoord[iDim*2+1];
  142976. assert( xleft1<=xright1 && (xleft1<xright1 || xleft2<=xright2) );
  142977. }
  142978. }
  142979. #endif
  142980. }
  142981. }
  142982. /*
  142983. ** Implementation of the R*-tree variant of SplitNode from Beckman[1990].
  142984. */
  142985. static int splitNodeStartree(
  142986. Rtree *pRtree,
  142987. RtreeCell *aCell,
  142988. int nCell,
  142989. RtreeNode *pLeft,
  142990. RtreeNode *pRight,
  142991. RtreeCell *pBboxLeft,
  142992. RtreeCell *pBboxRight
  142993. ){
  142994. int **aaSorted;
  142995. int *aSpare;
  142996. int ii;
  142997. int iBestDim = 0;
  142998. int iBestSplit = 0;
  142999. RtreeDValue fBestMargin = RTREE_ZERO;
  143000. int nByte = (pRtree->nDim+1)*(sizeof(int*)+nCell*sizeof(int));
  143001. aaSorted = (int **)sqlite3_malloc(nByte);
  143002. if( !aaSorted ){
  143003. return SQLITE_NOMEM;
  143004. }
  143005. aSpare = &((int *)&aaSorted[pRtree->nDim])[pRtree->nDim*nCell];
  143006. memset(aaSorted, 0, nByte);
  143007. for(ii=0; ii<pRtree->nDim; ii++){
  143008. int jj;
  143009. aaSorted[ii] = &((int *)&aaSorted[pRtree->nDim])[ii*nCell];
  143010. for(jj=0; jj<nCell; jj++){
  143011. aaSorted[ii][jj] = jj;
  143012. }
  143013. SortByDimension(pRtree, aaSorted[ii], nCell, ii, aCell, aSpare);
  143014. }
  143015. for(ii=0; ii<pRtree->nDim; ii++){
  143016. RtreeDValue margin = RTREE_ZERO;
  143017. RtreeDValue fBestOverlap = RTREE_ZERO;
  143018. RtreeDValue fBestArea = RTREE_ZERO;
  143019. int iBestLeft = 0;
  143020. int nLeft;
  143021. for(
  143022. nLeft=RTREE_MINCELLS(pRtree);
  143023. nLeft<=(nCell-RTREE_MINCELLS(pRtree));
  143024. nLeft++
  143025. ){
  143026. RtreeCell left;
  143027. RtreeCell right;
  143028. int kk;
  143029. RtreeDValue overlap;
  143030. RtreeDValue area;
  143031. memcpy(&left, &aCell[aaSorted[ii][0]], sizeof(RtreeCell));
  143032. memcpy(&right, &aCell[aaSorted[ii][nCell-1]], sizeof(RtreeCell));
  143033. for(kk=1; kk<(nCell-1); kk++){
  143034. if( kk<nLeft ){
  143035. cellUnion(pRtree, &left, &aCell[aaSorted[ii][kk]]);
  143036. }else{
  143037. cellUnion(pRtree, &right, &aCell[aaSorted[ii][kk]]);
  143038. }
  143039. }
  143040. margin += cellMargin(pRtree, &left);
  143041. margin += cellMargin(pRtree, &right);
  143042. overlap = cellOverlap(pRtree, &left, &right, 1);
  143043. area = cellArea(pRtree, &left) + cellArea(pRtree, &right);
  143044. if( (nLeft==RTREE_MINCELLS(pRtree))
  143045. || (overlap<fBestOverlap)
  143046. || (overlap==fBestOverlap && area<fBestArea)
  143047. ){
  143048. iBestLeft = nLeft;
  143049. fBestOverlap = overlap;
  143050. fBestArea = area;
  143051. }
  143052. }
  143053. if( ii==0 || margin<fBestMargin ){
  143054. iBestDim = ii;
  143055. fBestMargin = margin;
  143056. iBestSplit = iBestLeft;
  143057. }
  143058. }
  143059. memcpy(pBboxLeft, &aCell[aaSorted[iBestDim][0]], sizeof(RtreeCell));
  143060. memcpy(pBboxRight, &aCell[aaSorted[iBestDim][iBestSplit]], sizeof(RtreeCell));
  143061. for(ii=0; ii<nCell; ii++){
  143062. RtreeNode *pTarget = (ii<iBestSplit)?pLeft:pRight;
  143063. RtreeCell *pBbox = (ii<iBestSplit)?pBboxLeft:pBboxRight;
  143064. RtreeCell *pCell = &aCell[aaSorted[iBestDim][ii]];
  143065. nodeInsertCell(pRtree, pTarget, pCell);
  143066. cellUnion(pRtree, pBbox, pCell);
  143067. }
  143068. sqlite3_free(aaSorted);
  143069. return SQLITE_OK;
  143070. }
  143071. static int updateMapping(
  143072. Rtree *pRtree,
  143073. i64 iRowid,
  143074. RtreeNode *pNode,
  143075. int iHeight
  143076. ){
  143077. int (*xSetMapping)(Rtree *, sqlite3_int64, sqlite3_int64);
  143078. xSetMapping = ((iHeight==0)?rowidWrite:parentWrite);
  143079. if( iHeight>0 ){
  143080. RtreeNode *pChild = nodeHashLookup(pRtree, iRowid);
  143081. if( pChild ){
  143082. nodeRelease(pRtree, pChild->pParent);
  143083. nodeReference(pNode);
  143084. pChild->pParent = pNode;
  143085. }
  143086. }
  143087. return xSetMapping(pRtree, iRowid, pNode->iNode);
  143088. }
  143089. static int SplitNode(
  143090. Rtree *pRtree,
  143091. RtreeNode *pNode,
  143092. RtreeCell *pCell,
  143093. int iHeight
  143094. ){
  143095. int i;
  143096. int newCellIsRight = 0;
  143097. int rc = SQLITE_OK;
  143098. int nCell = NCELL(pNode);
  143099. RtreeCell *aCell;
  143100. int *aiUsed;
  143101. RtreeNode *pLeft = 0;
  143102. RtreeNode *pRight = 0;
  143103. RtreeCell leftbbox;
  143104. RtreeCell rightbbox;
  143105. /* Allocate an array and populate it with a copy of pCell and
  143106. ** all cells from node pLeft. Then zero the original node.
  143107. */
  143108. aCell = sqlite3_malloc((sizeof(RtreeCell)+sizeof(int))*(nCell+1));
  143109. if( !aCell ){
  143110. rc = SQLITE_NOMEM;
  143111. goto splitnode_out;
  143112. }
  143113. aiUsed = (int *)&aCell[nCell+1];
  143114. memset(aiUsed, 0, sizeof(int)*(nCell+1));
  143115. for(i=0; i<nCell; i++){
  143116. nodeGetCell(pRtree, pNode, i, &aCell[i]);
  143117. }
  143118. nodeZero(pRtree, pNode);
  143119. memcpy(&aCell[nCell], pCell, sizeof(RtreeCell));
  143120. nCell++;
  143121. if( pNode->iNode==1 ){
  143122. pRight = nodeNew(pRtree, pNode);
  143123. pLeft = nodeNew(pRtree, pNode);
  143124. pRtree->iDepth++;
  143125. pNode->isDirty = 1;
  143126. writeInt16(pNode->zData, pRtree->iDepth);
  143127. }else{
  143128. pLeft = pNode;
  143129. pRight = nodeNew(pRtree, pLeft->pParent);
  143130. nodeReference(pLeft);
  143131. }
  143132. if( !pLeft || !pRight ){
  143133. rc = SQLITE_NOMEM;
  143134. goto splitnode_out;
  143135. }
  143136. memset(pLeft->zData, 0, pRtree->iNodeSize);
  143137. memset(pRight->zData, 0, pRtree->iNodeSize);
  143138. rc = splitNodeStartree(pRtree, aCell, nCell, pLeft, pRight,
  143139. &leftbbox, &rightbbox);
  143140. if( rc!=SQLITE_OK ){
  143141. goto splitnode_out;
  143142. }
  143143. /* Ensure both child nodes have node numbers assigned to them by calling
  143144. ** nodeWrite(). Node pRight always needs a node number, as it was created
  143145. ** by nodeNew() above. But node pLeft sometimes already has a node number.
  143146. ** In this case avoid the all to nodeWrite().
  143147. */
  143148. if( SQLITE_OK!=(rc = nodeWrite(pRtree, pRight))
  143149. || (0==pLeft->iNode && SQLITE_OK!=(rc = nodeWrite(pRtree, pLeft)))
  143150. ){
  143151. goto splitnode_out;
  143152. }
  143153. rightbbox.iRowid = pRight->iNode;
  143154. leftbbox.iRowid = pLeft->iNode;
  143155. if( pNode->iNode==1 ){
  143156. rc = rtreeInsertCell(pRtree, pLeft->pParent, &leftbbox, iHeight+1);
  143157. if( rc!=SQLITE_OK ){
  143158. goto splitnode_out;
  143159. }
  143160. }else{
  143161. RtreeNode *pParent = pLeft->pParent;
  143162. int iCell;
  143163. rc = nodeParentIndex(pRtree, pLeft, &iCell);
  143164. if( rc==SQLITE_OK ){
  143165. nodeOverwriteCell(pRtree, pParent, &leftbbox, iCell);
  143166. rc = AdjustTree(pRtree, pParent, &leftbbox);
  143167. }
  143168. if( rc!=SQLITE_OK ){
  143169. goto splitnode_out;
  143170. }
  143171. }
  143172. if( (rc = rtreeInsertCell(pRtree, pRight->pParent, &rightbbox, iHeight+1)) ){
  143173. goto splitnode_out;
  143174. }
  143175. for(i=0; i<NCELL(pRight); i++){
  143176. i64 iRowid = nodeGetRowid(pRtree, pRight, i);
  143177. rc = updateMapping(pRtree, iRowid, pRight, iHeight);
  143178. if( iRowid==pCell->iRowid ){
  143179. newCellIsRight = 1;
  143180. }
  143181. if( rc!=SQLITE_OK ){
  143182. goto splitnode_out;
  143183. }
  143184. }
  143185. if( pNode->iNode==1 ){
  143186. for(i=0; i<NCELL(pLeft); i++){
  143187. i64 iRowid = nodeGetRowid(pRtree, pLeft, i);
  143188. rc = updateMapping(pRtree, iRowid, pLeft, iHeight);
  143189. if( rc!=SQLITE_OK ){
  143190. goto splitnode_out;
  143191. }
  143192. }
  143193. }else if( newCellIsRight==0 ){
  143194. rc = updateMapping(pRtree, pCell->iRowid, pLeft, iHeight);
  143195. }
  143196. if( rc==SQLITE_OK ){
  143197. rc = nodeRelease(pRtree, pRight);
  143198. pRight = 0;
  143199. }
  143200. if( rc==SQLITE_OK ){
  143201. rc = nodeRelease(pRtree, pLeft);
  143202. pLeft = 0;
  143203. }
  143204. splitnode_out:
  143205. nodeRelease(pRtree, pRight);
  143206. nodeRelease(pRtree, pLeft);
  143207. sqlite3_free(aCell);
  143208. return rc;
  143209. }
  143210. /*
  143211. ** If node pLeaf is not the root of the r-tree and its pParent pointer is
  143212. ** still NULL, load all ancestor nodes of pLeaf into memory and populate
  143213. ** the pLeaf->pParent chain all the way up to the root node.
  143214. **
  143215. ** This operation is required when a row is deleted (or updated - an update
  143216. ** is implemented as a delete followed by an insert). SQLite provides the
  143217. ** rowid of the row to delete, which can be used to find the leaf on which
  143218. ** the entry resides (argument pLeaf). Once the leaf is located, this
  143219. ** function is called to determine its ancestry.
  143220. */
  143221. static int fixLeafParent(Rtree *pRtree, RtreeNode *pLeaf){
  143222. int rc = SQLITE_OK;
  143223. RtreeNode *pChild = pLeaf;
  143224. while( rc==SQLITE_OK && pChild->iNode!=1 && pChild->pParent==0 ){
  143225. int rc2 = SQLITE_OK; /* sqlite3_reset() return code */
  143226. sqlite3_bind_int64(pRtree->pReadParent, 1, pChild->iNode);
  143227. rc = sqlite3_step(pRtree->pReadParent);
  143228. if( rc==SQLITE_ROW ){
  143229. RtreeNode *pTest; /* Used to test for reference loops */
  143230. i64 iNode; /* Node number of parent node */
  143231. /* Before setting pChild->pParent, test that we are not creating a
  143232. ** loop of references (as we would if, say, pChild==pParent). We don't
  143233. ** want to do this as it leads to a memory leak when trying to delete
  143234. ** the referenced counted node structures.
  143235. */
  143236. iNode = sqlite3_column_int64(pRtree->pReadParent, 0);
  143237. for(pTest=pLeaf; pTest && pTest->iNode!=iNode; pTest=pTest->pParent);
  143238. if( !pTest ){
  143239. rc2 = nodeAcquire(pRtree, iNode, 0, &pChild->pParent);
  143240. }
  143241. }
  143242. rc = sqlite3_reset(pRtree->pReadParent);
  143243. if( rc==SQLITE_OK ) rc = rc2;
  143244. if( rc==SQLITE_OK && !pChild->pParent ) rc = SQLITE_CORRUPT_VTAB;
  143245. pChild = pChild->pParent;
  143246. }
  143247. return rc;
  143248. }
  143249. static int deleteCell(Rtree *, RtreeNode *, int, int);
  143250. static int removeNode(Rtree *pRtree, RtreeNode *pNode, int iHeight){
  143251. int rc;
  143252. int rc2;
  143253. RtreeNode *pParent = 0;
  143254. int iCell;
  143255. assert( pNode->nRef==1 );
  143256. /* Remove the entry in the parent cell. */
  143257. rc = nodeParentIndex(pRtree, pNode, &iCell);
  143258. if( rc==SQLITE_OK ){
  143259. pParent = pNode->pParent;
  143260. pNode->pParent = 0;
  143261. rc = deleteCell(pRtree, pParent, iCell, iHeight+1);
  143262. }
  143263. rc2 = nodeRelease(pRtree, pParent);
  143264. if( rc==SQLITE_OK ){
  143265. rc = rc2;
  143266. }
  143267. if( rc!=SQLITE_OK ){
  143268. return rc;
  143269. }
  143270. /* Remove the xxx_node entry. */
  143271. sqlite3_bind_int64(pRtree->pDeleteNode, 1, pNode->iNode);
  143272. sqlite3_step(pRtree->pDeleteNode);
  143273. if( SQLITE_OK!=(rc = sqlite3_reset(pRtree->pDeleteNode)) ){
  143274. return rc;
  143275. }
  143276. /* Remove the xxx_parent entry. */
  143277. sqlite3_bind_int64(pRtree->pDeleteParent, 1, pNode->iNode);
  143278. sqlite3_step(pRtree->pDeleteParent);
  143279. if( SQLITE_OK!=(rc = sqlite3_reset(pRtree->pDeleteParent)) ){
  143280. return rc;
  143281. }
  143282. /* Remove the node from the in-memory hash table and link it into
  143283. ** the Rtree.pDeleted list. Its contents will be re-inserted later on.
  143284. */
  143285. nodeHashDelete(pRtree, pNode);
  143286. pNode->iNode = iHeight;
  143287. pNode->pNext = pRtree->pDeleted;
  143288. pNode->nRef++;
  143289. pRtree->pDeleted = pNode;
  143290. return SQLITE_OK;
  143291. }
  143292. static int fixBoundingBox(Rtree *pRtree, RtreeNode *pNode){
  143293. RtreeNode *pParent = pNode->pParent;
  143294. int rc = SQLITE_OK;
  143295. if( pParent ){
  143296. int ii;
  143297. int nCell = NCELL(pNode);
  143298. RtreeCell box; /* Bounding box for pNode */
  143299. nodeGetCell(pRtree, pNode, 0, &box);
  143300. for(ii=1; ii<nCell; ii++){
  143301. RtreeCell cell;
  143302. nodeGetCell(pRtree, pNode, ii, &cell);
  143303. cellUnion(pRtree, &box, &cell);
  143304. }
  143305. box.iRowid = pNode->iNode;
  143306. rc = nodeParentIndex(pRtree, pNode, &ii);
  143307. if( rc==SQLITE_OK ){
  143308. nodeOverwriteCell(pRtree, pParent, &box, ii);
  143309. rc = fixBoundingBox(pRtree, pParent);
  143310. }
  143311. }
  143312. return rc;
  143313. }
  143314. /*
  143315. ** Delete the cell at index iCell of node pNode. After removing the
  143316. ** cell, adjust the r-tree data structure if required.
  143317. */
  143318. static int deleteCell(Rtree *pRtree, RtreeNode *pNode, int iCell, int iHeight){
  143319. RtreeNode *pParent;
  143320. int rc;
  143321. if( SQLITE_OK!=(rc = fixLeafParent(pRtree, pNode)) ){
  143322. return rc;
  143323. }
  143324. /* Remove the cell from the node. This call just moves bytes around
  143325. ** the in-memory node image, so it cannot fail.
  143326. */
  143327. nodeDeleteCell(pRtree, pNode, iCell);
  143328. /* If the node is not the tree root and now has less than the minimum
  143329. ** number of cells, remove it from the tree. Otherwise, update the
  143330. ** cell in the parent node so that it tightly contains the updated
  143331. ** node.
  143332. */
  143333. pParent = pNode->pParent;
  143334. assert( pParent || pNode->iNode==1 );
  143335. if( pParent ){
  143336. if( NCELL(pNode)<RTREE_MINCELLS(pRtree) ){
  143337. rc = removeNode(pRtree, pNode, iHeight);
  143338. }else{
  143339. rc = fixBoundingBox(pRtree, pNode);
  143340. }
  143341. }
  143342. return rc;
  143343. }
  143344. static int Reinsert(
  143345. Rtree *pRtree,
  143346. RtreeNode *pNode,
  143347. RtreeCell *pCell,
  143348. int iHeight
  143349. ){
  143350. int *aOrder;
  143351. int *aSpare;
  143352. RtreeCell *aCell;
  143353. RtreeDValue *aDistance;
  143354. int nCell;
  143355. RtreeDValue aCenterCoord[RTREE_MAX_DIMENSIONS];
  143356. int iDim;
  143357. int ii;
  143358. int rc = SQLITE_OK;
  143359. int n;
  143360. memset(aCenterCoord, 0, sizeof(RtreeDValue)*RTREE_MAX_DIMENSIONS);
  143361. nCell = NCELL(pNode)+1;
  143362. n = (nCell+1)&(~1);
  143363. /* Allocate the buffers used by this operation. The allocation is
  143364. ** relinquished before this function returns.
  143365. */
  143366. aCell = (RtreeCell *)sqlite3_malloc(n * (
  143367. sizeof(RtreeCell) + /* aCell array */
  143368. sizeof(int) + /* aOrder array */
  143369. sizeof(int) + /* aSpare array */
  143370. sizeof(RtreeDValue) /* aDistance array */
  143371. ));
  143372. if( !aCell ){
  143373. return SQLITE_NOMEM;
  143374. }
  143375. aOrder = (int *)&aCell[n];
  143376. aSpare = (int *)&aOrder[n];
  143377. aDistance = (RtreeDValue *)&aSpare[n];
  143378. for(ii=0; ii<nCell; ii++){
  143379. if( ii==(nCell-1) ){
  143380. memcpy(&aCell[ii], pCell, sizeof(RtreeCell));
  143381. }else{
  143382. nodeGetCell(pRtree, pNode, ii, &aCell[ii]);
  143383. }
  143384. aOrder[ii] = ii;
  143385. for(iDim=0; iDim<pRtree->nDim; iDim++){
  143386. aCenterCoord[iDim] += DCOORD(aCell[ii].aCoord[iDim*2]);
  143387. aCenterCoord[iDim] += DCOORD(aCell[ii].aCoord[iDim*2+1]);
  143388. }
  143389. }
  143390. for(iDim=0; iDim<pRtree->nDim; iDim++){
  143391. aCenterCoord[iDim] = (aCenterCoord[iDim]/(nCell*(RtreeDValue)2));
  143392. }
  143393. for(ii=0; ii<nCell; ii++){
  143394. aDistance[ii] = RTREE_ZERO;
  143395. for(iDim=0; iDim<pRtree->nDim; iDim++){
  143396. RtreeDValue coord = (DCOORD(aCell[ii].aCoord[iDim*2+1]) -
  143397. DCOORD(aCell[ii].aCoord[iDim*2]));
  143398. aDistance[ii] += (coord-aCenterCoord[iDim])*(coord-aCenterCoord[iDim]);
  143399. }
  143400. }
  143401. SortByDistance(aOrder, nCell, aDistance, aSpare);
  143402. nodeZero(pRtree, pNode);
  143403. for(ii=0; rc==SQLITE_OK && ii<(nCell-(RTREE_MINCELLS(pRtree)+1)); ii++){
  143404. RtreeCell *p = &aCell[aOrder[ii]];
  143405. nodeInsertCell(pRtree, pNode, p);
  143406. if( p->iRowid==pCell->iRowid ){
  143407. if( iHeight==0 ){
  143408. rc = rowidWrite(pRtree, p->iRowid, pNode->iNode);
  143409. }else{
  143410. rc = parentWrite(pRtree, p->iRowid, pNode->iNode);
  143411. }
  143412. }
  143413. }
  143414. if( rc==SQLITE_OK ){
  143415. rc = fixBoundingBox(pRtree, pNode);
  143416. }
  143417. for(; rc==SQLITE_OK && ii<nCell; ii++){
  143418. /* Find a node to store this cell in. pNode->iNode currently contains
  143419. ** the height of the sub-tree headed by the cell.
  143420. */
  143421. RtreeNode *pInsert;
  143422. RtreeCell *p = &aCell[aOrder[ii]];
  143423. rc = ChooseLeaf(pRtree, p, iHeight, &pInsert);
  143424. if( rc==SQLITE_OK ){
  143425. int rc2;
  143426. rc = rtreeInsertCell(pRtree, pInsert, p, iHeight);
  143427. rc2 = nodeRelease(pRtree, pInsert);
  143428. if( rc==SQLITE_OK ){
  143429. rc = rc2;
  143430. }
  143431. }
  143432. }
  143433. sqlite3_free(aCell);
  143434. return rc;
  143435. }
  143436. /*
  143437. ** Insert cell pCell into node pNode. Node pNode is the head of a
  143438. ** subtree iHeight high (leaf nodes have iHeight==0).
  143439. */
  143440. static int rtreeInsertCell(
  143441. Rtree *pRtree,
  143442. RtreeNode *pNode,
  143443. RtreeCell *pCell,
  143444. int iHeight
  143445. ){
  143446. int rc = SQLITE_OK;
  143447. if( iHeight>0 ){
  143448. RtreeNode *pChild = nodeHashLookup(pRtree, pCell->iRowid);
  143449. if( pChild ){
  143450. nodeRelease(pRtree, pChild->pParent);
  143451. nodeReference(pNode);
  143452. pChild->pParent = pNode;
  143453. }
  143454. }
  143455. if( nodeInsertCell(pRtree, pNode, pCell) ){
  143456. if( iHeight<=pRtree->iReinsertHeight || pNode->iNode==1){
  143457. rc = SplitNode(pRtree, pNode, pCell, iHeight);
  143458. }else{
  143459. pRtree->iReinsertHeight = iHeight;
  143460. rc = Reinsert(pRtree, pNode, pCell, iHeight);
  143461. }
  143462. }else{
  143463. rc = AdjustTree(pRtree, pNode, pCell);
  143464. if( rc==SQLITE_OK ){
  143465. if( iHeight==0 ){
  143466. rc = rowidWrite(pRtree, pCell->iRowid, pNode->iNode);
  143467. }else{
  143468. rc = parentWrite(pRtree, pCell->iRowid, pNode->iNode);
  143469. }
  143470. }
  143471. }
  143472. return rc;
  143473. }
  143474. static int reinsertNodeContent(Rtree *pRtree, RtreeNode *pNode){
  143475. int ii;
  143476. int rc = SQLITE_OK;
  143477. int nCell = NCELL(pNode);
  143478. for(ii=0; rc==SQLITE_OK && ii<nCell; ii++){
  143479. RtreeNode *pInsert;
  143480. RtreeCell cell;
  143481. nodeGetCell(pRtree, pNode, ii, &cell);
  143482. /* Find a node to store this cell in. pNode->iNode currently contains
  143483. ** the height of the sub-tree headed by the cell.
  143484. */
  143485. rc = ChooseLeaf(pRtree, &cell, (int)pNode->iNode, &pInsert);
  143486. if( rc==SQLITE_OK ){
  143487. int rc2;
  143488. rc = rtreeInsertCell(pRtree, pInsert, &cell, (int)pNode->iNode);
  143489. rc2 = nodeRelease(pRtree, pInsert);
  143490. if( rc==SQLITE_OK ){
  143491. rc = rc2;
  143492. }
  143493. }
  143494. }
  143495. return rc;
  143496. }
  143497. /*
  143498. ** Select a currently unused rowid for a new r-tree record.
  143499. */
  143500. static int newRowid(Rtree *pRtree, i64 *piRowid){
  143501. int rc;
  143502. sqlite3_bind_null(pRtree->pWriteRowid, 1);
  143503. sqlite3_bind_null(pRtree->pWriteRowid, 2);
  143504. sqlite3_step(pRtree->pWriteRowid);
  143505. rc = sqlite3_reset(pRtree->pWriteRowid);
  143506. *piRowid = sqlite3_last_insert_rowid(pRtree->db);
  143507. return rc;
  143508. }
  143509. /*
  143510. ** Remove the entry with rowid=iDelete from the r-tree structure.
  143511. */
  143512. static int rtreeDeleteRowid(Rtree *pRtree, sqlite3_int64 iDelete){
  143513. int rc; /* Return code */
  143514. RtreeNode *pLeaf = 0; /* Leaf node containing record iDelete */
  143515. int iCell; /* Index of iDelete cell in pLeaf */
  143516. RtreeNode *pRoot; /* Root node of rtree structure */
  143517. /* Obtain a reference to the root node to initialize Rtree.iDepth */
  143518. rc = nodeAcquire(pRtree, 1, 0, &pRoot);
  143519. /* Obtain a reference to the leaf node that contains the entry
  143520. ** about to be deleted.
  143521. */
  143522. if( rc==SQLITE_OK ){
  143523. rc = findLeafNode(pRtree, iDelete, &pLeaf, 0);
  143524. }
  143525. /* Delete the cell in question from the leaf node. */
  143526. if( rc==SQLITE_OK ){
  143527. int rc2;
  143528. rc = nodeRowidIndex(pRtree, pLeaf, iDelete, &iCell);
  143529. if( rc==SQLITE_OK ){
  143530. rc = deleteCell(pRtree, pLeaf, iCell, 0);
  143531. }
  143532. rc2 = nodeRelease(pRtree, pLeaf);
  143533. if( rc==SQLITE_OK ){
  143534. rc = rc2;
  143535. }
  143536. }
  143537. /* Delete the corresponding entry in the <rtree>_rowid table. */
  143538. if( rc==SQLITE_OK ){
  143539. sqlite3_bind_int64(pRtree->pDeleteRowid, 1, iDelete);
  143540. sqlite3_step(pRtree->pDeleteRowid);
  143541. rc = sqlite3_reset(pRtree->pDeleteRowid);
  143542. }
  143543. /* Check if the root node now has exactly one child. If so, remove
  143544. ** it, schedule the contents of the child for reinsertion and
  143545. ** reduce the tree height by one.
  143546. **
  143547. ** This is equivalent to copying the contents of the child into
  143548. ** the root node (the operation that Gutman's paper says to perform
  143549. ** in this scenario).
  143550. */
  143551. if( rc==SQLITE_OK && pRtree->iDepth>0 && NCELL(pRoot)==1 ){
  143552. int rc2;
  143553. RtreeNode *pChild;
  143554. i64 iChild = nodeGetRowid(pRtree, pRoot, 0);
  143555. rc = nodeAcquire(pRtree, iChild, pRoot, &pChild);
  143556. if( rc==SQLITE_OK ){
  143557. rc = removeNode(pRtree, pChild, pRtree->iDepth-1);
  143558. }
  143559. rc2 = nodeRelease(pRtree, pChild);
  143560. if( rc==SQLITE_OK ) rc = rc2;
  143561. if( rc==SQLITE_OK ){
  143562. pRtree->iDepth--;
  143563. writeInt16(pRoot->zData, pRtree->iDepth);
  143564. pRoot->isDirty = 1;
  143565. }
  143566. }
  143567. /* Re-insert the contents of any underfull nodes removed from the tree. */
  143568. for(pLeaf=pRtree->pDeleted; pLeaf; pLeaf=pRtree->pDeleted){
  143569. if( rc==SQLITE_OK ){
  143570. rc = reinsertNodeContent(pRtree, pLeaf);
  143571. }
  143572. pRtree->pDeleted = pLeaf->pNext;
  143573. sqlite3_free(pLeaf);
  143574. }
  143575. /* Release the reference to the root node. */
  143576. if( rc==SQLITE_OK ){
  143577. rc = nodeRelease(pRtree, pRoot);
  143578. }else{
  143579. nodeRelease(pRtree, pRoot);
  143580. }
  143581. return rc;
  143582. }
  143583. /*
  143584. ** Rounding constants for float->double conversion.
  143585. */
  143586. #define RNDTOWARDS (1.0 - 1.0/8388608.0) /* Round towards zero */
  143587. #define RNDAWAY (1.0 + 1.0/8388608.0) /* Round away from zero */
  143588. #if !defined(SQLITE_RTREE_INT_ONLY)
  143589. /*
  143590. ** Convert an sqlite3_value into an RtreeValue (presumably a float)
  143591. ** while taking care to round toward negative or positive, respectively.
  143592. */
  143593. static RtreeValue rtreeValueDown(sqlite3_value *v){
  143594. double d = sqlite3_value_double(v);
  143595. float f = (float)d;
  143596. if( f>d ){
  143597. f = (float)(d*(d<0 ? RNDAWAY : RNDTOWARDS));
  143598. }
  143599. return f;
  143600. }
  143601. static RtreeValue rtreeValueUp(sqlite3_value *v){
  143602. double d = sqlite3_value_double(v);
  143603. float f = (float)d;
  143604. if( f<d ){
  143605. f = (float)(d*(d<0 ? RNDTOWARDS : RNDAWAY));
  143606. }
  143607. return f;
  143608. }
  143609. #endif /* !defined(SQLITE_RTREE_INT_ONLY) */
  143610. /*
  143611. ** The xUpdate method for rtree module virtual tables.
  143612. */
  143613. static int rtreeUpdate(
  143614. sqlite3_vtab *pVtab,
  143615. int nData,
  143616. sqlite3_value **azData,
  143617. sqlite_int64 *pRowid
  143618. ){
  143619. Rtree *pRtree = (Rtree *)pVtab;
  143620. int rc = SQLITE_OK;
  143621. RtreeCell cell; /* New cell to insert if nData>1 */
  143622. int bHaveRowid = 0; /* Set to 1 after new rowid is determined */
  143623. rtreeReference(pRtree);
  143624. assert(nData>=1);
  143625. cell.iRowid = 0; /* Used only to suppress a compiler warning */
  143626. /* Constraint handling. A write operation on an r-tree table may return
  143627. ** SQLITE_CONSTRAINT for two reasons:
  143628. **
  143629. ** 1. A duplicate rowid value, or
  143630. ** 2. The supplied data violates the "x2>=x1" constraint.
  143631. **
  143632. ** In the first case, if the conflict-handling mode is REPLACE, then
  143633. ** the conflicting row can be removed before proceeding. In the second
  143634. ** case, SQLITE_CONSTRAINT must be returned regardless of the
  143635. ** conflict-handling mode specified by the user.
  143636. */
  143637. if( nData>1 ){
  143638. int ii;
  143639. /* Populate the cell.aCoord[] array. The first coordinate is azData[3].
  143640. **
  143641. ** NB: nData can only be less than nDim*2+3 if the rtree is mis-declared
  143642. ** with "column" that are interpreted as table constraints.
  143643. ** Example: CREATE VIRTUAL TABLE bad USING rtree(x,y,CHECK(y>5));
  143644. ** This problem was discovered after years of use, so we silently ignore
  143645. ** these kinds of misdeclared tables to avoid breaking any legacy.
  143646. */
  143647. assert( nData<=(pRtree->nDim*2 + 3) );
  143648. #ifndef SQLITE_RTREE_INT_ONLY
  143649. if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
  143650. for(ii=0; ii<nData-4; ii+=2){
  143651. cell.aCoord[ii].f = rtreeValueDown(azData[ii+3]);
  143652. cell.aCoord[ii+1].f = rtreeValueUp(azData[ii+4]);
  143653. if( cell.aCoord[ii].f>cell.aCoord[ii+1].f ){
  143654. rc = SQLITE_CONSTRAINT;
  143655. goto constraint;
  143656. }
  143657. }
  143658. }else
  143659. #endif
  143660. {
  143661. for(ii=0; ii<nData-4; ii+=2){
  143662. cell.aCoord[ii].i = sqlite3_value_int(azData[ii+3]);
  143663. cell.aCoord[ii+1].i = sqlite3_value_int(azData[ii+4]);
  143664. if( cell.aCoord[ii].i>cell.aCoord[ii+1].i ){
  143665. rc = SQLITE_CONSTRAINT;
  143666. goto constraint;
  143667. }
  143668. }
  143669. }
  143670. /* If a rowid value was supplied, check if it is already present in
  143671. ** the table. If so, the constraint has failed. */
  143672. if( sqlite3_value_type(azData[2])!=SQLITE_NULL ){
  143673. cell.iRowid = sqlite3_value_int64(azData[2]);
  143674. if( sqlite3_value_type(azData[0])==SQLITE_NULL
  143675. || sqlite3_value_int64(azData[0])!=cell.iRowid
  143676. ){
  143677. int steprc;
  143678. sqlite3_bind_int64(pRtree->pReadRowid, 1, cell.iRowid);
  143679. steprc = sqlite3_step(pRtree->pReadRowid);
  143680. rc = sqlite3_reset(pRtree->pReadRowid);
  143681. if( SQLITE_ROW==steprc ){
  143682. if( sqlite3_vtab_on_conflict(pRtree->db)==SQLITE_REPLACE ){
  143683. rc = rtreeDeleteRowid(pRtree, cell.iRowid);
  143684. }else{
  143685. rc = SQLITE_CONSTRAINT;
  143686. goto constraint;
  143687. }
  143688. }
  143689. }
  143690. bHaveRowid = 1;
  143691. }
  143692. }
  143693. /* If azData[0] is not an SQL NULL value, it is the rowid of a
  143694. ** record to delete from the r-tree table. The following block does
  143695. ** just that.
  143696. */
  143697. if( sqlite3_value_type(azData[0])!=SQLITE_NULL ){
  143698. rc = rtreeDeleteRowid(pRtree, sqlite3_value_int64(azData[0]));
  143699. }
  143700. /* If the azData[] array contains more than one element, elements
  143701. ** (azData[2]..azData[argc-1]) contain a new record to insert into
  143702. ** the r-tree structure.
  143703. */
  143704. if( rc==SQLITE_OK && nData>1 ){
  143705. /* Insert the new record into the r-tree */
  143706. RtreeNode *pLeaf = 0;
  143707. /* Figure out the rowid of the new row. */
  143708. if( bHaveRowid==0 ){
  143709. rc = newRowid(pRtree, &cell.iRowid);
  143710. }
  143711. *pRowid = cell.iRowid;
  143712. if( rc==SQLITE_OK ){
  143713. rc = ChooseLeaf(pRtree, &cell, 0, &pLeaf);
  143714. }
  143715. if( rc==SQLITE_OK ){
  143716. int rc2;
  143717. pRtree->iReinsertHeight = -1;
  143718. rc = rtreeInsertCell(pRtree, pLeaf, &cell, 0);
  143719. rc2 = nodeRelease(pRtree, pLeaf);
  143720. if( rc==SQLITE_OK ){
  143721. rc = rc2;
  143722. }
  143723. }
  143724. }
  143725. constraint:
  143726. rtreeRelease(pRtree);
  143727. return rc;
  143728. }
  143729. /*
  143730. ** The xRename method for rtree module virtual tables.
  143731. */
  143732. static int rtreeRename(sqlite3_vtab *pVtab, const char *zNewName){
  143733. Rtree *pRtree = (Rtree *)pVtab;
  143734. int rc = SQLITE_NOMEM;
  143735. char *zSql = sqlite3_mprintf(
  143736. "ALTER TABLE %Q.'%q_node' RENAME TO \"%w_node\";"
  143737. "ALTER TABLE %Q.'%q_parent' RENAME TO \"%w_parent\";"
  143738. "ALTER TABLE %Q.'%q_rowid' RENAME TO \"%w_rowid\";"
  143739. , pRtree->zDb, pRtree->zName, zNewName
  143740. , pRtree->zDb, pRtree->zName, zNewName
  143741. , pRtree->zDb, pRtree->zName, zNewName
  143742. );
  143743. if( zSql ){
  143744. rc = sqlite3_exec(pRtree->db, zSql, 0, 0, 0);
  143745. sqlite3_free(zSql);
  143746. }
  143747. return rc;
  143748. }
  143749. /*
  143750. ** This function populates the pRtree->nRowEst variable with an estimate
  143751. ** of the number of rows in the virtual table. If possible, this is based
  143752. ** on sqlite_stat1 data. Otherwise, use RTREE_DEFAULT_ROWEST.
  143753. */
  143754. static int rtreeQueryStat1(sqlite3 *db, Rtree *pRtree){
  143755. const char *zFmt = "SELECT stat FROM %Q.sqlite_stat1 WHERE tbl = '%q_rowid'";
  143756. char *zSql;
  143757. sqlite3_stmt *p;
  143758. int rc;
  143759. i64 nRow = 0;
  143760. zSql = sqlite3_mprintf(zFmt, pRtree->zDb, pRtree->zName);
  143761. if( zSql==0 ){
  143762. rc = SQLITE_NOMEM;
  143763. }else{
  143764. rc = sqlite3_prepare_v2(db, zSql, -1, &p, 0);
  143765. if( rc==SQLITE_OK ){
  143766. if( sqlite3_step(p)==SQLITE_ROW ) nRow = sqlite3_column_int64(p, 0);
  143767. rc = sqlite3_finalize(p);
  143768. }else if( rc!=SQLITE_NOMEM ){
  143769. rc = SQLITE_OK;
  143770. }
  143771. if( rc==SQLITE_OK ){
  143772. if( nRow==0 ){
  143773. pRtree->nRowEst = RTREE_DEFAULT_ROWEST;
  143774. }else{
  143775. pRtree->nRowEst = MAX(nRow, RTREE_MIN_ROWEST);
  143776. }
  143777. }
  143778. sqlite3_free(zSql);
  143779. }
  143780. return rc;
  143781. }
  143782. static sqlite3_module rtreeModule = {
  143783. 0, /* iVersion */
  143784. rtreeCreate, /* xCreate - create a table */
  143785. rtreeConnect, /* xConnect - connect to an existing table */
  143786. rtreeBestIndex, /* xBestIndex - Determine search strategy */
  143787. rtreeDisconnect, /* xDisconnect - Disconnect from a table */
  143788. rtreeDestroy, /* xDestroy - Drop a table */
  143789. rtreeOpen, /* xOpen - open a cursor */
  143790. rtreeClose, /* xClose - close a cursor */
  143791. rtreeFilter, /* xFilter - configure scan constraints */
  143792. rtreeNext, /* xNext - advance a cursor */
  143793. rtreeEof, /* xEof */
  143794. rtreeColumn, /* xColumn - read data */
  143795. rtreeRowid, /* xRowid - read data */
  143796. rtreeUpdate, /* xUpdate - write data */
  143797. 0, /* xBegin - begin transaction */
  143798. 0, /* xSync - sync transaction */
  143799. 0, /* xCommit - commit transaction */
  143800. 0, /* xRollback - rollback transaction */
  143801. 0, /* xFindFunction - function overloading */
  143802. rtreeRename, /* xRename - rename the table */
  143803. 0, /* xSavepoint */
  143804. 0, /* xRelease */
  143805. 0 /* xRollbackTo */
  143806. };
  143807. static int rtreeSqlInit(
  143808. Rtree *pRtree,
  143809. sqlite3 *db,
  143810. const char *zDb,
  143811. const char *zPrefix,
  143812. int isCreate
  143813. ){
  143814. int rc = SQLITE_OK;
  143815. #define N_STATEMENT 9
  143816. static const char *azSql[N_STATEMENT] = {
  143817. /* Read and write the xxx_node table */
  143818. "SELECT data FROM '%q'.'%q_node' WHERE nodeno = :1",
  143819. "INSERT OR REPLACE INTO '%q'.'%q_node' VALUES(:1, :2)",
  143820. "DELETE FROM '%q'.'%q_node' WHERE nodeno = :1",
  143821. /* Read and write the xxx_rowid table */
  143822. "SELECT nodeno FROM '%q'.'%q_rowid' WHERE rowid = :1",
  143823. "INSERT OR REPLACE INTO '%q'.'%q_rowid' VALUES(:1, :2)",
  143824. "DELETE FROM '%q'.'%q_rowid' WHERE rowid = :1",
  143825. /* Read and write the xxx_parent table */
  143826. "SELECT parentnode FROM '%q'.'%q_parent' WHERE nodeno = :1",
  143827. "INSERT OR REPLACE INTO '%q'.'%q_parent' VALUES(:1, :2)",
  143828. "DELETE FROM '%q'.'%q_parent' WHERE nodeno = :1"
  143829. };
  143830. sqlite3_stmt **appStmt[N_STATEMENT];
  143831. int i;
  143832. pRtree->db = db;
  143833. if( isCreate ){
  143834. char *zCreate = sqlite3_mprintf(
  143835. "CREATE TABLE \"%w\".\"%w_node\"(nodeno INTEGER PRIMARY KEY, data BLOB);"
  143836. "CREATE TABLE \"%w\".\"%w_rowid\"(rowid INTEGER PRIMARY KEY, nodeno INTEGER);"
  143837. "CREATE TABLE \"%w\".\"%w_parent\"(nodeno INTEGER PRIMARY KEY,"
  143838. " parentnode INTEGER);"
  143839. "INSERT INTO '%q'.'%q_node' VALUES(1, zeroblob(%d))",
  143840. zDb, zPrefix, zDb, zPrefix, zDb, zPrefix, zDb, zPrefix, pRtree->iNodeSize
  143841. );
  143842. if( !zCreate ){
  143843. return SQLITE_NOMEM;
  143844. }
  143845. rc = sqlite3_exec(db, zCreate, 0, 0, 0);
  143846. sqlite3_free(zCreate);
  143847. if( rc!=SQLITE_OK ){
  143848. return rc;
  143849. }
  143850. }
  143851. appStmt[0] = &pRtree->pReadNode;
  143852. appStmt[1] = &pRtree->pWriteNode;
  143853. appStmt[2] = &pRtree->pDeleteNode;
  143854. appStmt[3] = &pRtree->pReadRowid;
  143855. appStmt[4] = &pRtree->pWriteRowid;
  143856. appStmt[5] = &pRtree->pDeleteRowid;
  143857. appStmt[6] = &pRtree->pReadParent;
  143858. appStmt[7] = &pRtree->pWriteParent;
  143859. appStmt[8] = &pRtree->pDeleteParent;
  143860. rc = rtreeQueryStat1(db, pRtree);
  143861. for(i=0; i<N_STATEMENT && rc==SQLITE_OK; i++){
  143862. char *zSql = sqlite3_mprintf(azSql[i], zDb, zPrefix);
  143863. if( zSql ){
  143864. rc = sqlite3_prepare_v2(db, zSql, -1, appStmt[i], 0);
  143865. }else{
  143866. rc = SQLITE_NOMEM;
  143867. }
  143868. sqlite3_free(zSql);
  143869. }
  143870. return rc;
  143871. }
  143872. /*
  143873. ** The second argument to this function contains the text of an SQL statement
  143874. ** that returns a single integer value. The statement is compiled and executed
  143875. ** using database connection db. If successful, the integer value returned
  143876. ** is written to *piVal and SQLITE_OK returned. Otherwise, an SQLite error
  143877. ** code is returned and the value of *piVal after returning is not defined.
  143878. */
  143879. static int getIntFromStmt(sqlite3 *db, const char *zSql, int *piVal){
  143880. int rc = SQLITE_NOMEM;
  143881. if( zSql ){
  143882. sqlite3_stmt *pStmt = 0;
  143883. rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
  143884. if( rc==SQLITE_OK ){
  143885. if( SQLITE_ROW==sqlite3_step(pStmt) ){
  143886. *piVal = sqlite3_column_int(pStmt, 0);
  143887. }
  143888. rc = sqlite3_finalize(pStmt);
  143889. }
  143890. }
  143891. return rc;
  143892. }
  143893. /*
  143894. ** This function is called from within the xConnect() or xCreate() method to
  143895. ** determine the node-size used by the rtree table being created or connected
  143896. ** to. If successful, pRtree->iNodeSize is populated and SQLITE_OK returned.
  143897. ** Otherwise, an SQLite error code is returned.
  143898. **
  143899. ** If this function is being called as part of an xConnect(), then the rtree
  143900. ** table already exists. In this case the node-size is determined by inspecting
  143901. ** the root node of the tree.
  143902. **
  143903. ** Otherwise, for an xCreate(), use 64 bytes less than the database page-size.
  143904. ** This ensures that each node is stored on a single database page. If the
  143905. ** database page-size is so large that more than RTREE_MAXCELLS entries
  143906. ** would fit in a single node, use a smaller node-size.
  143907. */
  143908. static int getNodeSize(
  143909. sqlite3 *db, /* Database handle */
  143910. Rtree *pRtree, /* Rtree handle */
  143911. int isCreate, /* True for xCreate, false for xConnect */
  143912. char **pzErr /* OUT: Error message, if any */
  143913. ){
  143914. int rc;
  143915. char *zSql;
  143916. if( isCreate ){
  143917. int iPageSize = 0;
  143918. zSql = sqlite3_mprintf("PRAGMA %Q.page_size", pRtree->zDb);
  143919. rc = getIntFromStmt(db, zSql, &iPageSize);
  143920. if( rc==SQLITE_OK ){
  143921. pRtree->iNodeSize = iPageSize-64;
  143922. if( (4+pRtree->nBytesPerCell*RTREE_MAXCELLS)<pRtree->iNodeSize ){
  143923. pRtree->iNodeSize = 4+pRtree->nBytesPerCell*RTREE_MAXCELLS;
  143924. }
  143925. }else{
  143926. *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
  143927. }
  143928. }else{
  143929. zSql = sqlite3_mprintf(
  143930. "SELECT length(data) FROM '%q'.'%q_node' WHERE nodeno = 1",
  143931. pRtree->zDb, pRtree->zName
  143932. );
  143933. rc = getIntFromStmt(db, zSql, &pRtree->iNodeSize);
  143934. if( rc!=SQLITE_OK ){
  143935. *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
  143936. }
  143937. }
  143938. sqlite3_free(zSql);
  143939. return rc;
  143940. }
  143941. /*
  143942. ** This function is the implementation of both the xConnect and xCreate
  143943. ** methods of the r-tree virtual table.
  143944. **
  143945. ** argv[0] -> module name
  143946. ** argv[1] -> database name
  143947. ** argv[2] -> table name
  143948. ** argv[...] -> column names...
  143949. */
  143950. static int rtreeInit(
  143951. sqlite3 *db, /* Database connection */
  143952. void *pAux, /* One of the RTREE_COORD_* constants */
  143953. int argc, const char *const*argv, /* Parameters to CREATE TABLE statement */
  143954. sqlite3_vtab **ppVtab, /* OUT: New virtual table */
  143955. char **pzErr, /* OUT: Error message, if any */
  143956. int isCreate /* True for xCreate, false for xConnect */
  143957. ){
  143958. int rc = SQLITE_OK;
  143959. Rtree *pRtree;
  143960. int nDb; /* Length of string argv[1] */
  143961. int nName; /* Length of string argv[2] */
  143962. int eCoordType = (pAux ? RTREE_COORD_INT32 : RTREE_COORD_REAL32);
  143963. const char *aErrMsg[] = {
  143964. 0, /* 0 */
  143965. "Wrong number of columns for an rtree table", /* 1 */
  143966. "Too few columns for an rtree table", /* 2 */
  143967. "Too many columns for an rtree table" /* 3 */
  143968. };
  143969. int iErr = (argc<6) ? 2 : argc>(RTREE_MAX_DIMENSIONS*2+4) ? 3 : argc%2;
  143970. if( aErrMsg[iErr] ){
  143971. *pzErr = sqlite3_mprintf("%s", aErrMsg[iErr]);
  143972. return SQLITE_ERROR;
  143973. }
  143974. sqlite3_vtab_config(db, SQLITE_VTAB_CONSTRAINT_SUPPORT, 1);
  143975. /* Allocate the sqlite3_vtab structure */
  143976. nDb = (int)strlen(argv[1]);
  143977. nName = (int)strlen(argv[2]);
  143978. pRtree = (Rtree *)sqlite3_malloc(sizeof(Rtree)+nDb+nName+2);
  143979. if( !pRtree ){
  143980. return SQLITE_NOMEM;
  143981. }
  143982. memset(pRtree, 0, sizeof(Rtree)+nDb+nName+2);
  143983. pRtree->nBusy = 1;
  143984. pRtree->base.pModule = &rtreeModule;
  143985. pRtree->zDb = (char *)&pRtree[1];
  143986. pRtree->zName = &pRtree->zDb[nDb+1];
  143987. pRtree->nDim = (argc-4)/2;
  143988. pRtree->nBytesPerCell = 8 + pRtree->nDim*4*2;
  143989. pRtree->eCoordType = eCoordType;
  143990. memcpy(pRtree->zDb, argv[1], nDb);
  143991. memcpy(pRtree->zName, argv[2], nName);
  143992. /* Figure out the node size to use. */
  143993. rc = getNodeSize(db, pRtree, isCreate, pzErr);
  143994. /* Create/Connect to the underlying relational database schema. If
  143995. ** that is successful, call sqlite3_declare_vtab() to configure
  143996. ** the r-tree table schema.
  143997. */
  143998. if( rc==SQLITE_OK ){
  143999. if( (rc = rtreeSqlInit(pRtree, db, argv[1], argv[2], isCreate)) ){
  144000. *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
  144001. }else{
  144002. char *zSql = sqlite3_mprintf("CREATE TABLE x(%s", argv[3]);
  144003. char *zTmp;
  144004. int ii;
  144005. for(ii=4; zSql && ii<argc; ii++){
  144006. zTmp = zSql;
  144007. zSql = sqlite3_mprintf("%s, %s", zTmp, argv[ii]);
  144008. sqlite3_free(zTmp);
  144009. }
  144010. if( zSql ){
  144011. zTmp = zSql;
  144012. zSql = sqlite3_mprintf("%s);", zTmp);
  144013. sqlite3_free(zTmp);
  144014. }
  144015. if( !zSql ){
  144016. rc = SQLITE_NOMEM;
  144017. }else if( SQLITE_OK!=(rc = sqlite3_declare_vtab(db, zSql)) ){
  144018. *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
  144019. }
  144020. sqlite3_free(zSql);
  144021. }
  144022. }
  144023. if( rc==SQLITE_OK ){
  144024. *ppVtab = (sqlite3_vtab *)pRtree;
  144025. }else{
  144026. assert( *ppVtab==0 );
  144027. assert( pRtree->nBusy==1 );
  144028. rtreeRelease(pRtree);
  144029. }
  144030. return rc;
  144031. }
  144032. /*
  144033. ** Implementation of a scalar function that decodes r-tree nodes to
  144034. ** human readable strings. This can be used for debugging and analysis.
  144035. **
  144036. ** The scalar function takes two arguments: (1) the number of dimensions
  144037. ** to the rtree (between 1 and 5, inclusive) and (2) a blob of data containing
  144038. ** an r-tree node. For a two-dimensional r-tree structure called "rt", to
  144039. ** deserialize all nodes, a statement like:
  144040. **
  144041. ** SELECT rtreenode(2, data) FROM rt_node;
  144042. **
  144043. ** The human readable string takes the form of a Tcl list with one
  144044. ** entry for each cell in the r-tree node. Each entry is itself a
  144045. ** list, containing the 8-byte rowid/pageno followed by the
  144046. ** <num-dimension>*2 coordinates.
  144047. */
  144048. static void rtreenode(sqlite3_context *ctx, int nArg, sqlite3_value **apArg){
  144049. char *zText = 0;
  144050. RtreeNode node;
  144051. Rtree tree;
  144052. int ii;
  144053. UNUSED_PARAMETER(nArg);
  144054. memset(&node, 0, sizeof(RtreeNode));
  144055. memset(&tree, 0, sizeof(Rtree));
  144056. tree.nDim = sqlite3_value_int(apArg[0]);
  144057. tree.nBytesPerCell = 8 + 8 * tree.nDim;
  144058. node.zData = (u8 *)sqlite3_value_blob(apArg[1]);
  144059. for(ii=0; ii<NCELL(&node); ii++){
  144060. char zCell[512];
  144061. int nCell = 0;
  144062. RtreeCell cell;
  144063. int jj;
  144064. nodeGetCell(&tree, &node, ii, &cell);
  144065. sqlite3_snprintf(512-nCell,&zCell[nCell],"%lld", cell.iRowid);
  144066. nCell = (int)strlen(zCell);
  144067. for(jj=0; jj<tree.nDim*2; jj++){
  144068. #ifndef SQLITE_RTREE_INT_ONLY
  144069. sqlite3_snprintf(512-nCell,&zCell[nCell], " %g",
  144070. (double)cell.aCoord[jj].f);
  144071. #else
  144072. sqlite3_snprintf(512-nCell,&zCell[nCell], " %d",
  144073. cell.aCoord[jj].i);
  144074. #endif
  144075. nCell = (int)strlen(zCell);
  144076. }
  144077. if( zText ){
  144078. char *zTextNew = sqlite3_mprintf("%s {%s}", zText, zCell);
  144079. sqlite3_free(zText);
  144080. zText = zTextNew;
  144081. }else{
  144082. zText = sqlite3_mprintf("{%s}", zCell);
  144083. }
  144084. }
  144085. sqlite3_result_text(ctx, zText, -1, sqlite3_free);
  144086. }
  144087. /* This routine implements an SQL function that returns the "depth" parameter
  144088. ** from the front of a blob that is an r-tree node. For example:
  144089. **
  144090. ** SELECT rtreedepth(data) FROM rt_node WHERE nodeno=1;
  144091. **
  144092. ** The depth value is 0 for all nodes other than the root node, and the root
  144093. ** node always has nodeno=1, so the example above is the primary use for this
  144094. ** routine. This routine is intended for testing and analysis only.
  144095. */
  144096. static void rtreedepth(sqlite3_context *ctx, int nArg, sqlite3_value **apArg){
  144097. UNUSED_PARAMETER(nArg);
  144098. if( sqlite3_value_type(apArg[0])!=SQLITE_BLOB
  144099. || sqlite3_value_bytes(apArg[0])<2
  144100. ){
  144101. sqlite3_result_error(ctx, "Invalid argument to rtreedepth()", -1);
  144102. }else{
  144103. u8 *zBlob = (u8 *)sqlite3_value_blob(apArg[0]);
  144104. sqlite3_result_int(ctx, readInt16(zBlob));
  144105. }
  144106. }
  144107. /*
  144108. ** Register the r-tree module with database handle db. This creates the
  144109. ** virtual table module "rtree" and the debugging/analysis scalar
  144110. ** function "rtreenode".
  144111. */
  144112. SQLITE_PRIVATE int sqlite3RtreeInit(sqlite3 *db){
  144113. const int utf8 = SQLITE_UTF8;
  144114. int rc;
  144115. rc = sqlite3_create_function(db, "rtreenode", 2, utf8, 0, rtreenode, 0, 0);
  144116. if( rc==SQLITE_OK ){
  144117. rc = sqlite3_create_function(db, "rtreedepth", 1, utf8, 0,rtreedepth, 0, 0);
  144118. }
  144119. if( rc==SQLITE_OK ){
  144120. #ifdef SQLITE_RTREE_INT_ONLY
  144121. void *c = (void *)RTREE_COORD_INT32;
  144122. #else
  144123. void *c = (void *)RTREE_COORD_REAL32;
  144124. #endif
  144125. rc = sqlite3_create_module_v2(db, "rtree", &rtreeModule, c, 0);
  144126. }
  144127. if( rc==SQLITE_OK ){
  144128. void *c = (void *)RTREE_COORD_INT32;
  144129. rc = sqlite3_create_module_v2(db, "rtree_i32", &rtreeModule, c, 0);
  144130. }
  144131. return rc;
  144132. }
  144133. /*
  144134. ** This routine deletes the RtreeGeomCallback object that was attached
  144135. ** one of the SQL functions create by sqlite3_rtree_geometry_callback()
  144136. ** or sqlite3_rtree_query_callback(). In other words, this routine is the
  144137. ** destructor for an RtreeGeomCallback objecct. This routine is called when
  144138. ** the corresponding SQL function is deleted.
  144139. */
  144140. static void rtreeFreeCallback(void *p){
  144141. RtreeGeomCallback *pInfo = (RtreeGeomCallback*)p;
  144142. if( pInfo->xDestructor ) pInfo->xDestructor(pInfo->pContext);
  144143. sqlite3_free(p);
  144144. }
  144145. /*
  144146. ** Each call to sqlite3_rtree_geometry_callback() or
  144147. ** sqlite3_rtree_query_callback() creates an ordinary SQLite
  144148. ** scalar function that is implemented by this routine.
  144149. **
  144150. ** All this function does is construct an RtreeMatchArg object that
  144151. ** contains the geometry-checking callback routines and a list of
  144152. ** parameters to this function, then return that RtreeMatchArg object
  144153. ** as a BLOB.
  144154. **
  144155. ** The R-Tree MATCH operator will read the returned BLOB, deserialize
  144156. ** the RtreeMatchArg object, and use the RtreeMatchArg object to figure
  144157. ** out which elements of the R-Tree should be returned by the query.
  144158. */
  144159. static void geomCallback(sqlite3_context *ctx, int nArg, sqlite3_value **aArg){
  144160. RtreeGeomCallback *pGeomCtx = (RtreeGeomCallback *)sqlite3_user_data(ctx);
  144161. RtreeMatchArg *pBlob;
  144162. int nBlob;
  144163. nBlob = sizeof(RtreeMatchArg) + (nArg-1)*sizeof(RtreeDValue);
  144164. pBlob = (RtreeMatchArg *)sqlite3_malloc(nBlob);
  144165. if( !pBlob ){
  144166. sqlite3_result_error_nomem(ctx);
  144167. }else{
  144168. int i;
  144169. pBlob->magic = RTREE_GEOMETRY_MAGIC;
  144170. pBlob->cb = pGeomCtx[0];
  144171. pBlob->nParam = nArg;
  144172. for(i=0; i<nArg; i++){
  144173. #ifdef SQLITE_RTREE_INT_ONLY
  144174. pBlob->aParam[i] = sqlite3_value_int64(aArg[i]);
  144175. #else
  144176. pBlob->aParam[i] = sqlite3_value_double(aArg[i]);
  144177. #endif
  144178. }
  144179. sqlite3_result_blob(ctx, pBlob, nBlob, sqlite3_free);
  144180. }
  144181. }
  144182. /*
  144183. ** Register a new geometry function for use with the r-tree MATCH operator.
  144184. */
  144185. SQLITE_API int SQLITE_STDCALL sqlite3_rtree_geometry_callback(
  144186. sqlite3 *db, /* Register SQL function on this connection */
  144187. const char *zGeom, /* Name of the new SQL function */
  144188. int (*xGeom)(sqlite3_rtree_geometry*,int,RtreeDValue*,int*), /* Callback */
  144189. void *pContext /* Extra data associated with the callback */
  144190. ){
  144191. RtreeGeomCallback *pGeomCtx; /* Context object for new user-function */
  144192. /* Allocate and populate the context object. */
  144193. pGeomCtx = (RtreeGeomCallback *)sqlite3_malloc(sizeof(RtreeGeomCallback));
  144194. if( !pGeomCtx ) return SQLITE_NOMEM;
  144195. pGeomCtx->xGeom = xGeom;
  144196. pGeomCtx->xQueryFunc = 0;
  144197. pGeomCtx->xDestructor = 0;
  144198. pGeomCtx->pContext = pContext;
  144199. return sqlite3_create_function_v2(db, zGeom, -1, SQLITE_ANY,
  144200. (void *)pGeomCtx, geomCallback, 0, 0, rtreeFreeCallback
  144201. );
  144202. }
  144203. /*
  144204. ** Register a new 2nd-generation geometry function for use with the
  144205. ** r-tree MATCH operator.
  144206. */
  144207. SQLITE_API int SQLITE_STDCALL sqlite3_rtree_query_callback(
  144208. sqlite3 *db, /* Register SQL function on this connection */
  144209. const char *zQueryFunc, /* Name of new SQL function */
  144210. int (*xQueryFunc)(sqlite3_rtree_query_info*), /* Callback */
  144211. void *pContext, /* Extra data passed into the callback */
  144212. void (*xDestructor)(void*) /* Destructor for the extra data */
  144213. ){
  144214. RtreeGeomCallback *pGeomCtx; /* Context object for new user-function */
  144215. /* Allocate and populate the context object. */
  144216. pGeomCtx = (RtreeGeomCallback *)sqlite3_malloc(sizeof(RtreeGeomCallback));
  144217. if( !pGeomCtx ) return SQLITE_NOMEM;
  144218. pGeomCtx->xGeom = 0;
  144219. pGeomCtx->xQueryFunc = xQueryFunc;
  144220. pGeomCtx->xDestructor = xDestructor;
  144221. pGeomCtx->pContext = pContext;
  144222. return sqlite3_create_function_v2(db, zQueryFunc, -1, SQLITE_ANY,
  144223. (void *)pGeomCtx, geomCallback, 0, 0, rtreeFreeCallback
  144224. );
  144225. }
  144226. #if !SQLITE_CORE
  144227. #ifdef _WIN32
  144228. __declspec(dllexport)
  144229. #endif
  144230. SQLITE_API int SQLITE_STDCALL sqlite3_rtree_init(
  144231. sqlite3 *db,
  144232. char **pzErrMsg,
  144233. const sqlite3_api_routines *pApi
  144234. ){
  144235. SQLITE_EXTENSION_INIT2(pApi)
  144236. return sqlite3RtreeInit(db);
  144237. }
  144238. #endif
  144239. #endif
  144240. /************** End of rtree.c ***********************************************/
  144241. /************** Begin file icu.c *********************************************/
  144242. /*
  144243. ** 2007 May 6
  144244. **
  144245. ** The author disclaims copyright to this source code. In place of
  144246. ** a legal notice, here is a blessing:
  144247. **
  144248. ** May you do good and not evil.
  144249. ** May you find forgiveness for yourself and forgive others.
  144250. ** May you share freely, never taking more than you give.
  144251. **
  144252. *************************************************************************
  144253. ** $Id: icu.c,v 1.7 2007/12/13 21:54:11 drh Exp $
  144254. **
  144255. ** This file implements an integration between the ICU library
  144256. ** ("International Components for Unicode", an open-source library
  144257. ** for handling unicode data) and SQLite. The integration uses
  144258. ** ICU to provide the following to SQLite:
  144259. **
  144260. ** * An implementation of the SQL regexp() function (and hence REGEXP
  144261. ** operator) using the ICU uregex_XX() APIs.
  144262. **
  144263. ** * Implementations of the SQL scalar upper() and lower() functions
  144264. ** for case mapping.
  144265. **
  144266. ** * Integration of ICU and SQLite collation sequences.
  144267. **
  144268. ** * An implementation of the LIKE operator that uses ICU to
  144269. ** provide case-independent matching.
  144270. */
  144271. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_ICU)
  144272. /* Include ICU headers */
  144273. #include <unicode/utypes.h>
  144274. #include <unicode/uregex.h>
  144275. #include <unicode/ustring.h>
  144276. #include <unicode/ucol.h>
  144277. /* #include <assert.h> */
  144278. #ifndef SQLITE_CORE
  144279. SQLITE_EXTENSION_INIT1
  144280. #else
  144281. #endif
  144282. /*
  144283. ** Maximum length (in bytes) of the pattern in a LIKE or GLOB
  144284. ** operator.
  144285. */
  144286. #ifndef SQLITE_MAX_LIKE_PATTERN_LENGTH
  144287. # define SQLITE_MAX_LIKE_PATTERN_LENGTH 50000
  144288. #endif
  144289. /*
  144290. ** Version of sqlite3_free() that is always a function, never a macro.
  144291. */
  144292. static void xFree(void *p){
  144293. sqlite3_free(p);
  144294. }
  144295. /*
  144296. ** Compare two UTF-8 strings for equality where the first string is
  144297. ** a "LIKE" expression. Return true (1) if they are the same and
  144298. ** false (0) if they are different.
  144299. */
  144300. static int icuLikeCompare(
  144301. const uint8_t *zPattern, /* LIKE pattern */
  144302. const uint8_t *zString, /* The UTF-8 string to compare against */
  144303. const UChar32 uEsc /* The escape character */
  144304. ){
  144305. static const int MATCH_ONE = (UChar32)'_';
  144306. static const int MATCH_ALL = (UChar32)'%';
  144307. int iPattern = 0; /* Current byte index in zPattern */
  144308. int iString = 0; /* Current byte index in zString */
  144309. int prevEscape = 0; /* True if the previous character was uEsc */
  144310. while( zPattern[iPattern]!=0 ){
  144311. /* Read (and consume) the next character from the input pattern. */
  144312. UChar32 uPattern;
  144313. U8_NEXT_UNSAFE(zPattern, iPattern, uPattern);
  144314. assert(uPattern!=0);
  144315. /* There are now 4 possibilities:
  144316. **
  144317. ** 1. uPattern is an unescaped match-all character "%",
  144318. ** 2. uPattern is an unescaped match-one character "_",
  144319. ** 3. uPattern is an unescaped escape character, or
  144320. ** 4. uPattern is to be handled as an ordinary character
  144321. */
  144322. if( !prevEscape && uPattern==MATCH_ALL ){
  144323. /* Case 1. */
  144324. uint8_t c;
  144325. /* Skip any MATCH_ALL or MATCH_ONE characters that follow a
  144326. ** MATCH_ALL. For each MATCH_ONE, skip one character in the
  144327. ** test string.
  144328. */
  144329. while( (c=zPattern[iPattern]) == MATCH_ALL || c == MATCH_ONE ){
  144330. if( c==MATCH_ONE ){
  144331. if( zString[iString]==0 ) return 0;
  144332. U8_FWD_1_UNSAFE(zString, iString);
  144333. }
  144334. iPattern++;
  144335. }
  144336. if( zPattern[iPattern]==0 ) return 1;
  144337. while( zString[iString] ){
  144338. if( icuLikeCompare(&zPattern[iPattern], &zString[iString], uEsc) ){
  144339. return 1;
  144340. }
  144341. U8_FWD_1_UNSAFE(zString, iString);
  144342. }
  144343. return 0;
  144344. }else if( !prevEscape && uPattern==MATCH_ONE ){
  144345. /* Case 2. */
  144346. if( zString[iString]==0 ) return 0;
  144347. U8_FWD_1_UNSAFE(zString, iString);
  144348. }else if( !prevEscape && uPattern==uEsc){
  144349. /* Case 3. */
  144350. prevEscape = 1;
  144351. }else{
  144352. /* Case 4. */
  144353. UChar32 uString;
  144354. U8_NEXT_UNSAFE(zString, iString, uString);
  144355. uString = u_foldCase(uString, U_FOLD_CASE_DEFAULT);
  144356. uPattern = u_foldCase(uPattern, U_FOLD_CASE_DEFAULT);
  144357. if( uString!=uPattern ){
  144358. return 0;
  144359. }
  144360. prevEscape = 0;
  144361. }
  144362. }
  144363. return zString[iString]==0;
  144364. }
  144365. /*
  144366. ** Implementation of the like() SQL function. This function implements
  144367. ** the build-in LIKE operator. The first argument to the function is the
  144368. ** pattern and the second argument is the string. So, the SQL statements:
  144369. **
  144370. ** A LIKE B
  144371. **
  144372. ** is implemented as like(B, A). If there is an escape character E,
  144373. **
  144374. ** A LIKE B ESCAPE E
  144375. **
  144376. ** is mapped to like(B, A, E).
  144377. */
  144378. static void icuLikeFunc(
  144379. sqlite3_context *context,
  144380. int argc,
  144381. sqlite3_value **argv
  144382. ){
  144383. const unsigned char *zA = sqlite3_value_text(argv[0]);
  144384. const unsigned char *zB = sqlite3_value_text(argv[1]);
  144385. UChar32 uEsc = 0;
  144386. /* Limit the length of the LIKE or GLOB pattern to avoid problems
  144387. ** of deep recursion and N*N behavior in patternCompare().
  144388. */
  144389. if( sqlite3_value_bytes(argv[0])>SQLITE_MAX_LIKE_PATTERN_LENGTH ){
  144390. sqlite3_result_error(context, "LIKE or GLOB pattern too complex", -1);
  144391. return;
  144392. }
  144393. if( argc==3 ){
  144394. /* The escape character string must consist of a single UTF-8 character.
  144395. ** Otherwise, return an error.
  144396. */
  144397. int nE= sqlite3_value_bytes(argv[2]);
  144398. const unsigned char *zE = sqlite3_value_text(argv[2]);
  144399. int i = 0;
  144400. if( zE==0 ) return;
  144401. U8_NEXT(zE, i, nE, uEsc);
  144402. if( i!=nE){
  144403. sqlite3_result_error(context,
  144404. "ESCAPE expression must be a single character", -1);
  144405. return;
  144406. }
  144407. }
  144408. if( zA && zB ){
  144409. sqlite3_result_int(context, icuLikeCompare(zA, zB, uEsc));
  144410. }
  144411. }
  144412. /*
  144413. ** This function is called when an ICU function called from within
  144414. ** the implementation of an SQL scalar function returns an error.
  144415. **
  144416. ** The scalar function context passed as the first argument is
  144417. ** loaded with an error message based on the following two args.
  144418. */
  144419. static void icuFunctionError(
  144420. sqlite3_context *pCtx, /* SQLite scalar function context */
  144421. const char *zName, /* Name of ICU function that failed */
  144422. UErrorCode e /* Error code returned by ICU function */
  144423. ){
  144424. char zBuf[128];
  144425. sqlite3_snprintf(128, zBuf, "ICU error: %s(): %s", zName, u_errorName(e));
  144426. zBuf[127] = '\0';
  144427. sqlite3_result_error(pCtx, zBuf, -1);
  144428. }
  144429. /*
  144430. ** Function to delete compiled regexp objects. Registered as
  144431. ** a destructor function with sqlite3_set_auxdata().
  144432. */
  144433. static void icuRegexpDelete(void *p){
  144434. URegularExpression *pExpr = (URegularExpression *)p;
  144435. uregex_close(pExpr);
  144436. }
  144437. /*
  144438. ** Implementation of SQLite REGEXP operator. This scalar function takes
  144439. ** two arguments. The first is a regular expression pattern to compile
  144440. ** the second is a string to match against that pattern. If either
  144441. ** argument is an SQL NULL, then NULL Is returned. Otherwise, the result
  144442. ** is 1 if the string matches the pattern, or 0 otherwise.
  144443. **
  144444. ** SQLite maps the regexp() function to the regexp() operator such
  144445. ** that the following two are equivalent:
  144446. **
  144447. ** zString REGEXP zPattern
  144448. ** regexp(zPattern, zString)
  144449. **
  144450. ** Uses the following ICU regexp APIs:
  144451. **
  144452. ** uregex_open()
  144453. ** uregex_matches()
  144454. ** uregex_close()
  144455. */
  144456. static void icuRegexpFunc(sqlite3_context *p, int nArg, sqlite3_value **apArg){
  144457. UErrorCode status = U_ZERO_ERROR;
  144458. URegularExpression *pExpr;
  144459. UBool res;
  144460. const UChar *zString = sqlite3_value_text16(apArg[1]);
  144461. (void)nArg; /* Unused parameter */
  144462. /* If the left hand side of the regexp operator is NULL,
  144463. ** then the result is also NULL.
  144464. */
  144465. if( !zString ){
  144466. return;
  144467. }
  144468. pExpr = sqlite3_get_auxdata(p, 0);
  144469. if( !pExpr ){
  144470. const UChar *zPattern = sqlite3_value_text16(apArg[0]);
  144471. if( !zPattern ){
  144472. return;
  144473. }
  144474. pExpr = uregex_open(zPattern, -1, 0, 0, &status);
  144475. if( U_SUCCESS(status) ){
  144476. sqlite3_set_auxdata(p, 0, pExpr, icuRegexpDelete);
  144477. }else{
  144478. assert(!pExpr);
  144479. icuFunctionError(p, "uregex_open", status);
  144480. return;
  144481. }
  144482. }
  144483. /* Configure the text that the regular expression operates on. */
  144484. uregex_setText(pExpr, zString, -1, &status);
  144485. if( !U_SUCCESS(status) ){
  144486. icuFunctionError(p, "uregex_setText", status);
  144487. return;
  144488. }
  144489. /* Attempt the match */
  144490. res = uregex_matches(pExpr, 0, &status);
  144491. if( !U_SUCCESS(status) ){
  144492. icuFunctionError(p, "uregex_matches", status);
  144493. return;
  144494. }
  144495. /* Set the text that the regular expression operates on to a NULL
  144496. ** pointer. This is not really necessary, but it is tidier than
  144497. ** leaving the regular expression object configured with an invalid
  144498. ** pointer after this function returns.
  144499. */
  144500. uregex_setText(pExpr, 0, 0, &status);
  144501. /* Return 1 or 0. */
  144502. sqlite3_result_int(p, res ? 1 : 0);
  144503. }
  144504. /*
  144505. ** Implementations of scalar functions for case mapping - upper() and
  144506. ** lower(). Function upper() converts its input to upper-case (ABC).
  144507. ** Function lower() converts to lower-case (abc).
  144508. **
  144509. ** ICU provides two types of case mapping, "general" case mapping and
  144510. ** "language specific". Refer to ICU documentation for the differences
  144511. ** between the two.
  144512. **
  144513. ** To utilise "general" case mapping, the upper() or lower() scalar
  144514. ** functions are invoked with one argument:
  144515. **
  144516. ** upper('ABC') -> 'abc'
  144517. ** lower('abc') -> 'ABC'
  144518. **
  144519. ** To access ICU "language specific" case mapping, upper() or lower()
  144520. ** should be invoked with two arguments. The second argument is the name
  144521. ** of the locale to use. Passing an empty string ("") or SQL NULL value
  144522. ** as the second argument is the same as invoking the 1 argument version
  144523. ** of upper() or lower().
  144524. **
  144525. ** lower('I', 'en_us') -> 'i'
  144526. ** lower('I', 'tr_tr') -> 'ı' (small dotless i)
  144527. **
  144528. ** http://www.icu-project.org/userguide/posix.html#case_mappings
  144529. */
  144530. static void icuCaseFunc16(sqlite3_context *p, int nArg, sqlite3_value **apArg){
  144531. const UChar *zInput;
  144532. UChar *zOutput;
  144533. int nInput;
  144534. int nOutput;
  144535. UErrorCode status = U_ZERO_ERROR;
  144536. const char *zLocale = 0;
  144537. assert(nArg==1 || nArg==2);
  144538. if( nArg==2 ){
  144539. zLocale = (const char *)sqlite3_value_text(apArg[1]);
  144540. }
  144541. zInput = sqlite3_value_text16(apArg[0]);
  144542. if( !zInput ){
  144543. return;
  144544. }
  144545. nInput = sqlite3_value_bytes16(apArg[0]);
  144546. nOutput = nInput * 2 + 2;
  144547. zOutput = sqlite3_malloc(nOutput);
  144548. if( !zOutput ){
  144549. return;
  144550. }
  144551. if( sqlite3_user_data(p) ){
  144552. u_strToUpper(zOutput, nOutput/2, zInput, nInput/2, zLocale, &status);
  144553. }else{
  144554. u_strToLower(zOutput, nOutput/2, zInput, nInput/2, zLocale, &status);
  144555. }
  144556. if( !U_SUCCESS(status) ){
  144557. icuFunctionError(p, "u_strToLower()/u_strToUpper", status);
  144558. return;
  144559. }
  144560. sqlite3_result_text16(p, zOutput, -1, xFree);
  144561. }
  144562. /*
  144563. ** Collation sequence destructor function. The pCtx argument points to
  144564. ** a UCollator structure previously allocated using ucol_open().
  144565. */
  144566. static void icuCollationDel(void *pCtx){
  144567. UCollator *p = (UCollator *)pCtx;
  144568. ucol_close(p);
  144569. }
  144570. /*
  144571. ** Collation sequence comparison function. The pCtx argument points to
  144572. ** a UCollator structure previously allocated using ucol_open().
  144573. */
  144574. static int icuCollationColl(
  144575. void *pCtx,
  144576. int nLeft,
  144577. const void *zLeft,
  144578. int nRight,
  144579. const void *zRight
  144580. ){
  144581. UCollationResult res;
  144582. UCollator *p = (UCollator *)pCtx;
  144583. res = ucol_strcoll(p, (UChar *)zLeft, nLeft/2, (UChar *)zRight, nRight/2);
  144584. switch( res ){
  144585. case UCOL_LESS: return -1;
  144586. case UCOL_GREATER: return +1;
  144587. case UCOL_EQUAL: return 0;
  144588. }
  144589. assert(!"Unexpected return value from ucol_strcoll()");
  144590. return 0;
  144591. }
  144592. /*
  144593. ** Implementation of the scalar function icu_load_collation().
  144594. **
  144595. ** This scalar function is used to add ICU collation based collation
  144596. ** types to an SQLite database connection. It is intended to be called
  144597. ** as follows:
  144598. **
  144599. ** SELECT icu_load_collation(<locale>, <collation-name>);
  144600. **
  144601. ** Where <locale> is a string containing an ICU locale identifier (i.e.
  144602. ** "en_AU", "tr_TR" etc.) and <collation-name> is the name of the
  144603. ** collation sequence to create.
  144604. */
  144605. static void icuLoadCollation(
  144606. sqlite3_context *p,
  144607. int nArg,
  144608. sqlite3_value **apArg
  144609. ){
  144610. sqlite3 *db = (sqlite3 *)sqlite3_user_data(p);
  144611. UErrorCode status = U_ZERO_ERROR;
  144612. const char *zLocale; /* Locale identifier - (eg. "jp_JP") */
  144613. const char *zName; /* SQL Collation sequence name (eg. "japanese") */
  144614. UCollator *pUCollator; /* ICU library collation object */
  144615. int rc; /* Return code from sqlite3_create_collation_x() */
  144616. assert(nArg==2);
  144617. zLocale = (const char *)sqlite3_value_text(apArg[0]);
  144618. zName = (const char *)sqlite3_value_text(apArg[1]);
  144619. if( !zLocale || !zName ){
  144620. return;
  144621. }
  144622. pUCollator = ucol_open(zLocale, &status);
  144623. if( !U_SUCCESS(status) ){
  144624. icuFunctionError(p, "ucol_open", status);
  144625. return;
  144626. }
  144627. assert(p);
  144628. rc = sqlite3_create_collation_v2(db, zName, SQLITE_UTF16, (void *)pUCollator,
  144629. icuCollationColl, icuCollationDel
  144630. );
  144631. if( rc!=SQLITE_OK ){
  144632. ucol_close(pUCollator);
  144633. sqlite3_result_error(p, "Error registering collation function", -1);
  144634. }
  144635. }
  144636. /*
  144637. ** Register the ICU extension functions with database db.
  144638. */
  144639. SQLITE_PRIVATE int sqlite3IcuInit(sqlite3 *db){
  144640. struct IcuScalar {
  144641. const char *zName; /* Function name */
  144642. int nArg; /* Number of arguments */
  144643. int enc; /* Optimal text encoding */
  144644. void *pContext; /* sqlite3_user_data() context */
  144645. void (*xFunc)(sqlite3_context*,int,sqlite3_value**);
  144646. } scalars[] = {
  144647. {"regexp", 2, SQLITE_ANY, 0, icuRegexpFunc},
  144648. {"lower", 1, SQLITE_UTF16, 0, icuCaseFunc16},
  144649. {"lower", 2, SQLITE_UTF16, 0, icuCaseFunc16},
  144650. {"upper", 1, SQLITE_UTF16, (void*)1, icuCaseFunc16},
  144651. {"upper", 2, SQLITE_UTF16, (void*)1, icuCaseFunc16},
  144652. {"lower", 1, SQLITE_UTF8, 0, icuCaseFunc16},
  144653. {"lower", 2, SQLITE_UTF8, 0, icuCaseFunc16},
  144654. {"upper", 1, SQLITE_UTF8, (void*)1, icuCaseFunc16},
  144655. {"upper", 2, SQLITE_UTF8, (void*)1, icuCaseFunc16},
  144656. {"like", 2, SQLITE_UTF8, 0, icuLikeFunc},
  144657. {"like", 3, SQLITE_UTF8, 0, icuLikeFunc},
  144658. {"icu_load_collation", 2, SQLITE_UTF8, (void*)db, icuLoadCollation},
  144659. };
  144660. int rc = SQLITE_OK;
  144661. int i;
  144662. for(i=0; rc==SQLITE_OK && i<(int)(sizeof(scalars)/sizeof(scalars[0])); i++){
  144663. struct IcuScalar *p = &scalars[i];
  144664. rc = sqlite3_create_function(
  144665. db, p->zName, p->nArg, p->enc, p->pContext, p->xFunc, 0, 0
  144666. );
  144667. }
  144668. return rc;
  144669. }
  144670. #if !SQLITE_CORE
  144671. #ifdef _WIN32
  144672. __declspec(dllexport)
  144673. #endif
  144674. SQLITE_API int SQLITE_STDCALL sqlite3_icu_init(
  144675. sqlite3 *db,
  144676. char **pzErrMsg,
  144677. const sqlite3_api_routines *pApi
  144678. ){
  144679. SQLITE_EXTENSION_INIT2(pApi)
  144680. return sqlite3IcuInit(db);
  144681. }
  144682. #endif
  144683. #endif
  144684. /************** End of icu.c *************************************************/
  144685. /************** Begin file fts3_icu.c ****************************************/
  144686. /*
  144687. ** 2007 June 22
  144688. **
  144689. ** The author disclaims copyright to this source code. In place of
  144690. ** a legal notice, here is a blessing:
  144691. **
  144692. ** May you do good and not evil.
  144693. ** May you find forgiveness for yourself and forgive others.
  144694. ** May you share freely, never taking more than you give.
  144695. **
  144696. *************************************************************************
  144697. ** This file implements a tokenizer for fts3 based on the ICU library.
  144698. */
  144699. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  144700. #ifdef SQLITE_ENABLE_ICU
  144701. /* #include <assert.h> */
  144702. /* #include <string.h> */
  144703. #include <unicode/ubrk.h>
  144704. /* #include <unicode/ucol.h> */
  144705. /* #include <unicode/ustring.h> */
  144706. #include <unicode/utf16.h>
  144707. typedef struct IcuTokenizer IcuTokenizer;
  144708. typedef struct IcuCursor IcuCursor;
  144709. struct IcuTokenizer {
  144710. sqlite3_tokenizer base;
  144711. char *zLocale;
  144712. };
  144713. struct IcuCursor {
  144714. sqlite3_tokenizer_cursor base;
  144715. UBreakIterator *pIter; /* ICU break-iterator object */
  144716. int nChar; /* Number of UChar elements in pInput */
  144717. UChar *aChar; /* Copy of input using utf-16 encoding */
  144718. int *aOffset; /* Offsets of each character in utf-8 input */
  144719. int nBuffer;
  144720. char *zBuffer;
  144721. int iToken;
  144722. };
  144723. /*
  144724. ** Create a new tokenizer instance.
  144725. */
  144726. static int icuCreate(
  144727. int argc, /* Number of entries in argv[] */
  144728. const char * const *argv, /* Tokenizer creation arguments */
  144729. sqlite3_tokenizer **ppTokenizer /* OUT: Created tokenizer */
  144730. ){
  144731. IcuTokenizer *p;
  144732. int n = 0;
  144733. if( argc>0 ){
  144734. n = strlen(argv[0])+1;
  144735. }
  144736. p = (IcuTokenizer *)sqlite3_malloc(sizeof(IcuTokenizer)+n);
  144737. if( !p ){
  144738. return SQLITE_NOMEM;
  144739. }
  144740. memset(p, 0, sizeof(IcuTokenizer));
  144741. if( n ){
  144742. p->zLocale = (char *)&p[1];
  144743. memcpy(p->zLocale, argv[0], n);
  144744. }
  144745. *ppTokenizer = (sqlite3_tokenizer *)p;
  144746. return SQLITE_OK;
  144747. }
  144748. /*
  144749. ** Destroy a tokenizer
  144750. */
  144751. static int icuDestroy(sqlite3_tokenizer *pTokenizer){
  144752. IcuTokenizer *p = (IcuTokenizer *)pTokenizer;
  144753. sqlite3_free(p);
  144754. return SQLITE_OK;
  144755. }
  144756. /*
  144757. ** Prepare to begin tokenizing a particular string. The input
  144758. ** string to be tokenized is pInput[0..nBytes-1]. A cursor
  144759. ** used to incrementally tokenize this string is returned in
  144760. ** *ppCursor.
  144761. */
  144762. static int icuOpen(
  144763. sqlite3_tokenizer *pTokenizer, /* The tokenizer */
  144764. const char *zInput, /* Input string */
  144765. int nInput, /* Length of zInput in bytes */
  144766. sqlite3_tokenizer_cursor **ppCursor /* OUT: Tokenization cursor */
  144767. ){
  144768. IcuTokenizer *p = (IcuTokenizer *)pTokenizer;
  144769. IcuCursor *pCsr;
  144770. const int32_t opt = U_FOLD_CASE_DEFAULT;
  144771. UErrorCode status = U_ZERO_ERROR;
  144772. int nChar;
  144773. UChar32 c;
  144774. int iInput = 0;
  144775. int iOut = 0;
  144776. *ppCursor = 0;
  144777. if( zInput==0 ){
  144778. nInput = 0;
  144779. zInput = "";
  144780. }else if( nInput<0 ){
  144781. nInput = strlen(zInput);
  144782. }
  144783. nChar = nInput+1;
  144784. pCsr = (IcuCursor *)sqlite3_malloc(
  144785. sizeof(IcuCursor) + /* IcuCursor */
  144786. ((nChar+3)&~3) * sizeof(UChar) + /* IcuCursor.aChar[] */
  144787. (nChar+1) * sizeof(int) /* IcuCursor.aOffset[] */
  144788. );
  144789. if( !pCsr ){
  144790. return SQLITE_NOMEM;
  144791. }
  144792. memset(pCsr, 0, sizeof(IcuCursor));
  144793. pCsr->aChar = (UChar *)&pCsr[1];
  144794. pCsr->aOffset = (int *)&pCsr->aChar[(nChar+3)&~3];
  144795. pCsr->aOffset[iOut] = iInput;
  144796. U8_NEXT(zInput, iInput, nInput, c);
  144797. while( c>0 ){
  144798. int isError = 0;
  144799. c = u_foldCase(c, opt);
  144800. U16_APPEND(pCsr->aChar, iOut, nChar, c, isError);
  144801. if( isError ){
  144802. sqlite3_free(pCsr);
  144803. return SQLITE_ERROR;
  144804. }
  144805. pCsr->aOffset[iOut] = iInput;
  144806. if( iInput<nInput ){
  144807. U8_NEXT(zInput, iInput, nInput, c);
  144808. }else{
  144809. c = 0;
  144810. }
  144811. }
  144812. pCsr->pIter = ubrk_open(UBRK_WORD, p->zLocale, pCsr->aChar, iOut, &status);
  144813. if( !U_SUCCESS(status) ){
  144814. sqlite3_free(pCsr);
  144815. return SQLITE_ERROR;
  144816. }
  144817. pCsr->nChar = iOut;
  144818. ubrk_first(pCsr->pIter);
  144819. *ppCursor = (sqlite3_tokenizer_cursor *)pCsr;
  144820. return SQLITE_OK;
  144821. }
  144822. /*
  144823. ** Close a tokenization cursor previously opened by a call to icuOpen().
  144824. */
  144825. static int icuClose(sqlite3_tokenizer_cursor *pCursor){
  144826. IcuCursor *pCsr = (IcuCursor *)pCursor;
  144827. ubrk_close(pCsr->pIter);
  144828. sqlite3_free(pCsr->zBuffer);
  144829. sqlite3_free(pCsr);
  144830. return SQLITE_OK;
  144831. }
  144832. /*
  144833. ** Extract the next token from a tokenization cursor.
  144834. */
  144835. static int icuNext(
  144836. sqlite3_tokenizer_cursor *pCursor, /* Cursor returned by simpleOpen */
  144837. const char **ppToken, /* OUT: *ppToken is the token text */
  144838. int *pnBytes, /* OUT: Number of bytes in token */
  144839. int *piStartOffset, /* OUT: Starting offset of token */
  144840. int *piEndOffset, /* OUT: Ending offset of token */
  144841. int *piPosition /* OUT: Position integer of token */
  144842. ){
  144843. IcuCursor *pCsr = (IcuCursor *)pCursor;
  144844. int iStart = 0;
  144845. int iEnd = 0;
  144846. int nByte = 0;
  144847. while( iStart==iEnd ){
  144848. UChar32 c;
  144849. iStart = ubrk_current(pCsr->pIter);
  144850. iEnd = ubrk_next(pCsr->pIter);
  144851. if( iEnd==UBRK_DONE ){
  144852. return SQLITE_DONE;
  144853. }
  144854. while( iStart<iEnd ){
  144855. int iWhite = iStart;
  144856. U16_NEXT(pCsr->aChar, iWhite, pCsr->nChar, c);
  144857. if( u_isspace(c) ){
  144858. iStart = iWhite;
  144859. }else{
  144860. break;
  144861. }
  144862. }
  144863. assert(iStart<=iEnd);
  144864. }
  144865. do {
  144866. UErrorCode status = U_ZERO_ERROR;
  144867. if( nByte ){
  144868. char *zNew = sqlite3_realloc(pCsr->zBuffer, nByte);
  144869. if( !zNew ){
  144870. return SQLITE_NOMEM;
  144871. }
  144872. pCsr->zBuffer = zNew;
  144873. pCsr->nBuffer = nByte;
  144874. }
  144875. u_strToUTF8(
  144876. pCsr->zBuffer, pCsr->nBuffer, &nByte, /* Output vars */
  144877. &pCsr->aChar[iStart], iEnd-iStart, /* Input vars */
  144878. &status /* Output success/failure */
  144879. );
  144880. } while( nByte>pCsr->nBuffer );
  144881. *ppToken = pCsr->zBuffer;
  144882. *pnBytes = nByte;
  144883. *piStartOffset = pCsr->aOffset[iStart];
  144884. *piEndOffset = pCsr->aOffset[iEnd];
  144885. *piPosition = pCsr->iToken++;
  144886. return SQLITE_OK;
  144887. }
  144888. /*
  144889. ** The set of routines that implement the simple tokenizer
  144890. */
  144891. static const sqlite3_tokenizer_module icuTokenizerModule = {
  144892. 0, /* iVersion */
  144893. icuCreate, /* xCreate */
  144894. icuDestroy, /* xCreate */
  144895. icuOpen, /* xOpen */
  144896. icuClose, /* xClose */
  144897. icuNext, /* xNext */
  144898. };
  144899. /*
  144900. ** Set *ppModule to point at the implementation of the ICU tokenizer.
  144901. */
  144902. SQLITE_PRIVATE void sqlite3Fts3IcuTokenizerModule(
  144903. sqlite3_tokenizer_module const**ppModule
  144904. ){
  144905. *ppModule = &icuTokenizerModule;
  144906. }
  144907. #endif /* defined(SQLITE_ENABLE_ICU) */
  144908. #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
  144909. /************** End of fts3_icu.c ********************************************/
  144910. /************** Begin file dbstat.c ******************************************/
  144911. /*
  144912. ** 2010 July 12
  144913. **
  144914. ** The author disclaims copyright to this source code. In place of
  144915. ** a legal notice, here is a blessing:
  144916. **
  144917. ** May you do good and not evil.
  144918. ** May you find forgiveness for yourself and forgive others.
  144919. ** May you share freely, never taking more than you give.
  144920. **
  144921. ******************************************************************************
  144922. **
  144923. ** This file contains an implementation of the "dbstat" virtual table.
  144924. **
  144925. ** The dbstat virtual table is used to extract low-level formatting
  144926. ** information from an SQLite database in order to implement the
  144927. ** "sqlite3_analyzer" utility. See the ../tool/spaceanal.tcl script
  144928. ** for an example implementation.
  144929. */
  144930. #if (defined(SQLITE_ENABLE_DBSTAT_VTAB) || defined(SQLITE_TEST)) \
  144931. && !defined(SQLITE_OMIT_VIRTUALTABLE)
  144932. /*
  144933. ** Page paths:
  144934. **
  144935. ** The value of the 'path' column describes the path taken from the
  144936. ** root-node of the b-tree structure to each page. The value of the
  144937. ** root-node path is '/'.
  144938. **
  144939. ** The value of the path for the left-most child page of the root of
  144940. ** a b-tree is '/000/'. (Btrees store content ordered from left to right
  144941. ** so the pages to the left have smaller keys than the pages to the right.)
  144942. ** The next to left-most child of the root page is
  144943. ** '/001', and so on, each sibling page identified by a 3-digit hex
  144944. ** value. The children of the 451st left-most sibling have paths such
  144945. ** as '/1c2/000/, '/1c2/001/' etc.
  144946. **
  144947. ** Overflow pages are specified by appending a '+' character and a
  144948. ** six-digit hexadecimal value to the path to the cell they are linked
  144949. ** from. For example, the three overflow pages in a chain linked from
  144950. ** the left-most cell of the 450th child of the root page are identified
  144951. ** by the paths:
  144952. **
  144953. ** '/1c2/000+000000' // First page in overflow chain
  144954. ** '/1c2/000+000001' // Second page in overflow chain
  144955. ** '/1c2/000+000002' // Third page in overflow chain
  144956. **
  144957. ** If the paths are sorted using the BINARY collation sequence, then
  144958. ** the overflow pages associated with a cell will appear earlier in the
  144959. ** sort-order than its child page:
  144960. **
  144961. ** '/1c2/000/' // Left-most child of 451st child of root
  144962. */
  144963. #define VTAB_SCHEMA \
  144964. "CREATE TABLE xx( " \
  144965. " name STRING, /* Name of table or index */" \
  144966. " path INTEGER, /* Path to page from root */" \
  144967. " pageno INTEGER, /* Page number */" \
  144968. " pagetype STRING, /* 'internal', 'leaf' or 'overflow' */" \
  144969. " ncell INTEGER, /* Cells on page (0 for overflow) */" \
  144970. " payload INTEGER, /* Bytes of payload on this page */" \
  144971. " unused INTEGER, /* Bytes of unused space on this page */" \
  144972. " mx_payload INTEGER, /* Largest payload size of all cells */" \
  144973. " pgoffset INTEGER, /* Offset of page in file */" \
  144974. " pgsize INTEGER /* Size of the page */" \
  144975. ");"
  144976. typedef struct StatTable StatTable;
  144977. typedef struct StatCursor StatCursor;
  144978. typedef struct StatPage StatPage;
  144979. typedef struct StatCell StatCell;
  144980. struct StatCell {
  144981. int nLocal; /* Bytes of local payload */
  144982. u32 iChildPg; /* Child node (or 0 if this is a leaf) */
  144983. int nOvfl; /* Entries in aOvfl[] */
  144984. u32 *aOvfl; /* Array of overflow page numbers */
  144985. int nLastOvfl; /* Bytes of payload on final overflow page */
  144986. int iOvfl; /* Iterates through aOvfl[] */
  144987. };
  144988. struct StatPage {
  144989. u32 iPgno;
  144990. DbPage *pPg;
  144991. int iCell;
  144992. char *zPath; /* Path to this page */
  144993. /* Variables populated by statDecodePage(): */
  144994. u8 flags; /* Copy of flags byte */
  144995. int nCell; /* Number of cells on page */
  144996. int nUnused; /* Number of unused bytes on page */
  144997. StatCell *aCell; /* Array of parsed cells */
  144998. u32 iRightChildPg; /* Right-child page number (or 0) */
  144999. int nMxPayload; /* Largest payload of any cell on this page */
  145000. };
  145001. struct StatCursor {
  145002. sqlite3_vtab_cursor base;
  145003. sqlite3_stmt *pStmt; /* Iterates through set of root pages */
  145004. int isEof; /* After pStmt has returned SQLITE_DONE */
  145005. StatPage aPage[32];
  145006. int iPage; /* Current entry in aPage[] */
  145007. /* Values to return. */
  145008. char *zName; /* Value of 'name' column */
  145009. char *zPath; /* Value of 'path' column */
  145010. u32 iPageno; /* Value of 'pageno' column */
  145011. char *zPagetype; /* Value of 'pagetype' column */
  145012. int nCell; /* Value of 'ncell' column */
  145013. int nPayload; /* Value of 'payload' column */
  145014. int nUnused; /* Value of 'unused' column */
  145015. int nMxPayload; /* Value of 'mx_payload' column */
  145016. i64 iOffset; /* Value of 'pgOffset' column */
  145017. int szPage; /* Value of 'pgSize' column */
  145018. };
  145019. struct StatTable {
  145020. sqlite3_vtab base;
  145021. sqlite3 *db;
  145022. int iDb; /* Index of database to analyze */
  145023. };
  145024. #ifndef get2byte
  145025. # define get2byte(x) ((x)[0]<<8 | (x)[1])
  145026. #endif
  145027. /*
  145028. ** Connect to or create a statvfs virtual table.
  145029. */
  145030. static int statConnect(
  145031. sqlite3 *db,
  145032. void *pAux,
  145033. int argc, const char *const*argv,
  145034. sqlite3_vtab **ppVtab,
  145035. char **pzErr
  145036. ){
  145037. StatTable *pTab = 0;
  145038. int rc = SQLITE_OK;
  145039. int iDb;
  145040. if( argc>=4 ){
  145041. iDb = sqlite3FindDbName(db, argv[3]);
  145042. if( iDb<0 ){
  145043. *pzErr = sqlite3_mprintf("no such database: %s", argv[3]);
  145044. return SQLITE_ERROR;
  145045. }
  145046. }else{
  145047. iDb = 0;
  145048. }
  145049. rc = sqlite3_declare_vtab(db, VTAB_SCHEMA);
  145050. if( rc==SQLITE_OK ){
  145051. pTab = (StatTable *)sqlite3_malloc64(sizeof(StatTable));
  145052. if( pTab==0 ) rc = SQLITE_NOMEM;
  145053. }
  145054. assert( rc==SQLITE_OK || pTab==0 );
  145055. if( rc==SQLITE_OK ){
  145056. memset(pTab, 0, sizeof(StatTable));
  145057. pTab->db = db;
  145058. pTab->iDb = iDb;
  145059. }
  145060. *ppVtab = (sqlite3_vtab*)pTab;
  145061. return rc;
  145062. }
  145063. /*
  145064. ** Disconnect from or destroy a statvfs virtual table.
  145065. */
  145066. static int statDisconnect(sqlite3_vtab *pVtab){
  145067. sqlite3_free(pVtab);
  145068. return SQLITE_OK;
  145069. }
  145070. /*
  145071. ** There is no "best-index". This virtual table always does a linear
  145072. ** scan of the binary VFS log file.
  145073. */
  145074. static int statBestIndex(sqlite3_vtab *tab, sqlite3_index_info *pIdxInfo){
  145075. /* Records are always returned in ascending order of (name, path).
  145076. ** If this will satisfy the client, set the orderByConsumed flag so that
  145077. ** SQLite does not do an external sort.
  145078. */
  145079. if( ( pIdxInfo->nOrderBy==1
  145080. && pIdxInfo->aOrderBy[0].iColumn==0
  145081. && pIdxInfo->aOrderBy[0].desc==0
  145082. ) ||
  145083. ( pIdxInfo->nOrderBy==2
  145084. && pIdxInfo->aOrderBy[0].iColumn==0
  145085. && pIdxInfo->aOrderBy[0].desc==0
  145086. && pIdxInfo->aOrderBy[1].iColumn==1
  145087. && pIdxInfo->aOrderBy[1].desc==0
  145088. )
  145089. ){
  145090. pIdxInfo->orderByConsumed = 1;
  145091. }
  145092. pIdxInfo->estimatedCost = 10.0;
  145093. return SQLITE_OK;
  145094. }
  145095. /*
  145096. ** Open a new statvfs cursor.
  145097. */
  145098. static int statOpen(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor){
  145099. StatTable *pTab = (StatTable *)pVTab;
  145100. StatCursor *pCsr;
  145101. int rc;
  145102. pCsr = (StatCursor *)sqlite3_malloc64(sizeof(StatCursor));
  145103. if( pCsr==0 ){
  145104. rc = SQLITE_NOMEM;
  145105. }else{
  145106. char *zSql;
  145107. memset(pCsr, 0, sizeof(StatCursor));
  145108. pCsr->base.pVtab = pVTab;
  145109. zSql = sqlite3_mprintf(
  145110. "SELECT 'sqlite_master' AS name, 1 AS rootpage, 'table' AS type"
  145111. " UNION ALL "
  145112. "SELECT name, rootpage, type"
  145113. " FROM \"%w\".sqlite_master WHERE rootpage!=0"
  145114. " ORDER BY name", pTab->db->aDb[pTab->iDb].zName);
  145115. if( zSql==0 ){
  145116. rc = SQLITE_NOMEM;
  145117. }else{
  145118. rc = sqlite3_prepare_v2(pTab->db, zSql, -1, &pCsr->pStmt, 0);
  145119. sqlite3_free(zSql);
  145120. }
  145121. if( rc!=SQLITE_OK ){
  145122. sqlite3_free(pCsr);
  145123. pCsr = 0;
  145124. }
  145125. }
  145126. *ppCursor = (sqlite3_vtab_cursor *)pCsr;
  145127. return rc;
  145128. }
  145129. static void statClearPage(StatPage *p){
  145130. int i;
  145131. if( p->aCell ){
  145132. for(i=0; i<p->nCell; i++){
  145133. sqlite3_free(p->aCell[i].aOvfl);
  145134. }
  145135. sqlite3_free(p->aCell);
  145136. }
  145137. sqlite3PagerUnref(p->pPg);
  145138. sqlite3_free(p->zPath);
  145139. memset(p, 0, sizeof(StatPage));
  145140. }
  145141. static void statResetCsr(StatCursor *pCsr){
  145142. int i;
  145143. sqlite3_reset(pCsr->pStmt);
  145144. for(i=0; i<ArraySize(pCsr->aPage); i++){
  145145. statClearPage(&pCsr->aPage[i]);
  145146. }
  145147. pCsr->iPage = 0;
  145148. sqlite3_free(pCsr->zPath);
  145149. pCsr->zPath = 0;
  145150. }
  145151. /*
  145152. ** Close a statvfs cursor.
  145153. */
  145154. static int statClose(sqlite3_vtab_cursor *pCursor){
  145155. StatCursor *pCsr = (StatCursor *)pCursor;
  145156. statResetCsr(pCsr);
  145157. sqlite3_finalize(pCsr->pStmt);
  145158. sqlite3_free(pCsr);
  145159. return SQLITE_OK;
  145160. }
  145161. static void getLocalPayload(
  145162. int nUsable, /* Usable bytes per page */
  145163. u8 flags, /* Page flags */
  145164. int nTotal, /* Total record (payload) size */
  145165. int *pnLocal /* OUT: Bytes stored locally */
  145166. ){
  145167. int nLocal;
  145168. int nMinLocal;
  145169. int nMaxLocal;
  145170. if( flags==0x0D ){ /* Table leaf node */
  145171. nMinLocal = (nUsable - 12) * 32 / 255 - 23;
  145172. nMaxLocal = nUsable - 35;
  145173. }else{ /* Index interior and leaf nodes */
  145174. nMinLocal = (nUsable - 12) * 32 / 255 - 23;
  145175. nMaxLocal = (nUsable - 12) * 64 / 255 - 23;
  145176. }
  145177. nLocal = nMinLocal + (nTotal - nMinLocal) % (nUsable - 4);
  145178. if( nLocal>nMaxLocal ) nLocal = nMinLocal;
  145179. *pnLocal = nLocal;
  145180. }
  145181. static int statDecodePage(Btree *pBt, StatPage *p){
  145182. int nUnused;
  145183. int iOff;
  145184. int nHdr;
  145185. int isLeaf;
  145186. int szPage;
  145187. u8 *aData = sqlite3PagerGetData(p->pPg);
  145188. u8 *aHdr = &aData[p->iPgno==1 ? 100 : 0];
  145189. p->flags = aHdr[0];
  145190. p->nCell = get2byte(&aHdr[3]);
  145191. p->nMxPayload = 0;
  145192. isLeaf = (p->flags==0x0A || p->flags==0x0D);
  145193. nHdr = 12 - isLeaf*4 + (p->iPgno==1)*100;
  145194. nUnused = get2byte(&aHdr[5]) - nHdr - 2*p->nCell;
  145195. nUnused += (int)aHdr[7];
  145196. iOff = get2byte(&aHdr[1]);
  145197. while( iOff ){
  145198. nUnused += get2byte(&aData[iOff+2]);
  145199. iOff = get2byte(&aData[iOff]);
  145200. }
  145201. p->nUnused = nUnused;
  145202. p->iRightChildPg = isLeaf ? 0 : sqlite3Get4byte(&aHdr[8]);
  145203. szPage = sqlite3BtreeGetPageSize(pBt);
  145204. if( p->nCell ){
  145205. int i; /* Used to iterate through cells */
  145206. int nUsable; /* Usable bytes per page */
  145207. sqlite3BtreeEnter(pBt);
  145208. nUsable = szPage - sqlite3BtreeGetReserveNoMutex(pBt);
  145209. sqlite3BtreeLeave(pBt);
  145210. p->aCell = sqlite3_malloc64((p->nCell+1) * sizeof(StatCell));
  145211. if( p->aCell==0 ) return SQLITE_NOMEM;
  145212. memset(p->aCell, 0, (p->nCell+1) * sizeof(StatCell));
  145213. for(i=0; i<p->nCell; i++){
  145214. StatCell *pCell = &p->aCell[i];
  145215. iOff = get2byte(&aData[nHdr+i*2]);
  145216. if( !isLeaf ){
  145217. pCell->iChildPg = sqlite3Get4byte(&aData[iOff]);
  145218. iOff += 4;
  145219. }
  145220. if( p->flags==0x05 ){
  145221. /* A table interior node. nPayload==0. */
  145222. }else{
  145223. u32 nPayload; /* Bytes of payload total (local+overflow) */
  145224. int nLocal; /* Bytes of payload stored locally */
  145225. iOff += getVarint32(&aData[iOff], nPayload);
  145226. if( p->flags==0x0D ){
  145227. u64 dummy;
  145228. iOff += sqlite3GetVarint(&aData[iOff], &dummy);
  145229. }
  145230. if( nPayload>(u32)p->nMxPayload ) p->nMxPayload = nPayload;
  145231. getLocalPayload(nUsable, p->flags, nPayload, &nLocal);
  145232. pCell->nLocal = nLocal;
  145233. assert( nLocal>=0 );
  145234. assert( nPayload>=(u32)nLocal );
  145235. assert( nLocal<=(nUsable-35) );
  145236. if( nPayload>(u32)nLocal ){
  145237. int j;
  145238. int nOvfl = ((nPayload - nLocal) + nUsable-4 - 1) / (nUsable - 4);
  145239. pCell->nLastOvfl = (nPayload-nLocal) - (nOvfl-1) * (nUsable-4);
  145240. pCell->nOvfl = nOvfl;
  145241. pCell->aOvfl = sqlite3_malloc64(sizeof(u32)*nOvfl);
  145242. if( pCell->aOvfl==0 ) return SQLITE_NOMEM;
  145243. pCell->aOvfl[0] = sqlite3Get4byte(&aData[iOff+nLocal]);
  145244. for(j=1; j<nOvfl; j++){
  145245. int rc;
  145246. u32 iPrev = pCell->aOvfl[j-1];
  145247. DbPage *pPg = 0;
  145248. rc = sqlite3PagerGet(sqlite3BtreePager(pBt), iPrev, &pPg);
  145249. if( rc!=SQLITE_OK ){
  145250. assert( pPg==0 );
  145251. return rc;
  145252. }
  145253. pCell->aOvfl[j] = sqlite3Get4byte(sqlite3PagerGetData(pPg));
  145254. sqlite3PagerUnref(pPg);
  145255. }
  145256. }
  145257. }
  145258. }
  145259. }
  145260. return SQLITE_OK;
  145261. }
  145262. /*
  145263. ** Populate the pCsr->iOffset and pCsr->szPage member variables. Based on
  145264. ** the current value of pCsr->iPageno.
  145265. */
  145266. static void statSizeAndOffset(StatCursor *pCsr){
  145267. StatTable *pTab = (StatTable *)((sqlite3_vtab_cursor *)pCsr)->pVtab;
  145268. Btree *pBt = pTab->db->aDb[pTab->iDb].pBt;
  145269. Pager *pPager = sqlite3BtreePager(pBt);
  145270. sqlite3_file *fd;
  145271. sqlite3_int64 x[2];
  145272. /* The default page size and offset */
  145273. pCsr->szPage = sqlite3BtreeGetPageSize(pBt);
  145274. pCsr->iOffset = (i64)pCsr->szPage * (pCsr->iPageno - 1);
  145275. /* If connected to a ZIPVFS backend, override the page size and
  145276. ** offset with actual values obtained from ZIPVFS.
  145277. */
  145278. fd = sqlite3PagerFile(pPager);
  145279. x[0] = pCsr->iPageno;
  145280. if( fd->pMethods!=0 && sqlite3OsFileControl(fd, 230440, &x)==SQLITE_OK ){
  145281. pCsr->iOffset = x[0];
  145282. pCsr->szPage = (int)x[1];
  145283. }
  145284. }
  145285. /*
  145286. ** Move a statvfs cursor to the next entry in the file.
  145287. */
  145288. static int statNext(sqlite3_vtab_cursor *pCursor){
  145289. int rc;
  145290. int nPayload;
  145291. char *z;
  145292. StatCursor *pCsr = (StatCursor *)pCursor;
  145293. StatTable *pTab = (StatTable *)pCursor->pVtab;
  145294. Btree *pBt = pTab->db->aDb[pTab->iDb].pBt;
  145295. Pager *pPager = sqlite3BtreePager(pBt);
  145296. sqlite3_free(pCsr->zPath);
  145297. pCsr->zPath = 0;
  145298. statNextRestart:
  145299. if( pCsr->aPage[0].pPg==0 ){
  145300. rc = sqlite3_step(pCsr->pStmt);
  145301. if( rc==SQLITE_ROW ){
  145302. int nPage;
  145303. u32 iRoot = (u32)sqlite3_column_int64(pCsr->pStmt, 1);
  145304. sqlite3PagerPagecount(pPager, &nPage);
  145305. if( nPage==0 ){
  145306. pCsr->isEof = 1;
  145307. return sqlite3_reset(pCsr->pStmt);
  145308. }
  145309. rc = sqlite3PagerGet(pPager, iRoot, &pCsr->aPage[0].pPg);
  145310. pCsr->aPage[0].iPgno = iRoot;
  145311. pCsr->aPage[0].iCell = 0;
  145312. pCsr->aPage[0].zPath = z = sqlite3_mprintf("/");
  145313. pCsr->iPage = 0;
  145314. if( z==0 ) rc = SQLITE_NOMEM;
  145315. }else{
  145316. pCsr->isEof = 1;
  145317. return sqlite3_reset(pCsr->pStmt);
  145318. }
  145319. }else{
  145320. /* Page p itself has already been visited. */
  145321. StatPage *p = &pCsr->aPage[pCsr->iPage];
  145322. while( p->iCell<p->nCell ){
  145323. StatCell *pCell = &p->aCell[p->iCell];
  145324. if( pCell->iOvfl<pCell->nOvfl ){
  145325. int nUsable;
  145326. sqlite3BtreeEnter(pBt);
  145327. nUsable = sqlite3BtreeGetPageSize(pBt) -
  145328. sqlite3BtreeGetReserveNoMutex(pBt);
  145329. sqlite3BtreeLeave(pBt);
  145330. pCsr->zName = (char *)sqlite3_column_text(pCsr->pStmt, 0);
  145331. pCsr->iPageno = pCell->aOvfl[pCell->iOvfl];
  145332. pCsr->zPagetype = "overflow";
  145333. pCsr->nCell = 0;
  145334. pCsr->nMxPayload = 0;
  145335. pCsr->zPath = z = sqlite3_mprintf(
  145336. "%s%.3x+%.6x", p->zPath, p->iCell, pCell->iOvfl
  145337. );
  145338. if( pCell->iOvfl<pCell->nOvfl-1 ){
  145339. pCsr->nUnused = 0;
  145340. pCsr->nPayload = nUsable - 4;
  145341. }else{
  145342. pCsr->nPayload = pCell->nLastOvfl;
  145343. pCsr->nUnused = nUsable - 4 - pCsr->nPayload;
  145344. }
  145345. pCell->iOvfl++;
  145346. statSizeAndOffset(pCsr);
  145347. return z==0 ? SQLITE_NOMEM : SQLITE_OK;
  145348. }
  145349. if( p->iRightChildPg ) break;
  145350. p->iCell++;
  145351. }
  145352. if( !p->iRightChildPg || p->iCell>p->nCell ){
  145353. statClearPage(p);
  145354. if( pCsr->iPage==0 ) return statNext(pCursor);
  145355. pCsr->iPage--;
  145356. goto statNextRestart; /* Tail recursion */
  145357. }
  145358. pCsr->iPage++;
  145359. assert( p==&pCsr->aPage[pCsr->iPage-1] );
  145360. if( p->iCell==p->nCell ){
  145361. p[1].iPgno = p->iRightChildPg;
  145362. }else{
  145363. p[1].iPgno = p->aCell[p->iCell].iChildPg;
  145364. }
  145365. rc = sqlite3PagerGet(pPager, p[1].iPgno, &p[1].pPg);
  145366. p[1].iCell = 0;
  145367. p[1].zPath = z = sqlite3_mprintf("%s%.3x/", p->zPath, p->iCell);
  145368. p->iCell++;
  145369. if( z==0 ) rc = SQLITE_NOMEM;
  145370. }
  145371. /* Populate the StatCursor fields with the values to be returned
  145372. ** by the xColumn() and xRowid() methods.
  145373. */
  145374. if( rc==SQLITE_OK ){
  145375. int i;
  145376. StatPage *p = &pCsr->aPage[pCsr->iPage];
  145377. pCsr->zName = (char *)sqlite3_column_text(pCsr->pStmt, 0);
  145378. pCsr->iPageno = p->iPgno;
  145379. rc = statDecodePage(pBt, p);
  145380. if( rc==SQLITE_OK ){
  145381. statSizeAndOffset(pCsr);
  145382. switch( p->flags ){
  145383. case 0x05: /* table internal */
  145384. case 0x02: /* index internal */
  145385. pCsr->zPagetype = "internal";
  145386. break;
  145387. case 0x0D: /* table leaf */
  145388. case 0x0A: /* index leaf */
  145389. pCsr->zPagetype = "leaf";
  145390. break;
  145391. default:
  145392. pCsr->zPagetype = "corrupted";
  145393. break;
  145394. }
  145395. pCsr->nCell = p->nCell;
  145396. pCsr->nUnused = p->nUnused;
  145397. pCsr->nMxPayload = p->nMxPayload;
  145398. pCsr->zPath = z = sqlite3_mprintf("%s", p->zPath);
  145399. if( z==0 ) rc = SQLITE_NOMEM;
  145400. nPayload = 0;
  145401. for(i=0; i<p->nCell; i++){
  145402. nPayload += p->aCell[i].nLocal;
  145403. }
  145404. pCsr->nPayload = nPayload;
  145405. }
  145406. }
  145407. return rc;
  145408. }
  145409. static int statEof(sqlite3_vtab_cursor *pCursor){
  145410. StatCursor *pCsr = (StatCursor *)pCursor;
  145411. return pCsr->isEof;
  145412. }
  145413. static int statFilter(
  145414. sqlite3_vtab_cursor *pCursor,
  145415. int idxNum, const char *idxStr,
  145416. int argc, sqlite3_value **argv
  145417. ){
  145418. StatCursor *pCsr = (StatCursor *)pCursor;
  145419. statResetCsr(pCsr);
  145420. return statNext(pCursor);
  145421. }
  145422. static int statColumn(
  145423. sqlite3_vtab_cursor *pCursor,
  145424. sqlite3_context *ctx,
  145425. int i
  145426. ){
  145427. StatCursor *pCsr = (StatCursor *)pCursor;
  145428. switch( i ){
  145429. case 0: /* name */
  145430. sqlite3_result_text(ctx, pCsr->zName, -1, SQLITE_TRANSIENT);
  145431. break;
  145432. case 1: /* path */
  145433. sqlite3_result_text(ctx, pCsr->zPath, -1, SQLITE_TRANSIENT);
  145434. break;
  145435. case 2: /* pageno */
  145436. sqlite3_result_int64(ctx, pCsr->iPageno);
  145437. break;
  145438. case 3: /* pagetype */
  145439. sqlite3_result_text(ctx, pCsr->zPagetype, -1, SQLITE_STATIC);
  145440. break;
  145441. case 4: /* ncell */
  145442. sqlite3_result_int(ctx, pCsr->nCell);
  145443. break;
  145444. case 5: /* payload */
  145445. sqlite3_result_int(ctx, pCsr->nPayload);
  145446. break;
  145447. case 6: /* unused */
  145448. sqlite3_result_int(ctx, pCsr->nUnused);
  145449. break;
  145450. case 7: /* mx_payload */
  145451. sqlite3_result_int(ctx, pCsr->nMxPayload);
  145452. break;
  145453. case 8: /* pgoffset */
  145454. sqlite3_result_int64(ctx, pCsr->iOffset);
  145455. break;
  145456. default: /* pgsize */
  145457. assert( i==9 );
  145458. sqlite3_result_int(ctx, pCsr->szPage);
  145459. break;
  145460. }
  145461. return SQLITE_OK;
  145462. }
  145463. static int statRowid(sqlite3_vtab_cursor *pCursor, sqlite_int64 *pRowid){
  145464. StatCursor *pCsr = (StatCursor *)pCursor;
  145465. *pRowid = pCsr->iPageno;
  145466. return SQLITE_OK;
  145467. }
  145468. /*
  145469. ** Invoke this routine to register the "dbstat" virtual table module
  145470. */
  145471. SQLITE_API int SQLITE_STDCALL sqlite3_dbstat_register(sqlite3 *db){
  145472. static sqlite3_module dbstat_module = {
  145473. 0, /* iVersion */
  145474. statConnect, /* xCreate */
  145475. statConnect, /* xConnect */
  145476. statBestIndex, /* xBestIndex */
  145477. statDisconnect, /* xDisconnect */
  145478. statDisconnect, /* xDestroy */
  145479. statOpen, /* xOpen - open a cursor */
  145480. statClose, /* xClose - close a cursor */
  145481. statFilter, /* xFilter - configure scan constraints */
  145482. statNext, /* xNext - advance a cursor */
  145483. statEof, /* xEof - check for end of scan */
  145484. statColumn, /* xColumn - read data */
  145485. statRowid, /* xRowid - read data */
  145486. 0, /* xUpdate */
  145487. 0, /* xBegin */
  145488. 0, /* xSync */
  145489. 0, /* xCommit */
  145490. 0, /* xRollback */
  145491. 0, /* xFindMethod */
  145492. 0, /* xRename */
  145493. };
  145494. return sqlite3_create_module(db, "dbstat", &dbstat_module, 0);
  145495. }
  145496. #endif /* SQLITE_ENABLE_DBSTAT_VTAB */
  145497. /************** End of dbstat.c **********************************************/